diff --git a/.gitattributes b/.gitattributes
index f801adc770c2c74f8b420d4ca0344ee0c50f13da..dcd6fcfc5cdf08d2cd77de1cbd2605b04c46c0cb 100644
--- a/.gitattributes
+++ b/.gitattributes
@@ -155,3 +155,36 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/_solve_toeplitz.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/cython_blas.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
.venv_haddock/lib/python3.12/site-packages/scipy/linalg/cython_lapack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_minpack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/signal/_sigtools.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/signal/_sosfilt.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/signal/_upfirdn_apply.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_csparsetools.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_sparsetools.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_flow.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_matching.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_min_spanning_tree.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_reordering.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_shortest_path.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_tools.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/csgraph/_traversal.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/linalg/_dsolve/_superlu.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/linalg/_eigen/arpack/_arpacklib.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/sparse/linalg/_propack.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/spatial/_ckdtree.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/spatial/_distance_pybind.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/spatial/_distance_wrap.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/spatial/_qhull.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/spatial/transform/_rigid_transform_cy.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
+.venv_haddock/lib/python3.12/site-packages/scipy/spatial/transform/_rotation_cy.cpython-312-darwin.so filter=lfs diff=lfs merge=lfs -text
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ctest.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ctest.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..0a28f66040f8134147ea37a984e6f0c655ee008d
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ctest.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_cytest.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_cytest.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..02f4fef3e564ab5e11f69b1a18056635d029f0c5
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_cytest.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_delegators.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_delegators.py
new file mode 100644
index 0000000000000000000000000000000000000000..bac1286a56c0937cc29ee926de4c77fbfb79c77f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_delegators.py
@@ -0,0 +1,303 @@
+"""Delegators for alternative backends in scipy.ndimage.
+
+The signature of `func_signature` must match the signature of ndimage.func.
+The job of a `func_signature` is to know which arguments of `ndimage.func`
+are arrays.
+
+* signatures are generated by
+
+--------------
+import inspect
+from scipy import ndimage
+
+names = [x for x in dir(ndimage) if not x.startswith('_')]
+objs = [getattr(ndimage, name) for name in names]
+funcs = [obj for obj in objs if inspect.isroutine(obj)]
+
+for func in funcs:
+ sig = inspect.signature(func)
+ print(f"def {func.__name__}_signature{sig}:\n\tpass\n\n")
+---------------
+
+* which arguments to delegate on: manually trawled the documentation for
+ array-like and array arguments
+
+"""
+import numpy as np
+from scipy._lib._array_api import array_namespace
+from scipy.ndimage._ni_support import _skip_if_dtype
+
+
+def affine_transform_signature(
+ input, matrix, offset=0.0, output_shape=None, output=None, *args, **kwds
+):
+ return array_namespace(input, matrix, _skip_if_dtype(output))
+
+
+def binary_closing_signature(
+ input, structure=None, iterations=1, output=None, *args, **kwds
+):
+ return array_namespace(input, structure, _skip_if_dtype(output))
+
+binary_opening_signature = binary_closing_signature
+
+
+def binary_dilation_signature(
+ input, structure=None, iterations=1, mask=None, output=None, *args, **kwds
+):
+ return array_namespace(input, structure, _skip_if_dtype(output), mask)
+
+binary_erosion_signature = binary_dilation_signature
+
+
+def binary_fill_holes_signature(
+ input, structure=None, output=None, origin=0, *args, **kwargs
+):
+ return array_namespace(input, structure, _skip_if_dtype(output))
+
+
+def label_signature(input, structure=None, output=None, origin=0):
+ return array_namespace(input, structure, _skip_if_dtype(output))
+
+
+def binary_hit_or_miss_signature(
+ input, structure1=None, structure2=None, output=None, *args, **kwds
+):
+ return array_namespace(input, structure1, structure2, _skip_if_dtype(output))
+
+
+def binary_propagation_signature(
+ input, structure=None, mask=None, output=None, *args, **kwds
+):
+ return array_namespace(input, structure, mask, _skip_if_dtype(output))
+
+
+def convolve_signature(input, weights, output=None, *args, **kwds):
+ return array_namespace(input, weights, _skip_if_dtype(output))
+
+correlate_signature = convolve_signature
+
+
+def convolve1d_signature(input, weights, axis=-1, output=None, *args, **kwds):
+ return array_namespace(input, weights, _skip_if_dtype(output))
+
+correlate1d_signature = convolve1d_signature
+
+
+def distance_transform_bf_signature(
+ input, metric='euclidean', sampling=None, return_distances=True,
+ return_indices=False, distances=None, indices=None
+):
+ return array_namespace(input, distances, indices)
+
+
+def distance_transform_cdt_signature(
+ input, metric='chessboard', return_distances=True, return_indices=False,
+ distances=None, indices=None
+):
+ return array_namespace(input, distances, indices)
+
+
+def distance_transform_edt_signature(
+ input, sampling=None, return_distances=True, return_indices=False,
+ distances=None, indices=None
+):
+ return array_namespace(input, distances, indices)
+
+
+def find_objects_signature(input, max_label=0):
+ return array_namespace(input)
+
+
+def fourier_ellipsoid_signature(input, size, n=-1, axis=-1, output=None):
+ return array_namespace(input, _skip_if_dtype(output))
+
+fourier_uniform_signature = fourier_ellipsoid_signature
+
+
+def fourier_gaussian_signature(input, sigma, n=-1, axis=-1, output=None):
+ return array_namespace(input, _skip_if_dtype(output))
+
+def fourier_shift_signature(input, shift, n=-1, axis=-1, output=None):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_filter_signature(input, sigma, order=0, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_filter1d_signature(
+ input, sigma, axis=-1, order=0, output=None, *args, **kwds
+):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def gaussian_gradient_magnitude_signature(input, sigma, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+gaussian_laplace_signature = gaussian_gradient_magnitude_signature
+
+
+def generate_binary_structure_signature(rank, connectivity):
+ # XXX: no input arrays; always return numpy
+ return np
+
+
+def generic_filter_signature(
+ input, function, size=None, footprint=None, output=None, *args, **kwds
+):
+ # XXX: function LowLevelCallable w/backends
+ return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def generic_filter1d_signature(
+ input, function, filter_size, axis=-1, output=None, *args, **kwds
+):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def generic_gradient_magnitude_signature(
+ input, derivative, output=None, *args, **kwds
+):
+ # XXX: function LowLevelCallable w/backends
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def generic_laplace_signature(input, derivative2, output=None, *args, **kwds):
+ # XXX: function LowLevelCallable w/backends
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def geometric_transform_signature(
+ input, mapping, output_shape=None, output=None, *args, **kwds
+):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def histogram_signature(input, min, max, bins, labels=None, index=None):
+ return array_namespace(input, labels)
+
+
+def iterate_structure_signature(structure, iterations, origin=None):
+ return array_namespace(structure)
+
+
+def labeled_comprehension_signature(input, labels, *args, **kwds):
+ return array_namespace(input, labels)
+
+
+def laplace_signature(input, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def map_coordinates_signature(input, coordinates, output=None, *args, **kwds):
+ return array_namespace(input, coordinates, _skip_if_dtype(output))
+
+
+def maximum_filter1d_signature(input, size, axis=-1, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+minimum_filter1d_signature = maximum_filter1d_signature
+uniform_filter1d_signature = maximum_filter1d_signature
+
+
+def maximum_signature(input, labels=None, index=None):
+ return array_namespace(input, labels, index)
+
+minimum_signature = maximum_signature
+median_signature = maximum_signature
+mean_signature = maximum_signature
+variance_signature = maximum_signature
+standard_deviation_signature = maximum_signature
+sum_labels_signature = maximum_signature
+sum_signature = maximum_signature # ndimage.sum is sum_labels
+
+maximum_position_signature = maximum_signature
+minimum_position_signature = maximum_signature
+
+extrema_signature = maximum_signature
+center_of_mass_signature = extrema_signature
+
+
+def median_filter_signature(
+ input, size=None, footprint=None, output=None, *args, **kwds
+):
+ return array_namespace(input, footprint, _skip_if_dtype(output))
+
+minimum_filter_signature = median_filter_signature
+maximum_filter_signature = median_filter_signature
+
+
+def morphological_gradient_signature(
+ input, size=None, footprint=None, structure=None, output=None, *args, **kwds
+):
+ return array_namespace(input, footprint, structure, _skip_if_dtype(output))
+
+morphological_laplace_signature = morphological_gradient_signature
+white_tophat_signature = morphological_gradient_signature
+black_tophat_signature = morphological_gradient_signature
+grey_closing_signature = morphological_gradient_signature
+grey_dilation_signature = morphological_gradient_signature
+grey_erosion_signature = morphological_gradient_signature
+grey_opening_signature = morphological_gradient_signature
+
+
+def percentile_filter_signature(
+ input, percentile, size=None, footprint=None, output=None, *args, **kwds
+):
+ return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def prewitt_signature(input, axis=-1, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+sobel_signature = prewitt_signature
+
+
+def rank_filter_signature(
+ input, rank, size=None, footprint=None, output=None, *args, **kwds
+):
+ return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def rotate_signature(
+ input, angle, axes=(1, 0), reshape=True, output=None , *args, **kwds
+):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def shift_signature(input, shift, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def spline_filter_signature(input, order=3, output=np.float64, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def spline_filter1d_signature(
+ input, order=3, axis=-1, output=np.float64, *args, **kwds
+):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def uniform_filter_signature(input, size=3, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
+
+def value_indices_signature(arr, *args, **kwds):
+ return array_namespace(arr)
+
+
+def vectorized_filter_signature(
+ input, function, size=None, footprint=None, output=None, *args, **kwds
+):
+ return array_namespace(input, footprint, _skip_if_dtype(output))
+
+
+def watershed_ift_signature(input, markers, structure=None, output=None):
+ return array_namespace(input, markers, structure, _skip_if_dtype(output))
+
+
+def zoom_signature(input, zoom, output=None, *args, **kwds):
+ return array_namespace(input, _skip_if_dtype(output))
+
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_filters.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..38abab3043ba98c8ca35dcb4e07a9143f4f5597a
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_filters.py
@@ -0,0 +1,2422 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+from collections.abc import Iterable
+import numbers
+import warnings
+import numpy as np
+import operator
+import math
+
+from scipy._lib._util import normalize_axis_index
+from scipy._lib._array_api import array_namespace, is_cupy, xp_size
+from . import _ni_support
+from . import _nd_image
+from . import _ni_docstrings
+from . import _rank_filter_1d
+
+__all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter',
+ 'prewitt', 'sobel', 'generic_laplace', 'laplace',
+ 'gaussian_laplace', 'generic_gradient_magnitude',
+ 'gaussian_gradient_magnitude', 'correlate', 'convolve',
+ 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
+ 'maximum_filter1d', 'minimum_filter', 'maximum_filter',
+ 'rank_filter', 'median_filter', 'percentile_filter',
+ 'generic_filter1d', 'generic_filter', 'vectorized_filter']
+
+
+def _vectorized_filter_iv(input, function, size, footprint, output, mode, cval, origin,
+ axes, batch_memory):
+ xp = array_namespace(input, footprint, output)
+
+ # vectorized_filter input validation and standardization
+ input = xp.asarray(input)
+
+ if not callable(function):
+ raise ValueError("`function` must be a callable.")
+
+ if size is None and footprint is None:
+ raise ValueError("Either `size` or `footprint` must be provided.")
+
+ if size is not None and footprint is not None:
+ raise ValueError("Either `size` or `footprint` may be provided, not both.")
+
+ if axes is None:
+ axes = tuple(range(-input.ndim, 0))
+ elif np.isscalar(axes):
+ axes = (axes,)
+ n_axes = len(axes)
+ n_batch = input.ndim - n_axes
+
+ if n_axes > input.ndim:
+ message = ("The length of `axes` may not exceed the dimensionality of `input`"
+ "(`input.ndim`).")
+ raise ValueError(message)
+
+ # Either footprint or size must be provided
+ footprinted_function = function
+ if size is not None:
+ # If provided, size must be an integer or tuple of integers.
+ size = (size,)*n_axes if np.isscalar(size) else tuple(size)
+ valid = [xp.isdtype(xp.asarray(i).dtype, 'integral') and i > 0 for i in size]
+ if not all(valid):
+ raise ValueError("All elements of `size` must be positive integers.")
+ else:
+ # If provided, `footprint` must be array-like
+ footprint = xp.asarray(footprint, dtype=xp.bool)
+ size = footprint.shape
+ def footprinted_function(input, *args, axis=-1, **kwargs):
+ return function(input[..., footprint], *args, axis=-1, **kwargs)
+
+ # And by now, the dimensionality of the footprint must equal the number of axes
+ if n_axes != len(size):
+ message = ("`axes` must be compatible with the dimensionality "
+ "of the window specified by `size` or `footprint`.")
+ raise ValueError(message)
+
+ # If this is not *equal* to the dimensionality of `input`, then `axes`
+ # must be a provided tuple, and its length must equal the core dimensionality.
+ elif n_axes < input.ndim:
+ if axes is None:
+ message = ("`axes` must be provided if the dimensionality of the window "
+ "(`len(size)` or `footprint.ndim`) does not equal the number "
+ "of axes of `input` (`input.ndim`).")
+ raise ValueError(message)
+ else:
+ axes = tuple(range(-n_axes, 0)) if axes is None else axes
+
+ axes = (axes,) if np.isscalar(axes) else axes
+
+ # If `origin` is provided, then it must be "broadcastable" to a tuple with length
+ # equal to the core dimensionality.
+ if origin is None:
+ origin = (0,) * n_axes
+ else:
+ origin = (origin,)*n_axes if np.isscalar(origin) else tuple(origin)
+ integral = [xp.isdtype(xp.asarray(i).dtype, 'integral') for i in origin]
+ if not all(integral):
+ raise ValueError("All elements of `origin` must be integers.")
+ if not len(origin) == n_axes:
+ message = ("`origin` must be an integer or tuple of integers with length "
+ "equal to the number of axes.")
+ raise ValueError(message)
+
+ # mode must be one of the allowed strings, and we should convert it to the
+ # value required by `np.pad`/`cp.pad` here.
+ valid_modes = {'reflect', 'constant', 'nearest', 'mirror', 'wrap',
+ 'grid-mirror', 'grid-constant', 'grid-wrap', 'valid'}
+ if mode not in valid_modes:
+ raise ValueError(f"`mode` must be one of {valid_modes}.")
+ mode_map = {'nearest': 'edge', 'reflect': 'symmetric', 'mirror': 'reflect',
+ 'grid-mirror': 'reflect', 'grid-constant': 'constant',
+ 'grid-wrap': 'wrap'}
+ mode = mode_map.get(mode, mode)
+
+ if mode == 'valid' and any(origin):
+ raise ValueError("`mode='valid'` is incompatible with use of `origin`.")
+
+ if cval is None:
+ cval = 0.0
+ elif mode != 'constant':
+ raise ValueError("Use of `cval` is compatible only with `mode='constant'`.")
+
+ # `cval` must be a scalar or "broadcastable" to a tuple with the same
+ # dimensionality of `input`. (Full input validation done by `np.pad`/`cp.pad`.)
+ if not xp.isdtype(xp.asarray(cval).dtype, 'numeric'):
+ raise ValueError("`cval` must include only numbers.")
+
+ # `batch_memory` must be a positive number.
+ temp = xp.asarray(batch_memory)
+ if temp.ndim != 0 or (not xp.isdtype(temp.dtype, 'numeric')) or temp <= 0:
+ raise ValueError("`batch_memory` must be positive number.")
+
+ # For simplicity, work with `axes` at the end.
+ working_axes = tuple(range(-n_axes, 0))
+ input = xp.moveaxis(input, axes, working_axes)
+ output = (xp.moveaxis(output, axes, working_axes)
+ if output is not None else output)
+
+ # Wrap the function to limit maximum memory usage, deal with `footprint`,
+ # and populate `output`. The latter requires some verbosity because we
+ # don't know the output dtype.
+ def wrapped_function(view, output=output):
+ kwargs = {'axis': working_axes}
+
+ if working_axes == ():
+ return footprinted_function(xp.asarray(view), **kwargs)
+
+ # for now, assume we only have to iterate over zeroth axis
+ chunk_size = math.prod(view.shape[1:]) * view.dtype.itemsize
+ slices_per_batch = min(view.shape[0], batch_memory // chunk_size)
+ if slices_per_batch < 1:
+ raise ValueError("`batch_memory` is insufficient for minimum chunk size.")
+
+ elif slices_per_batch == view.shape[0]:
+ if output is None:
+ return footprinted_function(xp.asarray(view), **kwargs)
+ else:
+ output[...] = footprinted_function(xp.asarray(view), **kwargs)
+ return output
+
+ for i in range(0, view.shape[0], slices_per_batch):
+ i2 = min(i + slices_per_batch, view.shape[0])
+ if output is None:
+ # Look at the dtype before allocating the array. (In a follow-up, we
+ # can also look at the shape to support non-scalar elements.)
+ temp = footprinted_function(xp.asarray(view[i:i2]), **kwargs)
+ output = xp.empty(view.shape[:-n_axes], dtype=temp.dtype)
+ output[i:i2, ...] = temp
+ else:
+ output[i:i2, ...] = footprinted_function(xp.asarray(view[i:i2]),
+ **kwargs)
+ return output
+
+ return (input, wrapped_function, size, mode, cval, origin,
+ working_axes, axes, n_axes, n_batch, xp)
+
+
+@_ni_docstrings.docfiller
+def vectorized_filter(input, function, *, size=None, footprint=None, output=None,
+ mode='reflect', cval=None, origin=None, axes=None,
+ batch_memory=2**30):
+ """Filter an array with a vectorized Python callable as the kernel
+
+ Parameters
+ ----------
+ %(input)s
+ function : callable
+ Kernel to apply over a window centered at each element of `input`.
+ Callable must have signature::
+
+ function(window: ndarray, *, axis: int | tuple) -> scalar
+
+ where ``axis`` specifies the axis (or axes) of ``window`` along which
+ the filter function is evaluated.
+ size : scalar or tuple, optional
+ See `footprint` below. Ignored if `footprint` is given.
+ footprint : array, optional
+ Either `size` or `footprint` must be defined. `size` gives
+ the shape that is taken from the input array, at every element
+ position, to define the input to the filter function.
+ `footprint` is a boolean array that specifies (implicitly) a
+ shape, but also which of the elements within this shape will get
+ passed to the filter function. Thus ``size=(n, m)`` is equivalent
+ to ``footprint=np.ones((n, m))``.
+ We adjust `size` to the number of dimensions indicated by `axes`.
+ For instance, if `axes` is ``(0, 2, 1)`` and ``n`` is passed for ``size``,
+ then the effective `size` is ``(n, n, n)``.
+ output : array, optional
+ The array in which to place the output. By default, an array of the dtype
+ returned by `function` will be created.
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+ The `mode` parameter determines how the input array is extended
+ beyond its boundaries. Default is 'reflect'. Behavior for each valid
+ value is as follows:
+
+ 'reflect' (`d c b a | a b c d | d c b a`)
+ The input is extended by reflecting about the edge of the last
+ pixel. This mode is also sometimes referred to as half-sample
+ symmetric.
+
+ 'constant' (`k k k k | a b c d | k k k k`)
+ The input is extended by filling all values beyond the edge with
+ the same constant value, defined by the `cval` parameter.
+
+ 'nearest' (`a a a a | a b c d | d d d d`)
+ The input is extended by replicating the last pixel.
+
+ 'mirror' (`d c b | a b c d | c b a`)
+ The input is extended by reflecting about the center of the last
+ pixel. This mode is also sometimes referred to as whole-sample
+ symmetric.
+
+ 'wrap' (`a b c d | a b c d | a b c d`)
+ The input is extended by wrapping around to the opposite edge.
+
+ 'valid' (`| a b c d |`)
+ The input is not extended; rather, the output shape is reduced depending
+ on the window size according to the following calculation::
+
+ window_size = np.asarray(size if size is not None else footprint.shape)
+ output_shape = np.asarray(input.shape)
+ output_shape[np.asarray(axes)] -= (window_size - 1)
+
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int, optional
+ If None, `input` is filtered along all axes. Otherwise, `input` is filtered
+ along the specified axes. When `axes` is specified, the dimensionality of
+ `footprint` and the length of any tuples used for `size` or `origin` must
+ match the length of `axes`. The ith axis of `footprint` and the ith element
+ in these tuples corresponds to the ith element of `axes`.
+ batch_memory : int, default: 2**30
+ The maximum number of bytes occupied by data in the ``window``
+ array passed to ``function``.
+
+ Returns
+ -------
+ output : ndarray
+ Filtered array. The dtype is the output dtype of `function`. If `function` is
+ scalar-valued when applied to a single window, the shape of the output is that
+ of `input` (unless ``mode=='valid'``; see `mode` documentation). If `function`
+ is multi-valued when applied to a single window, the placement of the
+ corresponding dimensions within the output shape depends entirely on the
+ behavior of `function`; see Examples.
+
+ See Also
+ --------
+ scipy.ndimage.generic_filter
+
+ Notes
+ -----
+ This function works by padding `input` according to `mode`, then calling the
+ provided `function` on chunks of a sliding window view over the padded array.
+ This approach is very simple and flexible, and so the function has many features
+ not offered by some other filter functions (e.g. memory control, ``float16``
+ and complex dtype support, and any NaN-handling features provided by the
+ `function` argument).
+
+ However, this brute-force approach may perform considerable redundant work.
+ Use a specialized filter (e.g. `minimum_filter` instead of this function with
+ `numpy.min` as the callable; `uniform_filter` instead of this function with
+ `numpy.mean` as the callable) when possible, as it may use a more efficient
+ algorithm.
+
+ When a specialized filter is not available, this function is ideal when `function`
+ is a vectorized, pure-Python callable. Even better performance may be possible
+ by passing a `scipy.LowLevelCallable` to `generic_filter`. `generic_filter` may
+ also be preferred for expensive callables with large filter footprints and
+ callables that are not vectorized (i.e. those without ``axis`` support).
+
+ This function does not provide the ``extra_arguments`` or ``extra_keywords``
+ arguments provided by some `ndimage` functions. There are two reasons:
+
+ - The passthrough functionality can be achieved by the user: simply wrap the
+ original callable in another function that provides the required arguments;
+ e.g., ``function=lambda input, axis: function(input, *extra_arguments, axis=axis, **extra_keywords)``.
+ - There are use cases for `function` to be passed additional *sliding-window data*
+ to `function` besides `input`. This is not yet implemented, but we reserve
+ these argument names for such a feature, which would add capability rather than
+ providing a duplicate interface to existing capability.
+
+ Examples
+ --------
+ Suppose we wish to perform a median filter with even window size on a ``float16``
+ image. Furthermore, the image has NaNs that we wish to be ignored (and effectively
+ removed by the filter). `median_filter` does not support ``float16`` data, its
+ behavior when NaNs are present is not defined, and for even window sizes, it does
+ not return the usual sample median - the average of the two middle elements. This
+ would be an excellent use case for `vectorized_filter` with
+ ``function=np.nanmedian``, which supports the required interface: it accepts a
+ data array of any shape as the first positional argument, and tuple of axes as
+ keyword argument ``axis``.
+
+ >>> import numpy as np
+ >>> from scipy import datasets, ndimage
+ >>> from scipy.ndimage import vectorized_filter
+ >>> import matplotlib.pyplot as plt
+ >>> ascent = ndimage.zoom(datasets.ascent(), 0.5).astype(np.float16)
+ >>> ascent[::16, ::16] = np.nan
+ >>> result = vectorized_filter(ascent, function=np.nanmedian, size=4)
+
+ Plot the original and filtered images.
+
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ Another need satisfied by `vectorized_filter` is to perform multi-output
+ filters. For instance, suppose we wish to filter an image according to the 25th
+ and 75th percentiles in addition to the median. We could perform the three
+ filters separately.
+
+ >>> ascent = ndimage.zoom(datasets.ascent(), 0.5)
+ >>> def get_quantile_fun(p):
+ ... return lambda x, axis: np.quantile(x, p, axis=axis)
+ >>> ref1 = vectorized_filter(ascent, get_quantile_fun(0.25), size=4)
+ >>> ref2 = vectorized_filter(ascent, get_quantile_fun(0.50), size=4)
+ >>> ref3 = vectorized_filter(ascent, get_quantile_fun(0.75), size=4)
+ >>> ref = np.stack([ref1, ref2, ref3])
+
+ However, `vectorized_filter` also supports filters that return multiple outputs
+ as long as `output` is unspecified and `batch_memory` is sufficiently high to
+ perform the calculation in a single chunk.
+
+ >>> def quartiles(x, axis):
+ ... return np.quantile(x, [0.25, 0.50, 0.75], axis=axis)
+ >>> res = vectorized_filter(ascent, quartiles, size=4, batch_memory=np.inf)
+ >>> np.all(np.isclose(res, ref))
+ np.True_
+
+ The placement of the additional dimension(s) corresponding with multiple outputs
+ is at the discretion of `function`. `quartiles` happens to prepend one dimension
+ corresponding with the three outputs simply because that is the behavior of
+ `np.quantile`:
+
+ >>> res.shape == (3,) + ascent.shape
+ True
+
+ If we wished for this dimension to be appended:
+
+ >>> def quartiles(x, axis):
+ ... return np.moveaxis(np.quantile(x, [0.25, 0.50, 0.75], axis=axis), 0, -1)
+ >>> res = vectorized_filter(ascent, quartiles, size=4, batch_memory=np.inf)
+ >>> res.shape == ascent.shape + (3,)
+ True
+
+ Suppose we wish to implment a "mode" filter - a filter that selects the most
+ frequently occuring value within the window. A simple (but rather slow)
+ approach is to use `generic_filter` with `scipy.stats.mode`.
+
+ >>> from scipy import stats
+ >>> rng = np.random.default_rng(3195824598724609246)
+ >>> input = rng.integers(255, size=(50, 50)).astype(np.uint8)
+ >>> def simple_mode(input):
+ ... return stats.mode(input, axis=None).mode
+ >>> ref = ndimage.generic_filter(input, simple_mode, size=5)
+
+ If speed is important, `vectorized_filter` can take advantage of the performance
+ benefit of a vectorized callable.
+
+ >>> def vectorized_mode(x, axis=(-1,)):
+ ... n_axes = 1 if np.isscalar(axis) else len(axis)
+ ... x = np.moveaxis(x, axis, tuple(range(-n_axes, 0)))
+ ... x = np.reshape(x, x.shape[:-n_axes] + (-1,))
+ ... y = np.sort(x, axis=-1)
+ ... i = np.concatenate([np.ones(y.shape[:-1] + (1,), dtype=bool),
+ ... y[..., :-1] != y[..., 1:]], axis=-1)
+ ... indices = np.arange(y.size)[i.ravel()]
+ ... counts = np.diff(indices, append=y.size)
+ ... counts = np.reshape(np.repeat(counts, counts), y.shape)
+ ... k = np.argmax(counts, axis=-1, keepdims=True)
+ ... return np.take_along_axis(y, k, axis=-1)[..., 0]
+ >>> res = vectorized_filter(input, vectorized_mode, size=5)
+ >>> np.all(res == ref)
+ np.True_
+
+ Depending on the machine, the `vectorized_filter` version may be as much as
+ 100x faster.
+
+ """ # noqa: E501
+
+ (input, function, size, mode, cval, origin, working_axes, axes, n_axes, n_batch, xp
+ ) = _vectorized_filter_iv(input, function, size, footprint, output, mode, cval,
+ origin, axes, batch_memory)
+
+ # `np.pad`/`cp.pad` raises with these sorts of cases, but the best result is
+ # probably to return the original array. It could be argued that we should call
+ # the function on the empty array with `axis=None` just to determine the output
+ # dtype, but I can also see rationale against that.
+ if xp_size(input) == 0:
+ return xp.asarray(input)
+
+ # This seems to be defined.
+ if input.ndim == 0 and size == ():
+ return xp.asarray(function(input) if footprint is None
+ else function(input[footprint]))
+
+ if is_cupy(xp):
+ # CuPy is the only GPU backend that has `pad` (with all modes)
+ # and `sliding_window_view`. An enhancement would be to use
+ # no-copy conversion to CuPy whenever the data is on the GPU.
+ cp = xp # let there be no ambiguity!
+ swv = cp.lib.stride_tricks.sliding_window_view
+ pad = cp.pad
+ else:
+ # Try to perform no-copy conversion to NumPy for padding and
+ # `sliding_window_view`. (If that fails, fine - for now, the only
+ # GPU backend we support is CuPy.)
+ swv = np.lib.stride_tricks.sliding_window_view
+ pad = np.pad
+ input = np.asarray(input)
+ cval = np.asarray(cval)[()] if mode == 'constant' else None
+
+ # Border the image according to `mode` and `offset`.
+ if mode != 'valid':
+ kwargs = {'constant_values': cval} if mode == 'constant' else {}
+ borders = tuple((i//2 + j, (i-1)//2 - j) for i, j in zip(size, origin))
+ bordered_input = pad(input, ((0, 0),)*n_batch + borders, mode=mode, **kwargs)
+ else:
+ bordered_input = input
+
+ # Evaluate function with sliding window view. Function is already wrapped to
+ # manage memory, deal with `footprint`, populate `output`, etc.
+ view = swv(bordered_input, size, working_axes)
+ res = function(view)
+
+ # move working_axes back to original positions
+ return xp.moveaxis(res, working_axes, axes)
+
+
+def _invalid_origin(origin, lenw):
+ return (origin < -(lenw // 2)) or (origin > (lenw - 1) // 2)
+
+
+def _complex_via_real_components(func, input, weights, output, cval, **kwargs):
+ """Complex convolution via a linear combination of real convolutions."""
+ complex_input = input.dtype.kind == 'c'
+ complex_weights = weights.dtype.kind == 'c'
+ if complex_input and complex_weights:
+ # real component of the output
+ func(input.real, weights.real, output=output.real,
+ cval=np.real(cval), **kwargs)
+ output.real -= func(input.imag, weights.imag, output=None,
+ cval=np.imag(cval), **kwargs)
+ # imaginary component of the output
+ func(input.real, weights.imag, output=output.imag,
+ cval=np.real(cval), **kwargs)
+ output.imag += func(input.imag, weights.real, output=None,
+ cval=np.imag(cval), **kwargs)
+ elif complex_input:
+ func(input.real, weights, output=output.real, cval=np.real(cval),
+ **kwargs)
+ func(input.imag, weights, output=output.imag, cval=np.imag(cval),
+ **kwargs)
+ else:
+ if np.iscomplexobj(cval):
+ raise ValueError("Cannot provide a complex-valued cval when the "
+ "input is real.")
+ func(input, weights.real, output=output.real, cval=cval, **kwargs)
+ func(input, weights.imag, output=output.imag, cval=cval, **kwargs)
+ return output
+
+
+def _expand_origin(ndim_image, axes, origin):
+ num_axes = len(axes)
+ origins = _ni_support._normalize_sequence(origin, num_axes)
+ if num_axes < ndim_image:
+ # set origin = 0 for any axes not being filtered
+ origins_temp = [0,] * ndim_image
+ for o, ax in zip(origins, axes):
+ origins_temp[ax] = o
+ origins = origins_temp
+ return origins
+
+
+def _expand_footprint(ndim_image, axes, footprint,
+ footprint_name="footprint"):
+ num_axes = len(axes)
+ if num_axes < ndim_image:
+ if footprint.ndim != num_axes:
+ raise RuntimeError(f"{footprint_name}.ndim ({footprint.ndim}) "
+ f"must match len(axes) ({num_axes})")
+
+ footprint = np.expand_dims(
+ footprint,
+ tuple(ax for ax in range(ndim_image) if ax not in axes)
+ )
+ return footprint
+
+
+def _expand_mode(ndim_image, axes, mode):
+ num_axes = len(axes)
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
+ # set mode = 'constant' for any axes not being filtered
+ modes = _ni_support._normalize_sequence(mode, num_axes)
+ modes_temp = ['constant'] * ndim_image
+ for m, ax in zip(modes, axes):
+ modes_temp[ax] = m
+ mode = modes_temp
+ return mode
+
+
+@_ni_docstrings.docfiller
+def correlate1d(input, weights, axis=-1, output=None, mode="reflect",
+ cval=0.0, origin=0):
+ """Calculate a 1-D correlation along the given axis.
+
+ The lines of the array along the given axis are correlated with the
+ given weights.
+
+ Parameters
+ ----------
+ %(input)s
+ weights : array
+ 1-D sequence of numbers.
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+
+ Returns
+ -------
+ result : ndarray
+ Correlation result. Has the same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy.ndimage import correlate1d
+ >>> correlate1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
+ array([ 8, 26, 8, 12, 7, 28, 36, 9])
+ """
+ input = np.asarray(input)
+ weights = np.asarray(weights)
+ complex_input = input.dtype.kind == 'c'
+ complex_weights = weights.dtype.kind == 'c'
+ if complex_input or complex_weights:
+ if complex_weights:
+ weights = weights.conj()
+ weights = weights.astype(np.complex128, copy=False)
+ kwargs = dict(axis=axis, mode=mode, origin=origin)
+ output = _ni_support._get_output(output, input, complex_output=True)
+ return _complex_via_real_components(correlate1d, input, weights,
+ output, cval, **kwargs)
+
+ output = _ni_support._get_output(output, input)
+ weights = np.asarray(weights, dtype=np.float64)
+ if weights.ndim != 1 or weights.shape[0] < 1:
+ raise RuntimeError('no filter weights given')
+ if not weights.flags.contiguous:
+ weights = weights.copy()
+ axis = normalize_axis_index(axis, input.ndim)
+ if _invalid_origin(origin, len(weights)):
+ raise ValueError('Invalid origin; origin must satisfy '
+ '-(len(weights) // 2) <= origin <= '
+ '(len(weights)-1) // 2')
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.correlate1d(input, weights, axis, output, mode, cval,
+ origin)
+ return output
+
+
+@_ni_docstrings.docfiller
+def convolve1d(input, weights, axis=-1, output=None, mode="reflect",
+ cval=0.0, origin=0):
+ """Calculate a 1-D convolution along the given axis.
+
+ The lines of the array along the given axis are convolved with the
+ given weights.
+
+ Parameters
+ ----------
+ %(input)s
+ weights : ndarray
+ 1-D sequence of numbers.
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+
+ Returns
+ -------
+ convolve1d : ndarray
+ Convolved array with same shape as input
+
+ Examples
+ --------
+ >>> from scipy.ndimage import convolve1d
+ >>> convolve1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3])
+ array([14, 24, 4, 13, 12, 36, 27, 0])
+ """
+ weights = np.asarray(weights)
+ weights = weights[::-1]
+ origin = -origin
+ if not weights.shape[0] & 1:
+ origin -= 1
+ if weights.dtype.kind == 'c':
+ # pre-conjugate here to counteract the conjugation in correlate1d
+ weights = weights.conj()
+ return correlate1d(input, weights, axis, output, mode, cval, origin)
+
+
+def _gaussian_kernel1d(sigma, order, radius):
+ """
+ Computes a 1-D Gaussian convolution kernel.
+ """
+ if order < 0:
+ raise ValueError('order must be non-negative')
+ exponent_range = np.arange(order + 1)
+ sigma2 = sigma * sigma
+ x = np.arange(-radius, radius+1)
+ phi_x = np.exp(-0.5 / sigma2 * x ** 2)
+ phi_x = phi_x / phi_x.sum()
+
+ if order == 0:
+ return phi_x
+ else:
+ # f(x) = q(x) * phi(x) = q(x) * exp(p(x))
+ # f'(x) = (q'(x) + q(x) * p'(x)) * phi(x)
+ # p'(x) = -1 / sigma ** 2
+ # Implement q'(x) + q(x) * p'(x) as a matrix operator and apply to the
+ # coefficients of q(x)
+ q = np.zeros(order + 1)
+ q[0] = 1
+ D = np.diag(exponent_range[1:], 1) # D @ q(x) = q'(x)
+ P = np.diag(np.ones(order)/-sigma2, -1) # P @ q(x) = q(x) * p'(x)
+ Q_deriv = D + P
+ for _ in range(order):
+ q = Q_deriv.dot(q)
+ q = (x[:, None] ** exponent_range).dot(q)
+ return q * phi_x
+
+
+@_ni_docstrings.docfiller
+def gaussian_filter1d(input, sigma, axis=-1, order=0, output=None,
+ mode="reflect", cval=0.0, truncate=4.0, *, radius=None):
+ """1-D Gaussian filter.
+
+ Parameters
+ ----------
+ %(input)s
+ sigma : scalar
+ standard deviation for Gaussian kernel
+ %(axis)s
+ order : int, optional
+ An order of 0 corresponds to convolution with a Gaussian
+ kernel. A positive order corresponds to convolution with
+ that derivative of a Gaussian.
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ truncate : float, optional
+ Truncate the filter at this many standard deviations.
+ Default is 4.0.
+ radius : None or int, optional
+ Radius of the Gaussian kernel. If specified, the size of
+ the kernel will be ``2*radius + 1``, and `truncate` is ignored.
+ Default is None.
+
+ Returns
+ -------
+ gaussian_filter1d : ndarray
+
+ 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_magnitude : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ """
+ if extra_keywords is None:
+ extra_keywords = {}
+ input = np.asarray(input)
+ output = _ni_support._get_output(output, input)
+ axes = _ni_support._check_axes(axes, input.ndim)
+ if len(axes) > 0:
+ modes = _ni_support._normalize_sequence(mode, len(axes))
+ derivative(input, axes[0], output, modes[0], cval,
+ *extra_arguments, **extra_keywords)
+ np.multiply(output, output, output)
+ for ii in range(1, len(axes)):
+ tmp = derivative(input, axes[ii], output.dtype, modes[ii], cval,
+ *extra_arguments, **extra_keywords)
+ np.multiply(tmp, tmp, tmp)
+ output += tmp
+ # This allows the sqrt to work with a different default casting
+ np.sqrt(output, output, casting='unsafe')
+ else:
+ output[...] = input[...]
+ return output
+
+
+@_ni_docstrings.docfiller
+def gaussian_gradient_magnitude(input, sigma, output=None,
+ mode="reflect", cval=0.0, *, axes=None,
+ **kwargs):
+ """Multidimensional gradient magnitude using Gaussian derivatives.
+
+ Parameters
+ ----------
+ %(input)s
+ sigma : scalar or sequence of scalars
+ The standard deviations of the Gaussian filter are given for
+ each axis as a sequence, or as a single number, in which case
+ it is equal for all axes.
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ axes : tuple of int or None
+ The axes over which to apply the filter. If `sigma` or `mode` tuples
+ are provided, their length must match the number of axes.
+ Extra keyword arguments will be passed to gaussian_filter().
+
+ Returns
+ -------
+ gaussian_gradient_magnitude : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.gaussian_gradient_magnitude(ascent, sigma=5)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+
+ def derivative(input, axis, output, mode, cval, sigma, **kwargs):
+ order = [0] * input.ndim
+ order[axis] = 1
+ return gaussian_filter(input, sigma, order, output, mode,
+ cval, **kwargs)
+
+ return generic_gradient_magnitude(input, derivative, output, mode,
+ cval, extra_arguments=(sigma,),
+ extra_keywords=kwargs, axes=axes)
+
+
+def _correlate_or_convolve(input, weights, output, mode, cval, origin,
+ convolution, axes):
+ input = np.asarray(input)
+ weights = np.asarray(weights)
+ complex_input = input.dtype.kind == 'c'
+ complex_weights = weights.dtype.kind == 'c'
+ if complex_input or complex_weights:
+ if complex_weights and not convolution:
+ # As for np.correlate, conjugate weights rather than input.
+ weights = weights.conj()
+ kwargs = dict(
+ mode=mode, origin=origin, convolution=convolution, axes=axes
+ )
+ output = _ni_support._get_output(output, input, complex_output=True)
+
+ return _complex_via_real_components(_correlate_or_convolve, input,
+ weights, output, cval, **kwargs)
+
+ axes = _ni_support._check_axes(axes, input.ndim)
+ weights = np.asarray(weights, dtype=np.float64)
+
+ # expand weights and origins if num_axes < input.ndim
+ weights = _expand_footprint(input.ndim, axes, weights, "weights")
+ origins = _expand_origin(input.ndim, axes, origin)
+
+ wshape = [ii for ii in weights.shape if ii > 0]
+ if len(wshape) != input.ndim:
+ raise RuntimeError(f"weights.ndim ({len(wshape)}) must match "
+ f"len(axes) ({len(axes)})")
+ if convolution:
+ weights = weights[tuple([slice(None, None, -1)] * weights.ndim)]
+ for ii in range(len(origins)):
+ origins[ii] = -origins[ii]
+ if not weights.shape[ii] & 1:
+ origins[ii] -= 1
+ for origin, lenw in zip(origins, wshape):
+ if _invalid_origin(origin, lenw):
+ raise ValueError('Invalid origin; origin must satisfy '
+ '-(weights.shape[k] // 2) <= origin[k] <= '
+ '(weights.shape[k]-1) // 2')
+
+ if not weights.flags.contiguous:
+ weights = weights.copy()
+ output = _ni_support._get_output(output, input)
+ temp_needed = np.may_share_memory(input, output)
+ if temp_needed:
+ # input and output arrays cannot share memory
+ temp = output
+ output = _ni_support._get_output(output.dtype, input)
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
+ raise RuntimeError("A sequence of modes is not supported")
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.correlate(input, weights, output, mode, cval, origins)
+ if temp_needed:
+ temp[...] = output
+ output = temp
+ return output
+
+
+@_ni_docstrings.docfiller
+def correlate(input, weights, output=None, mode='reflect', cval=0.0,
+ origin=0, *, axes=None):
+ """
+ Multidimensional correlation.
+
+ The array is correlated with the given kernel.
+
+ Parameters
+ ----------
+ %(input)s
+ weights : ndarray
+ array of weights, same number of dimensions as input
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `mode` or `origin` must match the length
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
+ entry in `axes`.
+
+ Returns
+ -------
+ result : ndarray
+ The result of correlation of `input` with `weights`.
+
+ See Also
+ --------
+ convolve : Convolve an image with a kernel.
+
+ Examples
+ --------
+ Correlation is the process of moving a filter mask often referred to
+ as kernel over the image and computing the sum of products at each location.
+
+ >>> from scipy.ndimage import correlate
+ >>> import numpy as np
+ >>> input_img = np.arange(25).reshape(5,5)
+ >>> print(input_img)
+ [[ 0 1 2 3 4]
+ [ 5 6 7 8 9]
+ [10 11 12 13 14]
+ [15 16 17 18 19]
+ [20 21 22 23 24]]
+
+ Define a kernel (weights) for correlation. In this example, it is for sum of
+ center and up, down, left and right next elements.
+
+ >>> weights = [[0, 1, 0],
+ ... [1, 1, 1],
+ ... [0, 1, 0]]
+
+ We can calculate a correlation result:
+ For example, element ``[2,2]`` is ``7 + 11 + 12 + 13 + 17 = 60``.
+
+ >>> correlate(input_img, weights)
+ array([[ 6, 10, 15, 20, 24],
+ [ 26, 30, 35, 40, 44],
+ [ 51, 55, 60, 65, 69],
+ [ 76, 80, 85, 90, 94],
+ [ 96, 100, 105, 110, 114]])
+
+ """
+ return _correlate_or_convolve(input, weights, output, mode, cval,
+ origin, False, axes)
+
+
+@_ni_docstrings.docfiller
+def convolve(input, weights, output=None, mode='reflect', cval=0.0,
+ origin=0, *, axes=None):
+ """
+ Multidimensional convolution.
+
+ The array is convolved with the given kernel.
+
+ Parameters
+ ----------
+ %(input)s
+ weights : array_like
+ Array of weights, same number of dimensions as input
+ %(output)s
+ %(mode_reflect)s
+ cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'. Default
+ is 0.0
+ origin : int or sequence, optional
+ Controls the placement of the filter on the input array's pixels.
+ A value of 0 (the default) centers the filter over the pixel, with
+ positive values shifting the filter to the right, and negative ones
+ to the left. By passing a sequence of origins with length equal to
+ the number of dimensions of the input array, different shifts can
+ be specified along each axis.
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `mode` or `origin` must match the length
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
+ entry in `axes`.
+
+ Returns
+ -------
+ result : ndarray
+ The result of convolution of `input` with `weights`.
+
+ See Also
+ --------
+ correlate : Correlate an image with a kernel.
+
+ Notes
+ -----
+ Each value in result is :math:`C_i = \\sum_j{I_{i+k-j} W_j}`, where
+ W is the `weights` kernel,
+ j is the N-D spatial index over :math:`W`,
+ I is the `input` and k is the coordinate of the center of
+ W, specified by `origin` in the input parameters.
+
+ Examples
+ --------
+ Perhaps the simplest case to understand is ``mode='constant', cval=0.0``,
+ because in this case borders (i.e., where the `weights` kernel, centered
+ on any one value, extends beyond an edge of `input`) are treated as zeros.
+
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> k = np.array([[1,1,1],[1,1,0],[1,0,0]])
+ >>> from scipy import ndimage
+ >>> ndimage.convolve(a, k, mode='constant', cval=0.0)
+ array([[11, 10, 7, 4],
+ [10, 3, 11, 11],
+ [15, 12, 14, 7],
+ [12, 3, 7, 0]])
+
+ Setting ``cval=1.0`` is equivalent to padding the outer edge of `input`
+ with 1.0's (and then extracting only the original region of the result).
+
+ >>> ndimage.convolve(a, k, mode='constant', cval=1.0)
+ array([[13, 11, 8, 7],
+ [11, 3, 11, 14],
+ [16, 12, 14, 10],
+ [15, 6, 10, 5]])
+
+ With ``mode='reflect'`` (the default), outer values are reflected at the
+ edge of `input` to fill in missing values.
+
+ >>> b = np.array([[2, 0, 0],
+ ... [1, 0, 0],
+ ... [0, 0, 0]])
+ >>> k = np.array([[0,1,0], [0,1,0], [0,1,0]])
+ >>> ndimage.convolve(b, k, mode='reflect')
+ array([[5, 0, 0],
+ [3, 0, 0],
+ [1, 0, 0]])
+
+ This includes diagonally at the corners.
+
+ >>> k = np.array([[1,0,0],[0,1,0],[0,0,1]])
+ >>> ndimage.convolve(b, k)
+ array([[4, 2, 0],
+ [3, 2, 0],
+ [1, 1, 0]])
+
+ With ``mode='nearest'``, the single nearest value in to an edge in
+ `input` is repeated as many times as needed to match the overlapping
+ `weights`.
+
+ >>> c = np.array([[2, 0, 1],
+ ... [1, 0, 0],
+ ... [0, 0, 0]])
+ >>> k = np.array([[0, 1, 0],
+ ... [0, 1, 0],
+ ... [0, 1, 0],
+ ... [0, 1, 0],
+ ... [0, 1, 0]])
+ >>> ndimage.convolve(c, k, mode='nearest')
+ array([[7, 0, 3],
+ [5, 0, 2],
+ [3, 0, 1]])
+
+ """
+ return _correlate_or_convolve(input, weights, output, mode, cval,
+ origin, True, axes)
+
+
+@_ni_docstrings.docfiller
+def uniform_filter1d(input, size, axis=-1, output=None,
+ mode="reflect", cval=0.0, origin=0):
+ """Calculate a 1-D uniform filter along the given axis.
+
+ The lines of the array along the given axis are filtered with a
+ uniform filter of given size.
+
+ Parameters
+ ----------
+ %(input)s
+ size : int
+ length of uniform filter
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+
+ Returns
+ -------
+ result : ndarray
+ Filtered array. Has same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy.ndimage import uniform_filter1d
+ >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+ array([4, 3, 4, 1, 4, 6, 6, 3])
+ """
+ input = np.asarray(input)
+ axis = normalize_axis_index(axis, input.ndim)
+ if size < 1:
+ raise RuntimeError('incorrect filter size')
+ complex_output = input.dtype.kind == 'c'
+ output = _ni_support._get_output(output, input,
+ complex_output=complex_output)
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+ raise ValueError('invalid origin')
+ mode = _ni_support._extend_mode_to_code(mode)
+ if not complex_output:
+ _nd_image.uniform_filter1d(input, size, axis, output, mode, cval,
+ origin)
+ else:
+ _nd_image.uniform_filter1d(input.real, size, axis, output.real, mode,
+ np.real(cval), origin)
+ _nd_image.uniform_filter1d(input.imag, size, axis, output.imag, mode,
+ np.imag(cval), origin)
+ return output
+
+
+@_ni_docstrings.docfiller
+def uniform_filter(input, size=3, output=None, mode="reflect",
+ cval=0.0, origin=0, *, axes=None):
+ """Multidimensional uniform filter.
+
+ Parameters
+ ----------
+ %(input)s
+ size : int or sequence of ints, optional
+ The sizes of the uniform filter are given for each axis as a
+ sequence, or as a single number, in which case the size is
+ equal for all axes.
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ uniform_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Notes
+ -----
+ The multidimensional filter is implemented as a sequence of
+ 1-D uniform filters. The intermediate arrays are stored
+ in the same data type as the output. Therefore, for output types
+ with a limited precision, the results may be imprecise because
+ intermediate results may be stored with insufficient precision.
+
+ %(nan)s
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.uniform_filter(ascent, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+ output = _ni_support._get_output(output, input,
+ complex_output=input.dtype.kind == 'c')
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ sizes = _ni_support._normalize_sequence(size, num_axes)
+ origins = _ni_support._normalize_sequence(origin, num_axes)
+ modes = _ni_support._normalize_sequence(mode, num_axes)
+ axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
+ for ii in range(num_axes) if sizes[ii] > 1]
+ if len(axes) > 0:
+ for axis, size, origin, mode in axes:
+ uniform_filter1d(input, int(size), axis, output, mode,
+ cval, origin)
+ input = output
+ else:
+ output[...] = input[...]
+ return output
+
+
+@_ni_docstrings.docfiller
+def minimum_filter1d(input, size, axis=-1, output=None,
+ mode="reflect", cval=0.0, origin=0):
+ """Calculate a 1-D minimum filter along the given axis.
+
+ The lines of the array along the given axis are filtered with a
+ minimum filter of given size.
+
+ Parameters
+ ----------
+ %(input)s
+ size : int
+ length along which to calculate 1D minimum
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+
+ Returns
+ -------
+ result : ndarray.
+ Filtered image. Has the same shape as `input`.
+
+ Notes
+ -----
+ This function implements the MINLIST algorithm [1]_, as described by
+ Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
+ the `input` length, regardless of filter size.
+
+ References
+ ----------
+ .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
+ .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
+
+
+ Examples
+ --------
+ >>> from scipy.ndimage import minimum_filter1d
+ >>> minimum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+ array([2, 0, 0, 0, 1, 1, 0, 0])
+ """
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ axis = normalize_axis_index(axis, input.ndim)
+ if size < 1:
+ raise RuntimeError('incorrect filter size')
+ output = _ni_support._get_output(output, input)
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+ raise ValueError('invalid origin')
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
+ origin, 1)
+ return output
+
+
+@_ni_docstrings.docfiller
+def maximum_filter1d(input, size, axis=-1, output=None,
+ mode="reflect", cval=0.0, origin=0):
+ """Calculate a 1-D maximum filter along the given axis.
+
+ The lines of the array along the given axis are filtered with a
+ maximum filter of given size.
+
+ Parameters
+ ----------
+ %(input)s
+ size : int
+ Length along which to calculate the 1-D maximum.
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+
+ Returns
+ -------
+ maximum1d : ndarray, None
+ Maximum-filtered array with same shape as input.
+ None if `output` is not None
+
+ Notes
+ -----
+ This function implements the MAXLIST algorithm [1]_, as described by
+ Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being
+ the `input` length, regardless of filter size.
+
+ References
+ ----------
+ .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777
+ .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html
+
+ Examples
+ --------
+ >>> from scipy.ndimage import maximum_filter1d
+ >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3)
+ array([8, 8, 8, 4, 9, 9, 9, 9])
+ """
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ axis = normalize_axis_index(axis, input.ndim)
+ if size < 1:
+ raise RuntimeError('incorrect filter size')
+ output = _ni_support._get_output(output, input)
+ if (size // 2 + origin < 0) or (size // 2 + origin >= size):
+ raise ValueError('invalid origin')
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval,
+ origin, 0)
+ return output
+
+
+def _min_or_max_filter(input, size, footprint, structure, output, mode,
+ cval, origin, minimum, axes=None):
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=3)
+ if structure is None:
+ if footprint is None:
+ if size is None:
+ raise RuntimeError("no footprint provided")
+ separable = True
+ else:
+ footprint = np.asarray(footprint, dtype=bool)
+ if not footprint.any():
+ raise ValueError("All-zero footprint is not supported.")
+ if footprint.all():
+ size = footprint.shape
+ footprint = None
+ separable = True
+ else:
+ separable = False
+ else:
+ structure = np.asarray(structure, dtype=np.float64)
+ separable = False
+ if footprint is None:
+ footprint = np.ones(structure.shape, bool)
+ else:
+ footprint = np.asarray(footprint, dtype=bool)
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError("Complex type not supported")
+ output = _ni_support._get_output(output, input)
+ temp_needed = np.may_share_memory(input, output)
+ if temp_needed:
+ # input and output arrays cannot share memory
+ temp = output
+ output = _ni_support._get_output(output.dtype, input)
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if separable:
+ origins = _ni_support._normalize_sequence(origin, num_axes)
+ sizes = _ni_support._normalize_sequence(size, num_axes)
+ modes = _ni_support._normalize_sequence(mode, num_axes)
+ axes = [(axes[ii], sizes[ii], origins[ii], modes[ii])
+ for ii in range(len(axes)) if sizes[ii] > 1]
+ if minimum:
+ filter_ = minimum_filter1d
+ else:
+ filter_ = maximum_filter1d
+ if len(axes) > 0:
+ for axis, size, origin, mode in axes:
+ filter_(input, int(size), axis, output, mode, cval, origin)
+ input = output
+ else:
+ output[...] = input[...]
+ else:
+ # expand origins and footprint if num_axes < input.ndim
+ footprint = _expand_footprint(input.ndim, axes, footprint)
+ origins = _expand_origin(input.ndim, axes, origin)
+
+ fshape = [ii for ii in footprint.shape if ii > 0]
+ if len(fshape) != input.ndim:
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
+ f"len(axes) ({len(axes)})")
+ for origin, lenf in zip(origins, fshape):
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+ raise ValueError("invalid origin")
+ if not footprint.flags.contiguous:
+ footprint = footprint.copy()
+ if structure is not None:
+ if len(structure.shape) != num_axes:
+ raise RuntimeError("structure array has incorrect shape")
+ if num_axes != structure.ndim:
+ structure = np.expand_dims(
+ structure,
+ tuple(ax for ax in range(structure.ndim) if ax not in axes)
+ )
+ if not structure.flags.contiguous:
+ structure = structure.copy()
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
+ raise RuntimeError(
+ "A sequence of modes is not supported for non-separable "
+ "footprints")
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.min_or_max_filter(input, footprint, structure, output,
+ mode, cval, origins, minimum)
+ if temp_needed:
+ temp[...] = output
+ output = temp
+ return output
+
+
+@_ni_docstrings.docfiller
+def minimum_filter(input, size=None, footprint=None, output=None,
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
+ """Calculate a multidimensional minimum filter.
+
+ Parameters
+ ----------
+ %(input)s
+ %(size_foot)s
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ minimum_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Notes
+ -----
+ A sequence of modes (one per axis) is only supported when the footprint is
+ separable. Otherwise, a single mode string must be provided.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.minimum_filter(ascent, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ return _min_or_max_filter(input, size, footprint, None, output, mode,
+ cval, origin, 1, axes)
+
+
+@_ni_docstrings.docfiller
+def maximum_filter(input, size=None, footprint=None, output=None,
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
+ """Calculate a multidimensional maximum filter.
+
+ Parameters
+ ----------
+ %(input)s
+ %(size_foot)s
+ %(output)s
+ %(mode_multiple)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ maximum_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Notes
+ -----
+ A sequence of modes (one per axis) is only supported when the footprint is
+ separable. Otherwise, a single mode string must be provided.
+
+ %(nan)s
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.maximum_filter(ascent, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ return _min_or_max_filter(input, size, footprint, None, output, mode,
+ cval, origin, 0, axes)
+
+
+@_ni_docstrings.docfiller
+def _rank_filter(input, rank, size=None, footprint=None, output=None,
+ mode="reflect", cval=0.0, origin=0, operation='rank',
+ axes=None):
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=3)
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if footprint is None:
+ if size is None:
+ raise RuntimeError("no footprint or filter size provided")
+ sizes = _ni_support._normalize_sequence(size, num_axes)
+ footprint = np.ones(sizes, dtype=bool)
+ else:
+ footprint = np.asarray(footprint, dtype=bool)
+ # expand origins, footprint and modes if num_axes < input.ndim
+ footprint = _expand_footprint(input.ndim, axes, footprint)
+ origins = _expand_origin(input.ndim, axes, origin)
+ mode = _expand_mode(input.ndim, axes, mode)
+
+ fshape = [ii for ii in footprint.shape if ii > 0]
+ if len(fshape) != input.ndim:
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) must match "
+ f"len(axes) ({len(axes)})")
+ for origin, lenf in zip(origins, fshape):
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+ raise ValueError('invalid origin')
+ if not footprint.flags.contiguous:
+ footprint = footprint.copy()
+ filter_size = np.where(footprint, 1, 0).sum()
+ if operation == 'median':
+ rank = filter_size // 2
+ elif operation == 'percentile':
+ percentile = rank
+ if percentile < 0.0:
+ percentile += 100.0
+ if percentile < 0 or percentile > 100:
+ raise RuntimeError('invalid percentile')
+ if percentile == 100.0:
+ rank = filter_size - 1
+ else:
+ rank = int(float(filter_size) * percentile / 100.0)
+ if rank < 0:
+ rank += filter_size
+ if rank < 0 or rank >= filter_size:
+ raise RuntimeError('rank not within filter footprint size')
+ if rank == 0:
+ return minimum_filter(input, None, footprint, output, mode, cval,
+ origins, axes=None)
+ elif rank == filter_size - 1:
+ return maximum_filter(input, None, footprint, output, mode, cval,
+ origins, axes=None)
+ else:
+ output = _ni_support._get_output(output, input)
+ temp_needed = np.may_share_memory(input, output)
+ if temp_needed:
+ # input and output arrays cannot share memory
+ temp = output
+ output = _ni_support._get_output(output.dtype, input)
+ if not isinstance(mode, str) and isinstance(mode, Iterable):
+ raise RuntimeError(
+ "A sequence of modes is not supported by non-separable rank "
+ "filters")
+ mode = _ni_support._extend_mode_to_code(mode, is_filter=True)
+ # Some corner cases are currently not allowed to use the
+ # "new"/fast 1D rank filter code, including when the
+ # footprint is large compared to the array size.
+ # See discussion in gh-23293; longer-term it may be possible
+ # to allow the fast path for these corner cases as well,
+ # if algorithmic fixes are found.
+ lim2 = input.size - ((footprint.size - 1) // 2 - origin)
+ if input.ndim == 1 and ((lim2 >= 0) or (input.size == 1)):
+ if input.dtype in (np.int64, np.float64, np.float32):
+ x = input
+ x_out = output
+ elif input.dtype == np.float16:
+ x = input.astype('float32')
+ x_out = np.empty(x.shape, dtype='float32')
+ elif np.result_type(input, np.int64) == np.int64:
+ x = input.astype('int64')
+ x_out = np.empty(x.shape, dtype='int64')
+ elif input.dtype.kind in 'biu':
+ # cast any other boolean, integer or unsigned type to int64
+ x = input.astype('int64')
+ x_out = np.empty(x.shape, dtype='int64')
+ else:
+ raise RuntimeError('Unsupported array type')
+ cval = x.dtype.type(cval)
+ _rank_filter_1d.rank_filter(x, rank, footprint.size, x_out, mode, cval,
+ origin)
+ if input.dtype not in (np.int64, np.float64, np.float32):
+ np.copyto(output, x_out, casting='unsafe')
+ else:
+ _nd_image.rank_filter(input, rank, footprint, output, mode, cval, origins)
+ if temp_needed:
+ temp[...] = output
+ output = temp
+ return output
+
+
+@_ni_docstrings.docfiller
+def rank_filter(input, rank, size=None, footprint=None, output=None,
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
+ """Calculate a multidimensional rank filter.
+
+ Parameters
+ ----------
+ %(input)s
+ rank : int
+ The rank parameter may be less than zero, i.e., rank = -1
+ indicates the largest element.
+ %(size_foot)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ rank_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.rank_filter(ascent, rank=42, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ rank = operator.index(rank)
+ return _rank_filter(input, rank, size, footprint, output, mode, cval,
+ origin, 'rank', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def median_filter(input, size=None, footprint=None, output=None,
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
+ """
+ Calculate a multidimensional median filter.
+
+ Parameters
+ ----------
+ %(input)s
+ %(size_foot)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ median_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ See Also
+ --------
+ scipy.signal.medfilt2d
+
+ Notes
+ -----
+ For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes
+ the specialised function `scipy.signal.medfilt2d` may be faster. It is
+ however limited to constant mode with ``cval=0``.
+
+ The filter always returns the argument that would appear at index ``n // 2`` in
+ a sorted array, where ``n`` is the number of elements in the footprint of the
+ filter. Note that this differs from the conventional definition of the median
+ when ``n`` is even. Also, this function does not support the ``float16`` dtype,
+ behavior in the presence of NaNs is undefined, and memory consumption scales with
+ ``n**4``. For ``float16`` support, greater control over the definition of the
+ filter, and to limit memory usage, consider using `vectorized_filter` with
+ NumPy functions `np.median` or `np.nanmedian`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.median_filter(ascent, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ return _rank_filter(input, 0, size, footprint, output, mode, cval,
+ origin, 'median', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def percentile_filter(input, percentile, size=None, footprint=None,
+ output=None, mode="reflect", cval=0.0, origin=0, *,
+ axes=None):
+ """Calculate a multidimensional percentile filter.
+
+ Parameters
+ ----------
+ %(input)s
+ percentile : scalar
+ The percentile parameter may be less than zero, i.e.,
+ percentile = -20 equals percentile = 80
+ %(size_foot)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin_multiple)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size`, `origin`, and/or `mode`
+ must match the length of `axes`. The ith entry in any of these tuples
+ corresponds to the ith entry in `axes`.
+
+ Returns
+ -------
+ percentile_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.percentile_filter(ascent, percentile=20, size=20)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result)
+ >>> plt.show()
+ """
+ return _rank_filter(input, percentile, size, footprint, output, mode,
+ cval, origin, 'percentile', axes=axes)
+
+
+@_ni_docstrings.docfiller
+def generic_filter1d(input, function, filter_size, axis=-1,
+ output=None, mode="reflect", cval=0.0, origin=0,
+ extra_arguments=(), extra_keywords=None):
+ """Calculate a 1-D filter along the given axis.
+
+ `generic_filter1d` iterates over the lines of the array, calling the
+ given function at each line. The arguments of the line are the
+ input line, and the output line. The input and output lines are 1-D
+ double arrays. The input line is extended appropriately according
+ to the filter size and origin. The output line must be modified
+ in-place with the result.
+
+ Parameters
+ ----------
+ %(input)s
+ function : {callable, scipy.LowLevelCallable}
+ Function to apply along given axis.
+ filter_size : scalar
+ Length of the filter.
+ %(axis)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin)s
+ %(extra_arguments)s
+ %(extra_keywords)s
+
+ Returns
+ -------
+ generic_filter1d : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ Notes
+ -----
+ This function also accepts low-level callback functions with one of
+ the following signatures and wrapped in `scipy.LowLevelCallable`:
+
+ .. code:: c
+
+ int function(double *input_line, npy_intp input_length,
+ double *output_line, npy_intp output_length,
+ void *user_data)
+ int function(double *input_line, intptr_t input_length,
+ double *output_line, intptr_t output_length,
+ void *user_data)
+
+ The calling function iterates over the lines of the input and output
+ arrays, calling the callback function at each line. The current line
+ is extended according to the border conditions set by the calling
+ function, and the result is copied into the array that is passed
+ through ``input_line``. The length of the input line (after extension)
+ is passed through ``input_length``. The callback function should apply
+ the filter and store the result in the array passed through
+ ``output_line``. The length of the output line is passed through
+ ``output_length``. ``user_data`` is the data pointer provided
+ to `scipy.LowLevelCallable` as-is.
+
+ The callback function must return an integer error status that is zero
+ if something went wrong and one otherwise. If an error occurs, you should
+ normally set the python error status with an informative message
+ before returning, otherwise a default error message is set by the
+ calling function.
+
+ In addition, some other low-level function pointer specifications
+ are accepted, but these are for backward compatibility only and should
+ not be used in new code.
+
+ """
+ if extra_keywords is None:
+ extra_keywords = {}
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ output = _ni_support._get_output(output, input)
+ if filter_size < 1:
+ raise RuntimeError('invalid filter size')
+ axis = normalize_axis_index(axis, input.ndim)
+ if (filter_size // 2 + origin < 0) or (filter_size // 2 + origin >=
+ filter_size):
+ raise ValueError('invalid origin')
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.generic_filter1d(input, function, filter_size, axis, output,
+ mode, cval, origin, extra_arguments,
+ extra_keywords)
+ return output
+
+
+@_ni_docstrings.docfiller
+def generic_filter(input, function, size=None, footprint=None,
+ output=None, mode="reflect", cval=0.0, origin=0,
+ extra_arguments=(), extra_keywords=None, *, axes=None):
+ """Calculate a multidimensional filter using the given function.
+
+ At each element the provided function is called. The input values
+ within the filter footprint at that element are passed to the function
+ as a 1-D array of double values.
+
+ Parameters
+ ----------
+ %(input)s
+ function : {callable, scipy.LowLevelCallable}
+ Function to apply at each element.
+ %(size_foot)s
+ %(output)s
+ %(mode_reflect)s
+ %(cval)s
+ %(origin_multiple)s
+ %(extra_arguments)s
+ %(extra_keywords)s
+ axes : tuple of int or None, optional
+ If None, `input` is filtered along all axes. Otherwise,
+ `input` is filtered along the specified axes. When `axes` is
+ specified, any tuples used for `size` or `origin` must match the length
+ of `axes`. The ith entry in any of these tuples corresponds to the ith
+ entry in `axes`.
+
+ Returns
+ -------
+ output : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ See Also
+ --------
+ vectorized_filter : similar functionality, but optimized for vectorized callables
+
+ Notes
+ -----
+ This function is ideal for use with instances of `scipy.LowLevelCallable`;
+ for vectorized, pure-Python callables, consider `vectorized_filter` for improved
+ performance.
+
+ Low-level callback functions must have one of the following signatures:
+
+ .. code:: c
+
+ int callback(double *buffer, npy_intp filter_size,
+ double *return_value, void *user_data)
+ int callback(double *buffer, intptr_t filter_size,
+ double *return_value, void *user_data)
+
+ The calling function iterates over the elements of the input and
+ output arrays, calling the callback function at each element. The
+ elements within the footprint of the filter at the current element are
+ passed through the ``buffer`` parameter, and the number of elements
+ within the footprint through ``filter_size``. The calculated value is
+ returned in ``return_value``. ``user_data`` is the data pointer provided
+ to `scipy.LowLevelCallable` as-is.
+
+ The callback function must return an integer error status that is zero
+ if something went wrong and one otherwise. If an error occurs, you should
+ normally set the python error status with an informative message
+ before returning, otherwise a default error message is set by the
+ calling function.
+
+ In addition, some other low-level function pointer specifications
+ are accepted, but these are for backward compatibility only and should
+ not be used in new code.
+
+ Examples
+ --------
+ Import the necessary modules and load the example image used for
+ filtering.
+
+ >>> import numpy as np
+ >>> from scipy import datasets
+ >>> from scipy.ndimage import zoom, generic_filter
+ >>> import matplotlib.pyplot as plt
+ >>> ascent = zoom(datasets.ascent(), 0.5)
+
+ Compute a maximum filter with kernel size 5 by passing a simple NumPy
+ aggregation function as argument to `function`.
+
+ >>> maximum_filter_result = generic_filter(ascent, np.amax, [5, 5])
+
+ While a maximum filter could also directly be obtained using
+ `maximum_filter`, `generic_filter` allows generic Python function or
+ `scipy.LowLevelCallable` to be used as a filter. Here, we compute the
+ range between maximum and minimum value as an example for a kernel size
+ of 5.
+
+ >>> def custom_filter(image):
+ ... return np.amax(image) - np.amin(image)
+ >>> custom_filter_result = generic_filter(ascent, custom_filter, [5, 5])
+
+ Plot the original and filtered images.
+
+ >>> fig, axes = plt.subplots(3, 1, figsize=(3, 9))
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> top, middle, bottom = axes
+ >>> for ax in axes:
+ ... ax.set_axis_off() # remove coordinate system
+ >>> top.imshow(ascent)
+ >>> top.set_title("Original image")
+ >>> middle.imshow(maximum_filter_result)
+ >>> middle.set_title("Maximum filter, Kernel: 5x5")
+ >>> bottom.imshow(custom_filter_result)
+ >>> bottom.set_title("Custom filter, Kernel: 5x5")
+ >>> fig.tight_layout()
+
+ """
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=2)
+ if extra_keywords is None:
+ extra_keywords = {}
+ input = np.asarray(input)
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if footprint is None:
+ if size is None:
+ raise RuntimeError("no footprint or filter size provided")
+ sizes = _ni_support._normalize_sequence(size, num_axes)
+ footprint = np.ones(sizes, dtype=bool)
+ else:
+ footprint = np.asarray(footprint, dtype=bool)
+
+ # expand origins, footprint if num_axes < input.ndim
+ footprint = _expand_footprint(input.ndim, axes, footprint)
+ origins = _expand_origin(input.ndim, axes, origin)
+
+ fshape = [ii for ii in footprint.shape if ii > 0]
+ if len(fshape) != input.ndim:
+ raise RuntimeError(f"footprint.ndim ({footprint.ndim}) "
+ f"must match len(axes) ({num_axes})")
+ for origin, lenf in zip(origins, fshape):
+ if (lenf // 2 + origin < 0) or (lenf // 2 + origin >= lenf):
+ raise ValueError('invalid origin')
+ if not footprint.flags.contiguous:
+ footprint = footprint.copy()
+ output = _ni_support._get_output(output, input)
+
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.generic_filter(input, function, footprint, output, mode,
+ cval, origins, extra_arguments, extra_keywords)
+ return output
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_fourier.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..bb5ffa6b9287cb740611aefba5f1f322011518cf
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_fourier.py
@@ -0,0 +1,306 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import numpy as np
+from scipy._lib._util import normalize_axis_index
+from . import _ni_support
+from . import _nd_image
+
+__all__ = ['fourier_gaussian', 'fourier_uniform', 'fourier_ellipsoid',
+ 'fourier_shift']
+
+
+def _get_output_fourier(output, input):
+ if output is None:
+ if input.dtype.type in [np.complex64, np.complex128, np.float32]:
+ output = np.zeros(input.shape, dtype=input.dtype)
+ else:
+ output = np.zeros(input.shape, dtype=np.float64)
+ elif type(output) is type:
+ if output not in [np.complex64, np.complex128,
+ np.float32, np.float64]:
+ raise RuntimeError("output type not supported")
+ output = np.zeros(input.shape, dtype=output)
+ elif output.shape != input.shape:
+ raise RuntimeError("output shape not correct")
+ return output
+
+
+def _get_output_fourier_complex(output, input):
+ if output is None:
+ if input.dtype.type in [np.complex64, np.complex128]:
+ output = np.zeros(input.shape, dtype=input.dtype)
+ else:
+ output = np.zeros(input.shape, dtype=np.complex128)
+ elif type(output) is type:
+ if output not in [np.complex64, np.complex128]:
+ raise RuntimeError("output type not supported")
+ output = np.zeros(input.shape, dtype=output)
+ elif output.shape != input.shape:
+ raise RuntimeError("output shape not correct")
+ return output
+
+
+def fourier_gaussian(input, sigma, n=-1, axis=-1, output=None):
+ """
+ Multidimensional Gaussian fourier filter.
+
+ The array is multiplied with the fourier transform of a Gaussian
+ kernel.
+
+ Parameters
+ ----------
+ input : array_like
+ The input array.
+ sigma : float or sequence
+ The sigma of the Gaussian kernel. If a float, `sigma` is the same for
+ all axes. If a sequence, `sigma` has to contain one value for each
+ axis.
+ n : int, optional
+ If `n` is negative (default), then the input is assumed to be the
+ result of a complex fft.
+ If `n` is larger than or equal to zero, the input is assumed to be the
+ result of a real fft, and `n` gives the length of the array before
+ transformation along the real transform direction.
+ axis : int, optional
+ The axis of the real transform.
+ output : ndarray, optional
+ If given, the result of filtering the input is placed in this array.
+
+ Returns
+ -------
+ fourier_gaussian : ndarray
+ The filtered input.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import numpy.fft
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ascent = datasets.ascent()
+ >>> input_ = numpy.fft.fft2(ascent)
+ >>> result = ndimage.fourier_gaussian(input_, sigma=4)
+ >>> result = numpy.fft.ifft2(result)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+ output = _get_output_fourier(output, input)
+ axis = normalize_axis_index(axis, input.ndim)
+ sigmas = _ni_support._normalize_sequence(sigma, input.ndim)
+ sigmas = np.asarray(sigmas, dtype=np.float64)
+ if not sigmas.flags.contiguous:
+ sigmas = sigmas.copy()
+
+ _nd_image.fourier_filter(input, sigmas, n, axis, output, 0)
+ return output
+
+
+def fourier_uniform(input, size, n=-1, axis=-1, output=None):
+ """
+ Multidimensional uniform fourier filter.
+
+ The array is multiplied with the Fourier transform of a box of given
+ size.
+
+ Parameters
+ ----------
+ input : array_like
+ The input array.
+ size : float or sequence
+ The size of the box used for filtering.
+ If a float, `size` is the same for all axes. If a sequence, `size` has
+ to contain one value for each axis.
+ n : int, optional
+ If `n` is negative (default), then the input is assumed to be the
+ result of a complex fft.
+ If `n` is larger than or equal to zero, the input is assumed to be the
+ result of a real fft, and `n` gives the length of the array before
+ transformation along the real transform direction.
+ axis : int, optional
+ The axis of the real transform.
+ output : ndarray, optional
+ If given, the result of filtering the input is placed in this array.
+
+ Returns
+ -------
+ fourier_uniform : ndarray
+ The filtered input.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import numpy.fft
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ascent = datasets.ascent()
+ >>> input_ = numpy.fft.fft2(ascent)
+ >>> result = ndimage.fourier_uniform(input_, size=20)
+ >>> result = numpy.fft.ifft2(result)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+ output = _get_output_fourier(output, input)
+ axis = normalize_axis_index(axis, input.ndim)
+ sizes = _ni_support._normalize_sequence(size, input.ndim)
+ sizes = np.asarray(sizes, dtype=np.float64)
+ if not sizes.flags.contiguous:
+ sizes = sizes.copy()
+ _nd_image.fourier_filter(input, sizes, n, axis, output, 1)
+ return output
+
+
+def fourier_ellipsoid(input, size, n=-1, axis=-1, output=None):
+ """
+ Multidimensional ellipsoid Fourier filter.
+
+ The array is multiplied with the fourier transform of an ellipsoid of
+ given sizes.
+
+ Parameters
+ ----------
+ input : array_like
+ The input array.
+ size : float or sequence
+ The size of the box used for filtering.
+ If a float, `size` is the same for all axes. If a sequence, `size` has
+ to contain one value for each axis.
+ n : int, optional
+ If `n` is negative (default), then the input is assumed to be the
+ result of a complex fft.
+ If `n` is larger than or equal to zero, the input is assumed to be the
+ result of a real fft, and `n` gives the length of the array before
+ transformation along the real transform direction.
+ axis : int, optional
+ The axis of the real transform.
+ output : ndarray, optional
+ If given, the result of filtering the input is placed in this array.
+
+ Returns
+ -------
+ fourier_ellipsoid : ndarray
+ The filtered input.
+
+ Notes
+ -----
+ This function is implemented for arrays of rank 1, 2, or 3.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import numpy.fft
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ascent = datasets.ascent()
+ >>> input_ = numpy.fft.fft2(ascent)
+ >>> result = ndimage.fourier_ellipsoid(input_, size=20)
+ >>> result = numpy.fft.ifft2(result)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+ if input.ndim > 3:
+ raise NotImplementedError("Only 1d, 2d and 3d inputs are supported")
+ output = _get_output_fourier(output, input)
+ if output.size == 0:
+ # The C code has a bug that can result in a segfault with arrays
+ # that have size 0 (gh-17270), so check here.
+ return output
+ axis = normalize_axis_index(axis, input.ndim)
+ sizes = _ni_support._normalize_sequence(size, input.ndim)
+ sizes = np.asarray(sizes, dtype=np.float64)
+ if not sizes.flags.contiguous:
+ sizes = sizes.copy()
+ _nd_image.fourier_filter(input, sizes, n, axis, output, 2)
+ return output
+
+
+def fourier_shift(input, shift, n=-1, axis=-1, output=None):
+ """
+ Multidimensional Fourier shift filter.
+
+ The array is multiplied with the Fourier transform of a shift operation.
+
+ Parameters
+ ----------
+ input : array_like
+ The input array.
+ shift : float or sequence
+ The size of the box used for filtering.
+ If a float, `shift` is the same for all axes. If a sequence, `shift`
+ has to contain one value for each axis.
+ n : int, optional
+ If `n` is negative (default), then the input is assumed to be the
+ result of a complex fft.
+ If `n` is larger than or equal to zero, the input is assumed to be the
+ result of a real fft, and `n` gives the length of the array before
+ transformation along the real transform direction.
+ axis : int, optional
+ The axis of the real transform.
+ output : ndarray, optional
+ If given, the result of shifting the input is placed in this array.
+
+ Returns
+ -------
+ fourier_shift : ndarray
+ The shifted input.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy.fft
+ >>> fig, (ax1, ax2) = plt.subplots(1, 2)
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> ascent = datasets.ascent()
+ >>> input_ = numpy.fft.fft2(ascent)
+ >>> result = ndimage.fourier_shift(input_, shift=200)
+ >>> result = numpy.fft.ifft2(result)
+ >>> ax1.imshow(ascent)
+ >>> ax2.imshow(result.real) # the imaginary part is an artifact
+ >>> plt.show()
+ """
+ input = np.asarray(input)
+ output = _get_output_fourier_complex(output, input)
+ axis = normalize_axis_index(axis, input.ndim)
+ shifts = _ni_support._normalize_sequence(shift, input.ndim)
+ shifts = np.asarray(shifts, dtype=np.float64)
+ if not shifts.flags.contiguous:
+ shifts = shifts.copy()
+ _nd_image.fourier_shift(input, shifts, n, axis, output)
+ return output
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_interpolation.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..9527cdce724568b79d5e7d4e676d87eed6fddef3
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_interpolation.py
@@ -0,0 +1,1033 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import itertools
+import warnings
+
+import numpy as np
+from scipy._lib._util import normalize_axis_index
+from scipy._lib import array_api_extra as xpx
+
+from scipy import special
+from . import _ni_support
+from . import _nd_image
+from ._ni_docstrings import docfiller
+
+
+__all__ = ['spline_filter1d', 'spline_filter', 'geometric_transform',
+ 'map_coordinates', 'affine_transform', 'shift', 'zoom', 'rotate']
+
+
+@docfiller
+def spline_filter1d(input, order=3, axis=-1, output=np.float64,
+ mode='mirror'):
+ """
+ Calculate a 1-D spline filter along the given axis.
+
+ The lines of the array along the given axis are filtered by a
+ spline filter. The order of the spline must be >= 2 and <= 5.
+
+ Parameters
+ ----------
+ %(input)s
+ order : int, optional
+ The order of the spline, default is 3.
+ axis : int, optional
+ The axis along which the spline filter is applied. Default is the last
+ axis.
+ output : ndarray or dtype, optional
+ The array in which to place the output, or the dtype of the returned
+ array. Default is ``numpy.float64``.
+ %(mode_interp_mirror)s
+
+ Returns
+ -------
+ spline_filter1d : ndarray
+ The filtered input.
+
+ See Also
+ --------
+ spline_filter : Multidimensional spline filter.
+
+ Notes
+ -----
+ All of the interpolation functions in `ndimage` do spline interpolation of
+ the input image. If using B-splines of `order > 1`, the input image
+ values have to be converted to B-spline coefficients first, which is
+ done by applying this 1-D filter sequentially along all
+ axes of the input. All functions that require B-spline coefficients
+ will automatically filter their inputs, a behavior controllable with
+ the `prefilter` keyword argument. For functions that accept a `mode`
+ parameter, the result will only be correct if it matches the `mode`
+ used when filtering.
+
+ For complex-valued `input`, this function processes the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ We can filter an image using 1-D spline along the given axis:
+
+ >>> from scipy.ndimage import spline_filter1d
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> orig_img = np.eye(20) # create an image
+ >>> orig_img[10, :] = 1.0
+ >>> sp_filter_axis_0 = spline_filter1d(orig_img, axis=0)
+ >>> sp_filter_axis_1 = spline_filter1d(orig_img, axis=1)
+ >>> f, ax = plt.subplots(1, 3, sharex=True)
+ >>> for ind, data in enumerate([[orig_img, "original image"],
+ ... [sp_filter_axis_0, "spline filter (axis=0)"],
+ ... [sp_filter_axis_1, "spline filter (axis=1)"]]):
+ ... ax[ind].imshow(data[0], cmap='gray_r')
+ ... ax[ind].set_title(data[1])
+ >>> plt.tight_layout()
+ >>> plt.show()
+
+ """
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input,
+ complex_output=complex_output)
+ if complex_output:
+ spline_filter1d(input.real, order, axis, output.real, mode)
+ spline_filter1d(input.imag, order, axis, output.imag, mode)
+ return output
+ if order in [0, 1]:
+ output[...] = np.array(input)
+ else:
+ mode = _ni_support._extend_mode_to_code(mode)
+ axis = normalize_axis_index(axis, input.ndim)
+ _nd_image.spline_filter1d(input, order, axis, output, mode)
+ return output
+
+@docfiller
+def spline_filter(input, order=3, output=np.float64, mode='mirror'):
+ """
+ Multidimensional spline filter.
+
+ Parameters
+ ----------
+ %(input)s
+ order : int, optional
+ The order of the spline, default is 3.
+ output : ndarray or dtype, optional
+ The array in which to place the output, or the dtype of the returned
+ array. Default is ``numpy.float64``.
+ %(mode_interp_mirror)s
+
+ Returns
+ -------
+ spline_filter : ndarray
+ Filtered array. Has the same shape as `input`.
+
+ See Also
+ --------
+ spline_filter1d : Calculate a 1-D spline filter along the given axis.
+
+ Notes
+ -----
+ The multidimensional filter is implemented as a sequence of
+ 1-D spline filters. The intermediate arrays are stored
+ in the same data type as the output. Therefore, for output types
+ with a limited precision, the results may be imprecise because
+ intermediate results may be stored with insufficient precision.
+
+ For complex-valued `input`, this function processes the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ We can filter an image using multidimensional splines:
+
+ >>> from scipy.ndimage import spline_filter
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> orig_img = np.eye(20) # create an image
+ >>> orig_img[10, :] = 1.0
+ >>> sp_filter = spline_filter(orig_img, order=3)
+ >>> f, ax = plt.subplots(1, 2, sharex=True)
+ >>> for ind, data in enumerate([[orig_img, "original image"],
+ ... [sp_filter, "spline filter"]]):
+ ... ax[ind].imshow(data[0], cmap='gray_r')
+ ... ax[ind].set_title(data[1])
+ >>> plt.tight_layout()
+ >>> plt.show()
+
+ """
+ if order < 2 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input,
+ complex_output=complex_output)
+ if complex_output:
+ spline_filter(input.real, order, output.real, mode)
+ spline_filter(input.imag, order, output.imag, mode)
+ return output
+ if order not in [0, 1] and input.ndim > 0:
+ for axis in range(input.ndim):
+ spline_filter1d(input, order, axis, output=output, mode=mode)
+ input = output
+ else:
+ output[...] = input[...]
+ return output
+
+
+def _prepad_for_spline_filter(input, mode, cval):
+ if mode in ['nearest', 'grid-constant']:
+ npad = 12
+ if mode == 'grid-constant':
+ padded = np.pad(input, npad, mode='constant',
+ constant_values=cval)
+ elif mode == 'nearest':
+ padded = np.pad(input, npad, mode='edge')
+ else:
+ # other modes have exact boundary conditions implemented so
+ # no prepadding is needed
+ npad = 0
+ padded = input
+ return padded, npad
+
+
+@docfiller
+def geometric_transform(input, mapping, output_shape=None,
+ output=None, order=3,
+ mode='constant', cval=0.0, prefilter=True,
+ extra_arguments=(), extra_keywords=None):
+ """
+ Apply an arbitrary geometric transform.
+
+ The given mapping function is used to find, for each point in the
+ output, the corresponding coordinates in the input. The value of the
+ input at those coordinates is determined by spline interpolation of
+ the requested order.
+
+ Parameters
+ ----------
+ %(input)s
+ mapping : {callable, scipy.LowLevelCallable}
+ A callable object that accepts a tuple of length equal to the output
+ array rank, and returns the corresponding input coordinates as a tuple
+ of length equal to the input array rank.
+ output_shape : tuple of ints, optional
+ Shape tuple.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+ extra_arguments : tuple, optional
+ Extra arguments passed to `mapping`.
+ extra_keywords : dict, optional
+ Extra keywords passed to `mapping`.
+
+ Returns
+ -------
+ output : ndarray
+ The filtered input.
+
+ See Also
+ --------
+ map_coordinates, affine_transform, spline_filter1d
+
+
+ Notes
+ -----
+ This function also accepts low-level callback functions with one
+ the following signatures and wrapped in `scipy.LowLevelCallable`:
+
+ .. code:: c
+
+ int mapping(npy_intp *output_coordinates, double *input_coordinates,
+ int output_rank, int input_rank, void *user_data)
+ int mapping(intptr_t *output_coordinates, double *input_coordinates,
+ int output_rank, int input_rank, void *user_data)
+
+ The calling function iterates over the elements of the output array,
+ calling the callback function at each element. The coordinates of the
+ current output element are passed through ``output_coordinates``. The
+ callback function must return the coordinates at which the input must
+ be interpolated in ``input_coordinates``. The rank of the input and
+ output arrays are given by ``input_rank`` and ``output_rank``
+ respectively. ``user_data`` is the data pointer provided
+ to `scipy.LowLevelCallable` as-is.
+
+ The callback function must return an integer error status that is zero
+ if something went wrong and one otherwise. If an error occurs, you should
+ normally set the Python error status with an informative message
+ before returning, otherwise a default error message is set by the
+ calling function.
+
+ In addition, some other low-level function pointer specifications
+ are accepted, but these are for backward compatibility only and should
+ not be used in new code.
+
+ For complex-valued `input`, this function transforms the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.ndimage import geometric_transform
+ >>> a = np.arange(12.).reshape((4, 3))
+ >>> def shift_func(output_coords):
+ ... return (output_coords[0] - 0.5, output_coords[1] - 0.5)
+ ...
+ >>> geometric_transform(a, shift_func)
+ array([[ 0. , 0. , 0. ],
+ [ 0. , 1.362, 2.738],
+ [ 0. , 4.812, 6.187],
+ [ 0. , 8.263, 9.637]])
+
+ >>> b = [1, 2, 3, 4, 5]
+ >>> def shift_func(output_coords):
+ ... return (output_coords[0] - 3,)
+ ...
+ >>> geometric_transform(b, shift_func, mode='constant')
+ array([0, 0, 0, 1, 2])
+ >>> geometric_transform(b, shift_func, mode='nearest')
+ array([1, 1, 1, 1, 2])
+ >>> geometric_transform(b, shift_func, mode='reflect')
+ array([3, 2, 1, 1, 2])
+ >>> geometric_transform(b, shift_func, mode='wrap')
+ array([2, 3, 4, 1, 2])
+
+ """
+ if extra_keywords is None:
+ extra_keywords = {}
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ if output_shape is None:
+ output_shape = input.shape
+ if input.ndim < 1 or len(output_shape) < 1:
+ raise RuntimeError('input and output rank must be > 0')
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input, shape=output_shape,
+ complex_output=complex_output)
+ if complex_output:
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter,
+ output_shape=output_shape,
+ extra_arguments=extra_arguments,
+ extra_keywords=extra_keywords)
+ geometric_transform(input.real, mapping, output=output.real,
+ cval=np.real(cval), **kwargs)
+ geometric_transform(input.imag, mapping, output=output.imag,
+ cval=np.imag(cval), **kwargs)
+ return output
+
+ if prefilter and order > 1:
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
+ filtered = spline_filter(padded, order, output=np.float64,
+ mode=mode)
+ else:
+ npad = 0
+ filtered = input
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.geometric_transform(filtered, mapping, None, None, None, output,
+ order, mode, cval, npad, extra_arguments,
+ extra_keywords)
+ return output
+
+
+@docfiller
+def map_coordinates(input, coordinates, output=None, order=3,
+ mode='constant', cval=0.0, prefilter=True):
+ """
+ Map the input array to new coordinates by interpolation.
+
+ The array of coordinates is used to find, for each point in the output,
+ the corresponding coordinates in the input. The value of the input at
+ those coordinates is determined by spline interpolation of the
+ requested order.
+
+ The shape of the output is derived from that of the coordinate
+ array by dropping the first axis. The values of the array along
+ the first axis are the coordinates in the input array at which the
+ output value is found.
+
+ Parameters
+ ----------
+ %(input)s
+ coordinates : array_like
+ The coordinates at which `input` is evaluated.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+
+ Returns
+ -------
+ map_coordinates : ndarray
+ The result of transforming the input. The shape of the output is
+ derived from that of `coordinates` by dropping the first axis.
+
+ See Also
+ --------
+ spline_filter, geometric_transform, scipy.interpolate
+
+ Notes
+ -----
+ For complex-valued `input`, this function maps the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.arange(12.).reshape((4, 3))
+ >>> a
+ array([[ 0., 1., 2.],
+ [ 3., 4., 5.],
+ [ 6., 7., 8.],
+ [ 9., 10., 11.]])
+ >>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1)
+ array([ 2., 7.])
+
+ Above, the interpolated value of a[0.5, 0.5] gives output[0], while
+ a[2, 1] is output[1].
+
+ >>> inds = np.array([[0.5, 2], [0.5, 4]])
+ >>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3)
+ array([ 2. , -33.3])
+ >>> ndimage.map_coordinates(a, inds, order=1, mode='nearest')
+ array([ 2., 8.])
+ >>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool)
+ array([ True, False], dtype=bool)
+
+ """
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ coordinates = np.asarray(coordinates)
+ if np.iscomplexobj(coordinates):
+ raise TypeError('Complex type not supported')
+ output_shape = coordinates.shape[1:]
+ if input.ndim < 1 or len(output_shape) < 1:
+ raise RuntimeError('input and output rank must be > 0')
+ if coordinates.shape[0] != input.ndim:
+ raise RuntimeError('invalid shape for coordinate array')
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input, shape=output_shape,
+ complex_output=complex_output)
+ if complex_output:
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+ map_coordinates(input.real, coordinates, output=output.real,
+ cval=np.real(cval), **kwargs)
+ map_coordinates(input.imag, coordinates, output=output.imag,
+ cval=np.imag(cval), **kwargs)
+ return output
+ if prefilter and order > 1:
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+ else:
+ npad = 0
+ filtered = input
+ mode = _ni_support._extend_mode_to_code(mode)
+ _nd_image.geometric_transform(filtered, None, coordinates, None, None,
+ output, order, mode, cval, npad, None, None)
+ return output
+
+
+@docfiller
+def affine_transform(input, matrix, offset=0.0, output_shape=None,
+ output=None, order=3,
+ mode='constant', cval=0.0, prefilter=True):
+ """
+ Apply an affine transformation.
+
+ Given an output image pixel index vector ``o``, the pixel value
+ is determined from the input image at position
+ ``np.dot(matrix, o) + offset``.
+
+ This does 'pull' (or 'backward') resampling, transforming the output space
+ to the input to locate data. Affine transformations are often described in
+ the 'push' (or 'forward') direction, transforming input to output. If you
+ have a matrix for the 'push' transformation, use its inverse
+ (:func:`numpy.linalg.inv`) in this function.
+
+ Parameters
+ ----------
+ %(input)s
+ matrix : ndarray
+ The inverse coordinate transformation matrix, mapping output
+ coordinates to input coordinates. If ``ndim`` is the number of
+ dimensions of ``input``, the given matrix must have one of the
+ following shapes:
+
+ - ``(ndim, ndim)``: the linear transformation matrix for each
+ output coordinate.
+ - ``(ndim,)``: assume that the 2-D transformation matrix is
+ diagonal, with the diagonal specified by the given value. A more
+ efficient algorithm is then used that exploits the separability
+ of the problem.
+ - ``(ndim + 1, ndim + 1)``: assume that the transformation is
+ specified using homogeneous coordinates [1]_. In this case, any
+ value passed to ``offset`` is ignored.
+ - ``(ndim, ndim + 1)``: as above, but the bottom row of a
+ homogeneous transformation matrix is always ``[0, 0, ..., 1]``,
+ and may be omitted.
+
+ offset : float or sequence, optional
+ The offset into the array where the transform is applied. If a float,
+ `offset` is the same for each axis. If a sequence, `offset` should
+ contain one value for each axis.
+ output_shape : tuple of ints, optional
+ Shape tuple.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+
+ Returns
+ -------
+ affine_transform : ndarray
+ The transformed input.
+
+ Examples
+ --------
+ Use `affine_transform` to stretch an image::
+
+ >>> from scipy.ndimage import affine_transform
+ >>> from scipy.datasets import face
+ >>> from matplotlib import pyplot as plt
+ >>> import numpy as np
+ >>> im = face(gray=True)
+ >>> matrix = (0.5, 2)
+ >>> im2 = affine_transform(im, matrix)
+ >>> plt.imshow(im2)
+ >>> plt.show()
+
+ Rotate an image by 90 degrees and project it onto an expanded canvas::
+
+ >>> matrix = ((0, 1), (1, 0))
+ >>> im3 = affine_transform(im, matrix, output_shape=(1024, 1024))
+ >>> plt.imshow(im3)
+ >>> plt.show()
+
+ Offset the rotation so that the image is centred::
+
+ >>> output_shape = (1200, 1200)
+ >>> offset = (np.array(im.shape) - output_shape) / 2
+ >>> im4 = affine_transform(im, matrix, offset=offset, output_shape=output_shape)
+ >>> plt.imshow(im4)
+ >>> plt.show()
+
+ Notes
+ -----
+ The given matrix and offset are used to find for each point in the
+ output the corresponding coordinates in the input by an affine
+ transformation. The value of the input at those coordinates is
+ determined by spline interpolation of the requested order. Points
+ outside the boundaries of the input are filled according to the given
+ mode.
+
+ .. versionchanged:: 0.18.0
+ Previously, the exact interpretation of the affine transformation
+ depended on whether the matrix was supplied as a 1-D or a
+ 2-D array. If a 1-D array was supplied
+ to the matrix parameter, the output pixel value at index ``o``
+ was determined from the input image at position
+ ``matrix * (o + offset)``.
+
+ For complex-valued `input`, this function transforms the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Homogeneous_coordinates
+ """
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ if output_shape is None:
+ if isinstance(output, np.ndarray):
+ output_shape = output.shape
+ else:
+ output_shape = input.shape
+ if input.ndim < 1 or len(output_shape) < 1:
+ raise RuntimeError('input and output rank must be > 0')
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input, shape=output_shape,
+ complex_output=complex_output)
+ if complex_output:
+ kwargs = dict(offset=offset, output_shape=output_shape, order=order,
+ mode=mode, prefilter=prefilter)
+ affine_transform(input.real, matrix, output=output.real,
+ cval=np.real(cval), **kwargs)
+ affine_transform(input.imag, matrix, output=output.imag,
+ cval=np.imag(cval), **kwargs)
+ return output
+ if prefilter and order > 1:
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+ else:
+ npad = 0
+ filtered = input
+ mode = _ni_support._extend_mode_to_code(mode)
+ matrix = np.asarray(matrix, dtype=np.float64)
+ if matrix.ndim not in [1, 2] or matrix.shape[0] < 1:
+ raise RuntimeError('no proper affine matrix provided')
+ if (matrix.ndim == 2 and matrix.shape[1] == input.ndim + 1 and
+ (matrix.shape[0] in [input.ndim, input.ndim + 1])):
+ if matrix.shape[0] == input.ndim + 1:
+ exptd = [0] * input.ndim + [1]
+ if not np.all(matrix[input.ndim] == exptd):
+ msg = (f'Expected homogeneous transformation matrix with '
+ f'shape {matrix.shape} for image shape {input.shape}, '
+ f'but bottom row was not equal to {exptd}')
+ raise ValueError(msg)
+ # assume input is homogeneous coordinate transformation matrix
+ offset = matrix[:input.ndim, input.ndim]
+ matrix = matrix[:input.ndim, :input.ndim]
+ if matrix.shape[0] != input.ndim:
+ raise RuntimeError('affine matrix has wrong number of rows')
+ if matrix.ndim == 2 and matrix.shape[1] != output.ndim:
+ raise RuntimeError('affine matrix has wrong number of columns')
+ if not matrix.flags.contiguous:
+ matrix = matrix.copy()
+ offset = _ni_support._normalize_sequence(offset, input.ndim)
+ offset = np.asarray(offset, dtype=np.float64)
+ if offset.ndim != 1 or offset.shape[0] < 1:
+ raise RuntimeError('no proper offset provided')
+ if not offset.flags.contiguous:
+ offset = offset.copy()
+ if matrix.ndim == 1:
+ _nd_image.zoom_shift(filtered, matrix, offset/matrix, output, order,
+ mode, cval, npad, False)
+ else:
+ _nd_image.geometric_transform(filtered, None, None, matrix, offset,
+ output, order, mode, cval, npad, None,
+ None)
+ return output
+
+
+@docfiller
+def shift(input, shift, output=None, order=3, mode='constant', cval=0.0,
+ prefilter=True):
+ """
+ Shift an array.
+
+ The array is shifted using spline interpolation of the requested order.
+ Points outside the boundaries of the input are filled according to the
+ given mode.
+
+ Parameters
+ ----------
+ %(input)s
+ shift : float or sequence
+ The shift along the axes. If a float, `shift` is the same for each
+ axis. If a sequence, `shift` should contain one value for each axis.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+
+ Returns
+ -------
+ shift : ndarray
+ The shifted input.
+
+ See Also
+ --------
+ affine_transform : Affine transformations
+
+ Notes
+ -----
+ For complex-valued `input`, this function shifts the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ Import the necessary modules and an exemplary image.
+
+ >>> from scipy.ndimage import shift
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy import datasets
+ >>> image = datasets.ascent()
+
+ Shift the image vertically by 20 pixels.
+
+ >>> image_shifted_vertically = shift(image, (20, 0))
+
+ Shift the image vertically by -200 pixels and horizontally by 100 pixels.
+
+ >>> image_shifted_both_directions = shift(image, (-200, 100))
+
+ Plot the original and the shifted images.
+
+ >>> fig, axes = plt.subplots(3, 1, figsize=(4, 12))
+ >>> plt.gray() # show the filtered result in grayscale
+ >>> top, middle, bottom = axes
+ >>> for ax in axes:
+ ... ax.set_axis_off() # remove coordinate system
+ >>> top.imshow(image)
+ >>> top.set_title("Original image")
+ >>> middle.imshow(image_shifted_vertically)
+ >>> middle.set_title("Vertically shifted image")
+ >>> bottom.imshow(image_shifted_both_directions)
+ >>> bottom.set_title("Image shifted in both directions")
+ >>> fig.tight_layout()
+ """
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ if input.ndim < 1:
+ raise RuntimeError('input and output rank must be > 0')
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input, complex_output=complex_output)
+ if complex_output:
+ # import under different name to avoid confusion with shift parameter
+ from scipy.ndimage._interpolation import shift as _shift
+
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+ _shift(input.real, shift, output=output.real, cval=np.real(cval), **kwargs)
+ _shift(input.imag, shift, output=output.imag, cval=np.imag(cval), **kwargs)
+ return output
+ if prefilter and order > 1:
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+ else:
+ npad = 0
+ filtered = input
+ mode = _ni_support._extend_mode_to_code(mode)
+ shift = _ni_support._normalize_sequence(shift, input.ndim)
+ shift = [-ii for ii in shift]
+ shift = np.asarray(shift, dtype=np.float64)
+ if not shift.flags.contiguous:
+ shift = shift.copy()
+ _nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval,
+ npad, False)
+ return output
+
+
+@docfiller
+def zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0,
+ prefilter=True, *, grid_mode=False):
+ """
+ Zoom an array.
+
+ The array is zoomed using spline interpolation of the requested order.
+
+ Parameters
+ ----------
+ %(input)s
+ zoom : float or sequence
+ The zoom factor along the axes. If a float, `zoom` is the same for each
+ axis. If a sequence, `zoom` should contain one value for each axis.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+ grid_mode : bool, optional
+ If False, the distance from the pixel centers is zoomed. Otherwise, the
+ distance including the full pixel extent is used. For example, a 1d
+ signal of length 5 is considered to have length 4 when `grid_mode` is
+ False, but length 5 when `grid_mode` is True. See the following
+ visual illustration:
+
+ .. code-block:: text
+
+ | pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 |
+ |<-------------------------------------->|
+ vs.
+ |<----------------------------------------------->|
+
+ The starting point of the arrow in the diagram above corresponds to
+ coordinate location 0 in each mode.
+
+ Returns
+ -------
+ zoom : ndarray
+ The zoomed input.
+
+ Notes
+ -----
+ For complex-valued `input`, this function zooms the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+
+ >>> fig = plt.figure()
+ >>> ax1 = fig.add_subplot(121) # left side
+ >>> ax2 = fig.add_subplot(122) # right side
+ >>> ascent = datasets.ascent()
+ >>> result = ndimage.zoom(ascent, 3.0)
+ >>> ax1.imshow(ascent, vmin=0, vmax=255)
+ >>> ax2.imshow(result, vmin=0, vmax=255)
+ >>> plt.show()
+
+ >>> print(ascent.shape)
+ (512, 512)
+
+ >>> print(result.shape)
+ (1536, 1536)
+ """
+ if order < 0 or order > 5:
+ raise RuntimeError('spline order not supported')
+ input = np.asarray(input)
+ if input.ndim < 1:
+ raise RuntimeError('input and output rank must be > 0')
+ zoom = _ni_support._normalize_sequence(zoom, input.ndim)
+ output_shape = tuple(
+ [int(round(ii * jj)) for ii, jj in zip(input.shape, zoom)])
+ complex_output = np.iscomplexobj(input)
+ output = _ni_support._get_output(output, input, shape=output_shape,
+ complex_output=complex_output)
+ if all(z == 1 for z in zoom) and prefilter: # early exit for gh-20999
+ # zoom 1 means "return original image". If `prefilter=False`,
+ # `input` is *not* the original image; processing is still needed
+ # to undo the filter. So we only early exit if `prefilter`.
+ output = xpx.at(output)[...].set(input)
+ return output
+ if complex_output:
+ # import under different name to avoid confusion with zoom parameter
+ from scipy.ndimage._interpolation import zoom as _zoom
+
+ kwargs = dict(order=order, mode=mode, prefilter=prefilter)
+ _zoom(input.real, zoom, output=output.real, cval=np.real(cval), **kwargs)
+ _zoom(input.imag, zoom, output=output.imag, cval=np.imag(cval), **kwargs)
+ return output
+ if prefilter and order > 1:
+ padded, npad = _prepad_for_spline_filter(input, mode, cval)
+ filtered = spline_filter(padded, order, output=np.float64, mode=mode)
+ else:
+ npad = 0
+ filtered = input
+ if grid_mode:
+ # warn about modes that may have surprising behavior
+ suggest_mode = None
+ if mode == 'constant':
+ suggest_mode = 'grid-constant'
+ elif mode == 'wrap':
+ suggest_mode = 'grid-wrap'
+ if suggest_mode is not None:
+ warnings.warn(
+ (f"It is recommended to use mode = {suggest_mode} instead of {mode} "
+ f"when grid_mode is True."),
+ stacklevel=2
+ )
+ mode = _ni_support._extend_mode_to_code(mode)
+
+ zoom_div = np.array(output_shape)
+ zoom_nominator = np.array(input.shape)
+ if not grid_mode:
+ zoom_div -= 1
+ zoom_nominator -= 1
+
+ # Zooming to infinite values is unpredictable, so just choose
+ # zoom factor 1 instead
+ zoom = np.divide(zoom_nominator, zoom_div,
+ out=np.ones_like(input.shape, dtype=np.float64),
+ where=zoom_div != 0)
+ zoom = np.ascontiguousarray(zoom)
+ _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval, npad,
+ grid_mode)
+ return output
+
+
+@docfiller
+def rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=3,
+ mode='constant', cval=0.0, prefilter=True):
+ """
+ Rotate an array.
+
+ The array is rotated in the plane defined by the two axes given by the
+ `axes` parameter using spline interpolation of the requested order.
+
+ Parameters
+ ----------
+ %(input)s
+ angle : float
+ The rotation angle in degrees.
+ axes : tuple of 2 ints, optional
+ The two axes that define the plane of rotation. Default is the first
+ two axes.
+ reshape : bool, optional
+ If `reshape` is true, the output shape is adapted so that the input
+ array is contained completely in the output. Default is True.
+ %(output)s
+ order : int, optional
+ The order of the spline interpolation, default is 3.
+ The order has to be in the range 0-5.
+ %(mode_interp_constant)s
+ %(cval)s
+ %(prefilter)s
+
+ Returns
+ -------
+ rotate : ndarray
+ The rotated input.
+
+ Notes
+ -----
+ For complex-valued `input`, this function rotates the real and imaginary
+ components independently.
+
+ .. versionadded:: 1.6.0
+ Complex-valued support added.
+
+ Examples
+ --------
+ >>> from scipy import ndimage, datasets
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure(figsize=(10, 3))
+ >>> ax1, ax2, ax3 = fig.subplots(1, 3)
+ >>> img = datasets.ascent()
+ >>> img_45 = ndimage.rotate(img, 45, reshape=False)
+ >>> full_img_45 = ndimage.rotate(img, 45, reshape=True)
+ >>> ax1.imshow(img, cmap='gray')
+ >>> ax1.set_axis_off()
+ >>> ax2.imshow(img_45, cmap='gray')
+ >>> ax2.set_axis_off()
+ >>> ax3.imshow(full_img_45, cmap='gray')
+ >>> ax3.set_axis_off()
+ >>> fig.set_layout_engine('tight')
+ >>> plt.show()
+ >>> print(img.shape)
+ (512, 512)
+ >>> print(img_45.shape)
+ (512, 512)
+ >>> print(full_img_45.shape)
+ (724, 724)
+
+ """
+ input_arr = np.asarray(input)
+ ndim = input_arr.ndim
+
+ if ndim < 2:
+ raise ValueError('input array should be at least 2D')
+
+ axes = list(axes)
+
+ if len(axes) != 2:
+ raise ValueError('axes should contain exactly two values')
+
+ if not all([float(ax).is_integer() for ax in axes]):
+ raise ValueError('axes should contain only integer values')
+
+ if axes[0] < 0:
+ axes[0] += ndim
+ if axes[1] < 0:
+ axes[1] += ndim
+ if axes[0] < 0 or axes[1] < 0 or axes[0] >= ndim or axes[1] >= ndim:
+ raise ValueError('invalid rotation plane specified')
+
+ axes.sort()
+
+ c, s = special.cosdg(angle), special.sindg(angle)
+
+ rot_matrix = np.array([[c, s],
+ [-s, c]])
+
+ img_shape = np.asarray(input_arr.shape)
+ in_plane_shape = img_shape[axes]
+ if reshape:
+ # Compute transformed input bounds
+ iy, ix = in_plane_shape
+ out_bounds = rot_matrix @ [[0, 0, iy, iy],
+ [0, ix, 0, ix]]
+ # Compute the shape of the transformed input plane
+ out_plane_shape = (np.ptp(out_bounds, axis=1) + 0.5).astype(int)
+ else:
+ out_plane_shape = img_shape[axes]
+
+ out_center = rot_matrix @ ((out_plane_shape - 1) / 2)
+ in_center = (in_plane_shape - 1) / 2
+ offset = in_center - out_center
+
+ output_shape = img_shape
+ output_shape[axes] = out_plane_shape
+ output_shape = tuple(output_shape)
+
+ complex_output = np.iscomplexobj(input_arr)
+ output = _ni_support._get_output(output, input_arr, shape=output_shape,
+ complex_output=complex_output)
+
+ if ndim <= 2:
+ affine_transform(input_arr, rot_matrix, offset, output_shape, output,
+ order, mode, cval, prefilter)
+ else:
+ # If ndim > 2, the rotation is applied over all the planes
+ # parallel to axes
+ planes_coord = itertools.product(
+ *[[slice(None)] if ax in axes else range(img_shape[ax])
+ for ax in range(ndim)])
+
+ out_plane_shape = tuple(out_plane_shape)
+
+ for coordinates in planes_coord:
+ ia = input_arr[coordinates]
+ oa = output[coordinates]
+ affine_transform(ia, rot_matrix, offset, out_plane_shape,
+ oa, order, mode, cval, prefilter)
+
+ return output
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_measurements.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..798c9b1f3070d1c42164f5ff8b20e93e2c9149bc
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_measurements.py
@@ -0,0 +1,1689 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import numpy as np
+from . import _ni_support
+from . import _ni_label
+from . import _nd_image
+from . import _morphology
+
+__all__ = ['label', 'find_objects', 'labeled_comprehension', 'sum', 'mean',
+ 'variance', 'standard_deviation', 'minimum', 'maximum', 'median',
+ 'minimum_position', 'maximum_position', 'extrema', 'center_of_mass',
+ 'histogram', 'watershed_ift', 'sum_labels', 'value_indices']
+
+
+def label(input, structure=None, output=None):
+ """
+ Label features in an array.
+
+ Parameters
+ ----------
+ input : array_like
+ An array-like object to be labeled. Any non-zero values in `input` are
+ counted as features and zero values are considered the background.
+ structure : array_like, optional
+ A structuring element that defines feature connections.
+ `structure` must be centrosymmetric
+ (see Notes).
+ If no structuring element is provided,
+ one is automatically generated with a squared connectivity equal to
+ one. That is, for a 2-D `input` array, the default structuring element
+ is::
+
+ [[0,1,0],
+ [1,1,1],
+ [0,1,0]]
+
+ output : (None, data-type, array_like), optional
+ If `output` is a data type, it specifies the type of the resulting
+ labeled feature array.
+ If `output` is an array-like object, then `output` will be updated
+ with the labeled features from this function. This function can
+ operate in-place, by passing output=input.
+ Note that the output must be able to store the largest label, or this
+ function will raise an Exception.
+
+ Returns
+ -------
+ label : ndarray or int
+ An integer ndarray where each unique feature in `input` has a unique
+ label in the returned array.
+ num_features : int
+ How many objects were found.
+
+ If `output` is None, this function returns a tuple of
+ (`labeled_array`, `num_features`).
+
+ If `output` is 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 an element of `index` does not exist
+ in `labels`.
+ pass_positions : bool, optional
+ If True, pass linear indices to `func` as a second argument.
+ Default is False.
+
+ Returns
+ -------
+ result : ndarray
+ Result of applying `func` to each of `labels` to `input` in `index`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> from scipy import ndimage
+ >>> lbl, nlbl = ndimage.label(a)
+ >>> lbls = np.arange(1, nlbl+1)
+ >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, 0)
+ array([ 2.75, 5.5 , 6. ])
+
+ Falling back to `default`:
+
+ >>> lbls = np.arange(1, nlbl+2)
+ >>> ndimage.labeled_comprehension(a, lbl, lbls, np.mean, float, -1)
+ array([ 2.75, 5.5 , 6. , -1. ])
+
+ Passing positions:
+
+ >>> def fn(val, pos):
+ ... print("fn says: %s : %s" % (val, pos))
+ ... return (val.sum()) if (pos.sum() % 2 == 0) else (-val.sum())
+ ...
+ >>> ndimage.labeled_comprehension(a, lbl, lbls, fn, float, 0, True)
+ fn says: [1 2 5 3] : [0 1 4 5]
+ fn says: [4 7] : [ 7 11]
+ fn says: [9 3] : [12 13]
+ array([ 11., 11., -12., 0.])
+
+ """
+
+ as_scalar = np.isscalar(index)
+ input = np.asarray(input)
+
+ if pass_positions:
+ positions = np.arange(input.size).reshape(input.shape)
+
+ if labels is None:
+ if index is not None:
+ raise ValueError("index without defined labels")
+ if not pass_positions:
+ return func(input.ravel())
+ else:
+ return func(input.ravel(), positions.ravel())
+
+ labels = np.asarray(labels)
+
+ try:
+ input, labels = np.broadcast_arrays(input, labels)
+ except ValueError as e:
+ raise ValueError("input and labels must have the same shape "
+ "(excepting dimensions with width 1)") from e
+
+ if index is None:
+ if not pass_positions:
+ return func(input[labels > 0])
+ else:
+ return func(input[labels > 0], positions[labels > 0])
+
+ index = np.atleast_1d(index)
+ if np.any(index.astype(labels.dtype).astype(index.dtype) != index):
+ raise ValueError(f"Cannot convert index values from <{index.dtype}> to "
+ f"<{labels.dtype}> (labels' type) without loss of precision")
+
+ index = index.astype(labels.dtype)
+
+ # optimization: find min/max in index,
+ # and select those parts of labels, input, and positions
+ lo = index.min()
+ hi = index.max()
+ mask = (labels >= lo) & (labels <= hi)
+
+ # this also ravels the arrays
+ labels = labels[mask]
+ input = input[mask]
+ if pass_positions:
+ positions = positions[mask]
+
+ # sort everything by labels
+ label_order = labels.argsort()
+ labels = labels[label_order]
+ input = input[label_order]
+ if pass_positions:
+ positions = positions[label_order]
+
+ index_order = index.argsort()
+ sorted_index = index[index_order]
+
+ def do_map(inputs, output):
+ """labels must be sorted"""
+ nidx = sorted_index.size
+
+ # Find boundaries for each stretch of constant labels
+ # This could be faster, but we already paid N log N to sort labels.
+ lo = np.searchsorted(labels, sorted_index, side='left')
+ hi = np.searchsorted(labels, sorted_index, side='right')
+
+ for i, l, h in zip(range(nidx), lo, hi):
+ if l == h:
+ continue
+ output[i] = func(*[inp[l:h] for inp in inputs])
+
+ temp = np.empty(index.shape, out_dtype)
+ temp[:] = default
+ if not pass_positions:
+ do_map([input], temp)
+ else:
+ do_map([input, positions], temp)
+
+ output = np.zeros(index.shape, out_dtype)
+ output[index_order] = temp
+ if as_scalar:
+ output = output[0]
+
+ return output
+
+
+def _safely_castable_to_int(dt):
+ """Test whether the NumPy data type `dt` can be safely cast to an int."""
+ int_size = np.dtype(int).itemsize
+ safe = ((np.issubdtype(dt, np.signedinteger) and dt.itemsize <= int_size) or
+ (np.issubdtype(dt, np.unsignedinteger) and dt.itemsize < int_size))
+ return safe
+
+
+def _stats(input, labels=None, index=None, centered=False):
+ """Count, sum, and optionally compute (sum - centre)^2 of input by label
+
+ Parameters
+ ----------
+ input : array_like, N-D
+ The input data to be analyzed.
+ labels : array_like (N-D), optional
+ The labels of the data in `input`. This array must be broadcast
+ compatible with `input`; typically, it is the same shape as `input`.
+ If `labels` is None, all nonzero values in `input` are treated as
+ the single labeled group.
+ index : label or sequence of labels, optional
+ These are the labels of the groups for which the stats are computed.
+ If `index` is None, the stats are computed for the single group where
+ `labels` is greater than 0.
+ centered : bool, optional
+ If True, the centered sum of squares for each labeled group is
+ also returned. Default is False.
+
+ Returns
+ -------
+ counts : int or ndarray of ints
+ The number of elements in each labeled group.
+ sums : scalar or ndarray of scalars
+ The sums of the values in each labeled group.
+ sums_c : scalar or ndarray of scalars, optional
+ The sums of mean-centered squares of the values in each labeled group.
+ This is only returned if `centered` is True.
+
+ """
+ def single_group(vals):
+ if centered:
+ vals_c = vals - vals.mean()
+ return vals.size, vals.sum(), (vals_c * vals_c.conjugate()).sum()
+ else:
+ return vals.size, vals.sum()
+
+ input = np.asarray(input)
+ if labels is None:
+ return single_group(input)
+
+ labels = np.asarray(labels)
+ # ensure input and labels match sizes
+ input, labels = np.broadcast_arrays(input, labels)
+
+ if index is None:
+ return single_group(input[labels > 0])
+
+ if np.isscalar(index):
+ return single_group(input[labels == index])
+
+ def _sum_centered(labels):
+ # `labels` is expected to be an ndarray with the same shape as `input`.
+ # It must contain the label indices (which are not necessarily the labels
+ # themselves).
+ means = sums / counts
+ centered_input = input - means[labels]
+ # bincount expects 1-D inputs, so we ravel the arguments.
+ bc = np.bincount(labels.ravel(),
+ weights=(centered_input *
+ centered_input.conjugate()).ravel())
+ return bc
+
+ # Remap labels to unique integers if necessary, or if the largest
+ # label is larger than the number of values.
+
+ if (not _safely_castable_to_int(labels.dtype) or
+ labels.min() < 0 or labels.max() > labels.size):
+ # Use np.unique to generate the label indices. `new_labels` will
+ # be 1-D, but it should be interpreted as the flattened N-D array of
+ # label indices.
+ unique_labels, new_labels = np.unique(labels, return_inverse=True)
+ new_labels = np.reshape(new_labels, (-1,)) # flatten, since it may be >1-D
+ counts = np.bincount(new_labels)
+ sums = np.bincount(new_labels, weights=input.ravel())
+ if centered:
+ # Compute the sum of the mean-centered squares.
+ # We must reshape new_labels to the N-D shape of `input` before
+ # passing it _sum_centered.
+ sums_c = _sum_centered(new_labels.reshape(labels.shape))
+ idxs = np.searchsorted(unique_labels, index)
+ # make all of idxs valid
+ idxs[idxs >= unique_labels.size] = 0
+ found = (unique_labels[idxs] == index)
+ else:
+ # labels are an integer type allowed by bincount, and there aren't too
+ # many, so call bincount directly.
+ counts = np.bincount(labels.ravel())
+ sums = np.bincount(labels.ravel(), weights=input.ravel())
+ if centered:
+ sums_c = _sum_centered(labels)
+ # make sure all index values are valid
+ idxs = np.asanyarray(index, np.int_).copy()
+ found = (idxs >= 0) & (idxs < counts.size)
+ idxs[~found] = 0
+
+ counts = counts[idxs]
+ counts[~found] = 0
+ sums = sums[idxs]
+ sums[~found] = 0
+
+ if not centered:
+ return (counts, sums)
+ else:
+ sums_c = sums_c[idxs]
+ sums_c[~found] = 0
+ return (counts, sums, sums_c)
+
+
+def sum(input, labels=None, index=None):
+ """
+ Calculate the sum of the values of the array.
+
+ Notes
+ -----
+ This is an alias for `ndimage.sum_labels` kept for backwards compatibility
+ reasons, for new code please prefer `sum_labels`. See the `sum_labels`
+ docstring for more details.
+
+ """
+ return sum_labels(input, labels, index)
+
+
+def sum_labels(input, labels=None, index=None):
+ """
+ Calculate the sum of the values of the array.
+
+ Parameters
+ ----------
+ input : array_like
+ Values of `input` inside the regions defined by `labels`
+ are summed together.
+ labels : array_like of ints, optional
+ Assign labels to the values of the array. Has to have the same shape as
+ `input`.
+ index : array_like, optional
+ A single label number or a sequence of label numbers of
+ the objects to be measured.
+
+ Returns
+ -------
+ sum : ndarray or scalar
+ An array of the sums of values of `input` inside the regions defined
+ by `labels` with the same shape as `index`. If 'index' is None or scalar,
+ a scalar is returned.
+
+ See Also
+ --------
+ mean, median
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> input = [0,1,2,3]
+ >>> labels = [1,1,2,2]
+ >>> ndimage.sum_labels(input, labels, index=[1,2])
+ [1.0, 5.0]
+ >>> ndimage.sum_labels(input, labels, index=1)
+ 1
+ >>> ndimage.sum_labels(input, labels)
+ 6
+
+
+ """
+ count, sum = _stats(input, labels, index)
+ return sum
+
+
+def mean(input, labels=None, index=None):
+ """
+ Calculate the mean of the values of an array at labels.
+
+ Parameters
+ ----------
+ input : array_like
+ Array on which to compute the mean of elements over distinct
+ regions.
+ labels : array_like, optional
+ Array of labels of same shape, or broadcastable to the same shape as
+ `input`. All elements sharing the same label form one region over
+ which the mean of the elements is computed.
+ index : int or sequence of ints, optional
+ Labels of the objects over which the mean is to be computed.
+ Default is None, in which case the mean for all values where label is
+ greater than 0 is calculated.
+
+ Returns
+ -------
+ out : list
+ Sequence of same length as `index`, with the mean of the different
+ regions labeled by the labels in `index`.
+
+ See Also
+ --------
+ variance, standard_deviation, minimum, maximum, sum, label
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.arange(25).reshape((5,5))
+ >>> labels = np.zeros_like(a)
+ >>> labels[3:5,3:5] = 1
+ >>> index = np.unique(labels)
+ >>> labels
+ array([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1],
+ [0, 0, 0, 1, 1]])
+ >>> index
+ array([0, 1])
+ >>> ndimage.mean(a, labels=labels, index=index)
+ [10.285714285714286, 21.0]
+
+ """
+
+ count, sum = _stats(input, labels, index)
+ return sum / np.asanyarray(count).astype(np.float64)
+
+
+def variance(input, labels=None, index=None):
+ """
+ Calculate the variance of the values of an N-D image array, optionally at
+ specified sub-regions.
+
+ Parameters
+ ----------
+ input : array_like
+ Nd-image data to process.
+ labels : array_like, optional
+ Labels defining sub-regions in `input`.
+ If not None, must be same shape as `input`.
+ index : int or sequence of ints, optional
+ `labels` to include in output. If None (default), all values where
+ `labels` is non-zero are used.
+
+ Returns
+ -------
+ variance : float or ndarray
+ Values of variance, for each sub-region if `labels` and `index` are
+ specified.
+
+ See Also
+ --------
+ label, standard_deviation, maximum, minimum, extrema
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> from scipy import ndimage
+ >>> ndimage.variance(a)
+ 7.609375
+
+ Features to process can be specified using `labels` and `index`:
+
+ >>> lbl, nlbl = ndimage.label(a)
+ >>> ndimage.variance(a, lbl, index=np.arange(1, nlbl+1))
+ array([ 2.1875, 2.25 , 9. ])
+
+ If no index is given, all non-zero `labels` are processed:
+
+ >>> ndimage.variance(a, lbl)
+ 6.1875
+
+ """
+ count, sum, sum_c_sq = _stats(input, labels, index, centered=True)
+ return sum_c_sq / np.asanyarray(count).astype(float)
+
+
+def standard_deviation(input, labels=None, index=None):
+ """
+ Calculate the standard deviation of the values of an N-D image array,
+ optionally at specified sub-regions.
+
+ Parameters
+ ----------
+ input : array_like
+ N-D image data to process.
+ labels : array_like, optional
+ Labels to identify sub-regions in `input`.
+ If not None, must be same shape as `input`.
+ index : int or sequence of ints, optional
+ `labels` to include in output. If None (default), all values where
+ `labels` is non-zero are used.
+
+ Returns
+ -------
+ standard_deviation : float or ndarray
+ Values of standard deviation, for each sub-region if `labels` and
+ `index` are specified.
+
+ See Also
+ --------
+ label, variance, maximum, minimum, extrema
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> from scipy import ndimage
+ >>> ndimage.standard_deviation(a)
+ 2.7585095613392387
+
+ Features to process can be specified using `labels` and `index`:
+
+ >>> lbl, nlbl = ndimage.label(a)
+ >>> ndimage.standard_deviation(a, lbl, index=np.arange(1, nlbl+1))
+ array([ 1.479, 1.5 , 3. ])
+
+ If no index is given, non-zero `labels` are processed:
+
+ >>> ndimage.standard_deviation(a, lbl)
+ 2.4874685927665499
+
+ """
+ return np.sqrt(variance(input, labels, index))
+
+
+def _select(input, labels=None, index=None, find_min=False, find_max=False,
+ find_min_positions=False, find_max_positions=False,
+ find_median=False):
+ """Returns min, max, or both, plus their positions (if requested), and
+ median."""
+
+ input = np.asanyarray(input)
+
+ find_positions = find_min_positions or find_max_positions
+ positions = None
+ if find_positions:
+ positions = np.arange(input.size).reshape(input.shape)
+
+ def single_group(vals, positions):
+ result = []
+ if find_min:
+ result += [vals.min()]
+ if find_min_positions:
+ result += [positions[vals == vals.min()][0]]
+ if find_max:
+ result += [vals.max()]
+ if find_max_positions:
+ result += [positions[vals == vals.max()][0]]
+ if find_median:
+ result += [np.median(vals)]
+ return result
+
+ if labels is None:
+ return single_group(input, positions)
+
+ labels = np.asarray(labels)
+ # ensure input and labels match sizes
+ input, labels = np.broadcast_arrays(input, labels)
+
+ if index is None:
+ mask = (labels > 0)
+ masked_positions = None
+ if find_positions:
+ masked_positions = positions[mask]
+ return single_group(input[mask], masked_positions)
+
+ if np.isscalar(index):
+ mask = (labels == index)
+ masked_positions = None
+ if find_positions:
+ masked_positions = positions[mask]
+ return single_group(input[mask], masked_positions)
+
+ index = np.asarray(index)
+
+ # remap labels to unique integers if necessary, or if the largest
+ # label is larger than the number of values.
+ if (not _safely_castable_to_int(labels.dtype) or
+ labels.min() < 0 or labels.max() > labels.size):
+ # remap labels, and indexes
+ unique_labels, labels = np.unique(labels, return_inverse=True)
+ idxs = np.searchsorted(unique_labels, index)
+
+ # make all of idxs valid
+ idxs[idxs >= unique_labels.size] = 0
+ found = (unique_labels[idxs] == index)
+ else:
+ # labels are an integer type, and there aren't too many
+ idxs = np.asanyarray(index, np.int_).copy()
+ found = (idxs >= 0) & (idxs <= labels.max())
+
+ idxs[~ found] = labels.max() + 1
+
+ if find_median:
+ order = np.lexsort((input.ravel(), labels.ravel()))
+ else:
+ order = input.ravel().argsort()
+ input = input.ravel()[order]
+ labels = labels.ravel()[order]
+ if find_positions:
+ positions = positions.ravel()[order]
+
+ result = []
+ if find_min:
+ mins = np.zeros(labels.max() + 2, input.dtype)
+ mins[labels[::-1]] = input[::-1]
+ result += [mins[idxs]]
+ if find_min_positions:
+ minpos = np.zeros(labels.max() + 2, int)
+ minpos[labels[::-1]] = positions[::-1]
+ result += [minpos[idxs]]
+ if find_max:
+ maxs = np.zeros(labels.max() + 2, input.dtype)
+ maxs[labels] = input
+ result += [maxs[idxs]]
+ if find_max_positions:
+ maxpos = np.zeros(labels.max() + 2, int)
+ maxpos[labels] = positions
+ result += [maxpos[idxs]]
+ if find_median:
+ locs = np.arange(len(labels))
+ lo = np.zeros(labels.max() + 2, np.int_)
+ lo[labels[::-1]] = locs[::-1]
+ hi = np.zeros(labels.max() + 2, np.int_)
+ hi[labels] = locs
+ lo = lo[idxs]
+ hi = hi[idxs]
+ # lo is an index to the lowest value in input for each label,
+ # hi is an index to the largest value.
+ # move them to be either the same ((hi - lo) % 2 == 0) or next
+ # to each other ((hi - lo) % 2 == 1), then average.
+ step = (hi - lo) // 2
+ lo += step
+ hi -= step
+ if (np.issubdtype(input.dtype, np.integer)
+ or np.issubdtype(input.dtype, np.bool_)):
+ # avoid integer overflow or boolean addition (gh-12836)
+ result += [(input[lo].astype('d') + input[hi].astype('d')) / 2.0]
+ else:
+ result += [(input[lo] + input[hi]) / 2.0]
+
+ return result
+
+
+def minimum(input, labels=None, index=None):
+ """
+ Calculate the minimum of the values of an array over labeled regions.
+
+ Parameters
+ ----------
+ input : array_like
+ Array_like of values. For each region specified by `labels`, the
+ minimal values of `input` over the region is computed.
+ labels : array_like, optional
+ An array_like of integers marking different regions over which the
+ minimum value of `input` is to be computed. `labels` must have the
+ same shape as `input`. If `labels` is not specified, the minimum
+ over the whole array is returned.
+ index : array_like, optional
+ A list of region labels that are taken into account for computing the
+ minima. If index is None, the minimum over all elements where `labels`
+ is non-zero is returned.
+
+ Returns
+ -------
+ output : a scalar or list of integers or floats based on input type.
+ List of minima of `input` over the regions determined by `labels` and
+ whose index is in `index`. If `index` or `labels` are not specified, a
+ float is returned: the minimal value of `input` if `labels` is None,
+ and the minimal value of elements where `labels` is greater than zero
+ if `index` is None.
+
+ See Also
+ --------
+ label, maximum, median, minimum_position, extrema, sum, mean, variance,
+ standard_deviation
+
+ Notes
+ -----
+ The function returns a Python list and not a NumPy array, use
+ `np.array` to convert the list to an array.
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> labels, labels_nb = ndimage.label(a)
+ >>> labels
+ array([[1, 1, 0, 0],
+ [1, 1, 0, 2],
+ [0, 0, 0, 2],
+ [3, 3, 0, 0]], dtype=int32)
+ >>> ndimage.minimum(a, labels=labels, index=np.arange(1, labels_nb + 1))
+ [1, 4, 3]
+ >>> ndimage.minimum(a)
+ 0
+ >>> ndimage.minimum(a, labels=labels)
+ 1
+
+ """
+ return _select(input, labels, index, find_min=True)[0]
+
+
+def maximum(input, labels=None, index=None):
+ """
+ Calculate the maximum of the values of an array over labeled regions.
+
+ Parameters
+ ----------
+ input : array_like
+ Array_like of values. For each region specified by `labels`, the
+ maximal values of `input` over the region is computed.
+ labels : array_like, optional
+ An array of integers marking different regions over which the
+ maximum value of `input` is to be computed. `labels` must have the
+ same shape as `input`. If `labels` is not specified, the maximum
+ over the whole array is returned.
+ index : array_like, optional
+ A list of region labels that are taken into account for computing the
+ maxima. If index is None, the maximum over all elements where `labels`
+ is non-zero is returned.
+
+ Returns
+ -------
+ output : a scalar or list of integers or floats based on input type.
+ List of maxima of `input` over the regions determined by `labels` and
+ whose index is in `index`. If `index` or `labels` are not specified, a
+ float is returned: the maximal value of `input` if `labels` is None,
+ and the maximal value of elements where `labels` is greater than zero
+ if `index` is None.
+
+ See Also
+ --------
+ label, minimum, median, maximum_position, extrema, sum, mean, variance,
+ standard_deviation
+
+ Notes
+ -----
+ The function returns a Python list and not a NumPy array, use
+ `np.array` to convert the list to an array.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.arange(16).reshape((4,4))
+ >>> a
+ array([[ 0, 1, 2, 3],
+ [ 4, 5, 6, 7],
+ [ 8, 9, 10, 11],
+ [12, 13, 14, 15]])
+ >>> labels = np.zeros_like(a)
+ >>> labels[:2,:2] = 1
+ >>> labels[2:, 1:3] = 2
+ >>> labels
+ array([[1, 1, 0, 0],
+ [1, 1, 0, 0],
+ [0, 2, 2, 0],
+ [0, 2, 2, 0]])
+ >>> from scipy import ndimage
+ >>> ndimage.maximum(a)
+ 15
+ >>> ndimage.maximum(a, labels=labels, index=[1,2])
+ [5, 14]
+ >>> ndimage.maximum(a, labels=labels)
+ 14
+
+ >>> b = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> labels, labels_nb = ndimage.label(b)
+ >>> labels
+ array([[1, 1, 0, 0],
+ [1, 1, 0, 2],
+ [0, 0, 0, 2],
+ [3, 3, 0, 0]], dtype=int32)
+ >>> ndimage.maximum(b, labels=labels, index=np.arange(1, labels_nb + 1))
+ [5, 7, 9]
+
+ """
+ return _select(input, labels, index, find_max=True)[0]
+
+
+def median(input, labels=None, index=None):
+ """
+ Calculate the median of the values of an array over labeled regions.
+
+ Parameters
+ ----------
+ input : array_like
+ Array_like of values. For each region specified by `labels`, the
+ median value of `input` over the region is computed.
+ labels : array_like, optional
+ An array_like of integers marking different regions over which the
+ median value of `input` is to be computed. `labels` must have the
+ same shape as `input`. If `labels` is not specified, the median
+ over the whole array is returned.
+ index : array_like, optional
+ A list of region labels that are taken into account for computing the
+ medians. If index is None, the median over all elements where `labels`
+ is non-zero is returned.
+
+ Returns
+ -------
+ median : float or list of floats
+ List of medians of `input` over the regions determined by `labels` and
+ whose index is in `index`. If `index` or `labels` are not specified, a
+ float is returned: the median value of `input` if `labels` is None,
+ and the median value of elements where `labels` is greater than zero
+ if `index` is None.
+
+ See Also
+ --------
+ label, minimum, maximum, extrema, sum, mean, variance, standard_deviation
+
+ Notes
+ -----
+ The function returns a Python list and not a NumPy array, use
+ `np.array` to convert the list to an array.
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 1],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> labels, labels_nb = ndimage.label(a)
+ >>> labels
+ array([[1, 1, 0, 2],
+ [1, 1, 0, 2],
+ [0, 0, 0, 2],
+ [3, 3, 0, 0]], dtype=int32)
+ >>> ndimage.median(a, labels=labels, index=np.arange(1, labels_nb + 1))
+ [2.5, 4.0, 6.0]
+ >>> ndimage.median(a)
+ 1.0
+ >>> ndimage.median(a, labels=labels)
+ 3.0
+
+ """
+ return _select(input, labels, index, find_median=True)[0]
+
+
+def minimum_position(input, labels=None, index=None):
+ """
+ Find the positions of the minimums of the values of an array at labels.
+
+ Parameters
+ ----------
+ input : array_like
+ Array_like of values.
+ labels : array_like, optional
+ An array of integers marking different regions over which the
+ position of the minimum value of `input` is to be computed.
+ `labels` must have the same shape as `input`. If `labels` is not
+ specified, the location of the first minimum over the whole
+ array is returned.
+
+ The `labels` argument only works when `index` is specified.
+ index : array_like, optional
+ A list of region labels that are taken into account for finding the
+ location of the minima. If `index` is None, the ``first`` minimum
+ over all elements where `labels` is non-zero is returned.
+
+ The `index` argument only works when `labels` is specified.
+
+ Returns
+ -------
+ output : list of tuples of ints
+ Tuple of ints or list of tuples of ints that specify the location
+ of minima of `input` over the regions determined by `labels` and
+ whose index is in `index`.
+
+ If `index` or `labels` are not specified, a tuple of ints is
+ returned specifying the location of the first minimal value of `input`.
+
+ See Also
+ --------
+ label, minimum, median, maximum_position, extrema, sum, mean, variance,
+ standard_deviation
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[10, 20, 30],
+ ... [40, 80, 100],
+ ... [1, 100, 200]])
+ >>> b = np.array([[1, 2, 0, 1],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+
+ >>> from scipy import ndimage
+
+ >>> ndimage.minimum_position(a)
+ (2, 0)
+ >>> ndimage.minimum_position(b)
+ (0, 2)
+
+ Features to process can be specified using `labels` and `index`:
+
+ >>> label, pos = ndimage.label(a)
+ >>> ndimage.minimum_position(a, label, index=np.arange(1, pos+1))
+ [(2, 0)]
+
+ >>> label, pos = ndimage.label(b)
+ >>> ndimage.minimum_position(b, label, index=np.arange(1, pos+1))
+ [(0, 0), (0, 3), (3, 1)]
+
+ """
+ dims = np.array(np.asarray(input).shape)
+ # see np.unravel_index to understand this line.
+ dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+ result = _select(input, labels, index, find_min_positions=True)[0]
+
+ if np.isscalar(result):
+ return tuple((result // dim_prod) % dims)
+
+ return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
+
+
+def maximum_position(input, labels=None, index=None):
+ """
+ Find the positions of the maximums of the values of an array at labels.
+
+ For each region specified by `labels`, the position of the maximum
+ value of `input` within the region is returned.
+
+ Parameters
+ ----------
+ input : array_like
+ Array_like of values.
+ labels : array_like, optional
+ An array of integers marking different regions over which the
+ position of the maximum value of `input` is to be computed.
+ `labels` must have the same shape as `input`. If `labels` is not
+ specified, the location of the first maximum over the whole
+ array is returned.
+
+ The `labels` argument only works when `index` is specified.
+ index : array_like, optional
+ A list of region labels that are taken into account for finding the
+ location of the maxima. If `index` is None, the first maximum
+ over all elements where `labels` is non-zero is returned.
+
+ The `index` argument only works when `labels` is specified.
+
+ Returns
+ -------
+ output : list of tuples of ints
+ List of tuples of ints that specify the location of maxima of
+ `input` over the regions determined by `labels` and whose index
+ is in `index`.
+
+ If `index` or `labels` are not specified, a tuple of ints is
+ returned specifying the location of the ``first`` maximal value
+ of `input`.
+
+ See Also
+ --------
+ label, minimum, median, maximum_position, extrema, sum, mean, variance,
+ standard_deviation
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> ndimage.maximum_position(a)
+ (3, 0)
+
+ Features to process can be specified using `labels` and `index`:
+
+ >>> lbl = np.array([[0, 1, 2, 3],
+ ... [0, 1, 2, 3],
+ ... [0, 1, 2, 3],
+ ... [0, 1, 2, 3]])
+ >>> ndimage.maximum_position(a, lbl, 1)
+ (1, 1)
+
+ If no index is given, non-zero `labels` are processed:
+
+ >>> ndimage.maximum_position(a, lbl)
+ (2, 3)
+
+ If there are no maxima, the position of the first element is returned:
+
+ >>> ndimage.maximum_position(a, lbl, 2)
+ (0, 2)
+
+ """
+ dims = np.array(np.asarray(input).shape)
+ # see np.unravel_index to understand this line.
+ dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+ result = _select(input, labels, index, find_max_positions=True)[0]
+
+ if np.isscalar(result):
+ return tuple((result // dim_prod) % dims)
+
+ return [tuple(v) for v in (result.reshape(-1, 1) // dim_prod) % dims]
+
+
+def extrema(input, labels=None, index=None):
+ """
+ Calculate the minimums and maximums of the values of an array
+ at labels, along with their positions.
+
+ Parameters
+ ----------
+ input : ndarray
+ N-D image data to process.
+ labels : ndarray, optional
+ Labels of features in input.
+ If not None, must be same shape as `input`.
+ index : int or sequence of ints, optional
+ Labels to include in output. If None (default), all values where
+ non-zero `labels` are used.
+
+ Returns
+ -------
+ minimums, maximums : int or ndarray
+ Values of minimums and maximums in each feature.
+ min_positions, max_positions : tuple or list of tuples
+ Each tuple gives the N-D coordinates of the corresponding minimum
+ or maximum.
+
+ See Also
+ --------
+ maximum, minimum, maximum_position, minimum_position, center_of_mass
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[1, 2, 0, 0],
+ ... [5, 3, 0, 4],
+ ... [0, 0, 0, 7],
+ ... [9, 3, 0, 0]])
+ >>> from scipy import ndimage
+ >>> ndimage.extrema(a)
+ (0, 9, (0, 2), (3, 0))
+
+ Features to process can be specified using `labels` and `index`:
+
+ >>> lbl, nlbl = ndimage.label(a)
+ >>> ndimage.extrema(a, lbl, index=np.arange(1, nlbl+1))
+ (array([1, 4, 3]),
+ array([5, 7, 9]),
+ [(0, 0), (1, 3), (3, 1)],
+ [(1, 0), (2, 3), (3, 0)])
+
+ If no index is given, non-zero `labels` are processed:
+
+ >>> ndimage.extrema(a, lbl)
+ (1, 9, (0, 0), (3, 0))
+
+ """
+ dims = np.array(np.asarray(input).shape)
+ # see np.unravel_index to understand this line.
+ dim_prod = np.cumprod([1] + list(dims[:0:-1]))[::-1]
+
+ minimums, min_positions, maximums, max_positions = _select(input, labels,
+ index,
+ find_min=True,
+ find_max=True,
+ find_min_positions=True,
+ find_max_positions=True)
+
+ if np.isscalar(minimums):
+ return (minimums, maximums, tuple((min_positions // dim_prod) % dims),
+ tuple((max_positions // dim_prod) % dims))
+
+ min_positions = [
+ tuple(v) for v in (min_positions.reshape(-1, 1) // dim_prod) % dims
+ ]
+ max_positions = [
+ tuple(v) for v in (max_positions.reshape(-1, 1) // dim_prod) % dims
+ ]
+
+ return minimums, maximums, min_positions, max_positions
+
+
+def center_of_mass(input, labels=None, index=None):
+ """
+ Calculate the center of mass of the values of an array at labels.
+
+ Parameters
+ ----------
+ input : ndarray
+ Data from which to calculate center-of-mass. The masses can either
+ be positive or negative.
+ labels : ndarray, optional
+ Labels for objects in `input`, as generated by `ndimage.label`.
+ Only used with `index`. Dimensions must be the same as `input`.
+ index : int or sequence of ints, optional
+ Labels for which to calculate centers-of-mass. If not specified,
+ the combined center of mass of all labels greater than zero
+ will be calculated. Only used with `labels`.
+
+ Returns
+ -------
+ center_of_mass : tuple, or list of tuples
+ Coordinates of centers-of-mass.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array(([0,0,0,0],
+ ... [0,1,1,0],
+ ... [0,1,1,0],
+ ... [0,1,1,0]))
+ >>> from scipy import ndimage
+ >>> ndimage.center_of_mass(a)
+ (2.0, 1.5)
+
+ Calculation of multiple objects in an image
+
+ >>> b = np.array(([0,1,1,0],
+ ... [0,1,0,0],
+ ... [0,0,0,0],
+ ... [0,0,1,1],
+ ... [0,0,1,1]))
+ >>> lbl = ndimage.label(b)[0]
+ >>> ndimage.center_of_mass(b, lbl, [1,2])
+ [(0.33333333333333331, 1.3333333333333333), (3.5, 2.5)]
+
+ Negative masses are also accepted, which can occur for example when
+ bias is removed from measured data due to random noise.
+
+ >>> c = np.array(([-1,0,0,0],
+ ... [0,-1,-1,0],
+ ... [0,1,-1,0],
+ ... [0,1,1,0]))
+ >>> ndimage.center_of_mass(c)
+ (-4.0, 1.0)
+
+ If there are division by zero issues, the function does not raise an
+ error but rather issues a RuntimeWarning before returning inf and/or NaN.
+
+ >>> d = np.array([-1, 1])
+ >>> ndimage.center_of_mass(d)
+ (inf,)
+ """
+ input = np.asarray(input)
+ normalizer = sum_labels(input, labels, index)
+ grids = np.ogrid[[slice(0, i) for i in input.shape]]
+
+ results = [sum_labels(input * grids[dir].astype(float), labels, index) / normalizer
+ for dir in range(input.ndim)]
+
+ if np.isscalar(results[0]):
+ return tuple(results)
+
+ return [tuple(v) for v in np.array(results).T]
+
+
+def histogram(input, min, max, bins, labels=None, index=None):
+ """
+ Calculate the histogram of the values of an array, optionally at labels.
+
+ Histogram calculates the frequency of values in an array within bins
+ determined by `min`, `max`, and `bins`. The `labels` and `index`
+ keywords can limit the scope of the histogram to specified sub-regions
+ within the array.
+
+ Parameters
+ ----------
+ input : array_like
+ Data for which to calculate histogram.
+ min, max : int
+ Minimum and maximum values of range of histogram bins.
+ bins : int
+ Number of bins.
+ labels : array_like, optional
+ Labels for objects in `input`.
+ If not None, must be same shape as `input`.
+ index : int or sequence of ints, optional
+ Label or labels for which to calculate histogram. If None, all values
+ where label is greater than zero are used
+
+ Returns
+ -------
+ hist : ndarray
+ Histogram counts.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> a = np.array([[ 0. , 0.2146, 0.5962, 0. ],
+ ... [ 0. , 0.7778, 0. , 0. ],
+ ... [ 0. , 0. , 0. , 0. ],
+ ... [ 0. , 0. , 0.7181, 0.2787],
+ ... [ 0. , 0. , 0.6573, 0.3094]])
+ >>> from scipy import ndimage
+ >>> ndimage.histogram(a, 0, 1, 10)
+ array([13, 0, 2, 1, 0, 1, 1, 2, 0, 0])
+
+ With labels and no indices, non-zero elements are counted:
+
+ >>> lbl, nlbl = ndimage.label(a)
+ >>> ndimage.histogram(a, 0, 1, 10, lbl)
+ array([0, 0, 2, 1, 0, 1, 1, 2, 0, 0])
+
+ Indices can be used to count only certain objects:
+
+ >>> ndimage.histogram(a, 0, 1, 10, lbl, 2)
+ array([0, 0, 1, 1, 0, 0, 1, 1, 0, 0])
+
+ """
+ _bins = np.linspace(min, max, bins + 1)
+
+ def _hist(vals):
+ return np.histogram(vals, _bins)[0]
+
+ return labeled_comprehension(input, labels, index, _hist, object, None,
+ pass_positions=False)
+
+
+def watershed_ift(input, markers, structure=None, output=None):
+ """
+ Apply watershed from markers using image foresting transform algorithm.
+
+ Parameters
+ ----------
+ input : array_like
+ Input.
+ markers : array_like
+ Markers are points within each watershed that form the beginning
+ of the process. Negative markers are considered background markers
+ which are processed after the other markers.
+ structure : structure element, optional
+ A structuring element defining the connectivity of the object can be
+ provided. If None, an element is generated with a squared
+ connectivity equal to one.
+ output : ndarray, optional
+ An output array can optionally be provided. The same shape as input.
+
+ Returns
+ -------
+ watershed_ift : ndarray
+ Output. Same shape as `input`.
+
+ References
+ ----------
+ .. [1] A.X. Falcao, J. Stolfi and R. de Alencar Lotufo, "The image
+ foresting transform: theory, algorithms, and applications",
+ Pattern Analysis and Machine Intelligence, vol. 26, pp. 19-29, 2004.
+
+ """
+ input = np.asarray(input)
+ if input.dtype.type not in [np.uint8, np.uint16]:
+ raise TypeError('only 8 and 16 unsigned inputs are supported')
+
+ if structure is None:
+ structure = _morphology.generate_binary_structure(input.ndim, 1)
+ structure = np.asarray(structure, dtype=bool)
+ if structure.ndim != input.ndim:
+ raise RuntimeError('structure and input must have equal rank')
+ for ii in structure.shape:
+ if ii != 3:
+ raise RuntimeError('structure dimensions must be equal to 3')
+
+ if not structure.flags.contiguous:
+ structure = structure.copy()
+ markers = np.asarray(markers)
+ if input.shape != markers.shape:
+ raise RuntimeError('input and markers must have equal shape')
+
+ integral_types = [np.int8,
+ np.int16,
+ np.int32,
+ np.int64,
+ np.intc,
+ np.intp]
+
+ if markers.dtype.type not in integral_types:
+ raise RuntimeError('marker should be of integer type')
+
+ if isinstance(output, np.ndarray):
+ if output.dtype.type not in integral_types:
+ raise RuntimeError('output should be of integer type')
+ else:
+ output = markers.dtype
+
+ output = _ni_support._get_output(output, input)
+ _nd_image.watershed_ift(input, markers, structure, output)
+ return output
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_morphology.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8e07ae8781853015503c600a20faab83eaa0440
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_morphology.py
@@ -0,0 +1,2633 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+import warnings
+import operator
+
+import numpy as np
+from . import _ni_support
+from . import _nd_image
+from . import _filters
+
+__all__ = ['iterate_structure', 'generate_binary_structure', 'binary_erosion',
+ 'binary_dilation', 'binary_opening', 'binary_closing',
+ 'binary_hit_or_miss', 'binary_propagation', 'binary_fill_holes',
+ 'grey_erosion', 'grey_dilation', 'grey_opening', 'grey_closing',
+ 'morphological_gradient', 'morphological_laplace', 'white_tophat',
+ 'black_tophat', 'distance_transform_bf', 'distance_transform_cdt',
+ 'distance_transform_edt']
+
+
+def _center_is_true(structure, origin):
+ structure = np.asarray(structure)
+ coor = tuple([oo + ss // 2 for ss, oo in zip(structure.shape,
+ origin)])
+ return bool(structure[coor])
+
+
+def iterate_structure(structure, iterations, origin=None):
+ """
+ Iterate a structure by dilating it with itself.
+
+ Parameters
+ ----------
+ structure : array_like
+ Structuring element (an array of bools, for example), to be dilated with
+ itself.
+ iterations : int
+ number of dilations performed on the structure with itself
+ origin : optional
+ If origin is None, only the iterated structure is returned. If
+ not, a tuple of the iterated structure and the modified origin is
+ returned.
+
+ Returns
+ -------
+ iterate_structure : ndarray of bools
+ A new structuring element obtained by dilating `structure`
+ (`iterations` - 1) times with itself.
+
+ See Also
+ --------
+ generate_binary_structure
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> struct = ndimage.generate_binary_structure(2, 1)
+ >>> struct.astype(int)
+ array([[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]])
+ >>> ndimage.iterate_structure(struct, 2).astype(int)
+ array([[0, 0, 1, 0, 0],
+ [0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0]])
+ >>> ndimage.iterate_structure(struct, 3).astype(int)
+ array([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]])
+
+ """
+ structure = np.asarray(structure)
+ if iterations < 2:
+ return structure.copy()
+ ni = iterations - 1
+ shape = [ii + ni * (ii - 1) for ii in structure.shape]
+ pos = [ni * (structure.shape[ii] // 2) for ii in range(len(shape))]
+ slc = tuple(slice(pos[ii], pos[ii] + structure.shape[ii], None)
+ for ii in range(len(shape)))
+ out = np.zeros(shape, bool)
+ out[slc] = structure != 0
+ out = binary_dilation(out, structure, iterations=ni)
+ if origin is None:
+ return out
+ else:
+ origin = _ni_support._normalize_sequence(origin, structure.ndim)
+ origin = [iterations * o for o in origin]
+ return out, origin
+
+
+def generate_binary_structure(rank, connectivity):
+ """
+ Generate a binary structure for binary morphological operations.
+
+ Parameters
+ ----------
+ rank : int
+ Number of dimensions of the array to which the structuring element
+ will be applied, as returned by `np.ndim`.
+ connectivity : int
+ `connectivity` determines which elements of the output array belong
+ to the structure, i.e., are considered as neighbors of the central
+ element. Elements up to a squared distance of `connectivity` from
+ the center are considered neighbors. `connectivity` may range from 1
+ (no diagonal elements are neighbors) to `rank` (all elements are
+ neighbors).
+
+ Returns
+ -------
+ output : ndarray of bools
+ Structuring element which may be used for binary morphological
+ operations, with `rank` dimensions and all dimensions equal to 3.
+
+ See Also
+ --------
+ iterate_structure, binary_dilation, binary_erosion
+
+ Notes
+ -----
+ `generate_binary_structure` can only create structuring elements with
+ dimensions equal to 3, i.e., minimal dimensions. For larger structuring
+ elements, that are useful e.g., for eroding large objects, one may either
+ use `iterate_structure`, or create directly custom arrays with
+ numpy functions such as `numpy.ones`.
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> struct = ndimage.generate_binary_structure(2, 1)
+ >>> struct
+ array([[False, True, False],
+ [ True, True, True],
+ [False, True, False]], dtype=bool)
+ >>> a = np.zeros((5,5))
+ >>> a[2, 2] = 1
+ >>> a
+ array([[ 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0.],
+ [ 0., 0., 1., 0., 0.],
+ [ 0., 0., 0., 0., 0.],
+ [ 0., 0., 0., 0., 0.]])
+ >>> b = ndimage.binary_dilation(a, structure=struct).astype(a.dtype)
+ >>> b
+ array([[ 0., 0., 0., 0., 0.],
+ [ 0., 0., 1., 0., 0.],
+ [ 0., 1., 1., 1., 0.],
+ [ 0., 0., 1., 0., 0.],
+ [ 0., 0., 0., 0., 0.]])
+ >>> ndimage.binary_dilation(b, structure=struct).astype(a.dtype)
+ array([[ 0., 0., 1., 0., 0.],
+ [ 0., 1., 1., 1., 0.],
+ [ 1., 1., 1., 1., 1.],
+ [ 0., 1., 1., 1., 0.],
+ [ 0., 0., 1., 0., 0.]])
+ >>> struct = ndimage.generate_binary_structure(2, 2)
+ >>> struct
+ array([[ True, True, True],
+ [ True, True, True],
+ [ True, True, True]], dtype=bool)
+ >>> struct = ndimage.generate_binary_structure(3, 1)
+ >>> struct # no diagonal elements
+ array([[[False, False, False],
+ [False, True, False],
+ [False, False, False]],
+ [[False, True, False],
+ [ True, True, True],
+ [False, True, False]],
+ [[False, False, False],
+ [False, True, False],
+ [False, False, False]]], dtype=bool)
+
+ """
+ if connectivity < 1:
+ connectivity = 1
+ if rank < 1:
+ return np.array(True, dtype=bool)
+ output = np.fabs(np.indices([3] * rank) - 1)
+ output = np.add.reduce(output, 0)
+ return output <= connectivity
+
+
+def _binary_erosion(input, structure, iterations, mask, output,
+ border_value, origin, invert, brute_force, axes):
+ try:
+ iterations = operator.index(iterations)
+ except TypeError as e:
+ raise TypeError('iterations parameter should be an integer') from e
+
+ input = np.asarray(input)
+ # The Cython code can't cope with broadcasted inputs
+ if not input.flags.c_contiguous and not input.flags.f_contiguous:
+ input = np.ascontiguousarray(input)
+
+ ndim = input.ndim
+ if np.iscomplexobj(input):
+ raise TypeError('Complex type not supported')
+ axes = _ni_support._check_axes(axes, input.ndim)
+ num_axes = len(axes)
+ if structure is None:
+ structure = generate_binary_structure(num_axes, 1)
+ else:
+ structure = np.asarray(structure, dtype=bool)
+ if ndim > num_axes:
+ structure = _filters._expand_footprint(ndim, axes, structure,
+ footprint_name="structure")
+
+ if structure.ndim != input.ndim:
+ raise RuntimeError('structure and input must have same dimensionality')
+ if not structure.flags.contiguous:
+ structure = structure.copy()
+ if structure.size < 1:
+ raise RuntimeError('structure must not be empty')
+ if mask is not None:
+ mask = np.asarray(mask)
+ if mask.shape != input.shape:
+ raise RuntimeError('mask and input must have equal sizes')
+ origin = _ni_support._normalize_sequence(origin, num_axes)
+ origin = _filters._expand_origin(ndim, axes, origin)
+ cit = _center_is_true(structure, origin)
+ if isinstance(output, np.ndarray):
+ if np.iscomplexobj(output):
+ raise TypeError('Complex output type not supported')
+ else:
+ output = bool
+ output = _ni_support._get_output(output, input)
+ temp_needed = np.may_share_memory(input, output)
+ if temp_needed:
+ # input and output arrays cannot share memory
+ temp = output
+ output = _ni_support._get_output(output.dtype, input)
+ if iterations == 1:
+ _nd_image.binary_erosion(input, structure, mask, output,
+ border_value, origin, invert, cit, 0)
+ elif cit and not brute_force:
+ changed, coordinate_list = _nd_image.binary_erosion(
+ input, structure, mask, output,
+ border_value, origin, invert, cit, 1)
+ structure = structure[tuple([slice(None, None, -1)] *
+ structure.ndim)]
+ for ii in range(len(origin)):
+ origin[ii] = -origin[ii]
+ if not structure.shape[ii] & 1:
+ origin[ii] -= 1
+ if mask is not None:
+ mask = np.asarray(mask, dtype=np.int8)
+ if not structure.flags.contiguous:
+ structure = structure.copy()
+ _nd_image.binary_erosion2(output, structure, mask, iterations - 1,
+ origin, invert, coordinate_list)
+ else:
+ tmp_in = np.empty_like(input, dtype=bool)
+ tmp_out = output
+ if iterations >= 1 and not iterations & 1:
+ tmp_in, tmp_out = tmp_out, tmp_in
+ changed = _nd_image.binary_erosion(
+ input, structure, mask, tmp_out,
+ border_value, origin, invert, cit, 0)
+ ii = 1
+ while ii < iterations or (iterations < 1 and changed):
+ tmp_in, tmp_out = tmp_out, tmp_in
+ changed = _nd_image.binary_erosion(
+ tmp_in, structure, mask, tmp_out,
+ border_value, origin, invert, cit, 0)
+ ii += 1
+ if temp_needed:
+ temp[...] = output
+ output = temp
+ return output
+
+
+def binary_erosion(input, structure=None, iterations=1, mask=None, output=None,
+ border_value=0, origin=0, brute_force=False, *, axes=None):
+ """
+ Multidimensional binary erosion with a given structuring element.
+
+ Binary erosion is a mathematical morphology operation used for image
+ processing.
+
+ Parameters
+ ----------
+ input : array_like
+ Binary image to be eroded. Non-zero (True) elements form
+ the subset to be eroded.
+ structure : array_like, optional
+ Structuring element used for the erosion. Non-zero elements are
+ considered True. If no structuring element is provided, an element
+ is generated with a square connectivity equal to one.
+ iterations : int, optional
+ The erosion is repeated `iterations` times (one, by default).
+ If iterations is less than 1, the erosion is repeated until the
+ result does not change anymore.
+ mask : array_like, optional
+ If a mask is given, only those elements with a True value at
+ the corresponding mask element are modified at each iteration.
+ output : ndarray, optional
+ Array of the same shape as input, into which the output is placed.
+ By default, a new array is created.
+ border_value : int (cast to 0 or 1), optional
+ Value at the border in the output array.
+ origin : int or tuple of ints, optional
+ Placement of the filter, by default 0.
+ brute_force : 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
+
+ """
+ input = np.asarray(input)
+ tmp1 = grey_dilation(input, size, footprint, structure, None, mode,
+ cval, origin, axes=axes)
+ if isinstance(output, np.ndarray):
+ grey_erosion(input, size, footprint, structure, output, mode,
+ cval, origin, axes=axes)
+ np.add(tmp1, output, output)
+ np.subtract(output, input, output)
+ return np.subtract(output, input, output)
+ else:
+ tmp2 = grey_erosion(input, size, footprint, structure, None, mode,
+ cval, origin, axes=axes)
+ np.add(tmp1, tmp2, tmp2)
+ np.subtract(tmp2, input, tmp2)
+ np.subtract(tmp2, input, tmp2)
+ return tmp2
+
+
+def white_tophat(input, size=None, footprint=None, structure=None,
+ output=None, mode="reflect", cval=0.0, origin=0, *,
+ axes=None):
+ """
+ Multidimensional white tophat filter.
+
+ Parameters
+ ----------
+ input : array_like
+ Input.
+ size : tuple of ints
+ Shape of a flat and full structuring element used for the filter.
+ Optional if `footprint` or `structure` is provided.
+ footprint : array of ints, optional
+ Positions of elements of a flat structuring element
+ used for the white tophat filter.
+ structure : array of ints, optional
+ Structuring element used for the filter. `structure` may be a non-flat
+ structuring element. The `structure` array applies offsets to the
+ pixels in a neighborhood (the offset is additive during dilation and
+ subtractive during erosion)
+ output : array, optional
+ An array used for storing the output of the filter may be provided.
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+ The `mode` parameter determines how the array borders are
+ handled, where `cval` is the value when mode is equal to
+ 'constant'. Default is 'reflect'
+ cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'.
+ Default is 0.0.
+ origin : scalar, optional
+ The `origin` parameter controls the placement of the filter.
+ Default is 0.
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ output : ndarray
+ Result of the filter of `input` with `structure`.
+
+ See Also
+ --------
+ black_tophat
+
+ Examples
+ --------
+ Subtract gray background from a bright peak.
+
+ >>> from scipy.ndimage import generate_binary_structure, white_tophat
+ >>> import numpy as np
+ >>> square = generate_binary_structure(rank=2, connectivity=3)
+ >>> bright_on_gray = np.array([[2, 3, 3, 3, 2],
+ ... [3, 4, 5, 4, 3],
+ ... [3, 5, 9, 5, 3],
+ ... [3, 4, 5, 4, 3],
+ ... [2, 3, 3, 3, 2]])
+ >>> white_tophat(input=bright_on_gray, structure=square)
+ array([[0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0],
+ [0, 1, 5, 1, 0],
+ [0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0]])
+
+ """
+ input = np.asarray(input)
+
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=2)
+ tmp = grey_erosion(input, size, footprint, structure, None, mode,
+ cval, origin, axes=axes)
+ tmp = grey_dilation(tmp, size, footprint, structure, output, mode,
+ cval, origin, axes=axes)
+ if tmp is None:
+ tmp = output
+
+ if input.dtype == np.bool_ and tmp.dtype == np.bool_:
+ np.bitwise_xor(input, tmp, out=tmp)
+ else:
+ np.subtract(input, tmp, out=tmp)
+ return tmp
+
+
+def black_tophat(input, size=None, footprint=None, structure=None, output=None,
+ mode="reflect", cval=0.0, origin=0, *, axes=None):
+ """
+ Multidimensional black tophat filter.
+
+ Parameters
+ ----------
+ input : array_like
+ Input.
+ size : tuple of ints, optional
+ Shape of a flat and full structuring element used for the filter.
+ Optional if `footprint` or `structure` is provided.
+ footprint : array of ints, optional
+ Positions of non-infinite elements of a flat structuring element
+ used for the black tophat filter.
+ structure : array of ints, optional
+ Structuring element used for the filter. `structure` may be a non-flat
+ structuring element. The `structure` array applies offsets to the
+ pixels in a neighborhood (the offset is additive during dilation and
+ subtractive during erosion)
+ output : array, optional
+ An array used for storing the output of the filter may be provided.
+ mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+ The `mode` parameter determines how the array borders are
+ handled, where `cval` is the value when mode is equal to
+ 'constant'. Default is 'reflect'
+ cval : scalar, optional
+ Value to fill past edges of input if `mode` is 'constant'. Default
+ is 0.0.
+ origin : scalar, optional
+ The `origin` parameter controls the placement of the filter.
+ Default 0
+ axes : tuple of int or None
+ The axes over which to apply the filter. If None, `input` is filtered
+ along all axes. If an `origin` tuple is provided, its length must match
+ the number of axes.
+
+ Returns
+ -------
+ black_tophat : ndarray
+ Result of the filter of `input` with `structure`.
+
+ See Also
+ --------
+ white_tophat, grey_opening, grey_closing
+
+ Examples
+ --------
+ Change dark peak to bright peak and subtract background.
+
+ >>> from scipy.ndimage import generate_binary_structure, black_tophat
+ >>> import numpy as np
+ >>> square = generate_binary_structure(rank=2, connectivity=3)
+ >>> dark_on_gray = np.array([[7, 6, 6, 6, 7],
+ ... [6, 5, 4, 5, 6],
+ ... [6, 4, 0, 4, 6],
+ ... [6, 5, 4, 5, 6],
+ ... [7, 6, 6, 6, 7]])
+ >>> black_tophat(input=dark_on_gray, structure=square)
+ array([[0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0],
+ [0, 1, 5, 1, 0],
+ [0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0]])
+
+ """
+ input = np.asarray(input)
+
+ if (size is not None) and (footprint is not None):
+ warnings.warn("ignoring size because footprint is set",
+ UserWarning, stacklevel=2)
+ tmp = grey_dilation(input, size, footprint, structure, None, mode,
+ cval, origin, axes=axes)
+ tmp = grey_erosion(tmp, size, footprint, structure, output, mode,
+ cval, origin, axes=axes)
+ if tmp is None:
+ tmp = output
+
+ if input.dtype == np.bool_ and tmp.dtype == np.bool_:
+ np.bitwise_xor(tmp, input, out=tmp)
+ else:
+ np.subtract(tmp, input, out=tmp)
+ return tmp
+
+
+def distance_transform_bf(input, metric="euclidean", sampling=None,
+ return_distances=True, return_indices=False,
+ distances=None, indices=None):
+ """
+ Distance transform function by a brute force algorithm.
+
+ This function calculates the distance transform of the `input`, by
+ replacing each foreground (non-zero) element, with its
+ shortest distance to the background (any zero-valued element).
+
+ In addition to the distance transform, the feature transform can
+ be calculated. In this case the index of the closest background
+ element to each foreground element is returned in a separate array.
+
+ Parameters
+ ----------
+ input : array_like
+ Input
+ metric : {'euclidean', 'taxicab', 'chessboard'}, optional
+ 'cityblock' and 'manhattan' are also valid, and map to 'taxicab'.
+ The default is 'euclidean'.
+ sampling : float, or sequence of float, optional
+ This parameter is only used when `metric` is 'euclidean'.
+ Spacing of elements along each dimension. If a sequence, must be of
+ length equal to the input rank; if a single number, this is used for
+ all axes. If not specified, a grid spacing of unity is implied.
+ return_distances : bool, optional
+ Whether to calculate the distance transform.
+ Default is True.
+ return_indices : bool, optional
+ Whether to calculate the feature transform.
+ Default is False.
+ distances : ndarray, optional
+ An output array to store the calculated distance transform, instead of
+ returning it.
+ `return_distances` must be True.
+ It must be the same shape as `input`, and of type float64 if `metric`
+ is 'euclidean', uint32 otherwise.
+ indices : int32 ndarray, optional
+ An output array to store the calculated feature transform, instead of
+ returning it.
+ `return_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 = rtmp.reshape(tmp1.shape)
+ tmp2[ii, ...] = rtmp
+ ft = tmp2
+
+ # construct and return the result
+ result = []
+ if return_distances and not dt_inplace:
+ result.append(dt)
+ if return_indices and not ft_inplace:
+ result.append(ft)
+
+ if len(result) == 2:
+ return tuple(result)
+ elif len(result) == 1:
+ return result[0]
+ else:
+ return None
+
+
+def distance_transform_cdt(input, metric='chessboard', return_distances=True,
+ return_indices=False, distances=None, indices=None):
+ """
+ Distance transform for chamfer type of transforms.
+
+ This function calculates the distance transform of the `input`, by
+ replacing each foreground (non-zero) element, with its
+ shortest distance to the background (any zero-valued element).
+
+ In addition to the distance transform, the feature transform can
+ be calculated. In this case the index of the closest background
+ element to each foreground element is returned in a separate array.
+
+ Parameters
+ ----------
+ input : array_like
+ Input. Values of 0 are treated as background.
+ metric : {'chessboard', 'taxicab'} or array_like, optional
+ The `metric` determines the type of chamfering that is done. If the
+ `metric` is equal to 'taxicab' a structure is generated using
+ `generate_binary_structure` with a squared distance equal to 1. If
+ the `metric` is equal to 'chessboard', a `metric` is generated
+ using `generate_binary_structure` with a squared distance equal to
+ the dimensionality of the array. These choices correspond to the
+ common interpretations of the 'taxicab' and the 'chessboard'
+ distance metrics in two dimensions.
+ A custom metric may be provided, in the form of a matrix where
+ each dimension has a length of three.
+ 'cityblock' and 'manhattan' are also valid, and map to 'taxicab'.
+ The default is 'chessboard'.
+ return_distances : bool, optional
+ Whether to calculate the distance transform.
+ Default is True.
+ return_indices : bool, optional
+ Whether to calculate the feature transform.
+ Default is False.
+ distances : int32 ndarray, optional
+ An output array to store the calculated distance transform, instead of
+ returning it.
+ `return_distances` must be True.
+ It must be the same shape as `input`.
+ indices : int32 ndarray, optional
+ An output array to store the calculated feature transform, instead of
+ returning it.
+ `return_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).reshape(dt.shape)
+ else:
+ ft = None
+
+ _nd_image.distance_transform_op(metric, dt, ft)
+ dt = dt[tuple([slice(None, None, -1)] * rank)]
+ if return_indices:
+ ft = ft[tuple([slice(None, None, -1)] * rank)]
+ _nd_image.distance_transform_op(metric, dt, ft)
+ dt = dt[tuple([slice(None, None, -1)] * rank)]
+ if return_indices:
+ ft = ft[tuple([slice(None, None, -1)] * rank)]
+ ft = np.ravel(ft)
+ if ft_inplace:
+ if indices.dtype.type != np.int32:
+ raise ValueError('indices array must be int32')
+ if indices.shape != (dt.ndim,) + dt.shape:
+ raise ValueError('indices array has wrong shape')
+ tmp = indices
+ else:
+ tmp = np.indices(dt.shape, dtype=np.int32)
+ for ii in range(tmp.shape[0]):
+ rtmp = np.ravel(tmp[ii, ...])[ft]
+ rtmp = rtmp.reshape(dt.shape)
+ tmp[ii, ...] = rtmp
+ ft = tmp
+
+ # construct and return the result
+ result = []
+ if return_distances and not dt_inplace:
+ result.append(dt)
+ if return_indices and not ft_inplace:
+ result.append(ft)
+
+ if len(result) == 2:
+ return tuple(result)
+ elif len(result) == 1:
+ return result[0]
+ else:
+ return None
+
+
+def distance_transform_edt(input, sampling=None, return_distances=True,
+ return_indices=False, distances=None, indices=None):
+ """
+ Exact Euclidean distance transform.
+
+ This function calculates the distance transform of the `input`, by
+ replacing each foreground (non-zero) element, with its
+ shortest distance to the background (any zero-valued element).
+
+ In addition to the distance transform, the feature transform can
+ be calculated. In this case the index of the closest background
+ element to each foreground element is returned in a separate array.
+
+ Parameters
+ ----------
+ input : array_like
+ Input data to transform. Can be any type but will be converted
+ into binary: 1 wherever input equates to True, 0 elsewhere.
+ sampling : float, or sequence of float, optional
+ Spacing of elements along each dimension. If a sequence, must be of
+ length equal to the input rank; if a single number, this is used for
+ all axes. If not specified, a grid spacing of unity is implied.
+ return_distances : bool, optional
+ Whether to calculate the distance transform.
+ Default is True.
+ return_indices : bool, optional
+ Whether to calculate the feature transform.
+ Default is False.
+ distances : float64 ndarray, optional
+ An output array to store the calculated distance transform, instead of
+ returning it.
+ `return_distances` must be True.
+ It must be the same shape as `input`.
+ indices : int32 ndarray, optional
+ An output array to store the calculated feature transform, instead of
+ returning it.
+ `return_indicies` must be True.
+ Its shape must be ``(input.ndim,) + input.shape``.
+
+ Returns
+ -------
+ distances : float64 ndarray, optional
+ The calculated distance transform. Returned only when
+ `return_distances` is True and `distances` is not supplied.
+ It will have the same shape as the input array.
+ indices : int32 ndarray, optional
+ The calculated feature transform. It has an input-shaped array for each
+ dimension of the input. See example below.
+ Returned only when `return_indices` is True and `indices` is not
+ supplied.
+
+ Notes
+ -----
+ The Euclidean distance transform gives values of the Euclidean
+ distance::
+
+ n
+ y_i = sqrt(sum (x[i]-b[i])**2)
+ i
+
+ where b[i] is the background point (value 0) with the smallest
+ Euclidean distance to input points x[i], and n is the
+ number of dimensions.
+
+ Examples
+ --------
+ >>> from scipy import ndimage
+ >>> import numpy as np
+ >>> a = np.array(([0,1,1,1,1],
+ ... [0,0,1,1,1],
+ ... [0,1,1,1,1],
+ ... [0,1,1,1,0],
+ ... [0,1,1,0,0]))
+ >>> ndimage.distance_transform_edt(a)
+ array([[ 0. , 1. , 1.4142, 2.2361, 3. ],
+ [ 0. , 0. , 1. , 2. , 2. ],
+ [ 0. , 1. , 1.4142, 1.4142, 1. ],
+ [ 0. , 1. , 1.4142, 1. , 0. ],
+ [ 0. , 1. , 1. , 0. , 0. ]])
+
+ With a sampling of 2 units along x, 1 along y:
+
+ >>> ndimage.distance_transform_edt(a, sampling=[2,1])
+ array([[ 0. , 1. , 2. , 2.8284, 3.6056],
+ [ 0. , 0. , 1. , 2. , 3. ],
+ [ 0. , 1. , 2. , 2.2361, 2. ],
+ [ 0. , 1. , 2. , 1. , 0. ],
+ [ 0. , 1. , 1. , 0. , 0. ]])
+
+ Asking for indices as well:
+
+ >>> edt, inds = ndimage.distance_transform_edt(a, return_indices=True)
+ >>> inds
+ array([[[0, 0, 1, 1, 3],
+ [1, 1, 1, 1, 3],
+ [2, 2, 1, 3, 3],
+ [3, 3, 4, 4, 3],
+ [4, 4, 4, 4, 4]],
+ [[0, 0, 1, 1, 4],
+ [0, 1, 1, 1, 4],
+ [0, 0, 1, 4, 4],
+ [0, 0, 3, 3, 4],
+ [0, 0, 3, 3, 4]]], dtype=int32)
+
+ With arrays provided for inplace outputs:
+
+ >>> indices = np.zeros(((np.ndim(a),) + a.shape), dtype=np.int32)
+ >>> ndimage.distance_transform_edt(a, return_indices=True, indices=indices)
+ array([[ 0. , 1. , 1.4142, 2.2361, 3. ],
+ [ 0. , 0. , 1. , 2. , 2. ],
+ [ 0. , 1. , 1.4142, 1.4142, 1. ],
+ [ 0. , 1. , 1.4142, 1. , 0. ],
+ [ 0. , 1. , 1. , 0. , 0. ]])
+ >>> indices
+ array([[[0, 0, 1, 1, 3],
+ [1, 1, 1, 1, 3],
+ [2, 2, 1, 3, 3],
+ [3, 3, 4, 4, 3],
+ [4, 4, 4, 4, 4]],
+ [[0, 0, 1, 1, 4],
+ [0, 1, 1, 1, 4],
+ [0, 0, 1, 4, 4],
+ [0, 0, 3, 3, 4],
+ [0, 0, 3, 3, 4]]], dtype=int32)
+
+ """
+ ft_inplace = isinstance(indices, np.ndarray)
+ dt_inplace = isinstance(distances, np.ndarray)
+ _distance_tranform_arg_check(
+ dt_inplace, ft_inplace, return_distances, return_indices
+ )
+
+ # calculate the feature transform
+ input = np.atleast_1d(np.where(input, 1, 0).astype(np.int8))
+ if sampling is not None:
+ sampling = _ni_support._normalize_sequence(sampling, input.ndim)
+ sampling = np.asarray(sampling, dtype=np.float64)
+ if not sampling.flags.contiguous:
+ sampling = sampling.copy()
+
+ if ft_inplace:
+ ft = indices
+ if ft.shape != (input.ndim,) + input.shape:
+ raise RuntimeError('indices array has wrong shape')
+ if ft.dtype.type != np.int32:
+ raise RuntimeError('indices array must be int32')
+ else:
+ ft = np.zeros((input.ndim,) + input.shape, dtype=np.int32)
+
+ _nd_image.euclidean_feature_transform(input, sampling, ft)
+ # if requested, calculate the distance transform
+ if return_distances:
+ dt = ft - np.indices(input.shape, dtype=ft.dtype)
+ dt = dt.astype(np.float64)
+ if sampling is not None:
+ for ii in range(len(sampling)):
+ dt[ii, ...] *= sampling[ii]
+ np.multiply(dt, dt, dt)
+ if dt_inplace:
+ dt = np.add.reduce(dt, axis=0)
+ if distances.shape != dt.shape:
+ raise RuntimeError('distances array has wrong shape')
+ if distances.dtype.type != np.float64:
+ raise RuntimeError('distances array must be float64')
+ np.sqrt(dt, distances)
+ else:
+ dt = np.add.reduce(dt, axis=0)
+ dt = np.sqrt(dt)
+
+ # construct and return the result
+ result = []
+ if return_distances and not dt_inplace:
+ result.append(dt)
+ if return_indices and not ft_inplace:
+ result.append(ft)
+
+ if len(result) == 2:
+ return tuple(result)
+ elif len(result) == 1:
+ return result[0]
+ else:
+ return None
+
+
+def _distance_tranform_arg_check(distances_out, indices_out,
+ return_distances, return_indices):
+ """Raise a RuntimeError if the arguments are invalid"""
+ error_msgs = []
+ if (not return_distances) and (not return_indices):
+ error_msgs.append(
+ 'at least one of return_distances/return_indices must be True')
+ if distances_out and not return_distances:
+ error_msgs.append(
+ 'return_distances must be True if distances is supplied'
+ )
+ if indices_out and not return_indices:
+ error_msgs.append('return_indices must be True if indices is supplied')
+ if error_msgs:
+ raise RuntimeError(', '.join(error_msgs))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..10a4d8f3c8714a3872227b06f821a2b13e20f562
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_nd_image.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:35fcb2473b289e07fec6786a16f743227829c5c7b7d223c2a46a924c2a0cb371
+size 156160
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ndimage_api.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ndimage_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..1673391726a4070af4814d04be16e29e01d9f29b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ndimage_api.py
@@ -0,0 +1,16 @@
+"""This is the 'bare' ndimage API.
+
+This --- private! --- module only collects implementations of public ndimage API
+for _support_alternative_backends.
+The latter --- also private! --- module adds delegation to CuPy etc and
+re-exports decorated names to __init__.py
+"""
+
+from ._filters import * # noqa: F403
+from ._fourier import * # noqa: F403
+from ._interpolation import * # noqa: F403
+from ._measurements import * # noqa: F403
+from ._morphology import * # noqa: F403
+
+# '@' due to pytest bug, scipy/scipy#22236
+__all__ = [s for s in dir() if not s.startswith(('_', '@'))]
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_docstrings.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_docstrings.py
new file mode 100644
index 0000000000000000000000000000000000000000..b008bd65cde2f0fba4ef8d3ebca84963394c61c4
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_docstrings.py
@@ -0,0 +1,214 @@
+"""Docstring components common to several ndimage functions."""
+from typing import Final
+
+from scipy._lib import doccer
+
+__all__ = ['docfiller']
+
+
+_input_doc = (
+"""input : array_like
+ The input array.""")
+_axis_doc = (
+"""axis : int, optional
+ The axis of `input` along which to calculate. Default is -1.""")
+_output_doc = (
+"""output : array or dtype, optional
+ The array in which to place the output, or the dtype of the
+ returned array. By default an array of the same dtype as input
+ will be created.""")
+_nan_doc = (
+"""The behavior of this function with NaN elements is undefined. To control
+behavior in the presence of NaNs, consider using `vectorized_filter`.""")
+_size_foot_doc = (
+"""size : scalar or tuple, optional
+ See footprint, below. Ignored if footprint is given.
+footprint : array, optional
+ Either `size` or `footprint` must be defined. `size` gives
+ the shape that is taken from the input array, at every element
+ position, to define the input to the filter function.
+ `footprint` is a boolean array that specifies (implicitly) a
+ shape, but also which of the elements within this shape will get
+ passed to the filter function. Thus ``size=(n,m)`` is equivalent
+ to ``footprint=np.ones((n,m))``. We adjust `size` to the number
+ of dimensions of the input array, so that, if the input array is
+ shape (10,10,10), and `size` is 2, then the actual size used is
+ (2,2,2). When `footprint` is given, `size` is ignored.""")
+_mode_reflect_doc = (
+"""mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
+ The `mode` parameter determines how the input array is extended
+ beyond its boundaries. Default is 'reflect'. Behavior for each valid
+ value is as follows:
+
+ 'reflect' (`d c b a | a b c d | d c b a`)
+ The input is extended by reflecting about the edge of the last
+ pixel. This mode is also sometimes referred to as half-sample
+ symmetric.
+
+ 'constant' (`k k k k | a b c d | k k k k`)
+ The input is extended by filling all values beyond the edge with
+ the same constant value, defined by the `cval` parameter.
+
+ 'nearest' (`a a a a | a b c d | d d d d`)
+ The input is extended by replicating the last pixel.
+
+ 'mirror' (`d c b | a b c d | c b a`)
+ The input is extended by reflecting about the center of the last
+ pixel. This mode is also sometimes referred to as whole-sample
+ symmetric.
+
+ 'wrap' (`a b c d | a b c d | a b c d`)
+ The input is extended by wrapping around to the opposite edge.
+
+ For consistency with the interpolation functions, the following mode
+ names can also be used:
+
+ 'grid-mirror'
+ This is a synonym for 'reflect'.
+
+ 'grid-constant'
+ This is a synonym for 'constant'.
+
+ 'grid-wrap'
+ This is a synonym for 'wrap'.""")
+
+_mode_interp_constant_doc = (
+"""mode : {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', \
+'mirror', 'grid-wrap', 'wrap'}, optional
+ The `mode` parameter determines how the input array is extended
+ beyond its boundaries. Default is 'constant'. Behavior for each valid
+ value is as follows (see additional plots and details on
+ :ref:`boundary modes `):
+
+ 'reflect' (`d c b a | a b c d | d c b a`)
+ The input is extended by reflecting about the edge of the last
+ pixel. This mode is also sometimes referred to as half-sample
+ symmetric.
+
+ 'grid-mirror'
+ This is a synonym for 'reflect'.
+
+ 'constant' (`k k k k | a b c d | k k k k`)
+ The input is extended by filling all values beyond the edge with
+ the same constant value, defined by the `cval` parameter. No
+ interpolation is performed beyond the edges of the input.
+
+ 'grid-constant' (`k k k k | a b c d | k k k k`)
+ The input is extended by filling all values beyond the edge with
+ the same constant value, defined by the `cval` parameter. Interpolation
+ occurs for samples outside the input's extent as well.
+
+ 'nearest' (`a a a a | a b c d | d d d d`)
+ The input is extended by replicating the last pixel.
+
+ 'mirror' (`d c b | a b c d | c b a`)
+ The input is extended by reflecting about the center of the last
+ pixel. This mode is also sometimes referred to as whole-sample
+ symmetric.
+
+ 'grid-wrap' (`a b c d | a b c d | a b c d`)
+ The input is extended by wrapping around to the opposite edge.
+
+ 'wrap' (`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,
+ 'nan': _nan_doc,
+ }
+
+docfiller: Final = doccer.filldoc(docdict)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..dfba8c5ecb112fd8440a9677acf8cf106ffe9834
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_label.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:6bebb5ab33670e0f0005e1f058e37d156849a46103bf4dd6a545347e44dbb8c4
+size 188400
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_support.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..52c526347653b214480f845ec96ab0d9fc72af5d
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_ni_support.py
@@ -0,0 +1,139 @@
+# Copyright (C) 2003-2005 Peter J. Verveer
+#
+# Redistribution and use in source and binary forms, with or without
+# modification, are permitted provided that the following conditions
+# are met:
+#
+# 1. Redistributions of source code must retain the above copyright
+# notice, this list of conditions and the following disclaimer.
+#
+# 2. Redistributions in binary form must reproduce the above
+# copyright notice, this list of conditions and the following
+# disclaimer in the documentation and/or other materials provided
+# with the distribution.
+#
+# 3. The name of the author may not be used to endorse or promote
+# products derived from this software without specific prior
+# written permission.
+#
+# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
+# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
+# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
+# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
+# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
+# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
+# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
+# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
+# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+
+from collections.abc import Iterable
+import operator
+import warnings
+import numpy as np
+
+
+def _extend_mode_to_code(mode, is_filter=False):
+ """Convert an extension mode to the corresponding integer code.
+ """
+ if mode == 'nearest':
+ return 0
+ elif mode == 'wrap':
+ return 1
+ elif mode in ['reflect', 'grid-mirror']:
+ return 2
+ elif mode == 'mirror':
+ return 3
+ elif mode == 'constant':
+ return 4
+ elif mode == 'grid-wrap' and is_filter:
+ return 1
+ elif mode == 'grid-wrap':
+ return 5
+ elif mode == 'grid-constant' and is_filter:
+ return 4
+ elif mode == 'grid-constant':
+ return 6
+ else:
+ raise RuntimeError('boundary mode not supported')
+
+
+def _normalize_sequence(input, rank):
+ """If input is a scalar, create a sequence of length equal to the
+ rank by duplicating the input. If input is a sequence,
+ check if its length is equal to the length of array.
+ """
+ is_str = isinstance(input, str)
+ if not is_str and np.iterable(input):
+ normalized = list(input)
+ if len(normalized) != rank:
+ err = "sequence argument must have length equal to input rank"
+ raise RuntimeError(err)
+ else:
+ normalized = [input] * rank
+ return normalized
+
+
+def _get_output(output, input, shape=None, complex_output=False):
+ if shape is None:
+ shape = input.shape
+ if output is None:
+ if not complex_output:
+ output = np.zeros(shape, dtype=input.dtype.name)
+ else:
+ complex_type = np.promote_types(input.dtype, np.complex64)
+ output = np.zeros(shape, dtype=complex_type)
+ elif isinstance(output, type | np.dtype):
+ # Classes (like `np.float32`) and dtypes are interpreted as dtype
+ if complex_output and np.dtype(output).kind != 'c':
+ warnings.warn("promoting specified output dtype to complex", stacklevel=3)
+ output = np.promote_types(output, np.complex64)
+ output = np.zeros(shape, dtype=output)
+ elif isinstance(output, str):
+ output = np.dtype(output)
+ if complex_output and output.kind != 'c':
+ raise RuntimeError("output must have complex dtype")
+ elif not issubclass(output.type, np.number):
+ raise RuntimeError("output must have numeric dtype")
+ output = np.zeros(shape, dtype=output)
+ else:
+ # output was supplied as an array
+ output = np.asarray(output)
+ if output.shape != shape:
+ raise RuntimeError("output shape not correct")
+ elif complex_output and output.dtype.kind != 'c':
+ raise RuntimeError("output must have complex dtype")
+ return output
+
+
+def _check_axes(axes, ndim):
+ if axes is None:
+ return tuple(range(ndim))
+ elif np.isscalar(axes):
+ axes = (operator.index(axes),)
+ elif isinstance(axes, Iterable):
+ for ax in axes:
+ axes = tuple(operator.index(ax) for ax in axes)
+ if ax < -ndim or ax > ndim - 1:
+ raise ValueError(f"specified axis: {ax} is out of range")
+ axes = tuple(ax % ndim if ax < 0 else ax for ax in axes)
+ else:
+ message = "axes must be an integer, iterable of integers, or None"
+ raise ValueError(message)
+ if len(tuple(set(axes))) != len(axes):
+ raise ValueError("axes must be unique")
+ return axes
+
+def _skip_if_dtype(arg):
+ """'array or dtype' polymorphism.
+
+ Return None for np.int8, dtype('float32') or 'f' etc
+ arg for np.empty(3) etc
+ """
+ if isinstance(arg, str):
+ return None
+ if type(arg) is type:
+ return None if issubclass(arg, np.generic) else arg
+ else:
+ return None if isinstance(arg, np.dtype) else arg
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_rank_filter_1d.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_rank_filter_1d.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..e6b5067700563b3e11daf5302baa99391e020169
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_rank_filter_1d.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_support_alternative_backends.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..e84d30d4543778874c43a18c95f9e4ac18759d2b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/_support_alternative_backends.py
@@ -0,0 +1,120 @@
+import functools
+from scipy._lib._array_api import (
+ is_cupy, is_jax, scipy_namespace_for, SCIPY_ARRAY_API, xp_capabilities
+)
+
+import numpy as np
+from ._ndimage_api import * # noqa: F403
+from . import _ndimage_api
+from . import _delegators
+__all__ = _ndimage_api.__all__
+
+
+MODULE_NAME = 'ndimage'
+
+
+def _maybe_convert_arg(arg, xp):
+ """Convert arrays/scalars hiding in the sequence `arg`."""
+ if isinstance(arg, np.ndarray | np.generic):
+ return xp.asarray(arg)
+ elif isinstance(arg, list | tuple):
+ return type(arg)(_maybe_convert_arg(x, xp) for x in arg)
+ else:
+ return arg
+
+
+# Some cupyx.scipy.ndimage functions don't exist or are incompatible with
+# their SciPy counterparts
+CUPY_BLOCKLIST = [
+ 'distance_transform_bf',
+ 'distance_transform_cdt',
+ 'find_objects',
+ 'geometric_transform',
+ 'vectorized_filter',
+]
+
+
+def delegate_xp(delegator, module_name):
+ def inner(func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwds):
+ xp = delegator(*args, **kwds)
+
+ # try delegating to a cupyx/jax namesake
+ if is_cupy(xp) and func.__name__ not in CUPY_BLOCKLIST:
+ # https://github.com/cupy/cupy/issues/8336
+ import importlib
+ cupyx_module = importlib.import_module(f"cupyx.scipy.{module_name}")
+ cupyx_func = getattr(cupyx_module, func.__name__)
+ return cupyx_func(*args, **kwds)
+ elif is_jax(xp) and func.__name__ == "map_coordinates":
+ spx = scipy_namespace_for(xp)
+ jax_module = getattr(spx, module_name)
+ jax_func = getattr(jax_module, func.__name__)
+ return jax_func(*args, **kwds)
+ else:
+ # the original function (does all np.asarray internally)
+ # XXX: output arrays
+ result = func(*args, **kwds)
+
+ if isinstance(result, np.ndarray | np.generic):
+ # XXX: np.int32->np.array_0D
+ return xp.asarray(result)
+ elif isinstance(result, int):
+ return result
+ elif isinstance(result, dict):
+ # value_indices:
+ # result is {np.int64(1): (array(0), array(1))} etc
+ return {
+ k.item(): tuple(xp.asarray(vv) for vv in v)
+ for k,v in result.items()
+ }
+ elif result is None:
+ # inplace operations
+ return result
+ else:
+ # lists/tuples
+ return _maybe_convert_arg(result, xp)
+ return wrapper
+ return inner
+
+default_capabilities = xp_capabilities(
+ cpu_only=True, exceptions=["cupy"], allow_dask_compute=True, jax_jit=False
+)
+
+capabilities_dict = {
+ "geometric_transform": xp_capabilities(
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
+ ),
+ "find_objects": xp_capabilities(
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
+ ),
+ "distance_transform_bf": xp_capabilities(
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
+ ),
+ "distance_transform_cdt": xp_capabilities(
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
+ ),
+ "vectorized_filter": xp_capabilities(
+ cpu_only=True, allow_dask_compute=True, jax_jit=False
+ ),
+ "generate_binary_structure": xp_capabilities(out_of_scope=True),
+ "map_coordinates": xp_capabilities(
+ cpu_only=True, exceptions=["cupy", "jax.numpy"],
+ allow_dask_compute=True, jax_jit=True
+ )
+}
+
+# ### decorate ###
+for func_name in _ndimage_api.__all__:
+ bare_func = getattr(_ndimage_api, func_name)
+ delegator = getattr(_delegators, func_name + "_signature")
+
+ capabilities = capabilities_dict.get(func_name, default_capabilities)
+
+ f = capabilities(
+ delegate_xp(delegator, MODULE_NAME)(bare_func)
+ if SCIPY_ARRAY_API else bare_func
+ )
+ # add the decorated function to the namespace, to be imported in __init__.py
+ vars()[func_name] = f
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/filters.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..e16d9d279a9585b2454c46ee09cf22143de833a6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/filters.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'correlate1d', 'convolve1d', 'gaussian_filter1d',
+ 'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace',
+ 'laplace', 'gaussian_laplace', 'generic_gradient_magnitude',
+ 'gaussian_gradient_magnitude', 'correlate', 'convolve',
+ 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
+ 'maximum_filter1d', 'minimum_filter', 'maximum_filter',
+ 'rank_filter', 'median_filter', 'percentile_filter',
+ 'generic_filter1d', 'generic_filter'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package='ndimage', module='filters',
+ private_modules=['_filters'], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/fourier.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..73c49bd52d9a446ce0fe25d9e15b8de68fbd46fb
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/fourier.py
@@ -0,0 +1,21 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'fourier_gaussian', 'fourier_uniform',
+ 'fourier_ellipsoid', 'fourier_shift'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package='ndimage', module='fourier',
+ private_modules=['_fourier'], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/interpolation.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2739c60c51037487ae8892c407e2f3d7870d5da
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/interpolation.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'spline_filter1d', 'spline_filter',
+ 'geometric_transform', 'map_coordinates',
+ 'affine_transform', 'shift', 'zoom', 'rotate',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package='ndimage', module='interpolation',
+ private_modules=['_interpolation'], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/measurements.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..22f76b01840ffb829205bd1d28a7ad1f9ac5db61
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/measurements.py
@@ -0,0 +1,24 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'label', 'find_objects', 'labeled_comprehension',
+ 'sum', 'mean', 'variance', 'standard_deviation',
+ 'minimum', 'maximum', 'median', 'minimum_position',
+ 'maximum_position', 'extrema', 'center_of_mass',
+ 'histogram', 'watershed_ift', 'sum_labels'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package='ndimage', module='measurements',
+ private_modules=['_measurements'], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/morphology.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..e522e7df3a4b06b7e04ed8c2d0ecaff2a98b951d
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/morphology.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.ndimage` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'iterate_structure', 'generate_binary_structure',
+ 'binary_erosion', 'binary_dilation', 'binary_opening',
+ 'binary_closing', 'binary_hit_or_miss', 'binary_propagation',
+ 'binary_fill_holes', 'grey_erosion', 'grey_dilation',
+ 'grey_opening', 'grey_closing', 'morphological_gradient',
+ 'morphological_laplace', 'white_tophat', 'black_tophat',
+ 'distance_transform_bf', 'distance_transform_cdt',
+ 'distance_transform_edt'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package='ndimage', module='morphology',
+ private_modules=['_morphology'], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._data b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._data
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._data differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._dots.png b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._dots.png
new file mode 100644
index 0000000000000000000000000000000000000000..1a316d03852d90a87a52d7747cdf1a6805e49e0f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._dots.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:fbd1f4c19356c9f782c0fce50a927d08f5a7a89ae88cc56fe8e671aeba8ef15d
+size 4096
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_c_api.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_c_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_c_api.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_datatypes.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_datatypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_datatypes.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_filters.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_filters.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_fourier.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_fourier.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_interpolation.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_interpolation.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_measurements.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_measurements.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_morphology.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_morphology.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_ni_support.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_ni_support.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_splines.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_splines.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/._test_splines.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..8d8fd292b537a84fe48d0c8ae8bee75bab2b3353
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/__init__.py
@@ -0,0 +1,12 @@
+import numpy as np
+
+# list of numarray data types
+integer_types: list[str] = [
+ "int8", "uint8", "int16", "uint16",
+ "int32", "uint32", "int64", "uint64"]
+
+float_types: list[str] = ["float32", "float64"]
+
+complex_types: list[str] = ["complex64", "complex128"]
+
+types: list[str] = integer_types + float_types
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_inputs.txt b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_inputs.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_inputs.txt differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_results.txt b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_results.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_results.txt differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_strels.txt b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_strels.txt
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/._label_strels.txt differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_inputs.txt b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_inputs.txt
new file mode 100644
index 0000000000000000000000000000000000000000..6c3cff3b12cec4ad050b31cc5d5c327f32784447
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_inputs.txt
@@ -0,0 +1,21 @@
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 0 1 1 1
+1 1 0 0 0 1 1
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+1 1 0 0 0 1 1
+1 1 1 0 1 1 1
+1 0 1 1 1 0 1
+0 0 0 1 0 0 0
+1 0 0 1 0 0 1
+1 1 1 1 1 1 1
+1 0 0 1 0 0 1
+0 0 0 1 0 0 0
+1 0 1 1 1 0 1
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_results.txt b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_results.txt
new file mode 100644
index 0000000000000000000000000000000000000000..c239b0369c9df3e06df9a2fbf048faec2f84941f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_results.txt
@@ -0,0 +1,294 @@
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+2 2 2 2 2 2 2
+3 3 3 3 3 3 3
+4 4 4 4 4 4 4
+5 5 5 5 5 5 5
+6 6 6 6 6 6 6
+7 7 7 7 7 7 7
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 2 3 4 5 6 7
+8 9 10 11 12 13 14
+15 16 17 18 19 20 21
+22 23 24 25 26 27 28
+29 30 31 32 33 34 35
+36 37 38 39 40 41 42
+43 44 45 46 47 48 49
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 2 3 4 5 6 7
+8 1 2 3 4 5 6
+9 8 1 2 3 4 5
+10 9 8 1 2 3 4
+11 10 9 8 1 2 3
+12 11 10 9 8 1 2
+13 12 11 10 9 8 1
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 2 3 4 5 6 7
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+2 1 2 1 2 1 2
+1 2 1 2 1 2 1
+1 2 3 4 5 6 7
+2 3 4 5 6 7 8
+3 4 5 6 7 8 9
+4 5 6 7 8 9 10
+5 6 7 8 9 10 11
+6 7 8 9 10 11 12
+7 8 9 10 11 12 13
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 1 1 1 1
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 2 0 4
+0 0 0 2 0 0 0
+5 0 2 0 6 0 7
+2 2 0 0 0 7 7
+2 2 2 0 7 7 7
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+3 0 1 0 4 0 2
+0 0 0 1 0 0 0
+5 0 6 0 1 0 7
+5 5 0 0 0 1 1
+5 5 5 0 1 1 1
+1 1 1 0 2 2 2
+3 3 0 0 0 4 4
+5 0 6 0 7 0 8
+0 0 0 9 0 0 0
+10 0 11 0 12 0 13
+14 14 0 0 0 15 15
+16 16 16 0 17 17 17
+1 1 1 0 2 3 3
+1 1 0 0 0 3 3
+1 0 4 0 3 0 3
+0 0 0 3 0 0 0
+3 0 3 0 5 0 6
+3 3 0 0 0 6 6
+3 3 7 0 6 6 6
+1 2 3 0 4 5 6
+7 8 0 0 0 9 10
+11 0 12 0 13 0 14
+0 0 0 15 0 0 0
+16 0 17 0 18 0 19
+20 21 0 0 0 22 23
+24 25 26 0 27 28 29
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 2 0 2
+0 0 0 2 0 0 0
+2 0 2 0 4 0 5
+2 2 0 0 0 5 5
+2 2 2 0 5 5 5
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 3 0 4 0 2
+0 0 0 5 0 0 0
+6 0 7 0 8 0 9
+6 6 0 0 0 9 9
+6 6 6 0 9 9 9
+1 2 3 0 4 5 6
+7 1 0 0 0 4 5
+8 0 1 0 9 0 4
+0 0 0 1 0 0 0
+10 0 11 0 1 0 12
+13 10 0 0 0 1 14
+15 13 10 0 16 17 1
+1 2 3 0 4 5 6
+1 2 0 0 0 5 6
+1 0 7 0 8 0 6
+0 0 0 9 0 0 0
+10 0 11 0 12 0 13
+10 14 0 0 0 15 13
+10 14 16 0 17 15 13
+1 1 1 0 1 1 1
+1 1 0 0 0 1 1
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+1 1 0 0 0 1 1
+1 1 1 0 1 1 1
+1 1 2 0 3 3 3
+1 1 0 0 0 3 3
+1 0 1 0 4 0 3
+0 0 0 1 0 0 0
+5 0 6 0 1 0 1
+5 5 0 0 0 1 1
+5 5 5 0 7 1 1
+1 2 1 0 1 3 1
+2 1 0 0 0 1 3
+1 0 1 0 1 0 1
+0 0 0 1 0 0 0
+1 0 1 0 1 0 1
+4 1 0 0 0 1 5
+1 4 1 0 1 5 1
+1 2 3 0 4 5 6
+2 3 0 0 0 6 7
+3 0 8 0 6 0 9
+0 0 0 6 0 0 0
+10 0 6 0 11 0 12
+13 6 0 0 0 12 14
+6 15 16 0 12 14 17
+1 1 1 0 2 2 2
+1 1 0 0 0 2 2
+1 0 1 0 3 0 2
+0 0 0 1 0 0 0
+4 0 5 0 1 0 1
+4 4 0 0 0 1 1
+4 4 4 0 1 1 1
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+4 0 0 5 0 0 5
+5 5 5 5 5 5 5
+5 0 0 5 0 0 6
+0 0 0 7 0 0 0
+8 0 7 7 7 0 9
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+4 0 0 4 0 0 5
+4 4 4 4 4 4 4
+6 0 0 4 0 0 4
+0 0 0 7 0 0 0
+8 0 7 7 7 0 9
+1 0 2 2 2 0 3
+0 0 0 4 0 0 0
+5 0 0 6 0 0 7
+8 8 8 8 8 8 8
+9 0 0 10 0 0 11
+0 0 0 12 0 0 0
+13 0 14 14 14 0 15
+1 0 2 3 3 0 4
+0 0 0 3 0 0 0
+5 0 0 3 0 0 6
+5 5 3 3 3 6 6
+5 0 0 3 0 0 6
+0 0 0 3 0 0 0
+7 0 3 3 8 0 9
+1 0 2 3 4 0 5
+0 0 0 6 0 0 0
+7 0 0 8 0 0 9
+10 11 12 13 14 15 16
+17 0 0 18 0 0 19
+0 0 0 20 0 0 0
+21 0 22 23 24 0 25
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 3 4 0 5
+0 0 0 2 0 0 0
+6 0 0 7 0 0 8
+9 6 10 11 7 12 13
+14 0 0 10 0 0 12
+0 0 0 15 0 0 0
+16 0 17 18 15 0 19
+1 0 2 3 4 0 5
+0 0 0 3 0 0 0
+6 0 0 3 0 0 7
+6 8 9 3 10 11 7
+6 0 0 3 0 0 7
+0 0 0 3 0 0 0
+12 0 13 3 14 0 15
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
+1 0 2 2 3 0 4
+0 0 0 2 0 0 0
+5 0 0 2 0 0 6
+5 5 2 2 2 6 6
+5 0 0 2 0 0 6
+0 0 0 2 0 0 0
+7 0 8 2 2 0 9
+1 0 2 3 2 0 4
+0 0 0 2 0 0 0
+5 0 0 6 0 0 7
+8 5 6 9 6 7 10
+5 0 0 6 0 0 7
+0 0 0 11 0 0 0
+12 0 11 13 11 0 14
+1 0 2 3 4 0 5
+0 0 0 4 0 0 0
+6 0 0 7 0 0 8
+9 10 7 11 12 8 13
+10 0 0 12 0 0 14
+0 0 0 15 0 0 0
+16 0 15 17 18 0 19
+1 0 2 2 2 0 3
+0 0 0 2 0 0 0
+2 0 0 2 0 0 2
+2 2 2 2 2 2 2
+2 0 0 2 0 0 2
+0 0 0 2 0 0 0
+4 0 2 2 2 0 5
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_strels.txt b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_strels.txt
new file mode 100644
index 0000000000000000000000000000000000000000..35ae8121364d4fb3292c11f2a72333f456fa9c0a
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/data/label_strels.txt
@@ -0,0 +1,42 @@
+0 0 1
+1 1 1
+1 0 0
+1 0 0
+1 1 1
+0 0 1
+0 0 0
+1 1 1
+0 0 0
+0 1 1
+0 1 0
+1 1 0
+0 0 0
+0 0 0
+0 0 0
+0 1 1
+1 1 1
+1 1 0
+0 1 0
+1 1 1
+0 1 0
+1 0 0
+0 1 0
+0 0 1
+0 1 0
+0 1 0
+0 1 0
+1 1 1
+1 1 1
+1 1 1
+1 1 0
+0 1 0
+0 1 1
+1 0 1
+0 1 0
+1 0 1
+0 0 1
+0 1 0
+1 0 0
+1 1 0
+1 1 1
+0 1 1
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/dots.png b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/dots.png
new file mode 100644
index 0000000000000000000000000000000000000000..2cb593b8e1cf68e429cc8402838c31f70be59afc
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/dots.png
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:b20b56fadc7471c0694d3e8148d9e28a83d7967bac16bf8852094afea3950414
+size 2114
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_c_api.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_c_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..61a5a0f70262ef9f21fe8593a64f155bd583cab1
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_c_api.py
@@ -0,0 +1,102 @@
+import numpy as np
+from scipy._lib._array_api import xp_assert_close
+
+from scipy import ndimage
+from scipy.ndimage import _ctest
+from scipy.ndimage import _cytest
+from scipy._lib._ccallback import LowLevelCallable
+
+FILTER1D_FUNCTIONS = [
+ lambda filter_size: _ctest.filter1d(filter_size),
+ lambda filter_size: _cytest.filter1d(filter_size, with_signature=False),
+ lambda filter_size: LowLevelCallable(
+ _cytest.filter1d(filter_size, with_signature=True)
+ ),
+ lambda filter_size: LowLevelCallable.from_cython(
+ _cytest, "_filter1d",
+ _cytest.filter1d_capsule(filter_size),
+ ),
+]
+
+FILTER2D_FUNCTIONS = [
+ lambda weights: _ctest.filter2d(weights),
+ lambda weights: _cytest.filter2d(weights, with_signature=False),
+ lambda weights: LowLevelCallable(_cytest.filter2d(weights, with_signature=True)),
+ lambda weights: LowLevelCallable.from_cython(_cytest,
+ "_filter2d",
+ _cytest.filter2d_capsule(weights),),
+]
+
+TRANSFORM_FUNCTIONS = [
+ lambda shift: _ctest.transform(shift),
+ lambda shift: _cytest.transform(shift, with_signature=False),
+ lambda shift: LowLevelCallable(_cytest.transform(shift, with_signature=True)),
+ lambda shift: LowLevelCallable.from_cython(_cytest,
+ "_transform",
+ _cytest.transform_capsule(shift),),
+]
+
+
+def test_generic_filter():
+ def filter2d(footprint_elements, weights):
+ return (weights*footprint_elements).sum()
+
+ def check(j):
+ func = FILTER2D_FUNCTIONS[j]
+
+ im = np.ones((20, 20))
+ im[:10,:10] = 0
+ footprint = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
+ footprint_size = np.count_nonzero(footprint)
+ weights = np.ones(footprint_size)/footprint_size
+
+ res = ndimage.generic_filter(im, func(weights),
+ footprint=footprint)
+ std = ndimage.generic_filter(im, filter2d, footprint=footprint,
+ extra_arguments=(weights,))
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+ for j, func in enumerate(FILTER2D_FUNCTIONS):
+ check(j)
+
+
+def test_generic_filter1d():
+ def filter1d(input_line, output_line, filter_size):
+ for i in range(output_line.size):
+ output_line[i] = 0
+ for j in range(filter_size):
+ output_line[i] += input_line[i+j]
+ output_line /= filter_size
+
+ def check(j):
+ func = FILTER1D_FUNCTIONS[j]
+
+ im = np.tile(np.hstack((np.zeros(10), np.ones(10))), (10, 1))
+ filter_size = 3
+
+ res = ndimage.generic_filter1d(im, func(filter_size),
+ filter_size)
+ std = ndimage.generic_filter1d(im, filter1d, filter_size,
+ extra_arguments=(filter_size,))
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+ for j, func in enumerate(FILTER1D_FUNCTIONS):
+ check(j)
+
+
+def test_geometric_transform():
+ def transform(output_coordinates, shift):
+ return output_coordinates[0] - shift, output_coordinates[1] - shift
+
+ def check(j):
+ func = TRANSFORM_FUNCTIONS[j]
+
+ im = np.arange(12).reshape(4, 3).astype(np.float64)
+ shift = 0.5
+
+ res = ndimage.geometric_transform(im, func(shift))
+ std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,))
+ xp_assert_close(res, std, err_msg=f"#{j} failed")
+
+ for j, func in enumerate(TRANSFORM_FUNCTIONS):
+ check(j)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_datatypes.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_datatypes.py
new file mode 100644
index 0000000000000000000000000000000000000000..a82de456bb92c96d5b9a599d4b33c987e134fdc8
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_datatypes.py
@@ -0,0 +1,67 @@
+""" Testing data types for ndimage calls
+"""
+import numpy as np
+
+from scipy._lib._array_api import assert_array_almost_equal
+import pytest
+
+from scipy import ndimage
+
+
+def test_map_coordinates_dts():
+ # check that ndimage accepts different data types for interpolation
+ data = np.array([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ shifted_data = np.array([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]])
+ idx = np.indices(data.shape)
+ dts = (np.uint8, np.uint16, np.uint32, np.uint64,
+ np.int8, np.int16, np.int32, np.int64,
+ np.intp, np.uintp, np.float32, np.float64)
+ for order in range(0, 6):
+ for data_dt in dts:
+ these_data = data.astype(data_dt)
+ for coord_dt in dts:
+ # affine mapping
+ mat = np.eye(2, dtype=coord_dt)
+ off = np.zeros((2,), dtype=coord_dt)
+ out = ndimage.affine_transform(these_data, mat, off)
+ assert_array_almost_equal(these_data, out)
+ # map coordinates
+ coords_m1 = idx.astype(coord_dt) - 1
+ coords_p10 = idx.astype(coord_dt) + 10
+ out = ndimage.map_coordinates(these_data, coords_m1, order=order)
+ assert_array_almost_equal(out, shifted_data)
+ # check constant fill works
+ out = ndimage.map_coordinates(these_data, coords_p10, order=order)
+ assert_array_almost_equal(out, np.zeros((3,4)))
+ # check shift and zoom
+ out = ndimage.shift(these_data, 1)
+ assert_array_almost_equal(out, shifted_data)
+ out = ndimage.zoom(these_data, 1)
+ assert_array_almost_equal(these_data, out)
+
+
+@pytest.mark.xfail(True, reason="Broken on many platforms")
+def test_uint64_max():
+ # Test interpolation respects uint64 max. Reported to fail at least on
+ # win32 (due to the 32 bit visual C compiler using signed int64 when
+ # converting between uint64 to double) and Debian on s390x.
+ # Interpolation is always done in double precision floating point, so
+ # we use the largest uint64 value for which int(float(big)) still fits
+ # in a uint64.
+ # This test was last enabled on macOS only, and there it started failing
+ # on arm64 as well (see gh-19117).
+ big = 2**64 - 1025
+ arr = np.array([big, big, big], dtype=np.uint64)
+ # Tests geometric transform (map_coordinates, affine_transform)
+ inds = np.indices(arr.shape) - 0.1
+ x = ndimage.map_coordinates(arr, inds)
+ assert x[1] == int(float(big))
+ assert x[2] == int(float(big))
+ # Tests zoom / shift
+ x = ndimage.shift(arr, 0.1)
+ assert x[1] == int(float(big))
+ assert x[2] == int(float(big))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_filters.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..f4b3e97cff3591bd5608b3da6a51a49474282276
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_filters.py
@@ -0,0 +1,3143 @@
+''' Some tests for filters '''
+import functools
+import itertools
+import re
+import contextlib
+import warnings
+
+import numpy as np
+import pytest
+from numpy.testing import assert_allclose, assert_array_equal
+from hypothesis import strategies as st
+from hypothesis import given
+import hypothesis.extra.numpy as npst
+from pytest import raises as assert_raises
+from scipy import ndimage
+from scipy._lib._array_api import (
+ assert_almost_equal,
+ assert_array_almost_equal,
+ xp_assert_close,
+ xp_assert_equal,
+ make_xp_test_case,
+ make_xp_pytest_param,
+)
+from scipy._lib._array_api import (is_cupy, is_torch, is_dask, is_jax, array_namespace,
+ is_array_api_strict, xp_copy)
+from scipy.ndimage._filters import _gaussian_kernel1d
+
+from . import types, float_types, complex_types
+
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+uses_output_dtype = skip_xp_backends(
+ np_only=True, exceptions=["cupy"],
+ reason="output=dtype is numpy-specific"
+)
+
+
+def uses_output_array(f):
+ return skip_xp_backends("dask.array", reason="output=array requires buffer view")(
+ skip_xp_backends("jax.numpy", reason="output=array requires buffer view")(f))
+
+
+
+def sumsq(a, b, xp=None):
+ xp = array_namespace(a, b) if xp is None else xp
+ return xp.sqrt(xp.sum((a - b)**2))
+
+
+def _complex_correlate(xp, array, kernel, real_dtype, convolve=False,
+ mode="reflect", cval=0, ):
+ """Utility to perform a reference complex-valued convolutions.
+
+ When convolve==False, correlation is performed instead
+ """
+ array = xp.asarray(array)
+ kernel = xp.asarray(kernel)
+ complex_array = xp.isdtype(array.dtype, 'complex floating')
+ complex_kernel = xp.isdtype(kernel.dtype, 'complex floating')
+ if array.ndim == 1:
+ func = ndimage.convolve1d if convolve else ndimage.correlate1d
+ else:
+ func = ndimage.convolve if convolve else ndimage.correlate
+ if not convolve:
+ kernel = xp.conj(kernel)
+ if complex_array and complex_kernel:
+ # use: real(cval) for array.real component
+ # imag(cval) for array.imag component
+ re_cval = cval.real if isinstance(cval, complex) else xp.real(cval)
+ im_cval = cval.imag if isinstance(cval, complex) else xp.imag(cval)
+
+ output = (
+ func(xp.real(array), xp.real(kernel), output=real_dtype,
+ mode=mode, cval=re_cval) -
+ func(xp.imag(array), xp.imag(kernel), output=real_dtype,
+ mode=mode, cval=im_cval) +
+ 1j * func(xp.imag(array), xp.real(kernel), output=real_dtype,
+ mode=mode, cval=im_cval) +
+ 1j * func(xp.real(array), xp.imag(kernel), output=real_dtype,
+ mode=mode, cval=re_cval)
+ )
+ elif complex_array:
+ re_cval = xp.real(cval)
+ re_cval = re_cval.item() if isinstance(re_cval, xp.ndarray) else re_cval
+ im_cval = xp.imag(cval)
+ im_cval = im_cval.item() if isinstance(im_cval, xp.ndarray) else im_cval
+
+ output = (
+ func(xp.real(array), kernel, output=real_dtype, mode=mode,
+ cval=re_cval) +
+ 1j * func(xp.imag(array), kernel, output=real_dtype, mode=mode,
+ cval=im_cval)
+ )
+ elif complex_kernel:
+ # real array so cval is real too
+ output = (
+ func(array, xp.real(kernel), output=real_dtype, mode=mode, cval=cval) +
+ 1j * func(array, xp.imag(kernel), output=real_dtype, mode=mode,
+ cval=cval)
+ )
+ return output
+
+
+def _cases_axes_tuple_length_mismatch():
+ # Generate combinations of filter function, valid kwargs, and
+ # keyword-value pairs for which the value will become with mismatched
+ # (invalid) size
+ filter_func = ndimage.gaussian_filter
+ kwargs = dict(radius=3, mode='constant', sigma=1.0, order=0)
+ for key, val in kwargs.items():
+ yield filter_func, kwargs, key, val
+
+ filter_funcs = [ndimage.uniform_filter, ndimage.minimum_filter,
+ ndimage.maximum_filter]
+ kwargs = dict(size=3, mode='constant', origin=0)
+ for filter_func in filter_funcs:
+ for key, val in kwargs.items():
+ yield filter_func, kwargs, key, val
+
+ filter_funcs = [ndimage.correlate, ndimage.convolve]
+ # sequence of mode not supported for correlate or convolve
+ kwargs = dict(origin=0)
+ for filter_func in filter_funcs:
+ for key, val in kwargs.items():
+ yield filter_func, kwargs, key, val
+
+
+@make_xp_test_case(ndimage.correlate, ndimage.correlate1d,
+ ndimage.convolve, ndimage.convolve1d)
+class TestNdimageFilters:
+ def _validate_complex(self, xp, array, kernel, type2, mode='reflect',
+ cval=0, check_warnings=True):
+ # utility for validating complex-valued correlations
+ real_dtype = xp.real(xp.asarray([], dtype=type2)).dtype
+ expected = _complex_correlate(
+ xp, array, kernel, real_dtype, convolve=False, mode=mode, cval=cval
+ )
+
+ if array.ndim == 1:
+ correlate = functools.partial(ndimage.correlate1d, axis=-1,
+ mode=mode, cval=cval)
+ convolve = functools.partial(ndimage.convolve1d, axis=-1,
+ mode=mode, cval=cval)
+ else:
+ correlate = functools.partial(ndimage.correlate, mode=mode,
+ cval=cval)
+ convolve = functools.partial(ndimage.convolve, mode=mode,
+ cval=cval)
+
+ # test correlate output dtype
+ output = correlate(array, kernel, output=type2)
+ assert_array_almost_equal(expected, output)
+ assert output.dtype.type == type2
+
+ # test correlate with pre-allocated output
+ output = xp.zeros_like(array, dtype=type2)
+ correlate(array, kernel, output=output)
+ assert_array_almost_equal(expected, output)
+
+ # test convolve output dtype
+ output = convolve(array, kernel, output=type2)
+ expected = _complex_correlate(
+ xp, array, kernel, real_dtype, convolve=True, mode=mode, cval=cval,
+ )
+ assert_array_almost_equal(expected, output)
+ assert output.dtype.type == type2
+
+ # convolve with pre-allocated output
+ convolve(array, kernel, output=output)
+ assert_array_almost_equal(expected, output)
+ assert output.dtype.type == type2
+
+ if check_warnings:
+ # warns if the output is not a complex dtype
+ with pytest.warns(UserWarning,
+ match="promoting specified output dtype to "
+ "complex"):
+ correlate(array, kernel, output=real_dtype)
+
+ with pytest.warns(UserWarning,
+ match="promoting specified output dtype to "
+ "complex"):
+ convolve(array, kernel, output=real_dtype)
+
+ # raises if output array is provided, but is not complex-valued
+ output_real = xp.zeros_like(array, dtype=real_dtype)
+ with assert_raises(RuntimeError):
+ correlate(array, kernel, output=output_real)
+
+ with assert_raises(RuntimeError):
+ convolve(array, kernel, output=output_real)
+
+ def test_correlate01(self, xp):
+ array = xp.asarray([1, 2])
+ weights = xp.asarray([2])
+ expected = xp.asarray([2, 4])
+
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ @xfail_xp_backends('cupy', reason="Differs by a factor of two?")
+ @uses_output_array
+ def test_correlate01_overlap(self, xp):
+ array = xp.reshape(xp.arange(256), (16, 16))
+ weights = xp.asarray([2])
+ expected = 2 * array
+
+ ndimage.correlate1d(array, weights, output=array)
+ assert_array_almost_equal(array, expected)
+
+ def test_correlate02(self, xp):
+ array = xp.asarray([1, 2, 3])
+ kernel = xp.asarray([1])
+
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ output = ndimage.correlate1d(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ output = ndimage.convolve1d(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ def test_correlate03(self, xp):
+ array = xp.asarray([1])
+ weights = xp.asarray([1, 1])
+ expected = xp.asarray([2])
+
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ def test_correlate04(self, xp):
+ array = xp.asarray([1, 2])
+ tcor = xp.asarray([2, 3])
+ tcov = xp.asarray([3, 4])
+ weights = xp.asarray([1, 1])
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, tcov)
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, tcov)
+
+ def test_correlate05(self, xp):
+ array = xp.asarray([1, 2, 3])
+ tcor = xp.asarray([2, 3, 5])
+ tcov = xp.asarray([3, 5, 6])
+ kernel = xp.asarray([1, 1])
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(tcor, output)
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(tcov, output)
+ output = ndimage.correlate1d(array, kernel)
+ assert_array_almost_equal(tcor, output)
+ output = ndimage.convolve1d(array, kernel)
+ assert_array_almost_equal(tcov, output)
+
+ def test_correlate06(self, xp):
+ array = xp.asarray([1, 2, 3])
+ tcor = xp.asarray([9, 14, 17])
+ tcov = xp.asarray([7, 10, 15])
+ weights = xp.asarray([1, 2, 3])
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, tcov)
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, tcov)
+
+ def test_correlate07(self, xp):
+ array = xp.asarray([1, 2, 3])
+ expected = xp.asarray([5, 8, 11])
+ weights = xp.asarray([1, 2, 1])
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, expected)
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, expected)
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, expected)
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, expected)
+
+ def test_correlate08(self, xp):
+ array = xp.asarray([1, 2, 3])
+ tcor = xp.asarray([1, 2, 5])
+ tcov = xp.asarray([3, 6, 7])
+ weights = xp.asarray([1, 2, -1])
+ output = ndimage.correlate(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve(array, weights)
+ assert_array_almost_equal(output, tcov)
+ output = ndimage.correlate1d(array, weights)
+ assert_array_almost_equal(output, tcor)
+ output = ndimage.convolve1d(array, weights)
+ assert_array_almost_equal(output, tcov)
+
+ def test_correlate09(self, xp):
+ array = xp.asarray([])
+ kernel = xp.asarray([1, 1])
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(array, output)
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(array, output)
+ output = ndimage.correlate1d(array, kernel)
+ assert_array_almost_equal(array, output)
+ output = ndimage.convolve1d(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ def test_correlate10(self, xp):
+ array = xp.asarray([[]])
+ kernel = xp.asarray([[1, 1]])
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(array, output)
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(array, output)
+
+ def test_correlate11(self, xp):
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]])
+ kernel = xp.asarray([[1, 1],
+ [1, 1]])
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output)
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(xp.asarray([[12, 16, 18], [18, 22, 24]]), output)
+
+ def test_correlate12(self, xp):
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]])
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ output = ndimage.correlate(array, kernel)
+ assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+ output = ndimage.convolve(array, kernel)
+ assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_kernel', types)
+ def test_correlate13(self, dtype_array, dtype_kernel, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_kernel = getattr(xp, dtype_kernel)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_array)
+ output = ndimage.correlate(array, kernel, output=dtype_kernel)
+ assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+ assert output.dtype.type == dtype_kernel
+
+ output = ndimage.convolve(array, kernel,
+ output=dtype_kernel)
+ assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+ assert output.dtype.type == dtype_kernel
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ def test_correlate14(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_array)
+ output = xp.zeros(array.shape, dtype=dtype_output)
+ ndimage.correlate(array, kernel, output=output)
+ assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+ assert output.dtype == dtype_output
+
+ ndimage.convolve(array, kernel, output=output)
+ assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+ assert output.dtype == dtype_output
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ def test_correlate15(self, dtype_array, xp):
+ dtype_array = getattr(xp, dtype_array)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_array)
+ output = ndimage.correlate(array, kernel, output=xp.float32)
+ assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+ assert output.dtype.type == xp.float32
+
+ output = ndimage.convolve(array, kernel, output=xp.float32)
+ assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+ assert output.dtype.type == xp.float32
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ def test_correlate16(self, dtype_array, xp):
+ dtype_array = getattr(xp, dtype_array)
+
+ kernel = xp.asarray([[0.5, 0],
+ [0, 0.5]])
+ array = xp.asarray([[1, 2, 3], [4, 5, 6]], dtype=dtype_array)
+ output = ndimage.correlate(array, kernel, output=xp.float32)
+ assert_array_almost_equal(xp.asarray([[1, 1.5, 2.5], [2.5, 3, 4]]), output)
+ assert output.dtype.type == xp.float32
+
+ output = ndimage.convolve(array, kernel, output=xp.float32)
+ assert_array_almost_equal(xp.asarray([[3, 4, 4.5], [4.5, 5.5, 6]]), output)
+ assert output.dtype.type == xp.float32
+
+ def test_correlate17(self, xp):
+ array = xp.asarray([1, 2, 3])
+ tcor = xp.asarray([3, 5, 6])
+ tcov = xp.asarray([2, 3, 5])
+ kernel = xp.asarray([1, 1])
+ output = ndimage.correlate(array, kernel, origin=-1)
+ assert_array_almost_equal(tcor, output)
+ output = ndimage.convolve(array, kernel, origin=-1)
+ assert_array_almost_equal(tcov, output)
+ output = ndimage.correlate1d(array, kernel, origin=-1)
+ assert_array_almost_equal(tcor, output)
+ output = ndimage.convolve1d(array, kernel, origin=-1)
+ assert_array_almost_equal(tcov, output)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ def test_correlate18(self, dtype_array, xp):
+ dtype_array = getattr(xp, dtype_array)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_array)
+ output = ndimage.correlate(array, kernel,
+ output=xp.float32,
+ mode='nearest', origin=-1)
+ assert_array_almost_equal(xp.asarray([[6, 8, 9], [9, 11, 12]]), output)
+ assert output.dtype.type == xp.float32
+
+ output = ndimage.convolve(array, kernel,
+ output=xp.float32,
+ mode='nearest', origin=-1)
+ assert_array_almost_equal(xp.asarray([[2, 3, 5], [5, 6, 8]]), output)
+ assert output.dtype.type == xp.float32
+
+ def test_correlate_mode_sequence(self, xp):
+ kernel = xp.ones((2, 2))
+ array = xp.ones((3, 3), dtype=xp.float64)
+ with assert_raises(RuntimeError):
+ ndimage.correlate(array, kernel, mode=['nearest', 'reflect'])
+ with assert_raises(RuntimeError):
+ ndimage.convolve(array, kernel, mode=['nearest', 'reflect'])
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ def test_correlate19(self, dtype_array, xp):
+ dtype_array = getattr(xp, dtype_array)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]])
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_array)
+ output = ndimage.correlate(array, kernel,
+ output=xp.float32,
+ mode='nearest', origin=[-1, 0])
+ assert_array_almost_equal(xp.asarray([[5, 6, 8], [8, 9, 11]]), output)
+ assert output.dtype.type == xp.float32
+
+ output = ndimage.convolve(array, kernel,
+ output=xp.float32,
+ mode='nearest', origin=[-1, 0])
+ assert_array_almost_equal(xp.asarray([[3, 5, 6], [6, 8, 9]]), output)
+ assert output.dtype.type == xp.float32
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ def test_correlate20(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ weights = xp.asarray([1, 2, 1])
+ expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=dtype_array)
+ output = xp.zeros((2, 3), dtype=dtype_output)
+ ndimage.correlate1d(array, weights, axis=0, output=output)
+ assert_array_almost_equal(output, expected)
+ ndimage.convolve1d(array, weights, axis=0, output=output)
+ assert_array_almost_equal(output, expected)
+
+ def test_correlate21(self, xp):
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]])
+ expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+ weights = xp.asarray([1, 2, 1])
+ output = ndimage.correlate1d(array, weights, axis=0)
+ assert_array_almost_equal(output, expected)
+ output = ndimage.convolve1d(array, weights, axis=0)
+ assert_array_almost_equal(output, expected)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ def test_correlate22(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ weights = xp.asarray([1, 2, 1])
+ expected = xp.asarray([[6, 12, 18], [6, 12, 18]])
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=dtype_array)
+ output = xp.zeros((2, 3), dtype=dtype_output)
+ ndimage.correlate1d(array, weights, axis=0,
+ mode='wrap', output=output)
+ assert_array_almost_equal(output, expected)
+ ndimage.convolve1d(array, weights, axis=0,
+ mode='wrap', output=output)
+ assert_array_almost_equal(output, expected)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ def test_correlate23(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ weights = xp.asarray([1, 2, 1])
+ expected = xp.asarray([[5, 10, 15], [7, 14, 21]])
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=dtype_array)
+ output = xp.zeros((2, 3), dtype=dtype_output)
+ ndimage.correlate1d(array, weights, axis=0,
+ mode='nearest', output=output)
+ assert_array_almost_equal(output, expected)
+ ndimage.convolve1d(array, weights, axis=0,
+ mode='nearest', output=output)
+ assert_array_almost_equal(output, expected)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ def test_correlate24(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ weights = xp.asarray([1, 2, 1])
+ tcor = xp.asarray([[7, 14, 21], [8, 16, 24]])
+ tcov = xp.asarray([[4, 8, 12], [5, 10, 15]])
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=dtype_array)
+ output = xp.zeros((2, 3), dtype=dtype_output)
+ ndimage.correlate1d(array, weights, axis=0,
+ mode='nearest', output=output, origin=-1)
+ assert_array_almost_equal(output, tcor)
+ ndimage.convolve1d(array, weights, axis=0,
+ mode='nearest', output=output, origin=-1)
+ assert_array_almost_equal(output, tcov)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ def test_correlate25(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ weights = xp.asarray([1, 2, 1])
+ tcor = xp.asarray([[4, 8, 12], [5, 10, 15]])
+ tcov = xp.asarray([[7, 14, 21], [8, 16, 24]])
+ array = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=dtype_array)
+ output = xp.zeros((2, 3), dtype=dtype_output)
+ ndimage.correlate1d(array, weights, axis=0,
+ mode='nearest', output=output, origin=1)
+ assert_array_almost_equal(output, tcor)
+ ndimage.convolve1d(array, weights, axis=0,
+ mode='nearest', output=output, origin=1)
+ assert_array_almost_equal(output, tcov)
+
+ def test_correlate26(self, xp):
+ # test fix for gh-11661 (mirror extension of a length 1 signal)
+ y = ndimage.convolve1d(xp.ones(1), xp.ones(5), mode='mirror')
+ xp_assert_equal(y, xp.asarray([5.]))
+
+ y = ndimage.correlate1d(xp.ones(1), xp.ones(5), mode='mirror')
+ xp_assert_equal(y, xp.asarray([5.]))
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', complex_types)
+ @pytest.mark.parametrize('dtype_input', types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ def test_correlate_complex_kernel(self, dtype_input, dtype_kernel,
+ dtype_output, xp, num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1 + 1j]], dtype=dtype_kernel)
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', complex_types)
+ @pytest.mark.parametrize('dtype_input', types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ @pytest.mark.parametrize('mode', ['grid-constant', 'constant'])
+ def test_correlate_complex_kernel_cval(self, dtype_input, dtype_kernel,
+ dtype_output, mode, xp,
+ num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ if is_cupy(xp) and mode == 'grid-constant':
+ pytest.xfail('cupy/cupy#8404')
+
+ # test use of non-zero cval with complex inputs
+ # also verifies that mode 'grid-constant' does not segfault
+ kernel = xp.asarray([[1, 0],
+ [0, 1 + 1j]], dtype=dtype_kernel)
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output, mode=mode,
+ cval=5.0,
+ check_warnings=num_parallel_threads == 1)
+
+ @xfail_xp_backends('cupy', reason="cupy/cupy#8405")
+ @pytest.mark.parametrize('dtype_kernel', complex_types)
+ @pytest.mark.parametrize('dtype_input', types)
+ def test_correlate_complex_kernel_invalid_cval(self, dtype_input,
+ dtype_kernel, xp):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+
+ # cannot give complex cval with a real image
+ kernel = xp.asarray([[1, 0],
+ [0, 1 + 1j]], dtype=dtype_kernel)
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype_input)
+ for func in [ndimage.convolve, ndimage.correlate, ndimage.convolve1d,
+ ndimage.correlate1d]:
+ with pytest.raises((ValueError, TypeError)):
+ func(array, kernel, mode='constant', cval=5.0 + 1.0j,
+ output=xp.complex64)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', complex_types)
+ @pytest.mark.parametrize('dtype_input', types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ def test_correlate1d_complex_kernel(self, dtype_input, dtype_kernel,
+ dtype_output, xp, num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel)
+ array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', complex_types)
+ @pytest.mark.parametrize('dtype_input', types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ def test_correlate1d_complex_kernel_cval(self, dtype_input, dtype_kernel,
+ dtype_output, xp,
+ num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 1 + 1j], dtype=dtype_kernel)
+ array = xp.asarray([1, 2, 3, 4, 5, 6], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+ cval=5.0,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', types)
+ @pytest.mark.parametrize('dtype_input', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ def test_correlate_complex_input(self, dtype_input, dtype_kernel,
+ dtype_output, xp, num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1]], dtype=dtype_kernel)
+ array = xp.asarray([[1, 2j, 3],
+ [1 + 4j, 5, 6j]], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_kernel', types)
+ @pytest.mark.parametrize('dtype_input', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ def test_correlate1d_complex_input(self, dtype_input, dtype_kernel,
+ dtype_output, xp, num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel)
+ array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @xfail_xp_backends("cupy", reason="cupy/cupy#8405")
+ @pytest.mark.parametrize('dtype_kernel', types)
+ @pytest.mark.parametrize('dtype_input', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ def test_correlate1d_complex_input_cval(self, dtype_input, dtype_kernel,
+ dtype_output, xp,
+ num_parallel_threads):
+ dtype_input = getattr(xp, dtype_input)
+ dtype_kernel = getattr(xp, dtype_kernel)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 0, 1], dtype=dtype_kernel)
+ array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype_input)
+ self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+ cval=5 - 3j,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @xfail_xp_backends("cupy", reason="unhashable type: 'ndarray'")
+ @pytest.mark.parametrize('dtype', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ def test_correlate_complex_input_and_kernel(self, dtype, dtype_output, xp,
+ num_parallel_threads):
+ dtype = getattr(xp, dtype)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1 + 1j]], dtype=dtype)
+ array = xp.asarray([[1, 2j, 3],
+ [1 + 4j, 5, 6j]], dtype=dtype)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @xfail_xp_backends("cupy", reason="cupy/cupy#8405")
+ @pytest.mark.parametrize('dtype', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ def test_correlate_complex_input_and_kernel_cval(self, dtype,
+ dtype_output, xp,
+ num_parallel_threads):
+ dtype = getattr(xp, dtype)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([[1, 0],
+ [0, 1 + 1j]], dtype=dtype)
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=dtype)
+ self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+ cval=5.0 + 2.0j,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @xfail_xp_backends("cupy", reason="unhashable type: 'ndarray'")
+ @pytest.mark.parametrize('dtype', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ def test_correlate1d_complex_input_and_kernel(self, dtype, dtype_output, xp,
+ num_parallel_threads):
+ dtype = getattr(xp, dtype)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 1 + 1j], dtype=dtype)
+ array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype)
+ self._validate_complex(xp, array, kernel, dtype_output,
+ check_warnings=num_parallel_threads == 1)
+
+ @uses_output_dtype
+ @xfail_xp_backends("cupy", reason="cupy/cupy#8405")
+ @pytest.mark.parametrize('dtype', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ def test_correlate1d_complex_input_and_kernel_cval(self, dtype,
+ dtype_output, xp,
+ num_parallel_threads):
+
+ dtype = getattr(xp, dtype)
+ dtype_output = getattr(xp, dtype_output)
+
+ kernel = xp.asarray([1, 1 + 1j], dtype=dtype)
+ array = xp.asarray([1, 2j, 3, 1 + 4j, 5, 6j], dtype=dtype)
+ self._validate_complex(xp, array, kernel, dtype_output, mode='constant',
+ cval=5.0 + 2.0j,
+ check_warnings=num_parallel_threads == 1)
+
+ def test_gauss01(self, xp):
+ input = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=xp.float32)
+ output = ndimage.gaussian_filter(input, 0)
+ assert_array_almost_equal(output, input)
+
+ def test_gauss02(self, xp):
+ input = xp.asarray([[1, 2, 3],
+ [2, 4, 6]], dtype=xp.float32)
+ output = ndimage.gaussian_filter(input, 1.0)
+ assert input.dtype == output.dtype
+ assert input.shape == output.shape
+
+ @xfail_xp_backends("cupy", reason="cupy/cupy#8403")
+ def test_gauss03(self, xp):
+ # single precision data
+ input = xp.arange(100 * 100, dtype=xp.float32)
+ input = xp.reshape(input, (100, 100))
+ output = ndimage.gaussian_filter(input, [1.0, 1.0])
+
+ assert input.dtype == output.dtype
+ assert input.shape == output.shape
+
+ # input.sum() is 49995000.0. With single precision floats, we can't
+ # expect more than 8 digits of accuracy, so use decimal=0 in this test.
+ o_sum = xp.sum(output, dtype=xp.float64)
+ i_sum = xp.sum(input, dtype=xp.float64)
+ assert_almost_equal(o_sum, i_sum, decimal=0)
+ assert sumsq(input, output) > 1.0
+
+ @uses_output_dtype
+ def test_gauss04(self, xp):
+ input = xp.arange(100 * 100, dtype=xp.float32)
+ input = xp.reshape(input, (100, 100))
+ otype = xp.float64
+ output = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype)
+ assert output.dtype.type == xp.float64
+ assert input.shape == output.shape
+ assert sumsq(input, output) > 1.0
+
+ @uses_output_dtype
+ def test_gauss05(self, xp):
+ input = xp.arange(100 * 100, dtype=xp.float32)
+ input = xp.reshape(input, (100, 100))
+ otype = xp.float64
+ output = ndimage.gaussian_filter(input, [1.0, 1.0],
+ order=1, output=otype)
+ assert output.dtype.type == xp.float64
+ assert input.shape == output.shape
+ assert sumsq(input, output) > 1.0
+
+ @uses_output_dtype
+ def test_gauss06(self, xp):
+ input = xp.arange(100 * 100, dtype=xp.float32)
+ input = xp.reshape(input, (100, 100))
+ otype = xp.float64
+ output1 = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype)
+ output2 = ndimage.gaussian_filter(input, 1.0, output=otype)
+ assert_array_almost_equal(output1, output2)
+
+ @uses_output_array
+ def test_gauss_memory_overlap(self, xp):
+ input = xp.arange(100 * 100, dtype=xp.float32)
+ input = xp.reshape(input, (100, 100))
+ output1 = ndimage.gaussian_filter(input, 1.0)
+ ndimage.gaussian_filter(input, 1.0, output=input)
+ assert_array_almost_equal(output1, input)
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize(('filter_func', 'extra_args', 'size0', 'size'),
+ [(ndimage.gaussian_filter, (), 0, 1.0),
+ (ndimage.uniform_filter, (), 1, 3),
+ (ndimage.minimum_filter, (), 1, 3),
+ (ndimage.maximum_filter, (), 1, 3),
+ (ndimage.median_filter, (), 1, 3),
+ (ndimage.rank_filter, (1,), 1, 3),
+ (ndimage.percentile_filter, (40,), 1, 3)])
+ @pytest.mark.parametrize(
+ 'axes',
+ tuple(itertools.combinations(range(-3, 3), 1))
+ + tuple(itertools.combinations(range(-3, 3), 2))
+ + ((0, 1, 2),))
+ def test_filter_axes(self, filter_func, extra_args, size0, size, axes, xp):
+ # Note: `size` is called `sigma` in `gaussian_filter`
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+
+ if len(set(ax % array.ndim for ax in axes)) != len(axes):
+ # parametrized cases with duplicate axes raise an error
+ with pytest.raises(ValueError, match="axes must be unique"):
+ filter_func(array, *extra_args, size, axes=axes)
+ return
+ output = filter_func(array, *extra_args, size, axes=axes)
+
+ # result should be equivalent to sigma=0.0/size=1 on unfiltered axes
+ axes = xp.asarray(axes)
+ all_sizes = tuple(size if ax in (axes % array.ndim) else size0
+ for ax in range(array.ndim))
+ expected = filter_func(array, *extra_args, all_sizes)
+ xp_assert_close(output, expected)
+
+ @skip_xp_backends("cupy",
+ reason="these filters do not yet have axes support")
+ @pytest.mark.parametrize(('filter_func', 'kwargs'),
+ [(ndimage.laplace, {}),
+ (ndimage.gaussian_gradient_magnitude,
+ {"sigma": 1.0}),
+ (ndimage.gaussian_laplace, {"sigma": 0.5})])
+ def test_derivative_filter_axes(self, xp, filter_func, kwargs):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+
+ # duplicate axes raises an error
+ with pytest.raises(ValueError, match="axes must be unique"):
+ filter_func(array, axes=(1, 1), **kwargs)
+
+ # compare results to manually looping over the non-filtered axes
+ output = filter_func(array, axes=(1, 2), **kwargs)
+ expected = xp.empty_like(output)
+ expected = []
+ for i in range(array.shape[0]):
+ expected.append(filter_func(array[i, ...], **kwargs))
+ expected = xp.stack(expected, axis=0)
+ xp_assert_close(output, expected)
+
+ output = filter_func(array, axes=(0, -1), **kwargs)
+ expected = []
+ for i in range(array.shape[1]):
+ expected.append(filter_func(array[:, i, :], **kwargs))
+ expected = xp.stack(expected, axis=1)
+ xp_assert_close(output, expected)
+
+ output = filter_func(array, axes=(1), **kwargs)
+ expected = []
+ for i in range(array.shape[0]):
+ exp_inner = []
+ for j in range(array.shape[2]):
+ exp_inner.append(filter_func(array[i, :, j], **kwargs))
+ expected.append(xp.stack(exp_inner, axis=-1))
+ expected = xp.stack(expected, axis=0)
+ xp_assert_close(output, expected)
+
+ @skip_xp_backends("cupy",
+ reason="generic_filter does not yet have axes support")
+ @pytest.mark.parametrize(
+ 'axes',
+ tuple(itertools.combinations(range(-3, 3), 1))
+ + tuple(itertools.combinations(range(-3, 3), 2))
+ + ((0, 1, 2),))
+ def test_generic_filter_axes(self, xp, axes):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+ size = 3
+ if len(set(ax % array.ndim for ax in axes)) != len(axes):
+ # parametrized cases with duplicate axes raise an error
+ with pytest.raises(ValueError, match="axes must be unique"):
+ ndimage.generic_filter(array, np.amax, size=size, axes=axes)
+ return
+
+ # choose np.amax as the function so we can compare to maximum_filter
+ output = ndimage.generic_filter(array, np.amax, size=size, axes=axes)
+ expected = ndimage.maximum_filter(array, size=size, axes=axes)
+ xp_assert_close(output, expected)
+
+ @skip_xp_backends("cupy",
+ reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize('func', [ndimage.correlate, ndimage.convolve])
+ @pytest.mark.parametrize(
+ 'dtype', [np.float32, np.float64, np.complex64, np.complex128]
+ )
+ @pytest.mark.parametrize(
+ 'axes', tuple(itertools.combinations(range(-3, 3), 2))
+ )
+ @pytest.mark.parametrize('origin', [(0, 0), (-1, 1)])
+ def test_correlate_convolve_axes(self, xp, func, dtype, axes, origin):
+ array = xp.asarray(np.arange(6 * 8 * 12, dtype=dtype).reshape(6, 8, 12))
+ weights = xp.arange(3 * 5)
+ weights = xp.reshape(weights, (3, 5))
+ axes = tuple(ax % array.ndim for ax in axes)
+ if len(tuple(set(axes))) != len(axes):
+ # parametrized cases with duplicate axes raise an error
+ with pytest.raises(ValueError):
+ func(array, weights=weights, axes=axes, origin=origin)
+ return
+ output = func(array, weights=weights, axes=axes, origin=origin)
+
+ missing_axis = tuple(set(range(3)) - set(axes))[0]
+ # module 'torch' has no attribute 'expand_dims' so use reshape instead
+ # weights_3d = xp.expand_dims(weights, axis=missing_axis)
+ shape_3d = (
+ weights.shape[:missing_axis] + (1,) + weights.shape[missing_axis:]
+ )
+ weights_3d = xp.reshape(weights, shape_3d)
+ origin_3d = [0, 0, 0]
+ for i, ax in enumerate(axes):
+ origin_3d[ax] = origin[i]
+ expected = func(array, weights=weights_3d, origin=origin_3d)
+ xp_assert_close(output, expected)
+
+ kwargs_gauss = dict(radius=[4, 2, 3], order=[0, 1, 2],
+ mode=['reflect', 'nearest', 'constant'])
+ kwargs_other = dict(origin=(-1, 0, 1),
+ mode=['reflect', 'nearest', 'constant'])
+ kwargs_rank = dict(origin=(-1, 0, 1))
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize("filter_func, size0, size, kwargs",
+ [(ndimage.gaussian_filter, 0, 1.0, kwargs_gauss),
+ (ndimage.uniform_filter, 1, 3, kwargs_other),
+ (ndimage.maximum_filter, 1, 3, kwargs_other),
+ (ndimage.minimum_filter, 1, 3, kwargs_other),
+ (ndimage.median_filter, 1, 3, kwargs_rank),
+ (ndimage.rank_filter, 1, 3, kwargs_rank),
+ (ndimage.percentile_filter, 1, 3, kwargs_rank)])
+ @pytest.mark.parametrize('axes', itertools.combinations(range(-3, 3), 2))
+ def test_filter_axes_kwargs(self, filter_func, size0, size, kwargs, axes, xp):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+
+ kwargs = {key: np.array(val) for key, val in kwargs.items()}
+ axes = np.array(axes)
+ n_axes = axes.size
+
+ if filter_func == ndimage.rank_filter:
+ args = (2,) # (rank,)
+ elif filter_func == ndimage.percentile_filter:
+ args = (30,) # (percentile,)
+ else:
+ args = ()
+
+ # form kwargs that specify only the axes in `axes`
+ reduced_kwargs = {key: val[axes] for key, val in kwargs.items()}
+ if len(set(axes % array.ndim)) != len(axes):
+ # parametrized cases with duplicate axes raise an error
+ with pytest.raises(ValueError, match="axes must be unique"):
+ filter_func(array, *args, [size]*n_axes, axes=axes,
+ **reduced_kwargs)
+ return
+
+ output = filter_func(array, *args, [size]*n_axes, axes=axes,
+ **reduced_kwargs)
+
+ # result should be equivalent to sigma=0.0/size=1 on unfiltered axes
+ size_3d = np.full(array.ndim, fill_value=size0)
+ size_3d[axes] = size
+ size_3d = [size_3d[i] for i in range(size_3d.shape[0])]
+ if 'origin' in kwargs:
+ # origin should be zero on the axis that has size 0
+ origin = np.asarray([0, 0, 0])
+ origin[axes] = reduced_kwargs['origin']
+ origin = xp.asarray(origin)
+ kwargs['origin'] = origin
+ expected = filter_func(array, *args, size_3d, **kwargs)
+ xp_assert_close(output, expected)
+
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize("filter_func, kwargs",
+ [(ndimage.convolve, {}),
+ (ndimage.correlate, {}),
+ (ndimage.minimum_filter, {}),
+ (ndimage.maximum_filter, {}),
+ (ndimage.median_filter, {}),
+ (ndimage.rank_filter, {"rank": 1}),
+ (ndimage.percentile_filter, {"percentile": 30})])
+ def test_filter_weights_subset_axes_origins(self, filter_func, kwargs, xp):
+ axes = (-2, -1)
+ origins = (0, 1)
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+
+ # weights with ndim matching len(axes)
+ footprint = np.ones((3, 5), dtype=bool)
+ footprint[0, 1] = 0 # make non-separable
+ footprint = xp.asarray(footprint)
+
+ if filter_func in (ndimage.convolve, ndimage.correlate):
+ kwargs["weights"] = footprint
+ else:
+ kwargs["footprint"] = footprint
+ kwargs["axes"] = axes
+
+ output = filter_func(array, origin=origins, **kwargs)
+
+ output0 = filter_func(array, origin=0, **kwargs)
+
+ # output has origin shift on last axis relative to output0, so
+ # expect shifted arrays to be equal.
+ if filter_func == ndimage.convolve:
+ # shift is in the opposite direction for convolve because it
+ # flips the weights array and negates the origin values.
+ xp_assert_equal(
+ output[:, :, :-origins[1]], output0[:, :, origins[1]:])
+ else:
+ xp_assert_equal(
+ output[:, :, origins[1]:], output0[:, :, :-origins[1]])
+
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize(
+ 'filter_func, args',
+ [(ndimage.convolve, (np.ones((3, 3, 3)),)), # args = (weights,)
+ (ndimage.correlate,(np.ones((3, 3, 3)),)), # args = (weights,)
+ (ndimage.gaussian_filter, (1.0,)), # args = (sigma,)
+ (ndimage.uniform_filter, (3,)), # args = (size,)
+ (ndimage.minimum_filter, (3,)), # args = (size,)
+ (ndimage.maximum_filter, (3,)), # args = (size,)
+ (ndimage.median_filter, (3,)), # args = (size,)
+ (ndimage.rank_filter, (2, 3)), # args = (rank, size)
+ (ndimage.percentile_filter, (30, 3))]) # args = (percentile, size)
+ @pytest.mark.parametrize(
+ 'axes', [(1.5,), (0, 1, 2, 3), (3,), (-4,)]
+ )
+ def test_filter_invalid_axes(self, filter_func, args, axes, xp):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+ args = [
+ xp.asarray(arg) if isinstance(arg, np.ndarray) else arg
+ for arg in args
+ ]
+ if any(isinstance(ax, float) for ax in axes):
+ error_class = TypeError
+ match = "cannot be interpreted as an integer"
+ else:
+ error_class = ValueError
+ match = "out of range"
+ with pytest.raises(error_class, match=match):
+ filter_func(array, *args, axes=axes)
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize(
+ 'filter_func, kwargs',
+ [(ndimage.convolve, {}),
+ (ndimage.correlate, {}),
+ (ndimage.minimum_filter, {}),
+ (ndimage.maximum_filter, {}),
+ (ndimage.median_filter, {}),
+ (ndimage.rank_filter, dict(rank=3)),
+ (ndimage.percentile_filter, dict(percentile=30))])
+ @pytest.mark.parametrize(
+ 'axes', [(0, ), (1, 2), (0, 1, 2)]
+ )
+ @pytest.mark.parametrize('separable_footprint', [False, True])
+ def test_filter_invalid_footprint_ndim(self, filter_func, kwargs, axes,
+ separable_footprint, xp):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+ # create a footprint with one too many dimensions
+ footprint = np.ones((3,) * (len(axes) + 1))
+ if not separable_footprint:
+ footprint[(0,) * footprint.ndim] = 0
+ footprint = xp.asarray(footprint)
+ if (filter_func in [ndimage.minimum_filter, ndimage.maximum_filter]
+ and separable_footprint):
+ match = "sequence argument must have length equal to input rank"
+ elif filter_func in [ndimage.convolve, ndimage.correlate]:
+ match = re.escape(f"weights.ndim ({footprint.ndim}) must match "
+ f"len(axes) ({len(axes)})")
+ else:
+ match = re.escape(f"footprint.ndim ({footprint.ndim}) must match "
+ f"len(axes) ({len(axes)})")
+ if filter_func in [ndimage.convolve, ndimage.correlate]:
+ kwargs["weights"] = footprint
+ else:
+ kwargs["footprint"] = footprint
+ with pytest.raises(RuntimeError, match=match):
+ filter_func(array, axes=axes, **kwargs)
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize('n_mismatch', [1, 3])
+ @pytest.mark.parametrize('filter_func, kwargs, key, val',
+ _cases_axes_tuple_length_mismatch())
+ def test_filter_tuple_length_mismatch(self, n_mismatch, filter_func,
+ kwargs, key, val, xp):
+ # Test for the intended RuntimeError when a kwargs has an invalid size
+ array = xp.arange(6 * 8 * 12, dtype=xp.float64)
+ array = xp.reshape(array, (6, 8, 12))
+ axes = (0, 1)
+ kwargs = dict(**kwargs, axes=axes)
+ kwargs[key] = (val,) * n_mismatch
+ if filter_func in [ndimage.convolve, ndimage.correlate]:
+ kwargs["weights"] = xp.ones((5,) * len(axes))
+ err_msg = "sequence argument must have length equal to input rank"
+ with pytest.raises(RuntimeError, match=err_msg):
+ filter_func(array, **kwargs)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ def test_prewitt01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1)
+ output = ndimage.prewitt(array, 0)
+ assert_array_almost_equal(t, output)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ def test_prewitt02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 1)
+ output = xp.zeros(array.shape, dtype=dtype)
+ ndimage.prewitt(array, 0, output)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ def test_prewitt03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ if is_cupy(xp) and dtype in [xp.uint32, xp.uint64]:
+ pytest.xfail("uint UB? XXX")
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 1.0, 1.0]), 0)
+ output = ndimage.prewitt(array, 1)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ def test_prewitt04(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.prewitt(array, -1)
+ output = ndimage.prewitt(array, 1)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ def test_sobel01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1)
+ output = ndimage.sobel(array, 0)
+ assert_array_almost_equal(t, output)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ def test_sobel02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 0)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 1)
+ output = xp.zeros(array.shape, dtype=dtype)
+ ndimage.sobel(array, 0, output)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ def test_sobel03(self, dtype, xp):
+ if is_cupy(xp) and dtype in ["uint32", "uint64"]:
+ pytest.xfail("uint UB? XXX")
+
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.correlate1d(array, xp.asarray([-1.0, 0.0, 1.0]), 1)
+ t = ndimage.correlate1d(t, xp.asarray([1.0, 2.0, 1.0]), 0)
+ output = xp.zeros(array.shape, dtype=dtype)
+ output = ndimage.sobel(array, 1)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ def test_sobel04(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ t = ndimage.sobel(array, -1)
+ output = ndimage.sobel(array, 1)
+ assert_array_almost_equal(t, output)
+
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ def test_laplace01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0)
+ tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1)
+ output = ndimage.laplace(array)
+ assert_array_almost_equal(tmp1 + tmp2, output)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ def test_laplace02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 0)
+ tmp2 = ndimage.correlate1d(array, xp.asarray([1, -2, 1]), 1)
+ output = xp.zeros(array.shape, dtype=dtype)
+ ndimage.laplace(array, output=output)
+ assert_array_almost_equal(tmp1 + tmp2, output)
+
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ def test_gaussian_laplace01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0])
+ tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2])
+ output = ndimage.gaussian_laplace(array, 1.0)
+ assert_array_almost_equal(tmp1 + tmp2, output)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ def test_gaussian_laplace02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0])
+ tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2])
+ output = xp.zeros(array.shape, dtype=dtype)
+ ndimage.gaussian_laplace(array, 1.0, output)
+ assert_array_almost_equal(tmp1 + tmp2, output)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype', types + complex_types)
+ def test_generic_laplace01(self, dtype, xp):
+ def derivative2(input, axis, output, mode, cval, a, b):
+ sigma = np.asarray([a, b / 2.0])
+ order = [0] * input.ndim
+ order[axis] = 2
+ return ndimage.gaussian_filter(input, sigma, order,
+ output, mode, cval)
+
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = xp.zeros(array.shape, dtype=dtype)
+ tmp = ndimage.generic_laplace(array, derivative2,
+ extra_arguments=(1.0,),
+ extra_keywords={'b': 2.0})
+ ndimage.gaussian_laplace(array, 1.0, output)
+ assert_array_almost_equal(tmp, output)
+
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ def test_gaussian_gradient_magnitude01(self, dtype, xp):
+ is_int_dtype = dtype == "int32"
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0])
+ tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1])
+ output = ndimage.gaussian_gradient_magnitude(array, 1.0)
+ expected = tmp1 * tmp1 + tmp2 * tmp2
+
+ expected_float = xp.astype(expected, xp.float64) if is_int_dtype else expected
+ expected = xp.astype(xp.sqrt(expected_float), dtype)
+ xp_assert_close(output, expected, rtol=1e-6, atol=1e-6)
+
+ @uses_output_array
+ @pytest.mark.parametrize('dtype',
+ ["int32", "float32", "float64",
+ "complex64", "complex128"])
+ def test_gaussian_gradient_magnitude02(self, dtype, xp):
+ is_int_dtype = dtype == 'int32'
+ dtype = getattr(xp, dtype)
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype) * 100
+ tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0])
+ tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1])
+ output = xp.zeros(array.shape, dtype=dtype)
+ ndimage.gaussian_gradient_magnitude(array, 1.0, output)
+ expected = tmp1 * tmp1 + tmp2 * tmp2
+
+ fl_expected = xp.astype(expected, xp.float64) if is_int_dtype else expected
+
+ expected = xp.astype(xp.sqrt(fl_expected), dtype)
+ xp_assert_close(output, expected, rtol=1e-6, atol=1e-6)
+
+ def test_generic_gradient_magnitude01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=xp.float64)
+
+ def derivative(input, axis, output, mode, cval, a, b):
+ sigma = [a, b / 2.0]
+ order = [0] * input.ndim
+ order[axis] = 1
+ return ndimage.gaussian_filter(input, sigma, order, output, mode, cval)
+
+ tmp1 = ndimage.gaussian_gradient_magnitude(array, 1.0)
+ tmp2 = ndimage.generic_gradient_magnitude(
+ array, derivative, extra_arguments=(1.0,),
+ extra_keywords={'b': 2.0})
+ assert_array_almost_equal(tmp1, tmp2)
+
+ def test_uniform01(self, xp):
+ array = xp.asarray([2, 4, 6])
+ size = 2
+ output = ndimage.uniform_filter1d(array, size, origin=-1)
+ assert_array_almost_equal(xp.asarray([3, 5, 6]), output)
+
+ def test_uniform01_complex(self, xp):
+ array = xp.asarray([2 + 1j, 4 + 2j, 6 + 3j], dtype=xp.complex128)
+ size = 2
+ output = ndimage.uniform_filter1d(array, size, origin=-1)
+ assert_array_almost_equal(xp.real(output), xp.asarray([3., 5, 6]))
+ assert_array_almost_equal(xp.imag(output), xp.asarray([1.5, 2.5, 3]))
+
+ def test_uniform02(self, xp):
+ array = xp.asarray([1, 2, 3])
+ filter_shape = [0]
+ output = ndimage.uniform_filter(array, filter_shape)
+ assert_array_almost_equal(array, output)
+
+ def test_uniform03(self, xp):
+ array = xp.asarray([1, 2, 3])
+ filter_shape = [1]
+ output = ndimage.uniform_filter(array, filter_shape)
+ assert_array_almost_equal(array, output)
+
+ def test_uniform04(self, xp):
+ array = xp.asarray([2, 4, 6])
+ filter_shape = [2]
+ output = ndimage.uniform_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([2, 3, 5]), output)
+
+ def test_uniform05(self, xp):
+ array = xp.asarray([])
+ filter_shape = [1]
+ output = ndimage.uniform_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([]), output)
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', types)
+ @pytest.mark.parametrize('dtype_output', types)
+ def test_uniform06(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ filter_shape = [2, 2]
+ array = xp.asarray([[4, 8, 12],
+ [16, 20, 24]], dtype=dtype_array)
+ output = ndimage.uniform_filter(
+ array, filter_shape, output=dtype_output)
+ assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output)
+ assert output.dtype.type == dtype_output
+
+ @uses_output_dtype
+ @pytest.mark.parametrize('dtype_array', complex_types)
+ @pytest.mark.parametrize('dtype_output', complex_types)
+ def test_uniform06_complex(self, dtype_array, dtype_output, xp):
+ dtype_array = getattr(xp, dtype_array)
+ dtype_output = getattr(xp, dtype_output)
+
+ filter_shape = [2, 2]
+ array = xp.asarray([[4, 8 + 5j, 12],
+ [16, 20, 24]], dtype=dtype_array)
+ output = ndimage.uniform_filter(
+ array, filter_shape, output=dtype_output)
+ assert_array_almost_equal(xp.asarray([[4, 6, 10], [10, 12, 16]]), output.real)
+ assert output.dtype.type == dtype_output
+
+ def test_minimum_filter01(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ filter_shape = xp.asarray([2])
+ output = ndimage.minimum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output)
+
+ def test_minimum_filter02(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ filter_shape = xp.asarray([3])
+ output = ndimage.minimum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([1, 1, 2, 3, 4]), output)
+
+ def test_minimum_filter03(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ filter_shape = xp.asarray([2])
+ output = ndimage.minimum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([3, 2, 2, 1, 1]), output)
+
+ def test_minimum_filter04(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ filter_shape = xp.asarray([3])
+ output = ndimage.minimum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([2, 2, 1, 1, 1]), output)
+
+ def test_minimum_filter05(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ filter_shape = xp.asarray([2, 3])
+ output = ndimage.minimum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+ [2, 2, 1, 1, 1],
+ [5, 3, 3, 1, 1]]), output)
+
+ @uses_output_array
+ def test_minimum_filter05_overlap(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ filter_shape = xp.asarray([2, 3])
+ ndimage.minimum_filter(array, filter_shape, output=array)
+ assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+ [2, 2, 1, 1, 1],
+ [5, 3, 3, 1, 1]]), array)
+
+ def test_minimum_filter06(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 1, 1], [1, 1, 1]])
+ output = ndimage.minimum_filter(array, footprint=footprint)
+ assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+ [2, 2, 1, 1, 1],
+ [5, 3, 3, 1, 1]]), output)
+ # separable footprint should allow mode sequence
+ output2 = ndimage.minimum_filter(array, footprint=footprint,
+ mode=['reflect', 'reflect'])
+ assert_array_almost_equal(output2, output)
+
+ def test_minimum_filter07(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.minimum_filter(array, footprint=footprint)
+ assert_array_almost_equal(xp.asarray([[2, 2, 1, 1, 1],
+ [2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1]]), output)
+ with assert_raises(RuntimeError):
+ ndimage.minimum_filter(array, footprint=footprint,
+ mode=['reflect', 'constant'])
+
+ def test_minimum_filter08(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.minimum_filter(array, footprint=footprint, origin=-1)
+ assert_array_almost_equal(xp.asarray([[3, 1, 3, 1, 1],
+ [5, 3, 3, 1, 1],
+ [3, 3, 1, 1, 1]]), output)
+
+ def test_minimum_filter09(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.minimum_filter(array, footprint=footprint,
+ origin=[-1, 0])
+ assert_array_almost_equal(xp.asarray([[2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1],
+ [5, 3, 3, 1, 1]]), output)
+
+ def test_maximum_filter01(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ filter_shape = xp.asarray([2])
+ output = ndimage.maximum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([1, 2, 3, 4, 5]), output)
+
+ def test_maximum_filter02(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ filter_shape = xp.asarray([3])
+ output = ndimage.maximum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([2, 3, 4, 5, 5]), output)
+
+ def test_maximum_filter03(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ filter_shape = xp.asarray([2])
+ output = ndimage.maximum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+
+ def test_maximum_filter04(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ filter_shape = xp.asarray([3])
+ output = ndimage.maximum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([3, 5, 5, 5, 4]), output)
+
+ def test_maximum_filter05(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ filter_shape = xp.asarray([2, 3])
+ output = ndimage.maximum_filter(array, filter_shape)
+ assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+ [7, 9, 9, 9, 5],
+ [8, 9, 9, 9, 7]]), output)
+
+ def test_maximum_filter06(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 1, 1], [1, 1, 1]])
+ output = ndimage.maximum_filter(array, footprint=footprint)
+ assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+ [7, 9, 9, 9, 5],
+ [8, 9, 9, 9, 7]]), output)
+ # separable footprint should allow mode sequence
+ output2 = ndimage.maximum_filter(array, footprint=footprint,
+ mode=['reflect', 'reflect'])
+ assert_array_almost_equal(output2, output)
+
+ def test_maximum_filter07(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.maximum_filter(array, footprint=footprint)
+ assert_array_almost_equal(xp.asarray([[3, 5, 5, 5, 4],
+ [7, 7, 9, 9, 5],
+ [7, 9, 8, 9, 7]]), output)
+ # non-separable footprint should not allow mode sequence
+ with assert_raises(RuntimeError):
+ ndimage.maximum_filter(array, footprint=footprint,
+ mode=['reflect', 'reflect'])
+
+ def test_maximum_filter08(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.maximum_filter(array, footprint=footprint, origin=-1)
+ assert_array_almost_equal(xp.asarray([[7, 9, 9, 5, 5],
+ [9, 8, 9, 7, 5],
+ [8, 8, 7, 7, 7]]), output)
+
+ def test_maximum_filter09(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.maximum_filter(array, footprint=footprint,
+ origin=[-1, 0])
+ assert_array_almost_equal(xp.asarray([[7, 7, 9, 9, 5],
+ [7, 9, 8, 9, 7],
+ [8, 8, 8, 7, 7]]), output)
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/8339")
+ @pytest.mark.parametrize(
+ 'axes', tuple(itertools.combinations(range(-3, 3), 2))
+ )
+ @pytest.mark.parametrize(
+ 'filter_func, kwargs',
+ [(ndimage.minimum_filter, {}),
+ (ndimage.maximum_filter, {}),
+ (ndimage.median_filter, {}),
+ (ndimage.rank_filter, dict(rank=3)),
+ (ndimage.percentile_filter, dict(percentile=60))]
+ )
+ def test_minmax_nonseparable_axes(self, filter_func, axes, kwargs, xp):
+ array = xp.arange(6 * 8 * 12, dtype=xp.float32)
+ array = xp.reshape(array, (6, 8, 12))
+ # use 2D triangular footprint because it is non-separable
+ footprint = xp.asarray(np.tri(5))
+ axes = np.asarray(axes)
+
+ if len(set(axes % array.ndim)) != len(axes):
+ # parametrized cases with duplicate axes raise an error
+ with pytest.raises(ValueError):
+ filter_func(array, footprint=footprint, axes=axes, **kwargs)
+ return
+ output = filter_func(array, footprint=footprint, axes=axes, **kwargs)
+
+ missing_axis = tuple(set(range(3)) - set(axes % array.ndim))[0]
+
+ footprint_3d = xp.expand_dims(footprint, axis=missing_axis)
+ expected = filter_func(array, footprint=footprint_3d, **kwargs)
+ xp_assert_close(output, expected)
+
+ def test_rank01(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ output = ndimage.rank_filter(array, 1, size=2)
+ xp_assert_equal(array, output)
+ output = ndimage.percentile_filter(array, 100, size=2)
+ xp_assert_equal(array, output)
+ output = ndimage.median_filter(array, 2)
+ xp_assert_equal(array, output)
+
+ def test_rank02(self, xp):
+ array = xp.asarray([1, 2, 3, 4, 5])
+ output = ndimage.rank_filter(array, 1, size=[3])
+ xp_assert_equal(array, output)
+ output = ndimage.percentile_filter(array, 50, size=3)
+ xp_assert_equal(array, output)
+ output = ndimage.median_filter(array, (3,))
+ xp_assert_equal(array, output)
+
+ def test_rank03(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ output = ndimage.rank_filter(array, 1, size=[2])
+ xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+ output = ndimage.percentile_filter(array, 100, size=2)
+ xp_assert_equal(xp.asarray([3, 3, 5, 5, 4]), output)
+
+ def test_rank04(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ expected = xp.asarray([3, 3, 2, 4, 4])
+ output = ndimage.rank_filter(array, 1, size=3)
+ xp_assert_equal(expected, output)
+ output = ndimage.percentile_filter(array, 50, size=3)
+ xp_assert_equal(expected, output)
+ output = ndimage.median_filter(array, size=3)
+ xp_assert_equal(expected, output)
+
+ def test_rank05(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ expected = xp.asarray([3, 3, 2, 4, 4])
+ output = ndimage.rank_filter(array, -2, size=3)
+ xp_assert_equal(expected, output)
+
+ def test_rank06(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]])
+ expected = [[2, 2, 1, 1, 1],
+ [3, 3, 2, 1, 1],
+ [5, 5, 3, 3, 1]]
+ expected = xp.asarray(expected)
+ output = ndimage.rank_filter(array, 1, size=[2, 3])
+ xp_assert_equal(expected, output)
+ output = ndimage.percentile_filter(array, 17, size=(2, 3))
+ xp_assert_equal(expected, output)
+
+ @xfail_xp_backends("cupy", reason="cupy/cupy#8406")
+ @uses_output_array
+ def test_rank06_overlap(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]])
+
+ array_copy = xp.asarray(array, copy=True)
+ expected = [[2, 2, 1, 1, 1],
+ [3, 3, 2, 1, 1],
+ [5, 5, 3, 3, 1]]
+ expected = xp.asarray(expected)
+ ndimage.rank_filter(array, 1, size=[2, 3], output=array)
+ xp_assert_equal(expected, array)
+
+ ndimage.percentile_filter(array_copy, 17, size=(2, 3),
+ output=array_copy)
+ xp_assert_equal(expected, array_copy)
+
+ def test_rank07(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]])
+ expected = [[3, 5, 5, 5, 4],
+ [5, 5, 7, 5, 4],
+ [6, 8, 8, 7, 5]]
+ expected = xp.asarray(expected)
+ output = ndimage.rank_filter(array, -2, size=[2, 3])
+ xp_assert_equal(expected, output)
+
+ def test_rank08(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]])
+ expected = [[3, 3, 2, 4, 4],
+ [5, 5, 5, 4, 4],
+ [5, 6, 7, 5, 5]]
+ expected = xp.asarray(expected)
+ output = ndimage.percentile_filter(array, 50.0, size=(2, 3))
+ xp_assert_equal(expected, output)
+ output = ndimage.rank_filter(array, 3, size=(2, 3))
+ xp_assert_equal(expected, output)
+ output = ndimage.median_filter(array, size=(2, 3))
+ xp_assert_equal(expected, output)
+
+ # non-separable: does not allow mode sequence
+ with assert_raises(RuntimeError):
+ ndimage.percentile_filter(array, 50.0, size=(2, 3),
+ mode=['reflect', 'constant'])
+ with assert_raises(RuntimeError):
+ ndimage.rank_filter(array, 3, size=(2, 3), mode=['reflect']*2)
+ with assert_raises(RuntimeError):
+ ndimage.median_filter(array, size=(2, 3), mode=['reflect']*2)
+
+ @pytest.mark.parametrize('dtype', types)
+ def test_rank09(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[3, 3, 2, 4, 4],
+ [3, 5, 2, 5, 1],
+ [5, 5, 8, 3, 5]]
+ expected = xp.asarray(expected)
+ footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = ndimage.rank_filter(array, 1, footprint=footprint)
+ assert_array_almost_equal(expected, output)
+ output = ndimage.percentile_filter(array, 35, footprint=footprint)
+ assert_array_almost_equal(expected, output)
+
+ def test_rank10(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ expected = [[2, 2, 1, 1, 1],
+ [2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1]]
+ expected = xp.asarray(expected)
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.rank_filter(array, 0, footprint=footprint)
+ xp_assert_equal(expected, output)
+ output = ndimage.percentile_filter(array, 0.0, footprint=footprint)
+ xp_assert_equal(expected, output)
+
+ def test_rank11(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ expected = [[3, 5, 5, 5, 4],
+ [7, 7, 9, 9, 5],
+ [7, 9, 8, 9, 7]]
+ expected = xp.asarray(expected)
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.rank_filter(array, -1, footprint=footprint)
+ xp_assert_equal(expected, output)
+ output = ndimage.percentile_filter(array, 100.0, footprint=footprint)
+ xp_assert_equal(expected, output)
+
+ @pytest.mark.parametrize('dtype', types)
+ def test_rank12(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[3, 3, 2, 4, 4],
+ [3, 5, 2, 5, 1],
+ [5, 5, 8, 3, 5]]
+ expected = xp.asarray(expected, dtype=dtype)
+ footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = ndimage.rank_filter(array, 1, footprint=footprint)
+ assert_array_almost_equal(expected, output)
+ output = ndimage.percentile_filter(array, 50.0,
+ footprint=footprint)
+ xp_assert_equal(expected, output)
+ output = ndimage.median_filter(array, footprint=footprint)
+ xp_assert_equal(expected, output)
+
+ @pytest.mark.parametrize('dtype', types)
+ def test_rank13(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[5, 2, 5, 1, 1],
+ [5, 8, 3, 5, 5],
+ [6, 6, 5, 5, 5]]
+ expected = xp.asarray(expected, dtype=dtype)
+ footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = ndimage.rank_filter(array, 1, footprint=footprint,
+ origin=-1)
+ xp_assert_equal(expected, output)
+
+ @pytest.mark.parametrize('dtype', types)
+ def test_rank14(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[3, 5, 2, 5, 1],
+ [5, 5, 8, 3, 5],
+ [5, 6, 6, 5, 5]]
+ expected = xp.asarray(expected, dtype=dtype)
+ footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = ndimage.rank_filter(array, 1, footprint=footprint,
+ origin=[-1, 0])
+ xp_assert_equal(expected, output)
+
+ @pytest.mark.parametrize('dtype', types)
+ def test_rank15(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[2, 3, 1, 4, 1],
+ [5, 3, 7, 1, 1],
+ [5, 5, 3, 3, 3]]
+ expected = xp.asarray(expected, dtype=dtype)
+ footprint = xp.asarray([[1, 0, 1], [0, 1, 0]])
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [5, 8, 3, 7, 1],
+ [5, 6, 9, 3, 5]], dtype=dtype)
+ output = ndimage.rank_filter(array, 0, footprint=footprint,
+ origin=[-1, 0])
+ xp_assert_equal(expected, output)
+
+ # NumPy-only because test is for list input
+ def test_rank16(self):
+ # test that lists are accepted and interpreted as numpy arrays
+ array = [3, 2, 5, 1, 4]
+ # expected values are: median(3, 2, 5) = 3, median(2, 5, 1) = 2, etc
+ expected = np.asarray([3, 3, 2, 4, 4])
+ output = ndimage.rank_filter(array, -2, size=3)
+ xp_assert_equal(expected, output)
+
+ def test_rank17(self, xp):
+ array = xp.asarray([3, 2, 5, 1, 4])
+ if not hasattr(array, 'flags'):
+ return
+ array.flags.writeable = False
+ expected = xp.asarray([3, 3, 2, 4, 4])
+ output = ndimage.rank_filter(array, -2, size=3)
+ xp_assert_equal(expected, output)
+
+ def test_rank18(self, xp):
+ # module 'array_api_strict' has no attribute 'float16'
+ tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64',
+ 'uint8', 'uint16', 'uint32', 'uint64']
+ for dtype_str in tested_dtypes:
+ dtype = getattr(xp, dtype_str)
+ x = xp.asarray([3, 2, 5, 1, 4], dtype=dtype)
+ y = ndimage.rank_filter(x, -2, size=3)
+ assert y.dtype == x.dtype
+
+ def test_rank19(self, xp):
+ # module 'array_api_strict' has no attribute 'float16'
+ tested_dtypes = ['int8', 'int16', 'int32', 'int64', 'float32', 'float64',
+ 'uint8', 'uint16', 'uint32', 'uint64']
+ for dtype_str in tested_dtypes:
+ dtype = getattr(xp, dtype_str)
+ x = xp.asarray([[3, 2, 5, 1, 4], [3, 2, 5, 1, 4]], dtype=dtype)
+ y = ndimage.rank_filter(x, -2, size=3)
+ assert y.dtype == x.dtype
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason="off-by-ones on alt backends")
+ @xfail_xp_backends("cupy", reason="does not support extra_arguments")
+ @pytest.mark.parametrize('dtype', types)
+ def test_generic_filter1d01(self, dtype, xp):
+ weights = xp.asarray([1.1, 2.2, 3.3])
+
+ def _filter_func(input, output, fltr, total):
+ fltr = fltr / total
+ for ii in range(input.shape[0] - 2):
+ output[ii] = input[ii] * fltr[0]
+ output[ii] += input[ii + 1] * fltr[1]
+ output[ii] += input[ii + 2] * fltr[2]
+
+ a = np.arange(12, dtype=dtype).reshape(3, 4)
+ a = xp.asarray(a)
+ dtype = getattr(xp, dtype)
+
+ r1 = ndimage.correlate1d(a, weights / xp.sum(weights), 0, origin=-1)
+ r2 = ndimage.generic_filter1d(
+ a, _filter_func, 3, axis=0, origin=-1,
+ extra_arguments=(weights,),
+ extra_keywords={'total': xp.sum(weights)})
+ assert_array_almost_equal(r1, r2)
+
+ @xfail_xp_backends("cupy", reason="does not support extra_arguments")
+ @pytest.mark.parametrize('dtype', types)
+ def test_generic_filter01(self, dtype, xp):
+ if is_torch(xp) and dtype in ("uint16", "uint32", "uint64"):
+ pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+ dtype_str = dtype
+ dtype = getattr(xp, dtype_str)
+
+ filter_ = xp.asarray([[1.0, 2.0], [3.0, 4.0]])
+ footprint = xp.asarray([[1.0, 0.0], [0.0, 1.0]])
+ cf = xp.asarray([1., 4.])
+
+ def _filter_func(buffer, weights, total=1.0):
+ weights = np.asarray(cf) / np.asarray(total)
+ return np.sum(buffer * weights)
+
+ a = np.arange(12, dtype=dtype_str).reshape(3, 4)
+ a = xp.asarray(a)
+ r1 = ndimage.correlate(a, filter_ * footprint)
+ if dtype_str in float_types:
+ r1 /= 5
+ else:
+ r1 //= 5
+ r2 = ndimage.generic_filter(
+ a, _filter_func, footprint=footprint, extra_arguments=(cf,),
+ extra_keywords={'total': xp.sum(cf)})
+ assert_array_almost_equal(r1, r2)
+
+ # generic_filter doesn't allow mode sequence
+ with assert_raises(RuntimeError):
+ r2 = ndimage.generic_filter(
+ a, _filter_func, mode=['reflect', 'reflect'],
+ footprint=footprint, extra_arguments=(cf,),
+ extra_keywords={'total': xp.sum(cf)})
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [1, 1, 2]),
+ ('wrap', [3, 1, 2]),
+ ('reflect', [1, 1, 2]),
+ ('mirror', [2, 1, 2]),
+ ('constant', [0, 1, 2])]
+ )
+ def test_extend01(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([1, 0])
+ output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [1, 1, 1]),
+ ('wrap', [3, 1, 2]),
+ ('reflect', [3, 3, 2]),
+ ('mirror', [1, 2, 3]),
+ ('constant', [0, 0, 0])]
+ )
+ def test_extend02(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([1, 0, 0, 0, 0, 0, 0, 0])
+ output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [2, 3, 3]),
+ ('wrap', [2, 3, 1]),
+ ('reflect', [2, 3, 3]),
+ ('mirror', [2, 3, 2]),
+ ('constant', [2, 3, 0])]
+ )
+ def test_extend03(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([0, 0, 1])
+ output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [3, 3, 3]),
+ ('wrap', [2, 3, 1]),
+ ('reflect', [2, 1, 1]),
+ ('mirror', [1, 2, 3]),
+ ('constant', [0, 0, 0])]
+ )
+ def test_extend04(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+ output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]),
+ ('wrap', [[9, 7, 8], [3, 1, 2], [6, 4, 5]]),
+ ('reflect', [[1, 1, 2], [1, 1, 2], [4, 4, 5]]),
+ ('mirror', [[5, 4, 5], [2, 1, 2], [5, 4, 5]]),
+ ('constant', [[0, 0, 0], [0, 1, 2], [0, 4, 5]])]
+ )
+ def test_extend05(self, mode, expected_value, xp):
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]])
+ weights = xp.asarray([[1, 0], [0, 0]])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]),
+ ('wrap', [[5, 6, 4], [8, 9, 7], [2, 3, 1]]),
+ ('reflect', [[5, 6, 6], [8, 9, 9], [8, 9, 9]]),
+ ('mirror', [[5, 6, 5], [8, 9, 8], [5, 6, 5]]),
+ ('constant', [[5, 6, 0], [8, 9, 0], [0, 0, 0]])]
+ )
+ def test_extend06(self, mode, expected_value, xp):
+ array = xp.asarray([[1, 2, 3],
+ [4, 5, 6],
+ [7, 8, 9]])
+ weights = xp.asarray([[0, 0, 0], [0, 0, 0], [0, 0, 1]])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [3, 3, 3]),
+ ('wrap', [2, 3, 1]),
+ ('reflect', [2, 1, 1]),
+ ('mirror', [1, 2, 3]),
+ ('constant', [0, 0, 0])]
+ )
+ def test_extend07(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [[3], [3], [3]]),
+ ('wrap', [[2], [3], [1]]),
+ ('reflect', [[2], [1], [1]]),
+ ('mirror', [[1], [2], [3]]),
+ ('constant', [[0], [0], [0]])]
+ )
+ def test_extend08(self, mode, expected_value, xp):
+ array = xp.asarray([[1], [2], [3]])
+ weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [3, 3, 3]),
+ ('wrap', [2, 3, 1]),
+ ('reflect', [2, 1, 1]),
+ ('mirror', [1, 2, 3]),
+ ('constant', [0, 0, 0])]
+ )
+ def test_extend09(self, mode, expected_value, xp):
+ array = xp.asarray([1, 2, 3])
+ weights = xp.asarray([0, 0, 0, 0, 0, 0, 0, 0, 1])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [[3], [3], [3]]),
+ ('wrap', [[2], [3], [1]]),
+ ('reflect', [[2], [1], [1]]),
+ ('mirror', [[1], [2], [3]]),
+ ('constant', [[0], [0], [0]])]
+ )
+ def test_extend10(self, mode, expected_value, xp):
+ array = xp.asarray([[1], [2], [3]])
+ weights = xp.asarray([[0], [0], [0], [0], [0], [0], [0], [0], [1]])
+ output = ndimage.correlate(array, weights, mode=mode, cval=0)
+ expected_value = xp.asarray(expected_value)
+ xp_assert_equal(output, expected_value)
+
+
+@xfail_xp_backends("cupy", reason="TypeError")
+@make_xp_test_case(ndimage.generic_filter)
+def test_ticket_701(xp):
+ # Test generic filter sizes
+ arr = xp.asarray(np.arange(4).reshape(2, 2))
+ def func(x):
+ return np.min(x) # NB: np.min not xp.min for callables
+ res = ndimage.generic_filter(arr, func, size=(1, 1))
+ # The following raises an error unless ticket 701 is fixed
+ res2 = ndimage.generic_filter(arr, func, size=1)
+ xp_assert_equal(res, res2)
+
+
+def test_gh_5430():
+ # At least one of these raises an error unless gh-5430 is
+ # fixed. In py2k an int is implemented using a C long, so
+ # which one fails depends on your system. In py3k there is only
+ # one arbitrary precision integer type, so both should fail.
+ sigma = np.int32(1)
+ out = ndimage._ni_support._normalize_sequence(sigma, 1)
+ assert out == [sigma]
+ sigma = np.int64(1)
+ out = ndimage._ni_support._normalize_sequence(sigma, 1)
+ assert out == [sigma]
+ # This worked before; make sure it still works
+ sigma = 1
+ out = ndimage._ni_support._normalize_sequence(sigma, 1)
+ assert out == [sigma]
+ # This worked before; make sure it still works
+ sigma = [1, 1]
+ out = ndimage._ni_support._normalize_sequence(sigma, 2)
+ assert out == sigma
+ # Also include the OPs original example to make sure we fixed the issue
+ x = np.random.normal(size=(256, 256))
+ perlin = np.zeros_like(x)
+ for i in 2**np.arange(6):
+ perlin += ndimage.gaussian_filter(x, i, mode="wrap") * i**2
+ # This also fixes gh-4106, show that the OPs example now runs.
+ x = np.int64(21)
+ ndimage._ni_support._normalize_sequence(x, 0)
+
+
+@skip_xp_backends("cupy", reason="tests a private scipy utility")
+def test_gaussian_kernel1d(xp):
+ radius = 10
+ sigma = 2
+ sigma2 = sigma * sigma
+ x = np.arange(-radius, radius + 1, dtype=np.float64)
+ x = xp.asarray(x)
+ phi_x = xp.exp(-0.5 * x * x / sigma2)
+ phi_x /= xp.sum(phi_x)
+ xp_assert_close(phi_x,
+ xp.asarray(_gaussian_kernel1d(sigma, 0, radius)))
+ xp_assert_close(-phi_x * x / sigma2,
+ xp.asarray(_gaussian_kernel1d(sigma, 1, radius)))
+ xp_assert_close(phi_x * (x * x / sigma2 - 1) / sigma2,
+ xp.asarray(_gaussian_kernel1d(sigma, 2, radius)))
+ xp_assert_close(phi_x * (3 - x * x / sigma2) * x / (sigma2 * sigma2),
+ xp.asarray(_gaussian_kernel1d(sigma, 3, radius)))
+
+
+@make_xp_test_case(ndimage.gaussian_filter, ndimage.gaussian_filter1d)
+def test_orders_gauss(xp):
+ # Check order inputs to Gaussians
+ arr = xp.zeros((1,))
+ xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=0), xp.asarray([0.]))
+ xp_assert_equal(ndimage.gaussian_filter(arr, 1, order=3), xp.asarray([0.]))
+ assert_raises(ValueError, ndimage.gaussian_filter, arr, 1, -1)
+ xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=0),
+ xp.asarray([0.]))
+ xp_assert_equal(ndimage.gaussian_filter1d(arr, 1, axis=-1, order=3),
+ xp.asarray([0.]))
+ assert_raises(ValueError, ndimage.gaussian_filter1d, arr, 1, -1, -1)
+
+
+@xfail_xp_backends("cupy", reason="TypeError")
+@make_xp_test_case(
+ ndimage.generic_filter,
+ ndimage.generic_filter1d,
+ ndimage.percentile_filter,
+)
+def test_valid_origins1(xp):
+ """Regression test for #1311."""
+
+ def func(x):
+ return xp.mean(x)
+
+ data = xp.asarray([1, 2, 3, 4, 5], dtype=xp.float64)
+ assert_raises(ValueError, ndimage.generic_filter, data, func, size=3,
+ origin=2)
+ assert_raises(ValueError, ndimage.generic_filter1d, data, func,
+ filter_size=3, origin=2)
+ assert_raises(ValueError, ndimage.percentile_filter, data, 0.2, size=3,
+ origin=2)
+
+
+@xfail_xp_backends("cupy", reason="TypeError")
+@pytest.mark.parametrize(
+ "filter_func",
+ [
+ make_xp_pytest_param(ndimage.uniform_filter),
+ make_xp_pytest_param(ndimage.minimum_filter),
+ make_xp_pytest_param(ndimage.maximum_filter),
+ make_xp_pytest_param(ndimage.maximum_filter1d),
+ make_xp_pytest_param(ndimage.median_filter),
+ make_xp_pytest_param(ndimage.minimum_filter1d),
+ ],
+)
+def test_valid_origins2(xp, filter_func):
+ """Regression test for #1311."""
+ data = xp.asarray([1, 2, 3, 4, 5], dtype=xp.float64)
+
+ # This should work, since for size == 3, the valid range for origin is
+ # -1 to 1.
+ list(filter_func(data, 3, origin=-1))
+ list(filter_func(data, 3, origin=1))
+ # Just check this raises an error instead of silently accepting or
+ # segfaulting.
+ assert_raises(ValueError, filter_func, data, 3, origin=2)
+
+
+@make_xp_test_case(
+ ndimage.correlate1d,
+ ndimage.correlate,
+ ndimage.convolve1d,
+ ndimage.convolve,
+)
+def test_bad_convolve_and_correlate_origins(xp):
+ """Regression test for gh-822."""
+ # Before gh-822 was fixed, these would generate seg. faults or
+ # other crashes on many system.
+ assert_raises(ValueError, ndimage.correlate1d,
+ [0, 1, 2, 3, 4, 5], [1, 1, 2, 0], origin=2)
+ assert_raises(ValueError, ndimage.correlate,
+ [0, 1, 2, 3, 4, 5], [0, 1, 2], origin=[2])
+ assert_raises(ValueError, ndimage.correlate,
+ xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, 1])
+
+ assert_raises(ValueError, ndimage.convolve1d,
+ xp.arange(10), xp.ones(3), origin=-2)
+ assert_raises(ValueError, ndimage.convolve,
+ xp.arange(10), xp.ones(3), origin=[-2])
+ assert_raises(ValueError, ndimage.convolve,
+ xp.ones((3, 5)), xp.ones((2, 2)), origin=[0, -2])
+
+
+@pytest.mark.parametrize(
+ "filter_func,args,kwargs",
+ [
+ make_xp_pytest_param(ndimage.gaussian_filter, [1], {}),
+ make_xp_pytest_param(ndimage.prewitt, [], {}),
+ make_xp_pytest_param(ndimage.sobel, [], {}),
+ make_xp_pytest_param(ndimage.laplace, [], {}),
+ make_xp_pytest_param(ndimage.gaussian_laplace, [1], {}),
+ make_xp_pytest_param(ndimage.maximum_filter, [], {"size": 5}),
+ make_xp_pytest_param(ndimage.minimum_filter, [], {"size": 5}),
+ make_xp_pytest_param(ndimage.gaussian_gradient_magnitude, [1], {}),
+ make_xp_pytest_param(ndimage.uniform_filter, [5], {}),
+ ],
+)
+def test_multiple_modes(xp, filter_func, args, kwargs):
+ # Test that the filters with multiple mode capabilities for different
+ # dimensions give the same result as applying a single mode.
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ mode1 = 'reflect'
+ mode2 = ['reflect', 'reflect']
+
+ xp_assert_equal(filter_func(arr, *args, mode=mode1, **kwargs),
+ filter_func(arr, *args, mode=mode2, **kwargs))
+
+
+@make_xp_test_case(
+ ndimage.gaussian_filter1d, ndimage.gaussian_filter,
+ ndimage.uniform_filter1d, ndimage.uniform_filter,
+ ndimage.maximum_filter1d, ndimage.maximum_filter,
+ ndimage.minimum_filter1d, ndimage.minimum_filter,
+)
+def test_multiple_modes_sequentially(xp):
+ # Test that the filters with multiple mode capabilities for different
+ # dimensions give the same result as applying the filters with
+ # different modes sequentially
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ modes = ['reflect', 'wrap']
+
+ expected = ndimage.gaussian_filter1d(arr, 1, axis=0, mode=modes[0])
+ expected = ndimage.gaussian_filter1d(expected, 1, axis=1, mode=modes[1])
+ xp_assert_equal(expected,
+ ndimage.gaussian_filter(arr, 1, mode=modes))
+
+ expected = ndimage.uniform_filter1d(arr, 5, axis=0, mode=modes[0])
+ expected = ndimage.uniform_filter1d(expected, 5, axis=1, mode=modes[1])
+ xp_assert_equal(expected,
+ ndimage.uniform_filter(arr, 5, mode=modes))
+
+ expected = ndimage.maximum_filter1d(arr, size=5, axis=0, mode=modes[0])
+ expected = ndimage.maximum_filter1d(expected, size=5, axis=1,
+ mode=modes[1])
+ xp_assert_equal(expected,
+ ndimage.maximum_filter(arr, size=5, mode=modes))
+
+ expected = ndimage.minimum_filter1d(arr, size=5, axis=0, mode=modes[0])
+ expected = ndimage.minimum_filter1d(expected, size=5, axis=1,
+ mode=modes[1])
+ xp_assert_equal(expected,
+ ndimage.minimum_filter(arr, size=5, mode=modes))
+
+
+@make_xp_test_case(ndimage.prewitt)
+def test_multiple_modes_prewitt(xp):
+ # Test prewitt filter for multiple extrapolation modes
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[1., -3., 2.],
+ [1., -2., 1.],
+ [1., -1., 0.]])
+
+ modes = ['reflect', 'wrap']
+
+ xp_assert_equal(expected,
+ ndimage.prewitt(arr, mode=modes))
+
+
+@make_xp_test_case(ndimage.sobel)
+def test_multiple_modes_sobel(xp):
+ # Test sobel filter for multiple extrapolation modes
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[1., -4., 3.],
+ [2., -3., 1.],
+ [1., -1., 0.]])
+
+ modes = ['reflect', 'wrap']
+
+ xp_assert_equal(expected,
+ ndimage.sobel(arr, mode=modes))
+
+
+@make_xp_test_case(ndimage.laplace)
+def test_multiple_modes_laplace(xp):
+ # Test laplace filter for multiple extrapolation modes
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[-2., 2., 1.],
+ [-2., -3., 2.],
+ [1., 1., 0.]])
+
+ modes = ['reflect', 'wrap']
+
+ xp_assert_equal(expected,
+ ndimage.laplace(arr, mode=modes))
+
+
+@make_xp_test_case(ndimage.gaussian_laplace)
+def test_multiple_modes_gaussian_laplace(xp):
+ # Test gaussian_laplace filter for multiple extrapolation modes
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[-0.28438687, 0.01559809, 0.19773499],
+ [-0.36630503, -0.20069774, 0.07483620],
+ [0.15849176, 0.18495566, 0.21934094]])
+
+ modes = ['reflect', 'wrap']
+
+ assert_almost_equal(expected,
+ ndimage.gaussian_laplace(arr, 1, mode=modes))
+
+
+@make_xp_test_case(ndimage.gaussian_gradient_magnitude)
+def test_multiple_modes_gaussian_gradient_magnitude(xp):
+ # Test gaussian_gradient_magnitude filter for multiple
+ # extrapolation modes
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[0.04928965, 0.09745625, 0.06405368],
+ [0.23056905, 0.14025305, 0.04550846],
+ [0.19894369, 0.14950060, 0.06796850]])
+
+ modes = ['reflect', 'wrap']
+
+ calculated = ndimage.gaussian_gradient_magnitude(arr, 1, mode=modes)
+
+ assert_almost_equal(expected, calculated)
+
+
+@make_xp_test_case(ndimage.uniform_filter)
+def test_multiple_modes_uniform(xp):
+ # Test uniform filter for multiple extrapolation modes
+ arr = xp.asarray([[1., 0., 0.],
+ [1., 1., 0.],
+ [0., 0., 0.]])
+
+ expected = xp.asarray([[0.32, 0.40, 0.48],
+ [0.20, 0.28, 0.32],
+ [0.28, 0.32, 0.40]])
+
+ modes = ['reflect', 'wrap']
+
+ assert_almost_equal(expected,
+ ndimage.uniform_filter(arr, 5, mode=modes))
+
+
+def _count_nonzero(arr):
+ # XXX: a simplified count_nonzero replacement; replace once
+ # https://github.com/data-apis/array-api/pull/803/ is in
+
+ # this assumes arr.dtype == xp.bool
+ xp = array_namespace(arr)
+ return xp.sum(xp.astype(arr, xp.int8))
+
+
+@make_xp_test_case(
+ ndimage.gaussian_filter, ndimage.gaussian_filter1d,
+ ndimage.gaussian_laplace, ndimage.gaussian_gradient_magnitude,
+)
+def test_gaussian_truncate(xp):
+ # Test that Gaussian filters can be truncated at different widths.
+ # These tests only check that the result has the expected number
+ # of nonzero elements.
+ arr = np.zeros((100, 100), dtype=np.float64)
+ arr[50, 50] = 1
+ arr = xp.asarray(arr)
+ num_nonzeros_2 = _count_nonzero(ndimage.gaussian_filter(arr, 5, truncate=2) > 0)
+ assert num_nonzeros_2 == 21**2
+
+ num_nonzeros_5 = _count_nonzero(
+ ndimage.gaussian_filter(arr, 5, truncate=5) > 0
+ )
+ assert num_nonzeros_5 == 51**2
+
+ # Test truncate when sigma is a sequence.
+ f = ndimage.gaussian_filter(arr, [0.5, 2.5], truncate=3.5)
+ fpos = f > 0
+ n0 = _count_nonzero(xp.any(fpos, axis=0))
+ assert n0 == 19
+ n1 = _count_nonzero(xp.any(fpos, axis=1))
+ assert n1 == 5
+
+ # Test gaussian_filter1d.
+ x = np.zeros(51)
+ x[25] = 1
+ x = xp.asarray(x)
+ f = ndimage.gaussian_filter1d(x, sigma=2, truncate=3.5)
+ n = _count_nonzero(f > 0)
+ assert n == 15
+
+ # Test gaussian_laplace
+ y = ndimage.gaussian_laplace(x, sigma=2, truncate=3.5)
+ nonzero_indices = xp.nonzero(y != 0)[0]
+
+ n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1
+ assert n == 15
+
+ # Test gaussian_gradient_magnitude
+ y = ndimage.gaussian_gradient_magnitude(x, sigma=2, truncate=3.5)
+ nonzero_indices = xp.nonzero(y != 0)[0]
+ n = xp.max(nonzero_indices) - xp.min(nonzero_indices) + 1
+ assert n == 15
+
+
+@xfail_xp_backends("cupy", reason="cupy/cupy#8402")
+@make_xp_test_case(ndimage.gaussian_filter1d, ndimage.gaussian_filter)
+def test_gaussian_radius(xp):
+ # Test that Gaussian filters with radius argument produce the same
+ # results as the filters with corresponding truncate argument.
+ # radius = int(truncate * sigma + 0.5)
+ # Test gaussian_filter1d
+ x = np.zeros(7)
+ x[3] = 1
+ x = xp.asarray(x)
+ f1 = ndimage.gaussian_filter1d(x, sigma=2, truncate=1.5)
+ f2 = ndimage.gaussian_filter1d(x, sigma=2, radius=3)
+ xp_assert_equal(f1, f2)
+
+ # Test gaussian_filter when sigma is a number.
+ a = np.zeros((9, 9))
+ a[4, 4] = 1
+ a = xp.asarray(a)
+ f1 = ndimage.gaussian_filter(a, sigma=0.5, truncate=3.5)
+ f2 = ndimage.gaussian_filter(a, sigma=0.5, radius=2)
+ xp_assert_equal(f1, f2)
+
+ # Test gaussian_filter when sigma is a sequence.
+ a = np.zeros((50, 50))
+ a[25, 25] = 1
+ a = xp.asarray(a)
+ f1 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], truncate=3.5)
+ f2 = ndimage.gaussian_filter(a, sigma=[0.5, 2.5], radius=[2, 9])
+ xp_assert_equal(f1, f2)
+
+
+@xfail_xp_backends("cupy", reason="cupy/cupy#8402")
+@make_xp_test_case(ndimage.gaussian_filter1d)
+def test_gaussian_radius_invalid(xp):
+ # radius must be a nonnegative integer
+ with assert_raises(ValueError):
+ ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=-1)
+ with assert_raises(ValueError):
+ ndimage.gaussian_filter1d(xp.zeros(8), sigma=1, radius=1.1)
+
+
+@uses_output_array
+class TestThreading:
+ def check_func_thread(self, n, fun, args, out):
+ from threading import Thread
+ thrds = [Thread(target=fun, args=args, kwargs={'output': out[x, ...]})
+ for x in range(n)]
+ [t.start() for t in thrds]
+ [t.join() for t in thrds]
+
+ def check_func_serial(self, n, fun, args, out):
+ for i in range(n):
+ fun(*args, output=out[i, ...])
+
+ @xfail_xp_backends("cupy",
+ reason="XXX thread exception; cannot repro outside of pytest")
+ @make_xp_test_case(ndimage.correlate1d)
+ def test_correlate1d(self, xp):
+ d = np.random.randn(5000)
+ os = np.empty((4, d.size))
+ ot = np.empty_like(os)
+ d = xp.asarray(d)
+ os = xp.asarray(os)
+ ot = xp.asarray(ot)
+ k = xp.arange(5)
+ self.check_func_serial(4, ndimage.correlate1d, (d, k), os)
+ self.check_func_thread(4, ndimage.correlate1d, (d, k), ot)
+ xp_assert_equal(os, ot)
+
+ @xfail_xp_backends("cupy",
+ reason="XXX thread exception; cannot repro outside of pytest")
+ @make_xp_test_case(ndimage.correlate)
+ def test_correlate(self, xp):
+ d = xp.asarray(np.random.randn(500, 500))
+ k = xp.asarray(np.random.randn(10, 10))
+ os = xp.empty([4] + list(d.shape))
+ ot = xp.empty_like(os)
+ self.check_func_serial(4, ndimage.correlate, (d, k), os)
+ self.check_func_thread(4, ndimage.correlate, (d, k), ot)
+ xp_assert_equal(os, ot)
+
+ @xfail_xp_backends("cupy",
+ reason="XXX thread exception; cannot repro outside of pytest")
+ @make_xp_test_case(ndimage.median_filter)
+ def test_median_filter(self, xp):
+ d = xp.asarray(np.random.randn(500, 500))
+ os = xp.empty([4] + list(d.shape))
+ ot = xp.empty_like(os)
+ self.check_func_serial(4, ndimage.median_filter, (d, 3), os)
+ self.check_func_thread(4, ndimage.median_filter, (d, 3), ot)
+ xp_assert_equal(os, ot)
+
+ @xfail_xp_backends("cupy",
+ reason="XXX thread exception; cannot repro outside of pytest")
+ @make_xp_test_case(ndimage.uniform_filter1d)
+ def test_uniform_filter1d(self, xp):
+ d = np.random.randn(5000)
+ os = np.empty((4, d.size))
+ ot = np.empty_like(os)
+ d = xp.asarray(d)
+ os = xp.asarray(os)
+ ot = xp.asarray(ot)
+ self.check_func_serial(4, ndimage.uniform_filter1d, (d, 5), os)
+ self.check_func_thread(4, ndimage.uniform_filter1d, (d, 5), ot)
+ xp_assert_equal(os, ot)
+
+ @xfail_xp_backends("cupy",
+ reason="XXX thread exception; cannot repro outside of pytest")
+ @make_xp_test_case(ndimage.maximum_filter, ndimage.minimum_filter)
+ def test_minmax_filter(self, xp):
+ d = xp.asarray(np.random.randn(500, 500))
+ os = xp.empty([4] + list(d.shape))
+ ot = xp.empty_like(os)
+ self.check_func_serial(4, ndimage.maximum_filter, (d, 3), os)
+ self.check_func_thread(4, ndimage.maximum_filter, (d, 3), ot)
+ xp_assert_equal(os, ot)
+ self.check_func_serial(4, ndimage.minimum_filter, (d, 3), os)
+ self.check_func_thread(4, ndimage.minimum_filter, (d, 3), ot)
+ xp_assert_equal(os, ot)
+
+@make_xp_test_case(ndimage.maximum_filter1d, ndimage.minimum_filter1d)
+def test_minmaximum_filter1d(xp):
+ # Regression gh-3898
+ in_ = xp.arange(10)
+ out = ndimage.minimum_filter1d(in_, 1)
+ xp_assert_equal(in_, out)
+ out = ndimage.maximum_filter1d(in_, 1)
+ xp_assert_equal(in_, out)
+ # Test reflect
+ out = ndimage.minimum_filter1d(in_, 5, mode='reflect')
+ xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out)
+ out = ndimage.maximum_filter1d(in_, 5, mode='reflect')
+ xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+ # Test constant
+ out = ndimage.minimum_filter1d(in_, 5, mode='constant', cval=-1)
+ xp_assert_equal(xp.asarray([-1, -1, 0, 1, 2, 3, 4, 5, -1, -1]), out)
+ out = ndimage.maximum_filter1d(in_, 5, mode='constant', cval=10)
+ xp_assert_equal(xp.asarray([10, 10, 4, 5, 6, 7, 8, 9, 10, 10]), out)
+ # Test nearest
+ out = ndimage.minimum_filter1d(in_, 5, mode='nearest')
+ xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 6, 7]), out)
+ out = ndimage.maximum_filter1d(in_, 5, mode='nearest')
+ xp_assert_equal(xp.asarray([2, 3, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+ # Test wrap
+ out = ndimage.minimum_filter1d(in_, 5, mode='wrap')
+ xp_assert_equal(xp.asarray([0, 0, 0, 1, 2, 3, 4, 5, 0, 0]), out)
+ out = ndimage.maximum_filter1d(in_, 5, mode='wrap')
+ xp_assert_equal(xp.asarray([9, 9, 4, 5, 6, 7, 8, 9, 9, 9]), out)
+
+
+@xfail_xp_backends("cupy", reason="cupy/cupy#8401")
+@make_xp_test_case(ndimage.uniform_filter1d)
+def test_uniform_filter1d_roundoff_errors(xp):
+ # gh-6930
+ in_ = np.repeat([0, 1, 0], [9, 9, 9])
+ in_ = xp.asarray(in_)
+
+ for filter_size in range(3, 10):
+ out = ndimage.uniform_filter1d(in_, filter_size)
+ xp_assert_equal(xp.sum(out), xp.asarray(10 - filter_size), check_0d=False)
+
+
+@make_xp_test_case(ndimage.maximum_filter)
+def test_footprint_all_zeros(xp):
+ # regression test for gh-6876: footprint of all zeros segfaults
+ arr = xp.asarray(np.random.randint(0, 100, (100, 100)))
+ kernel = xp.asarray(np.zeros((3, 3), dtype=bool))
+ with assert_raises(ValueError):
+ ndimage.maximum_filter(arr, footprint=kernel)
+
+
+@xfail_xp_backends("cupy", reason="does not raise")
+@skip_xp_backends("array_api_strict", reason="no float16")
+@skip_xp_backends("dask.array", reason="no float16")
+@make_xp_test_case(ndimage.gaussian_filter)
+def test_gaussian_filter_float16(xp):
+ # gh-8207
+ data = xp.asarray([1], dtype=xp.float16)
+ sigma = 1.0
+ with assert_raises(RuntimeError):
+ ndimage.gaussian_filter(data, sigma)
+
+
+@xfail_xp_backends("cupy", reason="does not raise")
+@make_xp_test_case(ndimage.rank_filter)
+def test_rank_filter_noninteger_rank(xp):
+ # regression test for issue 9388: ValueError for
+ # non integer rank when performing rank_filter
+ arr = xp.asarray(np.random.random((10, 20, 30)))
+ footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool))
+ assert_raises(TypeError, ndimage.rank_filter, arr, 0.5,
+ footprint=footprint)
+
+
+@make_xp_test_case(ndimage.rank_filter)
+def test_size_footprint_both_set(xp):
+ # test for input validation, expect user warning when
+ # size and footprint is set
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore",
+ "ignoring size because footprint is set", UserWarning)
+ arr = xp.asarray(np.random.random((10, 20, 30)))
+ footprint = xp.asarray(np.ones((1, 1, 10), dtype=bool))
+ ndimage.rank_filter(
+ arr, 5, size=2, footprint=footprint
+ )
+
+
+# NumPy-only because 'byteorder is numpy-specific'
+def test_byte_order_median():
+ """Regression test for #413: median_filter does not handle bytes orders."""
+ a = np.arange(9, dtype='1 makes sense too
+ (3,
+ np.array([0.25266576, 0.30958242, 0.27894721, 0.27894721, 0.27894721, 0.30445588,
+ 0.31442572, 0.30445588, 0.18015438, 0.14831921, 0.18015438, 0.25754605,
+ 0.32910465, 0.25754605, 0.17736568, 0.17736568, 0.09089549, 0.22183391,
+ 0.25266576, 0.30958242]),
+ ),
+ (15,
+ np.array([0.27894721, 0.25266576, 0.25266576, 0.25266576, 0.27894721, 0.27894721,
+ 0.27894721, 0.27894721, 0.25754605, 0.25754605, 0.22183391, 0.22183391,
+ 0.25266576, 0.25266576, 0.22183391, 0.22183391, 0.25266576, 0.25266576,
+ 0.25754605, 0.25754605]),
+ ),
+])
+def test_gh_22250(filter_size, exp):
+ rng = np.random.default_rng(42)
+ image = np.zeros((20,))
+ noisy_image = image + 0.4 * rng.random(image.shape)
+ result = ndimage.median_filter(noisy_image, size=filter_size, mode='wrap')
+ assert_allclose(result, exp)
+
+
+def test_gh_22333():
+ x = np.array([272, 58, 67, 163, 463, 608, 87, 108, 1378])
+ expected = [58, 67, 87, 108, 163, 108, 108, 108, 87]
+ actual = ndimage.median_filter(x, size=9, mode='constant')
+ assert_array_equal(actual, expected)
+
+
+@pytest.mark.filterwarnings("ignore:The given NumPy array is not writable:UserWarning")
+@make_xp_test_case(ndimage.vectorized_filter)
+class TestVectorizedFilter:
+ @pytest.mark.parametrize("axes, size",
+ [(None, (3, 4, 5)), ((0, 2), (3, 4)), ((-1,), (5,))])
+ @pytest.mark.parametrize("origin", [-1, 0, 1])
+ @pytest.mark.parametrize("mode",
+ ['reflect', 'nearest', 'mirror', 'wrap', 'constant'])
+ @pytest.mark.parametrize("use_output", [False, True])
+ def test_against_generic_filter(self, axes, size, origin, mode, use_output, xp):
+ rng = np.random.default_rng(435982456983456987356)
+
+ if use_output and (is_dask(xp) or is_jax(xp)):
+ pytest.skip("Requires mutable arrays.")
+
+ input = rng.random(size=(11, 12, 13))
+ input_copy = input.copy() # check that it is not modified
+ output = xp.zeros(input.shape) if use_output else None
+
+ kwargs = dict(axes=axes, size=size, origin=origin, mode=mode)
+ ref = ndimage.generic_filter(input, np.mean, **kwargs)
+ kwargs['output'] = output
+ res = ndimage.vectorized_filter(xp.asarray(input.tolist()),
+ xp.mean, **kwargs)
+ xp_assert_close(res, xp.asarray(ref.tolist()), atol=1e-15)
+ if use_output:
+ xp_assert_equal(output, res)
+
+ if not (is_array_api_strict(xp) or is_dask(xp)):
+ # currently requires support for [..., mask] indexing
+ kwargs.pop('size')
+ kwargs.pop('output')
+ kwargs['footprint'] = rng.random(size=size or input.shape) > 0.5
+ ref = ndimage.generic_filter(input, np.mean, **kwargs)
+ kwargs['footprint'] = xp.asarray(kwargs['footprint'])
+ kwargs['output'] = output
+ res = ndimage.vectorized_filter(xp.asarray(input.tolist()),
+ xp.mean, **kwargs)
+ xp_assert_close(res, xp.asarray(ref.tolist()), atol=1e-15)
+ if use_output:
+ xp_assert_equal(output, res)
+
+ xp_assert_equal(xp.asarray(input), xp.asarray(input_copy))
+
+ @pytest.mark.parametrize("dtype",
+ ["uint8", "uint16", "uint32", "uint64",
+ "int8", "int16", "int32", "int64",
+ "float32", "float64", "complex64", "complex128"])
+ @pytest.mark.parametrize("batch_memory", [1, 16*3, np.inf])
+ @pytest.mark.parametrize("use_footprint", [False, True])
+ def test_dtype_batch_memory(self, dtype, batch_memory, use_footprint, xp):
+ rng = np.random.default_rng(435982456983456987356)
+ w = 3
+
+ if is_jax(xp) and not (batch_memory == 1):
+ pytest.skip("Requires mutable array.")
+ if is_torch(xp) and dtype in {'uint16', 'uint32', 'uint64'}:
+ pytest.skip("Needs uint support.")
+
+ dtype = getattr(xp, dtype)
+
+ if use_footprint:
+ if (is_dask(xp) or is_array_api_strict(xp)):
+ pytest.skip("Requires [..., mask] indexing.")
+ footprint = xp.asarray([True, False, True])
+ kwargs = dict(footprint=footprint, batch_memory=batch_memory)
+ else:
+ footprint = xp.asarray([True, True, True])
+ kwargs = dict(size=w, batch_memory=batch_memory)
+
+ # The intent here is to exercise all the code paths involved in `batch_memory`
+ # and `output` handling. To test the limited-memory case, `batch_memory=16*3`
+ # is chosen to be just large enough for a *single* window of `complex128` to
+ # fit, and `n` is large enough that a whole sliding window view of `uint8`s
+ # *won't* fit.
+ n = 16*3 + 1
+ input = rng.integers(0, 42, size=(n,))
+ input = input + input*1j if xp.isdtype(dtype, 'complex floating') else input
+ input_padded = xp.asarray(np.pad(input, [(1, 1)], mode='symmetric'),
+ dtype=dtype)
+ input = xp.asarray(input, dtype=dtype)
+
+ ref = [xp.sum(input_padded[i: i + w][footprint]) for i in range(n)]
+ sum_dtype = xp.sum(input_padded).dtype
+
+ message = "`batch_memory` is insufficient for minimum chunk size."
+ context = (pytest.raises(ValueError, match=message)
+ if batch_memory == 1 else contextlib.nullcontext())
+ with context:
+ res = ndimage.vectorized_filter(input, xp.sum, **kwargs)
+ xp_assert_close(res, xp.astype(xp.stack(ref), sum_dtype))
+ assert res.dtype == sum_dtype
+
+ output = xp.empty_like(input)
+ res = ndimage.vectorized_filter(
+ input,
+ lambda x, *args, **kw: xp.astype(
+ xp.sum(x, *args, **kw), x.dtype, copy=False
+ ),
+ output=output,
+ **kwargs
+ )
+ xp_assert_close(res, xp.astype(xp.stack(ref), dtype))
+ assert res.dtype == dtype
+
+ def test_mode_valid(self, xp):
+ rng = np.random.default_rng(435982456983456987356)
+ input = rng.random(size=(10, 11))
+ input_xp = xp.asarray(input)
+ input_xp_copy = xp_copy(input_xp) # check that it is not modified
+ size = (3, 5)
+
+ res = ndimage.vectorized_filter(input_xp, xp.mean, size=size, mode='valid')
+
+ view = np.lib.stride_tricks.sliding_window_view(input, size)
+ ref = np.mean(view, axis=(-2, -1))
+
+ xp_assert_close(res, xp.asarray(ref))
+ assert res.shape == tuple(input.shape - np.asarray(size) + 1)
+ xp_assert_equal(input_xp, input_xp_copy)
+
+ def test_input_validation(self, xp):
+ input = xp.ones((10, 10))
+ function = xp.mean
+ size = 2
+ footprint = xp.ones((2, 2))
+
+ message = "`function` must be a callable."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, "eggplant", size=size)
+
+ message = "Either `size` or `footprint` must be provided."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function)
+
+ message = "Either `size` or `footprint` may be provided, not both."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, footprint=footprint)
+
+ message = "All elements of `size` must be positive integers."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=(1, -1))
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=0)
+
+ message = "The length of `axes` may not exceed "
+ axes = (0, 1, 2)
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=(1, 2), axes=axes)
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, footprint=xp.ones((2, 2)),
+ axes=axes)
+
+ message = "`axes` must be compatible with the dimensionality..."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=(1,))
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=(2,), axes=(0,1))
+
+ message = "All elements of `origin` must be integers"
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, origin=(1, 1.5))
+
+ message = "`origin` must be an integer or tuple of integers with length..."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, origin=(1, 2, 3))
+
+ message = "`mode` must be one of..."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, mode='coconut')
+
+ message = "`mode='valid'` is incompatible with use of `origin`."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size,
+ mode='valid', origin=1)
+
+ message = "Use of `cval` is compatible only with `mode='constant'`."
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, mode='valid', cval=1)
+
+ other_messages = "|Unsupported|The array_api_strict|new|Value 'a duck'"
+ message = "`cval` must include only numbers." + other_messages
+ with pytest.raises((ValueError, TypeError), match=message):
+ ndimage.vectorized_filter(input, function, size=size,
+ mode='constant', cval='a duck')
+
+ message = "`batch_memory` must be positive number." + other_messages
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, batch_memory=0)
+ with pytest.raises(ValueError, match=message):
+ ndimage.vectorized_filter(input, function, size=size, batch_memory=(1, 2))
+ with pytest.raises((ValueError, TypeError), match=message):
+ ndimage.vectorized_filter(input, function, size=size, batch_memory="a duck")
+
+ @pytest.mark.parametrize('shape', [(0,), (1, 0), (0, 1, 0)])
+ def test_zero_size(self, shape, xp):
+ input = xp.empty(shape)
+ res = ndimage.vectorized_filter(input, xp.mean, size=1)
+ xp_assert_equal(res, input)
+
+ @pytest.mark.filterwarnings("ignore:Mean of empty slice:RuntimeWarning")
+ def test_edge_cases(self, xp):
+ rng = np.random.default_rng(4835982345234982)
+ function = xp.mean
+
+ # 0-D input
+ input = xp.asarray(1.)
+ res = ndimage.vectorized_filter(input, function, size=())
+ xp_assert_equal(res, xp.asarray(function(input, axis=())))
+
+ if not (is_array_api_strict(xp) or is_dask(xp)):
+ res = ndimage.vectorized_filter(input, function, footprint=True)
+ xp_assert_equal(res, xp.asarray(function(input[True], axis=())))
+
+ res = ndimage.vectorized_filter(input, function, footprint=False)
+ xp_assert_equal(res, xp.asarray(function(input[False], axis=())))
+
+ # 1x1 window
+ input = xp.asarray(rng.random((5, 5)))
+ res = ndimage.vectorized_filter(input, function, size=1)
+ xp_assert_equal(res, input)
+
+ # window is bigger than input shouldn't be a problem
+ res = ndimage.vectorized_filter(input, function, size=21)
+ ref = ndimage.vectorized_filter(input, function, size=21)
+ xp_assert_close(res, ref)
+
+ def test_gh23046_feature(self, xp):
+ # The intent of gh-23046 was to always allow `size` to be a scalar.
+ rng = np.random.default_rng(45982734597824)
+ img = xp.asarray(rng.random((5, 5)))
+
+ ref = ndimage.vectorized_filter(img, xp.mean, size=2)
+ res = ndimage.vectorized_filter(img, xp.mean, size=2, axes=(0, 1))
+ xp_assert_close(res, ref)
+
+ ref = ndimage.vectorized_filter(img, xp.mean, size=(2,), axes=(0,))
+ res = ndimage.vectorized_filter(img, xp.mean, size=2, axes=0)
+ xp_assert_close(res, ref)
+
+ def test_gh23046_fix(self, xp):
+ # While investigating the feasibility of gh-23046, I noticed a bug when the
+ # length of an `axes` tuple equals the dimensionality of the image.
+ rng = np.random.default_rng(45982734597824)
+ img = xp.asarray(rng.random((5, 5)))
+ size = (2, 3)
+ ref = ndimage.vectorized_filter(img.T, xp.mean, size=size).T
+ res = ndimage.vectorized_filter(img, xp.mean, size=size, axes=(1, 0))
+ xp_assert_close(res, ref)
+
+ ref = ndimage.vectorized_filter(img, xp.mean, size=size, mode='constant')
+ res = ndimage.vectorized_filter(img, xp.mean, size=size[::-1], axes=(1, 0),
+ mode='constant')
+ xp_assert_close(res, ref)
+
+
+@given(x=npst.arrays(dtype=np.float64,
+ shape=st.integers(min_value=1, max_value=1000)),
+ size=st.integers(min_value=1, max_value=50),
+ mode=st.sampled_from(["constant", "mirror", "wrap", "reflect",
+ "nearest"]),
+ )
+def test_gh_22586_crash_property(x, size, mode):
+ # property-based test for median_filter resilience to hard crashing
+ ndimage.median_filter(x, size=size, mode=mode)
+
+
+@pytest.mark.parametrize('samples, mode, size, expected', [
+ ([1, 2], "reflect", 5, [2, 1]),
+ ([2], "reflect", 5, [2]), # original failure from gh-23075
+ ([2], "nearest", 5, [2]),
+ ([2], "wrap", 5, [2]),
+ ([2], "mirror", 5, [2]),
+ ([2], "constant", 5, [0]),
+ ([2], "reflect", 1, [2]),
+ ([2], "nearest", 1, [2]),
+ ([2], "wrap", 1, [2]),
+ ([2], "mirror", 1, [2]),
+ ([2], "constant", 1, [2]),
+ ([2], "reflect", 100, [2]),
+ ([2], "nearest", 100, [2]),
+ ([2], "wrap", 100, [2]),
+ ([2], "mirror", 100, [2]),
+ ([2], "constant", 100, [0]),
+])
+def test_gh_23075(samples, mode, size, expected):
+ # results verified against SciPy 1.14.1, before the median_filter
+ # overhaul
+ sample_array = np.asarray(samples, dtype=np.float32)
+ expected = np.asarray(expected, dtype=np.float32)
+ filtered_samples = ndimage.median_filter(sample_array, size=size, mode=mode)
+ xp_assert_close(filtered_samples, expected, check_shape=True, check_dtype=True)
+
+
+@pytest.mark.parametrize('samples, size, cval, expected', [
+ ([2], 5, 17.7, [17.7]),
+ ([2], 1, 0, [2]),
+ ([2], 100, 1.4, [1.4]),
+ ([9], 137, -7807.7, [-7807.7]),
+])
+def test_gh_23075_constant(samples, size, cval, expected):
+ # results verified against SciPy 1.14.1, before the median_filter
+ # overhaul
+ sample_array = np.asarray(samples, dtype=np.single)
+ expected = np.asarray(expected, dtype=np.single)
+ filtered_samples = ndimage.median_filter(sample_array,
+ size=size,
+ mode="constant",
+ cval=cval)
+ xp_assert_close(filtered_samples, expected, check_shape=True, check_dtype=True)
+
+
+def test_median_filter_lim2():
+ sample_array = np.ones(8)
+ expected = np.ones(8)
+ filtered_samples = ndimage.median_filter(sample_array, size=19, mode="reflect")
+ xp_assert_close(filtered_samples, expected, check_shape=True, check_dtype=True)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_fourier.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_fourier.py
new file mode 100644
index 0000000000000000000000000000000000000000..97c737d3f62b4b84b01a884ea9fa43b6a75eb932
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_fourier.py
@@ -0,0 +1,197 @@
+import math
+import numpy as np
+
+from scipy._lib._array_api import (
+ xp_assert_equal,
+ assert_array_almost_equal,
+ assert_almost_equal,
+ is_cupy,
+ make_xp_test_case,
+ make_xp_pytest_param,
+)
+
+import pytest
+
+from scipy import ndimage
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+class TestNdimageFourier:
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+ @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
+ @make_xp_test_case(ndimage.fourier_gaussian)
+ def test_fourier_gaussian_real01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.rfft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.irfft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1), decimal=dec,
+ check_0d=False)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
+ @make_xp_test_case(ndimage.fourier_gaussian)
+ def test_fourier_gaussian_complex01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.fft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.ifft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+ check_0d=False)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+ @pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
+ @make_xp_test_case(ndimage.fourier_uniform)
+ def test_fourier_uniform_real01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.rfft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.irfft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
+ check_0d=False)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
+ @make_xp_test_case(ndimage.fourier_uniform)
+ def test_fourier_uniform_complex01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.fft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.ifft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+ check_0d=False)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+ @pytest.mark.parametrize('dtype, dec', [("float32", 4), ("float64", 11)])
+ @make_xp_test_case(ndimage.fourier_shift)
+ def test_fourier_shift_real01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
+ expected = xp.asarray(expected)
+
+ a = fft.rfft(expected, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_shift(a, [1, 1], shape[0], 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.irfft(a, n=shape[0], axis=0)
+ assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1], decimal=dec)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 4), ("complex128", 11)])
+ @make_xp_test_case(ndimage.fourier_shift)
+ def test_fourier_shift_complex01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
+ expected = xp.asarray(expected)
+
+ a = fft.fft(expected, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_shift(a, [1, 1], -1, 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.ifft(a, n=shape[0], axis=0)
+ assert_array_almost_equal(xp.real(a)[1:, 1:], expected[:-1, :-1], decimal=dec)
+ assert_array_almost_equal(xp.imag(a), xp.zeros(shape), decimal=dec)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
+ @pytest.mark.parametrize('dtype, dec', [("float32", 5), ("float64", 14)])
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
+ def test_fourier_ellipsoid_real01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.rfft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.irfft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
+ check_0d=False)
+
+ @pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
+ @pytest.mark.parametrize('dtype, dec', [("complex64", 5), ("complex128", 14)])
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
+ def test_fourier_ellipsoid_complex01(self, shape, dtype, dec, xp):
+ fft = getattr(xp, 'fft')
+
+ a = np.zeros(shape, dtype=dtype)
+ a[0, 0] = 1.0
+ a = xp.asarray(a)
+
+ a = fft.fft(a, n=shape[0], axis=0)
+ a = fft.fft(a, n=shape[1], axis=1)
+ a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0)
+ a = fft.ifft(a, n=shape[1], axis=1)
+ a = fft.ifft(a, n=shape[0], axis=0)
+ assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
+ check_0d=False)
+
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
+ def test_fourier_ellipsoid_unimplemented_ndim(self, xp):
+ # arrays with ndim > 3 raise NotImplementedError
+ x = xp.ones((4, 6, 8, 10), dtype=xp.complex128)
+ with pytest.raises(NotImplementedError):
+ ndimage.fourier_ellipsoid(x, 3)
+
+ @make_xp_test_case(ndimage.fourier_ellipsoid)
+ def test_fourier_ellipsoid_1d_complex(self, xp):
+ # expected result of 1d ellipsoid is the same as for fourier_uniform
+ for shape in [(32, ), (31, )]:
+ for type_, dec in zip([xp.complex64, xp.complex128], [5, 14]):
+ x = xp.ones(shape, dtype=type_)
+ a = ndimage.fourier_ellipsoid(x, 5, -1, 0)
+ b = ndimage.fourier_uniform(x, 5, -1, 0)
+ assert_array_almost_equal(a, b, decimal=dec)
+
+ @pytest.mark.parametrize('shape', [(0, ), (0, 10), (10, 0)])
+ @pytest.mark.parametrize('dtype', ["float32", "float64",
+ "complex64", "complex128"])
+ @pytest.mark.parametrize('test_func',
+ [make_xp_pytest_param(ndimage.fourier_ellipsoid),
+ make_xp_pytest_param(ndimage.fourier_gaussian),
+ make_xp_pytest_param(ndimage.fourier_uniform)])
+ def test_fourier_zero_length_dims(self, shape, dtype, test_func, xp):
+ if (
+ is_cupy(xp)
+ and test_func.__name__ == "fourier_ellipsoid"
+ and math.prod(shape) == 0
+ ):
+ pytest.xfail("CuPy's fourier_ellipsoid does not accept size==0 arrays")
+ dtype = getattr(xp, dtype)
+ a = xp.ones(shape, dtype=dtype)
+ b = test_func(a, 3)
+ xp_assert_equal(a, b)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_interpolation.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_interpolation.py
new file mode 100644
index 0000000000000000000000000000000000000000..cc992b7c8383e9803c98188f3920c72c2fce2b9b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_interpolation.py
@@ -0,0 +1,1499 @@
+import sys
+import warnings
+
+import numpy as np
+from scipy._lib._array_api import (
+ _asarray, assert_array_almost_equal,
+ is_jax, np_compat,
+ xp_assert_equal, xp_assert_close,
+ make_xp_test_case,
+)
+
+import pytest
+from pytest import raises as assert_raises
+import scipy.ndimage as ndimage
+
+from . import types
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+# lazy_xp_modules = [ndimage]
+
+
+eps = 1e-12
+
+ndimage_to_numpy_mode = {
+ 'mirror': 'reflect',
+ 'reflect': 'symmetric',
+ 'grid-mirror': 'symmetric',
+ 'grid-wrap': 'wrap',
+ 'nearest': 'edge',
+ 'grid-constant': 'constant',
+}
+
+
+class TestBoundaries:
+
+ @make_xp_test_case(ndimage.geometric_transform)
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [1.5, 2.5, 3.5, 4, 4, 4, 4]),
+ ('wrap', [1.5, 2.5, 3.5, 1.5, 2.5, 3.5, 1.5]),
+ ('grid-wrap', [1.5, 2.5, 3.5, 2.5, 1.5, 2.5, 3.5]),
+ ('mirror', [1.5, 2.5, 3.5, 3.5, 2.5, 1.5, 1.5]),
+ ('reflect', [1.5, 2.5, 3.5, 4, 3.5, 2.5, 1.5]),
+ ('constant', [1.5, 2.5, 3.5, -1, -1, -1, -1]),
+ ('grid-constant', [1.5, 2.5, 3.5, 1.5, -1, -1, -1])]
+ )
+ def test_boundaries(self, mode, expected_value, xp):
+ def shift(x):
+ return (x[0] + 0.5,)
+
+ data = xp.asarray([1, 2, 3, 4.])
+ xp_assert_equal(
+ ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
+ output_shape=(7,), order=1),
+ xp.asarray(expected_value))
+
+ @make_xp_test_case(ndimage.geometric_transform)
+ @pytest.mark.parametrize(
+ 'mode, expected_value',
+ [('nearest', [1, 1, 2, 3]),
+ ('wrap', [3, 1, 2, 3]),
+ ('grid-wrap', [4, 1, 2, 3]),
+ ('mirror', [2, 1, 2, 3]),
+ ('reflect', [1, 1, 2, 3]),
+ ('constant', [-1, 1, 2, 3]),
+ ('grid-constant', [-1, 1, 2, 3])]
+ )
+ def test_boundaries2(self, mode, expected_value, xp):
+ def shift(x):
+ return (x[0] - 0.9,)
+
+ data = xp.asarray([1, 2, 3, 4])
+ xp_assert_equal(
+ ndimage.geometric_transform(data, shift, cval=-1, mode=mode,
+ output_shape=(4,)),
+ xp.asarray(expected_value))
+
+ @make_xp_test_case(ndimage.map_coordinates)
+ @pytest.mark.parametrize('mode', ['mirror', 'reflect', 'grid-mirror',
+ 'grid-wrap', 'grid-constant',
+ 'nearest'])
+ @pytest.mark.parametrize('order', range(6))
+ def test_boundary_spline_accuracy(self, mode, order, xp):
+ """Tests based on examples from gh-2640"""
+ if (is_jax(xp) and
+ (mode not in ['mirror', 'reflect', 'constant', 'wrap', 'nearest']
+ or order > 1)
+ ):
+ pytest.xfail("Jax does not support grid- modes or order > 1")
+
+ np_data = np.arange(-6, 7, dtype=np.float64)
+ data = xp.asarray(np_data)
+ x = xp.asarray(np.linspace(-8, 15, num=1000))
+ y = ndimage.map_coordinates(data, x[xp.newaxis, ...], order=order, mode=mode)
+
+ # compute expected value using explicit padding via np.pad
+ npad = 32
+ pad_mode = ndimage_to_numpy_mode.get(mode)
+ padded = xp.asarray(np.pad(np_data, npad, mode=pad_mode))
+ coords = xp.asarray(npad + x)[xp.newaxis, ...]
+ expected = ndimage.map_coordinates(padded, coords, order=order, mode=mode)
+
+ atol = 1e-5 if mode == 'grid-constant' else 1e-12
+ xp_assert_close(y, expected, rtol=1e-7, atol=atol)
+
+
+@make_xp_test_case(ndimage.spline_filter)
+@pytest.mark.parametrize('order', range(2, 6))
+@pytest.mark.parametrize('dtype', types)
+class TestSpline:
+
+ def test_spline01(self, dtype, order, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([], dtype=dtype)
+ out = ndimage.spline_filter(data, order=order)
+ assert out == xp.asarray(1, dtype=out.dtype)
+
+ def test_spline02(self, dtype, order, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([1], dtype=dtype)
+ out = ndimage.spline_filter(data, order=order)
+ assert_array_almost_equal(out, xp.asarray([1]))
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='output=dtype is numpy-specific')
+ def test_spline03(self, dtype, order, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([], dtype=dtype)
+ out = ndimage.spline_filter(data, order, output=dtype)
+ assert out == xp.asarray(1, dtype=out.dtype)
+
+ def test_spline04(self, dtype, order, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([4], dtype=dtype)
+ out = ndimage.spline_filter(data, order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
+
+ def test_spline05(self, dtype, order, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([4, 4], dtype=dtype)
+ out = ndimage.spline_filter(data, order=order)
+ expected = xp.asarray([[1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1]])
+ assert_array_almost_equal(out, expected)
+
+
+@make_xp_test_case(ndimage.geometric_transform)
+@pytest.mark.parametrize('order', range(0, 6))
+class TestGeometricTransform:
+
+ def test_geometric_transform01(self, order, xp):
+ data = xp.asarray([1])
+
+ def mapping(x):
+ return x
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype))
+
+ def test_geometric_transform02(self, order, xp):
+ data = xp.ones([4])
+
+ def mapping(x):
+ return x
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
+
+ def test_geometric_transform03(self, order, xp):
+ data = xp.ones([4])
+
+ def mapping(x):
+ return (x[0] - 1,)
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1], dtype=out.dtype))
+
+ def test_geometric_transform04(self, order, xp):
+ data = xp.asarray([4, 1, 3, 2])
+
+ def mapping(x):
+ return (x[0] - 1,)
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3], dtype=out.dtype))
+
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+ def test_geometric_transform05(self, order, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1]], dtype=dtype)
+ expected = xp.asarray([[0, 1, 1, 1],
+ [0, 1, 1, 1],
+ [0, 1, 1, 1]], dtype=dtype)
+
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ expected -= 1j * expected
+
+ def mapping(x):
+ return (x[0], x[1] - 1)
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ assert_array_almost_equal(out, expected)
+
+ def test_geometric_transform06(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+
+ def mapping(x):
+ return (x[0], x[1] - 1)
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ expected = xp.asarray([[0, 4, 1, 3],
+ [0, 7, 6, 8],
+ [0, 3, 5, 3]], dtype=out.dtype)
+ assert_array_almost_equal(out, expected)
+
+ def test_geometric_transform07(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+
+ def mapping(x):
+ return (x[0] - 1, x[1])
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ expected = xp.asarray([[0, 0, 0, 0],
+ [4, 1, 3, 2],
+ [7, 6, 8, 5]], dtype=out.dtype)
+ assert_array_almost_equal(out, expected)
+
+ def test_geometric_transform08(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+
+ def mapping(x):
+ return (x[0] - 1, x[1] - 1)
+
+ out = ndimage.geometric_transform(data, mapping, data.shape,
+ order=order)
+ expected = xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]], dtype=out.dtype)
+ assert_array_almost_equal(out, expected)
+
+ def test_geometric_transform10(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+
+ def mapping(x):
+ return (x[0] - 1, x[1] - 1)
+
+ if (order > 1):
+ filtered = ndimage.spline_filter(data, order=order)
+ else:
+ filtered = data
+ out = ndimage.geometric_transform(filtered, mapping, data.shape,
+ order=order, prefilter=False)
+ expected = xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]], dtype=out.dtype)
+ assert_array_almost_equal(out, expected)
+
+ def test_geometric_transform13(self, order, xp):
+ data = xp.ones([2], dtype=xp.float64)
+
+ def mapping(x):
+ return (x[0] // 2,)
+
+ out = ndimage.geometric_transform(data, mapping, [4], order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1], dtype=out.dtype))
+
+ def test_geometric_transform14(self, order, xp):
+ data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
+
+ def mapping(x):
+ return (2 * x[0],)
+
+ out = ndimage.geometric_transform(data, mapping, [4], order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4], dtype=out.dtype))
+
+ def test_geometric_transform15(self, order, xp):
+ data = xp.asarray([1, 2, 3, 4])
+
+ def mapping(x):
+ return (x[0] / 2,)
+
+ out = ndimage.geometric_transform(data, mapping, [8], order=order)
+ assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4]))
+
+ def test_geometric_transform16(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9.0, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0], x[1] * 2)
+
+ out = ndimage.geometric_transform(data, mapping, (3, 2),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]]))
+
+ def test_geometric_transform17(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0] * 2, x[1])
+
+ out = ndimage.geometric_transform(data, mapping, (1, 4),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]]))
+
+ def test_geometric_transform18(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0] * 2, x[1] * 2)
+
+ out = ndimage.geometric_transform(data, mapping, (1, 2),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 3]]))
+
+ def test_geometric_transform19(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0], x[1] / 2)
+
+ out = ndimage.geometric_transform(data, mapping, (3, 8),
+ order=order)
+ assert_array_almost_equal(out[..., ::2], data)
+
+ def test_geometric_transform20(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0] / 2, x[1])
+
+ out = ndimage.geometric_transform(data, mapping, (6, 4),
+ order=order)
+ assert_array_almost_equal(out[::2, ...], data)
+
+ def test_geometric_transform21(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (x[0] / 2, x[1] / 2)
+
+ out = ndimage.geometric_transform(data, mapping, (6, 8),
+ order=order)
+ assert_array_almost_equal(out[::2, ::2], data)
+
+ def test_geometric_transform22(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data, dtype=xp.float64)
+
+ def mapping1(x):
+ return (x[0] / 2, x[1] / 2)
+
+ def mapping2(x):
+ return (x[0] * 2, x[1] * 2)
+
+ out = ndimage.geometric_transform(data, mapping1,
+ (6, 8), order=order)
+ out = ndimage.geometric_transform(out, mapping2,
+ (3, 4), order=order)
+ assert_array_almost_equal(out, data)
+
+ def test_geometric_transform23(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x):
+ return (1, x[0] * 2)
+
+ out = ndimage.geometric_transform(data, mapping, (2,), order=order)
+ assert_array_almost_equal(out, xp.asarray([5, 7]))
+
+ def test_geometric_transform24(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+
+ def mapping(x, a, b):
+ return (a, x[0] * b)
+
+ out = ndimage.geometric_transform(
+ data, mapping, (2,), order=order, extra_arguments=(1,),
+ extra_keywords={'b': 2})
+ assert_array_almost_equal(out, xp.asarray([5, 7]))
+
+
+@make_xp_test_case(ndimage.geometric_transform)
+class TestGeometricTransformExtra:
+
+ def test_geometric_transform_grid_constant_order1(self, xp):
+
+ # verify interpolation outside the original bounds
+ x = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=xp.float64)
+
+ def mapping(x):
+ return (x[0] - 0.5), (x[1] - 0.5)
+
+ expected_result = xp.asarray([[0.25, 0.75, 1.25],
+ [1.25, 3.00, 4.00]])
+ assert_array_almost_equal(
+ ndimage.geometric_transform(x, mapping, mode='grid-constant',
+ order=1),
+ expected_result,
+ )
+
+ @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
+ 'mirror', 'reflect'])
+ @pytest.mark.parametrize('order', range(6))
+ def test_geometric_transform_vs_padded(self, order, mode, xp):
+
+ def mapping(x):
+ return (x[0] - 0.4), (x[1] + 2.3)
+
+ # Manually pad and then extract center after the transform to get the
+ # expected result.
+ x = np.arange(144, dtype=float).reshape(12, 12)
+ npad = 24
+ pad_mode = ndimage_to_numpy_mode.get(mode)
+ x_padded = np.pad(x, npad, mode=pad_mode)
+
+ x = xp.asarray(x)
+ x_padded = xp.asarray(x_padded)
+
+ center_slice = tuple([slice(npad, -npad)] * x.ndim)
+ expected_result = ndimage.geometric_transform(
+ x_padded, mapping, mode=mode, order=order)[center_slice]
+
+ xp_assert_close(
+ ndimage.geometric_transform(x, mapping, mode=mode,
+ order=order),
+ expected_result,
+ rtol=1e-7,
+ )
+
+ @skip_xp_backends(np_only=True, reason='endianness is numpy-specific')
+ def test_geometric_transform_endianness_with_output_parameter(self, xp):
+ # geometric transform given output ndarray or dtype with
+ # non-native endianness. see issue #4127
+ data = np.asarray([1])
+
+ def mapping(x):
+ return x
+
+ for out in [data.dtype, data.dtype.newbyteorder(),
+ np.empty_like(data),
+ np.empty_like(data).astype(data.dtype.newbyteorder())]:
+ returned = ndimage.geometric_transform(data, mapping, data.shape,
+ output=out)
+ result = out if returned is None else returned
+ assert_array_almost_equal(result, [1])
+
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+ def test_geometric_transform_with_string_output(self, xp):
+ data = xp.asarray([1])
+
+ def mapping(x):
+ return x
+
+ out = ndimage.geometric_transform(data, mapping, output='f')
+ assert out.dtype is np.dtype('f')
+ assert_array_almost_equal(out, [1])
+
+
+@make_xp_test_case(ndimage.map_coordinates)
+class TestMapCoordinates:
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('dtype', [np.float64, np.complex128])
+ def test_map_coordinates01(self, order, dtype, xp):
+ if is_jax(xp) and order > 1:
+ pytest.xfail("jax map_coordinates requires order <= 1")
+
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ expected = xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]])
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data = data - 1j * data
+ expected = expected - 1j * expected
+
+ idx = np.indices(data.shape)
+ idx -= 1
+ idx = xp.asarray(idx)
+
+ out = ndimage.map_coordinates(data, idx, order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_map_coordinates02(self, order, xp):
+ if is_jax(xp):
+ if order > 1:
+ pytest.xfail("jax map_coordinates requires order <= 1")
+ if order == 1:
+ pytest.xfail("output differs. jax bug?")
+
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ idx = np.indices(data.shape, np.float64)
+ idx -= 0.5
+ idx = xp.asarray(idx)
+
+ out1 = ndimage.shift(data, 0.5, order=order)
+ out2 = ndimage.map_coordinates(data, idx, order=order)
+ assert_array_almost_equal(out1, out2)
+
+ @skip_xp_backends("jax.numpy", reason="`order` is required in jax")
+ def test_map_coordinates03(self, xp):
+ data = _asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]], order='F', xp=xp)
+ idx = np.indices(data.shape) - 1
+ idx = xp.asarray(idx)
+ out = ndimage.map_coordinates(data, idx)
+ expected = xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]])
+ assert_array_almost_equal(out, expected)
+ assert_array_almost_equal(out, ndimage.shift(data, (1, 1)))
+
+ idx = np.indices(data[::2, ...].shape) - 1
+ idx = xp.asarray(idx)
+ out = ndimage.map_coordinates(data[::2, ...], idx)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3]]))
+ assert_array_almost_equal(out, ndimage.shift(data[::2, ...], (1, 1)))
+
+ idx = np.indices(data[:, ::2].shape) - 1
+ idx = xp.asarray(idx)
+ out = ndimage.map_coordinates(data[:, ::2], idx)
+ assert_array_almost_equal(out, xp.asarray([[0, 0], [0, 4], [0, 7]]))
+ assert_array_almost_equal(out, ndimage.shift(data[:, ::2], (1, 1)))
+
+ @skip_xp_backends(np_only=True)
+ def test_map_coordinates_endianness_with_output_parameter(self, xp):
+ # output parameter given as array or dtype with either endianness
+ # see issue #4127
+ # NB: NumPy-only
+
+ data = np.asarray([[1, 2], [7, 6]])
+ expected = np.asarray([[0, 0], [0, 1]])
+ idx = np.indices(data.shape)
+ idx -= 1
+ for out in [
+ data.dtype,
+ data.dtype.newbyteorder(),
+ np.empty_like(expected),
+ np.empty_like(expected).astype(expected.dtype.newbyteorder())
+ ]:
+ returned = ndimage.map_coordinates(data, idx, output=out)
+ result = out if returned is None else returned
+ assert_array_almost_equal(result, expected)
+
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+ def test_map_coordinates_with_string_output(self, xp):
+ data = xp.asarray([[1]])
+ idx = np.indices(data.shape)
+ idx = xp.asarray(idx)
+ out = ndimage.map_coordinates(data, idx, output='f')
+ assert out.dtype is np.dtype('f')
+ assert_array_almost_equal(out, xp.asarray([[1]]))
+
+ @pytest.mark.skip_xp_backends(cpu_only=True)
+ @pytest.mark.skipif('win32' in sys.platform or np.intp(0).itemsize < 8,
+ reason='do not run on 32 bit or windows '
+ '(no sparse memory)')
+ def test_map_coordinates_large_data(self, xp):
+ # check crash on large data
+ try:
+ n = 30000
+ # a = xp.reshape(xp.empty(n**2, dtype=xp.float32), (n, n))
+ a = np.empty(n**2, dtype=np.float32).reshape(n, n)
+ # fill the part we might read
+ a[n - 3:, n - 3:] = 0
+ ndimage.map_coordinates(
+ xp.asarray(a), xp.asarray([[n - 1.5], [n - 1.5]]), order=1
+ )
+ except MemoryError as e:
+ raise pytest.skip('Not enough memory available') from e
+
+
+@make_xp_test_case(ndimage.affine_transform)
+class TestAffineTransform:
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform01(self, order, xp):
+ data = xp.asarray([1])
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
+ assert_array_almost_equal(out, xp.asarray([1]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform02(self, order, xp):
+ data = xp.ones([4])
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform03(self, order, xp):
+ data = xp.ones([4])
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform04(self, order, xp):
+ data = xp.asarray([4, 1, 3, 2])
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), -1, order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+ def test_affine_transform05(self, order, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1]], dtype=dtype)
+ expected = xp.asarray([[0, 1, 1, 1],
+ [0, 1, 1, 1],
+ [0, 1, 1, 1]], dtype=dtype)
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ expected -= 1j * expected
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+ [0, -1], order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform06(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+ [0, -1], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
+ [0, 7, 6, 8],
+ [0, 3, 5, 3]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform07(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+ [-1, 0], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [4, 1, 3, 2],
+ [7, 6, 8, 5]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform08(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 1]]),
+ [-1, -1], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform09(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ if (order > 1):
+ filtered = ndimage.spline_filter(data, order=order)
+ else:
+ filtered = data
+ out = ndimage.affine_transform(filtered, xp.asarray([[1, 0], [0, 1]]),
+ [-1, -1], order=order,
+ prefilter=False)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform10(self, order, xp):
+ data = xp.ones([2], dtype=xp.float64)
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), output_shape=(4,),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform11(self, order, xp):
+ data = xp.asarray([1, 5, 2, 6, 3, 7, 4, 4])
+ out = ndimage.affine_transform(data, xp.asarray([[2]]), 0, (4,), order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 2, 3, 4]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform12(self, order, xp):
+ data = xp.asarray([1, 2, 3, 4])
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), 0, (8,), order=order)
+ assert_array_almost_equal(out[::2], xp.asarray([1, 2, 3, 4]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform13(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9.0, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0], [0, 2]]), 0, (3, 2),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 3], [5, 7], [9, 11]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform14(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 1]]), 0, (1, 4),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 2, 3, 4]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform15(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[2, 0], [0, 2]]), 0, (1, 2),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([[1, 3]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform16(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[1, 0.0], [0, 0.5]]), 0,
+ (3, 8), order=order)
+ assert_array_almost_equal(out[..., ::2], data)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform17(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 1]]), 0,
+ (6, 4), order=order)
+ assert_array_almost_equal(out[::2, ...], data)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform18(self, order, xp):
+ data = xp.asarray([[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]])
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
+ (6, 8), order=order)
+ assert_array_almost_equal(out[::2, ::2], data)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform19(self, order, xp):
+ data = xp.asarray([[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]], dtype=xp.float64)
+ out = ndimage.affine_transform(data, xp.asarray([[0.5, 0], [0, 0.5]]), 0,
+ (6, 8), order=order)
+ out = ndimage.affine_transform(out, xp.asarray([[2.0, 0], [0, 2.0]]), 0,
+ (3, 4), order=order)
+ assert_array_almost_equal(out, data)
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8394")
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform20(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[0], [2]]), 0, (2,),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 3]))
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8394")
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform21(self, order, xp):
+ data = [[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]]
+ data = xp.asarray(data)
+ out = ndimage.affine_transform(data, xp.asarray([[2], [0]]), 0, (2,),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 9]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform22(self, order, xp):
+ # shift and offset interaction; see issue #1547
+ data = xp.asarray([4, 1, 3, 2])
+ out = ndimage.affine_transform(data, xp.asarray([[2]]), [-1], (3,),
+ order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 2]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform23(self, order, xp):
+ # shift and offset interaction; see issue #1547
+ data = xp.asarray([4, 1, 3, 2])
+ out = ndimage.affine_transform(data, xp.asarray([[0.5]]), [-1], (8,),
+ order=order)
+ assert_array_almost_equal(out[::2], xp.asarray([0, 4, 1, 3]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform24(self, order, xp):
+ # consistency between diagonal and non-diagonal case; see issue #1547
+ data = xp.asarray([4, 1, 3, 2])
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ 'The behavior of affine_transform with a 1-D array .* has changed',
+ UserWarning)
+ out1 = ndimage.affine_transform(data, xp.asarray([2]), -1, order=order)
+ out2 = ndimage.affine_transform(data, xp.asarray([[2]]), -1, order=order)
+ assert_array_almost_equal(out1, out2)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform25(self, order, xp):
+ # consistency between diagonal and non-diagonal case; see issue #1547
+ data = xp.asarray([4, 1, 3, 2])
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore",
+ 'The behavior of affine_transform with a 1-D array .* '
+ 'has changed', UserWarning)
+ out1 = ndimage.affine_transform(data, xp.asarray([0.5]), -1, order=order)
+ out2 = ndimage.affine_transform(data, xp.asarray([[0.5]]), -1, order=order)
+ assert_array_almost_equal(out1, out2)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform26(self, order, xp):
+ # test homogeneous coordinates
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ if (order > 1):
+ filtered = ndimage.spline_filter(data, order=order)
+ else:
+ filtered = data
+ tform_original = xp.eye(2)
+ offset_original = -xp.ones((2, 1))
+
+ tform_h1 = xp.concat((tform_original, offset_original), axis=1) # hstack
+ tform_h2 = xp.concat((tform_h1, xp.asarray([[0.0, 0, 1]])), axis=0) # vstack
+
+ offs = [float(x) for x in xp.reshape(offset_original, (-1,))]
+
+ out1 = ndimage.affine_transform(filtered, tform_original,
+ offs,
+ order=order, prefilter=False)
+ out2 = ndimage.affine_transform(filtered, tform_h1, order=order,
+ prefilter=False)
+ out3 = ndimage.affine_transform(filtered, tform_h2, order=order,
+ prefilter=False)
+ for out in [out1, out2, out3]:
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]]))
+
+ @xfail_xp_backends("cupy", reason="does not raise")
+ def test_affine_transform27(self, xp):
+ # test valid homogeneous transformation matrix
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ tform_h1 = xp.concat((xp.eye(2), -xp.ones((2, 1))) , axis=1) # vstack
+ tform_h2 = xp.concat((tform_h1, xp.asarray([[5.0, 2, 1]])), axis=0) # hstack
+
+ assert_raises(ValueError, ndimage.affine_transform, data, tform_h2)
+
+ @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
+ def test_affine_transform_1d_endianness_with_output_parameter(self, xp):
+ # 1d affine transform given output ndarray or dtype with
+ # either endianness. see issue #7388
+ data = xp.ones((2, 2))
+ for out in [xp.empty_like(data),
+ xp.empty_like(data).astype(data.dtype.newbyteorder()),
+ data.dtype, data.dtype.newbyteorder()]:
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore",
+ 'The behavior of affine_transform with a 1-D array '
+ '.* has changed', UserWarning)
+ matrix = xp.asarray([1, 1])
+ returned = ndimage.affine_transform(data, matrix, output=out)
+ result = out if returned is None else returned
+ assert_array_almost_equal(result, xp.asarray([[1, 1], [1, 1]]))
+
+ @skip_xp_backends(np_only=True, reason='byteorder is numpy-specific')
+ def test_affine_transform_multi_d_endianness_with_output_parameter(self, xp):
+ # affine transform given output ndarray or dtype with either endianness
+ # see issue #4127
+ # NB: byteorder is numpy-specific
+ data = np.asarray([1])
+ for out in [data.dtype, data.dtype.newbyteorder(),
+ np.empty_like(data),
+ np.empty_like(data).astype(data.dtype.newbyteorder())]:
+ returned = ndimage.affine_transform(data, np.asarray([[1]]), output=out)
+ result = out if returned is None else returned
+ assert_array_almost_equal(result, np.asarray([1]))
+
+ @skip_xp_backends(np_only=True,
+ reason='`out` of a different size is numpy-specific'
+ )
+ def test_affine_transform_output_shape(self, xp):
+ # don't require output_shape when out of a different size is given
+ data = xp.arange(8, dtype=xp.float64)
+ out = xp.ones((16,))
+
+ ndimage.affine_transform(data, xp.asarray([[1]]), output=out)
+ assert_array_almost_equal(out[:8], data)
+
+ # mismatched output shape raises an error
+ with pytest.raises(RuntimeError):
+ ndimage.affine_transform(
+ data, [[1]], output=out, output_shape=(12,))
+
+ @skip_xp_backends(np_only=True, reason='string `output` is numpy-specific')
+ def test_affine_transform_with_string_output(self, xp):
+ data = xp.asarray([1])
+ out = ndimage.affine_transform(data, xp.asarray([[1]]), output='f')
+ assert out.dtype is np.dtype('f')
+ assert_array_almost_equal(out, xp.asarray([1]))
+
+ @pytest.mark.parametrize('shift',
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform_shift_via_grid_wrap(self, shift, order, xp):
+ # For mode 'grid-wrap', integer shifts should match np.roll
+ x = np.asarray([[0, 1],
+ [2, 3]])
+ affine = np.zeros((2, 3))
+ affine[:2, :2] = np.eye(2)
+ affine[:, 2] = np.asarray(shift)
+
+ expected = np.roll(x, shift, axis=(0, 1))
+
+ x = xp.asarray(x)
+ affine = xp.asarray(affine)
+ expected = xp.asarray(expected)
+
+ assert_array_almost_equal(
+ ndimage.affine_transform(x, affine, mode='grid-wrap', order=order),
+ expected
+ )
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_affine_transform_shift_reflect(self, order, xp):
+ # shift by x.shape results in reflection
+ x = np.asarray([[0, 1, 2],
+ [3, 4, 5]])
+ expected = x[::-1, ::-1].copy() # strides >0 for torch
+ x = xp.asarray(x)
+ expected = xp.asarray(expected)
+
+ affine = np.zeros([2, 3])
+ affine[:2, :2] = np.eye(2)
+ affine[:, 2] = np.asarray(x.shape)
+ affine = xp.asarray(affine)
+
+ assert_array_almost_equal(
+ ndimage.affine_transform(x, affine, mode='reflect', order=order),
+ expected,
+ )
+
+
+@make_xp_test_case(ndimage.shift)
+class TestShift:
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift01(self, order, xp):
+ data = xp.asarray([1])
+ out = ndimage.shift(data, [1], order=order)
+ assert_array_almost_equal(out, xp.asarray([0]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift02(self, order, xp):
+ data = xp.ones([4])
+ out = ndimage.shift(data, [1], order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift03(self, order, xp):
+ data = xp.ones([4])
+ out = ndimage.shift(data, -1, order=order)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift04(self, order, xp):
+ data = xp.asarray([4, 1, 3, 2])
+ out = ndimage.shift(data, 1, order=order)
+ assert_array_almost_equal(out, xp.asarray([0, 4, 1, 3]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+ def test_shift05(self, order, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1]], dtype=dtype)
+ expected = xp.asarray([[0, 1, 1, 1],
+ [0, 1, 1, 1],
+ [0, 1, 1, 1]], dtype=dtype)
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ expected -= 1j * expected
+ out = ndimage.shift(data, [0, 1], order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('mode', ['constant', 'grid-constant'])
+ @pytest.mark.parametrize('dtype', ['float64', 'complex128'])
+ def test_shift_with_nonzero_cval(self, order, mode, dtype, xp):
+ data = np.asarray([[1, 1, 1, 1],
+ [1, 1, 1, 1],
+ [1, 1, 1, 1]], dtype=dtype)
+
+ expected = np.asarray([[0, 1, 1, 1],
+ [0, 1, 1, 1],
+ [0, 1, 1, 1]], dtype=dtype)
+
+ if np_compat.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ expected -= 1j * expected
+ cval = 5.0
+ expected[:, 0] = cval # specific to shift of [0, 1] used below
+
+ data = xp.asarray(data)
+ expected = xp.asarray(expected)
+ out = ndimage.shift(data, [0, 1], order=order, mode=mode, cval=cval)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift06(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.shift(data, [0, 1], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 4, 1, 3],
+ [0, 7, 6, 8],
+ [0, 3, 5, 3]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift07(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.shift(data, [1, 0], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [4, 1, 3, 2],
+ [7, 6, 8, 5]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift08(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ out = ndimage.shift(data, [1, 1], order=order)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift09(self, order, xp):
+ data = xp.asarray([[4, 1, 3, 2],
+ [7, 6, 8, 5],
+ [3, 5, 3, 6]])
+ if (order > 1):
+ filtered = ndimage.spline_filter(data, order=order)
+ else:
+ filtered = data
+ out = ndimage.shift(filtered, [1, 1], order=order, prefilter=False)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0],
+ [0, 4, 1, 3],
+ [0, 7, 6, 8]]))
+
+ @pytest.mark.parametrize('shift',
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift_grid_wrap(self, shift, order, xp):
+ # For mode 'grid-wrap', integer shifts should match np.roll
+ x = np.asarray([[0, 1],
+ [2, 3]])
+ expected = np.roll(x, shift, axis=(0,1))
+
+ x = xp.asarray(x)
+ expected = xp.asarray(expected)
+
+ assert_array_almost_equal(
+ ndimage.shift(x, shift, mode='grid-wrap', order=order),
+ expected
+ )
+
+ @pytest.mark.parametrize('shift',
+ [(1, 0), (0, 1), (-1, 1), (3, -5), (2, 7)])
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift_grid_constant1(self, shift, order, xp):
+ # For integer shifts, 'constant' and 'grid-constant' should be equal
+ x = xp.reshape(xp.arange(20), (5, 4))
+ assert_array_almost_equal(
+ ndimage.shift(x, shift, mode='grid-constant', order=order),
+ ndimage.shift(x, shift, mode='constant', order=order),
+ )
+
+ def test_shift_grid_constant_order1(self, xp):
+ x = xp.asarray([[1, 2, 3],
+ [4, 5, 6]], dtype=xp.float64)
+ expected_result = xp.asarray([[0.25, 0.75, 1.25],
+ [1.25, 3.00, 4.00]])
+ assert_array_almost_equal(
+ ndimage.shift(x, (0.5, 0.5), mode='grid-constant', order=1),
+ expected_result,
+ )
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_shift_reflect(self, order, xp):
+ # shift by x.shape results in reflection
+ x = np.asarray([[0, 1, 2],
+ [3, 4, 5]])
+ expected = x[::-1, ::-1].copy() # strides > 0 for torch
+
+ x = xp.asarray(x)
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(
+ ndimage.shift(x, x.shape, mode='reflect', order=order),
+ expected,
+ )
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('prefilter', [False, True])
+ def test_shift_nearest_boundary(self, order, prefilter, xp):
+ # verify that shifting at least order // 2 beyond the end of the array
+ # gives a value equal to the edge value.
+ x = xp.arange(16)
+ kwargs = dict(mode='nearest', order=order, prefilter=prefilter)
+ assert_array_almost_equal(
+ ndimage.shift(x, order // 2 + 1, **kwargs)[0], x[0],
+ )
+ assert_array_almost_equal(
+ ndimage.shift(x, -order // 2 - 1, **kwargs)[-1], x[-1],
+ )
+
+ @pytest.mark.parametrize('mode', ['grid-constant', 'grid-wrap', 'nearest',
+ 'mirror', 'reflect'])
+ @pytest.mark.parametrize('order', range(6))
+ def test_shift_vs_padded(self, order, mode, xp):
+ x_np = np.arange(144, dtype=float).reshape(12, 12)
+ shift = (0.4, -2.3)
+
+ # manually pad and then extract center to get expected result
+ npad = 32
+ pad_mode = ndimage_to_numpy_mode.get(mode)
+ x_padded = xp.asarray(np.pad(x_np, npad, mode=pad_mode))
+ x = xp.asarray(x_np)
+
+ center_slice = tuple([slice(npad, -npad)] * x.ndim)
+ expected_result = ndimage.shift(
+ x_padded, shift, mode=mode, order=order)[center_slice]
+
+ xp_assert_close(
+ ndimage.shift(x, shift, mode=mode, order=order),
+ expected_result,
+ rtol=1e-7,
+ )
+
+
+@make_xp_test_case(ndimage.zoom)
+class TestZoom:
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_zoom1(self, order, xp):
+ for z in [2, [2, 2]]:
+ arr = xp.reshape(xp.arange(25, dtype=xp.float64), (5, 5))
+ arr = ndimage.zoom(arr, z, order=order)
+ assert arr.shape == (10, 10)
+ assert xp.all(arr[-1, :] != 0)
+ assert xp.all(arr[-1, :] >= (20 - eps))
+ assert xp.all(arr[0, :] <= (5 + eps))
+ assert xp.all(arr >= (0 - eps))
+ assert xp.all(arr <= (24 + eps))
+
+ def test_zoom2(self, xp):
+ arr = xp.reshape(xp.arange(12), (3, 4))
+ out = ndimage.zoom(ndimage.zoom(arr, 2), 0.5)
+ xp_assert_equal(out, arr)
+
+ def test_zoom3(self, xp):
+ arr = xp.asarray([[1, 2]])
+ out1 = ndimage.zoom(arr, (2, 1))
+ out2 = ndimage.zoom(arr, (1, 2))
+
+ assert_array_almost_equal(out1, xp.asarray([[1, 2], [1, 2]]))
+ assert_array_almost_equal(out2, xp.asarray([[1, 1, 2, 2]]))
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+ def test_zoom_affine01(self, order, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[1, 2, 3, 4],
+ [5, 6, 7, 8],
+ [9, 10, 11, 12]], dtype=dtype)
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore",
+ 'The behavior of affine_transform with a 1-D array .* '
+ 'has changed', UserWarning)
+ out = ndimage.affine_transform(data, xp.asarray([0.5, 0.5]), 0,
+ (6, 8), order=order)
+ assert_array_almost_equal(out[::2, ::2], data)
+
+ def test_zoom_infinity(self, xp):
+ # Ticket #1419 regression test
+ dim = 8
+ ndimage.zoom(xp.zeros((dim, dim)), 1. / dim, mode='nearest')
+
+ def test_zoom_zoomfactor_one(self, xp):
+ # Ticket #1122 regression test
+ arr = xp.zeros((1, 5, 5))
+ zoom = (1.0, 2.0, 2.0)
+
+ out = ndimage.zoom(arr, zoom, cval=7)
+ ref = xp.zeros((1, 10, 10))
+ assert_array_almost_equal(out, ref)
+
+ def test_zoom_output_shape_roundoff(self, xp):
+ arr = xp.zeros((3, 11, 25))
+ zoom = (4.0 / 3, 15.0 / 11, 29.0 / 25)
+ out = ndimage.zoom(arr, zoom)
+ assert out.shape == (4, 15, 29)
+
+ @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
+ @pytest.mark.parametrize('mode', ['nearest', 'constant', 'wrap', 'reflect',
+ 'mirror', 'grid-wrap', 'grid-mirror',
+ 'grid-constant'])
+ def test_zoom_by_int_order0(self, zoom, mode, xp):
+ # order 0 zoom should be the same as replication via np.kron
+ # Note: This is not True for general x shapes when grid_mode is False,
+ # but works here for all modes because the size ratio happens to
+ # always be an integer when x.shape = (2, 2).
+ x_np = np.asarray([[0, 1],
+ [2, 3]], dtype=np.float64)
+ expected = np.kron(x_np, np.ones(zoom))
+
+ x = xp.asarray(x_np)
+ expected = xp.asarray(expected)
+
+ assert_array_almost_equal(
+ ndimage.zoom(x, zoom, order=0, mode=mode),
+ expected
+ )
+
+ @pytest.mark.parametrize('shape', [(2, 3), (4, 4)])
+ @pytest.mark.parametrize('zoom', [(1, 1), (3, 5), (8, 2), (8, 8)])
+ @pytest.mark.parametrize('mode', ['nearest', 'reflect', 'mirror',
+ 'grid-wrap', 'grid-constant'])
+ def test_zoom_grid_by_int_order0(self, shape, zoom, mode, xp):
+ # When grid_mode is True, order 0 zoom should be the same as
+ # replication via np.kron. The only exceptions to this are the
+ # non-grid modes 'constant' and 'wrap'.
+ x_np = np.arange(np.prod(shape), dtype=float).reshape(shape)
+
+ x = xp.asarray(x_np)
+ assert_array_almost_equal(
+ ndimage.zoom(x, zoom, order=0, mode=mode, grid_mode=True),
+ xp.asarray(np.kron(x_np, np.ones(zoom)))
+ )
+
+ @pytest.mark.parametrize('mode', ['constant', 'wrap'])
+ def test_zoom_grid_mode_warnings(self, mode, xp):
+ # Warn on use of non-grid modes when grid_mode is True
+ x = xp.reshape(xp.arange(9, dtype=xp.float64), (3, 3))
+ with pytest.warns(UserWarning,
+ match="It is recommended to use mode"):
+ ndimage.zoom(x, 2, mode=mode, grid_mode=True),
+
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ def test_zoom_output_shape(self, xp):
+ """Ticket #643"""
+ x = xp.reshape(xp.arange(12), (3, 4))
+ ndimage.zoom(x, 2, output=xp.zeros((6, 8)))
+
+ def test_zoom_0d_array(self, xp):
+ # Ticket #21670 regression test
+ a = xp.arange(10.)
+ factor = 2
+ actual = ndimage.zoom(a, np.array(factor))
+ expected = ndimage.zoom(a, factor)
+ xp_assert_close(actual, expected)
+
+ @xfail_xp_backends("cupy", reason="CuPy `zoom` needs similar fix.")
+ def test_zoom_1_gh20999(self, xp):
+ # gh-20999 reported that zoom with `zoom=1` (or sequence of ones)
+ # introduced noise. Check that this is resolved.
+ x = xp.eye(3)
+ xp_assert_equal(ndimage.zoom(x, 1), x)
+ xp_assert_equal(ndimage.zoom(x, (1, 1)), x)
+
+ @xfail_xp_backends("cupy", reason="CuPy `zoom` needs similar fix.")
+ @skip_xp_backends("jax.numpy", reason="read-only backend")
+ @xfail_xp_backends("dask.array", reason="numpy round-trip")
+ def test_zoom_1_gh20999_output(self, xp):
+ x = xp.eye(3)
+ output = xp.zeros_like(x)
+ ndimage.zoom(x, 1, output=output)
+ xp_assert_equal(output, x)
+
+
+@make_xp_test_case(ndimage.rotate)
+class TestRotate:
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate01(self, order, xp):
+ data = xp.asarray([[0, 0, 0, 0],
+ [0, 1, 1, 0],
+ [0, 0, 0, 0]], dtype=xp.float64)
+ out = ndimage.rotate(data, 0, order=order)
+ assert_array_almost_equal(out, data)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate02(self, order, xp):
+ data = xp.asarray([[0, 0, 0, 0],
+ [0, 1, 0, 0],
+ [0, 0, 0, 0]], dtype=xp.float64)
+ expected = xp.asarray([[0, 0, 0],
+ [0, 0, 0],
+ [0, 1, 0],
+ [0, 0, 0]], dtype=xp.float64)
+ out = ndimage.rotate(data, 90, order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ @pytest.mark.parametrize('dtype', ["float64", "complex128"])
+ def test_rotate03(self, order, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0]], dtype=dtype)
+ expected = xp.asarray([[0, 0, 0],
+ [0, 0, 0],
+ [0, 1, 0],
+ [0, 1, 0],
+ [0, 0, 0]], dtype=dtype)
+ if xp.isdtype(data.dtype, 'complex floating'):
+ data -= 1j * data
+ expected -= 1j * expected
+ out = ndimage.rotate(data, 90, order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate04(self, order, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0]], dtype=xp.float64)
+ expected = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0]], dtype=xp.float64)
+ out = ndimage.rotate(data, 90, reshape=False, order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate05(self, order, xp):
+ data = np.empty((4, 3, 3))
+ for i in range(3):
+ data[:, :, i] = np.asarray([[0, 0, 0],
+ [0, 1, 0],
+ [0, 1, 0],
+ [0, 0, 0]], dtype=np.float64)
+ data = xp.asarray(data)
+ expected = xp.asarray([[0, 0, 0, 0],
+ [0, 1, 1, 0],
+ [0, 0, 0, 0]], dtype=xp.float64)
+ out = ndimage.rotate(data, 90, order=order)
+ for i in range(3):
+ assert_array_almost_equal(out[:, :, i], expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate06(self, order, xp):
+ data = np.empty((3, 4, 3))
+ for i in range(3):
+ data[:, :, i] = np.asarray([[0, 0, 0, 0],
+ [0, 1, 1, 0],
+ [0, 0, 0, 0]], dtype=np.float64)
+ data = xp.asarray(data)
+ expected = xp.asarray([[0, 0, 0],
+ [0, 1, 0],
+ [0, 1, 0],
+ [0, 0, 0]], dtype=xp.float64)
+ out = ndimage.rotate(data, 90, order=order)
+ for i in range(3):
+ assert_array_almost_equal(out[:, :, i], expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate07(self, order, xp):
+ data = xp.asarray([[[0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+ data = xp.permute_dims(data, (2, 1, 0))
+ expected = xp.asarray([[[0, 0, 0],
+ [0, 1, 0],
+ [0, 1, 0],
+ [0, 0, 0],
+ [0, 0, 0]]] * 2, dtype=xp.float64)
+ expected = xp.permute_dims(expected, (2, 1, 0))
+ out = ndimage.rotate(data, 90, axes=(0, 1), order=order)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('order', range(0, 6))
+ def test_rotate08(self, order, xp):
+ data = xp.asarray([[[0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+ data = xp.permute_dims(data, (2, 1, 0)) # == np.transpose
+ expected = xp.asarray([[[0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0]]] * 2, dtype=xp.float64)
+ expected = xp.permute_dims(expected, (2, 1, 0))
+ out = ndimage.rotate(data, 90, axes=(0, 1), reshape=False, order=order)
+ assert_array_almost_equal(out, expected)
+
+ def test_rotate09(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0]] * 2, dtype=xp.float64)
+ with assert_raises(ValueError):
+ ndimage.rotate(data, 90, axes=(0, data.ndim))
+
+ def test_rotate10(self, xp):
+ data = xp.reshape(xp.arange(45, dtype=xp.float64), (3, 5, 3))
+
+ # The output of ndimage.rotate before refactoring
+ expected = xp.asarray([[[0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0],
+ [6.54914793, 7.54914793, 8.54914793],
+ [10.84520162, 11.84520162, 12.84520162],
+ [0.0, 0.0, 0.0]],
+ [[6.19286575, 7.19286575, 8.19286575],
+ [13.4730712, 14.4730712, 15.4730712],
+ [21.0, 22.0, 23.0],
+ [28.5269288, 29.5269288, 30.5269288],
+ [35.80713425, 36.80713425, 37.80713425]],
+ [[0.0, 0.0, 0.0],
+ [31.15479838, 32.15479838, 33.15479838],
+ [35.45085207, 36.45085207, 37.45085207],
+ [0.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0]]], dtype=xp.float64)
+
+ out = ndimage.rotate(data, angle=12, reshape=False)
+ #assert_array_almost_equal(out, expected)
+ xp_assert_close(out, expected, rtol=1e-6, atol=2e-6)
+
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8400")
+ def test_rotate_exact_180(self, xp):
+ a = xp.asarray(np.tile(np.arange(5), (5, 1)))
+ b = ndimage.rotate(ndimage.rotate(a, 180), -180)
+ xp_assert_equal(a, b)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_measurements.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_measurements.py
new file mode 100644
index 0000000000000000000000000000000000000000..20c0e09b4137d124ce5977b87c0f762557e422e2
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_measurements.py
@@ -0,0 +1,1696 @@
+import os
+import os.path
+import warnings
+
+import numpy as np
+
+from scipy._lib._array_api import (
+ is_torch,
+ xp_assert_equal,
+ xp_assert_close,
+ assert_array_almost_equal,
+ assert_almost_equal,
+ make_xp_test_case,
+)
+
+import pytest
+from pytest import raises as assert_raises
+
+import scipy.ndimage as ndimage
+
+from . import types
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+IS_WINDOWS_AND_NP1 = os.name == 'nt' and np.__version__ < '2'
+
+
+@skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
+class Test_measurements_stats:
+ """ndimage._measurements._stats() is a utility used by other functions.
+
+ Since internal ndimage/_measurements.py code is NumPy-only,
+ so is this this test class.
+ """
+ def test_a(self, xp):
+ x = [0, 1, 2, 6]
+ labels = [0, 0, 1, 1]
+ index = [0, 1]
+ for shp in [(4,), (2, 2)]:
+ x = np.array(x).reshape(shp)
+ labels = np.array(labels).reshape(shp)
+ counts, sums = ndimage._measurements._stats(
+ x, labels=labels, index=index)
+
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+
+ def test_b(self, xp):
+ # Same data as test_a, but different labels. The label 9 exceeds the
+ # length of 'labels', so this test will follow a different code path.
+ x = [0, 1, 2, 6]
+ labels = [0, 0, 9, 9]
+ index = [0, 9]
+ for shp in [(4,), (2, 2)]:
+ x = np.array(x).reshape(shp)
+ labels = np.array(labels).reshape(shp)
+ counts, sums = ndimage._measurements._stats(
+ x, labels=labels, index=index)
+
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+
+ def test_a_centered(self, xp):
+ x = [0, 1, 2, 6]
+ labels = [0, 0, 1, 1]
+ index = [0, 1]
+ for shp in [(4,), (2, 2)]:
+ x = np.array(x).reshape(shp)
+ labels = np.array(labels).reshape(shp)
+ counts, sums, centers = ndimage._measurements._stats(
+ x, labels=labels, index=index, centered=True)
+
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+ def test_b_centered(self, xp):
+ x = [0, 1, 2, 6]
+ labels = [0, 0, 9, 9]
+ index = [0, 9]
+ for shp in [(4,), (2, 2)]:
+ x = np.array(x).reshape(shp)
+ labels = np.array(labels).reshape(shp)
+ counts, sums, centers = ndimage._measurements._stats(
+ x, labels=labels, index=index, centered=True)
+
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+ def test_nonint_labels(self, xp):
+ x = [0, 1, 2, 6]
+ labels = [0.0, 0.0, 9.0, 9.0]
+ index = [0.0, 9.0]
+ for shp in [(4,), (2, 2)]:
+ x = np.array(x).reshape(shp)
+ labels = np.array(labels).reshape(shp)
+ counts, sums, centers = ndimage._measurements._stats(
+ x, labels=labels, index=index, centered=True)
+
+ dtype_arg = {'dtype': np.int64} if IS_WINDOWS_AND_NP1 else {}
+ xp_assert_equal(counts, np.asarray([2, 2], **dtype_arg))
+ xp_assert_equal(sums, np.asarray([1.0, 8.0]))
+ xp_assert_equal(centers, np.asarray([0.5, 8.0]))
+
+
+@skip_xp_backends(np_only=True, reason='test internal numpy-only helpers')
+class Test_measurements_select:
+ """ndimage._measurements._select() is a utility used by other functions."""
+
+ def test_basic(self, xp):
+ x = [0, 1, 6, 2]
+ cases = [
+ ([0, 0, 1, 1], [0, 1]), # "Small" integer labels
+ ([0, 0, 9, 9], [0, 9]), # A label larger than len(labels)
+ ([0.0, 0.0, 7.0, 7.0], [0.0, 7.0]), # Non-integer labels
+ ]
+ for labels, index in cases:
+ result = ndimage._measurements._select(
+ x, labels=labels, index=index)
+ assert len(result) == 0
+ result = ndimage._measurements._select(
+ x, labels=labels, index=index, find_max=True)
+ assert len(result) == 1
+ xp_assert_equal(result[0], [1, 6])
+ result = ndimage._measurements._select(
+ x, labels=labels, index=index, find_min=True)
+ assert len(result) == 1
+ xp_assert_equal(result[0], [0, 2])
+ result = ndimage._measurements._select(
+ x, labels=labels, index=index, find_min=True,
+ find_min_positions=True)
+ assert len(result) == 2
+ xp_assert_equal(result[0], [0, 2])
+ xp_assert_equal(result[1], [0, 3])
+ assert result[1].dtype.kind == 'i'
+ result = ndimage._measurements._select(
+ x, labels=labels, index=index, find_max=True,
+ find_max_positions=True)
+ assert len(result) == 2
+ xp_assert_equal(result[0], [1, 6])
+ xp_assert_equal(result[1], [1, 2])
+ assert result[1].dtype.kind == 'i'
+
+
+@make_xp_test_case(ndimage.label)
+def test_label01(xp):
+ data = xp.ones(())
+ out, n = ndimage.label(data)
+ assert out == 1
+ assert n == 1
+
+
+@make_xp_test_case(ndimage.label)
+def test_label02(xp):
+ data = xp.zeros(())
+ out, n = ndimage.label(data)
+ assert out == 0
+ assert n == 0
+
+
+@make_xp_test_case(ndimage.label)
+def test_label03(xp):
+ data = xp.ones([1])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray([1]))
+ assert n == 1
+
+
+@make_xp_test_case(ndimage.label)
+def test_label04(xp):
+ data = xp.zeros([1])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray([0]))
+ assert n == 0
+
+
+@make_xp_test_case(ndimage.label)
+def test_label05(xp):
+ data = xp.ones([5])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+ assert n == 1
+
+
+@make_xp_test_case(ndimage.label)
+def test_label06(xp):
+ data = xp.asarray([1, 0, 1, 1, 0, 1])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 2, 2, 0, 3]))
+ assert n == 3
+
+
+@make_xp_test_case(ndimage.label)
+def test_label07(xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0]])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray(
+ [[0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0]]))
+ assert n == 0
+
+
+@make_xp_test_case(ndimage.label)
+def test_label08(xp):
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [1, 1, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0]])
+ out, n = ndimage.label(data)
+ assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [3, 3, 0, 0, 0, 0],
+ [3, 3, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]]))
+ assert n == 4
+
+
+@make_xp_test_case(ndimage.label)
+def test_label09(xp):
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [1, 1, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0]])
+ struct = ndimage.generate_binary_structure(2, 2)
+ struct = xp.asarray(struct)
+ out, n = ndimage.label(data, struct)
+ assert_array_almost_equal(out, xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [2, 2, 0, 0, 0, 0],
+ [2, 2, 0, 0, 0, 0],
+ [0, 0, 0, 3, 3, 0]]))
+ assert n == 3
+
+
+@make_xp_test_case(ndimage.label)
+def test_label10(xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0]])
+ struct = ndimage.generate_binary_structure(2, 2)
+ struct = xp.asarray(struct)
+ out, n = ndimage.label(data, struct)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0]]))
+ assert n == 1
+
+
+@make_xp_test_case(ndimage.label)
+def test_label11(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [1, 1, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
+ out, n = ndimage.label(data)
+ expected = [[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [3, 3, 0, 0, 0, 0],
+ [3, 3, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+ assert n == 4
+
+
+@skip_xp_backends(np_only=True, reason='inplace output is numpy-specific')
+@make_xp_test_case(ndimage.label)
+def test_label11_inplace(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [1, 1, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
+ n = ndimage.label(data, output=data)
+ expected = [[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [3, 3, 0, 0, 0, 0],
+ [3, 3, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(data, expected)
+ assert n == 4
+
+
+@make_xp_test_case(ndimage.label)
+def test_label12(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ data = xp.asarray([[0, 0, 0, 0, 1, 1],
+ [0, 0, 0, 0, 0, 1],
+ [0, 0, 1, 0, 1, 1],
+ [0, 0, 1, 1, 1, 1],
+ [0, 0, 0, 1, 1, 0]], dtype=dtype)
+ out, n = ndimage.label(data)
+ expected = [[0, 0, 0, 0, 1, 1],
+ [0, 0, 0, 0, 0, 1],
+ [0, 0, 1, 0, 1, 1],
+ [0, 0, 1, 1, 1, 1],
+ [0, 0, 0, 1, 1, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+ assert n == 1
+
+
+@make_xp_test_case(ndimage.label)
+def test_label13(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ data = xp.asarray([[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
+ [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]],
+ dtype=dtype)
+ out, n = ndimage.label(data)
+ expected = [[1, 0, 1, 1, 1, 0, 1, 1, 1, 0, 1],
+ [1, 1, 1, 0, 1, 1, 1, 0, 1, 1, 1],
+ [1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+ assert n == 1
+
+
+@skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='output=dtype is numpy-specific')
+@make_xp_test_case(ndimage.label)
+def test_label_output_typed(xp):
+ data = xp.ones([5])
+ for t in types:
+ dtype = getattr(xp, t)
+ output = xp.zeros([5], dtype=dtype)
+ n = ndimage.label(data, output=output)
+ assert_array_almost_equal(output,
+ xp.ones(output.shape, dtype=output.dtype))
+ assert n == 1
+
+
+@skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='output=dtype is numpy-specific')
+@make_xp_test_case(ndimage.label)
+def test_label_output_dtype(xp):
+ data = xp.ones([5])
+ for t in types:
+ dtype = getattr(xp, t)
+ output, n = ndimage.label(data, output=dtype)
+ assert_array_almost_equal(output,
+ xp.ones(output.shape, dtype=output.dtype))
+ assert output.dtype == t
+
+
+@skip_xp_backends(np_only=True, reason="in-place output is numpy-specific")
+@make_xp_test_case(ndimage.label)
+def test_label_output_wrong_size(xp):
+ data = xp.ones([5])
+ for t in types:
+ dtype = getattr(xp, t)
+ output = xp.zeros([10], dtype=dtype)
+ assert_raises(ValueError, ndimage.label, data, output=output)
+
+
+@make_xp_test_case(ndimage.label)
+def test_label_structuring_elements(xp):
+ data = np.loadtxt(os.path.join(os.path.dirname(
+ __file__), "data", "label_inputs.txt"))
+ strels = np.loadtxt(os.path.join(
+ os.path.dirname(__file__), "data", "label_strels.txt"))
+ results = np.loadtxt(os.path.join(
+ os.path.dirname(__file__), "data", "label_results.txt"))
+ data = data.reshape((-1, 7, 7))
+ strels = strels.reshape((-1, 3, 3))
+ results = results.reshape((-1, 7, 7))
+
+ data = xp.asarray(data)
+ strels = xp.asarray(strels)
+ results = xp.asarray(results)
+ r = 0
+ for i in range(data.shape[0]):
+ d = data[i, :, :]
+ for j in range(strels.shape[0]):
+ s = strels[j, :, :]
+ xp_assert_equal(ndimage.label(d, s)[0], results[r, :, :], check_dtype=False)
+ r += 1
+
+
+@make_xp_test_case(ndimage.label, ndimage.find_objects)
+def test_ticket_742(xp):
+ def SE(img, thresh=.7, size=4):
+ mask = img > thresh
+ rank = len(mask.shape)
+ struct = ndimage.generate_binary_structure(rank, rank)
+ struct = xp.asarray(struct)
+ la, co = ndimage.label(mask,
+ struct)
+ _ = ndimage.find_objects(la)
+
+ if np.dtype(np.intp) != np.dtype('i'):
+ shape = (3, 1240, 1240)
+ a = np.random.rand(np.prod(shape)).reshape(shape)
+ a = xp.asarray(a)
+ # shouldn't crash
+ SE(a)
+
+
+@make_xp_test_case(ndimage.label)
+def test_gh_issue_3025(xp):
+ """Github issue #3025 - improper merging of labels"""
+ d = np.zeros((60, 320))
+ d[:, :257] = 1
+ d[:, 260:] = 1
+ d[36, 257] = 1
+ d[35, 258] = 1
+ d[35, 259] = 1
+ d = xp.asarray(d)
+ assert ndimage.label(d, xp.ones((3, 3)))[1] == 1
+
+
+@make_xp_test_case(ndimage.label, ndimage.find_objects)
+class TestFindObjects:
+ def test_label_default_dtype(self, xp):
+ test_array = np.random.rand(10, 10)
+ test_array = xp.asarray(test_array)
+ label, no_features = ndimage.label(test_array > 0.5)
+ assert label.dtype in (xp.int32, xp.int64)
+ # Shouldn't raise an exception
+ ndimage.find_objects(label)
+
+
+ def test_find_objects01(self, xp):
+ data = xp.ones([], dtype=xp.int64)
+ out = ndimage.find_objects(data)
+ assert out == [()]
+
+
+ def test_find_objects02(self, xp):
+ data = xp.zeros([], dtype=xp.int64)
+ out = ndimage.find_objects(data)
+ assert out == []
+
+
+ def test_find_objects03(self, xp):
+ data = xp.ones([1], dtype=xp.int64)
+ out = ndimage.find_objects(data)
+ assert out == [(slice(0, 1, None),)]
+
+
+ def test_find_objects04(self, xp):
+ data = xp.zeros([1], dtype=xp.int64)
+ out = ndimage.find_objects(data)
+ assert out == []
+
+
+ def test_find_objects05(self, xp):
+ data = xp.ones([5], dtype=xp.int64)
+ out = ndimage.find_objects(data)
+ assert out == [(slice(0, 5, None),)]
+
+
+ def test_find_objects06(self, xp):
+ data = xp.asarray([1, 0, 2, 2, 0, 3])
+ out = ndimage.find_objects(data)
+ assert out == [(slice(0, 1, None),),
+ (slice(2, 4, None),),
+ (slice(5, 6, None),)]
+
+
+ def test_find_objects07(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0]])
+ out = ndimage.find_objects(data)
+ assert out == []
+
+
+ def test_find_objects08(self, xp):
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [3, 3, 0, 0, 0, 0],
+ [3, 3, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]])
+ out = ndimage.find_objects(data)
+ assert out == [(slice(0, 1, None), slice(0, 1, None)),
+ (slice(1, 3, None), slice(2, 5, None)),
+ (slice(3, 5, None), slice(0, 2, None)),
+ (slice(5, 6, None), slice(3, 5, None))]
+
+
+ def test_find_objects09(self, xp):
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]])
+ out = ndimage.find_objects(data)
+ assert out == [(slice(0, 1, None), slice(0, 1, None)),
+ (slice(1, 3, None), slice(2, 5, None)),
+ None,
+ (slice(5, 6, None), slice(3, 5, None))]
+
+
+@make_xp_test_case(ndimage.value_indices)
+def test_value_indices01(xp):
+ "Test dictionary keys and entries"
+ data = xp.asarray([[1, 0, 0, 0, 0, 0],
+ [0, 0, 2, 2, 0, 0],
+ [0, 0, 2, 2, 2, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 0]])
+ vi = ndimage.value_indices(data, ignore_value=0)
+ true_keys = [1, 2, 4]
+ assert list(vi.keys()) == true_keys
+
+ truevi = {k: xp.nonzero(data == k) for k in true_keys}
+
+ vi = ndimage.value_indices(data, ignore_value=0)
+ assert vi.keys() == truevi.keys()
+ for key in vi.keys():
+ assert len(vi[key]) == len(truevi[key])
+ for v, true_v in zip(vi[key], truevi[key]):
+ xp_assert_equal(v, true_v)
+
+
+@make_xp_test_case(ndimage.value_indices)
+def test_value_indices02(xp):
+ "Test input checking"
+ data = xp.zeros((5, 4), dtype=xp.float32)
+ msg = "Parameter 'arr' must be an integer array"
+ with assert_raises(ValueError, match=msg):
+ ndimage.value_indices(data)
+
+
+@make_xp_test_case(ndimage.value_indices)
+def test_value_indices03(xp):
+ "Test different input array shapes, from 1-D to 4-D"
+ for shape in [(36,), (18, 2), (3, 3, 4), (3, 3, 2, 2)]:
+ a = np.asarray((12*[1]+12*[2]+12*[3]), dtype=np.int32)
+ a = np.reshape(a, shape)
+
+ trueKeys = np.unique(a)
+ a = xp.asarray(a)
+ vi = ndimage.value_indices(a)
+ assert list(vi.keys()) == list(trueKeys)
+ for k in [int(x) for x in trueKeys]:
+ trueNdx = xp.nonzero(a == k)
+ assert len(vi[k]) == len(trueNdx)
+ for vik, true_vik in zip(vi[k], trueNdx):
+ xp_assert_equal(vik, true_vik)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum01(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([], dtype=dtype)
+ output = ndimage.sum(input)
+ assert output == 0
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum02(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.zeros([0, 4], dtype=dtype)
+ output = ndimage.sum(input)
+ assert output == 0
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum03(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.ones([], dtype=dtype)
+ output = ndimage.sum(input)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum04(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 2], dtype=dtype)
+ output = ndimage.sum(input)
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum05(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.sum(input)
+ assert_almost_equal(output, xp.asarray(10.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum06(xp):
+ labels = np.asarray([], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([], dtype=dtype)
+ output = ndimage.sum(input, labels=labels)
+ assert output == 0
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum07(xp):
+ labels = np.ones([0, 4], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.zeros([0, 4], dtype=dtype)
+ output = ndimage.sum(input, labels=labels)
+ assert output == 0
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum08(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 2], dtype=dtype)
+ output = ndimage.sum(input, labels=labels)
+ assert output == 1
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum09(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.sum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum10(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ input = np.asarray([[1, 2], [3, 4]], dtype=bool)
+
+ labels = xp.asarray(labels)
+ input = xp.asarray(input)
+ output = ndimage.sum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum11(xp):
+ labels = xp.asarray([1, 2], dtype=xp.int8)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.sum(input, labels=labels,
+ index=2)
+ assert_almost_equal(output, xp.asarray(6.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum12(xp):
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
+ assert_array_almost_equal(output, xp.asarray([4.0, 0.0, 5.0]))
+
+
+@make_xp_test_case(ndimage.sum)
+def test_sum_labels(xp):
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output_sum = ndimage.sum(input, labels=labels, index=xp.asarray([4, 8, 2]))
+ output_labels = ndimage.sum_labels(
+ input, labels=labels, index=xp.asarray([4, 8, 2]))
+
+ assert xp.all(output_sum == output_labels)
+ assert_array_almost_equal(output_labels, xp.asarray([4.0, 0.0, 5.0]))
+
+
+@make_xp_test_case(ndimage.mean)
+def test_mean01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.mean(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.mean)
+def test_mean02(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ input = np.asarray([[1, 2], [3, 4]], dtype=bool)
+
+ labels = xp.asarray(labels)
+ input = xp.asarray(input)
+ output = ndimage.mean(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.mean)
+def test_mean03(xp):
+ labels = xp.asarray([1, 2])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.mean(input, labels=labels,
+ index=2)
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.mean)
+def test_mean04(xp):
+ labels = xp.asarray([[1, 2], [2, 4]], dtype=xp.int8)
+ with np.errstate(all='ignore'):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.mean(input, labels=labels,
+ index=xp.asarray([4, 8, 2]))
+ # XXX: output[[0, 2]] does not work in array-api-strict; annoying
+ # assert_array_almost_equal(output[[0, 2]], xp.asarray([4.0, 2.5]))
+ assert output[0] == 4.0
+ assert output[2] == 2.5
+ assert xp.isnan(output[1])
+
+
+@make_xp_test_case(ndimage.minimum)
+def test_minimum01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.minimum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.minimum)
+def test_minimum02(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ input = np.asarray([[2, 2], [2, 4]], dtype=bool)
+
+ labels = xp.asarray(labels)
+ input = xp.asarray(input)
+ output = ndimage.minimum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.minimum)
+def test_minimum03(xp):
+ labels = xp.asarray([1, 2])
+ for type in types:
+ dtype = getattr(xp, type)
+
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.minimum(input, labels=labels,
+ index=2)
+ assert_almost_equal(output, xp.asarray(2.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.minimum)
+def test_minimum04(xp):
+ labels = xp.asarray([[1, 2], [2, 3]])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.minimum(input, labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ assert_array_almost_equal(output, xp.asarray([2.0, 4.0, 0.0]))
+
+
+@make_xp_test_case(ndimage.maximum)
+def test_maximum01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.maximum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.maximum)
+def test_maximum02(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ input = np.asarray([[2, 2], [2, 4]], dtype=bool)
+ labels = xp.asarray(labels)
+ input = xp.asarray(input)
+ output = ndimage.maximum(input, labels=labels)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.maximum)
+def test_maximum03(xp):
+ labels = xp.asarray([1, 2])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.maximum(input, labels=labels,
+ index=2)
+ assert_almost_equal(output, xp.asarray(4.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.maximum)
+def test_maximum04(xp):
+ labels = xp.asarray([[1, 2], [2, 3]])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.maximum(input, labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ assert_array_almost_equal(output, xp.asarray([3.0, 4.0, 0.0]))
+
+
+@make_xp_test_case(ndimage.maximum)
+def test_maximum05(xp):
+ # Regression test for ticket #501 (Trac)
+ x = xp.asarray([-3, -2, -1])
+ assert ndimage.maximum(x) == -1
+
+
+@make_xp_test_case(ndimage.median)
+def test_median01(xp):
+ a = xp.asarray([[1, 2, 0, 1],
+ [5, 3, 0, 4],
+ [0, 0, 0, 7],
+ [9, 3, 0, 0]])
+ labels = xp.asarray([[1, 1, 0, 2],
+ [1, 1, 0, 2],
+ [0, 0, 0, 2],
+ [3, 3, 0, 0]])
+ output = ndimage.median(a, labels=labels, index=xp.asarray([1, 2, 3]))
+ assert_array_almost_equal(output, xp.asarray([2.5, 4.0, 6.0]))
+
+
+@make_xp_test_case(ndimage.median)
+def test_median02(xp):
+ a = xp.asarray([[1, 2, 0, 1],
+ [5, 3, 0, 4],
+ [0, 0, 0, 7],
+ [9, 3, 0, 0]])
+ output = ndimage.median(a)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.median)
+def test_median03(xp):
+ a = xp.asarray([[1, 2, 0, 1],
+ [5, 3, 0, 4],
+ [0, 0, 0, 7],
+ [9, 3, 0, 0]])
+ labels = xp.asarray([[1, 1, 0, 2],
+ [1, 1, 0, 2],
+ [0, 0, 0, 2],
+ [3, 3, 0, 0]])
+ output = ndimage.median(a, labels=labels)
+ assert_almost_equal(output, xp.asarray(3.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.median)
+def test_median_gh12836_bool(xp):
+ # test boolean addition fix on example from gh-12836
+ a = np.asarray([1, 1], dtype=bool)
+ a = xp.asarray(a)
+ output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
+ assert_array_almost_equal(output, xp.asarray([1.0]))
+
+
+@make_xp_test_case(ndimage.median)
+def test_median_no_int_overflow(xp):
+ # test integer overflow fix on example from gh-12836
+ a = xp.asarray([65, 70], dtype=xp.int8)
+ output = ndimage.median(a, labels=xp.ones((2,)), index=xp.asarray([1]))
+ assert_array_almost_equal(output, xp.asarray([67.5]))
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance01(xp):
+ with np.errstate(all='ignore'):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([], dtype=dtype)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "Mean of empty slice", RuntimeWarning)
+ output = ndimage.variance(input)
+ assert xp.isnan(output)
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance02(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1], dtype=dtype)
+ output = ndimage.variance(input)
+ assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance03(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 3], dtype=dtype)
+ output = ndimage.variance(input)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance04(xp):
+ input = np.asarray([1, 0], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.variance(input)
+ assert_almost_equal(output, xp.asarray(0.25), check_0d=False)
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance05(xp):
+ labels = xp.asarray([2, 2, 3])
+ for type in types:
+ dtype = getattr(xp, type)
+
+ input = xp.asarray([1, 3, 8], dtype=dtype)
+ output = ndimage.variance(input, labels, 2)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.variance)
+def test_variance06(xp):
+ labels = xp.asarray([2, 2, 3, 3, 4])
+ with np.errstate(all='ignore'):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
+ output = ndimage.variance(input, labels, xp.asarray([2, 3, 4]))
+ assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation01(xp):
+ with np.errstate(all='ignore'):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([], dtype=dtype)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "Mean of empty slice", RuntimeWarning)
+ output = ndimage.standard_deviation(input)
+ assert xp.isnan(output)
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation02(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1], dtype=dtype)
+ output = ndimage.standard_deviation(input)
+ assert_almost_equal(output, xp.asarray(0.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation03(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 3], dtype=dtype)
+ output = ndimage.standard_deviation(input)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation04(xp):
+ input = np.asarray([1, 0], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.standard_deviation(input)
+ assert_almost_equal(output, xp.asarray(0.5), check_0d=False)
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation05(xp):
+ labels = xp.asarray([2, 2, 3])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 3, 8], dtype=dtype)
+ output = ndimage.standard_deviation(input, labels, 2)
+ assert_almost_equal(output, xp.asarray(1.0), check_0d=False)
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation06(xp):
+ labels = xp.asarray([2, 2, 3, 3, 4])
+ with np.errstate(all='ignore'):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([1, 3, 8, 10, 8], dtype=dtype)
+ output = ndimage.standard_deviation(
+ input, labels, xp.asarray([2, 3, 4])
+ )
+ assert_array_almost_equal(output, xp.asarray([1.0, 1.0, 0.0]))
+
+
+@make_xp_test_case(ndimage.standard_deviation)
+def test_standard_deviation07(xp):
+ labels = xp.asarray([1])
+ with np.errstate(all='ignore'):
+ for type in types:
+ if is_torch(xp) and type == 'uint8':
+ pytest.xfail("value cannot be converted to type uint8 "
+ "without overflow")
+ dtype = getattr(xp, type)
+ input = xp.asarray([-0.00619519], dtype=dtype)
+ output = ndimage.standard_deviation(input, labels, xp.asarray([1]))
+ assert_array_almost_equal(output, xp.asarray([0]))
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.minimum_position(input, labels=labels)
+ assert output == (0, 0)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position02(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 0, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.minimum_position(input)
+ assert output == (1, 2)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position03(xp):
+ input = np.asarray([[5, 4, 2, 5],
+ [3, 7, 0, 2],
+ [1, 5, 1, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.minimum_position(input)
+ assert output == (1, 2)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position04(xp):
+ input = np.asarray([[5, 4, 2, 5],
+ [3, 7, 1, 2],
+ [1, 5, 1, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.minimum_position(input)
+ assert output == (0, 0)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position05(xp):
+ labels = xp.asarray([1, 2, 0, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 0, 2],
+ [1, 5, 2, 3]], dtype=dtype)
+ output = ndimage.minimum_position(input, labels)
+ assert output == (2, 0)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position06(xp):
+ labels = xp.asarray([1, 2, 3, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 0, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.minimum_position(input, labels, 2)
+ assert output == (0, 1)
+
+
+@make_xp_test_case(ndimage.minimum_position)
+def test_minimum_position07(xp):
+ labels = xp.asarray([1, 2, 3, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 0, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.minimum_position(input, labels,
+ xp.asarray([2, 3]))
+ assert output[0] == (0, 1)
+ assert output[1] == (1, 2)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output = ndimage.maximum_position(input,
+ labels=labels)
+ assert output == (1, 0)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position02(xp):
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.maximum_position(input)
+ assert output == (1, 2)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position03(xp):
+ input = np.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.maximum_position(input)
+ assert output == (0, 0)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position04(xp):
+ labels = xp.asarray([1, 2, 0, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.maximum_position(input, labels)
+ assert output == (1, 1)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position05(xp):
+ labels = xp.asarray([1, 2, 0, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.maximum_position(input, labels, 1)
+ assert output == (0, 0)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position06(xp):
+ labels = xp.asarray([1, 2, 0, 4])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.maximum_position(input, labels,
+ xp.asarray([1, 2]))
+ assert output[0] == (0, 0)
+ assert output[1] == (1, 1)
+
+
+@make_xp_test_case(ndimage.maximum_position)
+def test_maximum_position07(xp):
+ # Test float labels
+ labels = xp.asarray([1.0, 2.5, 0.0, 4.5])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output = ndimage.maximum_position(input, labels,
+ xp.asarray([1.0, 4.5]))
+ assert output[0] == (0, 0)
+ assert output[1] == (0, 3)
+
+
+@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
+ ndimage.minimum_position, ndimage.maximum_position)
+def test_extrema01(xp):
+ labels = np.asarray([1, 0], dtype=bool)
+ labels = xp.asarray(labels)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output1 = ndimage.extrema(input, labels=labels)
+ output2 = ndimage.minimum(input, labels=labels)
+ output3 = ndimage.maximum(input, labels=labels)
+ output4 = ndimage.minimum_position(input,
+ labels=labels)
+ output5 = ndimage.maximum_position(input,
+ labels=labels)
+ assert output1 == (output2, output3, output4, output5)
+
+
+@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
+ ndimage.minimum_position, ndimage.maximum_position)
+def test_extrema02(xp):
+ labels = xp.asarray([1, 2])
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output1 = ndimage.extrema(input, labels=labels,
+ index=2)
+ output2 = ndimage.minimum(input, labels=labels,
+ index=2)
+ output3 = ndimage.maximum(input, labels=labels,
+ index=2)
+ output4 = ndimage.minimum_position(input,
+ labels=labels, index=2)
+ output5 = ndimage.maximum_position(input,
+ labels=labels, index=2)
+ assert output1 == (output2, output3, output4, output5)
+
+
+@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
+ ndimage.minimum_position, ndimage.maximum_position)
+def test_extrema03(xp):
+ labels = xp.asarray([[1, 2], [2, 3]])
+ for type in types:
+ if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
+ pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 2], [3, 4]], dtype=dtype)
+ output1 = ndimage.extrema(input,
+ labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ output2 = ndimage.minimum(input,
+ labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ output3 = ndimage.maximum(input, labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ output4 = ndimage.minimum_position(input,
+ labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ output5 = ndimage.maximum_position(input,
+ labels=labels,
+ index=xp.asarray([2, 3, 8]))
+ assert_array_almost_equal(output1[0], output2)
+ assert_array_almost_equal(output1[1], output3)
+ assert output1[2] == output4
+ assert output1[3] == output5
+
+
+@make_xp_test_case(ndimage.extrema, ndimage.minimum, ndimage.maximum,
+ ndimage.minimum_position, ndimage.maximum_position)
+def test_extrema04(xp):
+ labels = xp.asarray([1, 2, 0, 4])
+ for type in types:
+ if is_torch(xp) and type in ("uint16", "uint32", "uint64"):
+ pytest.xfail("https://github.com/pytorch/pytorch/issues/58734")
+
+ dtype = getattr(xp, type)
+ input = xp.asarray([[5, 4, 2, 5],
+ [3, 7, 8, 2],
+ [1, 5, 1, 1]], dtype=dtype)
+ output1 = ndimage.extrema(input, labels, xp.asarray([1, 2]))
+ output2 = ndimage.minimum(input, labels, xp.asarray([1, 2]))
+ output3 = ndimage.maximum(input, labels, xp.asarray([1, 2]))
+ output4 = ndimage.minimum_position(input, labels,
+ xp.asarray([1, 2]))
+ output5 = ndimage.maximum_position(input, labels,
+ xp.asarray([1, 2]))
+ assert_array_almost_equal(output1[0], output2)
+ assert_array_almost_equal(output1[1], output3)
+ assert output1[2] == output4
+ assert output1[3] == output5
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass01(xp):
+ expected = (0.0, 0.0)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 0], [0, 0]], dtype=dtype)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass02(xp):
+ expected = (1, 0)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[0, 0], [1, 0]], dtype=dtype)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass03(xp):
+ expected = (0, 1)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[0, 1], [0, 0]], dtype=dtype)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass04(xp):
+ expected = (1, 1)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[0, 0], [0, 1]], dtype=dtype)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass05(xp):
+ expected = (0.5, 0.5)
+ for type in types:
+ dtype = getattr(xp, type)
+ input = xp.asarray([[1, 1], [1, 1]], dtype=dtype)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass06(xp):
+ expected = (0.5, 0.5)
+ input = np.asarray([[1, 2], [3, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.center_of_mass(input)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass07(xp):
+ labels = xp.asarray([1, 0])
+ expected = (0.5, 0.0)
+ input = np.asarray([[1, 2], [3, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.center_of_mass(input, labels)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass08(xp):
+ labels = xp.asarray([1, 2])
+ expected = (0.5, 1.0)
+ input = np.asarray([[5, 2], [3, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.center_of_mass(input, labels, 2)
+ assert output == expected
+
+
+@make_xp_test_case(ndimage.center_of_mass)
+def test_center_of_mass09(xp):
+ labels = xp.asarray((1, 2))
+ expected = xp.asarray([(0.5, 0.0), (0.5, 1.0)], dtype=xp.float64)
+ input = np.asarray([[1, 2], [1, 1]], dtype=bool)
+ input = xp.asarray(input)
+ output = ndimage.center_of_mass(input, labels, xp.asarray([1, 2]))
+ xp_assert_equal(xp.asarray(output), xp.asarray(expected))
+
+
+@make_xp_test_case(ndimage.histogram)
+def test_histogram01(xp):
+ expected = xp.ones(10)
+ input = xp.arange(10)
+ output = ndimage.histogram(input, 0, 10, 10)
+ assert_array_almost_equal(output, expected)
+
+
+@make_xp_test_case(ndimage.histogram)
+def test_histogram02(xp):
+ labels = xp.asarray([1, 1, 1, 1, 2, 2, 2, 2])
+ expected = xp.asarray([0, 2, 0, 1, 1])
+ input = xp.asarray([1, 1, 3, 4, 3, 3, 3, 3])
+ output = ndimage.histogram(input, 0, 4, 5, labels, 1)
+ assert_array_almost_equal(output, expected)
+
+
+@skip_xp_backends(np_only=True, reason='object arrays')
+@make_xp_test_case(ndimage.histogram)
+def test_histogram03(xp):
+ labels = xp.asarray([1, 0, 1, 1, 2, 2, 2, 2])
+ expected1 = xp.asarray([0, 1, 0, 1, 1])
+ expected2 = xp.asarray([0, 0, 0, 3, 0])
+ input = xp.asarray([1, 1, 3, 4, 3, 5, 3, 3])
+
+ output = ndimage.histogram(input, 0, 4, 5, labels, (1, 2))
+
+ assert_array_almost_equal(output[0], expected1)
+ assert_array_almost_equal(output[1], expected2)
+
+@make_xp_test_case(ndimage.mean, ndimage.variance, ndimage.standard_deviation,
+ ndimage.median, ndimage.minimum, ndimage.maximum)
+def test_stat_funcs_2d(xp):
+ a = xp.asarray([[5, 6, 0, 0, 0], [8, 9, 0, 0, 0], [0, 0, 0, 3, 5]])
+ lbl = xp.asarray([[1, 1, 0, 0, 0], [1, 1, 0, 0, 0], [0, 0, 0, 2, 2]])
+
+ mean = ndimage.mean(a, labels=lbl, index=xp.asarray([1, 2]))
+ xp_assert_equal(mean, xp.asarray([7.0, 4.0], dtype=xp.float64))
+
+ var = ndimage.variance(a, labels=lbl, index=xp.asarray([1, 2]))
+ xp_assert_equal(var, xp.asarray([2.5, 1.0], dtype=xp.float64))
+
+ std = ndimage.standard_deviation(a, labels=lbl, index=xp.asarray([1, 2]))
+ assert_array_almost_equal(std, xp.sqrt(xp.asarray([2.5, 1.0], dtype=xp.float64)))
+
+ med = ndimage.median(a, labels=lbl, index=xp.asarray([1, 2]))
+ xp_assert_equal(med, xp.asarray([7.0, 4.0], dtype=xp.float64))
+
+ min = ndimage.minimum(a, labels=lbl, index=xp.asarray([1, 2]))
+ xp_assert_equal(min, xp.asarray([5, 3]), check_dtype=False)
+
+ max = ndimage.maximum(a, labels=lbl, index=xp.asarray([1, 2]))
+ xp_assert_equal(max, xp.asarray([9, 5]), check_dtype=False)
+
+
+@skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
+@make_xp_test_case(ndimage.watershed_ift)
+class TestWatershedIft:
+
+ def test_watershed_ift01(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+ structure=xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+ out = ndimage.watershed_ift(data, markers, structure=structure)
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ def test_watershed_ift02(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+ out = ndimage.watershed_ift(data, markers)
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, 1, 1, 1, -1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, -1, 1, 1, 1, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ def test_watershed_ift03(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 2, 0, 3, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, -1]], dtype=xp.int8)
+ out = ndimage.watershed_ift(data, markers)
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, 2, -1, 3, -1, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, -1, 2, -1, 3, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ def test_watershed_ift04(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 2, 0, 3, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, -1]],
+ dtype=xp.int8)
+
+ structure=xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+ out = ndimage.watershed_ift(data, markers, structure=structure)
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, 2, 2, 3, 3, 3, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ def test_watershed_ift05(self, xp):
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 0, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 3, 0, 2, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, -1]],
+ dtype=xp.int8)
+ structure = xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+ out = ndimage.watershed_ift(data, markers, structure=structure)
+ expected = [[-1, -1, -1, -1, -1, -1, -1],
+ [-1, 3, 3, 2, 2, 2, -1],
+ [-1, 3, 3, 2, 2, 2, -1],
+ [-1, 3, 3, 2, 2, 2, -1],
+ [-1, 3, 3, 2, 2, 2, -1],
+ [-1, 3, 3, 2, 2, 2, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ def test_watershed_ift06(self, xp):
+ data = xp.asarray([[0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.uint8)
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+ structure=xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+ out = ndimage.watershed_ift(data, markers, structure=structure)
+ expected = [[-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ @skip_xp_backends(np_only=True, reason="inplace ops are numpy-specific")
+ def test_watershed_ift07(self, xp):
+ shape = (7, 6)
+ data = np.zeros(shape, dtype=np.uint8)
+ data = data.transpose()
+ data[...] = np.asarray([[0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 0, 0, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=np.uint8)
+ data = xp.asarray(data)
+ markers = xp.asarray([[-1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=xp.int8)
+ out = xp.zeros(shape, dtype=xp.int16)
+ out = out.T
+ structure=xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+ ndimage.watershed_ift(data, markers, structure=structure,
+ output=out)
+ expected = [[-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, 1, 1, 1, 1, 1, -1],
+ [-1, -1, -1, -1, -1, -1, -1],
+ [-1, -1, -1, -1, -1, -1, -1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
+ def test_watershed_ift08(self, xp):
+ # Test cost larger than uint8. See gh-10069.
+ data = xp.asarray([[256, 0],
+ [0, 0]], dtype=xp.uint16)
+ markers = xp.asarray([[1, 0],
+ [0, 0]], dtype=xp.int8)
+ out = ndimage.watershed_ift(data, markers)
+ expected = [[1, 1],
+ [1, 1]]
+ assert_array_almost_equal(out, xp.asarray(expected))
+
+ @skip_xp_backends("cupy", reason="no watershed_ift on CuPy")
+ def test_watershed_ift09(self, xp):
+ # Test large cost. See gh-19575
+ data = xp.asarray([[xp.iinfo(xp.uint16).max, 0],
+ [0, 0]], dtype=xp.uint16)
+ markers = xp.asarray([[1, 0],
+ [0, 0]], dtype=xp.int8)
+ out = ndimage.watershed_ift(data, markers)
+ expected = [[1, 1],
+ [1, 1]]
+ xp_assert_close(out, xp.asarray(expected), check_dtype=False)
+
+
+@skip_xp_backends(np_only=True)
+@pytest.mark.parametrize("dt", [np.intc, np.uintc])
+@make_xp_test_case(ndimage.value_indices)
+def test_gh_19423(dt, xp):
+ rng = np.random.default_rng(123)
+ max_val = 8
+ image = rng.integers(low=0, high=max_val, size=(10, 12)).astype(dtype=dt)
+ val_idx = ndimage.value_indices(image)
+ assert len(val_idx.keys()) == max_val
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_morphology.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_morphology.py
new file mode 100644
index 0000000000000000000000000000000000000000..810b8b2b791e9b2d855f4ede8dad3bf199b470f8
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_morphology.py
@@ -0,0 +1,3105 @@
+import numpy as np
+from scipy._lib._array_api import (
+ is_cupy, is_numpy,
+ xp_assert_close, xp_assert_equal, assert_array_almost_equal,
+ make_xp_test_case,
+ make_xp_pytest_param,
+)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy import ndimage
+
+from . import types
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+
+class TestNdimageMorphology:
+
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ # brute force (bf) distance transform
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_bf(data, 'euclidean',
+ return_indices=True)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 2, 4, 2, 1, 0, 0],
+ [0, 0, 1, 4, 8, 4, 1, 0, 0],
+ [0, 0, 1, 2, 4, 2, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out * out, expected)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 2, 1, 2, 2, 2, 2],
+ [3, 3, 3, 2, 1, 2, 3, 3, 3],
+ [4, 4, 4, 4, 6, 4, 4, 4, 4],
+ [5, 5, 6, 6, 7, 6, 6, 5, 5],
+ [6, 6, 6, 7, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 1, 2, 4, 6, 7, 7, 8],
+ [0, 1, 1, 1, 6, 7, 7, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_bf(data, 'cityblock',
+ return_indices=True)
+
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 2, 2, 2, 1, 0, 0],
+ [0, 0, 1, 2, 3, 2, 1, 0, 0],
+ [0, 0, 1, 2, 2, 2, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 2, 1, 2, 2, 2, 2],
+ [3, 3, 3, 3, 1, 3, 3, 3, 3],
+ [4, 4, 4, 4, 7, 4, 4, 4, 4],
+ [5, 5, 6, 7, 7, 7, 6, 5, 5],
+ [6, 6, 6, 7, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 1, 1, 4, 7, 7, 7, 8],
+ [0, 1, 1, 1, 4, 7, 7, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_bf(data, 'chessboard',
+ return_indices=True)
+
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 2, 1, 1, 0, 0],
+ [0, 0, 1, 2, 2, 2, 1, 0, 0],
+ [0, 0, 1, 1, 2, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 2, 1, 2, 2, 2, 2],
+ [3, 3, 4, 2, 2, 2, 4, 3, 3],
+ [4, 4, 5, 6, 6, 6, 5, 4, 4],
+ [5, 5, 6, 6, 7, 6, 6, 5, 5],
+ [6, 6, 6, 7, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 5, 6, 6, 7, 8],
+ [0, 1, 1, 2, 6, 6, 7, 7, 8],
+ [0, 1, 1, 2, 6, 7, 7, 7, 8],
+ [0, 1, 2, 2, 6, 6, 7, 7, 8],
+ [0, 1, 2, 4, 5, 6, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+
+ @skip_xp_backends(
+ np_only=True, reason='inplace distances= arrays are numpy-specific'
+ )
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf04(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ tdt, tft = ndimage.distance_transform_bf(data, return_indices=1)
+ dts = []
+ fts = []
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ndimage.distance_transform_bf(data, distances=dt)
+ dts.append(dt)
+ ft = ndimage.distance_transform_bf(
+ data, return_distances=False, return_indices=1)
+ fts.append(ft)
+ ft = np.indices(data.shape, dtype=xp.int32)
+ ndimage.distance_transform_bf(
+ data, return_distances=False, return_indices=True, indices=ft)
+ fts.append(ft)
+ dt, ft = ndimage.distance_transform_bf(
+ data, return_indices=1)
+ dts.append(dt)
+ fts.append(ft)
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ft = ndimage.distance_transform_bf(
+ data, distances=dt, return_indices=True)
+ dts.append(dt)
+ fts.append(ft)
+ ft = np.indices(data.shape, dtype=xp.int32)
+ dt = ndimage.distance_transform_bf(
+ data, return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ft = np.indices(data.shape, dtype=xp.int32)
+ ndimage.distance_transform_bf(
+ data, distances=dt, return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+ for dt in dts:
+ assert_array_almost_equal(tdt, dt)
+ for ft in fts:
+ assert_array_almost_equal(tft, ft)
+
+ @xfail_xp_backends('cupy', reason='CuPy does not have distance_transform_bf')
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf05(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_bf(
+ data, 'euclidean', return_indices=True, sampling=[2, 2])
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 4, 4, 4, 0, 0, 0],
+ [0, 0, 4, 8, 16, 8, 4, 0, 0],
+ [0, 0, 4, 16, 32, 16, 4, 0, 0],
+ [0, 0, 4, 8, 16, 8, 4, 0, 0],
+ [0, 0, 0, 4, 4, 4, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out * out, expected)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 2, 1, 2, 2, 2, 2],
+ [3, 3, 3, 2, 1, 2, 3, 3, 3],
+ [4, 4, 4, 4, 6, 4, 4, 4, 4],
+ [5, 5, 6, 6, 7, 6, 6, 5, 5],
+ [6, 6, 6, 7, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 1, 2, 4, 6, 7, 7, 8],
+ [0, 1, 1, 1, 6, 7, 7, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_bf06(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_bf(
+ data, 'euclidean', return_indices=True, sampling=[2, 1])
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 4, 1, 0, 0, 0],
+ [0, 0, 1, 4, 8, 4, 1, 0, 0],
+ [0, 0, 1, 4, 9, 4, 1, 0, 0],
+ [0, 0, 1, 4, 8, 4, 1, 0, 0],
+ [0, 0, 0, 1, 4, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out * out, expected)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 2, 2, 2, 2, 2, 2],
+ [3, 3, 3, 3, 2, 3, 3, 3, 3],
+ [4, 4, 4, 4, 4, 4, 4, 4, 4],
+ [5, 5, 5, 5, 6, 5, 5, 5, 5],
+ [6, 6, 6, 6, 7, 6, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 6, 6, 6, 7, 8],
+ [0, 1, 1, 1, 6, 7, 7, 7, 8],
+ [0, 1, 1, 1, 7, 7, 7, 7, 8],
+ [0, 1, 1, 1, 6, 7, 7, 7, 8],
+ [0, 1, 2, 2, 4, 6, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @make_xp_test_case(ndimage.distance_transform_bf)
+ def test_distance_transform_bf07(self, xp):
+ # test input validation per discussion on PR #13302
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+ with assert_raises(RuntimeError):
+ ndimage.distance_transform_bf(
+ data, return_distances=False, return_indices=False
+ )
+
+ @make_xp_test_case(ndimage.distance_transform_bf,
+ ndimage.distance_transform_cdt)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_cdt01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ # chamfer type distance (cdt) transform
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_cdt(
+ data, 'cityblock', return_indices=True)
+ bf = ndimage.distance_transform_bf(data, 'cityblock')
+ assert_array_almost_equal(bf, out)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 1, 1, 1, 2, 2, 2],
+ [3, 3, 2, 1, 1, 1, 2, 3, 3],
+ [4, 4, 4, 4, 1, 4, 4, 4, 4],
+ [5, 5, 5, 5, 7, 7, 6, 5, 5],
+ [6, 6, 6, 6, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 1, 1, 4, 7, 7, 7, 8],
+ [0, 1, 1, 1, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @make_xp_test_case(ndimage.distance_transform_bf,
+ ndimage.distance_transform_cdt)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_cdt02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_cdt(data, 'chessboard',
+ return_indices=True)
+ bf = ndimage.distance_transform_bf(data, 'chessboard')
+ assert_array_almost_equal(bf, out)
+
+ expected = [[[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 1, 1],
+ [2, 2, 2, 1, 1, 1, 2, 2, 2],
+ [3, 3, 2, 2, 1, 2, 2, 3, 3],
+ [4, 4, 3, 2, 2, 2, 3, 4, 4],
+ [5, 5, 4, 6, 7, 6, 4, 5, 5],
+ [6, 6, 6, 6, 7, 7, 6, 6, 6],
+ [7, 7, 7, 7, 7, 7, 7, 7, 7],
+ [8, 8, 8, 8, 8, 8, 8, 8, 8]],
+ [[0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 2, 3, 4, 6, 7, 8],
+ [0, 1, 1, 2, 2, 6, 6, 7, 8],
+ [0, 1, 1, 1, 2, 6, 7, 7, 8],
+ [0, 1, 1, 2, 6, 6, 7, 7, 8],
+ [0, 1, 2, 2, 5, 6, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8],
+ [0, 1, 2, 3, 4, 5, 6, 7, 8]]]
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(ft, expected)
+
+ @skip_xp_backends(
+ np_only=True, reason='inplace indices= arrays are numpy-specific'
+ )
+ @make_xp_test_case(ndimage.distance_transform_cdt)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_cdt03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ tdt, tft = ndimage.distance_transform_cdt(data, return_indices=True)
+ dts = []
+ fts = []
+ dt = xp.zeros(data.shape, dtype=xp.int32)
+ ndimage.distance_transform_cdt(data, distances=dt)
+ dts.append(dt)
+ ft = ndimage.distance_transform_cdt(
+ data, return_distances=False, return_indices=True)
+ fts.append(ft)
+ ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+ ndimage.distance_transform_cdt(
+ data, return_distances=False, return_indices=True, indices=ft)
+ fts.append(ft)
+ dt, ft = ndimage.distance_transform_cdt(
+ data, return_indices=True)
+ dts.append(dt)
+ fts.append(ft)
+ dt = xp.zeros(data.shape, dtype=xp.int32)
+ ft = ndimage.distance_transform_cdt(
+ data, distances=dt, return_indices=True)
+ dts.append(dt)
+ fts.append(ft)
+ ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+ dt = ndimage.distance_transform_cdt(
+ data, return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+ dt = xp.zeros(data.shape, dtype=xp.int32)
+ ft = xp.asarray(np.indices(data.shape, dtype=np.int32))
+ ndimage.distance_transform_cdt(data, distances=dt,
+ return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+ for dt in dts:
+ assert_array_almost_equal(tdt, dt)
+ for ft in fts:
+ assert_array_almost_equal(tft, ft)
+
+ @skip_xp_backends(
+ np_only=True, reason='XXX: does not raise unless indices is a numpy array'
+ )
+ @make_xp_test_case(ndimage.distance_transform_cdt)
+ def test_distance_transform_cdt04(self, xp):
+ # test input validation per discussion on PR #13302
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+ indices_out = xp.zeros((data.ndim,) + data.shape, dtype=xp.int32)
+ with assert_raises(RuntimeError):
+ ndimage.distance_transform_bf(
+ data,
+ return_distances=True,
+ return_indices=False,
+ indices=indices_out
+ )
+
+ @xfail_xp_backends("torch", reason="int overflow")
+ @make_xp_test_case(ndimage.distance_transform_cdt)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_cdt05(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ # test custom metric type per discussion on issue #17381
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ metric_arg = xp.ones((3, 3))
+ actual = ndimage.distance_transform_cdt(data, metric=metric_arg)
+ assert xp.sum(actual) == -21
+
+ @skip_xp_backends("cupy", reason="CuPy does not have distance_transform_bf")
+ @make_xp_test_case(ndimage.distance_transform_edt,
+ ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_edt01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ # euclidean distance transform (edt)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out, ft = ndimage.distance_transform_edt(data, return_indices=True)
+ bf = ndimage.distance_transform_bf(data, 'euclidean')
+ assert_array_almost_equal(bf, out)
+
+ # np-specific check
+ np_ft = np.asarray(ft)
+ dt = np_ft - np.indices(np_ft.shape[1:], dtype=np_ft.dtype)
+ dt = dt.astype(np.float64)
+ np.multiply(dt, dt, dt)
+ dt = np.add.reduce(dt, axis=0)
+ np.sqrt(dt, dt)
+
+ dt = xp.asarray(dt)
+ assert_array_almost_equal(bf, dt)
+
+ @skip_xp_backends(
+ np_only=True, reason='inplace distances= are numpy-specific'
+ )
+ @make_xp_test_case(ndimage.distance_transform_edt,
+ ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_edt02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ tdt, tft = ndimage.distance_transform_edt(data, return_indices=True)
+ dts = []
+ fts = []
+
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ndimage.distance_transform_edt(data, distances=dt)
+ dts.append(dt)
+
+ ft = ndimage.distance_transform_edt(
+ data, return_distances=0, return_indices=True)
+ fts.append(ft)
+
+ ft = np.indices(data.shape, dtype=xp.int32)
+ ft = xp.asarray(ft)
+ ndimage.distance_transform_edt(
+ data, return_distances=False, return_indices=True, indices=ft)
+ fts.append(ft)
+
+ dt, ft = ndimage.distance_transform_edt(
+ data, return_indices=True)
+ dts.append(dt)
+ fts.append(ft)
+
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ft = ndimage.distance_transform_edt(
+ data, distances=dt, return_indices=True)
+ dts.append(dt)
+ fts.append(ft)
+
+ ft = np.indices(data.shape, dtype=xp.int32)
+ ft = xp.asarray(ft)
+ dt = ndimage.distance_transform_edt(
+ data, return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+
+ dt = xp.zeros(data.shape, dtype=xp.float64)
+ ft = np.indices(data.shape, dtype=xp.int32)
+ ft = xp.asarray(ft)
+ ndimage.distance_transform_edt(
+ data, distances=dt, return_indices=True, indices=ft)
+ dts.append(dt)
+ fts.append(ft)
+
+ for dt in dts:
+ assert_array_almost_equal(tdt, dt)
+ for ft in fts:
+ assert_array_almost_equal(tft, ft)
+
+ @make_xp_test_case(ndimage.distance_transform_edt,
+ ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_edt03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 2])
+ out = ndimage.distance_transform_edt(data, sampling=[2, 2])
+ assert_array_almost_equal(out, ref)
+
+ @make_xp_test_case(ndimage.distance_transform_edt,
+ ndimage.distance_transform_bf)
+ @pytest.mark.parametrize('dtype', types)
+ def test_distance_transform_edt4(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ ref = ndimage.distance_transform_bf(data, 'euclidean', sampling=[2, 1])
+ out = ndimage.distance_transform_edt(data, sampling=[2, 1])
+ assert_array_almost_equal(out, ref)
+
+ @xfail_xp_backends(
+ "cupy", reason="Only 2D and 3D distance transforms are supported in CuPy"
+ )
+ @make_xp_test_case(ndimage.distance_transform_edt)
+ def test_distance_transform_edt5(self, xp):
+ # Ticket #954 regression test
+ out = ndimage.distance_transform_edt(xp.asarray(False))
+ assert_array_almost_equal(out, xp.asarray([0.]))
+
+ @xfail_xp_backends(
+ np_only=True, reason='XXX: does not raise unless indices is a numpy array'
+ )
+ @make_xp_test_case(ndimage.distance_transform_edt)
+ def test_distance_transform_edt6(self, xp):
+ # test input validation per discussion on PR #13302
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0]])
+ distances_out = xp.zeros(data.shape, dtype=xp.float64)
+ with assert_raises(RuntimeError):
+ ndimage.distance_transform_bf(
+ data,
+ return_indices=True,
+ return_distances=False,
+ distances=distances_out
+ )
+
+ @make_xp_test_case(ndimage.generate_binary_structure)
+ def test_generate_structure01(self, xp):
+ struct = ndimage.generate_binary_structure(0, 1)
+ assert struct == 1
+
+ @make_xp_test_case(ndimage.generate_binary_structure)
+ def test_generate_structure02(self, xp):
+ struct = ndimage.generate_binary_structure(1, 1)
+ assert_array_almost_equal(struct, [1, 1, 1])
+
+ @make_xp_test_case(ndimage.generate_binary_structure)
+ def test_generate_structure03(self, xp):
+ struct = ndimage.generate_binary_structure(2, 1)
+ assert_array_almost_equal(struct, [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]])
+
+ @make_xp_test_case(ndimage.generate_binary_structure)
+ def test_generate_structure04(self, xp):
+ struct = ndimage.generate_binary_structure(2, 2)
+ assert_array_almost_equal(struct, [[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]])
+
+ @make_xp_test_case(ndimage.iterate_structure)
+ def test_iterate_structure01(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ out = ndimage.iterate_structure(struct, 2)
+ expected = np.asarray([[0, 0, 1, 0, 0],
+ [0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.iterate_structure)
+ def test_iterate_structure02(self, xp):
+ struct = [[0, 1],
+ [1, 1],
+ [0, 1]]
+ struct = xp.asarray(struct)
+ out = ndimage.iterate_structure(struct, 2)
+ expected = np.asarray([[0, 0, 1],
+ [0, 1, 1],
+ [1, 1, 1],
+ [0, 1, 1],
+ [0, 0, 1]], dtype=bool)
+ expected = xp.asarray(expected)
+
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.iterate_structure)
+ def test_iterate_structure03(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ out = ndimage.iterate_structure(struct, 2, 1)
+ expected = [[0, 0, 1, 0, 0],
+ [0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0]]
+ expected = np.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ assert_array_almost_equal(out[0], expected)
+ assert out[1] == [2, 2]
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert out == xp.asarray(1, dtype=out.dtype)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert out == xp.asarray(1, dtype=out.dtype)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([0]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion04(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion05(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 0]))
+
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8912")
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion05_broadcasted(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones((1, ), dtype=dtype)
+ data = xp.broadcast_to(data, (3, ))
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 0]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion06(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion07(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([5], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion08(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([5], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion09(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([0, 0, 0, 0, 0]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion10(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 0, 0, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion11(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_erosion(data, struct, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion12(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion13(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_erosion(data, struct, border_value=1, origin=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion14(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 1])
+ out = ndimage.binary_erosion(data, struct, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion15(self, dtype, xp):
+ data = np.ones([5], dtype=dtype)
+ data[2] = 0
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 1])
+ out = ndimage.binary_erosion(data, struct, border_value=1, origin=-1)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 0, 1, 1]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion16(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 1], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([[1]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion17(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 1], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([[0]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion18(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 3], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion19(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 3], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([[1, 1, 1]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion20(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3, 3], dtype=dtype)
+ out = ndimage.binary_erosion(data)
+ assert_array_almost_equal(out, xp.asarray([[0, 0, 0],
+ [0, 1, 0],
+ [0, 0, 0]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion21(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3, 3], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]]))
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion22(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_erosion(data, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion23(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = ndimage.generate_binary_structure(2, 2)
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_erosion(data, struct, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion24(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = xp.asarray([[0, 1],
+ [1, 1]])
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 1, 1],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_erosion(data, struct, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion25(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = [[0, 1, 0],
+ [1, 0, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 0, 1, 1],
+ [0, 0, 1, 0, 1, 1, 0, 0],
+ [0, 1, 0, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_erosion(data, struct, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_erosion26(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = [[0, 1, 0],
+ [1, 0, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 1],
+ [0, 0, 0, 0, 1, 0, 0, 1],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 1]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 0, 1, 1],
+ [0, 0, 1, 0, 1, 1, 0, 0],
+ [0, 1, 0, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_erosion(data, struct, border_value=1,
+ origin=(-1, -1))
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends(
+ "cupy", reason="CuPy: NotImplementedError: only brute_force iteration"
+ )
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion27(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=2)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion28(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = np.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=2, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends(
+ "cupy", reason="CuPy: NotImplementedError: only brute_force iteration"
+ )
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion29(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, struct,
+ border_value=1, iterations=3)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion30(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = np.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=3, output=out)
+ assert_array_almost_equal(out, expected)
+
+ # test with output memory overlap
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=3, output=data)
+ assert_array_almost_equal(data, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion31(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0],
+ [1, 1, 1, 1, 1, 0, 1],
+ [0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 1]]
+ expected = np.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=1, output=out, origin=(-1, -1))
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion32(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, struct,
+ border_value=1, iterations=2)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion33(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 1, 1],
+ [0, 0, 0, 0, 0, 0, 1],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ mask = [[1, 1, 1, 1, 1, 0, 0],
+ [1, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1]]
+ mask = xp.asarray(mask)
+ data = np.asarray([[0, 0, 0, 0, 0, 1, 1],
+ [0, 0, 0, 1, 0, 0, 1],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, struct,
+ border_value=1, mask=mask, iterations=-1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion34(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ mask = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ mask = xp.asarray(mask)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_erosion(data, struct,
+ border_value=1, mask=mask)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion35(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ mask = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ mask = np.asarray(mask, dtype=bool)
+ mask = xp.asarray(mask)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ tmp = [[0, 0, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0],
+ [1, 1, 1, 1, 1, 0, 1],
+ [0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 1]]
+ tmp = np.asarray(tmp, dtype=bool)
+ tmp = xp.asarray(tmp)
+ expected = xp.logical_and(tmp, mask)
+ tmp = xp.logical_and(data, xp.logical_not(mask))
+ expected = xp.logical_or(expected, tmp)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=1, output=out,
+ origin=(-1, -1), mask=mask)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion36(self, xp):
+ struct = [[0, 1, 0],
+ [1, 0, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ mask = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ mask = np.asarray(mask, dtype=bool)
+ mask = xp.asarray(mask)
+ tmp = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 1],
+ [0, 0, 0, 0, 1, 0, 0, 1],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 1]]
+ tmp = np.asarray(tmp, dtype=bool)
+ tmp = xp.asarray(tmp)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 1, 1],
+ [0, 0, 1, 1, 1, 0, 1, 1],
+ [0, 0, 1, 0, 1, 1, 0, 0],
+ [0, 1, 0, 1, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ expected = xp.logical_and(tmp, mask)
+ tmp = xp.logical_and(data, xp.logical_not(mask))
+ expected = xp.logical_or(expected, tmp)
+ out = ndimage.binary_erosion(data, struct, mask=mask,
+ border_value=1, origin=(-1, -1))
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion37(self, xp):
+ a = np.asarray([[1, 0, 1],
+ [0, 1, 0],
+ [1, 0, 1]], dtype=bool)
+ a = xp.asarray(a)
+ b = xp.zeros_like(a)
+ out = ndimage.binary_erosion(a, structure=a, output=b, iterations=0,
+ border_value=True, brute_force=True)
+ assert out is b
+ xp_assert_equal(
+ ndimage.binary_erosion(a, structure=a, iterations=0,
+ border_value=True),
+ b)
+
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion38(self, xp):
+ data = np.asarray([[1, 0, 1],
+ [0, 1, 0],
+ [1, 0, 1]], dtype=bool)
+ data = xp.asarray(data)
+ iterations = 2.0
+ with assert_raises(TypeError):
+ _ = ndimage.binary_erosion(data, iterations=iterations)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion39(self, xp):
+ iterations = np.int32(3)
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=iterations, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace out= arguments are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_erosion)
+ def test_binary_erosion40(self, xp):
+ iterations = np.int64(3)
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0]]
+ expected = np.asarray(expected, dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_erosion(data, struct, border_value=1,
+ iterations=iterations, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert out == xp.asarray(1, dtype=out.dtype)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.zeros([], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert out == xp.asarray(False)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1], dtype=out.dtype))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation04(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.zeros([1], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation05(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation05_broadcasted(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones((1, ), dtype=dtype)
+ data = xp.broadcast_to(data, (3,))
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation06(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.zeros([3], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([0, 0, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation07(self, dtype, xp):
+ data = np.zeros([3], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation08(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data[3] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 1, 1]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation09(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 1, 0, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation10(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, origin=-1)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 1, 1, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation11(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, origin=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 0, 0, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation12(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_dilation(data, struct)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation13(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_dilation(data, struct, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 0, 1, 0, 1]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation14(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_dilation(data, struct, origin=-1)
+ assert_array_almost_equal(out, xp.asarray([0, 1, 0, 1, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation15(self, dtype, xp):
+ data = np.zeros([5], dtype=dtype)
+ data[1] = 1
+ data = xp.asarray(data)
+ struct = xp.asarray([1, 0, 1])
+ out = ndimage.binary_dilation(data, struct,
+ origin=-1, border_value=1)
+ assert_array_almost_equal(out, xp.asarray([1, 1, 0, 1, 0]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation16(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 1], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([[1]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation17(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.zeros([1, 1], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([[0]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation18(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([1, 3], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([[1, 1, 1]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation19(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.ones([3, 3], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation20(self, dtype, xp):
+ data = np.zeros([3, 3], dtype=dtype)
+ data[1, 1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, xp.asarray([[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation21(self, dtype, xp):
+ struct = ndimage.generate_binary_structure(2, 2)
+ struct = xp.asarray(struct)
+ data = np.zeros([3, 3], dtype=dtype)
+ data[1, 1] = 1
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, struct)
+ assert_array_almost_equal(out, xp.asarray([[1, 1, 1],
+ [1, 1, 1],
+ [1, 1, 1]]))
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation22(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation23(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 0, 0, 0, 0, 1],
+ [1, 1, 0, 0, 0, 1, 0, 1],
+ [1, 0, 0, 1, 1, 1, 1, 1],
+ [1, 0, 1, 1, 1, 1, 0, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 0, 1, 0, 0, 1, 0, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation24(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[1, 1, 0, 0, 0, 0, 0, 0],
+ [1, 0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 0, 0],
+ [0, 1, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, origin=(1, 1))
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation25(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[1, 1, 0, 0, 0, 0, 1, 1],
+ [1, 0, 0, 0, 1, 0, 1, 1],
+ [0, 0, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 0, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 0, 0, 1, 0, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, origin=(1, 1), border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation26(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = ndimage.generate_binary_structure(2, 2)
+ expected = [[1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, struct)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation27(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = [[0, 1],
+ [1, 1]]
+ expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+ [1, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, struct)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation28(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[1, 1, 1, 1],
+ [1, 0, 0, 1],
+ [1, 0, 0, 1],
+ [1, 1, 1, 1]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation29(self, xp):
+ struct = [[0, 1],
+ [1, 1]]
+ expected = [[0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, struct, iterations=2)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='output= arrays are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation30(self, xp):
+ struct = [[0, 1],
+ [1, 1]]
+ expected = [[0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_dilation(data, struct, iterations=2, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation31(self, xp):
+ struct = [[0, 1],
+ [1, 1]]
+ expected = [[0, 0, 0, 1, 0],
+ [0, 0, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, struct, iterations=3)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='output= arrays are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation32(self, xp):
+ struct = [[0, 1],
+ [1, 1]]
+ expected = [[0, 0, 0, 1, 0],
+ [0, 0, 1, 1, 0],
+ [0, 1, 1, 1, 0],
+ [1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = np.zeros(data.shape, dtype=bool)
+ out = xp.asarray(out)
+ ndimage.binary_dilation(data, struct, iterations=3, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation33(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 1, 1, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+ mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 1, 1, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ mask = xp.asarray(mask)
+ data = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+
+ out = ndimage.binary_dilation(data, struct, iterations=-1,
+ mask=mask, border_value=0)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason='inplace output= arrays are numpy-specific')
+ @xfail_xp_backends("cupy",
+ reason="NotImplementedError: only brute_force iteration")
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation34(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ mask = xp.asarray(mask)
+ data = np.zeros(mask.shape, dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, struct, iterations=-1,
+ mask=mask, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation35(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ tmp = [[1, 1, 0, 0, 0, 0, 1, 1],
+ [1, 0, 0, 0, 1, 0, 1, 1],
+ [0, 0, 1, 1, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1, 0, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1],
+ [0, 1, 0, 0, 1, 0, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1],
+ [1, 1, 1, 1, 1, 1, 1, 1]]
+
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]])
+ mask = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ mask = np.asarray(mask, dtype=bool)
+
+ expected = np.logical_and(tmp, mask)
+ tmp = np.logical_and(data, np.logical_not(mask))
+ expected = np.logical_or(expected, tmp)
+
+ mask = xp.asarray(mask)
+ expected = xp.asarray(expected)
+
+ data = xp.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_dilation(data, mask=mask,
+ origin=(1, 1), border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_dilation)
+ def test_binary_dilation36(self, xp):
+ # gh-21009
+ data = np.zeros([], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_dilation(data, iterations=-1)
+ assert out == xp.asarray(False)
+
+ @make_xp_test_case(ndimage.binary_propagation)
+ def test_binary_propagation01(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 1, 1, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+ mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 1, 0],
+ [0, 0, 0, 0, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0, 0, 0],
+ [0, 1, 1, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ mask = xp.asarray(mask)
+ data = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_propagation(data, struct,
+ mask=mask, border_value=0)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_propagation)
+ def test_binary_propagation02(self, xp):
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ struct = xp.asarray(struct)
+ mask = np.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ mask = xp.asarray(mask)
+ data = np.zeros(mask.shape, dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_propagation(data, struct,
+ mask=mask, border_value=1)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_propagation)
+ def test_binary_propagation03(self, xp):
+ # gh-21009
+ data = xp.asarray(np.zeros([], dtype=bool))
+ expected = xp.asarray(np.zeros([], dtype=bool))
+ out = ndimage.binary_propagation(data)
+ assert out == expected
+
+ @make_xp_test_case(ndimage.binary_opening)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_opening01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[0, 1, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 0, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_opening(data)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_opening)
+ @pytest.mark.parametrize('dtype', types)
+ def test_binary_opening02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = ndimage.generate_binary_structure(2, 2)
+ expected = [[1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ struct = xp.asarray(struct)
+ data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_opening(data, struct)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_closing)
+ def test_binary_closing01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 1, 0, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 0, 1, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_closing(data)
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('dtype', types)
+ @make_xp_test_case(ndimage.binary_closing)
+ def test_binary_closing02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = ndimage.generate_binary_structure(2, 2)
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ struct = xp.asarray(struct)
+ data = xp.asarray([[1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [1, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_closing(data, struct)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_fill_holes)
+ def test_binary_fill_holes01(self, xp):
+ expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+
+ out = ndimage.binary_fill_holes(data)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_fill_holes)
+ def test_binary_fill_holes02(self, xp):
+ expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 1, 0, 0, 1, 0, 0],
+ [0, 0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_fill_holes(data)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_fill_holes)
+ def test_binary_fill_holes03(self, xp):
+ expected = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 0, 1, 1, 1],
+ [0, 1, 1, 1, 0, 1, 1, 1],
+ [0, 1, 1, 1, 0, 1, 1, 1],
+ [0, 0, 1, 0, 0, 1, 1, 1],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+ data = np.asarray([[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 1, 0, 1, 1, 1],
+ [0, 1, 0, 1, 0, 1, 0, 1],
+ [0, 1, 0, 1, 0, 1, 0, 1],
+ [0, 0, 1, 0, 0, 1, 1, 1],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=bool)
+ data = xp.asarray(data)
+ out = ndimage.binary_fill_holes(data)
+ assert_array_almost_equal(out, expected)
+
+ @skip_xp_backends(cpu_only=True)
+ @skip_xp_backends(
+ "cupy", reason="these filters do not yet have axes support in CuPy")
+ @skip_xp_backends(
+ "jax.numpy", reason="these filters are not implemented in JAX.numpy")
+ @pytest.mark.parametrize('border_value',[0, 1])
+ @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)])
+ @pytest.mark.parametrize('expand_axis', [0, 1, 2])
+ @pytest.mark.parametrize(
+ 'func', [
+ make_xp_pytest_param(ndimage.binary_erosion),
+ make_xp_pytest_param(ndimage.binary_dilation),
+ make_xp_pytest_param(ndimage.binary_opening),
+ make_xp_pytest_param(ndimage.binary_closing),
+ make_xp_pytest_param(ndimage.binary_hit_or_miss),
+ make_xp_pytest_param(ndimage.binary_propagation),
+ make_xp_pytest_param(ndimage.binary_fill_holes),
+ ]
+ )
+ def test_binary_axes(self, xp, func, expand_axis, origin, border_value):
+ func_name = func.__name__
+ struct = np.asarray([[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]], bool)
+ struct = xp.asarray(struct)
+
+ data = np.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 0, 1, 0],
+ [0, 1, 0, 1, 1, 0, 1],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0]], bool)
+ data = xp.asarray(data)
+ if func_name == "binary_hit_or_miss":
+ kwargs = dict(origin1=origin, origin2=origin)
+ else:
+ kwargs = dict(origin=origin)
+ border_supported = func_name not in ["binary_hit_or_miss",
+ "binary_fill_holes"]
+ if border_supported:
+ kwargs['border_value'] = border_value
+ elif border_value != 0:
+ pytest.skip('border_value !=0 unsupported by this function')
+
+ expected = func(data, struct, **kwargs)
+
+ # replicate data and expected result along a new axis
+ n_reps = 5
+ expected = xp.stack([expected] * n_reps, axis=expand_axis)
+ data = xp.stack([data] * n_reps, axis=expand_axis)
+
+ # filter all axes except expand_axis
+ axes = [0, 1, 2]
+ axes.remove(expand_axis)
+ if is_numpy(xp) or is_cupy(xp):
+ out = xp.asarray(np.zeros(data.shape, bool))
+ func(data, struct, output=out, axes=axes, **kwargs)
+ else:
+ # inplace output= is unsupported by JAX
+ out = func(data, struct, axes=axes, **kwargs)
+ xp_assert_close(out, expected)
+
+ @make_xp_test_case(ndimage.grey_erosion)
+ def test_grey_erosion01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ output = ndimage.grey_erosion(array, footprint=footprint)
+ assert_array_almost_equal(output,
+ xp.asarray([[2, 2, 1, 1, 1],
+ [2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1]]))
+
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/8398")
+ @make_xp_test_case(ndimage.grey_erosion)
+ def test_grey_erosion01_overlap(self, xp):
+
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ ndimage.grey_erosion(array, footprint=footprint, output=array)
+ assert_array_almost_equal(array,
+ xp.asarray([[2, 2, 1, 1, 1],
+ [2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1]])
+ )
+
+ @make_xp_test_case(ndimage.grey_erosion)
+ def test_grey_erosion02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ output = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output,
+ xp.asarray([[2, 2, 1, 1, 1],
+ [2, 3, 1, 3, 1],
+ [5, 5, 3, 3, 1]])
+ )
+
+ @make_xp_test_case(ndimage.grey_erosion)
+ def test_grey_erosion03(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[1, 1, 1], [1, 1, 1]])
+ output = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output,
+ xp.asarray([[1, 1, 0, 0, 0],
+ [1, 2, 0, 2, 0],
+ [4, 4, 2, 2, 0]])
+ )
+
+ @make_xp_test_case(ndimage.grey_dilation)
+ def test_grey_dilation01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+ output = ndimage.grey_dilation(array, footprint=footprint)
+ assert_array_almost_equal(output,
+ xp.asarray([[7, 7, 9, 9, 5],
+ [7, 9, 8, 9, 7],
+ [8, 8, 8, 7, 7]]),
+ )
+
+ @make_xp_test_case(ndimage.grey_dilation)
+ def test_grey_dilation02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ output = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output,
+ xp.asarray([[7, 7, 9, 9, 5],
+ [7, 9, 8, 9, 7],
+ [8, 8, 8, 7, 7]]),
+ )
+
+ @make_xp_test_case(ndimage.grey_dilation)
+ def test_grey_dilation03(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[0, 1, 1], [1, 0, 1]])
+ structure = xp.asarray([[1, 1, 1], [1, 1, 1]])
+ output = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output,
+ xp.asarray([[8, 8, 10, 10, 6],
+ [8, 10, 9, 10, 8],
+ [9, 9, 9, 8, 8]]),
+ )
+
+ @make_xp_test_case(ndimage.grey_opening)
+ def test_grey_opening01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ tmp = ndimage.grey_erosion(array, footprint=footprint)
+ expected = ndimage.grey_dilation(tmp, footprint=footprint)
+ output = ndimage.grey_opening(array, footprint=footprint)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_opening)
+ def test_grey_opening02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ expected = ndimage.grey_dilation(tmp, footprint=footprint,
+ structure=structure)
+ output = ndimage.grey_opening(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_closing)
+ def test_grey_closing01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ tmp = ndimage.grey_dilation(array, footprint=footprint)
+ expected = ndimage.grey_erosion(tmp, footprint=footprint)
+ output = ndimage.grey_closing(array, footprint=footprint)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_closing)
+ def test_grey_closing02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ expected = ndimage.grey_erosion(tmp, footprint=footprint,
+ structure=structure)
+ output = ndimage.grey_closing(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+ @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion,
+ ndimage.morphological_gradient)
+ def test_morphological_gradient01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ expected = tmp1 - tmp2
+ output = xp.zeros(array.shape, dtype=array.dtype)
+ ndimage.morphological_gradient(array, footprint=footprint,
+ structure=structure, output=output)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion,
+ ndimage.morphological_gradient)
+ def test_morphological_gradient02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ expected = tmp1 - tmp2
+ output = ndimage.morphological_gradient(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @skip_xp_backends(np_only=True, reason='output= arrays are numpy-specific')
+ @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion,
+ ndimage.morphological_laplace)
+ def test_morphological_laplace01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ expected = tmp1 + tmp2 - 2 * array
+ output = xp.zeros(array.shape, dtype=array.dtype)
+ ndimage.morphological_laplace(array, footprint=footprint,
+ structure=structure, output=output)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_dilation, ndimage.grey_erosion,
+ ndimage.morphological_laplace)
+ def test_morphological_laplace02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp1 = ndimage.grey_dilation(array, footprint=footprint,
+ structure=structure)
+ tmp2 = ndimage.grey_erosion(array, footprint=footprint,
+ structure=structure)
+ expected = tmp1 + tmp2 - 2 * array
+ output = ndimage.morphological_laplace(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @make_xp_test_case(ndimage.grey_opening, ndimage.white_tophat)
+ def test_white_tophat01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_opening(array, footprint=footprint,
+ structure=structure)
+ expected = array - tmp
+ output = xp.zeros(array.shape, dtype=array.dtype)
+ ndimage.white_tophat(array, footprint=footprint,
+ structure=structure, output=output)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_opening, ndimage.white_tophat)
+ def test_white_tophat02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_opening(array, footprint=footprint,
+ structure=structure)
+ expected = array - tmp
+ output = ndimage.white_tophat(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @xfail_xp_backends('cupy', reason="cupy#8399")
+ @make_xp_test_case(ndimage.white_tophat)
+ def test_white_tophat03(self, xp):
+
+ array = np.asarray([[1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 1]], dtype=bool)
+ array = xp.asarray(array)
+ structure = np.ones((3, 3), dtype=bool)
+ structure = xp.asarray(structure)
+ expected = np.asarray([[0, 1, 1, 0, 0, 0, 0],
+ [1, 0, 0, 1, 1, 1, 0],
+ [1, 0, 0, 1, 1, 1, 0],
+ [0, 1, 1, 0, 0, 0, 1],
+ [0, 1, 1, 0, 1, 0, 1],
+ [0, 1, 1, 0, 0, 0, 1],
+ [0, 0, 0, 1, 1, 1, 1]], dtype=bool)
+ expected = xp.asarray(expected)
+
+ output = ndimage.white_tophat(array, structure=structure)
+ xp_assert_equal(output, expected)
+
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @make_xp_test_case(ndimage.white_tophat)
+ def test_white_tophat04(self, xp):
+ array = np.eye(5, dtype=bool)
+ structure = np.ones((3, 3), dtype=bool)
+
+ array = xp.asarray(array)
+ structure = xp.asarray(structure)
+
+ # Check that type mismatch is properly handled
+ output = xp.empty_like(array, dtype=xp.float64)
+ ndimage.white_tophat(array, structure=structure, output=output)
+
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @make_xp_test_case(ndimage.grey_closing, ndimage.black_tophat)
+ def test_black_tophat01(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_closing(array, footprint=footprint,
+ structure=structure)
+ expected = tmp - array
+ output = xp.zeros(array.shape, dtype=array.dtype)
+ ndimage.black_tophat(array, footprint=footprint,
+ structure=structure, output=output)
+ assert_array_almost_equal(output, expected)
+
+ @make_xp_test_case(ndimage.grey_closing, ndimage.black_tophat)
+ def test_black_tophat02(self, xp):
+ array = xp.asarray([[3, 2, 5, 1, 4],
+ [7, 6, 9, 3, 5],
+ [5, 8, 3, 7, 1]])
+ footprint = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ structure = xp.asarray([[0, 0, 0], [0, 0, 0]])
+ tmp = ndimage.grey_closing(array, footprint=footprint,
+ structure=structure)
+ expected = tmp - array
+ output = ndimage.black_tophat(array, footprint=footprint,
+ structure=structure)
+ assert_array_almost_equal(output, expected)
+
+ @xfail_xp_backends('cupy', reason="cupy/cupy#8399")
+ @make_xp_test_case(ndimage.black_tophat)
+ def test_black_tophat03(self, xp):
+
+ array = np.asarray([[1, 0, 0, 0, 0, 0, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0, 1, 0],
+ [0, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 1]], dtype=bool)
+ array = xp.asarray(array)
+ structure = np.ones((3, 3), dtype=bool)
+ structure = xp.asarray(structure)
+ expected = np.asarray([[0, 1, 1, 1, 1, 1, 1],
+ [1, 0, 0, 0, 0, 0, 1],
+ [1, 0, 0, 0, 0, 0, 1],
+ [1, 0, 0, 0, 0, 0, 1],
+ [1, 0, 0, 0, 1, 0, 1],
+ [1, 0, 0, 0, 0, 0, 1],
+ [1, 1, 1, 1, 1, 1, 0]], dtype=bool)
+ expected = xp.asarray(expected)
+
+ output = ndimage.black_tophat(array, structure=structure)
+ xp_assert_equal(output, expected)
+
+ @skip_xp_backends("jax.numpy", reason="output=array requires buffer view")
+ @skip_xp_backends("dask.array", reason="output=array requires buffer view")
+ @make_xp_test_case(ndimage.black_tophat)
+ def test_black_tophat04(self, xp):
+ array = xp.asarray(np.eye(5, dtype=bool))
+ structure = xp.asarray(np.ones((3, 3), dtype=bool))
+
+ # Check that type mismatch is properly handled
+ output = xp.empty_like(array, dtype=xp.float64)
+ ndimage.black_tophat(array, structure=structure, output=output)
+
+ @skip_xp_backends(cpu_only=True)
+ @skip_xp_backends(
+ "cupy", reason="these filters do not yet have axes support in CuPy")
+ @skip_xp_backends(
+ "jax.numpy", reason="these filters are not implemented in JAX.numpy")
+ @pytest.mark.parametrize('origin', [(0, 0), (-1, 0)])
+ @pytest.mark.parametrize('expand_axis', [0, 1, 2])
+ @pytest.mark.parametrize('mode', ['reflect', 'constant', 'nearest',
+ 'mirror', 'wrap'])
+ @pytest.mark.parametrize('footprint_mode', ['size', 'footprint',
+ 'structure'])
+ @pytest.mark.parametrize(
+ 'func',
+ [
+ make_xp_pytest_param(ndimage.grey_erosion),
+ make_xp_pytest_param(ndimage.grey_dilation),
+ make_xp_pytest_param(ndimage.grey_opening),
+ make_xp_pytest_param(ndimage.grey_closing),
+ make_xp_pytest_param(ndimage.morphological_laplace),
+ make_xp_pytest_param(ndimage.morphological_gradient),
+ make_xp_pytest_param(ndimage.white_tophat),
+ make_xp_pytest_param(ndimage.black_tophat),
+ ]
+ )
+ def test_grey_axes(self, xp, func, expand_axis, origin, footprint_mode,
+ mode):
+ data = xp.asarray([[0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 4, 0, 0, 0],
+ [0, 0, 2, 1, 0, 2, 0],
+ [0, 3, 0, 6, 5, 0, 1],
+ [0, 4, 5, 3, 3, 4, 0],
+ [0, 0, 9, 3, 0, 0, 0],
+ [0, 0, 0, 2, 0, 0, 0]])
+ kwargs = dict(origin=origin, mode=mode)
+ if footprint_mode == 'size':
+ kwargs['size'] = (2, 3)
+ else:
+ kwargs['footprint'] = xp.asarray([[1, 0, 1], [1, 1, 0]])
+ if footprint_mode == 'structure':
+ kwargs['structure'] = xp.ones_like(kwargs['footprint'])
+
+ expected = func(data, **kwargs)
+
+ # replicate data and expected result along a new axis
+ n_reps = 5
+ expected = xp.stack([expected] * n_reps, axis=expand_axis)
+ data = xp.stack([data] * n_reps, axis=expand_axis)
+
+ # filter all axes except expand_axis
+ axes = [0, 1, 2]
+ axes.remove(expand_axis)
+
+ if is_numpy(xp) or is_cupy(xp):
+ out = xp.zeros(expected.shape, dtype=expected.dtype)
+ func(data, output=out, axes=axes, **kwargs)
+ else:
+ # inplace output= is unsupported by JAX
+ out = func(data, axes=axes, **kwargs)
+ xp_assert_close(out, expected)
+
+ @skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason="inplace output= is numpy-specific")
+ @make_xp_test_case(ndimage.binary_hit_or_miss)
+ @pytest.mark.parametrize('dtype', types)
+ def test_hit_or_miss01(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ struct = xp.asarray(struct)
+ expected = [[0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0]]
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 1, 0, 0, 0],
+ [1, 1, 1, 0, 0],
+ [0, 1, 0, 1, 1],
+ [0, 0, 1, 1, 1],
+ [0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1],
+ [0, 1, 1, 1, 1],
+ [0, 0, 0, 0, 0]], dtype=dtype)
+ out = xp.asarray(np.zeros(data.shape, dtype=bool))
+ ndimage.binary_hit_or_miss(data, struct, output=out)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_hit_or_miss)
+ @pytest.mark.parametrize('dtype', types)
+ def test_hit_or_miss02(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct = [[0, 1, 0],
+ [1, 1, 1],
+ [0, 1, 0]]
+ expected = [[0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ struct = xp.asarray(struct)
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0],
+ [1, 1, 1, 0, 0, 1, 0, 0],
+ [0, 1, 0, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_hit_or_miss(data, struct)
+ assert_array_almost_equal(out, expected)
+
+ @make_xp_test_case(ndimage.binary_hit_or_miss)
+ @pytest.mark.parametrize('dtype', types)
+ def test_hit_or_miss03(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ struct1 = [[0, 0, 0],
+ [1, 1, 1],
+ [0, 0, 0]]
+ struct2 = [[1, 1, 1],
+ [0, 0, 0],
+ [1, 1, 1]]
+ expected = [[0, 0, 0, 0, 0, 1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]]
+ struct1 = xp.asarray(struct1)
+ struct2 = xp.asarray(struct2)
+ expected = xp.asarray(expected)
+ data = xp.asarray([[0, 1, 0, 0, 1, 1, 1, 0],
+ [1, 1, 1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 1, 1, 1, 1, 0],
+ [0, 0, 1, 1, 1, 1, 1, 0],
+ [0, 1, 1, 1, 0, 1, 1, 0],
+ [0, 0, 0, 0, 1, 1, 1, 0],
+ [0, 1, 1, 1, 1, 1, 1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0]], dtype=dtype)
+ out = ndimage.binary_hit_or_miss(data, struct1, struct2)
+ assert_array_almost_equal(out, expected)
+
+
+@make_xp_test_case(ndimage.binary_dilation, ndimage.grey_dilation)
+class TestDilateFix:
+
+ # pytest's setup_method seems to clash with the autouse `xp` fixture
+ # so call _setup manually from all methods
+ def _setup(self, xp):
+ # dilation related setup
+ self.array = xp.asarray([[0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0],
+ [0, 0, 1, 1, 0],
+ [0, 0, 0, 0, 0]], dtype=xp.uint8)
+
+ self.sq3x3 = xp.ones((3, 3))
+ dilated3x3 = ndimage.binary_dilation(self.array, structure=self.sq3x3)
+
+ if is_numpy(xp):
+ self.dilated3x3 = dilated3x3.view(xp.uint8)
+ else:
+ self.dilated3x3 = xp.astype(dilated3x3, xp.uint8)
+
+
+ def test_dilation_square_structure(self, xp):
+ self._setup(xp)
+ result = ndimage.grey_dilation(self.array, structure=self.sq3x3)
+ # +1 accounts for difference between grey and binary dilation
+ assert_array_almost_equal(result, self.dilated3x3 + 1)
+
+ def test_dilation_scalar_size(self, xp):
+ self._setup(xp)
+ result = ndimage.grey_dilation(self.array, size=3)
+ assert_array_almost_equal(result, self.dilated3x3)
+
+
+@make_xp_test_case(ndimage.binary_opening, ndimage.binary_closing)
+class TestBinaryOpeningClosing:
+
+ def _setup(self, xp):
+ a = np.zeros((5, 5), dtype=bool)
+ a[1:4, 1:4] = True
+ a[4, 4] = True
+ self.array = xp.asarray(a)
+ self.sq3x3 = xp.ones((3, 3))
+ self.opened_old = ndimage.binary_opening(self.array, self.sq3x3,
+ 1, None, 0)
+ self.closed_old = ndimage.binary_closing(self.array, self.sq3x3,
+ 1, None, 0)
+
+ def test_opening_new_arguments(self, xp):
+ self._setup(xp)
+ opened_new = ndimage.binary_opening(self.array, self.sq3x3, 1, None,
+ 0, None, 0, False)
+ xp_assert_equal(opened_new, self.opened_old)
+
+ def test_closing_new_arguments(self, xp):
+ self._setup(xp)
+ closed_new = ndimage.binary_closing(self.array, self.sq3x3, 1, None,
+ 0, None, 0, False)
+ xp_assert_equal(closed_new, self.closed_old)
+
+
+@make_xp_test_case(ndimage.binary_erosion)
+def test_binary_erosion_noninteger_iterations(xp):
+ # regression test for gh-9905, gh-9909: ValueError for
+ # non integer iterations
+ data = xp.ones([1])
+ assert_raises(TypeError, ndimage.binary_erosion, data, iterations=0.5)
+ assert_raises(TypeError, ndimage.binary_erosion, data, iterations=1.5)
+
+
+@make_xp_test_case(ndimage.binary_dilation)
+def test_binary_dilation_noninteger_iterations(xp):
+ # regression test for gh-9905, gh-9909: ValueError for
+ # non integer iterations
+ data = xp.ones([1])
+ assert_raises(TypeError, ndimage.binary_dilation, data, iterations=0.5)
+ assert_raises(TypeError, ndimage.binary_dilation, data, iterations=1.5)
+
+
+@make_xp_test_case(ndimage.binary_opening)
+def test_binary_opening_noninteger_iterations(xp):
+ # regression test for gh-9905, gh-9909: ValueError for
+ # non integer iterations
+ data = xp.ones([1])
+ assert_raises(TypeError, ndimage.binary_opening, data, iterations=0.5)
+ assert_raises(TypeError, ndimage.binary_opening, data, iterations=1.5)
+
+
+@make_xp_test_case(ndimage.binary_closing)
+def test_binary_closing_noninteger_iterations(xp):
+ # regression test for gh-9905, gh-9909: ValueError for
+ # non integer iterations
+ data = xp.ones([1])
+ assert_raises(TypeError, ndimage.binary_closing, data, iterations=0.5)
+ assert_raises(TypeError, ndimage.binary_closing, data, iterations=1.5)
+
+
+@xfail_xp_backends(
+ "cupy", reason="CuPy: NotImplementedError: only brute_force iteration"
+)
+@make_xp_test_case(ndimage.binary_erosion)
+def test_binary_closing_noninteger_brute_force_passes_when_true(xp):
+ # regression test for gh-9905, gh-9909: ValueError for non integer iterations
+ data = xp.ones([1])
+ xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=1.5),
+ ndimage.binary_erosion(data, iterations=2, brute_force=bool(1.5))
+ )
+ xp_assert_equal(ndimage.binary_erosion(data, iterations=2, brute_force=0.0),
+ ndimage.binary_erosion(data, iterations=2, brute_force=bool(0.0))
+ )
+
+
+@skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason="inplace output= is numpy-specific")
+@xfail_xp_backends("cupy", reason="NotImplementedError: only brute_force iteration")
+@pytest.mark.parametrize(
+ 'func',
+ [
+ make_xp_pytest_param(ndimage.binary_erosion),
+ make_xp_pytest_param(ndimage.binary_dilation),
+ make_xp_pytest_param(ndimage.binary_opening),
+ make_xp_pytest_param(ndimage.binary_closing),
+ ],
+)
+@pytest.mark.parametrize('iterations', [1, 5])
+@pytest.mark.parametrize('brute_force', [False, True])
+def test_binary_input_as_output(func, iterations, brute_force, xp):
+ rstate = np.random.RandomState(123)
+ data = rstate.randint(low=0, high=2, size=100).astype(bool)
+ data = xp.asarray(data)
+
+ # input data is not modified
+ data_orig = data.copy()
+ expected = func(data, brute_force=brute_force, iterations=iterations)
+ xp_assert_equal(data, data_orig)
+
+ # data should now contain the expected result
+ func(data, brute_force=brute_force, iterations=iterations, output=data)
+ xp_assert_equal(data, expected)
+
+
+@skip_xp_backends(np_only=True, exceptions=["cupy"],
+ reason="inplace output= is numpy-specific")
+@make_xp_test_case(ndimage.binary_hit_or_miss)
+def test_binary_hit_or_miss_input_as_output(xp):
+ rstate = np.random.RandomState(123)
+ data = rstate.randint(low=0, high=2, size=100).astype(bool)
+ data = xp.asarray(data)
+
+ # input data is not modified
+ data_orig = data.copy()
+ expected = ndimage.binary_hit_or_miss(data)
+ xp_assert_equal(data, data_orig)
+
+ # data should now contain the expected result
+ ndimage.binary_hit_or_miss(data, output=data)
+ xp_assert_equal(data, expected)
+
+
+@make_xp_test_case(ndimage.distance_transform_cdt)
+def test_distance_transform_cdt_invalid_metric(xp):
+ msg = 'invalid metric provided'
+ with pytest.raises(ValueError, match=msg):
+ ndimage.distance_transform_cdt(xp.ones((5, 5)),
+ metric="garbage")
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_ni_support.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_ni_support.py
new file mode 100644
index 0000000000000000000000000000000000000000..e857e879c5e507c203cc83cd3807835e477f2757
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_ni_support.py
@@ -0,0 +1,77 @@
+import pytest
+
+import numpy as np
+from .._ni_support import _get_output
+
+
+@pytest.mark.parametrize(
+ 'dtype',
+ [
+ # String specifiers
+ 'f4', 'float32', 'complex64', 'complex128',
+ # Type and dtype specifiers
+ np.float32, float, np.dtype('f4'),
+ # Derive from input
+ None,
+ ],
+)
+def test_get_output_basic(dtype):
+ shape = (2, 3)
+
+ input_ = np.zeros(shape, dtype='float32')
+
+ # For None, derive dtype from input
+ expected_dtype = 'float32' if dtype is None else dtype
+
+ # Output is dtype-specifier, retrieve shape from input
+ result = _get_output(dtype, input_)
+ assert result.shape == shape
+ assert result.dtype == np.dtype(expected_dtype)
+
+ # Output is dtype specifier, with explicit shape, overriding input
+ result = _get_output(dtype, input_, shape=(3, 2))
+ assert result.shape == (3, 2)
+ assert result.dtype == np.dtype(expected_dtype)
+
+ # Output is pre-allocated array, return directly
+ output = np.zeros(shape, dtype=dtype)
+ result = _get_output(output, input_)
+ assert result is output
+
+
+def test_get_output_complex():
+ shape = (2, 3)
+
+ input_ = np.zeros(shape)
+
+ # None, promote input type to complex
+ result = _get_output(None, input_, complex_output=True)
+ assert result.shape == shape
+ assert result.dtype == np.dtype('complex128')
+
+ # Explicit type, promote type to complex
+ with pytest.warns(UserWarning, match='promoting specified output dtype to complex'):
+ result = _get_output(float, input_, complex_output=True)
+ assert result.shape == shape
+ assert result.dtype == np.dtype('complex128')
+
+ # String specifier, simply verify complex output
+ result = _get_output('complex64', input_, complex_output=True)
+ assert result.shape == shape
+ assert result.dtype == np.dtype('complex64')
+
+
+def test_get_output_error_cases():
+ input_ = np.zeros((2, 3), 'float32')
+
+ # Two separate paths can raise the same error
+ with pytest.raises(RuntimeError, match='output must have complex dtype'):
+ _get_output('float32', input_, complex_output=True)
+ with pytest.raises(RuntimeError, match='output must have complex dtype'):
+ _get_output(np.zeros((2, 3)), input_, complex_output=True)
+
+ with pytest.raises(RuntimeError, match='output must have numeric dtype'):
+ _get_output('void', input_)
+
+ with pytest.raises(RuntimeError, match='shape not correct'):
+ _get_output(np.zeros((3, 2)), input_)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_splines.py b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_splines.py
new file mode 100644
index 0000000000000000000000000000000000000000..35368072cf57268aaf0a27bb63196f20acb73619
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/ndimage/tests/test_splines.py
@@ -0,0 +1,68 @@
+"""Tests for spline filtering."""
+import pytest
+
+import numpy as np
+from scipy._lib._array_api import assert_almost_equal, make_xp_test_case
+
+from scipy import ndimage
+
+
+def get_spline_knot_values(order):
+ """Knot values to the right of a B-spline's center."""
+ knot_values = {0: [1],
+ 1: [1],
+ 2: [6, 1],
+ 3: [4, 1],
+ 4: [230, 76, 1],
+ 5: [66, 26, 1]}
+
+ return knot_values[order]
+
+
+def make_spline_knot_matrix(xp, n, order, mode='mirror'):
+ """Matrix to invert to find the spline coefficients."""
+ knot_values = get_spline_knot_values(order)
+
+ # NB: do computations with numpy, convert to xp as the last step only
+
+ matrix = np.zeros((n, n))
+ for diag, knot_value in enumerate(knot_values):
+ indices = np.arange(diag, n)
+ if diag == 0:
+ matrix[indices, indices] = knot_value
+ else:
+ matrix[indices, indices - diag] = knot_value
+ matrix[indices - diag, indices] = knot_value
+
+ knot_values_sum = knot_values[0] + 2 * sum(knot_values[1:])
+
+ if mode == 'mirror':
+ start, step = 1, 1
+ elif mode == 'reflect':
+ start, step = 0, 1
+ elif mode == 'grid-wrap':
+ start, step = -1, -1
+ else:
+ raise ValueError(f'unsupported mode {mode}')
+
+ for row in range(len(knot_values) - 1):
+ for idx, knot_value in enumerate(knot_values[row + 1:]):
+ matrix[row, start + step*idx] += knot_value
+ matrix[-row - 1, -start - 1 - step*idx] += knot_value
+
+ return xp.asarray(matrix / knot_values_sum)
+
+
+@make_xp_test_case(ndimage.spline_filter1d)
+@pytest.mark.parametrize('order', [0, 1, 2, 3, 4, 5])
+@pytest.mark.parametrize('mode', ['mirror', 'grid-wrap', 'reflect'])
+def test_spline_filter_vs_matrix_solution(order, mode, xp):
+ n = 100
+ eye = xp.eye(n, dtype=xp.float64)
+ spline_filter_axis_0 = ndimage.spline_filter1d(eye, axis=0, order=order,
+ mode=mode)
+ spline_filter_axis_1 = ndimage.spline_filter1d(eye, axis=1, order=order,
+ mode=mode)
+ matrix = make_spline_knot_matrix(xp, n, order, mode=mode)
+ assert_almost_equal(eye, spline_filter_axis_0 @ matrix)
+ assert_almost_equal(eye, spline_filter_axis_1 @ matrix.T)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.___odrpack.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.___odrpack.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.___odrpack.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.__add_newdocs.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.__add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.__add_newdocs.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.__models.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.__models.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.__models.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.__odrpack.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.__odrpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/.__odrpack.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/._models.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/._models.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/._models.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/._odrpack.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/._odrpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/._odrpack.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/._tests b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/._tests
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/._tests differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..1e3c3addc07bc8797f7fcbdf42ca72dc6f4d424f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/__init__.py
@@ -0,0 +1,177 @@
+"""
+=================================================
+Orthogonal distance regression (:mod:`scipy.odr`)
+=================================================
+
+.. currentmodule:: scipy.odr
+
+.. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ The following example shows a brief comparison of the APIs::
+
+ import numpy as np
+ import scipy.odr
+ import odrpack
+
+ # Classic "Pearson data" that motivates ODR.
+ # Errors are in both variables, and if you don't account for this,
+ # doing a linear fit of X vs. Y or Y vs. X will give you quite
+ # different results.
+ p_x = np.array([0., .9, 1.8, 2.6, 3.3, 4.4, 5.2, 6.1, 6.5, 7.4])
+ p_y = np.array([5.9, 5.4, 4.4, 4.6, 3.5, 3.7, 2.8, 2.8, 2.4, 1.5])
+ p_sx = np.array([.03, .03, .04, .035, .07, .11, .13, .22, .74, 1.])
+ p_sy = np.array([1., .74, .5, .35, .22, .22, .12, .12, .1, .04])
+
+ # Old-style
+ # The RealData class takes care of details like turning
+ # standard-deviation error bars into weights.
+ p_dat = scipy.odr.RealData(p_x, p_y, sx=p_sx, sy=p_sy)
+ # Note, parameters come before `x` in scipy.odr
+ p_mod = scipy.odr.Model(lambda beta, x: beta[0] + beta[1]*x)
+ p_odr = scipy.odr.ODR(p_dat, p_mod, beta0=[1., 1.])
+ old_out = p_odr.run()
+
+ # New-style
+ # Parameters come after data, in the new API.
+ # We must convert the error bars into weights ourselves.
+ new_out = odrpack.odr_fit(lambda x, beta: beta[0] + beta[1] * x,
+ p_x, p_y, beta0=np.array([1.0, 1.0]),
+ weight_x=p_sx**-2, weight_y=p_sy**-2)
+
+ assert np.isclose(old_out.beta, new_out.beta).all()
+
+
+Package Content
+===============
+
+.. autosummary::
+ :toctree: generated/
+
+ Data -- The data to fit.
+ RealData -- Data with weights as actual std. dev.s and/or covariances.
+ Model -- Stores information about the function to be fit.
+ ODR -- Gathers all info & manages the main fitting routine.
+ Output -- Result from the fit.
+ odr -- Low-level function for ODR.
+
+ OdrWarning -- Warning about potential problems when running ODR.
+ OdrError -- Error exception.
+ OdrStop -- Stop exception.
+
+ polynomial -- Factory function for a general polynomial model.
+ exponential -- Exponential model
+ multilinear -- Arbitrary-dimensional linear model
+ unilinear -- Univariate linear model
+ quadratic -- Quadratic model
+
+Usage information
+=================
+
+Introduction
+------------
+
+Why Orthogonal Distance Regression (ODR)? Sometimes one has
+measurement errors in the explanatory (a.k.a., "independent")
+variable(s), not just the response (a.k.a., "dependent") variable(s).
+Ordinary Least Squares (OLS) fitting procedures treat the data for
+explanatory variables as fixed, i.e., not subject to error of any kind.
+Furthermore, OLS procedures require that the response variables be an
+explicit function of the explanatory variables; sometimes making the
+equation explicit is impractical and/or introduces errors. ODR can
+handle both of these cases with ease, and can even reduce to the OLS
+case if that is sufficient for the problem.
+
+ODRPACK is a FORTRAN-77 library for performing ODR with possibly
+non-linear fitting functions. It uses a modified trust-region
+Levenberg-Marquardt-type algorithm [1]_ to estimate the function
+parameters. The fitting functions are provided by Python functions
+operating on NumPy arrays. The required derivatives may be provided
+by Python functions as well, or may be estimated numerically. ODRPACK
+can do explicit or implicit ODR fits, or it can do OLS. Input and
+output variables may be multidimensional. Weights can be provided to
+account for different variances of the observations, and even
+covariances between dimensions of the variables.
+
+The `scipy.odr` package offers an object-oriented interface to
+ODRPACK, in addition to the low-level `odr` function.
+
+Additional background information about ODRPACK can be found in the
+`ODRPACK User's Guide
+`_, reading
+which is recommended.
+
+Basic usage
+-----------
+
+1. Define the function you want to fit against.::
+
+ def f(B, x):
+ '''Linear function y = m*x + b'''
+ # B is a vector of the parameters.
+ # x is an array of the current x values.
+ # x is in the same format as the x passed to Data or RealData.
+ #
+ # Return an array in the same format as y passed to Data or RealData.
+ return B[0]*x + B[1]
+
+2. Create a Model.::
+
+ linear = Model(f)
+
+3. Create a Data or RealData instance.::
+
+ mydata = Data(x, y, wd=1./power(sx,2), we=1./power(sy,2))
+
+ or, when the actual covariances are known::
+
+ mydata = RealData(x, y, sx=sx, sy=sy)
+
+4. Instantiate ODR with your data, model and initial parameter estimate.::
+
+ myodr = ODR(mydata, linear, beta0=[1., 2.])
+
+5. Run the fit.::
+
+ myoutput = myodr.run()
+
+6. Examine output.::
+
+ myoutput.pprint()
+
+
+References
+----------
+.. [1] P. T. Boggs and J. E. Rogers, "Orthogonal Distance Regression,"
+ in "Statistical analysis of measurement error models and
+ applications: proceedings of the AMS-IMS-SIAM joint summer research
+ conference held June 10-16, 1989," Contemporary Mathematics,
+ vol. 112, pg. 186, 1990.
+
+"""
+# version: 0.7
+# author: Robert Kern
+# date: 2006-09-21
+
+from ._odrpack import *
+from ._models import *
+from . import _add_newdocs
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import models, odrpack
+
+__all__ = [s for s in dir()
+ if not (s.startswith('_') or s in ('odr_stop', 'odr_error'))]
+
+import warnings
+msg = ("`scipy.odr` is deprecated as of version 1.17.0 and will be removed in "
+ "SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.")
+warnings.warn(msg, DeprecationWarning, stacklevel=2)
+del warnings
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..a376a9e44f2607d06b59ff384e5fbf4b95b0f181
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/__odrpack.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:70f16af62aecdf0b1bec4dc63dfa0e78190e7ced2b82566cac19bd1446b1be53
+size 240656
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/_add_newdocs.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/_add_newdocs.py
new file mode 100644
index 0000000000000000000000000000000000000000..3961b7623e88affeb7514fd702124319a495722e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/_add_newdocs.py
@@ -0,0 +1,39 @@
+from numpy.lib import add_newdoc
+
+add_newdoc('scipy.odr', 'odr',
+ """
+ odr(fcn, beta0, y, x, we=None, wd=None, fjacb=None, fjacd=None, extra_args=None,
+ ifixx=None, ifixb=None, job=0, iprint=0, errfile=None, rptfile=None, ndigit=0,
+ taufac=0.0, sstol=-1.0, partol=-1.0, maxit=-1, stpb=None, stpd=None, sclb=None,
+ scld=None, work=None, iwork=None, full_output=0)
+
+ Low-level function for ODR.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ See Also
+ --------
+ ODR : The ODR class gathers all information and coordinates the running of the
+ main fitting routine.
+ Model : The Model class stores information about the function you wish to fit.
+ Data : The data to fit.
+ RealData : Data with weights as actual std. dev.s and/or covariances.
+
+ Notes
+ -----
+ This is a function performing the same operation as the `ODR`,
+ `Model`, and `Data` classes together. The parameters of this
+ function are explained in the class documentation.
+
+ """)
+
+add_newdoc('scipy.odr.__odrpack', '_set_exceptions',
+ """
+ _set_exceptions(odr_error, odr_stop)
+
+ Internal function: set exception classes.
+
+ """)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/_models.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/_models.py
new file mode 100644
index 0000000000000000000000000000000000000000..8e5e7314873acc95bad184ca5410215f34b968fd
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/_models.py
@@ -0,0 +1,333 @@
+""" Collection of Model instances for use with the odrpack fitting package.
+"""
+import numpy as np
+from scipy.odr._odrpack import Model
+
+__all__ = ['Model', 'exponential', 'multilinear', 'unilinear', 'quadratic',
+ 'polynomial']
+
+
+def _lin_fcn(B, x):
+ a, b = B[0], B[1:]
+ b = b.reshape((b.shape[0], 1))
+
+ return a + (x*b).sum(axis=0)
+
+
+def _lin_fjb(B, x):
+ a = np.ones(x.shape[-1], float)
+ res = np.concatenate((a, x.ravel()))
+ return res.reshape((B.shape[-1], x.shape[-1]))
+
+
+def _lin_fjd(B, x):
+ b = B[1:]
+ b = np.repeat(b, (x.shape[-1],)*b.shape[-1], axis=0)
+ return b.reshape(x.shape)
+
+
+def _lin_est(data):
+ # Eh. The answer is analytical, so just return all ones.
+ # Don't return zeros since that will interfere with
+ # ODRPACK's auto-scaling procedures.
+
+ if len(data.x.shape) == 2:
+ m = data.x.shape[0]
+ else:
+ m = 1
+
+ return np.ones((m + 1,), float)
+
+
+def _poly_fcn(B, x, powers):
+ a, b = B[0], B[1:]
+ b = b.reshape((b.shape[0], 1))
+
+ return a + np.sum(b * np.power(x, powers), axis=0)
+
+
+def _poly_fjacb(B, x, powers):
+ res = np.concatenate((np.ones(x.shape[-1], float),
+ np.power(x, powers).flat))
+ return res.reshape((B.shape[-1], x.shape[-1]))
+
+
+def _poly_fjacd(B, x, powers):
+ b = B[1:]
+ b = b.reshape((b.shape[0], 1))
+
+ b = b * powers
+
+ return np.sum(b * np.power(x, powers-1), axis=0)
+
+
+def _exp_fcn(B, x):
+ return B[0] + np.exp(B[1] * x)
+
+
+def _exp_fjd(B, x):
+ return B[1] * np.exp(B[1] * x)
+
+
+def _exp_fjb(B, x):
+ res = np.concatenate((np.ones(x.shape[-1], float), x * np.exp(B[1] * x)))
+ return res.reshape((2, x.shape[-1]))
+
+
+def _exp_est(data):
+ # Eh.
+ return np.array([1., 1.])
+
+
+class _MultilinearModel(Model):
+ r"""
+ Arbitrary-dimensional linear model
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+
+ This model is defined by :math:`y=\beta_0 + \sum_{i=1}^m \beta_i x_i`
+
+ Examples
+ --------
+ We can calculate orthogonal distance regression with an arbitrary
+ dimensional linear model:
+
+ >>> from scipy import odr
+ >>> import numpy as np
+ >>> x = np.linspace(0.0, 5.0)
+ >>> y = 10.0 + 5.0 * x
+ >>> data = odr.Data(x, y)
+ >>> odr_obj = odr.ODR(data, odr.multilinear)
+ >>> output = odr_obj.run()
+ >>> print(output.beta)
+ [10. 5.]
+
+ """
+
+ def __init__(self):
+ super().__init__(
+ _lin_fcn, fjacb=_lin_fjb, fjacd=_lin_fjd, estimate=_lin_est,
+ meta={'name': 'Arbitrary-dimensional Linear',
+ 'equ': 'y = B_0 + Sum[i=1..m, B_i * x_i]',
+ 'TeXequ': r'$y=\beta_0 + \sum_{i=1}^m \beta_i x_i$'})
+
+
+multilinear = _MultilinearModel()
+
+
+def polynomial(order):
+ """
+ Factory function for a general polynomial model.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ Parameters
+ ----------
+ order : int or sequence
+ If an integer, it becomes the order of the polynomial to fit. If
+ a sequence of numbers, then these are the explicit powers in the
+ polynomial.
+ A constant term (power 0) is always included, so don't include 0.
+ Thus, polynomial(n) is equivalent to polynomial(range(1, n+1)).
+
+ Returns
+ -------
+ polynomial : Model instance
+ Model instance.
+
+ Examples
+ --------
+ We can fit an input data using orthogonal distance regression (ODR) with
+ a polynomial model:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy import odr
+ >>> x = np.linspace(0.0, 5.0)
+ >>> y = np.sin(x)
+ >>> poly_model = odr.polynomial(3) # using third order polynomial model
+ >>> data = odr.Data(x, y)
+ >>> odr_obj = odr.ODR(data, poly_model)
+ >>> output = odr_obj.run() # running ODR fitting
+ >>> poly = np.poly1d(output.beta[::-1])
+ >>> poly_y = poly(x)
+ >>> plt.plot(x, y, label="input data")
+ >>> plt.plot(x, poly_y, label="polynomial ODR")
+ >>> plt.legend()
+ >>> plt.show()
+
+ """
+
+ powers = np.asarray(order)
+ if powers.shape == ():
+ # Scalar.
+ powers = np.arange(1, powers + 1)
+
+ powers = powers.reshape((len(powers), 1))
+ len_beta = len(powers) + 1
+
+ def _poly_est(data, len_beta=len_beta):
+ # Eh. Ignore data and return all ones.
+ return np.ones((len_beta,), float)
+
+ return Model(_poly_fcn, fjacd=_poly_fjacd, fjacb=_poly_fjacb,
+ estimate=_poly_est, extra_args=(powers,),
+ meta={'name': 'Sorta-general Polynomial',
+ 'equ': 'y = B_0 + Sum[i=1..%s, B_i * (x**i)]' % (len_beta-1),
+ 'TeXequ': r'$y=\beta_0 + \sum_{i=1}^{%s} \beta_i x^i$' %
+ (len_beta-1)})
+
+
+class _ExponentialModel(Model):
+ r"""
+ Exponential model
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ This model is defined by :math:`y=\beta_0 + e^{\beta_1 x}`
+
+ Examples
+ --------
+ We can calculate orthogonal distance regression with an exponential model:
+
+ >>> from scipy import odr
+ >>> import numpy as np
+ >>> x = np.linspace(0.0, 5.0)
+ >>> y = -10.0 + np.exp(0.5*x)
+ >>> data = odr.Data(x, y)
+ >>> odr_obj = odr.ODR(data, odr.exponential)
+ >>> output = odr_obj.run()
+ >>> print(output.beta)
+ [-10. 0.5]
+
+ """
+
+ def __init__(self):
+ super().__init__(_exp_fcn, fjacd=_exp_fjd, fjacb=_exp_fjb,
+ estimate=_exp_est,
+ meta={'name': 'Exponential',
+ 'equ': 'y= B_0 + exp(B_1 * x)',
+ 'TeXequ': r'$y=\beta_0 + e^{\beta_1 x}$'})
+
+
+exponential = _ExponentialModel()
+
+
+def _unilin(B, x):
+ return x*B[0] + B[1]
+
+
+def _unilin_fjd(B, x):
+ return np.ones(x.shape, float) * B[0]
+
+
+def _unilin_fjb(B, x):
+ _ret = np.concatenate((x, np.ones(x.shape, float)))
+ return _ret.reshape((2,) + x.shape)
+
+
+def _unilin_est(data):
+ return (1., 1.)
+
+
+def _quadratic(B, x):
+ return x*(x*B[0] + B[1]) + B[2]
+
+
+def _quad_fjd(B, x):
+ return 2*x*B[0] + B[1]
+
+
+def _quad_fjb(B, x):
+ _ret = np.concatenate((x*x, x, np.ones(x.shape, float)))
+ return _ret.reshape((3,) + x.shape)
+
+
+def _quad_est(data):
+ return (1.,1.,1.)
+
+
+class _UnilinearModel(Model):
+ r"""
+ Univariate linear model
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ This model is defined by :math:`y = \beta_0 x + \beta_1`
+
+ Examples
+ --------
+ We can calculate orthogonal distance regression with 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
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ This model is defined by :math:`y = \beta_0 x^2 + \beta_1 x + \beta_2`
+
+ Examples
+ --------
+ We can calculate orthogonal distance regression with a quadratic model:
+
+ >>> from scipy import odr
+ >>> import numpy as np
+ >>> x = np.linspace(0.0, 5.0)
+ >>> y = 1.0 * x ** 2 + 2.0 * x + 3.0
+ >>> data = odr.Data(x, y)
+ >>> odr_obj = odr.ODR(data, odr.quadratic)
+ >>> output = odr_obj.run()
+ >>> print(output.beta)
+ [1. 2. 3.]
+
+ """
+
+ def __init__(self):
+ super().__init__(
+ _quadratic, fjacd=_quad_fjd, fjacb=_quad_fjb, estimate=_quad_est,
+ meta={'name': 'Quadratic',
+ 'equ': 'y = B_0*x**2 + B_1*x + B_2',
+ 'TeXequ': '$y = \\beta_0 x^2 + \\beta_1 x + \\beta_2'})
+
+
+quadratic = _QuadraticModel()
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/_odrpack.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/_odrpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..0f9af4a92f6fed986d9f5de8a6d5115e65315f5c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/_odrpack.py
@@ -0,0 +1,1200 @@
+"""
+Python wrappers for Orthogonal Distance Regression (ODRPACK).
+
+Notes
+=====
+
+* Array formats -- FORTRAN stores its arrays in memory column first, i.e., an
+ array element A(i, j, k) will be next to A(i+1, j, k). In C and, consequently,
+ NumPy, arrays are stored row first: A[i, j, k] is next to A[i, j, k+1]. For
+ efficiency and convenience, the input and output arrays of the fitting
+ function (and its Jacobians) are passed to FORTRAN without transposition.
+ Therefore, where the ODRPACK documentation says that the X array is of shape
+ (N, M), it will be passed to the Python function as an array of shape (M, N).
+ If M==1, the 1-D case, then nothing matters; if M>1, then your
+ Python functions will be dealing with arrays that are indexed in reverse of
+ the ODRPACK documentation. No real issue, but watch out for your indexing of
+ the Jacobians: the i,jth elements (@f_i/@x_j) evaluated at the nth
+ observation will be returned as jacd[j, i, n]. Except for the Jacobians, it
+ really is easier to deal with x[0] and x[1] than x[:,0] and x[:,1]. Of course,
+ you can always use the transpose() function from SciPy explicitly.
+
+* Examples -- See the accompanying file test/test.py for examples of how to set
+ up fits of your own. Some are taken from the User's Guide; some are from
+ other sources.
+
+* Models -- Some common models are instantiated in the accompanying module
+ models.py . Contributions are welcome.
+
+Credits
+=======
+
+* Thanks to Arnold Moene and Gerard Vermeulen for fixing some killer bugs.
+
+Robert Kern
+robert.kern@gmail.com
+
+"""
+import os
+from threading import Lock
+
+import numpy as np
+from warnings import warn
+from scipy.odr import __odrpack
+
+__all__ = ['odr', 'OdrWarning', 'OdrError', 'OdrStop',
+ 'Data', 'RealData', 'Model', 'Output', 'ODR',
+ 'odr_error', 'odr_stop']
+
+odr = __odrpack.odr
+ODR_LOCK = Lock()
+
+
+class OdrWarning(UserWarning):
+ """
+ Warning indicating that the data passed into
+ ODR will cause problems when passed into 'odr'
+ that the user should be aware of.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ """
+ pass
+
+
+class OdrError(Exception):
+ """
+ Exception indicating an error in fitting.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+
+ This is raised by `~scipy.odr.odr` if an error occurs during fitting.
+ """
+ pass
+
+
+class OdrStop(Exception):
+ """
+ Exception stopping fitting.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+
+ You can raise this exception in your objective function to tell
+ `~scipy.odr.odr` to stop fitting.
+ """
+ pass
+
+
+# Backwards compatibility
+odr_error = OdrError
+odr_stop = OdrStop
+
+__odrpack._set_exceptions(OdrError, OdrStop)
+
+
+def _conv(obj, dtype=None):
+ """ Convert an object to the preferred form for input to the odr routine.
+ """
+
+ if obj is None:
+ return obj
+ else:
+ if dtype is None:
+ obj = np.asarray(obj)
+ else:
+ obj = np.asarray(obj, dtype)
+ if obj.shape == ():
+ # Scalar.
+ return obj.dtype.type(obj)
+ else:
+ return obj
+
+
+def _report_error(info):
+ """ Interprets the return code of the odr routine.
+
+ Parameters
+ ----------
+ info : int
+ The return code of the odr routine.
+
+ Returns
+ -------
+ problems : list(str)
+ A list of messages about why the odr() routine stopped.
+ """
+
+ stopreason = ('Blank',
+ 'Sum of squares convergence',
+ 'Parameter convergence',
+ 'Both sum of squares and parameter convergence',
+ 'Iteration limit reached')[info % 5]
+
+ if info >= 5:
+ # questionable results or fatal error
+
+ I = (info//10000 % 10,
+ info//1000 % 10,
+ info//100 % 10,
+ info//10 % 10,
+ info % 10)
+ problems = []
+
+ if I[0] == 0:
+ if I[1] != 0:
+ problems.append('Derivatives possibly not correct')
+ if I[2] != 0:
+ problems.append('Error occurred in callback')
+ if I[3] != 0:
+ problems.append('Problem is not full rank at solution')
+ problems.append(stopreason)
+ elif I[0] == 1:
+ if I[1] != 0:
+ problems.append('N < 1')
+ if I[2] != 0:
+ problems.append('M < 1')
+ if I[3] != 0:
+ problems.append('NP < 1 or NP > N')
+ if I[4] != 0:
+ problems.append('NQ < 1')
+ elif I[0] == 2:
+ if I[1] != 0:
+ problems.append('LDY and/or LDX incorrect')
+ if I[2] != 0:
+ problems.append('LDWE, LD2WE, LDWD, and/or LD2WD incorrect')
+ if I[3] != 0:
+ problems.append('LDIFX, LDSTPD, and/or LDSCLD incorrect')
+ if I[4] != 0:
+ problems.append('LWORK and/or LIWORK too small')
+ elif I[0] == 3:
+ if I[1] != 0:
+ problems.append('STPB and/or STPD incorrect')
+ if I[2] != 0:
+ problems.append('SCLB and/or SCLD incorrect')
+ if I[3] != 0:
+ problems.append('WE incorrect')
+ if I[4] != 0:
+ problems.append('WD incorrect')
+ elif I[0] == 4:
+ problems.append('Error in derivatives')
+ elif I[0] == 5:
+ problems.append('Error occurred in callback')
+ elif I[0] == 6:
+ problems.append('Numerical error detected')
+
+ return problems
+
+ else:
+ return [stopreason]
+
+
+class Data:
+ """
+ The data to fit.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ Parameters
+ ----------
+ x : array_like
+ Observed data for the independent variable of the regression
+ y : array_like, optional
+ If array-like, observed data for the dependent variable of the
+ regression. A scalar input implies that the model to be used on
+ the data is implicit.
+ we : array_like, optional
+ If `we` is a scalar, then that value is used for all data points (and
+ all dimensions of the response variable).
+ If `we` is a rank-1 array of length q (the dimensionality of the
+ response variable), then this vector is the diagonal of the covariant
+ weighting matrix for all data points.
+ If `we` is a rank-1 array of length n (the number of data points), then
+ the i'th element is the weight for the i'th response variable
+ observation (single-dimensional only).
+ If `we` is a rank-2 array of shape (q, q), then this is the full
+ covariant weighting matrix broadcast to each observation.
+ If `we` is a rank-2 array of shape (q, n), then `we[:,i]` is the
+ diagonal of the covariant weighting matrix for the i'th observation.
+ If `we` is a rank-3 array of shape (q, q, n), then `we[:,:,i]` is the
+ full specification of the covariant weighting matrix for each
+ observation.
+ If the fit is implicit, then only a positive scalar value is used.
+ wd : array_like, optional
+ If `wd` is a scalar, then that value is used for all data points
+ (and all dimensions of the input variable). If `wd` = 0, then the
+ covariant weighting matrix for each observation is set to the identity
+ matrix (so each dimension of each observation has the same weight).
+ If `wd` is a rank-1 array of length m (the dimensionality of the input
+ variable), then this vector is the diagonal of the covariant weighting
+ matrix for all data points.
+ If `wd` is a rank-1 array of length n (the number of data points), then
+ the i'th element is the weight for the ith input variable observation
+ (single-dimensional only).
+ If `wd` is a rank-2 array of shape (m, m), then this is the full
+ covariant weighting matrix broadcast to each observation.
+ If `wd` is a rank-2 array of shape (m, n), then `wd[:,i]` is the
+ diagonal of the covariant weighting matrix for the ith observation.
+ If `wd` is a rank-3 array of shape (m, m, n), then `wd[:,:,i]` is the
+ full specification of the covariant weighting matrix for each
+ observation.
+ fix : array_like of ints, optional
+ The `fix` argument is the same as ifixx in the class ODR. It is an
+ array of integers with the same shape as data.x that determines which
+ input observations are treated as fixed. One can use a sequence of
+ length m (the dimensionality of the input observations) to fix some
+ dimensions for all observations. A value of 0 fixes the observation,
+ a value > 0 makes it free.
+ meta : dict, optional
+ Free-form dictionary for metadata.
+
+ Notes
+ -----
+ Each argument is attached to the member of the instance of the same name.
+ The structures of `x` and `y` are described in the Model class docstring.
+ If `y` is an integer, then the Data instance can only be used to fit with
+ implicit models where the dimensionality of the response is equal to the
+ specified value of `y`.
+
+ The `we` argument weights the effect a deviation in the response variable
+ has on the fit. The `wd` argument weights the effect a deviation in the
+ input variable has on the fit. To handle multidimensional inputs and
+ responses easily, the structure of these arguments has the n'th
+ dimensional axis first. These arguments heavily use the structured
+ arguments feature of ODRPACK to conveniently and flexibly support all
+ options. See the ODRPACK User's Guide for a full explanation of how these
+ weights are used in the algorithm. Basically, a higher value of the weight
+ for a particular data point makes a deviation at that point more
+ detrimental to the fit.
+
+ """
+
+ def __init__(self, x, y=None, we=None, wd=None, fix=None, meta=None):
+ self.x = _conv(x)
+
+ if not isinstance(self.x, np.ndarray):
+ raise ValueError("Expected an 'ndarray' of data for 'x', "
+ f"but instead got data of type '{type(self.x).__name__}'")
+
+ self.y = _conv(y)
+ self.we = _conv(we)
+ self.wd = _conv(wd)
+ self.fix = _conv(fix)
+ self.meta = {} if meta is None else meta
+
+ def set_meta(self, **kwds):
+ """ Update the metadata dictionary with the keywords and data provided
+ by keywords.
+
+ Examples
+ --------
+ ::
+
+ data.set_meta(lab="Ph 7; Lab 26", title="Ag110 + Ag108 Decay")
+ """
+
+ self.meta.update(kwds)
+
+ def __getattr__(self, attr):
+ """ Dispatch attribute access to the metadata dictionary.
+ """
+ if attr != "meta" and attr in self.meta:
+ return self.meta[attr]
+ else:
+ raise AttributeError(f"'{attr}' not in metadata")
+
+
+class RealData(Data):
+ """
+ The data, with weightings as actual standard deviations and/or
+ covariances.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ Parameters
+ ----------
+ x : array_like
+ Observed data for the independent variable of the regression
+ y : array_like, optional
+ If array-like, observed data for the dependent variable of the
+ regression. A scalar input implies that the model to be used on
+ the data is implicit.
+ sx : array_like, optional
+ Standard deviations of `x`.
+ `sx` are standard deviations of `x` and are converted to weights by
+ dividing 1.0 by their squares.
+ sy : array_like, optional
+ Standard deviations of `y`.
+ `sy` are standard deviations of `y` and are converted to weights by
+ dividing 1.0 by their squares.
+ covx : array_like, optional
+ Covariance of `x`
+ `covx` is an array of covariance matrices of `x` and are converted to
+ weights by performing a matrix inversion on each observation's
+ covariance matrix.
+ covy : array_like, optional
+ Covariance of `y`
+ `covy` is an array of covariance matrices and are converted to
+ weights by performing a matrix inversion on each observation's
+ covariance matrix.
+ fix : array_like, optional
+ The argument and member fix is the same as Data.fix and ODR.ifixx:
+ It is an array of integers with the same shape as `x` that
+ determines which input observations are treated as fixed. One can
+ use a sequence of length m (the dimensionality of the input
+ observations) to fix some dimensions for all observations. A value
+ of 0 fixes the observation, a value > 0 makes it free.
+ meta : dict, optional
+ Free-form dictionary for metadata.
+
+ Notes
+ -----
+ The weights `wd` and `we` are computed from provided values as follows:
+
+ `sx` and `sy` are converted to weights by dividing 1.0 by their squares.
+ For example, ``wd = 1./np.power(`sx`, 2)``.
+
+ `covx` and `covy` are arrays of covariance matrices and are converted to
+ weights by performing a matrix inversion on each observation's covariance
+ matrix. For example, ``we[i] = np.linalg.inv(covy[i])``.
+
+ These arguments follow the same structured argument conventions as wd and
+ we only restricted by their natures: `sx` and `sy` can't be rank-3, but
+ `covx` and `covy` can be.
+
+ Only set *either* `sx` or `covx` (not both). Setting both will raise an
+ exception. Same with `sy` and `covy`.
+
+ """
+
+ def __init__(self, x, y=None, sx=None, sy=None, covx=None, covy=None,
+ fix=None, meta=None):
+ if (sx is not None) and (covx is not None):
+ raise ValueError("cannot set both sx and covx")
+ if (sy is not None) and (covy is not None):
+ raise ValueError("cannot set both sy and covy")
+
+ # Set flags for __getattr__
+ self._ga_flags = {}
+ if sx is not None:
+ self._ga_flags['wd'] = 'sx'
+ else:
+ self._ga_flags['wd'] = 'covx'
+ if sy is not None:
+ self._ga_flags['we'] = 'sy'
+ else:
+ self._ga_flags['we'] = 'covy'
+
+ self.x = _conv(x)
+
+ if not isinstance(self.x, np.ndarray):
+ raise ValueError("Expected an 'ndarray' of data for 'x', "
+ f"but instead got data of type '{type(self.x).__name__}'")
+
+ self.y = _conv(y)
+ self.sx = _conv(sx)
+ self.sy = _conv(sy)
+ self.covx = _conv(covx)
+ self.covy = _conv(covy)
+ self.fix = _conv(fix)
+ self.meta = {} if meta is None else meta
+
+ def _sd2wt(self, sd):
+ """ Convert standard deviation to weights.
+ """
+
+ return 1./np.power(sd, 2)
+
+ def _cov2wt(self, cov):
+ """ Convert covariance matrix(-ices) to weights.
+ """
+
+ from scipy.linalg import inv
+
+ if len(cov.shape) == 2:
+ return inv(cov)
+ else:
+ weights = np.zeros(cov.shape, float)
+
+ for i in range(cov.shape[-1]): # n
+ weights[:,:,i] = inv(cov[:,:,i])
+
+ return weights
+
+ def __getattr__(self, attr):
+
+ if attr not in ('wd', 'we'):
+ if attr != "meta" and attr in self.meta:
+ return self.meta[attr]
+ else:
+ raise AttributeError(f"'{attr}' not in metadata")
+ else:
+ lookup_tbl = {('wd', 'sx'): (self._sd2wt, self.sx),
+ ('wd', 'covx'): (self._cov2wt, self.covx),
+ ('we', 'sy'): (self._sd2wt, self.sy),
+ ('we', 'covy'): (self._cov2wt, self.covy)}
+
+ func, arg = lookup_tbl[(attr, self._ga_flags[attr])]
+
+ if arg is not None:
+ return func(*(arg,))
+ else:
+ return None
+
+
+class Model:
+ """
+ The Model class stores information about the function you wish to fit.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ It stores the function itself, at the least, and optionally stores
+ functions which compute the Jacobians used during fitting. Also, one
+ can provide a function that will provide reasonable starting values
+ for the fit parameters possibly given the set of data.
+
+ Parameters
+ ----------
+ fcn : function
+ fcn(beta, x) --> y
+ fjacb : function
+ Jacobian of fcn wrt the fit parameters beta.
+
+ fjacb(beta, x) --> @f_i(x,B)/@B_j
+ fjacd : function
+ Jacobian of fcn wrt the (possibly multidimensional) input
+ variable.
+
+ fjacd(beta, x) --> @f_i(x,B)/@x_j
+ extra_args : tuple, optional
+ If specified, `extra_args` should be a tuple of extra
+ arguments to pass to `fcn`, `fjacb`, and `fjacd`. Each will be called
+ by `apply(fcn, (beta, x) + extra_args)`
+ estimate : array_like of rank-1
+ Provides estimates of the fit parameters from the data
+
+ estimate(data) --> estbeta
+ implicit : 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(beta,x)[l,k,i] =
+ d f_l(beta,x)/d B_k`` evaluated at the ith data point. If ``q == 1``, then
+ the return array is only rank-2 and with shape ``(p, n)``.
+ `fjacd`
+ as with fjacb, only the return array's shape is ``(q, m, n)``
+ such that ``fjacd(beta,x)[l,j,i] = d f_l(beta,x)/d X_j`` at the ith data
+ point. If ``q == 1``, then the return array's shape is ``(m, n)``. If
+ ``m == 1``, the shape is (q, n). If `m == q == 1`, the shape is ``(n,)``.
+
+ """
+
+ def __init__(self, fcn, fjacb=None, fjacd=None,
+ extra_args=None, estimate=None, implicit=0, meta=None):
+
+ self.fcn = fcn
+ self.fjacb = fjacb
+ self.fjacd = fjacd
+
+ if extra_args is not None:
+ extra_args = tuple(extra_args)
+
+ self.extra_args = extra_args
+ self.estimate = estimate
+ self.implicit = implicit
+ self.meta = meta if meta is not None else {}
+
+ def set_meta(self, **kwds):
+ """ Update the metadata dictionary with the keywords and data provided
+ here.
+
+ Examples
+ --------
+ set_meta(name="Exponential", equation="y = a exp(b x) + c")
+ """
+
+ self.meta.update(kwds)
+
+ def __getattr__(self, attr):
+ """ Dispatch attribute access to the metadata.
+ """
+
+ if attr != "meta" and attr in self.meta:
+ return self.meta[attr]
+ else:
+ raise AttributeError(f"'{attr}' not in metadata")
+
+
+class Output:
+ """
+ The Output class stores the output of an ODR run.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ Attributes
+ ----------
+ beta : ndarray
+ Estimated parameter values, of shape (q,).
+ sd_beta : ndarray
+ Standard deviations of the estimated parameters, of shape (p,).
+ cov_beta : ndarray
+ Covariance matrix of the estimated parameters, of shape (p,p).
+ Note that this `cov_beta` is not scaled by the residual variance
+ `res_var`, whereas `sd_beta` is. This means
+ ``np.sqrt(np.diag(output.cov_beta * output.res_var))`` is the same
+ result as `output.sd_beta`.
+ delta : ndarray, optional
+ Array of estimated errors in input variables, of same shape as `x`.
+ eps : ndarray, optional
+ Array of estimated errors in response variables, of same shape as `y`.
+ xplus : ndarray, optional
+ Array of ``x + delta``.
+ y : ndarray, optional
+ Array ``y = fcn(x + delta)``.
+ res_var : float, optional
+ Residual variance.
+ sum_square : float, optional
+ Sum of squares error.
+ sum_square_delta : float, optional
+ Sum of squares of delta error.
+ sum_square_eps : float, optional
+ Sum of squares of eps error.
+ inv_condnum : float, optional
+ Inverse condition number (cf. ODRPACK UG p. 77).
+ rel_error : float, optional
+ Relative error in function values computed within fcn.
+ work : ndarray, optional
+ Final work array.
+ work_ind : dict, optional
+ Indices into work for drawing out values (cf. ODRPACK UG p. 83).
+ info : int, optional
+ Reason for returning, as output by ODRPACK (cf. ODRPACK UG p. 38).
+ stopreason : list of str, optional
+ `info` interpreted into English.
+
+ Notes
+ -----
+ Takes one argument for initialization, the return value from the
+ function `~scipy.odr.odr`. The attributes listed as "optional" above are
+ only present if `~scipy.odr.odr` was run with ``full_output=1``.
+
+ """
+
+ def __init__(self, output):
+ self.beta = output[0]
+ self.sd_beta = output[1]
+ self.cov_beta = output[2]
+
+ if len(output) == 4:
+ # full output
+ self.__dict__.update(output[3])
+ self.stopreason = _report_error(self.info)
+
+ def pprint(self):
+ """ Pretty-print important results.
+ """
+
+ print('Beta:', self.beta)
+ print('Beta Std Error:', self.sd_beta)
+ print('Beta Covariance:', self.cov_beta)
+ if hasattr(self, 'info'):
+ print('Residual Variance:',self.res_var)
+ print('Inverse Condition #:', self.inv_condnum)
+ print('Reason(s) for Halting:')
+ for r in self.stopreason:
+ print(f' {r}')
+
+
+class ODR:
+ """
+ The ODR class gathers all information and coordinates the running of the
+ main fitting routine.
+
+ .. deprecated:: 1.17.0
+ `scipy.odr` is deprecated and will be removed in SciPy 1.19.0. Please use
+ `pypi.org/project/odrpack/ `_
+ instead.
+
+ Members of instances of the ODR class have the same names as the arguments
+ to the initialization routine.
+
+ Parameters
+ ----------
+ data : Data class instance
+ instance of the Data class
+ model : Model class instance
+ instance of the Model class
+
+ Other Parameters
+ ----------------
+ beta0 : array_like of rank-1
+ a rank-1 sequence of initial parameter values. Optional if
+ model provides an "estimate" function to estimate these values.
+ delta0 : array_like of floats of rank-1, optional
+ a (double-precision) float array to hold the initial values of
+ the errors in the input variables. Must be same shape as data.x
+ ifixb : array_like of ints of rank-1, optional
+ sequence of integers with the same length as beta0 that determines
+ which parameters are held fixed. A value of 0 fixes the parameter,
+ a value > 0 makes the parameter free.
+ ifixx : array_like of ints with same shape as data.x, optional
+ an array of integers with the same shape as data.x that determines
+ which input observations are treated as fixed. One can use a sequence
+ of length m (the dimensionality of the input observations) to fix some
+ dimensions for all observations. A value of 0 fixes the observation,
+ a value > 0 makes it free.
+ job : int, optional
+ an integer telling ODRPACK what tasks to perform. See p. 31 of the
+ ODRPACK User's Guide if you absolutely must set the value here. Use the
+ method set_job post-initialization for a more readable interface.
+ iprint : int, optional
+ an integer telling ODRPACK what to print. See pp. 33-34 of the
+ ODRPACK User's Guide if you absolutely must set the value here. Use the
+ method set_iprint post-initialization for a more readable interface.
+ errfile : str, optional
+ string with the filename to print ODRPACK errors to. If the file already
+ exists, an error will be thrown. The `overwrite` argument can be used to
+ prevent this. *Do Not Open This File Yourself!*
+ rptfile : str, optional
+ string with the filename to print ODRPACK summaries to. If the file
+ already exists, an error will be thrown. The `overwrite` argument can be
+ used to prevent this. *Do Not Open This File Yourself!*
+ ndigit : int, optional
+ integer specifying the number of reliable digits in the computation
+ of the function.
+ taufac : float, optional
+ float specifying the initial trust region. The default value is 1.
+ The initial trust region is equal to taufac times the length of the
+ first computed Gauss-Newton step. taufac must be less than 1.
+ sstol : float, optional
+ float specifying the tolerance for convergence based on the relative
+ change in the sum-of-squares. The default value is eps**(1/2) where eps
+ is the smallest value such that 1 + eps > 1 for double precision
+ computation on the machine. sstol must be less than 1.
+ partol : float, optional
+ float specifying the tolerance for convergence based on the relative
+ change in the estimated parameters. The default value is eps**(2/3) for
+ explicit models and ``eps**(1/3)`` for implicit models. partol must be less
+ than 1.
+ maxit : int, optional
+ integer specifying the maximum number of iterations to perform. For
+ first runs, maxit is the total number of iterations performed and
+ defaults to 50. For restarts, maxit is the number of additional
+ iterations to perform and defaults to 10.
+ stpb : array_like, optional
+ sequence (``len(stpb) == len(beta0)``) of relative step sizes to compute
+ finite difference derivatives wrt the parameters.
+ stpd : optional
+ array (``stpd.shape == data.x.shape`` or ``stpd.shape == (m,)``) of relative
+ step sizes to compute finite difference derivatives wrt the input
+ variable errors. If stpd is a rank-1 array with length m (the
+ dimensionality of the input variable), then the values are broadcast to
+ all observations.
+ sclb : array_like, optional
+ sequence (``len(stpb) == len(beta0)``) of scaling factors for the
+ parameters. The purpose of these scaling factors are to scale all of
+ the parameters to around unity. Normally appropriate scaling factors
+ are computed if this argument is not specified. Specify them yourself
+ if the automatic procedure goes awry.
+ scld : array_like, optional
+ array (scld.shape == data.x.shape or scld.shape == (m,)) of scaling
+ factors for the *errors* in the input variables. Again, these factors
+ are automatically computed if you do not provide them. If scld.shape ==
+ (m,), then the scaling factors are broadcast to all observations.
+ work : ndarray, optional
+ array to hold the double-valued working data for ODRPACK. When
+ restarting, takes the value of self.output.work.
+ iwork : ndarray, optional
+ array to hold the integer-valued working data for ODRPACK. When
+ restarting, takes the value of self.output.iwork.
+ overwrite : bool, optional
+ If it is True, output files defined by `errfile` and `rptfile` are
+ overwritten. The default is False.
+
+ Attributes
+ ----------
+ data : Data
+ The data for this fit
+ model : Model
+ The model used in fit
+ output : Output
+ An instance if the Output class containing all of the returned
+ data from an invocation of ODR.run() or ODR.restart()
+
+ """
+
+ def __init__(self, data, model, beta0=None, delta0=None, ifixb=None,
+ ifixx=None, job=None, iprint=None, errfile=None, rptfile=None,
+ ndigit=None, taufac=None, sstol=None, partol=None, maxit=None,
+ stpb=None, stpd=None, sclb=None, scld=None, work=None, iwork=None,
+ overwrite=False):
+
+ self.data = data
+ self.model = model
+
+ if beta0 is None:
+ if self.model.estimate is not None:
+ self.beta0 = _conv(self.model.estimate(self.data))
+ else:
+ raise ValueError(
+ "must specify beta0 or provide an estimator with the model"
+ )
+ else:
+ self.beta0 = _conv(beta0)
+
+ if ifixx is None and data.fix is not None:
+ ifixx = data.fix
+
+ if overwrite:
+ # remove output files for overwriting.
+ if rptfile is not None and os.path.exists(rptfile):
+ os.remove(rptfile)
+ if errfile is not None and os.path.exists(errfile):
+ os.remove(errfile)
+
+ self.delta0 = _conv(delta0)
+ # These really are 32-bit integers in FORTRAN (gfortran), even on 64-bit
+ # platforms.
+ # XXX: some other FORTRAN compilers may not agree.
+ self.ifixx = _conv(ifixx, dtype=np.int32)
+ self.ifixb = _conv(ifixb, dtype=np.int32)
+ self.job = job
+ self.iprint = iprint
+ self.errfile = errfile
+ self.rptfile = rptfile
+ self.ndigit = ndigit
+ self.taufac = taufac
+ self.sstol = sstol
+ self.partol = partol
+ self.maxit = maxit
+ self.stpb = _conv(stpb)
+ self.stpd = _conv(stpd)
+ self.sclb = _conv(sclb)
+ self.scld = _conv(scld)
+ self.work = _conv(work)
+ self.iwork = _conv(iwork)
+
+ self.output = None
+
+ self._check()
+
+ def _check(self):
+ """ Check the inputs for consistency, but don't bother checking things
+ that the builtin function odr will check.
+ """
+
+ x_s = list(self.data.x.shape)
+
+ if isinstance(self.data.y, np.ndarray):
+ y_s = list(self.data.y.shape)
+ if self.model.implicit:
+ raise OdrError("an implicit model cannot use response data")
+ if self.job is not None and (self.job % 10) == 1:
+ raise OdrError("job parameter requests an implicit model,"
+ " but an explicit model was passed")
+ else:
+ # implicit model with q == self.data.y
+ y_s = [self.data.y, x_s[-1]]
+ if not self.model.implicit:
+ raise OdrError("an explicit model needs response data")
+ self.set_job(fit_type=1)
+
+ if x_s[-1] != y_s[-1]:
+ raise OdrError("number of observations do not match")
+
+ n = x_s[-1]
+
+ if len(x_s) == 2:
+ m = x_s[0]
+ else:
+ m = 1
+ if len(y_s) == 2:
+ q = y_s[0]
+ else:
+ q = 1
+
+ p = len(self.beta0)
+
+ # permissible output array shapes
+
+ fcn_perms = [(q, n)]
+ fjacd_perms = [(q, m, n)]
+ fjacb_perms = [(q, p, n)]
+
+ if q == 1:
+ fcn_perms.append((n,))
+ fjacd_perms.append((m, n))
+ fjacb_perms.append((p, n))
+ if m == 1:
+ fjacd_perms.append((q, n))
+ if p == 1:
+ fjacb_perms.append((q, n))
+ if m == q == 1:
+ fjacd_perms.append((n,))
+ if p == q == 1:
+ fjacb_perms.append((n,))
+
+ # try evaluating the supplied functions to make sure they provide
+ # sensible outputs
+
+ arglist = (self.beta0, self.data.x)
+ if self.model.extra_args is not None:
+ arglist = arglist + self.model.extra_args
+ res = self.model.fcn(*arglist)
+
+ if res.shape not in fcn_perms:
+ print(res.shape)
+ print(fcn_perms)
+ raise OdrError(f"fcn does not output {y_s}-shaped array")
+
+ if self.model.fjacd is not None:
+ res = self.model.fjacd(*arglist)
+ if res.shape not in fjacd_perms:
+ raise OdrError(
+ f"fjacd does not output {repr((q, m, n))}-shaped array")
+ if self.model.fjacb is not None:
+ res = self.model.fjacb(*arglist)
+ if res.shape not in fjacb_perms:
+ raise OdrError(
+ f"fjacb does not output {repr((q, p, n))}-shaped array")
+
+ # check shape of delta0
+
+ if self.delta0 is not None and self.delta0.shape != self.data.x.shape:
+ raise OdrError(
+ f"delta0 is not a {repr(self.data.x.shape)}-shaped array")
+
+ if self.data.x.size == 0:
+ warn("Empty data detected for ODR instance. "
+ "Do not expect any fitting to occur",
+ OdrWarning, stacklevel=3)
+
+ def _gen_work(self):
+ """ Generate a suitable work array if one does not already exist.
+ """
+
+ n = self.data.x.shape[-1]
+ p = self.beta0.shape[0]
+
+ if len(self.data.x.shape) == 2:
+ m = self.data.x.shape[0]
+ else:
+ m = 1
+
+ if self.model.implicit:
+ q = self.data.y
+ elif len(self.data.y.shape) == 2:
+ q = self.data.y.shape[0]
+ else:
+ q = 1
+
+ if self.data.we is None:
+ ldwe = ld2we = 1
+ elif len(self.data.we.shape) == 3:
+ ld2we, ldwe = self.data.we.shape[1:]
+ else:
+ we = self.data.we
+ ldwe = 1
+ ld2we = 1
+ if we.ndim == 1 and q == 1:
+ ldwe = n
+ elif we.ndim == 2:
+ if we.shape == (q, q):
+ ld2we = q
+ elif we.shape == (q, n):
+ ldwe = n
+
+ if self.job % 10 < 2:
+ # ODR not OLS
+ lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 6*n*m + 2*n*q*p +
+ 2*n*q*m + q*q + 5*q + q*(p+m) + ldwe*ld2we*q)
+ else:
+ # OLS not ODR
+ lwork = (18 + 11*p + p*p + m + m*m + 4*n*q + 2*n*m + 2*n*q*p +
+ 5*q + q*(p+m) + ldwe*ld2we*q)
+
+ if isinstance(self.work, np.ndarray) and self.work.shape == (lwork,)\
+ and self.work.dtype.str.endswith('f8'):
+ # the existing array is fine
+ return
+ else:
+ self.work = np.zeros((lwork,), float)
+
+ def set_job(self, fit_type=None, deriv=None, var_calc=None,
+ del_init=None, restart=None):
+ """
+ Sets the "job" parameter is a hopefully comprehensible way.
+
+ If an argument is not specified, then the value is left as is. The
+ default value from class initialization is for all of these options set
+ to 0.
+
+ Parameters
+ ----------
+ fit_type : {0, 1, 2} int
+ 0 -> explicit ODR
+
+ 1 -> implicit ODR
+
+ 2 -> ordinary least-squares
+ deriv : {0, 1, 2, 3} int
+ 0 -> forward finite differences
+
+ 1 -> central finite differences
+
+ 2 -> user-supplied derivatives (Jacobians) with results
+ checked by ODRPACK
+
+ 3 -> user-supplied derivatives, no checking
+ var_calc : {0, 1, 2} int
+ 0 -> calculate asymptotic covariance matrix and fit
+ parameter uncertainties (V_B, s_B) using derivatives
+ recomputed at the final solution
+
+ 1 -> calculate V_B and s_B using derivatives from last iteration
+
+ 2 -> do not calculate V_B and s_B
+ del_init : {0, 1} int
+ 0 -> initial input variable offsets set to 0
+
+ 1 -> initial offsets provided by user in variable "work"
+ restart : {0, 1} int
+ 0 -> fit is not a restart
+
+ 1 -> fit is a restart
+
+ Notes
+ -----
+ The permissible values are different from those given on pg. 31 of the
+ ODRPACK User's Guide only in that one cannot specify numbers greater than
+ the last value for each variable.
+
+ If one does not supply functions to compute the Jacobians, the fitting
+ procedure will change deriv to 0, finite differences, as a default. To
+ initialize the input variable offsets by yourself, set del_init to 1 and
+ put the offsets into the "work" variable correctly.
+
+ """
+
+ if self.job is None:
+ job_l = [0, 0, 0, 0, 0]
+ else:
+ job_l = [self.job // 10000 % 10,
+ self.job // 1000 % 10,
+ self.job // 100 % 10,
+ self.job // 10 % 10,
+ self.job % 10]
+
+ if fit_type in (0, 1, 2):
+ job_l[4] = fit_type
+ if deriv in (0, 1, 2, 3):
+ job_l[3] = deriv
+ if var_calc in (0, 1, 2):
+ job_l[2] = var_calc
+ if del_init in (0, 1):
+ job_l[1] = del_init
+ if restart in (0, 1):
+ job_l[0] = restart
+
+ self.job = (job_l[0]*10000 + job_l[1]*1000 +
+ job_l[2]*100 + job_l[3]*10 + job_l[4])
+
+ def set_iprint(self, init=None, so_init=None,
+ iter=None, so_iter=None, iter_step=None, final=None, so_final=None):
+ """ Set the iprint parameter for the printing of computation reports.
+
+ If any of the arguments are specified here, then they are set in the
+ iprint member. If iprint is not set manually or with this method, then
+ ODRPACK defaults to no printing. If no filename is specified with the
+ member rptfile, then ODRPACK prints to stdout. One can tell ODRPACK to
+ print to stdout in addition to the specified filename by setting the
+ so_* arguments to this function, but one cannot specify to print to
+ stdout but not a file since one can do that by not specifying a rptfile
+ filename.
+
+ There are three reports: initialization, iteration, and final reports.
+ They are represented by the arguments init, iter, and final
+ respectively. The permissible values are 0, 1, and 2 representing "no
+ report", "short report", and "long report" respectively.
+
+ The argument iter_step (0 <= iter_step <= 9) specifies how often to make
+ the iteration report; the report will be made for every iter_step'th
+ iteration starting with iteration one. If iter_step == 0, then no
+ iteration report is made, regardless of the other arguments.
+
+ If the rptfile is None, then any so_* arguments supplied will raise an
+ exception.
+ """
+ if self.iprint is None:
+ self.iprint = 0
+
+ ip = [self.iprint // 1000 % 10,
+ self.iprint // 100 % 10,
+ self.iprint // 10 % 10,
+ self.iprint % 10]
+
+ # make a list to convert iprint digits to/from argument inputs
+ # rptfile, stdout
+ ip2arg = [[0, 0], # none, none
+ [1, 0], # short, none
+ [2, 0], # long, none
+ [1, 1], # short, short
+ [2, 1], # long, short
+ [1, 2], # short, long
+ [2, 2]] # long, long
+
+ if (self.rptfile is None and
+ (so_init is not None or
+ so_iter is not None or
+ so_final is not None)):
+ raise OdrError(
+ "no rptfile specified, cannot output to stdout twice")
+
+ iprint_l = ip2arg[ip[0]] + ip2arg[ip[1]] + ip2arg[ip[3]]
+
+ if init is not None:
+ iprint_l[0] = init
+ if so_init is not None:
+ iprint_l[1] = so_init
+ if iter is not None:
+ iprint_l[2] = iter
+ if so_iter is not None:
+ iprint_l[3] = so_iter
+ if final is not None:
+ iprint_l[4] = final
+ if so_final is not None:
+ iprint_l[5] = so_final
+
+ if iter_step in range(10):
+ # 0..9
+ ip[2] = iter_step
+
+ ip[0] = ip2arg.index(iprint_l[0:2])
+ ip[1] = ip2arg.index(iprint_l[2:4])
+ ip[3] = ip2arg.index(iprint_l[4:6])
+
+ self.iprint = ip[0]*1000 + ip[1]*100 + ip[2]*10 + ip[3]
+
+ def run(self):
+ """ Run the fitting routine with all of the information given and with ``full_output=1``.
+
+ Returns
+ -------
+ output : Output instance
+ This object is also assigned to the attribute .output .
+ """ # noqa: E501
+
+ args = (self.model.fcn, self.beta0, self.data.y, self.data.x)
+ kwds = {'full_output': 1}
+ kwd_l = ['ifixx', 'ifixb', 'job', 'iprint', 'errfile', 'rptfile',
+ 'ndigit', 'taufac', 'sstol', 'partol', 'maxit', 'stpb',
+ 'stpd', 'sclb', 'scld', 'work', 'iwork']
+
+ if self.delta0 is not None and (self.job // 10000) % 10 == 0:
+ # delta0 provided and fit is not a restart
+ self._gen_work()
+
+ d0 = np.ravel(self.delta0)
+
+ self.work[:len(d0)] = d0
+
+ # set the kwds from other objects explicitly
+ if self.model.fjacb is not None:
+ kwds['fjacb'] = self.model.fjacb
+ if self.model.fjacd is not None:
+ kwds['fjacd'] = self.model.fjacd
+ if self.data.we is not None:
+ kwds['we'] = self.data.we
+ if self.data.wd is not None:
+ kwds['wd'] = self.data.wd
+ if self.model.extra_args is not None:
+ kwds['extra_args'] = self.model.extra_args
+
+ # implicitly set kwds from self's members
+ for attr in kwd_l:
+ obj = getattr(self, attr)
+ if obj is not None:
+ kwds[attr] = obj
+
+ with ODR_LOCK:
+ self.output = Output(odr(*args, **kwds))
+
+ return self.output
+
+ def restart(self, iter=None):
+ """ Restarts the run with iter more iterations.
+
+ Parameters
+ ----------
+ iter : int, optional
+ ODRPACK's default for the number of new iterations is 10.
+
+ Returns
+ -------
+ output : Output instance
+ This object is also assigned to the attribute .output .
+ """
+
+ if self.output is None:
+ raise OdrError("cannot restart: run() has not been called before")
+
+ self.set_job(restart=1)
+ self.work = self.output.work
+ self.iwork = self.output.iwork
+
+ self.maxit = iter
+
+ return self.run()
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/models.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/models.py
new file mode 100644
index 0000000000000000000000000000000000000000..e144e443a2849b753733a4e604a6c389df70f73a
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/models.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.odr` namespace for importing the functions
+# included below.
+
+
+__all__ = [ # noqa: F822
+ 'Model', 'exponential', 'multilinear', 'unilinear',
+ 'quadratic', 'polynomial'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ msg = ("`scipy.odr` is deprecated as of version 1.17.0 and will be removed in "
+ "SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.")
+ if name not in __all__:
+ raise AttributeError(
+ f"`scipy.odr.models` has no attribute {name}. In addition, {msg}")
+
+ import warnings
+ from . import _models
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
+
+ return getattr(_models, name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/odrpack.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/odrpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..d3c3f029f107eabc5ad78d679cc9b4d22d8b533b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/odrpack.py
@@ -0,0 +1,28 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.odr` namespace for importing the functions
+# included below.
+
+
+__all__ = [ # noqa: F822
+ 'odr', 'OdrWarning', 'OdrError', 'OdrStop',
+ 'Data', 'RealData', 'Model', 'Output', 'ODR',
+ 'odr_error', 'odr_stop'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ msg = ("`scipy.odr` is deprecated as of version 1.17.0 and will be removed in "
+ "SciPy 1.19.0. Please use `https://pypi.org/project/odrpack/` instead.")
+ if name not in __all__:
+ raise AttributeError(
+ f"`scipy.odr.odrpack` has no attribute {name}. In addition, {msg}")
+
+ import warnings
+ from . import _odrpack
+ warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
+
+ return getattr(_odrpack, name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/._test_odr.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/._test_odr.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/._test_odr.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/test_odr.py b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/test_odr.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d0545b018097237377878fd085960587082903a
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/odr/tests/test_odr.py
@@ -0,0 +1,621 @@
+import pickle
+import tempfile
+import shutil
+import os
+
+import numpy as np
+from numpy import pi
+from numpy.testing import (assert_array_almost_equal,
+ assert_equal,
+ assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.odr import (Data, Model, ODR, RealData, OdrStop, OdrWarning,
+ OdrError, multilinear, exponential, unilinear,
+ quadratic, polynomial)
+
+
+class TestODR:
+
+ # Bad Data for 'x'
+
+ def test_bad_data(self):
+ assert_raises(ValueError, Data, 2, 1)
+ assert_raises(ValueError, RealData, 2, 1)
+
+ # Empty Data for 'x'
+ def empty_data_func(self, B, x):
+ return B[0]*x + B[1]
+
+ def test_empty_data(self):
+ beta0 = [0.02, 0.0]
+ linear = Model(self.empty_data_func)
+
+ empty_dat = Data([], [])
+ with pytest.warns(OdrWarning):
+ ODR(empty_dat, linear, beta0=beta0)
+
+ empty_dat = RealData([], [])
+ with pytest.warns(OdrWarning):
+ ODR(empty_dat, linear, beta0=beta0)
+
+ # Explicit Example
+
+ def explicit_fcn(self, B, x):
+ ret = B[0] + B[1] * np.power(np.exp(B[2]*x) - 1.0, 2)
+ return ret
+
+ def explicit_fjd(self, B, x):
+ eBx = np.exp(B[2]*x)
+ ret = B[1] * 2.0 * (eBx-1.0) * B[2] * eBx
+ return ret
+
+ def explicit_fjb(self, B, x):
+ eBx = np.exp(B[2]*x)
+ res = np.vstack([np.ones(x.shape[-1]),
+ np.power(eBx-1.0, 2),
+ B[1]*2.0*(eBx-1.0)*eBx*x])
+ return res
+
+ def test_explicit(self):
+ explicit_mod = Model(
+ self.explicit_fcn,
+ fjacb=self.explicit_fjb,
+ fjacd=self.explicit_fjd,
+ meta=dict(name='Sample Explicit Model',
+ ref='ODRPACK UG, pg. 39'),
+ )
+ explicit_dat = Data([0.,0.,5.,7.,7.5,10.,16.,26.,30.,34.,34.5,100.],
+ [1265.,1263.6,1258.,1254.,1253.,1249.8,1237.,1218.,1220.6,
+ 1213.8,1215.5,1212.])
+ explicit_odr = ODR(explicit_dat, explicit_mod, beta0=[1500.0, -50.0, -0.1],
+ ifixx=[0,0,1,1,1,1,1,1,1,1,1,0])
+ explicit_odr.set_job(deriv=2)
+ explicit_odr.set_iprint(init=0, iter=0, final=0)
+
+ out = explicit_odr.run()
+ assert_array_almost_equal(
+ out.beta,
+ np.array([1.2646548050648876e+03, -5.4018409956678255e+01,
+ -8.7849712165253724e-02]),
+ )
+ assert_array_almost_equal(
+ out.sd_beta,
+ np.array([1.0349270280543437, 1.583997785262061, 0.0063321988657267]),
+ )
+ assert_array_almost_equal(
+ out.cov_beta,
+ np.array([[4.4949592379003039e-01, -3.7421976890364739e-01,
+ -8.0978217468468912e-04],
+ [-3.7421976890364739e-01, 1.0529686462751804e+00,
+ -1.9453521827942002e-03],
+ [-8.0978217468468912e-04, -1.9453521827942002e-03,
+ 1.6827336938454476e-05]]),
+ )
+
+ # Implicit Example
+
+ def implicit_fcn(self, B, x):
+ return (B[2]*np.power(x[0]-B[0], 2) +
+ 2.0*B[3]*(x[0]-B[0])*(x[1]-B[1]) +
+ B[4]*np.power(x[1]-B[1], 2) - 1.0)
+
+ def test_implicit(self):
+ implicit_mod = Model(
+ self.implicit_fcn,
+ implicit=1,
+ meta=dict(name='Sample Implicit Model',
+ ref='ODRPACK UG, pg. 49'),
+ )
+ implicit_dat = Data([
+ [0.5,1.2,1.6,1.86,2.12,2.36,2.44,2.36,2.06,1.74,1.34,0.9,-0.28,
+ -0.78,-1.36,-1.9,-2.5,-2.88,-3.18,-3.44],
+ [-0.12,-0.6,-1.,-1.4,-2.54,-3.36,-4.,-4.75,-5.25,-5.64,-5.97,-6.32,
+ -6.44,-6.44,-6.41,-6.25,-5.88,-5.5,-5.24,-4.86]],
+ 1,
+ )
+ implicit_odr = ODR(implicit_dat, implicit_mod,
+ beta0=[-1.0, -3.0, 0.09, 0.02, 0.08])
+
+ out = implicit_odr.run()
+ assert_array_almost_equal(
+ out.beta,
+ np.array([-0.9993809167281279, -2.9310484652026476, 0.0875730502693354,
+ 0.0162299708984738, 0.0797537982976416]),
+ )
+ assert_array_almost_equal(
+ out.sd_beta,
+ np.array([0.1113840353364371, 0.1097673310686467, 0.0041060738314314,
+ 0.0027500347539902, 0.0034962501532468]),
+ )
+ assert_allclose(
+ out.cov_beta,
+ np.array([[2.1089274602333052e+00, -1.9437686411979040e+00,
+ 7.0263550868344446e-02, -4.7175267373474862e-02,
+ 5.2515575927380355e-02],
+ [-1.9437686411979040e+00, 2.0481509222414456e+00,
+ -6.1600515853057307e-02, 4.6268827806232933e-02,
+ -5.8822307501391467e-02],
+ [7.0263550868344446e-02, -6.1600515853057307e-02,
+ 2.8659542561579308e-03, -1.4628662260014491e-03,
+ 1.4528860663055824e-03],
+ [-4.7175267373474862e-02, 4.6268827806232933e-02,
+ -1.4628662260014491e-03, 1.2855592885514335e-03,
+ -1.2692942951415293e-03],
+ [5.2515575927380355e-02, -5.8822307501391467e-02,
+ 1.4528860663055824e-03, -1.2692942951415293e-03,
+ 2.0778813389755596e-03]]),
+ rtol=1e-6, atol=2e-6,
+ )
+
+ # Multi-variable Example
+
+ def multi_fcn(self, B, x):
+ if (x < 0.0).any():
+ raise OdrStop
+ theta = pi*B[3]/2.
+ ctheta = np.cos(theta)
+ stheta = np.sin(theta)
+ omega = np.power(2.*pi*x*np.exp(-B[2]), B[3])
+ phi = np.arctan2((omega*stheta), (1.0 + omega*ctheta))
+ r = (B[0] - B[1]) * np.power(np.sqrt(np.power(1.0 + omega*ctheta, 2) +
+ np.power(omega*stheta, 2)), -B[4])
+ ret = np.vstack([B[1] + r*np.cos(B[4]*phi),
+ r*np.sin(B[4]*phi)])
+ return ret
+
+ def test_multi(self):
+ multi_mod = Model(
+ self.multi_fcn,
+ meta=dict(name='Sample Multi-Response Model',
+ ref='ODRPACK UG, pg. 56'),
+ )
+
+ multi_x = np.array([30.0, 50.0, 70.0, 100.0, 150.0, 200.0, 300.0, 500.0,
+ 700.0, 1000.0, 1500.0, 2000.0, 3000.0, 5000.0, 7000.0, 10000.0,
+ 15000.0, 20000.0, 30000.0, 50000.0, 70000.0, 100000.0, 150000.0])
+ multi_y = np.array([
+ [4.22, 4.167, 4.132, 4.038, 4.019, 3.956, 3.884, 3.784, 3.713,
+ 3.633, 3.54, 3.433, 3.358, 3.258, 3.193, 3.128, 3.059, 2.984,
+ 2.934, 2.876, 2.838, 2.798, 2.759],
+ [0.136, 0.167, 0.188, 0.212, 0.236, 0.257, 0.276, 0.297, 0.309,
+ 0.311, 0.314, 0.311, 0.305, 0.289, 0.277, 0.255, 0.24, 0.218,
+ 0.202, 0.182, 0.168, 0.153, 0.139],
+ ])
+ n = len(multi_x)
+ multi_we = np.zeros((2, 2, n), dtype=float)
+ multi_ifixx = np.ones(n, dtype=int)
+ multi_delta = np.zeros(n, dtype=float)
+
+ multi_we[0,0,:] = 559.6
+ multi_we[1,0,:] = multi_we[0,1,:] = -1634.0
+ multi_we[1,1,:] = 8397.0
+
+ for i in range(n):
+ if multi_x[i] < 100.0:
+ multi_ifixx[i] = 0
+ elif multi_x[i] <= 150.0:
+ pass # defaults are fine
+ elif multi_x[i] <= 1000.0:
+ multi_delta[i] = 25.0
+ elif multi_x[i] <= 10000.0:
+ multi_delta[i] = 560.0
+ elif multi_x[i] <= 100000.0:
+ multi_delta[i] = 9500.0
+ else:
+ multi_delta[i] = 144000.0
+ if multi_x[i] == 100.0 or multi_x[i] == 150.0:
+ multi_we[:,:,i] = 0.0
+
+ multi_dat = Data(multi_x, multi_y, wd=1e-4/np.power(multi_x, 2),
+ we=multi_we)
+ multi_odr = ODR(multi_dat, multi_mod, beta0=[4.,2.,7.,.4,.5],
+ delta0=multi_delta, ifixx=multi_ifixx)
+ multi_odr.set_job(deriv=1, del_init=1)
+
+ out = multi_odr.run()
+ assert_array_almost_equal(
+ out.beta,
+ np.array([4.3799880305938963, 2.4333057577497703, 8.0028845899503978,
+ 0.5101147161764654, 0.5173902330489161]),
+ )
+ assert_array_almost_equal(
+ out.sd_beta,
+ np.array([0.0130625231081944, 0.0130499785273277, 0.1167085962217757,
+ 0.0132642749596149, 0.0288529201353984]),
+ )
+ assert_array_almost_equal(
+ out.cov_beta,
+ np.array([[0.0064918418231375, 0.0036159705923791, 0.0438637051470406,
+ -0.0058700836512467, 0.011281212888768],
+ [0.0036159705923791, 0.0064793789429006, 0.0517610978353126,
+ -0.0051181304940204, 0.0130726943624117],
+ [0.0438637051470406, 0.0517610978353126, 0.5182263323095322,
+ -0.0563083340093696, 0.1269490939468611],
+ [-0.0058700836512467, -0.0051181304940204, -0.0563083340093696,
+ 0.0066939246261263, -0.0140184391377962],
+ [0.011281212888768, 0.0130726943624117, 0.1269490939468611,
+ -0.0140184391377962, 0.0316733013820852]]),
+ )
+
+ # Pearson's Data
+ # K. Pearson, Philosophical Magazine, 2, 559 (1901)
+
+ def pearson_fcn(self, B, x):
+ return B[0] + B[1]*x
+
+ def test_pearson(self):
+ p_x = np.array([0.,.9,1.8,2.6,3.3,4.4,5.2,6.1,6.5,7.4])
+ p_y = np.array([5.9,5.4,4.4,4.6,3.5,3.7,2.8,2.8,2.4,1.5])
+ p_sx = np.array([.03,.03,.04,.035,.07,.11,.13,.22,.74,1.])
+ p_sy = np.array([1.,.74,.5,.35,.22,.22,.12,.12,.1,.04])
+
+ p_dat = RealData(p_x, p_y, sx=p_sx, sy=p_sy)
+
+ # Reverse the data to test invariance of results
+ pr_dat = RealData(p_y, p_x, sx=p_sy, sy=p_sx)
+
+ p_mod = Model(self.pearson_fcn, meta=dict(name='Uni-linear Fit'))
+
+ p_odr = ODR(p_dat, p_mod, beta0=[1.,1.])
+ pr_odr = ODR(pr_dat, p_mod, beta0=[1.,1.])
+
+ out = p_odr.run()
+ assert_array_almost_equal(
+ out.beta,
+ np.array([5.4767400299231674, -0.4796082367610305]),
+ )
+ assert_array_almost_equal(
+ out.sd_beta,
+ np.array([0.3590121690702467, 0.0706291186037444]),
+ )
+ assert_array_almost_equal(
+ out.cov_beta,
+ np.array([[0.0854275622946333, -0.0161807025443155],
+ [-0.0161807025443155, 0.003306337993922]]),
+ )
+
+ rout = pr_odr.run()
+ assert_array_almost_equal(
+ rout.beta,
+ np.array([11.4192022410781231, -2.0850374506165474]),
+ )
+ assert_array_almost_equal(
+ rout.sd_beta,
+ np.array([0.9820231665657161, 0.3070515616198911]),
+ )
+ assert_array_almost_equal(
+ rout.cov_beta,
+ np.array([[0.6391799462548782, -0.1955657291119177],
+ [-0.1955657291119177, 0.0624888159223392]]),
+ )
+
+ # Lorentz Peak
+ # The data is taken from one of the undergraduate physics labs I performed.
+
+ def lorentz(self, beta, x):
+ return (beta[0]*beta[1]*beta[2] / np.sqrt(np.power(x*x -
+ beta[2]*beta[2], 2.0) + np.power(beta[1]*x, 2.0)))
+
+ def test_lorentz(self):
+ l_sy = np.array([.29]*18)
+ l_sx = np.array([.000972971,.000948268,.000707632,.000706679,
+ .000706074, .000703918,.000698955,.000456856,
+ .000455207,.000662717,.000654619,.000652694,
+ .000000859202,.00106589,.00106378,.00125483, .00140818,.00241839])
+
+ l_dat = RealData(
+ [3.9094, 3.85945, 3.84976, 3.84716, 3.84551, 3.83964, 3.82608,
+ 3.78847, 3.78163, 3.72558, 3.70274, 3.6973, 3.67373, 3.65982,
+ 3.6562, 3.62498, 3.55525, 3.41886],
+ [652, 910.5, 984, 1000, 1007.5, 1053, 1160.5, 1409.5, 1430, 1122,
+ 957.5, 920, 777.5, 709.5, 698, 578.5, 418.5, 275.5],
+ sx=l_sx,
+ sy=l_sy,
+ )
+ l_mod = Model(self.lorentz, meta=dict(name='Lorentz Peak'))
+ l_odr = ODR(l_dat, l_mod, beta0=(1000., .1, 3.8))
+
+ out = l_odr.run()
+ assert_array_almost_equal(
+ out.beta,
+ np.array([1.4306780846149925e+03, 1.3390509034538309e-01,
+ 3.7798193600109009e+00]),
+ )
+ assert_array_almost_equal(
+ out.sd_beta,
+ np.array([7.3621186811330963e-01, 3.5068899941471650e-04,
+ 2.4451209281408992e-04]),
+ )
+ assert_array_almost_equal(
+ out.cov_beta,
+ np.array([[2.4714409064597873e-01, -6.9067261911110836e-05,
+ -3.1236953270424990e-05],
+ [-6.9067261911110836e-05, 5.6077531517333009e-08,
+ 3.6133261832722601e-08],
+ [-3.1236953270424990e-05, 3.6133261832722601e-08,
+ 2.7261220025171730e-08]]),
+ )
+
+ def test_ticket_1253(self):
+ def linear(c, x):
+ return c[0]*x+c[1]
+
+ c = [2.0, 3.0]
+ x = np.linspace(0, 10)
+ y = linear(c, x)
+
+ model = Model(linear)
+ data = Data(x, y, wd=1.0, we=1.0)
+ job = ODR(data, model, beta0=[1.0, 1.0])
+ result = job.run()
+ assert_equal(result.info, 2)
+
+ # Verify fix for gh-9140
+
+ def test_ifixx(self):
+ x1 = [-2.01, -0.99, -0.001, 1.02, 1.98]
+ x2 = [3.98, 1.01, 0.001, 0.998, 4.01]
+ fix = np.vstack((np.zeros_like(x1, dtype=int), np.ones_like(x2, dtype=int)))
+ data = Data(np.vstack((x1, x2)), y=1, fix=fix)
+ model = Model(lambda beta, x: x[1, :] - beta[0] * x[0, :]**2., implicit=True)
+
+ odr1 = ODR(data, model, beta0=np.array([1.]))
+ sol1 = odr1.run()
+ odr2 = ODR(data, model, beta0=np.array([1.]), ifixx=fix)
+ sol2 = odr2.run()
+ assert_equal(sol1.beta, sol2.beta)
+
+ # verify bugfix for #11800 in #11802
+ def test_ticket_11800(self):
+ # parameters
+ beta_true = np.array([1.0, 2.3, 1.1, -1.0, 1.3, 0.5])
+ nr_measurements = 10
+
+ std_dev_x = 0.01
+ x_error = np.array([[0.00063445, 0.00515731, 0.00162719, 0.01022866,
+ -0.01624845, 0.00482652, 0.00275988, -0.00714734, -0.00929201, -0.00687301],
+ [-0.00831623, -0.00821211, -0.00203459, 0.00938266, -0.00701829,
+ 0.0032169, 0.00259194, -0.00581017, -0.0030283, 0.01014164]])
+
+ std_dev_y = 0.05
+ y_error = np.array([[0.05275304, 0.04519563, -0.07524086, 0.03575642,
+ 0.04745194, 0.03806645, 0.07061601, -0.00753604, -0.02592543, -0.02394929],
+ [0.03632366, 0.06642266, 0.08373122, 0.03988822, -0.0092536,
+ -0.03750469, -0.03198903, 0.01642066, 0.01293648, -0.05627085]])
+
+ beta_solution = np.array([
+ 2.62920235756665876536e+00, -1.26608484996299608838e+02,
+ 1.29703572775403074502e+02, -1.88560985401185465804e+00,
+ 7.83834160771274923718e+01, -7.64124076838087091801e+01])
+
+ # model's function and Jacobians
+ def func(beta, x):
+ y0 = beta[0] + beta[1] * x[0, :] + beta[2] * x[1, :]
+ y1 = beta[3] + beta[4] * x[0, :] + beta[5] * x[1, :]
+
+ return np.vstack((y0, y1))
+
+ def df_dbeta_odr(beta, x):
+ nr_meas = np.shape(x)[1]
+ zeros = np.zeros(nr_meas)
+ ones = np.ones(nr_meas)
+
+ dy0 = np.array([ones, x[0, :], x[1, :], zeros, zeros, zeros])
+ dy1 = np.array([zeros, zeros, zeros, ones, x[0, :], x[1, :]])
+
+ return np.stack((dy0, dy1))
+
+ def df_dx_odr(beta, x):
+ nr_meas = np.shape(x)[1]
+ ones = np.ones(nr_meas)
+
+ dy0 = np.array([beta[1] * ones, beta[2] * ones])
+ dy1 = np.array([beta[4] * ones, beta[5] * ones])
+ return np.stack((dy0, dy1))
+
+ # do measurements with errors in independent and dependent variables
+ x0_true = np.linspace(1, 10, nr_measurements)
+ x1_true = np.linspace(1, 10, nr_measurements)
+ x_true = np.array([x0_true, x1_true])
+
+ y_true = func(beta_true, x_true)
+
+ x_meas = x_true + x_error
+ y_meas = y_true + y_error
+
+ # estimate model's parameters
+ model_f = Model(func, fjacb=df_dbeta_odr, fjacd=df_dx_odr)
+
+ data = RealData(x_meas, y_meas, sx=std_dev_x, sy=std_dev_y)
+
+ odr_obj = ODR(data, model_f, beta0=0.9 * beta_true, maxit=100)
+ #odr_obj.set_iprint(init=2, iter=0, iter_step=1, final=1)
+ odr_obj.set_job(deriv=3)
+
+ odr_out = odr_obj.run()
+
+ # check results
+ assert_equal(odr_out.info, 1)
+ assert_array_almost_equal(odr_out.beta, beta_solution)
+
+ def test_multilinear_model(self):
+ x = np.linspace(0.0, 5.0)
+ y = 10.0 + 5.0 * x
+ data = Data(x, y)
+ odr_obj = ODR(data, multilinear)
+ output = odr_obj.run()
+ assert_array_almost_equal(output.beta, [10.0, 5.0])
+
+ def test_exponential_model(self):
+ x = np.linspace(0.0, 5.0)
+ y = -10.0 + np.exp(0.5*x)
+ data = Data(x, y)
+ odr_obj = ODR(data, exponential)
+ output = odr_obj.run()
+ assert_array_almost_equal(output.beta, [-10.0, 0.5])
+
+ def test_polynomial_model(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 + 2.0 * x + 3.0 * x ** 2 + 4.0 * x ** 3
+ poly_model = polynomial(3)
+ data = Data(x, y)
+ odr_obj = ODR(data, poly_model)
+ output = odr_obj.run()
+ assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0, 4.0])
+
+ def test_unilinear_model(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x + 2.0
+ data = Data(x, y)
+ odr_obj = ODR(data, unilinear)
+ output = odr_obj.run()
+ assert_array_almost_equal(output.beta, [1.0, 2.0])
+
+ def test_quadratic_model(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x ** 2 + 2.0 * x + 3.0
+ data = Data(x, y)
+ odr_obj = ODR(data, quadratic)
+ output = odr_obj.run()
+ assert_array_almost_equal(output.beta, [1.0, 2.0, 3.0])
+
+ def test_work_ind(self):
+
+ def func(par, x):
+ b0, b1 = par
+ return b0 + b1 * x
+
+ # generate some data
+ n_data = 4
+ x = np.arange(n_data)
+ y = np.where(x % 2, x + 0.1, x - 0.1)
+ x_err = np.full(n_data, 0.1)
+ y_err = np.full(n_data, 0.1)
+
+ # do the fitting
+ linear_model = Model(func)
+ real_data = RealData(x, y, sx=x_err, sy=y_err)
+ odr_obj = ODR(real_data, linear_model, beta0=[0.4, 0.4])
+ odr_obj.set_job(fit_type=0)
+ out = odr_obj.run()
+
+ sd_ind = out.work_ind['sd']
+ assert_array_almost_equal(out.sd_beta,
+ out.work[sd_ind:sd_ind + len(out.sd_beta)])
+
+ @pytest.mark.skipif(True, reason="Fortran I/O prone to crashing so better "
+ "not to run this test, see gh-13127")
+ def test_output_file_overwrite(self):
+ """
+ Verify fix for gh-1892
+ """
+ def func(b, x):
+ return b[0] + b[1] * x
+
+ p = Model(func)
+ data = Data(np.arange(10), 12 * np.arange(10))
+ tmp_dir = tempfile.mkdtemp()
+ error_file_path = os.path.join(tmp_dir, "error.dat")
+ report_file_path = os.path.join(tmp_dir, "report.dat")
+ try:
+ ODR(data, p, beta0=[0.1, 13], errfile=error_file_path,
+ rptfile=report_file_path).run()
+ ODR(data, p, beta0=[0.1, 13], errfile=error_file_path,
+ rptfile=report_file_path, overwrite=True).run()
+ finally:
+ # remove output files for clean up
+ shutil.rmtree(tmp_dir)
+
+ def test_odr_model_default_meta(self):
+ def func(b, x):
+ return b[0] + b[1] * x
+
+ p = Model(func)
+ p.set_meta(name='Sample Model Meta', ref='ODRPACK')
+ assert_equal(p.meta, {'name': 'Sample Model Meta', 'ref': 'ODRPACK'})
+
+ def test_work_array_del_init(self):
+ """
+ Verify fix for gh-18739 where del_init=1 fails.
+ """
+ def func(b, x):
+ return b[0] + b[1] * x
+
+ # generate some data
+ n_data = 4
+ x = np.arange(n_data)
+ y = np.where(x % 2, x + 0.1, x - 0.1)
+ x_err = np.full(n_data, 0.1)
+ y_err = np.full(n_data, 0.1)
+
+ linear_model = Model(func)
+ # Try various shapes of the `we` array from various `sy` and `covy`
+ rd0 = RealData(x, y, sx=x_err, sy=y_err)
+ rd1 = RealData(x, y, sx=x_err, sy=0.1)
+ rd2 = RealData(x, y, sx=x_err, sy=[0.1])
+ rd3 = RealData(x, y, sx=x_err, sy=np.full((1, n_data), 0.1))
+ rd4 = RealData(x, y, sx=x_err, covy=[[0.01]])
+ rd5 = RealData(x, y, sx=x_err, covy=np.full((1, 1, n_data), 0.01))
+ for rd in [rd0, rd1, rd2, rd3, rd4, rd5]:
+ odr_obj = ODR(rd, linear_model, beta0=[0.4, 0.4],
+ delta0=np.full(n_data, -0.1))
+ odr_obj.set_job(fit_type=0, del_init=1)
+ # Just make sure that it runs without raising an exception.
+ odr_obj.run()
+
+ def test_pickling_data(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x + 2.0
+ data = Data(x, y)
+
+ obj_pickle = pickle.dumps(data)
+ del data
+ pickle.loads(obj_pickle)
+
+ def test_pickling_real_data(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x + 2.0
+ data = RealData(x, y)
+
+ obj_pickle = pickle.dumps(data)
+ del data
+ pickle.loads(obj_pickle)
+
+ def test_pickling_model(self):
+ obj_pickle = pickle.dumps(unilinear)
+ pickle.loads(obj_pickle)
+
+ def test_pickling_odr(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x + 2.0
+ odr_obj = ODR(Data(x, y), unilinear)
+
+ obj_pickle = pickle.dumps(odr_obj)
+ del odr_obj
+ pickle.loads(obj_pickle)
+
+ def test_pickling_output(self):
+ x = np.linspace(0.0, 5.0)
+ y = 1.0 * x + 2.0
+ output = ODR(Data(x, y), unilinear).run
+
+ obj_pickle = pickle.dumps(output)
+ del output
+ pickle.loads(obj_pickle)
+
+ def test_explicit_model_with_implicit_job(self):
+ """
+ Verify fix for gh-23763 that ODR doesn't segfault
+ """
+ x = np.linspace(0, 10, 10)
+ y = 2.0 + 3.0 * x
+
+ data = Data(x, y)
+ model = unilinear # this is an explicit model
+
+ # job=1 is implicit, should raise on explicit model
+ with assert_raises(OdrError):
+ odr = ODR(data, model, job=1)
+ odr.run()
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.___init__.pxd b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.___init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.___init__.pxd differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__basinhopping.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__basinhopping.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__basinhopping.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__bglu_dense.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__bglu_dense.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__bglu_dense.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__bracket.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__bracket.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__bracket.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__chandrupatla.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__chandrupatla.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__chandrupatla.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__cobyla_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__cobyla_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__cobyla_py.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__cobyqa_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__cobyqa_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__cobyqa_py.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__constraints.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__constraints.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__dcsrch.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__dcsrch.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__dcsrch.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__differentiable_functions.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__differentiable_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__differentiable_functions.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__differentialevolution.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__differentialevolution.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__differentialevolution.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__direct.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__direct.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__direct.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__direct_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__direct_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__direct_py.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__dual_annealing.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__dual_annealing.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__dual_annealing.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__elementwise.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__elementwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__elementwise.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__group_columns.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__group_columns.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__group_columns.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__hessian_update_strategy.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__hessian_update_strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__hessian_update_strategy.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__highspy b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__highspy
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__highspy differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__isotonic.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__isotonic.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__isotonic.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lbfgsb.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lbfgsb.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lbfgsb.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lbfgsb_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lbfgsb_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lbfgsb_py.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linesearch.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linesearch.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_doc.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_doc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_doc.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_highs.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_highs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_highs.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_ip.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_ip.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_ip.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_rs.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_rs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_rs.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_simplex.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_simplex.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_simplex.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_util.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__linprog_util.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lsap.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lsap.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lsap.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lsq b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lsq
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__lsq differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__milp.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__milp.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__milp.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__minimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__minimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__minimize.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__minpack.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__minpack.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__minpack.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__minpack_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__minpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__minpack_py.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__moduleTNC.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__moduleTNC.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__moduleTNC.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__nnls.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__nnls.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__nnls.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__nonlin.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__nonlin.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__numdiff.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__numdiff.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__numdiff.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__optimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__optimize.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__pava_pybind.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__pava_pybind.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__pava_pybind.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__qap.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__qap.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__qap.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__remove_redundancy.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__remove_redundancy.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__remove_redundancy.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__root.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__root.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__root.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__root_scalar.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__root_scalar.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__root_scalar.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__shgo.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__shgo.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__shgo.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__shgo_lib b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__shgo_lib
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__shgo_lib differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__slsqp_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__slsqp_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__slsqp_py.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__slsqplib.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__slsqplib.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__slsqplib.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__spectral.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__spectral.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__tnc.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__tnc.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trlib b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trlib
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trlib differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_constr b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_constr
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_constr differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_dogleg.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_dogleg.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_dogleg.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_exact.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_exact.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_exact.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_krylov.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_krylov.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_krylov.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_ncg.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_ncg.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__trustregion_ncg.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__tstutils.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__tstutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__tstutils.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__zeros.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__zeros.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__zeros.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__zeros_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__zeros_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/.__zeros_py.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._cobyla.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._cobyla.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._cobyla.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._cython_optimize b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._cython_optimize
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._cython_optimize differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._cython_optimize.pxd b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._cython_optimize.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._cython_optimize.pxd differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._elementwise.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._elementwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._elementwise.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._lbfgsb.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._lbfgsb.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._lbfgsb.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._linesearch.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._linesearch.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._minpack.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._minpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._minpack.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._minpack2.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._minpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._minpack2.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._moduleTNC.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._moduleTNC.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._moduleTNC.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._nonlin.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._nonlin.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._optimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._optimize.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._slsqp.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._slsqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._slsqp.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._tests b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._tests
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._tests differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._tnc.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._tnc.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._zeros.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._zeros.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/._zeros.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/__init__.pxd b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/__init__.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..2402eeb020d34ad8b82e287e32545423911ff66c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/__init__.pxd
@@ -0,0 +1 @@
+from .optimize cimport cython_optimize
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..fce4cecd22b165f9975160fe7c1ed718ed358853
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/__init__.py
@@ -0,0 +1,460 @@
+"""
+=====================================================
+Optimization and root finding (:mod:`scipy.optimize`)
+=====================================================
+
+.. currentmodule:: scipy.optimize
+
+.. toctree::
+ :hidden:
+
+ optimize.cython_optimize
+
+SciPy ``optimize`` provides functions for minimizing (or maximizing)
+objective functions, possibly subject to constraints. It includes
+solvers for nonlinear problems (with support for both local and global
+optimization algorithms), linear programming, constrained
+and nonlinear least-squares, root finding, and curve fitting.
+
+Common functions and objects, shared across different solvers, are:
+
+.. autosummary::
+ :toctree: generated/
+
+ show_options - Show specific options optimization solvers.
+ OptimizeResult - The optimization result returned by some optimizers.
+ OptimizeWarning - The optimization encountered problems.
+
+
+Optimization
+============
+
+Scalar functions optimization
+-----------------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ minimize_scalar - Interface for minimizers of univariate functions
+
+The `minimize_scalar` function supports the following methods:
+
+.. toctree::
+
+ optimize.minimize_scalar-brent
+ optimize.minimize_scalar-bounded
+ optimize.minimize_scalar-golden
+
+Local (multivariate) optimization
+---------------------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ minimize - Interface for minimizers of multivariate functions.
+
+The `minimize` function supports the following methods:
+
+.. toctree::
+
+ optimize.minimize-neldermead
+ optimize.minimize-powell
+ optimize.minimize-cg
+ optimize.minimize-bfgs
+ optimize.minimize-newtoncg
+ optimize.minimize-lbfgsb
+ optimize.minimize-tnc
+ optimize.minimize-cobyla
+ optimize.minimize-cobyqa
+ optimize.minimize-slsqp
+ optimize.minimize-trustconstr
+ optimize.minimize-dogleg
+ optimize.minimize-trustncg
+ optimize.minimize-trustkrylov
+ optimize.minimize-trustexact
+
+Constraints are passed to `minimize` function as a single object or
+as a list of objects from the following classes:
+
+.. autosummary::
+ :toctree: generated/
+
+ NonlinearConstraint - Class defining general nonlinear constraints.
+ LinearConstraint - Class defining general linear constraints.
+
+Simple bound constraints are handled separately and there is a special class
+for them:
+
+.. autosummary::
+ :toctree: generated/
+
+ Bounds - Bound constraints.
+
+Quasi-Newton strategies implementing `HessianUpdateStrategy`
+interface can be used to approximate the Hessian in `minimize`
+function (available only for the 'trust-constr' method). Available
+quasi-Newton methods implementing this interface are:
+
+.. autosummary::
+ :toctree: generated/
+
+ BFGS - Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy.
+ SR1 - Symmetric-rank-1 Hessian update strategy.
+
+.. _global_optimization:
+
+Global optimization
+-------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ basinhopping - Basinhopping stochastic optimizer.
+ brute - Brute force searching optimizer.
+ differential_evolution - Stochastic optimizer using differential evolution.
+
+ shgo - Simplicial homology global optimizer.
+ dual_annealing - Dual annealing stochastic optimizer.
+ direct - DIRECT (Dividing Rectangles) optimizer.
+
+Least-squares and curve fitting
+===============================
+
+Nonlinear least-squares
+-----------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ least_squares - Solve a nonlinear least-squares problem with bounds on the variables.
+
+Linear least-squares
+--------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ nnls - Linear least-squares problem with non-negativity constraint.
+ lsq_linear - Linear least-squares problem with bound constraints.
+ isotonic_regression - Least squares problem of isotonic regression via PAVA.
+
+Curve fitting
+-------------
+
+.. autosummary::
+ :toctree: generated/
+
+ curve_fit -- Fit curve to a set of points.
+
+Root finding
+============
+
+Scalar functions
+----------------
+.. autosummary::
+ :toctree: generated/
+
+ root_scalar - Unified interface for nonlinear solvers of scalar functions.
+ brentq - quadratic interpolation Brent method.
+ brenth - Brent method, modified by Harris with hyperbolic extrapolation.
+ ridder - Ridder's method.
+ bisect - Bisection method.
+ newton - Newton's method (also Secant and Halley's methods).
+ toms748 - Alefeld, Potra & Shi Algorithm 748.
+ RootResults - The root finding result returned by some root finders.
+
+The `root_scalar` function supports the following methods:
+
+.. toctree::
+
+ optimize.root_scalar-brentq
+ optimize.root_scalar-brenth
+ optimize.root_scalar-bisect
+ optimize.root_scalar-ridder
+ optimize.root_scalar-newton
+ optimize.root_scalar-toms748
+ optimize.root_scalar-secant
+ optimize.root_scalar-halley
+
+
+
+The table below lists situations and appropriate methods, along with
+*asymptotic* convergence rates per iteration (and per function evaluation)
+for successful convergence to a simple root(*).
+Bisection is the slowest of them all, adding one bit of accuracy for each
+function evaluation, but is guaranteed to converge.
+The other bracketing methods all (eventually) increase the number of accurate
+bits by about 50% for every function evaluation.
+The derivative-based methods, all built on `newton`, can converge quite quickly
+if the initial value is close to the root. They can also be applied to
+functions defined on (a subset of) the complex plane.
+
++-------------+----------+----------+-----------+-------------+-------------+----------------+
+| Domain of f | Bracket? | Derivatives? | Solvers | Convergence |
++ + +----------+-----------+ +-------------+----------------+
+| | | `fprime` | `fprime2` | | Guaranteed? | Rate(s)(*) |
++=============+==========+==========+===========+=============+=============+================+
+| `R` | Yes | N/A | N/A | - bisection | - Yes | - 1 "Linear" |
+| | | | | - brentq | - Yes | - >=1, <= 1.62 |
+| | | | | - brenth | - Yes | - >=1, <= 1.62 |
+| | | | | - ridder | - Yes | - 2.0 (1.41) |
+| | | | | - toms748 | - Yes | - 2.7 (1.65) |
++-------------+----------+----------+-----------+-------------+-------------+----------------+
+| `R` or `C` | No | No | No | secant | No | 1.62 (1.62) |
++-------------+----------+----------+-----------+-------------+-------------+----------------+
+| `R` or `C` | No | Yes | No | newton | No | 2.00 (1.41) |
++-------------+----------+----------+-----------+-------------+-------------+----------------+
+| `R` or `C` | No | Yes | Yes | halley | No | 3.00 (1.44) |
++-------------+----------+----------+-----------+-------------+-------------+----------------+
+
+.. seealso::
+
+ `scipy.optimize.cython_optimize` -- Typed Cython versions of root finding functions
+
+Fixed point finding:
+
+.. autosummary::
+ :toctree: generated/
+
+ fixed_point - Single-variable fixed-point solver.
+
+Multidimensional
+----------------
+
+.. autosummary::
+ :toctree: generated/
+
+ root - Unified interface for nonlinear solvers of multivariate functions.
+
+The `root` function supports the following methods:
+
+.. toctree::
+
+ optimize.root-hybr
+ optimize.root-lm
+ optimize.root-broyden1
+ optimize.root-broyden2
+ optimize.root-anderson
+ optimize.root-linearmixing
+ optimize.root-diagbroyden
+ optimize.root-excitingmixing
+ optimize.root-krylov
+ optimize.root-dfsane
+
+Elementwise Minimization and Root Finding
+=========================================
+
+.. toctree::
+ :maxdepth: 3
+
+ optimize.elementwise
+
+Linear programming / MILP
+=========================
+
+.. autosummary::
+ :toctree: generated/
+
+ milp -- Mixed integer linear programming.
+ linprog -- Unified interface for minimizers of linear programming problems.
+
+The `linprog` function supports the following methods:
+
+.. toctree::
+
+ optimize.linprog-simplex
+ optimize.linprog-interior-point
+ optimize.linprog-revised_simplex
+ optimize.linprog-highs-ipm
+ optimize.linprog-highs-ds
+ optimize.linprog-highs
+
+The simplex, interior-point, and revised simplex methods support callback
+functions, such as:
+
+.. autosummary::
+ :toctree: generated/
+
+ linprog_verbose_callback -- Sample callback function for linprog (simplex).
+
+Assignment problems
+===================
+
+.. autosummary::
+ :toctree: generated/
+
+ linear_sum_assignment -- Solves the linear-sum assignment problem.
+ quadratic_assignment -- Solves the quadratic assignment problem.
+
+The `quadratic_assignment` function supports the following methods:
+
+.. toctree::
+
+ optimize.qap-faq
+ optimize.qap-2opt
+
+Utilities
+=========
+
+Finite-difference approximation
+-------------------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ approx_fprime - Approximate the gradient of a scalar function.
+ check_grad - Check the supplied derivative using finite differences.
+
+
+Line search
+-----------
+
+.. autosummary::
+ :toctree: generated/
+
+ bracket - Bracket a minimum, given two starting points.
+ line_search - Return a step that satisfies the strong Wolfe conditions.
+
+Hessian approximation
+---------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ LbfgsInvHessProduct - Linear operator for L-BFGS approximate inverse Hessian.
+ HessianUpdateStrategy - Interface for implementing Hessian update strategies
+
+Benchmark problems
+------------------
+
+.. autosummary::
+ :toctree: generated/
+
+ rosen - The Rosenbrock function.
+ rosen_der - The derivative of the Rosenbrock function.
+ rosen_hess - The Hessian matrix of the Rosenbrock function.
+ rosen_hess_prod - Product of the Rosenbrock Hessian with a vector.
+
+Legacy functions
+================
+
+The functions below are not recommended for use in new scripts;
+all of these methods are accessible via a newer, more consistent
+interfaces, provided by the interfaces above.
+
+Optimization
+------------
+
+General-purpose multivariate methods:
+
+.. autosummary::
+ :toctree: generated/
+
+ fmin - Nelder-Mead Simplex algorithm.
+ fmin_powell - Powell's (modified) conjugate direction method.
+ fmin_cg - Non-linear (Polak-Ribiere) conjugate gradient algorithm.
+ fmin_bfgs - Quasi-Newton method (Broydon-Fletcher-Goldfarb-Shanno).
+ fmin_ncg - Line-search Newton Conjugate Gradient.
+
+Constrained multivariate methods:
+
+.. autosummary::
+ :toctree: generated/
+
+ fmin_l_bfgs_b - Zhu, Byrd, and Nocedal's constrained optimizer.
+ fmin_tnc - Truncated Newton code.
+ fmin_cobyla - Constrained optimization by linear approximation.
+ fmin_slsqp - Minimization using sequential least-squares programming.
+
+Univariate (scalar) minimization methods:
+
+.. autosummary::
+ :toctree: generated/
+
+ fminbound - Bounded minimization of a scalar function.
+ brent - 1-D function minimization using Brent method.
+ golden - 1-D function minimization using Golden Section method.
+
+Least-squares
+-------------
+
+.. autosummary::
+ :toctree: generated/
+
+ leastsq - Minimize the sum of squares of M equations in N unknowns.
+
+Root finding
+------------
+
+General nonlinear solvers:
+
+.. autosummary::
+ :toctree: generated/
+
+ fsolve - Non-linear multivariable equation solver.
+ broyden1 - Broyden's first method.
+ broyden2 - Broyden's second method.
+ NoConvergence - Exception raised when nonlinear solver does not converge.
+
+Large-scale nonlinear solvers:
+
+.. autosummary::
+ :toctree: generated/
+
+ newton_krylov
+ anderson
+
+ BroydenFirst
+ InverseJacobian
+ KrylovJacobian
+
+Simple iteration solvers:
+
+.. autosummary::
+ :toctree: generated/
+
+ excitingmixing
+ linearmixing
+ diagbroyden
+
+""" # noqa: E501
+
+from ._optimize import *
+from ._minimize import *
+from ._root import *
+from ._root_scalar import *
+from ._minpack_py import *
+from ._zeros_py import *
+from ._lbfgsb_py import fmin_l_bfgs_b, LbfgsInvHessProduct
+from ._tnc import fmin_tnc
+from ._cobyla_py import fmin_cobyla
+from ._nonlin import *
+from ._slsqp_py import fmin_slsqp
+from ._nnls import nnls
+from ._basinhopping import basinhopping
+from ._linprog import linprog, linprog_verbose_callback
+from ._lsap import linear_sum_assignment
+from ._differentialevolution import differential_evolution
+from ._lsq import least_squares, lsq_linear
+from ._isotonic import isotonic_regression
+from ._constraints import (NonlinearConstraint,
+ LinearConstraint,
+ Bounds)
+from ._hessian_update_strategy import HessianUpdateStrategy, BFGS, SR1
+from ._shgo import shgo
+from ._dual_annealing import dual_annealing
+from ._qap import quadratic_assignment
+from ._direct_py import direct
+from ._milp import milp
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import (
+ cobyla, lbfgsb, linesearch, minpack, minpack2, moduleTNC, nonlin, optimize,
+ slsqp, tnc, zeros
+)
+
+__all__ = [s for s in dir() if not s.startswith('_')]
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_basinhopping.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_basinhopping.py
new file mode 100644
index 0000000000000000000000000000000000000000..3108e1cb0a97dedfe8ec397e0944f57a7e30a820
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_basinhopping.py
@@ -0,0 +1,742 @@
+"""
+basinhopping: The basinhopping global optimization algorithm
+"""
+import numpy as np
+import math
+import inspect
+import scipy.optimize
+from scipy._lib._util import (check_random_state, _transition_to_rng,
+ wrapped_inspect_signature)
+
+__all__ = ['basinhopping']
+
+
+_params = (inspect.Parameter('res_new', kind=inspect.Parameter.KEYWORD_ONLY),
+ inspect.Parameter('res_old', kind=inspect.Parameter.KEYWORD_ONLY))
+_new_accept_test_signature = inspect.Signature(parameters=_params)
+
+
+class Storage:
+ """
+ Class used to store the lowest energy structure
+ """
+ def __init__(self, minres):
+ self._add(minres)
+
+ def _add(self, minres):
+ self.minres = minres
+ self.minres.x = np.copy(minres.x)
+
+ def update(self, minres):
+ if minres.success and (minres.fun < self.minres.fun
+ or not self.minres.success):
+ self._add(minres)
+ return True
+ else:
+ return False
+
+ def get_lowest(self):
+ return self.minres
+
+
+class BasinHoppingRunner:
+ """This class implements the core of the basinhopping algorithm.
+
+ x0 : ndarray
+ The starting coordinates.
+ minimizer : callable
+ The local minimizer, with signature ``result = minimizer(x)``.
+ The return value is an `optimize.OptimizeResult` object.
+ step_taking : callable
+ This function displaces the coordinates randomly. Signature should
+ be ``x_new = step_taking(x)``. Note that `x` may be modified in-place.
+ accept_tests : list of callables
+ Each test is passed the kwargs `f_new`, `x_new`, `f_old` and
+ `x_old`. These tests will be used to judge whether or not to accept
+ the step. The acceptable return values are True, False, or ``"force
+ accept"``. If any of the tests return False then the step is rejected.
+ If ``"force accept"``, then this will override any other tests in
+ order to accept the step. This can be used, for example, to forcefully
+ escape from a local minimum that ``basinhopping`` is trapped in.
+ disp : bool, optional
+ Display status messages.
+
+ """
+ def __init__(self, x0, minimizer, step_taking, accept_tests, disp=False):
+ self.x = np.copy(x0)
+ self.minimizer = minimizer
+ self.step_taking = step_taking
+ self.accept_tests = accept_tests
+ self.disp = disp
+
+ self.nstep = 0
+
+ # initialize return object
+ self.res = scipy.optimize.OptimizeResult()
+ self.res.minimization_failures = 0
+
+ # do initial minimization
+ minres = minimizer(self.x)
+ if not minres.success:
+ self.res.minimization_failures += 1
+ if self.disp:
+ print("warning: basinhopping: local minimization failure")
+ self.x = np.copy(minres.x)
+ self.energy = minres.fun
+ self.incumbent_minres = minres # best minimize result found so far
+ if self.disp:
+ print(f"basinhopping step {self.nstep}: f {self.energy:g}")
+
+ # initialize storage class
+ self.storage = Storage(minres)
+
+ if hasattr(minres, "nfev"):
+ self.res.nfev = minres.nfev
+ if hasattr(minres, "njev"):
+ self.res.njev = minres.njev
+ if hasattr(minres, "nhev"):
+ self.res.nhev = minres.nhev
+
+ def _monte_carlo_step(self):
+ """Do one Monte Carlo iteration
+
+ Randomly displace the coordinates, minimize, and decide whether
+ or not to accept the new coordinates.
+ """
+ # Take a random step. Make a copy of x because the step_taking
+ # algorithm might change x in place
+ x_after_step = np.copy(self.x)
+ x_after_step = self.step_taking(x_after_step)
+
+ # do a local minimization
+ minres = self.minimizer(x_after_step)
+ x_after_quench = minres.x
+ energy_after_quench = minres.fun
+ if not minres.success:
+ self.res.minimization_failures += 1
+ if self.disp:
+ print("warning: basinhopping: local minimization failure")
+ if hasattr(minres, "nfev"):
+ self.res.nfev += minres.nfev
+ if hasattr(minres, "njev"):
+ self.res.njev += minres.njev
+ if hasattr(minres, "nhev"):
+ self.res.nhev += minres.nhev
+
+ # accept the move based on self.accept_tests. If any test is False,
+ # then reject the step. If any test returns the special string
+ # 'force accept', then accept the step regardless. This can be used
+ # to forcefully escape from a local minimum if normal basin hopping
+ # steps are not sufficient.
+ accept = True
+ for test in self.accept_tests:
+ if wrapped_inspect_signature(test) == _new_accept_test_signature:
+ testres = test(res_new=minres, res_old=self.incumbent_minres)
+ else:
+ testres = test(f_new=energy_after_quench, x_new=x_after_quench,
+ f_old=self.energy, x_old=self.x)
+
+ if testres == 'force accept':
+ accept = True
+ break
+ elif testres is None:
+ raise ValueError("accept_tests must return True, False, or "
+ "'force accept'")
+ elif not testres:
+ accept = False
+
+ # Report the result of the acceptance test to the take step class.
+ # This is for adaptive step taking
+ if hasattr(self.step_taking, "report"):
+ self.step_taking.report(accept, f_new=energy_after_quench,
+ x_new=x_after_quench, f_old=self.energy,
+ x_old=self.x)
+
+ return accept, minres
+
+ def one_cycle(self):
+ """Do one cycle of the basinhopping algorithm
+ """
+ self.nstep += 1
+ new_global_min = False
+
+ accept, minres = self._monte_carlo_step()
+
+ if accept:
+ self.energy = minres.fun
+ self.x = np.copy(minres.x)
+ self.incumbent_minres = minres # best minimize result found so far
+ new_global_min = self.storage.update(minres)
+
+ # print some information
+ if self.disp:
+ self.print_report(minres.fun, accept)
+ if new_global_min:
+ print(
+ f"found new global minimum on step {self.nstep} with "
+ f"function value {self.energy:g}"
+ )
+
+ # save some variables as BasinHoppingRunner attributes
+ self.xtrial = minres.x
+ self.energy_trial = minres.fun
+ self.accept = accept
+
+ return new_global_min
+
+ def print_report(self, energy_trial, accept):
+ """print a status update"""
+ minres = self.storage.get_lowest()
+ print(
+ f"basinhopping step {self.nstep}: f {self.energy:g} "
+ f"trial_f {energy_trial:g} accepted {accept} "
+ f"lowest_f {minres.fun:g}"
+ )
+
+
+class AdaptiveStepsize:
+ """
+ Class to implement adaptive stepsize.
+
+ This class wraps the step taking class and modifies the stepsize to
+ ensure the true acceptance rate is as close as possible to the target.
+
+ Parameters
+ ----------
+ takestep : callable
+ The step taking routine. Must contain modifiable attribute
+ takestep.stepsize
+ accept_rate : float, optional
+ The target step acceptance rate
+ interval : int, optional
+ Interval for how often to update the stepsize
+ factor : float, optional
+ The step size is multiplied or divided by this factor upon each
+ update.
+ verbose : bool, optional
+ Print information about each update
+
+ """
+ def __init__(self, takestep, accept_rate=0.5, interval=50, factor=0.9,
+ verbose=True):
+ self.takestep = takestep
+ self.target_accept_rate = accept_rate
+ self.interval = interval
+ self.factor = factor
+ self.verbose = verbose
+
+ self.nstep = 0
+ self.nstep_tot = 0
+ self.naccept = 0
+
+ def __call__(self, x):
+ return self.take_step(x)
+
+ def _adjust_step_size(self):
+ old_stepsize = self.takestep.stepsize
+ accept_rate = float(self.naccept) / self.nstep
+ if accept_rate > self.target_accept_rate:
+ # We're accepting too many steps. This generally means we're
+ # trapped in a basin. Take bigger steps.
+ self.takestep.stepsize /= self.factor
+ else:
+ # We're not accepting enough steps. Take smaller steps.
+ self.takestep.stepsize *= self.factor
+ if self.verbose:
+ print(f"adaptive stepsize: acceptance rate {accept_rate:f} target "
+ f"{self.target_accept_rate:f} new stepsize "
+ f"{self.takestep.stepsize:g} old stepsize {old_stepsize:g}")
+
+ def take_step(self, x):
+ self.nstep += 1
+ self.nstep_tot += 1
+ if self.nstep % self.interval == 0:
+ self._adjust_step_size()
+ return self.takestep(x)
+
+ def report(self, accept, **kwargs):
+ "called by basinhopping to report the result of the step"
+ if accept:
+ self.naccept += 1
+
+
+class RandomDisplacement:
+ """Add a random displacement of maximum size `stepsize` to each coordinate.
+
+ Calling this updates `x` in-place.
+
+ Parameters
+ ----------
+ stepsize : float, optional
+ Maximum stepsize in any dimension
+ rng : {None, int, `numpy.random.Generator`}, optional
+ Random number generator
+ """
+
+ def __init__(self, stepsize=0.5, rng=None):
+ self.stepsize = stepsize
+ self.rng = check_random_state(rng)
+
+ def __call__(self, x):
+ x += self.rng.uniform(-self.stepsize, self.stepsize,
+ np.shape(x))
+ return x
+
+
+class MinimizerWrapper:
+ """
+ wrap a minimizer function as a minimizer class
+ """
+ def __init__(self, minimizer, func=None, **kwargs):
+ self.minimizer = minimizer
+ self.func = func
+ self.kwargs = kwargs
+
+ def __call__(self, x0):
+ if self.func is None:
+ return self.minimizer(x0, **self.kwargs)
+ else:
+ return self.minimizer(self.func, x0, **self.kwargs)
+
+
+class Metropolis:
+ """Metropolis acceptance criterion.
+
+ Parameters
+ ----------
+ T : float
+ The "temperature" parameter for the accept or reject criterion.
+ rng : {None, int, `numpy.random.Generator`}, optional
+ Random number generator used for acceptance test.
+
+ """
+
+ def __init__(self, T, rng=None):
+ # Avoid ZeroDivisionError since "MBH can be regarded as a special case
+ # of the BH framework with the Metropolis criterion, where temperature
+ # T = 0." (Reject all steps that increase energy.)
+ self.beta = 1.0 / T if T != 0 else float('inf')
+ self.rng = check_random_state(rng)
+
+ def accept_reject(self, res_new, res_old):
+ """
+ Assuming the local search underlying res_new was successful:
+ If new energy is lower than old, it will always be accepted.
+ If new is higher than old, there is a chance it will be accepted,
+ less likely for larger differences.
+ """
+ with np.errstate(invalid='ignore'):
+ # The energy values being fed to Metropolis are 1-length arrays, and if
+ # they are equal, their difference is 0, which gets multiplied by beta,
+ # which is inf, and array([0]) * float('inf') causes
+ #
+ # RuntimeWarning: invalid value encountered in multiply
+ #
+ # Ignore this warning so when the algorithm is on a flat plane, it always
+ # accepts the step, to try to move off the plane.
+ prod = -(res_new.fun - res_old.fun) * self.beta
+ w = math.exp(min(0, prod))
+
+ rand = self.rng.uniform()
+ return w >= rand and (res_new.success or not res_old.success)
+
+ def __call__(self, *, res_new, res_old):
+ """
+ f_new and f_old are mandatory in kwargs
+ """
+ return bool(self.accept_reject(res_new, res_old))
+
+
+@_transition_to_rng("seed", position_num=12, replace_doc=True)
+def basinhopping(func, x0, niter=100, T=1.0, stepsize=0.5,
+ minimizer_kwargs=None, take_step=None, accept_test=None,
+ callback=None, interval=50, disp=False, niter_success=None,
+ rng=None, *, target_accept_rate=0.5, stepwise_factor=0.9):
+ """Find the global minimum of a function using the basin-hopping algorithm.
+
+ Basin-hopping is a two-phase method that combines a global stepping
+ algorithm with local minimization at each step. Designed to mimic
+ the natural process of energy minimization of clusters of atoms, it works
+ well for similar problems with "funnel-like, but rugged" energy landscapes
+ [5]_.
+
+ As the step-taking, step acceptance, and minimization methods are all
+ customizable, this function can also be used to implement other two-phase
+ methods.
+
+ Parameters
+ ----------
+ func : callable ``f(x, *args)``
+ Function to be optimized. ``args`` can be passed as an optional item
+ in the dict `minimizer_kwargs`
+ x0 : array_like
+ Initial guess.
+ niter : 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. ``lowest_optimization_result`` will only be updated if a
+ local minimization was successful.
+ See `OptimizeResult` for a description of other attributes.
+
+ See Also
+ --------
+ minimize :
+ The local minimization function called once for each basinhopping step.
+ `minimizer_kwargs` is passed to this routine.
+
+ Notes
+ -----
+ Basin-hopping is a stochastic algorithm which attempts to find the global
+ minimum of a smooth scalar function of one or more variables [1]_ [2]_ [3]_
+ [4]_. The algorithm in its current form was described by David Wales and
+ Jonathan Doye [2]_ http://www-wales.ch.cam.ac.uk/.
+
+ The algorithm is iterative with each cycle composed of the following
+ features
+
+ 1) random perturbation of the coordinates
+
+ 2) local minimization
+
+ 3) accept or reject the new coordinates based on the minimized function
+ value
+
+ The acceptance test used here is the Metropolis criterion of standard Monte
+ Carlo algorithms, although there are many other possibilities [3]_.
+
+ This global minimization method has been shown to be extremely efficient
+ for a wide variety of problems in physics and chemistry. It is
+ particularly useful when the function has many minima separated by large
+ barriers. See the `Cambridge Cluster Database
+ `_ for databases of molecular
+ systems that have been optimized primarily using basin-hopping. This
+ database includes minimization problems exceeding 300 degrees of freedom.
+
+ See the free software program `GMIN `_
+ for a Fortran implementation of basin-hopping. This implementation has many
+ variations of the procedure described above, including more
+ advanced step taking algorithms and alternate acceptance criterion.
+
+ For stochastic global optimization there is no way to determine if the true
+ global minimum has actually been found. Instead, as a consistency check,
+ the algorithm can be run from a number of different random starting points
+ to ensure the lowest minimum found in each example has converged to the
+ global minimum. For this reason, `basinhopping` will by default simply
+ run for the number of iterations `niter` and return the lowest minimum
+ found. It is left to the user to ensure that this is in fact the global
+ minimum.
+
+ Choosing `stepsize`: This is a crucial parameter in `basinhopping` and
+ depends on the problem being solved. The step is chosen uniformly in the
+ region from x0-stepsize to x0+stepsize, in each dimension. Ideally, it
+ should be comparable to the typical separation (in argument values) between
+ local minima of the function being optimized. `basinhopping` will, by
+ default, adjust `stepsize` to find an optimal value, but this may take
+ many iterations. You will get quicker results if you set a sensible
+ initial value for ``stepsize``.
+
+ Choosing `T`: The parameter `T` is the "temperature" used in the
+ Metropolis criterion. Basinhopping steps are always accepted if
+ ``func(xnew) < func(xold)``. Otherwise, they are accepted with
+ probability::
+
+ exp( -(func(xnew) - func(xold)) / T )
+
+ So, for best results, `T` should to be comparable to the typical
+ difference (in function values) between local minima. (The height of
+ "walls" between local minima is irrelevant.)
+
+ If `T` is 0, the algorithm becomes Monotonic Basin-Hopping, in which all
+ steps that increase energy are rejected.
+
+ .. versionadded:: 0.12.0
+
+ References
+ ----------
+ .. [1] Wales, David J. 2003, Energy Landscapes, Cambridge University Press,
+ Cambridge, UK.
+ .. [2] Wales, D J, and Doye J P K, Global Optimization by Basin-Hopping and
+ the Lowest Energy Structures of Lennard-Jones Clusters Containing up to
+ 110 Atoms. Journal of Physical Chemistry A, 1997, 101, 5111.
+ .. [3] Li, Z. and Scheraga, H. A., Monte Carlo-minimization approach to the
+ multiple-minima problem in protein folding, Proc. Natl. Acad. Sci. USA,
+ 1987, 84, 6611.
+ .. [4] Wales, D. J. and Scheraga, H. A., Global optimization of clusters,
+ crystals, and biomolecules, Science, 1999, 285, 1368.
+ .. [5] Olson, B., Hashmi, I., Molloy, K., and Shehu1, A., Basin Hopping as
+ a General and Versatile Optimization Framework for the Characterization
+ of Biological Macromolecules, Advances in Artificial Intelligence,
+ Volume 2012 (2012), Article ID 674832, :doi:`10.1155/2012/674832`
+
+ Examples
+ --------
+ The following example is a 1-D minimization problem, with many
+ local minima superimposed on a parabola.
+
+ >>> import numpy as np
+ >>> from scipy.optimize import basinhopping
+ >>> func = lambda x: np.cos(14.5 * x - 0.3) + (x + 0.2) * x
+ >>> x0 = [1.]
+
+ Basinhopping, internally, uses a local minimization algorithm. We will use
+ the parameter `minimizer_kwargs` to tell basinhopping which algorithm to
+ use and how to set up that minimizer. This parameter will be passed to
+ `scipy.optimize.minimize`.
+
+ >>> minimizer_kwargs = {"method": "BFGS"}
+ >>> ret = basinhopping(func, x0, minimizer_kwargs=minimizer_kwargs,
+ ... niter=200)
+ >>> # the global minimum is:
+ >>> ret.x, ret.fun
+ -0.1951, -1.0009
+
+ Next consider a 2-D minimization problem. Also, this time, we
+ will use gradient information to significantly speed up the search.
+
+ >>> def func2d(x):
+ ... f = np.cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] +
+ ... 0.2) * x[0]
+ ... df = np.zeros(2)
+ ... df[0] = -14.5 * np.sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2
+ ... df[1] = 2. * x[1] + 0.2
+ ... return f, df
+
+ We'll also use a different local minimization algorithm. Also, we must tell
+ the minimizer that our function returns both energy and gradient (Jacobian).
+
+ >>> minimizer_kwargs = {"method":"L-BFGS-B", "jac":True}
+ >>> x0 = [1.0, 1.0]
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
+ ... niter=200)
+ >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
+ ... ret.x[1],
+ ... ret.fun))
+ global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109
+
+ Here is an example using a custom step-taking routine. Imagine you want
+ the first coordinate to take larger steps than the rest of the coordinates.
+ This can be implemented like so:
+
+ >>> class MyTakeStep:
+ ... def __init__(self, stepsize=0.5):
+ ... self.stepsize = stepsize
+ ... self.rng = np.random.default_rng()
+ ... def __call__(self, x):
+ ... s = self.stepsize
+ ... x[0] += self.rng.uniform(-2.*s, 2.*s)
+ ... x[1:] += self.rng.uniform(-s, s, x[1:].shape)
+ ... return x
+
+ Since ``MyTakeStep.stepsize`` exists basinhopping will adjust the magnitude
+ of `stepsize` to optimize the search. We'll use the same 2-D function as
+ before
+
+ >>> mytakestep = MyTakeStep()
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
+ ... niter=200, take_step=mytakestep)
+ >>> print("global minimum: x = [%.4f, %.4f], f(x) = %.4f" % (ret.x[0],
+ ... ret.x[1],
+ ... ret.fun))
+ global minimum: x = [-0.1951, -0.1000], f(x) = -1.0109
+
+ Now, let's do an example using a custom callback function which prints the
+ value of every minimum found
+
+ >>> def print_fun(x, f, accepted):
+ ... print("at minimum %.4f accepted %d" % (f, int(accepted)))
+
+ We'll run it for only 10 basinhopping steps this time.
+
+ >>> rng = np.random.default_rng()
+ >>> ret = basinhopping(func2d, x0, minimizer_kwargs=minimizer_kwargs,
+ ... niter=10, callback=print_fun, rng=rng)
+ at minimum 0.4159 accepted 1
+ at minimum -0.4317 accepted 1
+ at minimum -1.0109 accepted 1
+ at minimum -0.9073 accepted 1
+ at minimum -0.4317 accepted 0
+ at minimum -0.1021 accepted 1
+ at minimum -0.7425 accepted 1
+ at minimum -0.9073 accepted 1
+ at minimum -0.4317 accepted 0
+ at minimum -0.7425 accepted 1
+ at minimum -0.9073 accepted 1
+
+ The minimum at -1.0109 is actually the global minimum, found already on the
+ 8th iteration.
+
+ """ # numpy/numpydoc#87 # noqa: E501
+ if target_accept_rate <= 0. or target_accept_rate >= 1.:
+ raise ValueError('target_accept_rate has to be in range (0, 1)')
+ if stepwise_factor <= 0. or stepwise_factor >= 1.:
+ raise ValueError('stepwise_factor has to be in range (0, 1)')
+
+ x0 = np.array(x0)
+
+ # set up the np.random generator
+ rng = check_random_state(rng)
+
+ # set up minimizer
+ if minimizer_kwargs is None:
+ minimizer_kwargs = dict()
+ wrapped_minimizer = MinimizerWrapper(scipy.optimize.minimize, func,
+ **minimizer_kwargs)
+
+ # set up step-taking algorithm
+ if take_step is not None:
+ if not callable(take_step):
+ raise TypeError("take_step must be callable")
+ # if take_step.stepsize exists then use AdaptiveStepsize to control
+ # take_step.stepsize
+ if hasattr(take_step, "stepsize"):
+ take_step_wrapped = AdaptiveStepsize(
+ take_step, interval=interval,
+ accept_rate=target_accept_rate,
+ factor=stepwise_factor,
+ verbose=disp)
+ else:
+ take_step_wrapped = take_step
+ else:
+ # use default
+ displace = RandomDisplacement(stepsize=stepsize, rng=rng)
+ take_step_wrapped = AdaptiveStepsize(displace, interval=interval,
+ accept_rate=target_accept_rate,
+ factor=stepwise_factor,
+ verbose=disp)
+
+ # set up accept tests
+ accept_tests = []
+ if accept_test is not None:
+ if not callable(accept_test):
+ raise TypeError("accept_test must be callable")
+ accept_tests = [accept_test]
+
+ # use default
+ metropolis = Metropolis(T, rng=rng)
+ accept_tests.append(metropolis)
+
+ if niter_success is None:
+ niter_success = niter + 2
+
+ bh = BasinHoppingRunner(x0, wrapped_minimizer, take_step_wrapped,
+ accept_tests, disp=disp)
+
+ # The wrapped minimizer is called once during construction of
+ # BasinHoppingRunner, so run the callback
+ if callable(callback):
+ callback(bh.storage.minres.x, bh.storage.minres.fun, True)
+
+ # start main iteration loop
+ count, i = 0, 0
+ message = ["requested number of basinhopping iterations completed"
+ " successfully"]
+ for i in range(niter):
+ new_global_min = bh.one_cycle()
+
+ if callable(callback):
+ # should we pass a copy of x?
+ val = callback(bh.xtrial, bh.energy_trial, bh.accept)
+ if val is not None:
+ if val:
+ message = ["callback function requested stop early by"
+ "returning True"]
+ break
+
+ count += 1
+ if new_global_min:
+ count = 0
+ elif count > niter_success:
+ message = ["success condition satisfied"]
+ break
+
+ # prepare return object
+ res = bh.res
+ res.lowest_optimization_result = bh.storage.get_lowest()
+ res.x = np.copy(res.lowest_optimization_result.x)
+ res.fun = res.lowest_optimization_result.fun
+ res.message = message
+ res.nit = i + 1
+ res.success = res.lowest_optimization_result.success
+ return res
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..3bdb665ff50fef5c9420632a71e7b6b584c039f2
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_bglu_dense.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:585cd8c8d869f561e86ff92f5c7ae732eee89d5bc373ed5fb5aa59ee344293f4
+size 171904
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_bracket.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_bracket.py
new file mode 100644
index 0000000000000000000000000000000000000000..8bc5ab0dc2f50ecda8bb8ca9200c71f7c5e5a94b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_bracket.py
@@ -0,0 +1,706 @@
+import numpy as np
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import array_namespace, xp_ravel, xp_promote
+
+_ELIMITS = -1 # used in _bracket_root
+_ESTOPONESIDE = 2 # used in _bracket_root
+
+def _bracket_root_iv(func, xl0, xr0, xmin, xmax, factor, args, maxiter):
+
+ if not callable(func):
+ raise ValueError('`func` must be callable.')
+
+ if not np.iterable(args):
+ args = (args,)
+
+ xp = array_namespace(xl0, xr0, xmin, xmax, factor, *args)
+
+ # If xr0 is not supplied, fill with a dummy value for the sake of
+ # broadcasting. We need to wait until xmax has been validated to
+ # compute the default value.
+ xr0_not_supplied = False
+ if xr0 is None:
+ xr0 = xp.nan
+ xr0_not_supplied = True
+
+ xmin = -xp.inf if xmin is None else xmin
+ xmax = xp.inf if xmax is None else xmax
+ factor = 2. if factor is None else factor
+ xl0, xr0, xmin, xmax, factor = xp_promote(
+ xl0, xr0, xmin, xmax, factor, broadcast=True, force_floating=True, xp=xp)
+
+ if not xp.isdtype(xl0.dtype, ('integral', 'real floating')):
+ raise ValueError('`xl0` must be numeric and real.')
+
+ if (not xp.isdtype(xr0.dtype, "numeric")
+ or xp.isdtype(xr0.dtype, "complex floating")):
+ raise ValueError('`xr0` must be numeric and real.')
+
+ if (not xp.isdtype(xmin.dtype, "numeric")
+ or xp.isdtype(xmin.dtype, "complex floating")):
+ raise ValueError('`xmin` must be numeric and real.')
+
+ if (not xp.isdtype(xmax.dtype, "numeric")
+ or xp.isdtype(xmax.dtype, "complex floating")):
+ raise ValueError('`xmax` must be numeric and real.')
+
+ if (not xp.isdtype(factor.dtype, "numeric")
+ or xp.isdtype(factor.dtype, "complex floating")):
+ raise ValueError('`factor` must be numeric and real.')
+ if not xp.all(factor > 1):
+ raise ValueError('All elements of `factor` must be greater than 1.')
+
+ # Calculate the default value of xr0 if a value has not been supplied.
+ # Be careful to ensure xr0 is not larger than xmax.
+ if xr0_not_supplied:
+ xr0 = xl0 + xp.minimum((xmax - xl0)/ 8, 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, xl0, xr0, xmin, xmax, factor, *args)
+
+ xmin = -xp.inf if xmin is None else xmin
+ xmax = xp.inf if xmax is None else xmax
+
+ # If xl0 (xr0) is not supplied, fill with a dummy value for the sake
+ # of broadcasting. We need to wait until xmin (xmax) has been validated
+ # to compute the default values.
+ xl0_not_supplied = False
+ if xl0 is None:
+ xl0 = xp.nan
+ xl0_not_supplied = True
+
+ xr0_not_supplied = False
+ if xr0 is None:
+ xr0 = xp.nan
+ xr0_not_supplied = True
+
+ factor = 2.0 if factor is None else factor
+
+ xm0, xl0, xr0, xmin, xmax, factor = xp_promote(
+ xm0, xl0, xr0, xmin, xmax, factor, broadcast=True, force_floating=True, xp=xp)
+
+ if not xp.isdtype(xm0.dtype, ('integral', 'real floating')):
+ raise ValueError('`xm0` must be numeric and real.')
+
+ if (not xp.isdtype(xl0.dtype, "numeric")
+ or xp.isdtype(xl0.dtype, "complex floating")):
+ raise ValueError('`xl0` must be numeric and real.')
+
+ if (not xp.isdtype(xr0.dtype, "numeric")
+ or xp.isdtype(xr0.dtype, "complex floating")):
+ raise ValueError('`xr0` must be numeric and real.')
+
+ if (not xp.isdtype(xmin.dtype, "numeric")
+ or xp.isdtype(xmin.dtype, "complex floating")):
+ raise ValueError('`xmin` must be numeric and real.')
+
+ if (not xp.isdtype(xmax.dtype, "numeric")
+ or xp.isdtype(xmax.dtype, "complex floating")):
+ raise ValueError('`xmax` must be numeric and real.')
+
+ if (not xp.isdtype(factor.dtype, "numeric")
+ or xp.isdtype(factor.dtype, "complex floating")):
+ raise ValueError('`factor` must be numeric and real.')
+ if not xp.all(factor > 1):
+ raise ValueError('All elements of `factor` must be greater than 1.')
+
+ # Calculate default values of xl0 and/or xr0 if they have not been supplied
+ # by the user. We need to be careful to ensure xl0 and xr0 are not outside
+ # of (xmin, xmax).
+ if xl0_not_supplied:
+ xl0 = xm0 - xp.minimum((xm0 - xmin)/16, 0.5)
+ xl0 = xp.astype(xl0, xm0.dtype, copy=False)
+ if xr0_not_supplied:
+ xr0 = xm0 + xp.minimum((xmax - xm0)/16, 0.5)
+ xr0 = xp.astype(xr0, xm0.dtype, copy=False)
+
+ maxiter = xp.asarray(maxiter)
+ message = '`maxiter` must be a non-negative integer.'
+ if (not xp.isdtype(maxiter.dtype, "numeric") or maxiter.shape != tuple()
+ or xp.isdtype(maxiter.dtype, "complex floating")):
+ raise ValueError(message)
+ maxiter_int = int(maxiter[()])
+ if not maxiter == maxiter_int or maxiter < 0:
+ raise ValueError(message)
+
+ return func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter, xp
+
+
+def _bracket_minimum(func, xm0, *, xl0=None, xr0=None, xmin=None, xmax=None,
+ factor=None, args=(), maxiter=1000):
+ """Bracket the minimum of a unimodal scalar function of one variable
+
+ This function works elementwise when `xm0`, `xl0`, `xr0`, `xmin`, `xmax`,
+ and the elements of `args` are broadcastable arrays.
+
+ Parameters
+ ----------
+ func : callable
+ The function for which the minimum is to be bracketed.
+ The signature must be::
+
+ func(x: ndarray, *args) -> ndarray
+
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
+ which may contain an arbitrary number of arrays that are broadcastable
+ with ``x``. `func` must be an elementwise function: each element
+ ``func(x)[i]`` must equal ``func(x[i])`` for all indices `i`.
+ xm0: float array_like
+ Starting guess for middle point of bracket.
+ xl0, xr0: float array_like, optional
+ Starting guesses for left and right endpoints of the bracket. Must be
+ broadcastable with one another and with `xm0`.
+ xmin, xmax : float array_like, optional
+ Minimum and maximum allowable endpoints of the bracket, inclusive. Must
+ be broadcastable with `xl0`, `xm0`, and `xr0`.
+ factor : float array_like, optional
+ Controls expansion of bracket endpoint in downhill direction. Works
+ differently in the cases where a limit is set in the downhill direction
+ with `xmax` or `xmin`. See Notes.
+ args : tuple, optional
+ Additional positional arguments to be passed to `func`. Must be arrays
+ broadcastable with `xl0`, `xm0`, `xr0`, `xmin`, and `xmax`. If the
+ callable to be bracketed requires arguments that are not broadcastable
+ with these arrays, wrap that callable with `func` such that `func`
+ accepts only ``x`` and broadcastable arrays.
+ maxiter : int, optional
+ The maximum number of iterations of the algorithm to perform. The number
+ of function evaluations is three greater than the number of iterations.
+
+ Returns
+ -------
+ res : _RichResult
+ An instance of `scipy._lib._util._RichResult` with the following
+ attributes. The descriptions are written as though the values will be
+ scalars; however, if `func` returns an array, the outputs will be
+ arrays of the same shape.
+
+ xl, xm, xr : float
+ The left, middle, and right points of the bracket, if the algorithm
+ terminated successfully.
+ fl, fm, fr : float
+ The function value at the left, middle, and right points of the bracket.
+ nfev : int
+ The number of function evaluations required to find the bracket.
+ nit : int
+ The number of iterations of the algorithm that were performed.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ - ``0`` : The algorithm produced a valid bracket.
+ - ``-1`` : The bracket expanded to the allowable limits. Assuming
+ unimodality, this implies the endpoint at the limit is a
+ minimizer.
+ - ``-2`` : The maximum number of iterations was reached.
+ - ``-3`` : A non-finite value was encountered.
+ - ``-4`` : ``None`` shall pass.
+ - ``-5`` : The initial bracket does not satisfy
+ `xmin <= xl0 < xm0 < xr0 <= xmax`.
+
+ success : bool
+ ``True`` when the algorithm terminated successfully (status ``0``).
+
+ Notes
+ -----
+ Similar to `scipy.optimize.bracket`, this function seeks to find real
+ points ``xl < xm < xr`` such that ``f(xl) >= f(xm)`` and ``f(xr) >= f(xm)``,
+ where at least one of the inequalities is strict. Unlike `scipy.optimize.bracket`,
+ this function can operate in a vectorized manner on array input, so long as
+ the input arrays are broadcastable with each other. Also unlike
+ `scipy.optimize.bracket`, users may specify minimum and maximum endpoints
+ for the desired bracket.
+
+ Given an initial trio of points ``xl = xl0``, ``xm = xm0``, ``xr = xr0``,
+ the algorithm checks if these points already give a valid bracket. If not,
+ a new endpoint, ``w`` is chosen in the "downhill" direction, ``xm`` becomes the new
+ opposite endpoint, and either `xl` or `xr` becomes the new middle point,
+ depending on which direction is downhill. The algorithm repeats from here.
+
+ The new endpoint `w` is chosen differently depending on whether or not a
+ boundary `xmin` or `xmax` has been set in the downhill direction. Without
+ loss of generality, suppose the downhill direction is to the right, so that
+ ``f(xl) > f(xm) > f(xr)``. If there is no boundary to the right, then `w`
+ is chosen to be ``xr + factor * (xr - xm)`` where `factor` is controlled by
+ the user (defaults to 2.0) so that step sizes increase in geometric proportion.
+ If there is a boundary, `xmax` in this case, then `w` is chosen to be
+ ``xmax - (xmax - xr)/factor``, with steps slowing to a stop at
+ `xmax`. This cautious approach ensures that a minimum near but distinct from
+ the boundary isn't missed while also detecting whether or not the `xmax` is
+ a minimizer when `xmax` is reached after a finite number of steps.
+ """ # noqa: E501
+ callback = None # works; I just don't want to test it
+
+ temp = _bracket_minimum_iv(func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter)
+ func, xm0, xl0, xr0, xmin, xmax, factor, args, maxiter, xp = temp
+
+ xs = (xl0, xm0, xr0)
+ temp = eim._initialize(func, xs, args)
+ func, xs, fs, args, shape, dtype, xp = temp
+
+ xl0, xm0, xr0 = xs
+ fl0, fm0, fr0 = fs
+ xmin = xp.astype(xp.broadcast_to(xmin, shape), dtype, copy=False)
+ xmin = xp_ravel(xmin, xp=xp)
+ xmax = xp.astype(xp.broadcast_to(xmax, shape), dtype, copy=False)
+ xmax = xp_ravel(xmax, xp=xp)
+ invalid_bracket = ~((xmin <= xl0) & (xl0 < xm0) & (xm0 < xr0) & (xr0 <= xmax))
+ # We will modify factor later on so make a copy. np.broadcast_to returns
+ # a read-only view.
+ factor = xp.astype(xp.broadcast_to(factor, shape), dtype, copy=True)
+ factor = xp_ravel(factor)
+
+ # To simplify the logic, swap xl and xr if f(xl) < f(xr). We should always be
+ # marching downhill in the direction from xl to xr.
+ comp = fl0 < fr0
+ xl0[comp], xr0[comp] = xr0[comp], xl0[comp]
+ fl0[comp], fr0[comp] = fr0[comp], fl0[comp]
+ # We only need the boundary in the direction we're traveling.
+ limit = xp.where(comp, xmin, xmax)
+
+ unlimited = xp.isinf(limit)
+ limited = ~unlimited
+ step = xp.empty_like(xl0)
+
+ step[unlimited] = (xr0[unlimited] - xm0[unlimited])
+ step[limited] = (limit[limited] - xr0[limited])
+
+ # Step size is divided by factor for case where there is a limit.
+ factor[limited] = 1 / factor[limited]
+
+ status = xp.full_like(xl0, eim._EINPROGRESS, dtype=xp.int32)
+ status[invalid_bracket] = eim._EINPUTERR
+ nit, nfev = 0, 3
+
+ work = _RichResult(xl=xl0, xm=xm0, xr=xr0, xr0=xr0, fl=fl0, fm=fm0, fr=fr0,
+ step=step, limit=limit, limited=limited, factor=factor, nit=nit,
+ nfev=nfev, status=status, args=args)
+
+ res_work_pairs = [('status', 'status'), ('xl', 'xl'), ('xm', 'xm'), ('xr', 'xr'),
+ ('nit', 'nit'), ('nfev', 'nfev'), ('fl', 'fl'), ('fm', 'fm'),
+ ('fr', 'fr')]
+
+ def pre_func_eval(work):
+ work.step *= work.factor
+ x = xp.empty_like(work.xr)
+ x[~work.limited] = work.xr0[~work.limited] + work.step[~work.limited]
+ x[work.limited] = work.limit[work.limited] - work.step[work.limited]
+ # Since the new bracket endpoint is calculated from an offset with the
+ # limit, it may be the case that the new endpoint equals the old endpoint,
+ # when the old endpoint is sufficiently close to the limit. We use the
+ # limit itself as the new endpoint in these cases.
+ x[work.limited] = xp.where(
+ x[work.limited] == work.xr[work.limited],
+ work.limit[work.limited],
+ x[work.limited],
+ )
+ return x
+
+ def post_func_eval(x, f, work):
+ work.xl, work.xm, work.xr = work.xm, work.xr, x
+ work.fl, work.fm, work.fr = work.fm, work.fr, f
+
+ def check_termination(work):
+ # Condition 0: Initial bracket is invalid.
+ stop = (work.status == eim._EINPUTERR)
+
+ # Condition 1: A valid bracket has been found.
+ i = (
+ (work.fl >= work.fm) & (work.fr > work.fm)
+ | (work.fl > work.fm) & (work.fr >= work.fm)
+ ) & ~stop
+ work.status[i] = eim._ECONVERGED
+ stop[i] = True
+
+ # Condition 2: Moving end of bracket reaches limit.
+ i = (work.xr == work.limit) & ~stop
+ work.status[i] = _ELIMITS
+ stop[i] = True
+
+ # Condition 3: non-finite value encountered
+ i = ~(xp.isfinite(work.xr) & xp.isfinite(work.fr)) & ~stop
+ work.status[i] = eim._EVALUEERR
+ stop[i] = True
+
+ return stop
+
+ def post_termination_check(work):
+ pass
+
+ def customize_result(res, shape):
+ # Reorder entries of xl and xr if they were swapped due to f(xl0) < f(xr0).
+ comp = res['xl'] > res['xr']
+ res['xl'][comp], res['xr'][comp] = res['xr'][comp], res['xl'][comp]
+ res['fl'][comp], res['fr'][comp] = res['fr'][comp], res['fl'][comp]
+ return shape
+
+ return eim._loop(work, callback, shape,
+ maxiter, func, args, dtype,
+ pre_func_eval, post_func_eval,
+ check_termination, post_termination_check,
+ customize_result, res_work_pairs, xp)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_chandrupatla.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_chandrupatla.py
new file mode 100644
index 0000000000000000000000000000000000000000..83a77b0db01ed37d7cc9bebaa963354d4b54ed7f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_chandrupatla.py
@@ -0,0 +1,551 @@
+import math
+import numpy as np
+import scipy._lib._elementwise_iterative_method as eim
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import xp_copy
+
+# 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, eim._EINPROGRESS,
+ dtype=xp.int32) # in progress
+ nit, nfev = 0, 2 # two function evaluations performed above
+ finfo = xp.finfo(dtype)
+ xatol = 4*finfo.smallest_normal if xatol is None else xatol
+ xrtol = 4*finfo.eps if xrtol is None else xrtol
+ fatol = finfo.smallest_normal if fatol is None else fatol
+ frtol = frtol * xp.minimum(xp.abs(f1), xp.abs(f2))
+ maxiter = (math.log2(finfo.max) - math.log2(finfo.smallest_normal)
+ if maxiter is None else maxiter)
+ work = _RichResult(x1=x1, f1=f1, x2=x2, f2=f2, x3=None, f3=None, t=0.5,
+ xatol=xatol, xrtol=xrtol, fatol=fatol, frtol=frtol,
+ nit=nit, nfev=nfev, status=status)
+ res_work_pairs = [('status', 'status'), ('x', 'xmin'), ('fun', 'fmin'),
+ ('nit', 'nit'), ('nfev', 'nfev'), ('xl', 'x1'),
+ ('fl', 'f1'), ('xr', 'x2'), ('fr', 'f2')]
+
+ def pre_func_eval(work):
+ # [1] Figure 1 (first box)
+ x = work.x1 + work.t * (work.x2 - work.x1)
+ return x
+
+ def post_func_eval(x, f, work):
+ # [1] Figure 1 (first diamond and boxes)
+ # Note: y/n are reversed in figure; compare to BASIC in appendix
+ work.x3, work.f3 = (xp.asarray(work.x2, copy=True),
+ xp.asarray(work.f2, copy=True))
+ j = xp.sign(f) == xp.sign(work.f1)
+ nj = ~j
+ work.x3[j], work.f3[j] = work.x1[j], work.f1[j]
+ work.x2[nj], work.f2[nj] = work.x1[nj], work.f1[nj]
+ work.x1, work.f1 = x, f
+
+ def check_termination(work):
+ # [1] Figure 1 (second diamond)
+ # Check for all terminal conditions and record statuses.
+
+ # See [1] Section 4 (first two sentences)
+ i = xp.abs(work.f1) < xp.abs(work.f2)
+ work.xmin = xp.where(i, work.x1, work.x2)
+ work.fmin = xp.where(i, work.f1, work.f2)
+ stop = xp.zeros_like(work.x1, dtype=xp.bool) # termination condition met
+
+ # If function value tolerance is met, report successful convergence,
+ # regardless of other conditions. Note that `frtol` has been redefined
+ # as `frtol = frtol * minimum(f1, f2)`, where `f1` and `f2` are the
+ # function evaluated at the original ends of the bracket.
+ i = xp.abs(work.fmin) <= work.fatol + work.frtol
+ work.status[i] = eim._ECONVERGED
+ stop[i] = True
+
+ # If the bracket is no longer valid, report failure (unless a function
+ # tolerance is met, as detected above).
+ i = (xp.sign(work.f1) == xp.sign(work.f2)) & ~stop
+ NaN = xp.asarray(xp.nan, dtype=work.xmin.dtype)
+ work.xmin[i], work.fmin[i], work.status[i] = NaN, NaN, eim._ESIGNERR
+ stop[i] = True
+
+ # If the abscissae are non-finite or either function value is NaN,
+ # report failure.
+ x_nonfinite = ~(xp.isfinite(work.x1) & xp.isfinite(work.x2))
+ f_nan = xp.isnan(work.f1) & xp.isnan(work.f2)
+ i = (x_nonfinite | f_nan) & ~stop
+ work.xmin[i], work.fmin[i], work.status[i] = NaN, NaN, eim._EVALUEERR
+ stop[i] = True
+
+ # This is the convergence criterion used in bisect. Chandrupatla's
+ # criterion is equivalent to this except with a factor of 4 on `xrtol`.
+ work.dx = xp.abs(work.x2 - work.x1)
+ work.tol = xp.abs(work.xmin) * work.xrtol + work.xatol
+ i = work.dx < work.tol
+ work.status[i] = eim._ECONVERGED
+ stop[i] = True
+
+ return stop
+
+ def post_termination_check(work):
+ # [1] Figure 1 (third diamond and boxes / Equation 1)
+ xi1 = (work.x1 - work.x2) / (work.x3 - work.x2)
+ with np.errstate(divide='ignore', invalid='ignore'):
+ phi1 = (work.f1 - work.f2) / (work.f3 - work.f2)
+ alpha = (work.x3 - work.x1) / (work.x2 - work.x1)
+ j = ((1 - xp.sqrt(1 - xi1)) < phi1) & (phi1 < xp.sqrt(xi1))
+
+ f1j, f2j, f3j, alphaj = work.f1[j], work.f2[j], work.f3[j], alpha[j]
+ t = xp.full_like(alpha, 0.5)
+ t[j] = (f1j / (f1j - f2j) * f3j / (f3j - f2j)
+ - alphaj * f1j / (f3j - f1j) * f2j / (f2j - f3j))
+
+ # [1] Figure 1 (last box; see also BASIC in appendix with comment
+ # "Adjust T Away from the Interval Boundary")
+ tl = 0.5 * work.tol / work.dx
+ work.t = xp.clip(t, tl, 1 - tl)
+
+ def customize_result(res, shape):
+ xl, xr, fl, fr = res['xl'], res['xr'], res['fl'], res['fr']
+ i = res['xl'] < res['xr']
+ res['xl'] = xp.where(i, xl, xr)
+ res['xr'] = xp.where(i, xr, xl)
+ res['fl'] = xp.where(i, fl, fr)
+ res['fr'] = xp.where(i, fr, fl)
+ return shape
+
+ return eim._loop(work, callback, shape, maxiter, func, args, dtype,
+ pre_func_eval, post_func_eval, check_termination,
+ post_termination_check, customize_result, res_work_pairs,
+ xp=xp)
+
+
+def _chandrupatla_iv(func, args, 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, eim._EINPROGRESS, dtype=xp.int32) # in progress
+ nit, nfev = 0, 3 # three function evaluations performed above
+ fatol = xp.finfo(dtype).smallest_normal if fatol is None else fatol
+ frtol = xp.finfo(dtype).smallest_normal if frtol is None else frtol
+ xatol = xp.finfo(dtype).smallest_normal if xatol is None else xatol
+ xrtol = math.sqrt(xp.finfo(dtype).eps) if xrtol is None else xrtol
+
+ # Ensure that x1 < x2 < x3 initially.
+ xs, fs = xp.stack((x1, x2, x3)), xp.stack((f1, f2, f3))
+ i = xp.argsort(xs, axis=0)
+ x1, x2, x3 = xp.take_along_axis(xs, i, axis=0) # data-apis/array-api#808
+ f1, f2, f3 = xp.take_along_axis(fs, i, axis=0) # data-apis/array-api#808
+ q0 = xp_copy(x3) # "At the start, q0 is set at x3..." ([1] after (7))
+
+ work = _RichResult(x1=x1, f1=f1, x2=x2, f2=f2, x3=x3, f3=f3, phi=phi,
+ xatol=xatol, xrtol=xrtol, fatol=fatol, frtol=frtol,
+ nit=nit, nfev=nfev, status=status, q0=q0, args=args)
+ res_work_pairs = [('status', 'status'),
+ ('x', 'x2'), ('fun', 'f2'),
+ ('nit', 'nit'), ('nfev', 'nfev'),
+ ('xl', 'x1'), ('xm', 'x2'), ('xr', 'x3'),
+ ('fl', 'f1'), ('fm', 'f2'), ('fr', 'f3')]
+
+ def pre_func_eval(work):
+ # `_check_termination` is called first -> `x3 - x2 > x2 - x1`
+ # But let's calculate a few terms that we'll reuse
+ x21 = work.x2 - work.x1
+ x32 = work.x3 - work.x2
+
+ # [1] Section 3. "The quadratic minimum point Q1 is calculated using
+ # the relations developed in the previous section." [1] Section 2 (5/6)
+ A = x21 * (work.f3 - work.f2)
+ B = x32 * (work.f1 - work.f2)
+ C = A / (A + B)
+ # q1 = C * (work.x1 + work.x2) / 2 + (1 - C) * (work.x2 + work.x3) / 2
+ q1 = 0.5 * (C*(work.x1 - work.x3) + work.x2 + work.x3) # much faster
+ # this is an array, so multiplying by 0.5 does not change dtype
+
+ # "If Q1 and Q0 are sufficiently close... Q1 is accepted if it is
+ # sufficiently away from the inside point x2"
+ i = xp.abs(q1 - work.q0) < 0.5 * xp.abs(x21) # [1] (7)
+ xi = q1[i]
+ # Later, after (9), "If the point Q1 is in a +/- xtol neighborhood of
+ # x2, the new point is chosen in the larger interval at a distance
+ # tol away from x2."
+ # See also QBASIC code after "Accept Ql adjust if close to X2".
+ j = xp.abs(q1[i] - work.x2[i]) <= work.xtol[i]
+ xi[j] = work.x2[i][j] + xp.sign(x32[i][j]) * work.xtol[i][j]
+
+ # "If condition (7) is not satisfied, golden sectioning of the larger
+ # interval is carried out to introduce the new point."
+ # (For simplicity, we go ahead and calculate it for all points, but we
+ # change the elements for which the condition was satisfied.)
+ x = work.x2 + (2 - work.phi) * x32
+ x[i] = xi
+
+ # "We define Q0 as the value of Q1 at the previous iteration."
+ work.q0 = q1
+ return x
+
+ def post_func_eval(x, f, work):
+ # Standard logic for updating a three-point bracket based on a new
+ # point. In QBASIC code, see "IF SGN(X-X2) = SGN(X3-X2) THEN...".
+ # There is an awful lot of data copying going on here; this would
+ # probably benefit from code optimization or implementation in Pythran.
+ i = xp.sign(x - work.x2) == xp.sign(work.x3 - work.x2)
+ xi, x1i, x2i, x3i = x[i], work.x1[i], work.x2[i], work.x3[i],
+ fi, f1i, f2i, f3i = f[i], work.f1[i], work.f2[i], work.f3[i]
+ j = fi > f2i
+ x3i[j], f3i[j] = xi[j], fi[j]
+ j = ~j
+ x1i[j], f1i[j], x2i[j], f2i[j] = x2i[j], f2i[j], xi[j], fi[j]
+
+ ni = ~i
+ xni, x1ni, x2ni, x3ni = x[ni], work.x1[ni], work.x2[ni], work.x3[ni],
+ fni, f1ni, f2ni, f3ni = f[ni], work.f1[ni], work.f2[ni], work.f3[ni]
+ j = fni > f2ni
+ x1ni[j], f1ni[j] = xni[j], fni[j]
+ j = ~j
+ x3ni[j], f3ni[j], x2ni[j], f2ni[j] = x2ni[j], f2ni[j], xni[j], fni[j]
+
+ work.x1[i], work.x2[i], work.x3[i] = x1i, x2i, x3i
+ work.f1[i], work.f2[i], work.f3[i] = f1i, f2i, f3i
+ work.x1[ni], work.x2[ni], work.x3[ni] = x1ni, x2ni, x3ni,
+ work.f1[ni], work.f2[ni], work.f3[ni] = f1ni, f2ni, f3ni
+
+ def check_termination(work):
+ # Check for all terminal conditions and record statuses.
+ stop = xp.zeros_like(work.x1, dtype=bool) # termination condition met
+
+ # Bracket is invalid; stop and don't return minimizer/minimum
+ i = ((work.f2 > work.f1) | (work.f2 > work.f3))
+ work.x2[i], work.f2[i] = xp.nan, xp.nan
+ stop[i], work.status[i] = True, eim._ESIGNERR
+
+ # Non-finite values; stop and don't return minimizer/minimum
+ finite = xp.isfinite(work.x1+work.x2+work.x3+work.f1+work.f2+work.f3)
+ i = ~(finite | stop)
+ work.x2[i], work.f2[i] = xp.nan, xp.nan
+ stop[i], work.status[i] = True, eim._EVALUEERR
+
+ # [1] Section 3 "Points 1 and 3 are interchanged if necessary to make
+ # the (x2, x3) the larger interval."
+ # Note: I had used np.choose; this is much faster. This would be a good
+ # place to save e.g. `work.x3 - work.x2` for reuse, but I tried and
+ # didn't notice a speed boost, so let's keep it simple.
+ i = xp.abs(work.x3 - work.x2) < xp.abs(work.x2 - work.x1)
+ temp = work.x1[i]
+ work.x1[i] = work.x3[i]
+ work.x3[i] = temp
+ temp = work.f1[i]
+ work.f1[i] = work.f3[i]
+ work.f3[i] = temp
+
+ # [1] Section 3 (bottom of page 212)
+ # "We set a tolerance value xtol..."
+ work.xtol = xp.abs(work.x2) * work.xrtol + work.xatol # [1] (8)
+ # "The convergence based on interval is achieved when..."
+ # Note: Equality allowed in case of `xtol=0`
+ i = xp.abs(work.x3 - work.x2) <= 2 * work.xtol # [1] (9)
+
+ # "We define ftol using..."
+ ftol = xp.abs(work.f2) * work.frtol + work.fatol # [1] (10)
+ # "The convergence based on function values is achieved when..."
+ # Note 1: modify in place to incorporate tolerance on function value.
+ # Note 2: factor of 2 is not in the text; see QBASIC start of DO loop
+ i |= (work.f1 - 2 * work.f2 + work.f3) <= 2*ftol # [1] (11)
+ i &= ~stop
+ stop[i], work.status[i] = True, eim._ECONVERGED
+
+ return stop
+
+ def post_termination_check(work):
+ pass
+
+ def customize_result(res, shape):
+ xl, xr, fl, fr = res['xl'], res['xr'], res['fl'], res['fr']
+ i = res['xl'] >= res['xr']
+ res['xl'] = xp.where(i, xr, xl)
+ res['xr'] = xp.where(i, xl, xr)
+ res['fl'] = xp.where(i, fr, fl)
+ res['fr'] = xp.where(i, fl, fr)
+ return shape
+
+ return eim._loop(work, callback, shape, maxiter, func, args, dtype,
+ pre_func_eval, post_func_eval, check_termination,
+ post_termination_check, customize_result, res_work_pairs,
+ xp=xp)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_cobyla_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_cobyla_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..5e9ab23768774191633f15543cf3162c92b750c5
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_cobyla_py.py
@@ -0,0 +1,296 @@
+"""
+Interface to Constrained Optimization By Linear Approximation
+
+Functions
+---------
+.. autosummary::
+ :toctree: generated/
+
+ fmin_cobyla
+
+"""
+
+import numpy as np
+from scipy._lib._util import wrapped_inspect_signature
+from ._optimize import (OptimizeResult, _check_unknown_options,
+ _prepare_scalar_function)
+from ._constraints import NonlinearConstraint
+
+
+__all__ = ['fmin_cobyla']
+
+
+def fmin_cobyla(func, x0, cons, args=(), consargs=None, rhobeg=1.0,
+ rhoend=1e-4, maxfun=1000, disp=None, catol=2e-4,
+ *, callback=None):
+ """
+ Minimize a function using the Constrained Optimization By Linear
+ Approximation (COBYLA) method. This method uses the pure-python implementation
+ of the algorithm from PRIMA.
+
+ Parameters
+ ----------
+ func : callable
+ Function to minimize. In the form func(x, \\*args).
+ x0 : ndarray
+ Initial guess.
+ cons : sequence
+ Constraint functions; must all be ``>=0`` (a single function
+ if only 1 constraint). Each function takes the parameters `x`
+ as its first argument, and it can return either a single number or
+ an array or list of numbers.
+ args : tuple, optional
+ Extra arguments to pass to function.
+ consargs : tuple, optional
+ Extra arguments to pass to constraint functions (default of None means
+ use same extra arguments as those passed to func).
+ Use ``()`` for no extra arguments.
+ rhobeg : float, optional
+ Reasonable initial changes to the variables.
+ rhoend : float, optional
+ Final accuracy in the optimization (not precisely guaranteed). This
+ is a lower bound on the size of the trust region.
+ disp : {0, 1, 2, 3}, optional
+ Controls the frequency of output; 0 implies no output.
+ maxfun : int, optional
+ Maximum number of function evaluations.
+ catol : float, optional
+ Absolute tolerance for constraint violations.
+ callback : callable, optional
+ Called after each iteration, as ``callback(x)``, where ``x`` is the
+ current parameter vector.
+
+ Returns
+ -------
+ x : ndarray
+ The argument that minimises `f`.
+
+ See also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'COBYLA' `method` in particular.
+
+ Notes
+ -----
+ This algorithm is based on linear approximations to the objective
+ function and each constraint. We briefly describe the algorithm.
+
+ Suppose the function is being minimized over k variables. At the
+ jth iteration the algorithm has k+1 points v_1, ..., v_(k+1),
+ an approximate solution x_j, and a radius RHO_j.
+ (i.e., linear plus a constant) approximations to the objective
+ function and constraint functions such that their function values
+ agree with the linear approximation on the k+1 points v_1,.., v_(k+1).
+ This gives a linear program to solve (where the linear approximations
+ of the constraint functions are constrained to be non-negative).
+
+ However, the linear approximations are likely only good
+ approximations near the current simplex, so the linear program is
+ given the further requirement that the solution, which
+ will become x_(j+1), must be within RHO_j from x_j. RHO_j only
+ decreases, never increases. The initial RHO_j is rhobeg and the
+ final RHO_j is rhoend. In this way COBYLA's iterations behave
+ like a trust region algorithm.
+
+ Additionally, the linear program may be inconsistent, or the
+ approximation may give poor improvement. For details about
+ how these issues are resolved, as well as how the points v_i are
+ updated, refer to the source code or the references below.
+
+ .. versionchanged:: 1.16.0
+ The original Powell implementation was replaced by a pure
+ Python version from the PRIMA package, with bug fixes and
+ improvements being made.
+
+
+ References
+ ----------
+ Powell M.J.D. (1994), "A direct search optimization method that models
+ the objective and constraint functions by linear interpolation.", in
+ Advances in Optimization and Numerical Analysis, eds. S. Gomez and
+ J-P Hennart, Kluwer Academic (Dordrecht), pp. 51-67
+
+ Powell M.J.D. (1998), "Direct search algorithms for optimization
+ calculations", Acta Numerica 7, 287-336
+
+ Powell M.J.D. (2007), "A view of algorithms for optimization without
+ derivatives", Cambridge University Technical Report DAMTP 2007/NA03
+
+ Zhang Z. (2023), "PRIMA: Reference Implementation for Powell's Methods with
+ Modernization and Amelioration", https://www.libprima.net,
+ :doi:`10.5281/zenodo.8052654`
+
+ Examples
+ --------
+ Minimize the objective function f(x,y) = x*y subject
+ to the constraints x**2 + y**2 < 1 and y > 0::
+
+ >>> def objective(x):
+ ... return x[0]*x[1]
+ ...
+ >>> def constr1(x):
+ ... return 1 - (x[0]**2 + x[1]**2)
+ ...
+ >>> def constr2(x):
+ ... return x[1]
+ ...
+ >>> from scipy.optimize import fmin_cobyla
+ >>> fmin_cobyla(objective, [0.0, 0.1], [constr1, constr2], rhoend=1e-7)
+ array([-0.70710685, 0.70710671])
+
+ The exact solution is (-sqrt(2)/2, sqrt(2)/2).
+
+
+
+ """
+ err = "cons must be a sequence of callable functions or a single"\
+ " callable function."
+ try:
+ len(cons)
+ except TypeError as e:
+ if callable(cons):
+ cons = [cons]
+ else:
+ raise TypeError(err) from e
+ else:
+ for thisfunc in cons:
+ if not callable(thisfunc):
+ raise TypeError(err)
+
+ if consargs is None:
+ consargs = args
+
+ # build constraints
+ nlcs = []
+ for con in cons:
+ # Use default argument, otherwise the last `con` is captured by all wrapped_con
+ def wrapped_con(x, confunc=con):
+ return confunc(x, *consargs)
+ nlcs.append(NonlinearConstraint(wrapped_con, 0, np.inf))
+
+ # options
+ opts = {'rhobeg': rhobeg,
+ 'tol': rhoend,
+ 'disp': disp,
+ 'maxiter': maxfun,
+ 'catol': catol,
+ 'callback': callback}
+
+ sol = _minimize_cobyla(func, x0, args, constraints=nlcs,
+ **opts)
+ if disp and not sol['success']:
+ print(f"COBYLA failed to find a solution: {sol.message}")
+ return sol['x']
+
+
+def _minimize_cobyla(fun, x0, args=(), constraints=(),
+ rhobeg=1.0, tol=1e-4, maxiter=1000,
+ disp=0, catol=None, f_target=-np.inf,
+ callback=None, bounds=None, **unknown_options):
+ """
+ Minimize a scalar function of one or more variables using the
+ Constrained Optimization BY Linear Approximation (COBYLA) algorithm.
+ This method uses the pure-python implementation of the algorithm from PRIMA.
+
+ Options
+ -------
+ rhobeg : float
+ Reasonable initial changes to the variables.
+ tol : float
+ Final accuracy in the optimization (not precisely guaranteed).
+ This is a lower bound on the size of the trust region.
+ disp : int
+ Controls the frequency of output:
+ 0. (default) There will be no printing
+ 1. A message will be printed to the screen at the end of iteration, showing
+ the best vector of variables found and its objective function value
+ 2. in addition to 1, each new value of RHO is printed to the screen,
+ with the best vector of variables so far and its objective function
+ value.
+ 3. in addition to 2, each function evaluation with its variables will
+ be printed to the screen.
+ maxiter : int
+ Maximum number of function evaluations.
+ catol : float
+ Tolerance (absolute) for constraint violations
+ f_target : float
+ Stop if the objective function is less than `f_target`.
+
+ .. versionchanged:: 1.16.0
+ The original Powell implementation was replaced by a pure
+ Python version from the PRIMA package, with bug fixes and
+ improvements being made.
+
+
+ References
+ ----------
+ Zhang Z. (2023), "PRIMA: Reference Implementation for Powell's Methods with
+ Modernization and Amelioration", https://www.libprima.net,
+ :doi:`10.5281/zenodo.8052654`
+ """
+ from .._lib.pyprima import minimize
+ from .._lib.pyprima.common.infos import SMALL_TR_RADIUS, FTARGET_ACHIEVED
+ from .._lib.pyprima.common.message import get_info_string
+ _check_unknown_options(unknown_options)
+ rhoend = tol
+ iprint = disp if disp is not None else 0
+ if iprint != 0 and iprint != 1 and iprint != 2 and iprint != 3:
+ raise ValueError(f'disp argument to minimize must be 0, 1, 2, or 3,\
+ received {iprint}')
+
+ # create the ScalarFunction, cobyla doesn't require derivative function
+ def _jac(x, *args):
+ return None
+
+ sf = _prepare_scalar_function(fun, x0, args=args, jac=_jac)
+
+ if callback is not None:
+ sig = wrapped_inspect_signature(callback)
+ if set(sig.parameters) == {"intermediate_result"}:
+ def wrapped_callback_intermediate(x, f, nf, tr, cstrv, nlconstrlist):
+ intermediate_result = OptimizeResult(x=np.copy(x), fun=f, nfev=nf,
+ nit=tr, maxcv=cstrv)
+ callback(intermediate_result=intermediate_result)
+ else:
+ def wrapped_callback_intermediate(x, f, nf, tr, cstrv, nlconstrlist):
+ callback(np.copy(x))
+ def wrapped_callback(x, f, nf, tr, cstrv, nlconstrlist):
+ try:
+ wrapped_callback_intermediate(x, f, nf, tr, cstrv, nlconstrlist)
+ return False
+ except StopIteration:
+ return True
+ else:
+ wrapped_callback = None
+
+
+ ctol = catol if catol is not None else np.sqrt(np.finfo(float).eps)
+ options = {
+ 'rhobeg': rhobeg,
+ 'rhoend': rhoend,
+ 'maxfev': maxiter,
+ 'iprint': iprint,
+ 'ctol': ctol,
+ 'ftarget': f_target,
+ }
+
+ result = minimize(sf.fun, x0, method='cobyla', bounds=bounds,
+ constraints=constraints, callback=wrapped_callback,
+ options=options)
+
+
+ if result.cstrv > ctol:
+ success = False
+ message = ('Did not converge to a solution satisfying the constraints. See '
+ '`maxcv` for the magnitude of the violation.')
+ else:
+ success = result.info == SMALL_TR_RADIUS or result.info == FTARGET_ACHIEVED
+ message = get_info_string('COBYLA', result.info)
+
+ return OptimizeResult(x=result.x,
+ status=result.info,
+ success=success,
+ message=message,
+ nfev=result.nf,
+ fun=result.f,
+ maxcv=result.cstrv)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_cobyqa_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_cobyqa_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..38ae0477ca38e28dda80e0bf2dd1f0905eacff6e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_cobyqa_py.py
@@ -0,0 +1,72 @@
+import numpy as np
+from threading import Lock
+
+from ._optimize import _check_unknown_options
+
+
+COBYQA_LOCK = Lock()
+
+
+def _minimize_cobyqa(fun, x0, args=(), bounds=None, constraints=(),
+ callback=None, disp=False, maxfev=None, maxiter=None,
+ f_target=-np.inf, feasibility_tol=1e-8,
+ initial_tr_radius=1.0, final_tr_radius=1e-6, scale=False,
+ **unknown_options):
+ """
+ Minimize a scalar function of one or more variables using the
+ Constrained Optimization BY Quadratic Approximations (COBYQA) algorithm [1]_.
+
+ .. versionadded:: 1.14.0
+
+ Options
+ -------
+ disp : bool
+ Set to True to print information about the optimization procedure.
+ Default is ``False``.
+ maxfev : int
+ Maximum number of function evaluations. Default is ``500 * n``, where
+ ``n`` is the number of variables.
+ maxiter : int
+ Maximum number of iterations. Default is ``1000 * n``, where ``n`` is
+ the number of variables.
+ f_target : float
+ Target value for the objective function. The optimization procedure is
+ terminated when the objective function value of a feasible point (see
+ `feasibility_tol` below) is less than or equal to this target. Default
+ is ``-numpy.inf``.
+ feasibility_tol : float
+ Absolute tolerance for the constraint violation. Default is ``1e-8``.
+ initial_tr_radius : float
+ Initial trust-region radius. Typically, this value should be in the
+ order of one tenth of the greatest expected change to the variables.
+ Default is ``1.0``.
+ final_tr_radius : float
+ Final trust-region radius. It should indicate the accuracy required in
+ the final values of the variables. If provided, this option overrides
+ the value of `tol` in the `minimize` function. Default is ``1e-6``.
+ scale : bool
+ Set to True to scale the variables according to the bounds. If True and
+ if all the lower and upper bounds are finite, the variables are scaled
+ to be within the range :math:`[-1, 1]`. If any of the lower or upper
+ bounds is infinite, the variables are not scaled. Default is ``False``.
+
+ References
+ ----------
+ .. [1] COBYQA
+ https://www.cobyqa.com/stable/
+ """
+ from .._lib.cobyqa import minimize # import here to avoid circular imports
+
+ _check_unknown_options(unknown_options)
+ options = {
+ 'disp': bool(disp),
+ 'maxfev': int(maxfev) if maxfev is not None else 500 * len(x0),
+ 'maxiter': int(maxiter) if maxiter is not None else 1000 * len(x0),
+ 'target': float(f_target),
+ 'feasibility_tol': float(feasibility_tol),
+ 'radius_init': float(initial_tr_radius),
+ 'radius_final': float(final_tr_radius),
+ 'scale': bool(scale),
+ }
+ with COBYQA_LOCK:
+ return minimize(fun, x0, args, bounds, constraints, callback, options)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_constraints.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..2eb0be9ee6a3f5061cbff880d56fce5f72f3a3cd
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_constraints.py
@@ -0,0 +1,607 @@
+"""Constraints definition for minimize."""
+from warnings import warn, catch_warnings, simplefilter, filterwarnings
+from types import GenericAlias
+
+import numpy as np
+
+from ._differentiable_functions import (
+ VectorFunction, LinearVectorFunction, IdentityVectorFunction
+)
+from ._hessian_update_strategy import BFGS
+from ._optimize import OptimizeWarning
+
+from scipy._lib._sparse import issparse
+
+
+def _arr_to_scalar(x):
+ # If x is a numpy array, return x.item(). This will
+ # fail if the array has more than one element.
+ return x.item() if isinstance(x, np.ndarray) else x
+
+
+class NonlinearConstraint:
+ """Nonlinear constraint on the variables.
+
+ The constraint has the general inequality form::
+
+ lb <= fun(x) <= ub
+
+ Here the vector of independent variables x is passed as ndarray of shape
+ (n,) and ``fun`` returns a vector with m components.
+
+ It is possible to use equal bounds to represent an equality constraint or
+ infinite bounds to represent a one-sided constraint.
+
+ Parameters
+ ----------
+ fun : callable
+ The function defining the constraint.
+ The signature is ``fun(x) -> array_like, shape (m,)``.
+ lb, ub : array_like
+ Lower and upper bounds on the constraint. Each array must have the
+ shape (m,) or be a scalar, in the latter case a bound will be the same
+ for all components of the constraint. Use ``np.inf`` with an
+ appropriate sign to specify a one-sided constraint.
+ Set components of `lb` and `ub` equal to represent an equality
+ constraint. Note that you can mix constraints of different types:
+ interval, one-sided or equality, by setting different components of
+ `lb` and `ub` as necessary.
+ jac : {callable, '2-point', '3-point', 'cs'}, optional
+ Method of computing the Jacobian matrix (an m-by-n matrix,
+ where element (i, j) is the partial derivative of f[i] with
+ respect to x[j]). The keywords {'2-point', '3-point',
+ 'cs'} select a finite difference scheme for the numerical estimation.
+ A callable must have the following signature::
+
+ jac(x) -> {ndarray, sparse array}, shape (m, n)
+
+ Default is '2-point'.
+ hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy, None}, optional
+ Method for computing the Hessian matrix. The keywords
+ {'2-point', '3-point', 'cs'} select a finite difference scheme for
+ numerical estimation. Alternatively, objects implementing
+ `HessianUpdateStrategy` interface can be used to approximate the
+ Hessian. Currently available implementations are:
+
+ - `BFGS` (default option)
+ - `SR1`
+
+ A callable must return the Hessian matrix of ``dot(fun, v)`` and
+ must have the following signature:
+ ``hess(x, v) -> {LinearOperator, sparse array, array_like}, shape (n, n)``.
+ Here ``v`` is ndarray with shape (m,) containing Lagrange multipliers.
+ keep_feasible : array_like of bool, optional
+ Whether to keep the constraint components feasible throughout
+ iterations. A single value sets this property for all components.
+ Default is False. Has no effect for equality constraints.
+ finite_diff_rel_step: None or array_like, optional
+ Relative step size for the finite difference approximation. Default is
+ None, which will select a reasonable value automatically depending
+ on a finite difference scheme.
+ finite_diff_jac_sparsity: {None, array_like, sparse array}, optional
+ Defines the sparsity structure of the Jacobian matrix for finite
+ difference estimation, its shape must be (m, n). If the Jacobian has
+ only few non-zero elements in *each* row, providing the sparsity
+ structure will greatly speed up the computations. A zero entry means
+ that a corresponding element in the Jacobian is identically zero.
+ If provided, forces the use of 'lsmr' trust-region solver.
+ If None (default) then dense differencing will be used.
+
+ Notes
+ -----
+ Finite difference schemes {'2-point', '3-point', 'cs'} may be used for
+ approximating either the Jacobian or the Hessian. We, however, do not allow
+ its use for approximating both simultaneously. Hence whenever the Jacobian
+ is estimated via finite-differences, we require the Hessian to be estimated
+ using one of the quasi-Newton strategies.
+
+ The scheme 'cs' is potentially the most accurate, but requires the function
+ to correctly handles complex inputs and be analytically continuable to the
+ complex plane. The scheme '3-point' is more accurate than '2-point' but
+ requires twice as many operations.
+
+ Examples
+ --------
+ Constrain ``x[0] < sin(x[1]) + 1.9``
+
+ >>> from scipy.optimize import NonlinearConstraint
+ >>> import numpy as np
+ >>> con = lambda x: x[0] - np.sin(x[1])
+ >>> nlc = NonlinearConstraint(con, -np.inf, 1.9)
+
+ """
+ def __init__(self, fun, lb, ub, jac='2-point', hess=None,
+ keep_feasible=False, finite_diff_rel_step=None,
+ finite_diff_jac_sparsity=None):
+ if hess is None:
+ hess = BFGS()
+ self.fun = fun
+ self.lb = lb
+ self.ub = ub
+ self.finite_diff_rel_step = finite_diff_rel_step
+ self.finite_diff_jac_sparsity = finite_diff_jac_sparsity
+ self.jac = jac
+ self.hess = hess
+ self.keep_feasible = keep_feasible
+
+
+class LinearConstraint:
+ """Linear constraint on the variables.
+
+ The constraint has the general inequality form::
+
+ lb <= A.dot(x) <= ub
+
+ Here the vector of independent variables x is passed as ndarray of shape
+ (n,) and the matrix A has shape (m, n).
+
+ It is possible to use equal bounds to represent an equality constraint or
+ infinite bounds to represent a one-sided constraint.
+
+ Parameters
+ ----------
+ A : {array_like, sparse array}, shape (m, n)
+ Matrix defining the constraint.
+ lb, ub : dense array_like, optional
+ Lower and upper limits on the constraint. Each array must have the
+ shape (m,) or be a scalar, in the latter case a bound will be the same
+ for all components of the constraint. Use ``np.inf`` with an
+ appropriate sign to specify a one-sided constraint.
+ Set components of `lb` and `ub` equal to represent an equality
+ constraint. Note that you can mix constraints of different types:
+ interval, one-sided or equality, by setting different components of
+ `lb` and `ub` as necessary. Defaults to ``lb = -np.inf``
+ and ``ub = np.inf`` (no limits).
+ keep_feasible : dense array_like of bool, optional
+ Whether to keep the constraint components feasible throughout
+ iterations. A single value sets this property for all components.
+ Default is False. Has no effect for equality constraints.
+ """
+ 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.
+ """
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__ = classmethod(GenericAlias)
+
+ 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.
+ """
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__ = classmethod(GenericAlias)
+
+ def __init__(self, constraint, x0, sparse_jacobian=None,
+ finite_diff_bounds=(-np.inf, np.inf)):
+ if isinstance(constraint, NonlinearConstraint):
+ fun = VectorFunction(constraint.fun, x0,
+ constraint.jac, constraint.hess,
+ constraint.finite_diff_rel_step,
+ constraint.finite_diff_jac_sparsity,
+ finite_diff_bounds, sparse_jacobian)
+ elif isinstance(constraint, LinearConstraint):
+ fun = LinearVectorFunction(constraint.A, x0, sparse_jacobian)
+ elif isinstance(constraint, Bounds):
+ fun = IdentityVectorFunction(x0, sparse_jacobian)
+ else:
+ raise ValueError("`constraint` of an unknown type is passed.")
+
+ m = fun.m
+
+ lb = np.asarray(constraint.lb, dtype=float)
+ ub = np.asarray(constraint.ub, dtype=float)
+ keep_feasible = np.asarray(constraint.keep_feasible, dtype=bool)
+
+ lb = np.broadcast_to(lb, m)
+ ub = np.broadcast_to(ub, m)
+ keep_feasible = np.broadcast_to(keep_feasible, m)
+
+ if keep_feasible.shape != (m,):
+ raise ValueError("`keep_feasible` has a wrong shape.")
+
+ mask = keep_feasible & (lb != ub)
+ f0 = fun.f
+ if np.any(f0[mask] < lb[mask]) or np.any(f0[mask] > ub[mask]):
+ raise ValueError("`x0` is infeasible with respect to some "
+ "inequality constraint with `keep_feasible` "
+ "set to True.")
+
+ self.fun = fun
+ self.bounds = (lb, ub)
+ self.keep_feasible = keep_feasible
+
+ def violation(self, x):
+ """How much the constraint is exceeded by.
+
+ Parameters
+ ----------
+ x : array-like
+ Vector of independent variables
+
+ Returns
+ -------
+ excess : array-like
+ How much the constraint is exceeded by, for each of the
+ constraints specified by `PreparedConstraint.fun`.
+ """
+ with catch_warnings():
+ # Ignore the following warning, it's not important when
+ # figuring out total violation
+ # UserWarning: delta_grad == 0.0. Check if the approximated
+ # function is linear
+ filterwarnings("ignore", "delta_grad", UserWarning)
+ ev = self.fun.fun(np.asarray(x))
+
+ excess_lb = np.maximum(self.bounds[0] - ev, 0)
+ excess_ub = np.maximum(ev - self.bounds[1], 0)
+
+ return excess_lb + excess_ub
+
+
+def new_bounds_to_old(lb, ub, n):
+ """Convert the new bounds representation to the old one.
+
+ The new representation is a tuple (lb, ub) and the old one is a list
+ containing n tuples, ith containing lower and upper 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(f'Constraint {ic} has no type defined.') from e
+ except TypeError as e:
+ raise TypeError(
+ 'Constraints must be a sequence of dictionaries.'
+ ) from e
+ except AttributeError as e:
+ raise TypeError("Constraint's type must be a string.") from e
+ else:
+ if ctype not in ['eq', 'ineq']:
+ raise ValueError(f"Unknown constraint type '{con['type']}'.")
+ if 'fun' not in con:
+ raise ValueError(f'Constraint {ic} has no function defined.')
+
+ lb = 0
+ if ctype == 'eq':
+ ub = 0
+ else:
+ ub = np.inf
+
+ jac = '2-point'
+ if 'args' in con:
+ args = con['args']
+ def fun(x):
+ return con["fun"](x, *args)
+ if 'jac' in con:
+ def jac(x):
+ return con["jac"](x, *args)
+ else:
+ fun = con['fun']
+ if 'jac' in con:
+ jac = con['jac']
+
+ return NonlinearConstraint(fun, lb, ub, jac)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_dcsrch.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_dcsrch.py
new file mode 100644
index 0000000000000000000000000000000000000000..f5bd95527500faa8671159454ee4514312b486b6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_dcsrch.py
@@ -0,0 +1,728 @@
+import numpy as np
+
+"""
+# 2023 - ported from minpack2.dcsrch, dcstep (Fortran) to Python
+c MINPACK-1 Project. June 1983.
+c Argonne National Laboratory.
+c Jorge J. More' and David J. Thuente.
+c
+c MINPACK-2 Project. November 1993.
+c Argonne National Laboratory and University of Minnesota.
+c Brett M. Averick, Richard G. Carter, and Jorge J. More'.
+"""
+
+# NOTE this file was linted by black on first commit, and can be kept that way.
+
+
+class DCSRCH:
+ """
+ Parameters
+ ----------
+ phi : callable phi(alpha)
+ Function at point `alpha`
+ derphi : callable phi'(alpha)
+ Objective function derivative. Returns a scalar.
+ ftol : float
+ A nonnegative tolerance for the sufficient decrease condition.
+ gtol : float
+ A nonnegative tolerance for the curvature condition.
+ xtol : float
+ A nonnegative relative tolerance for an acceptable step. The
+ subroutine exits with a warning if the relative difference between
+ sty and stx is less than xtol.
+ stpmin : float
+ A nonnegative lower bound for the step.
+ stpmax :
+ A nonnegative upper bound for the step.
+
+ Notes
+ -----
+
+ This subroutine finds a step that satisfies a sufficient
+ decrease condition and a curvature condition.
+
+ Each call of the subroutine updates an interval with
+ endpoints stx and sty. The interval is initially chosen
+ so that it contains a minimizer of the modified function
+
+ psi(stp) = f(stp) - f(0) - ftol*stp*f'(0).
+
+ If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the
+ interval is chosen so that it contains a minimizer of f.
+
+ The algorithm is designed to find a step that satisfies
+ the sufficient decrease condition
+
+ f(stp) <= f(0) + ftol*stp*f'(0),
+
+ and the curvature condition
+
+ abs(f'(stp)) <= gtol*abs(f'(0)).
+
+ If ftol is less than gtol and if, for example, the function
+ is bounded below, then there is always a step which satisfies
+ both conditions.
+
+ If no step can be found that satisfies both conditions, then
+ the algorithm stops with a warning. In this case stp only
+ satisfies the sufficient decrease condition.
+
+ A typical invocation of dcsrch has the following outline:
+
+ Evaluate the function at stp = 0.0d0; store in f.
+ Evaluate the gradient at stp = 0.0d0; store in g.
+ Choose a starting step stp.
+
+ task = 'START'
+ 10 continue
+ call dcsrch(stp,f,g,ftol,gtol,xtol,task,stpmin,stpmax,
+ isave,dsave)
+ if (task .eq. 'FG') then
+ Evaluate the function and the gradient at stp
+ go to 10
+ end if
+
+ NOTE: The user must not alter work arrays between calls.
+
+ The subroutine statement is
+
+ subroutine dcsrch(f,g,stp,ftol,gtol,xtol,stpmin,stpmax,
+ task,isave,dsave)
+ where
+
+ stp is a double precision variable.
+ On entry stp is the current estimate of a satisfactory
+ step. On initial entry, a positive initial estimate
+ must be provided.
+ On exit stp is the current estimate of a satisfactory step
+ if task = 'FG'. If task = 'CONV' then stp satisfies
+ the sufficient decrease and curvature condition.
+
+ f is a double precision variable.
+ On initial entry f is the value of the function at 0.
+ On subsequent entries f is the value of the
+ function at stp.
+ On exit f is the value of the function at stp.
+
+ g is a double precision variable.
+ On initial entry g is the derivative of the function at 0.
+ On subsequent entries g is the derivative of the
+ function at stp.
+ On exit g is the derivative of the function at stp.
+
+ ftol is a double precision variable.
+ On entry ftol specifies a nonnegative tolerance for the
+ sufficient decrease condition.
+ On exit ftol is unchanged.
+
+ gtol is a double precision variable.
+ On entry gtol specifies a nonnegative tolerance for the
+ curvature condition.
+ On exit gtol is unchanged.
+
+ xtol is a double precision variable.
+ On entry xtol specifies a nonnegative relative tolerance
+ for an acceptable step. The subroutine exits with a
+ warning if the relative difference between sty and stx
+ is less than xtol.
+
+ On exit xtol is unchanged.
+
+ task is a character variable of length at least 60.
+ On initial entry task must be set to 'START'.
+ On exit task indicates the required action:
+
+ If task(1:2) = 'FG' then evaluate the function and
+ derivative at stp and call dcsrch again.
+
+ If task(1:4) = 'CONV' then the search is successful.
+
+ If task(1:4) = 'WARN' then the subroutine is not able
+ to satisfy the convergence conditions. The exit value of
+ stp contains the best point found during the search.
+
+ If task(1:5) = 'ERROR' then there is an error in the
+ input arguments.
+
+ On exit with convergence, a warning or an error, the
+ variable task contains additional information.
+
+ stpmin is a double precision variable.
+ On entry stpmin is a nonnegative lower bound for the step.
+ On exit stpmin is unchanged.
+
+ stpmax is a double precision variable.
+ On entry stpmax is a nonnegative upper bound for the step.
+ On exit stpmax is unchanged.
+
+ isave is an integer work array of dimension 2.
+
+ dsave is a double precision work array of dimension 13.
+
+ Subprograms called
+
+ MINPACK-2 ... dcstep
+ MINPACK-1 Project. June 1983.
+ Argonne National Laboratory.
+ Jorge J. More' and David J. Thuente.
+
+ MINPACK-2 Project. November 1993.
+ Argonne National Laboratory and University of Minnesota.
+ Brett M. Averick, Richard G. Carter, and Jorge J. More'.
+ """
+
+ def __init__(self, phi, derphi, ftol, gtol, xtol, stpmin, stpmax):
+ self.stage = None
+ self.ginit = None
+ self.gtest = None
+ self.gx = None
+ self.gy = None
+ self.finit = None
+ self.fx = None
+ self.fy = None
+ self.stx = None
+ self.sty = None
+ self.stmin = None
+ self.stmax = None
+ self.width = None
+ self.width1 = None
+
+ # leave all assessment of tolerances/limits to the first call of
+ # this object
+ self.ftol = ftol
+ self.gtol = gtol
+ self.xtol = xtol
+ self.stpmin = stpmin
+ self.stpmax = stpmax
+
+ self.phi = phi
+ self.derphi = derphi
+
+ def __call__(self, alpha1, phi0=None, derphi0=None, maxiter=100):
+ """
+ Parameters
+ ----------
+ alpha1 : float
+ alpha1 is the current estimate of a satisfactory
+ step. A positive initial estimate must be provided.
+ phi0 : float
+ the value of `phi` at 0 (if known).
+ derphi0 : float
+ the derivative of `derphi` at 0 (if known).
+ maxiter : int
+
+ Returns
+ -------
+ alpha : float
+ Step size, or None if no suitable step was found.
+ phi : float
+ Value of `phi` at the new point `alpha`.
+ phi0 : float
+ Value of `phi` at `alpha=0`.
+ task : bytes
+ On exit task indicates status information.
+
+ If task[:4] == b'CONV' then the search is successful.
+
+ If task[:4] == b'WARN' then the subroutine is not able
+ to satisfy the convergence conditions. The exit value of
+ stp contains the best point found during the search.
+
+ If task[:5] == b'ERROR' then there is an error in the
+ input arguments.
+ """
+ if phi0 is None:
+ phi0 = self.phi(0.0)
+ if derphi0 is None:
+ derphi0 = self.derphi(0.0)
+
+ phi1 = phi0
+ derphi1 = derphi0
+
+ task = b"START"
+ for i in range(maxiter):
+ stp, phi1, derphi1, task = self._iterate(
+ alpha1, phi1, derphi1, task
+ )
+
+ if not np.isfinite(stp):
+ task = b"WARN"
+ stp = None
+ break
+
+ if task[:2] == b"FG":
+ alpha1 = stp
+ phi1 = self.phi(stp)
+ derphi1 = self.derphi(stp)
+ else:
+ break
+ else:
+ # maxiter reached, the line search did not converge
+ stp = None
+ task = b"WARNING: dcsrch did not converge within max iterations"
+
+ if task[:5] == b"ERROR" or task[:4] == b"WARN":
+ stp = None # failed
+
+ return stp, phi1, phi0, task
+
+ def _iterate(self, stp, f, g, task):
+ """
+ Parameters
+ ----------
+ stp : float
+ The current estimate of a satisfactory step. On initial entry, a
+ positive initial estimate must be provided.
+ f : float
+ On first call f is the value of the function at 0. On subsequent
+ entries f should be the value of the function at stp.
+ g : float
+ On initial entry g is the derivative of the function at 0. On
+ subsequent entries g is the derivative of the function at stp.
+ task : bytes
+ On initial entry task must be set to 'START'.
+
+ On exit with convergence, a warning or an error, the
+ variable task contains additional information.
+
+
+ Returns
+ -------
+ stp, f, g, task: tuple
+
+ stp : float
+ the current estimate of a satisfactory step if task = 'FG'. If
+ task = 'CONV' then stp satisfies the sufficient decrease and
+ curvature condition.
+ f : float
+ the value of the function at stp.
+ g : float
+ the derivative of the function at stp.
+ task : bytes
+ On exit task indicates the required action:
+
+ If task(1:2) == b'FG' then evaluate the function and
+ derivative at stp and call dcsrch again.
+
+ If task(1:4) == b'CONV' then the search is successful.
+
+ If task(1:4) == b'WARN' then the subroutine is not able
+ to satisfy the convergence conditions. The exit value of
+ stp contains the best point found during the search.
+
+ If task(1:5) == b'ERROR' then there is an error in the
+ input arguments.
+ """
+ p5 = 0.5
+ p66 = 0.66
+ xtrapl = 1.1
+ xtrapu = 4.0
+
+ if task[:5] == b"START":
+ if stp < self.stpmin:
+ task = b"ERROR: STP .LT. STPMIN"
+ if stp > self.stpmax:
+ task = b"ERROR: STP .GT. STPMAX"
+ if g >= 0:
+ task = b"ERROR: INITIAL G .GE. ZERO"
+ if self.ftol < 0:
+ task = b"ERROR: FTOL .LT. ZERO"
+ if self.gtol < 0:
+ task = b"ERROR: GTOL .LT. ZERO"
+ if self.xtol < 0:
+ task = b"ERROR: XTOL .LT. ZERO"
+ if self.stpmin < 0:
+ task = b"ERROR: STPMIN .LT. ZERO"
+ if self.stpmax < self.stpmin:
+ task = b"ERROR: STPMAX .LT. STPMIN"
+
+ if task[:5] == b"ERROR":
+ return stp, f, g, task
+
+ # Initialize local variables.
+
+ self.brackt = False
+ self.stage = 1
+ self.finit = f
+ self.ginit = g
+ self.gtest = self.ftol * self.ginit
+ self.width = self.stpmax - self.stpmin
+ self.width1 = self.width / p5
+
+ # The variables stx, fx, gx contain the values of the step,
+ # function, and derivative at the best step.
+ # The variables sty, fy, gy contain the value of the step,
+ # function, and derivative at sty.
+ # The variables stp, f, g contain the values of the step,
+ # function, and derivative at stp.
+
+ self.stx = 0.0
+ self.fx = self.finit
+ self.gx = self.ginit
+ self.sty = 0.0
+ self.fy = self.finit
+ self.gy = self.ginit
+ self.stmin = 0
+ self.stmax = stp + xtrapu * stp
+ task = b"FG"
+ return stp, f, g, task
+
+ # in the original Fortran this was a location to restore variables
+ # we don't need to do that because they're attributes.
+
+ # If psi(stp) <= 0 and f'(stp) >= 0 for some step, then the
+ # algorithm enters the second stage.
+ ftest = self.finit + stp * self.gtest
+
+ if self.stage == 1 and f <= ftest and g >= 0:
+ self.stage = 2
+
+ # test for warnings
+ if self.brackt and (stp <= self.stmin or stp >= self.stmax):
+ task = b"WARNING: ROUNDING ERRORS PREVENT PROGRESS"
+ if self.brackt and self.stmax - self.stmin <= self.xtol * self.stmax:
+ task = b"WARNING: XTOL TEST SATISFIED"
+ if stp == self.stpmax and f <= ftest and g <= self.gtest:
+ task = b"WARNING: STP = STPMAX"
+ if stp == self.stpmin and (f > ftest or g >= self.gtest):
+ task = b"WARNING: STP = STPMIN"
+
+ # test for convergence
+ if f <= ftest and abs(g) <= self.gtol * -self.ginit:
+ task = b"CONVERGENCE"
+
+ # test for termination
+ if task[:4] == b"WARN" or task[:4] == b"CONV":
+ return stp, f, g, task
+
+ # A modified function is used to predict the step during the
+ # first stage if a lower function value has been obtained but
+ # the decrease is not sufficient.
+ if self.stage == 1 and f <= self.fx and f > ftest:
+ # Define the modified function and derivative values.
+ fm = f - stp * self.gtest
+ fxm = self.fx - self.stx * self.gtest
+ fym = self.fy - self.sty * self.gtest
+ gm = g - self.gtest
+ gxm = self.gx - self.gtest
+ gym = self.gy - self.gtest
+
+ # Call dcstep to update stx, sty, and to compute the new step.
+ # dcstep can have several operations which can produce NaN
+ # e.g. inf/inf. Filter these out.
+ with np.errstate(invalid="ignore", over="ignore"):
+ tup = dcstep(
+ self.stx,
+ fxm,
+ gxm,
+ self.sty,
+ fym,
+ gym,
+ stp,
+ fm,
+ gm,
+ self.brackt,
+ self.stmin,
+ self.stmax,
+ )
+ self.stx, fxm, gxm, self.sty, fym, gym, stp, self.brackt = tup
+
+ # Reset the function and derivative values for f
+ self.fx = fxm + self.stx * self.gtest
+ self.fy = fym + self.sty * self.gtest
+ self.gx = gxm + self.gtest
+ self.gy = gym + self.gtest
+
+ else:
+ # Call dcstep to update stx, sty, and to compute the new step.
+ # dcstep can have several operations which can produce NaN
+ # e.g. inf/inf. Filter these out.
+
+ with np.errstate(invalid="ignore", over="ignore"):
+ tup = dcstep(
+ self.stx,
+ self.fx,
+ self.gx,
+ self.sty,
+ self.fy,
+ self.gy,
+ stp,
+ f,
+ g,
+ self.brackt,
+ self.stmin,
+ self.stmax,
+ )
+ (
+ self.stx,
+ self.fx,
+ self.gx,
+ self.sty,
+ self.fy,
+ self.gy,
+ stp,
+ self.brackt,
+ ) = tup
+
+ # Decide if a bisection step is needed
+ if self.brackt:
+ if abs(self.sty - self.stx) >= p66 * self.width1:
+ stp = self.stx + p5 * (self.sty - self.stx)
+ self.width1 = self.width
+ self.width = abs(self.sty - self.stx)
+
+ # Set the minimum and maximum steps allowed for stp.
+ if self.brackt:
+ self.stmin = min(self.stx, self.sty)
+ self.stmax = max(self.stx, self.sty)
+ else:
+ self.stmin = stp + xtrapl * (stp - self.stx)
+ self.stmax = stp + xtrapu * (stp - self.stx)
+
+ # Force the step to be within the bounds stpmax and stpmin.
+ stp = np.clip(stp, self.stpmin, self.stpmax)
+
+ # If further progress is not possible, let stp be the best
+ # point obtained during the search.
+ if (
+ self.brackt
+ and (stp <= self.stmin or stp >= self.stmax)
+ or (
+ self.brackt
+ and self.stmax - self.stmin <= self.xtol * self.stmax
+ )
+ ):
+ stp = self.stx
+
+ # Obtain another function and derivative
+ task = b"FG"
+ return stp, f, g, task
+
+
+def dcstep(stx, fx, dx, sty, fy, dy, stp, fp, dp, brackt, stpmin, stpmax):
+ """
+ Subroutine dcstep
+
+ This subroutine computes a safeguarded step for a search
+ procedure and updates an interval that contains a step that
+ satisfies a sufficient decrease and a curvature condition.
+
+ The parameter stx contains the step with the least function
+ value. If brackt is set to .true. then a minimizer has
+ been bracketed in an interval with endpoints stx and sty.
+ The parameter stp contains the current step.
+ The subroutine assumes that if brackt is set to .true. then
+
+ min(stx,sty) < stp < max(stx,sty),
+
+ and that the derivative at stx is negative in the direction
+ of the step.
+
+ The subroutine statement is
+
+ subroutine dcstep(stx,fx,dx,sty,fy,dy,stp,fp,dp,brackt,
+ stpmin,stpmax)
+
+ where
+
+ stx is a double precision variable.
+ On entry stx is the best step obtained so far and is an
+ endpoint of the interval that contains the minimizer.
+ On exit stx is the updated best step.
+
+ fx is a double precision variable.
+ On entry fx is the function at stx.
+ On exit fx is the function at stx.
+
+ dx is a double precision variable.
+ On entry dx is the derivative of the function at
+ stx. The derivative must be negative in the direction of
+ the step, that is, dx and stp - stx must have opposite
+ signs.
+ On exit dx is the derivative of the function at stx.
+
+ sty is a double precision variable.
+ On entry sty is the second endpoint of the interval that
+ contains the minimizer.
+ On exit sty is the updated endpoint of the interval that
+ contains the minimizer.
+
+ fy is a double precision variable.
+ On entry fy is the function at sty.
+ On exit fy is the function at sty.
+
+ dy is a double precision variable.
+ On entry dy is the derivative of the function at sty.
+ On exit dy is the derivative of the function at the exit sty.
+
+ stp is a double precision variable.
+ On entry stp is the current step. If brackt is set to .true.
+ then on input stp must be between stx and sty.
+ On exit stp is a new trial step.
+
+ fp is a double precision variable.
+ On entry fp is the function at stp
+ On exit fp is unchanged.
+
+ dp is a double precision variable.
+ On entry dp is the derivative of the function at stp.
+ On exit dp is unchanged.
+
+ brackt is a logical variable.
+ On entry brackt specifies if a minimizer has been bracketed.
+ Initially brackt must be set to .false.
+ On exit brackt specifies if a minimizer has been bracketed.
+ When a minimizer is bracketed brackt is set to .true.
+
+ stpmin is a double precision variable.
+ On entry stpmin is a lower bound for the step.
+ On exit stpmin is unchanged.
+
+ stpmax is a double precision variable.
+ On entry stpmax is an upper bound for the step.
+ On exit stpmax is unchanged.
+
+ MINPACK-1 Project. June 1983
+ Argonne National Laboratory.
+ Jorge J. More' and David J. Thuente.
+
+ MINPACK-2 Project. November 1993.
+ Argonne National Laboratory and University of Minnesota.
+ Brett M. Averick and Jorge J. More'.
+
+ """
+ sgn_dp = np.sign(dp)
+ sgn_dx = np.sign(dx)
+
+ # sgnd = dp * (dx / abs(dx))
+ sgnd = sgn_dp * sgn_dx
+
+ # First case: A higher function value. The minimum is bracketed.
+ # If the cubic step is closer to stx than the quadratic step, the
+ # cubic step is taken, otherwise the average of the cubic and
+ # quadratic steps is taken.
+ if fp > fx:
+ theta = 3.0 * (fx - fp) / (stp - stx) + dx + dp
+ s = max(abs(theta), abs(dx), abs(dp))
+ gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s))
+ if stp < stx:
+ gamma *= -1
+ p = (gamma - dx) + theta
+ q = ((gamma - dx) + gamma) + dp
+ r = p / q
+ stpc = stx + r * (stp - stx)
+ stpq = stx + ((dx / ((fx - fp) / (stp - stx) + dx)) / 2.0) * (stp - stx)
+ if abs(stpc - stx) <= abs(stpq - stx):
+ stpf = stpc
+ else:
+ stpf = stpc + (stpq - stpc) / 2.0
+ brackt = True
+ elif sgnd < 0.0:
+ # Second case: A lower function value and derivatives of opposite
+ # sign. The minimum is bracketed. If the cubic step is farther from
+ # stp than the secant step, the cubic step is taken, otherwise the
+ # secant step is taken.
+ theta = 3 * (fx - fp) / (stp - stx) + dx + dp
+ s = max(abs(theta), abs(dx), abs(dp))
+ gamma = s * np.sqrt((theta / s) ** 2 - (dx / s) * (dp / s))
+ if stp > stx:
+ gamma *= -1
+ p = (gamma - dp) + theta
+ q = ((gamma - dp) + gamma) + dx
+ r = p / q
+ stpc = stp + r * (stx - stp)
+ stpq = stp + (dp / (dp - dx)) * (stx - stp)
+ if abs(stpc - stp) > abs(stpq - stp):
+ stpf = stpc
+ else:
+ stpf = stpq
+ brackt = True
+ elif abs(dp) < abs(dx):
+ # Third case: A lower function value, derivatives of the same sign,
+ # and the magnitude of the derivative decreases.
+
+ # The cubic step is computed only if the cubic tends to infinity
+ # in the direction of the step or if the minimum of the cubic
+ # is beyond stp. Otherwise the cubic step is defined to be the
+ # secant step.
+ theta = 3 * (fx - fp) / (stp - stx) + dx + dp
+ s = max(abs(theta), abs(dx), abs(dp))
+
+ # The case gamma = 0 only arises if the cubic does not tend
+ # to infinity in the direction of the step.
+ gamma = s * np.sqrt(max(0, (theta / s) ** 2 - (dx / s) * (dp / s)))
+ if stp > stx:
+ gamma = -gamma
+ p = (gamma - dp) + theta
+ q = (gamma + (dx - dp)) + gamma
+ r = p / q
+ if r < 0 and gamma != 0:
+ stpc = stp + r * (stx - stp)
+ elif stp > stx:
+ stpc = stpmax
+ else:
+ stpc = stpmin
+ stpq = stp + (dp / (dp - dx)) * (stx - stp)
+
+ if brackt:
+ # A minimizer has been bracketed. If the cubic step is
+ # closer to stp than the secant step, the cubic step is
+ # taken, otherwise the secant step is taken.
+ if abs(stpc - stp) < abs(stpq - stp):
+ stpf = stpc
+ else:
+ stpf = stpq
+
+ if stp > stx:
+ stpf = min(stp + 0.66 * (sty - stp), stpf)
+ else:
+ stpf = max(stp + 0.66 * (sty - stp), stpf)
+ else:
+ # A minimizer has not been bracketed. If the cubic step is
+ # farther from stp than the secant step, the cubic step is
+ # taken, otherwise the secant step is taken.
+ if abs(stpc - stp) > abs(stpq - stp):
+ stpf = stpc
+ else:
+ stpf = stpq
+ stpf = np.clip(stpf, stpmin, stpmax)
+
+ else:
+ # Fourth case: A lower function value, derivatives of the same sign,
+ # and the magnitude of the derivative does not decrease. If the
+ # minimum is not bracketed, the step is either stpmin or stpmax,
+ # otherwise the cubic step is taken.
+ if brackt:
+ theta = 3.0 * (fp - fy) / (sty - stp) + dy + dp
+ s = max(abs(theta), abs(dy), abs(dp))
+ gamma = s * np.sqrt((theta / s) ** 2 - (dy / s) * (dp / s))
+ if stp > sty:
+ gamma = -gamma
+ p = (gamma - dp) + theta
+ q = ((gamma - dp) + gamma) + dy
+ r = p / q
+ stpc = stp + r * (sty - stp)
+ stpf = stpc
+ elif stp > stx:
+ stpf = stpmax
+ else:
+ stpf = stpmin
+
+ # Update the interval which contains a minimizer.
+ if fp > fx:
+ sty = stp
+ fy = fp
+ dy = dp
+ else:
+ if sgnd < 0:
+ sty = stx
+ fy = fx
+ dy = dx
+ stx = stp
+ fx = fp
+ dx = dp
+
+ # Compute the new step.
+ stp = stpf
+
+ return stx, fx, dx, sty, fy, dy, stp, brackt
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_differentiable_functions.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_differentiable_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..e707f3d4311b1989d3a4c69d4d63de24cb508966
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_differentiable_functions.py
@@ -0,0 +1,844 @@
+from collections import namedtuple
+
+import numpy as np
+import scipy.sparse as sps
+from ._numdiff import approx_derivative, group_columns
+from ._hessian_update_strategy import HessianUpdateStrategy
+from scipy.sparse.linalg import LinearOperator
+from scipy._lib._array_api import array_namespace, xp_copy
+from scipy._lib import array_api_extra as xpx
+from scipy._lib._util import _ScalarFunctionWrapper
+
+
+FD_METHODS = ('2-point', '3-point', 'cs')
+
+
+class _ScalarGradWrapper:
+ """
+ Wrapper class for gradient calculation
+ """
+ def __init__(
+ self,
+ grad,
+ fun=None,
+ args=None,
+ finite_diff_options=None,
+ ):
+ self.fun = fun
+ self.grad = grad
+ self.args = [] if args is None else args
+ self.finite_diff_options = finite_diff_options
+ self.ngev = 0
+ # number of function evaluations consumed by finite difference
+ self.nfev = 0
+
+ def __call__(self, x, f0=None, **kwds):
+ # Send a copy because the user may overwrite it.
+ # The user of this class might want `x` to remain unchanged.
+ if callable(self.grad):
+ g = np.atleast_1d(self.grad(np.copy(x), *self.args))
+ elif self.grad in FD_METHODS:
+ g, dct = approx_derivative(
+ self.fun,
+ x,
+ f0=f0,
+ **self.finite_diff_options,
+ )
+ self.nfev += dct['nfev']
+
+ self.ngev += 1
+ return g
+
+
+class _ScalarHessWrapper:
+ """
+ Wrapper class for hess calculation via finite differences
+ """
+ def __init__(
+ self,
+ hess,
+ x0=None,
+ grad=None,
+ args=None,
+ finite_diff_options=None,
+ ):
+ self.hess = hess
+ self.grad = grad
+ self.args = [] if args is None else args
+ self.finite_diff_options = finite_diff_options
+ # keep track of any finite difference function evaluations for grad
+ self.ngev = 0
+ self.nhev = 0
+ self.H = None
+ self._hess_func = None
+
+ if callable(hess):
+ self.H = hess(np.copy(x0), *args)
+ self.nhev += 1
+
+ if sps.issparse(self.H):
+ self._hess_func = "sparse_callable"
+ self.H = sps.csr_array(self.H)
+ elif isinstance(self.H, LinearOperator):
+ self._hess_func = "linearoperator_callable"
+ else:
+ # dense
+ self._hess_func = "dense_callable"
+ self.H = np.atleast_2d(np.asarray(self.H))
+ elif hess in FD_METHODS:
+ self._hess_func = "fd_hess"
+
+ def __call__(self, x, f0=None, **kwds):
+ match self._hess_func:
+ case "sparse_callable":
+ _h = self._sparse_callable
+ case "linearoperator_callable":
+ _h = self._linearoperator_callable
+ case "dense_callable":
+ _h = self._dense_callable
+ case "fd_hess":
+ _h = self._fd_hess
+
+ return _h(np.copy(x), f0=f0)
+
+ def _fd_hess(self, x, f0=None, **kwds):
+ self.H, dct = approx_derivative(
+ self.grad, x, f0=f0, **self.finite_diff_options
+ )
+ self.ngev += dct["nfev"]
+ return self.H
+
+ def _sparse_callable(self, x, **kwds):
+ self.nhev += 1
+ self.H = sps.csr_array(self.hess(x, *self.args))
+ return self.H
+
+ def _dense_callable(self, x, **kwds):
+ self.nhev += 1
+ self.H = np.atleast_2d(
+ np.asarray(self.hess(x, *self.args))
+ )
+ return self.H
+
+ def _linearoperator_callable(self, x, **kwds):
+ self.nhev += 1
+ self.H = self.hess(x, *self.args)
+ return self.H
+
+class ScalarFunction:
+ """Scalar function and its derivatives.
+
+ This class defines a scalar function F: R^n->R and methods for
+ computing or approximating its first and second derivatives.
+
+ Parameters
+ ----------
+ fun : callable
+ evaluates the scalar function. Must be of the form ``fun(x, *args)``,
+ where ``x`` is the argument in the form of a 1-D array and ``args`` is
+ a tuple of any additional fixed parameters needed to completely specify
+ the function. Should return a scalar.
+ x0 : array-like
+ Provides an initial set of variables for evaluating fun. Array of real
+ elements of size (n,), where 'n' is the number of independent
+ variables.
+ args : tuple, optional
+ Any additional fixed parameters needed to completely specify the scalar
+ function.
+ grad : {callable, '2-point', '3-point', 'cs'}
+ Method for computing the gradient vector.
+ If it is a callable, it should be a function that returns the gradient
+ vector:
+
+ ``grad(x, *args) -> array_like, shape (n,)``
+
+ where ``x`` is an array with shape (n,) and ``args`` is a tuple with
+ the fixed parameters.
+ Alternatively, the keywords {'2-point', '3-point', 'cs'} can be used
+ to select a finite difference scheme for numerical estimation of the
+ gradient with a relative step size. These finite difference schemes
+ obey any specified `bounds`.
+ hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy}
+ Method for computing the Hessian matrix. If it is callable, it should
+ return the Hessian matrix:
+
+ ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)``
+
+ where x is a (n,) ndarray and `args` is a tuple with the fixed
+ parameters. Alternatively, the keywords {'2-point', '3-point', 'cs'}
+ select a finite difference scheme for numerical estimation. Or, objects
+ implementing `HessianUpdateStrategy` interface can be used to
+ approximate the Hessian.
+ Whenever the gradient is estimated via finite-differences, the Hessian
+ cannot be estimated with options {'2-point', '3-point', 'cs'} and needs
+ to be estimated using one of the quasi-Newton strategies.
+ finite_diff_rel_step : None or array_like
+ Relative step size to use. The absolute step size is computed as
+ ``h = finite_diff_rel_step * sign(x0) * max(1, abs(x0))``, possibly
+ adjusted to fit into the bounds. For ``method='3-point'`` the sign
+ of `h` is ignored. If None then finite_diff_rel_step is selected
+ automatically,
+ finite_diff_bounds : tuple of array_like
+ Lower and upper bounds on independent variables. Defaults to no bounds,
+ (-np.inf, np.inf). Each bound must match the size of `x0` or be a
+ scalar, in the latter case the bound will be the same for all
+ variables. Use it to limit the range of function evaluation.
+ epsilon : None or array_like, optional
+ Absolute step size to use, possibly adjusted to fit into the bounds.
+ For ``method='3-point'`` the sign of `epsilon` is ignored. By default
+ relative steps are used, only if ``epsilon is not None`` are absolute
+ steps used.
+ workers : map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``, or
+ ``workers(grad, iterable)``, depending on what is being numerically
+ differentiated.
+ Alternatively, if `workers` is an int the task is subdivided into `workers`
+ sections and the function evaluated in parallel
+ (uses `multiprocessing.Pool `).
+ Supply -1 to use all available CPU cores.
+ It is recommended that a map-like be used instead of int, as repeated
+ calls to `approx_derivative` will incur large overhead from setting up
+ new processes.
+
+ .. versionadded:: 1.16.0
+
+ Notes
+ -----
+ This class implements a memoization logic. There are methods `fun`,
+ `grad`, hess` and corresponding attributes `f`, `g` and `H`. The following
+ things should be considered:
+
+ 1. Use only public methods `fun`, `grad` and `hess`.
+ 2. After one of the methods is called, the corresponding attribute
+ will be set. However, a subsequent call with a different argument
+ of *any* of the methods may overwrite the attribute.
+ """
+ def __init__(self, fun, x0, args, grad, hess, finite_diff_rel_step=None,
+ finite_diff_bounds=(-np.inf, np.inf), epsilon=None, workers=None):
+
+ if not callable(grad) and grad not in FD_METHODS:
+ raise ValueError(
+ f"`grad` must be either callable or one of {FD_METHODS}."
+ )
+
+ if not (callable(hess) or hess in FD_METHODS
+ or isinstance(hess, HessianUpdateStrategy)):
+ raise ValueError(
+ f"`hess` must be either callable, HessianUpdateStrategy"
+ f" or one of {FD_METHODS}."
+ )
+
+ if grad in FD_METHODS and hess in FD_METHODS:
+ raise ValueError("Whenever the gradient is estimated via "
+ "finite-differences, we require the Hessian "
+ "to be estimated using one of the "
+ "quasi-Newton strategies.")
+ self.xp = xp = array_namespace(x0)
+ _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ _dtype = xp.float64
+ if xp.isdtype(_x.dtype, "real floating"):
+ _dtype = _x.dtype
+
+ # original arguments
+ self._wrapped_fun = _ScalarFunctionWrapper(fun, args)
+ self._orig_fun = fun
+ self._orig_grad = grad
+ self._orig_hess = hess
+ self._args = args
+
+ # promotes to floating
+ self.x = xp.astype(_x, _dtype)
+ self.x_dtype = _dtype
+ self.n = self.x.size
+ self.f_updated = False
+ self.g_updated = False
+ self.H_updated = False
+
+ self._lowest_x = None
+ self._lowest_f = np.inf
+
+ # normalize workers
+ workers = workers or map
+
+ finite_diff_options = {}
+ if grad in FD_METHODS:
+ finite_diff_options["method"] = grad
+ finite_diff_options["rel_step"] = finite_diff_rel_step
+ finite_diff_options["abs_step"] = epsilon
+ finite_diff_options["bounds"] = finite_diff_bounds
+ finite_diff_options["workers"] = workers
+ finite_diff_options["full_output"] = True
+ if hess in FD_METHODS:
+ finite_diff_options["method"] = hess
+ finite_diff_options["rel_step"] = finite_diff_rel_step
+ finite_diff_options["abs_step"] = epsilon
+ finite_diff_options["as_linear_operator"] = True
+ finite_diff_options["workers"] = workers
+ finite_diff_options["full_output"] = True
+
+ # Initial function evaluation
+ self._nfev = 0
+ self._update_fun()
+
+ # Initial gradient evaluation
+ self._wrapped_grad = _ScalarGradWrapper(
+ grad,
+ fun=self._wrapped_fun,
+ args=args,
+ finite_diff_options=finite_diff_options,
+ )
+ self._update_grad()
+
+ # Hessian evaluation
+ if isinstance(hess, HessianUpdateStrategy):
+ self.H = hess
+ self.H.initialize(self.n, 'hess')
+ self.H_updated = True
+ self.x_prev = None
+ self.g_prev = None
+ _FakeCounter = namedtuple('_FakeCounter', ['ngev', 'nhev'])
+ self._wrapped_hess = _FakeCounter(ngev=0, nhev=0)
+ else:
+ if callable(hess):
+ self._wrapped_hess = _ScalarHessWrapper(
+ hess,
+ x0=x0,
+ args=args,
+ finite_diff_options=finite_diff_options
+ )
+ self.H = self._wrapped_hess.H
+ self.H_updated = True
+ elif hess in FD_METHODS:
+ self._wrapped_hess = _ScalarHessWrapper(
+ hess,
+ x0=x0,
+ args=args,
+ grad=self._wrapped_grad,
+ finite_diff_options=finite_diff_options
+ )
+ self._update_grad()
+ self.H = self._wrapped_hess(self.x, f0=self.g)
+ self.H_updated = True
+
+ @property
+ def nfev(self):
+ return self._nfev + self._wrapped_grad.nfev
+
+ @property
+ def ngev(self):
+ return self._wrapped_grad.ngev #+ self._wrapped_hess.ngev
+
+ @property
+ def nhev(self):
+ return self._wrapped_hess.nhev
+
+ def _update_x(self, x):
+ if isinstance(self._orig_hess, HessianUpdateStrategy):
+ self._update_grad()
+ self.x_prev = self.x
+ self.g_prev = self.g
+ # ensure that self.x is a copy of x. Don't store a reference
+ # otherwise the memoization doesn't work properly.
+
+ _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp)
+ self.x = self.xp.astype(_x, self.x_dtype)
+ self.f_updated = False
+ self.g_updated = False
+ self.H_updated = False
+ self._update_hess()
+ else:
+ # ensure that self.x is a copy of x. Don't store a reference
+ # otherwise the memoization doesn't work properly.
+ _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp)
+ self.x = self.xp.astype(_x, self.x_dtype)
+ self.f_updated = False
+ self.g_updated = False
+ self.H_updated = False
+
+ def _update_fun(self):
+ if not self.f_updated:
+ fx = self._wrapped_fun(self.x)
+ self._nfev += 1
+ if fx < self._lowest_f:
+ self._lowest_x = self.x
+ self._lowest_f = fx
+
+ self.f = fx
+ self.f_updated = True
+
+ def _update_grad(self):
+ if not self.g_updated:
+ if self._orig_grad in FD_METHODS:
+ self._update_fun()
+ self.g = self._wrapped_grad(self.x, f0=self.f)
+ self.g_updated = True
+
+ def _update_hess(self):
+ if not self.H_updated:
+ if self._orig_hess in FD_METHODS:
+ self._update_grad()
+ self.H = self._wrapped_hess(self.x, f0=self.g)
+ elif isinstance(self._orig_hess, HessianUpdateStrategy):
+ self._update_grad()
+ self.H.update(self.x - self.x_prev, self.g - self.g_prev)
+ else: # should be callable(hess)
+ self.H = self._wrapped_hess(self.x)
+
+ self.H_updated = True
+
+ def fun(self, x):
+ if not np.array_equal(x, self.x):
+ self._update_x(x)
+ self._update_fun()
+ return self.f
+
+ def grad(self, x):
+ if not np.array_equal(x, self.x):
+ self._update_x(x)
+ self._update_grad()
+ return self.g
+
+ def hess(self, x):
+ if not np.array_equal(x, self.x):
+ self._update_x(x)
+ self._update_hess()
+ return self.H
+
+ def fun_and_grad(self, x):
+ if not np.array_equal(x, self.x):
+ self._update_x(x)
+ self._update_fun()
+ self._update_grad()
+ return self.f, self.g
+
+
+class _VectorFunWrapper:
+ def __init__(self, fun):
+ self.fun = fun
+ self.nfev = 0
+
+ def __call__(self, x):
+ self.nfev += 1
+ return np.atleast_1d(self.fun(x))
+
+
+class _VectorJacWrapper:
+ """
+ Wrapper class for Jacobian calculation
+ """
+ def __init__(
+ self,
+ jac,
+ fun=None,
+ finite_diff_options=None,
+ sparse_jacobian=None
+ ):
+ self.fun = fun
+ self.jac = jac
+ self.finite_diff_options = finite_diff_options
+ self.sparse_jacobian = sparse_jacobian
+
+ self.njev = 0
+ # number of function evaluations consumed by finite difference
+ self.nfev = 0
+
+ def __call__(self, x, f0=None, **kwds):
+ # Send a copy because the user may overwrite it.
+ # The user of this class might want `x` to remain unchanged.
+ if callable(self.jac):
+ J = self.jac(x)
+ self.njev += 1
+ elif self.jac in FD_METHODS:
+ J, dct = approx_derivative(
+ self.fun,
+ x,
+ f0=f0,
+ **self.finite_diff_options,
+ )
+ self.nfev += dct['nfev']
+
+ if self.sparse_jacobian:
+ return sps.csr_array(J)
+ elif sps.issparse(J):
+ return J.toarray()
+ elif isinstance(J, LinearOperator):
+ return J
+ else:
+ return np.atleast_2d(J)
+
+
+class _VectorHessWrapper:
+ """
+ Wrapper class for Jacobian calculation
+ """
+ def __init__(
+ self,
+ hess,
+ jac=None,
+ finite_diff_options=None,
+ ):
+ self.jac = jac
+ self.hess = hess
+ self.finite_diff_options = finite_diff_options
+ self.nhev = 0
+ # number of jac evaluations consumed by finite difference
+ self.njev = 0
+
+ def __call__(self, x, v, J0=None, **kwds):
+ # Send a copy because the user may overwrite it.
+ # The user of this class might want `x` to remain unchanged.
+ if callable(self.hess):
+ self.nhev += 1
+ return self._callable_hess(x, v)
+ elif self.hess in FD_METHODS:
+ return self._fd_hess(x, v, J0=J0)
+
+ def _fd_hess(self, x, v, J0=None):
+ if J0 is None:
+ J0 = self.jac(x)
+ self.njev += 1
+
+ # H will be a LinearOperator
+ H = approx_derivative(self.jac_dot_v, x,
+ f0=J0.T.dot(v),
+ args=(v,),
+ **self.finite_diff_options)
+ return H
+
+ def jac_dot_v(self, x, v):
+ self.njev += 1
+ return self.jac(x).T.dot(v)
+
+ def _callable_hess(self, x, v):
+ H = self.hess(x, v)
+
+ if sps.issparse(H):
+ return sps.csr_array(H)
+ elif isinstance(H, LinearOperator):
+ return H
+ else:
+ return np.atleast_2d(np.asarray(H))
+
+
+class VectorFunction:
+ """Vector function and its derivatives.
+
+ This class defines a vector function F: R^n->R^m and methods for
+ computing or approximating its first and second derivatives.
+
+ Notes
+ -----
+ This class implements a memoization logic. There are methods `fun`,
+ `jac`, hess` and corresponding attributes `f`, `J` and `H`. The following
+ things should be considered:
+
+ 1. Use only public methods `fun`, `jac` and `hess`.
+ 2. After one of the methods is called, the corresponding attribute
+ will be set. However, a subsequent call with a different argument
+ of *any* of the methods may overwrite the attribute.
+ """
+ def __init__(self, fun, x0, jac, hess,
+ finite_diff_rel_step=None, finite_diff_jac_sparsity=None,
+ finite_diff_bounds=(-np.inf, np.inf), sparse_jacobian=None,
+ workers=None):
+ if not callable(jac) and jac not in FD_METHODS:
+ raise ValueError(f"`jac` must be either callable or one of {FD_METHODS}.")
+
+ if not (callable(hess) or hess in FD_METHODS
+ or isinstance(hess, HessianUpdateStrategy)):
+ raise ValueError("`hess` must be either callable,"
+ f"HessianUpdateStrategy or one of {FD_METHODS}.")
+
+ if jac in FD_METHODS and hess in FD_METHODS:
+ raise ValueError("Whenever the Jacobian is estimated via "
+ "finite-differences, we require the Hessian to "
+ "be estimated using one of the quasi-Newton "
+ "strategies.")
+
+ self.xp = xp = array_namespace(x0)
+ _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ _dtype = xp.float64
+ if xp.isdtype(_x.dtype, "real floating"):
+ _dtype = _x.dtype
+
+ # store original functions
+ self._orig_fun = fun
+ self._orig_jac = jac
+ self._orig_hess = hess
+
+ # promotes to floating, ensures that it's a copy
+ self.x = xp.astype(_x, _dtype)
+ self.x_dtype = _dtype
+
+ self.n = self.x.size
+ self._nfev = 0
+ self._njev = 0
+ self._nhev = 0
+ self.f_updated = False
+ self.J_updated = False
+ self.H_updated = False
+
+ # normalize workers
+ workers = workers or map
+
+ finite_diff_options = {}
+ if jac in FD_METHODS:
+ finite_diff_options["method"] = jac
+ finite_diff_options["rel_step"] = finite_diff_rel_step
+ if finite_diff_jac_sparsity is not None:
+ sparsity_groups = group_columns(finite_diff_jac_sparsity)
+ finite_diff_options["sparsity"] = (finite_diff_jac_sparsity,
+ sparsity_groups)
+ finite_diff_options["bounds"] = finite_diff_bounds
+ finite_diff_options["workers"] = workers
+ finite_diff_options["full_output"] = True
+ self.x_diff = np.copy(self.x)
+ if hess in FD_METHODS:
+ finite_diff_options["method"] = hess
+ finite_diff_options["rel_step"] = finite_diff_rel_step
+ finite_diff_options["as_linear_operator"] = True
+ # workers is not useful for evaluation of the LinearOperator
+ # produced by approx_derivative. Only two/three function
+ # evaluations are used, and the LinearOperator may persist
+ # outside the scope that workers is valid in.
+ self.x_diff = np.copy(self.x)
+ if jac in FD_METHODS and hess in FD_METHODS:
+ raise ValueError("Whenever the Jacobian is estimated via "
+ "finite-differences, we require the Hessian to "
+ "be estimated using one of the quasi-Newton "
+ "strategies.")
+
+ self.fun_wrapped = _VectorFunWrapper(fun)
+ self._update_fun()
+
+ self.v = np.zeros_like(self.f)
+ self.m = self.v.size
+
+ # Initial Jacobian Evaluation
+ if callable(jac):
+ self.J = jac(xp_copy(self.x))
+ self.J_updated = True
+ self._njev += 1
+ elif jac in FD_METHODS:
+ self.J, dct = approx_derivative(
+ self.fun_wrapped, self.x, f0=self.f, **finite_diff_options
+ )
+ self.J_updated = True
+ self._nfev += dct['nfev']
+
+ self.sparse_jacobian = False
+ if (sparse_jacobian or
+ sparse_jacobian is None and sps.issparse(self.J)):
+ # something truthy was specified for sparse_jacobian,
+ # or it turns out that the Jacobian was sparse.
+ self.J = sps.csr_array(self.J)
+ self.sparse_jacobian = True
+ elif sps.issparse(self.J):
+ self.J = self.J.toarray()
+ elif isinstance(self.J, LinearOperator):
+ pass
+ else:
+ self.J = np.atleast_2d(self.J)
+
+ self.jac_wrapped = _VectorJacWrapper(
+ jac,
+ fun=self.fun_wrapped,
+ finite_diff_options=finite_diff_options,
+ sparse_jacobian=self.sparse_jacobian
+ )
+
+ self.hess_wrapped = _VectorHessWrapper(
+ hess, jac=self.jac_wrapped, finite_diff_options=finite_diff_options
+ )
+
+ # Define Hessian
+ if callable(hess) or hess in FD_METHODS:
+ self.H = self.hess_wrapped(xp_copy(self.x), self.v, J0=self.J)
+ self.H_updated = True
+ if callable(hess):
+ self._nhev += 1
+ elif isinstance(hess, HessianUpdateStrategy):
+ self.H = hess
+ self.H.initialize(self.n, 'hess')
+ self.H_updated = True
+ self.x_prev = None
+ self.J_prev = None
+
+ @property
+ def nfev(self):
+ return self._nfev + self.jac_wrapped.nfev
+
+ @property
+ def njev(self):
+ return self._njev + self.hess_wrapped.njev
+
+ @property
+ def nhev(self):
+ return self._nhev
+
+ def _update_v(self, v):
+ if not np.array_equal(v, self.v):
+ self.v = v
+ self.H_updated = False
+
+ def _update_x(self, x):
+ if not np.array_equal(x, self.x):
+ if isinstance(self._orig_hess, HessianUpdateStrategy):
+ self._update_jac()
+ self.x_prev = self.x
+ self.J_prev = self.J
+ _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp)
+ self.x = self.xp.astype(_x, self.x_dtype)
+ self.f_updated = False
+ self.J_updated = False
+ self.H_updated = False
+ self._update_hess()
+ else:
+ _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp)
+ self.x = self.xp.astype(_x, self.x_dtype)
+ self.f_updated = False
+ self.J_updated = False
+ self.H_updated = False
+
+ def _update_fun(self):
+ if not self.f_updated:
+ self.f = self.fun_wrapped(xp_copy(self.x))
+ self._nfev += 1
+ self.f_updated = True
+
+ def _update_jac(self):
+ if not self.J_updated:
+ if self._orig_jac in FD_METHODS:
+ # need to update fun to get f0
+ self._update_fun()
+ else:
+ self._njev += 1
+
+ self.J = self.jac_wrapped(xp_copy(self.x), f0=self.f)
+ self.J_updated = True
+
+ def _update_hess(self):
+ if not self.H_updated:
+ if callable(self._orig_hess):
+ self.H = self.hess_wrapped(xp_copy(self.x), self.v)
+ self._nhev += 1
+ elif self._orig_hess in FD_METHODS:
+ self._update_jac()
+ self.H = self.hess_wrapped(xp_copy(self.x), self.v, J0=self.J)
+ elif isinstance(self._orig_hess, HessianUpdateStrategy):
+ self._update_jac()
+ # When v is updated before x was updated, then x_prev and
+ # J_prev are None and we need this check.
+ if self.x_prev is not None and self.J_prev is not None:
+ delta_x = self.x - self.x_prev
+ delta_g = self.J.T.dot(self.v) - self.J_prev.T.dot(self.v)
+ self.H.update(delta_x, delta_g)
+
+ self.H_updated = True
+
+ def fun(self, x):
+ self._update_x(x)
+ self._update_fun()
+ # returns a copy so that downstream can't overwrite the
+ # internal attribute
+ return xp_copy(self.f)
+
+ def jac(self, x):
+ self._update_x(x)
+ self._update_jac()
+ if hasattr(self.J, "astype"):
+ # returns a copy so that downstream can't overwrite the
+ # internal attribute. But one can't copy a LinearOperator
+ return self.J.astype(self.J.dtype)
+ return self.J
+
+ def hess(self, x, v):
+ # v should be updated before x.
+ self._update_v(v)
+ self._update_x(x)
+ self._update_hess()
+ if hasattr(self.H, "astype"):
+ # returns a copy so that downstream can't overwrite the
+ # internal attribute. But one can't copy non-arrays
+ return self.H.astype(self.H.dtype)
+ return self.H
+
+
+class LinearVectorFunction:
+ """Linear vector function and its derivatives.
+
+ Defines a linear function F = A x, where x is N-D vector and
+ A is m-by-n matrix. The Jacobian is constant and equals to A. The Hessian
+ is identically zero and it is returned as a csr matrix.
+ """
+ def __init__(self, A, x0, sparse_jacobian):
+ if sparse_jacobian or sparse_jacobian is None and sps.issparse(A):
+ self.J = sps.csr_array(A)
+ self.sparse_jacobian = True
+ elif sps.issparse(A):
+ self.J = A.toarray()
+ self.sparse_jacobian = False
+ else:
+ # np.asarray makes sure A is ndarray and not matrix
+ self.J = np.atleast_2d(np.asarray(A))
+ self.sparse_jacobian = False
+
+ self.m, self.n = self.J.shape
+
+ self.xp = xp = array_namespace(x0)
+ _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ _dtype = xp.float64
+ if xp.isdtype(_x.dtype, "real floating"):
+ _dtype = _x.dtype
+
+ # promotes to floating
+ self.x = xp.astype(_x, _dtype)
+ self.x_dtype = _dtype
+
+ self.f = self.J.dot(self.x)
+ self.f_updated = True
+
+ self.v = np.zeros(self.m, dtype=float)
+ self.H = sps.csr_array((self.n, self.n))
+
+ def _update_x(self, x):
+ if not np.array_equal(x, self.x):
+ _x = xpx.atleast_nd(self.xp.asarray(x), ndim=1, xp=self.xp)
+ self.x = self.xp.astype(_x, self.x_dtype)
+ self.f_updated = False
+
+ def fun(self, x):
+ self._update_x(x)
+ if not self.f_updated:
+ self.f = self.J.dot(x)
+ self.f_updated = True
+ return self.f
+
+ def jac(self, x):
+ self._update_x(x)
+ return self.J
+
+ def hess(self, x, v):
+ self._update_x(x)
+ self.v = v
+ return self.H
+
+
+class IdentityVectorFunction(LinearVectorFunction):
+ """Identity vector function and its derivatives.
+
+ The Jacobian is the identity matrix, returned as a dense array when
+ `sparse_jacobian=False` and as a csr matrix otherwise. The Hessian is
+ identically zero and it is returned as a csr matrix.
+ """
+ def __init__(self, x0, sparse_jacobian):
+ n = len(x0)
+ if sparse_jacobian or sparse_jacobian is None:
+ A = sps.eye_array(n, format='csr')
+ sparse_jacobian = True
+ else:
+ A = np.eye(n)
+ sparse_jacobian = False
+ super().__init__(A, x0, sparse_jacobian)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_differentialevolution.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_differentialevolution.py
new file mode 100644
index 0000000000000000000000000000000000000000..d836ebf26c8d26f5b7e4b3a1d0016a4aa4af9404
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_differentialevolution.py
@@ -0,0 +1,2037 @@
+"""
+differential_evolution: The differential evolution global optimization algorithm
+Added by Andrew Nelson 2014
+"""
+from functools import partial
+import warnings
+
+import numpy as np
+
+from scipy.optimize import OptimizeResult, minimize
+from scipy.optimize._constraints import (Bounds, new_bounds_to_old,
+ NonlinearConstraint, LinearConstraint)
+from scipy.optimize._optimize import _status_message, _wrap_callback
+from scipy._lib._util import (check_random_state, MapWrapper, _FunctionWrapper,
+ rng_integers, _transition_to_rng)
+from scipy._lib._sparse import issparse
+
+
+__all__ = ['differential_evolution']
+
+
+_MACHEPS = np.finfo(np.float64).eps
+
+
+@_transition_to_rng("seed", position_num=9)
+def differential_evolution(func, bounds, args=(), strategy='best1bin',
+ maxiter=1000, popsize=15, tol=0.01,
+ mutation=(0.5, 1), recombination=0.7, rng=None,
+ callback=None, disp=False, polish=True,
+ init='latinhypercube', atol=0, updating='immediate',
+ workers=1, constraints=(), x0=None, *,
+ integrality=None, vectorized=False):
+ r"""Finds the global minimum of a multivariate function.
+
+ The differential evolution method [1]_ is stochastic in nature. It does
+ not use gradient methods to find the minimum, and can search large areas
+ of candidate space, but often requires larger numbers of function
+ evaluations than conventional gradient-based techniques.
+
+ The algorithm is due to Storn and Price [2]_.
+
+ Parameters
+ ----------
+ func : callable
+ The objective function to be minimized. Must be in the form
+ ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
+ and ``args`` is a tuple of any additional fixed parameters needed to
+ completely specify the function. The number of parameters, N, is equal
+ to ``len(x)``.
+ bounds : sequence or `Bounds`
+ Bounds for variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. ``(min, max)`` pairs for each element in ``x``, defining the
+ finite lower and upper bounds for the optimizing argument of
+ `func`.
+
+ The total number of bounds is used to determine the number of
+ parameters, N. If there are parameters whose bounds are equal the total
+ number of free parameters is ``N - N_equal``.
+
+ args : tuple, optional
+ Any additional fixed parameters needed to
+ completely specify the objective function.
+ strategy : {str, callable}, optional
+ The differential evolution strategy to use. Should be one of:
+
+ - 'best1bin'
+ - 'best1exp'
+ - 'rand1bin'
+ - 'rand1exp'
+ - 'rand2bin'
+ - 'rand2exp'
+ - 'randtobest1bin'
+ - 'randtobest1exp'
+ - 'currenttobest1bin'
+ - 'currenttobest1exp'
+ - 'best2exp'
+ - 'best2bin'
+
+ The default is 'best1bin'. Strategies that may be implemented are
+ outlined in 'Notes'.
+ Alternatively the differential evolution strategy can be customized by
+ providing a callable that constructs a trial vector. The callable must
+ have the form ``strategy(candidate: int, population: np.ndarray, rng=None)``,
+ where ``candidate`` is an integer specifying which entry of the
+ population is being evolved, ``population`` is an array of shape
+ ``(S, N)`` containing all the population members (where S is the
+ total population size), and ``rng`` is the random number generator
+ being used within the solver.
+ ``candidate`` will be in the range ``[0, S)``.
+ ``strategy`` must return a trial vector with shape ``(N,)``. The
+ fitness of this trial vector is compared against the fitness of
+ ``population[candidate]``.
+
+ .. versionchanged:: 1.12.0
+ Customization of evolution strategy via a callable.
+
+ maxiter : int, optional
+ The maximum number of generations over which the entire population is
+ evolved. The maximum number of function evaluations (with no polishing)
+ is: ``(maxiter + 1) * popsize * (N - N_equal)``
+ popsize : int, optional
+ A multiplier for setting the total population size. The population has
+ ``popsize * (N - N_equal)`` individuals. This keyword is overridden if
+ an initial population is supplied via the `init` keyword. When using
+ ``init='sobol'`` the population size is calculated as the next power
+ of 2 after ``popsize * (N - N_equal)``.
+ tol : float, optional
+ Relative tolerance for convergence, the solving stops when
+ ``np.std(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``,
+ where and `atol` and `tol` are the absolute and relative tolerance
+ respectively.
+ mutation : float or tuple(float, float), optional
+ The mutation constant. In the literature this is also known as
+ differential weight, being denoted by :math:`F`.
+ If specified as a float it should be in the range [0, 2).
+ If specified as a tuple ``(min, max)`` dithering is employed. Dithering
+ randomly changes the mutation constant on a generation by generation
+ basis. The mutation constant for that generation is taken from
+ ``U[min, max)``. Dithering can help speed convergence significantly.
+ Increasing the mutation constant increases the search radius, but will
+ slow down convergence.
+ recombination : float, optional
+ The recombination constant, should be in the range [0, 1]. In the
+ literature this is also known as the crossover probability, being
+ denoted by CR. Increasing this value allows a larger number of mutants
+ to progress into the next generation, but at the risk of population
+ stability.
+ rng : `numpy.random.Generator`, optional
+ Pseudorandom number generator state. When `rng` is None, a new
+ `numpy.random.Generator` is created using entropy from the
+ operating system. Types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+ disp : bool, optional
+ Prints the evaluated `func` at every iteration.
+ callback : callable, optional
+ A callable called after each iteration. Has the signature::
+
+ callback(intermediate_result: OptimizeResult)
+
+ where ``intermediate_result`` is a keyword parameter containing an
+ `OptimizeResult` with attributes ``x`` and ``fun``, the best solution
+ found so far and the objective function. Note that the name
+ of the parameter must be ``intermediate_result`` for the callback
+ to be passed an `OptimizeResult`.
+
+ The callback also supports a signature like::
+
+ callback(x, convergence: float=val)
+
+ ``val`` represents the fractional value of the population convergence.
+ When ``val`` is greater than ``1.0``, the function halts.
+
+ Introspection is used to determine which of the signatures is invoked.
+
+ Global minimization will halt if the callback raises ``StopIteration``
+ or returns ``True``; any polishing is still carried out.
+
+ .. versionchanged:: 1.12.0
+ callback accepts the ``intermediate_result`` keyword.
+
+ polish : {bool, callable}, optional
+ If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B`
+ method is used to polish the best population member at the end, which
+ can improve the minimization slightly. If a constrained problem is
+ being studied then the `trust-constr` method is used instead. For large
+ problems with many constraints, polishing can take a long time due to
+ the Jacobian computations.
+ Alternatively supply a callable that has a `minimize`-like signature,
+ ``polish_func(func, x0, **kwds)`` and returns an `OptimizeResult`. This
+ allows the user to have fine control over how the polishing occurs.
+ `bounds` and `constraints` will be present in ``kwds``. Extra keywords
+ could be supplied to `polish_func` using `functools.partial`. It is the
+ user's responsibility to ensure that the polishing function obeys
+ bounds, any constraints (including integrality constraints), and that
+ appropriate attributes are set in the `OptimizeResult`, such as ``fun``,
+ ``x``, ``nfev``, ``jac``.
+
+ .. versionchanged:: 1.15.0
+ If `workers` is specified then the map-like callable that wraps
+ `func` is supplied to `minimize` instead of it using `func`
+ directly. This allows the caller to control how and where the
+ invocations actually run.
+
+ .. versionchanged:: 1.17.0
+ A callable obeying the `minimize` signature can be supplied to
+ polish the best population member.
+
+ init : str or array-like, optional
+ Specify which type of population initialization is performed. Should be
+ one of:
+
+ - 'latinhypercube'
+ - 'sobol'
+ - 'halton'
+ - 'random'
+ - array specifying the initial population. The array should have
+ shape ``(S, N)``, where S is the total population size and N is
+ the number of parameters.
+
+ `init` is clipped to `bounds` before use.
+
+ The default is 'latinhypercube'. Latin Hypercube sampling tries to
+ maximize coverage of the available parameter space.
+
+ 'sobol' and 'halton' are superior alternatives and maximize even more
+ the parameter space. 'sobol' will enforce an initial population
+ size which is calculated as the next power of 2 after
+ ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit
+ less efficient. See `scipy.stats.qmc` for more details.
+
+ 'random' initializes the population randomly - this has the drawback
+ that clustering can occur, preventing the whole of parameter space
+ being covered. Use of an array to specify a population could be used,
+ for example, to create a tight bunch of initial guesses in 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(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``,
+ where and `atol` and `tol` are the absolute and relative tolerance
+ respectively.
+ updating : {'immediate', 'deferred'}, optional
+ If ``'immediate'``, the best solution vector is continuously updated
+ within a single generation [4]_. This can lead to faster convergence as
+ trial vectors can take advantage of continuous improvements in the best
+ solution.
+ With ``'deferred'``, the best solution vector is updated once per
+ generation. Only ``'deferred'`` is compatible with parallelization or
+ vectorization, and the `workers` and `vectorized` keywords can
+ over-ride this option.
+
+ .. versionadded:: 1.2.0
+
+ workers : int or map-like callable, optional
+ If `workers` is an int the population is subdivided into `workers`
+ sections and evaluated in parallel
+ (uses `multiprocessing.Pool `).
+ Supply -1 to use all available CPU cores.
+ Alternatively supply a map-like callable, such as
+ `multiprocessing.Pool.map` for evaluating the population in parallel.
+ This evaluation is carried out as ``workers(func, iterable)``.
+ This option will override the `updating` keyword to
+ ``updating='deferred'`` if ``workers != 1``.
+ This option overrides the `vectorized` keyword if ``workers != 1``.
+ Requires that `func` be pickleable.
+
+ .. versionadded:: 1.2.0
+
+ constraints : {NonLinearConstraint, LinearConstraint, Bounds}
+ Constraints on the solver, over and above those applied by the `bounds`
+ kwd. Uses the approach by Lampinen [5]_.
+
+ .. versionadded:: 1.4.0
+
+ x0 : None or array-like, optional
+ Provides an initial guess to the minimization. Once the population has
+ been initialized this vector replaces the first (best) member. This
+ replacement is done even if `init` is given an initial population.
+ ``x0.shape == (N,)``.
+
+ .. versionadded:: 1.7.0
+
+ integrality : 1-D array, optional
+ For each decision variable, a boolean value indicating whether the
+ decision variable is constrained to integer values. The array is
+ broadcast to ``(N,)``.
+ If any decision variables are constrained to be integral, they will not
+ be changed during polishing.
+ Only integer values lying between the lower and upper bounds are used.
+ If there are no integer values lying between the bounds then a
+ `ValueError` is raised.
+
+ .. versionadded:: 1.9.0
+
+ vectorized : bool, optional
+ If ``vectorized is True``, `func` is sent an `x` array with
+ ``x.shape == (N, S)``, and is expected to return an array of shape
+ ``(S,)``, where `S` is the number of solution vectors to be calculated.
+ If constraints are applied, each of the functions used to construct
+ a `Constraint` object should accept an `x` array with
+ ``x.shape == (N, S)``, and return an array of shape ``(M, S)``, where
+ `M` is the number of constraint components.
+ This option is an alternative to the parallelization offered by
+ `workers`, and may help in optimization speed by reducing interpreter
+ overhead from multiple function calls. This keyword is ignored if
+ ``workers != 1``.
+ This option will override the `updating` keyword to
+ ``updating='deferred'``.
+ See the notes section for further discussion on when to use
+ ``'vectorized'``, and when to use ``'workers'``.
+
+ .. versionadded:: 1.9.0
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a `OptimizeResult` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully,
+ ``message`` which describes the cause of the termination,
+ ``population`` the solution vectors present in the population, and
+ ``population_energies`` the value of the objective function for each
+ entry in ``population``.
+ See `OptimizeResult` for a description of other attributes. If `polish`
+ was employed, and a lower minimum was obtained by the polishing, then
+ OptimizeResult also contains the ``jac`` attribute.
+ If the eventual solution does not satisfy the applied constraints
+ ``success`` will be `False`.
+
+ Notes
+ -----
+ Differential evolution is a stochastic population based method that is
+ useful for global optimization problems. At each pass through the
+ population the algorithm mutates each candidate solution by mixing with
+ other candidate solutions to create a trial candidate. There are several
+ strategies [3]_ for creating trial candidates, which suit some problems
+ more than others. The 'best1bin' strategy is a good starting point for
+ many systems. In this strategy two members of the population are randomly
+ chosen. Their difference is used to mutate the best member (the 'best' in
+ 'best1bin'), :math:`x_0`, so far:
+
+ .. math::
+
+ b' = x_0 + F \cdot (x_{r_0} - x_{r_1})
+
+ where :math:`F` is the `mutation` parameter.
+ A trial vector is then constructed. Starting with a randomly chosen ith
+ parameter the trial is sequentially filled (in modulo) with parameters
+ from ``b'`` or the original candidate. The choice of whether to use ``b'``
+ or the original candidate is made with a binomial distribution (the 'bin'
+ in 'best1bin') - a random number in [0, 1) is generated. If this number is
+ less than the `recombination` constant then the parameter is loaded from
+ ``b'``, otherwise it is loaded from the original candidate. A randomly
+ selected parameter is always loaded from ``b'``. For binomial crossover,
+ this is a single random parameter. For exponential crossover, this is the
+ starting point of a consecutive sequence of parameters from ``b'``. Once
+ the trial candidate is built its fitness is assessed. If the trial is
+ better than the original candidate then it takes its place. If it is
+ also better than the best overall candidate it also replaces that.
+
+ The other strategies available are outlined in Qiang and
+ Mitchell (2014) [3]_.
+
+
+ - ``rand1`` : :math:`b' = x_{r_0} + F \cdot (x_{r_1} - x_{r_2})`
+ - ``rand2`` : :math:`b' = x_{r_0} + F \cdot (x_{r_1} + x_{r_2} - x_{r_3} - x_{r_4})`
+ - ``best1`` : :math:`b' = x_0 + F \cdot (x_{r_0} - x_{r_1})`
+ - ``best2`` : :math:`b' = x_0 + F \cdot (x_{r_0} + x_{r_1} - x_{r_2} - x_{r_3})`
+ - ``currenttobest1`` : :math:`b' = x_i + F \cdot (x_0 - x_i + x_{r_0} - x_{r_1})`
+ - ``randtobest1`` : :math:`b' = x_{r_0} + F \cdot (x_0 - x_{r_0} + x_{r_1} - x_{r_2})`
+
+ where the integers :math:`r_0, r_1, r_2, r_3, r_4` are chosen randomly
+ from the interval [0, NP) with `NP` being the total population size and
+ the original candidate having index `i`. The user can fully customize the
+ generation of the trial candidates by supplying a callable to ``strategy``.
+
+ To improve your chances of finding a global minimum use higher `popsize`
+ values, with higher `mutation` and (dithering), but lower `recombination`
+ values. This has the effect of widening the search radius, but slowing
+ convergence.
+
+ By default the best solution vector is updated continuously within a single
+ iteration (``updating='immediate'``). This is a modification [4]_ of the
+ original differential evolution algorithm which can lead to faster
+ convergence as trial vectors can immediately benefit from improved
+ solutions. To use the original Storn and Price behaviour, updating the best
+ solution once per iteration, set ``updating='deferred'``.
+ The ``'deferred'`` approach is compatible with both parallelization and
+ vectorization (``'workers'`` and ``'vectorized'`` keywords). These may
+ improve minimization speed by using computer resources more efficiently.
+ The ``'workers'`` distribute calculations over multiple processors. By
+ default the Python `multiprocessing` module is used, but other approaches
+ are also possible, such as the Message Passing Interface (MPI) used on
+ clusters [6]_ [7]_. The overhead from these approaches (creating new
+ Processes, etc) may be significant, meaning that computational speed
+ doesn't necessarily scale with the number of processors used.
+ Parallelization is best suited to computationally expensive objective
+ functions. If the objective function is less expensive, then
+ ``'vectorized'`` may aid by only calling the objective function once per
+ iteration, rather than multiple times for all the population members; the
+ interpreter overhead is reduced.
+
+ .. versionadded:: 0.15.0
+
+ References
+ ----------
+ .. [1] Differential evolution, Wikipedia,
+ http://en.wikipedia.org/wiki/Differential_evolution
+ .. [2] Storn, R and Price, K, Differential Evolution - a Simple and
+ Efficient Heuristic for Global Optimization over Continuous Spaces,
+ Journal of Global Optimization, 1997, 11, 341 - 359.
+ .. [3] Qiang, J., Mitchell, C., A Unified Differential Evolution Algorithm
+ for Global Optimization, 2014, https://www.osti.gov/servlets/purl/1163659
+ .. [4] Wormington, M., Panaccione, C., Matney, K. M., Bowen, D. K., -
+ Characterization of structures from X-ray scattering data using
+ genetic algorithms, Phil. Trans. R. Soc. Lond. A, 1999, 357,
+ 2827-2848
+ .. [5] Lampinen, J., A constraint handling approach for the differential
+ evolution algorithm. Proceedings of the 2002 Congress on
+ Evolutionary Computation. CEC'02 (Cat. No. 02TH8600). Vol. 2. IEEE,
+ 2002.
+ .. [6] https://mpi4py.readthedocs.io/en/stable/
+ .. [7] https://schwimmbad.readthedocs.io/en/latest/
+
+
+ Examples
+ --------
+ Let us consider the problem of minimizing the Rosenbrock function. This
+ function is implemented in `rosen` in `scipy.optimize`.
+
+ >>> import numpy as np
+ >>> from scipy.optimize import rosen, differential_evolution
+ >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
+ >>> result = differential_evolution(rosen, bounds)
+ >>> result.x, result.fun
+ (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19)
+
+ Now repeat, but with parallelization.
+
+ >>> result = differential_evolution(rosen, bounds, updating='deferred',
+ ... workers=2)
+ >>> result.x, result.fun
+ (array([1., 1., 1., 1., 1.]), 1.9216496320061384e-19)
+
+ Let's do a constrained minimization.
+
+ >>> from scipy.optimize import LinearConstraint, Bounds
+
+ We add the constraint that the sum of ``x[0]`` and ``x[1]`` must be less
+ than or equal to 1.9. This is a linear constraint, which may be written
+ ``A @ x <= 1.9``, where ``A = array([[1, 1]])``. This can be encoded as
+ a `LinearConstraint` instance:
+
+ >>> lc = LinearConstraint([[1, 1]], -np.inf, 1.9)
+
+ Specify limits using a `Bounds` object.
+
+ >>> bounds = Bounds([0., 0.], [2., 2.])
+ >>> result = differential_evolution(rosen, bounds, constraints=lc,
+ ... rng=1)
+ >>> result.x, result.fun
+ (array([0.96632622, 0.93367155]), 0.0011352416852625719)
+
+ Next find the minimum of the Ackley function
+ (https://en.wikipedia.org/wiki/Test_functions_for_optimization).
+
+ >>> def ackley(x):
+ ... arg1 = -0.2 * np.sqrt(0.5 * (x[0] ** 2 + x[1] ** 2))
+ ... arg2 = 0.5 * (np.cos(2. * np.pi * x[0]) + np.cos(2. * np.pi * x[1]))
+ ... return -20. * np.exp(arg1) - np.exp(arg2) + 20. + np.e
+ >>> bounds = [(-5, 5), (-5, 5)]
+ >>> result = differential_evolution(ackley, bounds, rng=1)
+ >>> result.x, result.fun
+ (array([0., 0.]), 4.440892098500626e-16)
+
+ The Ackley function is written in a vectorized manner, so the
+ ``'vectorized'`` keyword can be employed. Note the reduced number of
+ function evaluations.
+
+ >>> result = differential_evolution(
+ ... ackley, bounds, vectorized=True, updating='deferred', rng=1
+ ... )
+ >>> result.x, result.fun
+ (array([0., 0.]), 4.440892098500626e-16)
+
+ The final polishing step can be customised by providing a callable that
+ mimics the `minimize` interface. The user is responsible for ensuring that
+ the minimizer obeys any bounds and constraints.
+
+ >>> from functools import partial
+ >>> from scipy.optimize import minimize
+ >>> # supply extra parameters to the polishing function using partial
+ >>> polish_func = partial(minimize, method="SLSQP")
+ >>> result = differential_evolution(
+ ... ackley, bounds, vectorized=True, updating='deferred', rng=1,
+ ... polish=polish_func
+ ... )
+ >>> result.x, result.fun
+ (array([0., 0.]), 4.440892098500626e-16)
+
+ The following custom strategy function mimics 'best1bin':
+
+ >>> def custom_strategy_fn(candidate, population, rng=None):
+ ... parameter_count = population.shape[-1]
+ ... mutation, recombination = 0.7, 0.9
+ ... trial = np.copy(population[candidate])
+ ... fill_point = rng.choice(parameter_count)
+ ...
+ ... pool = np.arange(len(population))
+ ... rng.shuffle(pool)
+ ...
+ ... # two unique random numbers that aren't the same, and
+ ... # aren't equal to candidate.
+ ... idxs = []
+ ... while len(idxs) < 2 and len(pool) > 0:
+ ... idx = pool[0]
+ ... pool = pool[1:]
+ ... if idx != candidate:
+ ... idxs.append(idx)
+ ...
+ ... r0, r1 = idxs[:2]
+ ...
+ ... bprime = (population[0] + mutation *
+ ... (population[r0] - population[r1]))
+ ...
+ ... crossovers = rng.uniform(size=parameter_count)
+ ... crossovers = crossovers < recombination
+ ... crossovers[fill_point] = True
+ ... trial = np.where(crossovers, bprime, trial)
+ ... return trial
+
+ """# noqa: E501
+
+ # using a context manager means that any created Pool objects are
+ # cleared up.
+ with DifferentialEvolutionSolver(func, bounds, args=args,
+ strategy=strategy,
+ maxiter=maxiter,
+ popsize=popsize, tol=tol,
+ mutation=mutation,
+ recombination=recombination,
+ rng=rng, polish=polish,
+ callback=callback,
+ disp=disp, init=init, atol=atol,
+ updating=updating,
+ workers=workers,
+ constraints=constraints,
+ x0=x0,
+ integrality=integrality,
+ vectorized=vectorized) as solver:
+ ret = solver.solve()
+
+ return ret
+
+
+class DifferentialEvolutionSolver:
+
+ """This class implements the differential evolution solver
+
+ Parameters
+ ----------
+ func : callable
+ The objective function to be minimized. Must be in the form
+ ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
+ and ``args`` is a tuple of any additional fixed parameters needed to
+ completely specify the function. The number of parameters, N, is equal
+ to ``len(x)``.
+ bounds : sequence or `Bounds`
+ Bounds for variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. ``(min, max)`` pairs for each element in ``x``, defining the
+ finite lower and upper bounds for the optimizing argument of
+ `func`.
+
+ The total number of bounds is used to determine the number of
+ parameters, N. If there are parameters whose bounds are equal the total
+ number of free parameters is ``N - N_equal``.
+ args : tuple, optional
+ Any additional fixed parameters needed to
+ completely specify the objective function.
+ strategy : {str, callable}, optional
+ The differential evolution strategy to use. Should be one of:
+
+ - 'best1bin'
+ - 'best1exp'
+ - 'rand1bin'
+ - 'rand1exp'
+ - 'rand2bin'
+ - 'rand2exp'
+ - 'randtobest1bin'
+ - 'randtobest1exp'
+ - 'currenttobest1bin'
+ - 'currenttobest1exp'
+ - 'best2exp'
+ - 'best2bin'
+
+ The default is 'best1bin'. Strategies that may be
+ implemented are outlined in 'Notes'.
+
+ Alternatively the differential evolution strategy can be customized
+ by providing a callable that constructs a trial vector. The callable
+ must have the form
+ ``strategy(candidate: int, population: np.ndarray, rng=None)``,
+ where ``candidate`` is an integer specifying which entry of the
+ population is being evolved, ``population`` is an array of shape
+ ``(S, N)`` containing all the population members (where S is the
+ total population size), and ``rng`` is the random number generator
+ being used within the solver.
+ ``candidate`` will be in the range ``[0, S)``.
+ ``strategy`` must return a trial vector with shape ``(N,)``. The
+ fitness of this trial vector is compared against the fitness of
+ ``population[candidate]``.
+ maxiter : int, optional
+ The maximum number of generations over which the entire population is
+ evolved. The maximum number of function evaluations (with no polishing)
+ is: ``(maxiter + 1) * popsize * (N - N_equal)``
+ popsize : int, optional
+ A multiplier for setting the total population size. The population has
+ ``popsize * (N - N_equal)`` individuals. This keyword is overridden if
+ an initial population is supplied via the `init` keyword. When using
+ ``init='sobol'`` the population size is calculated as the next power
+ of 2 after ``popsize * (N - N_equal)``.
+ tol : float, optional
+ Relative tolerance for convergence, the solving stops when
+ ``np.std(population_energies) <= atol + tol * np.abs(np.mean(population_energies))``,
+ where and `atol` and `tol` are the absolute and relative tolerance
+ respectively.
+ mutation : float or tuple(float, float), optional
+ The mutation constant. In the literature this is also known as
+ differential weight, being denoted by F.
+ If specified as a float it should be in the range [0, 2].
+ If specified as a tuple ``(min, max)`` dithering is employed. Dithering
+ randomly changes the mutation constant on a generation by generation
+ basis. The mutation constant for that generation is taken from
+ U[min, max). Dithering can help speed convergence significantly.
+ Increasing the mutation constant increases the search radius, but will
+ slow down convergence.
+ recombination : float, optional
+ The recombination constant, should be in the range [0, 1]. In the
+ literature this is also known as the crossover probability, being
+ denoted by CR. Increasing this value allows a larger number of mutants
+ to progress into the next generation, but at the risk of population
+ stability.
+
+ rng : {None, int, `numpy.random.Generator`}, optional
+
+ ..versionchanged:: 1.15.0
+ As part of the `SPEC-007 `_
+ transition from use of `numpy.random.RandomState` to
+ `numpy.random.Generator` this keyword was changed from `seed` to `rng`.
+ For an interim period both keywords will continue to work (only specify
+ one of them). After the interim period using the `seed` keyword will emit
+ warnings. The behavior of the `seed` and `rng` keywords is outlined below.
+
+ If `rng` is passed by keyword, types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a `Generator`.
+ If `rng` is already a `Generator` instance, then the provided instance is
+ used.
+
+ If this argument is passed by position or `seed` is passed by keyword, the
+ behavior is:
+
+ - If `seed` is None (or `np.random`), the `numpy.random.RandomState`
+ singleton is used.
+ - If `seed` is an int, a new `RandomState` instance is used,
+ seeded with `seed`.
+ - If `seed` is already a `Generator` or `RandomState` instance then
+ that instance is used.
+
+ Specify `seed`/`rng` for repeatable minimizations.
+ disp : bool, optional
+ Prints the evaluated `func` at every iteration.
+ callback : callable, optional
+ A callable called after each iteration. Has the signature:
+
+ ``callback(intermediate_result: OptimizeResult)``
+
+ where ``intermediate_result`` is a keyword parameter containing an
+ `OptimizeResult` with attributes ``x`` and ``fun``, the best solution
+ found so far and the objective function. Note that the name
+ of the parameter must be ``intermediate_result`` for the callback
+ to be passed an `OptimizeResult`.
+
+ The callback also supports a signature like:
+
+ ``callback(x, convergence: float=val)``
+
+ ``val`` represents the fractional value of the population convergence.
+ When ``val`` is greater than ``1.0``, the function halts.
+
+ Introspection is used to determine which of the signatures is invoked.
+
+ Global minimization will halt if the callback raises ``StopIteration``
+ or returns ``True``; any polishing is still carried out.
+
+ .. versionchanged:: 1.12.0
+ callback accepts the ``intermediate_result`` keyword.
+
+ polish : {bool, callable}, optional
+ If True (default), then `scipy.optimize.minimize` with the `L-BFGS-B`
+ method is used to polish the best population member at the end, which
+ can improve the minimization slightly. If a constrained problem is
+ being studied then the `trust-constr` method is used instead. For large
+ problems with many constraints, polishing can take a long time due to
+ the Jacobian computations.
+ Alternatively supply a callable that has a `minimize`-like signature,
+ ``polish_func(func, x0, **kwds)`` and returns an `OptimizeResult`. This
+ allows the user to have fine control over how the polishing occurs.
+ `bounds` and `constraints` will be present in ``kwds``. Extra keywords
+ could be supplied to `polish_func` using `functools.partial`. It is the
+ user's responsibility to ensure that the polishing function obeys
+ bounds, any constraints (including integrality constraints), and that
+ appropriate attributes are set in the `OptimizeResult`, such as ``fun``,
+ ```x``, ``nfev``, ``jac``.
+ maxfun : int, optional
+ Set the maximum number of function evaluations. However, it probably
+ makes more sense to set `maxiter` instead.
+ init : str or array-like, optional
+ Specify which type of population initialization is performed. Should be
+ one of:
+
+ - 'latinhypercube'
+ - 'sobol'
+ - 'halton'
+ - 'random'
+ - array specifying the initial population. The array should have
+ shape ``(S, N)``, where S is the total population size and
+ N is the number of parameters.
+ `init` is clipped to `bounds` before use.
+
+ The default is 'latinhypercube'. Latin Hypercube sampling tries to
+ maximize coverage of the available parameter space.
+
+ 'sobol' and 'halton' are superior alternatives and maximize even more
+ the parameter space. 'sobol' will enforce an initial population
+ size which is calculated as the next power of 2 after
+ ``popsize * (N - N_equal)``. 'halton' has no requirements but is a bit
+ less efficient. See `scipy.stats.qmc` for more details.
+
+ 'random' initializes the population randomly - this has the drawback
+ that clustering can occur, preventing the whole of parameter space
+ being covered. Use of an array to specify a population could be used,
+ for example, to create a tight bunch of initial guesses in 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'}
+ __combined = _binomial | _exponential
+
+ __init_error_msg = ("The population initialization method must be one of "
+ "'latinhypercube' or 'random', or an array of shape "
+ "(S, N) where N is the number of parameters and S>5")
+
+ def __init__(self, func, bounds, args=(),
+ strategy='best1bin', maxiter=1000, popsize=15,
+ tol=0.01, mutation=(0.5, 1), recombination=0.7, rng=None,
+ maxfun=np.inf, callback=None, disp=False, polish=True,
+ init='latinhypercube', atol=0, updating='immediate',
+ workers=1, constraints=(), x0=None, *, integrality=None,
+ vectorized=False):
+
+ if callable(strategy):
+ # a callable strategy is going to be stored in self.strategy anyway
+ pass
+ elif strategy not in self.__combined:
+ raise ValueError("Please select a valid mutation strategy")
+ self.strategy = strategy
+
+ self.callback = _wrap_callback(callback, "differential_evolution")
+ self.polish = polish
+
+ # set the updating / parallelisation options
+ if updating in ['immediate', 'deferred']:
+ self._updating = updating
+
+ self.vectorized = vectorized
+
+ # want to use parallelisation, but updating is immediate
+ if workers != 1 and updating == 'immediate':
+ warnings.warn("differential_evolution: the 'workers' keyword has"
+ " overridden updating='immediate' to"
+ " updating='deferred'", UserWarning, stacklevel=2)
+ self._updating = 'deferred'
+
+ if vectorized and workers != 1:
+ warnings.warn("differential_evolution: the 'workers' keyword"
+ " overrides the 'vectorized' keyword", stacklevel=2)
+ self.vectorized = vectorized = False
+
+ if vectorized and updating == 'immediate':
+ warnings.warn("differential_evolution: the 'vectorized' keyword"
+ " has overridden updating='immediate' to updating"
+ "='deferred'", UserWarning, stacklevel=2)
+ self._updating = 'deferred'
+
+ # an object with a map method.
+ if vectorized:
+ def maplike_for_vectorized_func(func, x):
+ # send an array (N, S) to the user func,
+ # expect to receive (S,). Transposition is required because
+ # internally the population is held as (S, N)
+ return np.atleast_1d(func(x.T))
+ workers = maplike_for_vectorized_func
+
+ self._mapwrapper = MapWrapper(workers)
+
+ # relative and absolute tolerances for convergence
+ self.tol, self.atol = tol, atol
+
+ # Mutation constant should be in [0, 2). If specified as a sequence
+ # then dithering is performed.
+ self.scale = mutation
+ if (not np.all(np.isfinite(mutation)) or
+ np.any(np.array(mutation) >= 2) or
+ np.any(np.array(mutation) < 0)):
+ raise ValueError('The mutation constant must be a float in '
+ 'U[0, 2), or specified as a tuple(min, max)'
+ ' where min < max and min, max are in U[0, 2).')
+
+ self.dither = None
+ if hasattr(mutation, '__iter__') and len(mutation) > 1:
+ self.dither = [mutation[0], mutation[1]]
+ self.dither.sort()
+
+ self.cross_over_probability = recombination
+
+ # we create a wrapped function to allow the use of map (and Pool.map
+ # in the future)
+ self.original_func = func
+ self.func = _FunctionWrapper(func, args)
+ self.args = args
+
+ # convert tuple of lower and upper bounds to limits
+ # [(low_0, high_0), ..., (low_n, high_n]
+ # -> [[low_0, ..., low_n], [high_0, ..., high_n]]
+ if isinstance(bounds, Bounds):
+ self.limits = np.array(new_bounds_to_old(bounds.lb,
+ bounds.ub,
+ len(bounds.lb)),
+ dtype=float).T
+ else:
+ self.limits = np.array(bounds, dtype='float').T
+
+ if (np.size(self.limits, 0) != 2 or not
+ np.all(np.isfinite(self.limits))):
+ raise ValueError('bounds should be a sequence containing finite '
+ 'real valued (min, max) pairs for each value'
+ ' in x')
+
+ if maxiter is None: # the default used to be None
+ maxiter = 1000
+ self.maxiter = maxiter
+ if maxfun is None: # the default used to be None
+ maxfun = np.inf
+ self.maxfun = maxfun
+
+ # population is scaled to between [0, 1].
+ # We have to scale between parameter <-> population
+ # save these arguments for _scale_parameter and
+ # _unscale_parameter. This is an optimization
+ self.__scale_arg1 = 0.5 * (self.limits[0] + self.limits[1])
+ self.__scale_arg2 = np.fabs(self.limits[0] - self.limits[1])
+ with np.errstate(divide='ignore'):
+ # if lb == ub then the following line will be 1/0, which is why
+ # we ignore the divide by zero warning. The result from 1/0 is
+ # inf, so replace those values by 0.
+ self.__recip_scale_arg2 = 1 / self.__scale_arg2
+ self.__recip_scale_arg2[~np.isfinite(self.__recip_scale_arg2)] = 0
+
+ self.parameter_count = np.size(self.limits, 1)
+
+ self.random_number_generator = check_random_state(rng)
+
+ # Which parameters are going to be integers?
+ if np.any(integrality):
+ # # user has provided a truth value for integer constraints
+ integrality = np.broadcast_to(
+ integrality,
+ self.parameter_count
+ )
+ integrality = np.asarray(integrality, bool)
+ # For integrality parameters change the limits to only allow
+ # integer values lying between the limits.
+ lb, ub = np.copy(self.limits)
+
+ lb = np.ceil(lb)
+ ub = np.floor(ub)
+ if not (lb[integrality] <= ub[integrality]).all():
+ # there's a parameter that doesn't have an integer value
+ # lying between the limits
+ raise ValueError("One of the integrality constraints does not"
+ " have any possible integer values between"
+ " the lower/upper bounds.")
+ nlb = np.nextafter(lb[integrality] - 0.5, np.inf)
+ nub = np.nextafter(ub[integrality] + 0.5, -np.inf)
+
+ self.integrality = integrality
+ self.limits[0, self.integrality] = nlb
+ self.limits[1, self.integrality] = nub
+ else:
+ self.integrality = False
+
+ # check for equal bounds
+ eb = self.limits[0] == self.limits[1]
+ eb_count = np.count_nonzero(eb)
+
+ # default population initialization is a latin hypercube design, but
+ # there are other population initializations possible.
+ # the minimum is 5 because 'best2bin' requires a population that's at
+ # least 5 long
+ # 202301 - reduced population size to account for parameters with
+ # equal bounds. If there are no varying parameters set N to at least 1
+ self.num_population_members = max(
+ 5,
+ popsize * max(1, self.parameter_count - eb_count)
+ )
+ self.population_shape = (self.num_population_members,
+ self.parameter_count)
+
+ self._nfev = 0
+ # check first str otherwise will fail to compare str with array
+ if isinstance(init, str):
+ if init == 'latinhypercube':
+ self.init_population_lhs()
+ elif init == 'sobol':
+ # must be Ns = 2**m for Sobol'
+ n_s = int(2 ** np.ceil(np.log2(self.num_population_members)))
+ self.num_population_members = n_s
+ self.population_shape = (self.num_population_members,
+ self.parameter_count)
+ self.init_population_qmc(qmc_engine='sobol')
+ elif init == 'halton':
+ self.init_population_qmc(qmc_engine='halton')
+ elif init == 'random':
+ self.init_population_random()
+ else:
+ raise ValueError(self.__init_error_msg)
+ else:
+ self.init_population_array(init)
+
+ if x0 is not None:
+ # scale to within unit interval and
+ # ensure parameters are within bounds.
+ x0_scaled = self._unscale_parameters(np.asarray(x0))
+ if ((x0_scaled > 1.0) | (x0_scaled < 0.0)).any():
+ raise ValueError(
+ "Some entries in x0 lay outside the specified bounds"
+ )
+ self.population[0] = x0_scaled
+
+ # infrastructure for constraints
+ self.constraints = constraints
+ self._wrapped_constraints = []
+
+ if hasattr(constraints, '__len__'):
+ # sequence of constraints, this will also deal with default
+ # keyword parameter
+ for c in constraints:
+ self._wrapped_constraints.append(
+ _ConstraintWrapper(c, self.x)
+ )
+ else:
+ self._wrapped_constraints = [
+ _ConstraintWrapper(constraints, self.x)
+ ]
+ self.total_constraints = np.sum(
+ [c.num_constr for c in self._wrapped_constraints]
+ )
+ self.constraint_violation = np.zeros((self.num_population_members, 1))
+ self.feasible = np.ones(self.num_population_members, bool)
+
+ # an array to shuffle when selecting candidates. Create it here
+ # rather than repeatedly creating it in _select_samples.
+ self._random_population_index = np.arange(self.num_population_members)
+ self.disp = disp
+
+ @property
+ def mutation_func(self):
+ return getattr(self, self.__combined[self.strategy])
+
+ def init_population_lhs(self):
+ """
+ Initializes the population with Latin Hypercube Sampling.
+ Latin Hypercube Sampling ensures that each parameter is uniformly
+ sampled over its range.
+ """
+ rng = self.random_number_generator
+
+ # Each parameter range needs to be sampled uniformly. The scaled
+ # parameter range ([0, 1)) needs to be split into
+ # `self.num_population_members` segments, each of which has the following
+ # size:
+ segsize = 1.0 / self.num_population_members
+
+ # Within each segment we sample from a uniform random distribution.
+ # We need to do this sampling for each parameter.
+ samples = (segsize * rng.uniform(size=self.population_shape)
+
+ # Offset each segment to cover the entire parameter range [0, 1)
+ + np.linspace(0., 1., self.num_population_members,
+ endpoint=False)[:, np.newaxis])
+
+ # Create an array for population of candidate solutions.
+ self.population = np.zeros_like(samples)
+
+ # Initialize population of candidate solutions by permutation of the
+ # random samples.
+ for j in range(self.parameter_count):
+ order = rng.permutation(range(self.num_population_members))
+ self.population[:, j] = samples[order, j]
+
+ # reset population energies
+ self.population_energies = np.full(self.num_population_members,
+ np.inf)
+
+ # reset number of function evaluations counter
+ self._nfev = 0
+
+ def init_population_qmc(self, qmc_engine):
+ """Initializes the population with a QMC method.
+
+ QMC methods ensures that each parameter is uniformly
+ sampled over its range.
+
+ Parameters
+ ----------
+ qmc_engine : str
+ The QMC method to use for initialization. Can be one of
+ ``latinhypercube``, ``sobol`` or ``halton``.
+
+ """
+ from scipy.stats import qmc
+
+ rng = self.random_number_generator
+
+ # Create an array for population of candidate solutions.
+ if qmc_engine == 'latinhypercube':
+ sampler = qmc.LatinHypercube(d=self.parameter_count, seed=rng)
+ elif qmc_engine == 'sobol':
+ sampler = qmc.Sobol(d=self.parameter_count, seed=rng)
+ elif qmc_engine == 'halton':
+ sampler = qmc.Halton(d=self.parameter_count, seed=rng)
+ else:
+ raise ValueError(self.__init_error_msg)
+
+ self.population = sampler.random(n=self.num_population_members)
+
+ # reset population energies
+ self.population_energies = np.full(self.num_population_members,
+ np.inf)
+
+ # reset number of function evaluations counter
+ self._nfev = 0
+
+ def init_population_random(self):
+ """
+ Initializes the population at random. This type of initialization
+ can possess clustering, Latin Hypercube sampling is generally better.
+ """
+ rng = self.random_number_generator
+ self.population = rng.uniform(size=self.population_shape)
+
+ # reset population energies
+ self.population_energies = np.full(self.num_population_members,
+ np.inf)
+
+ # reset number of function evaluations counter
+ self._nfev = 0
+
+ def init_population_array(self, init):
+ """
+ Initializes the population with a user specified population.
+
+ Parameters
+ ----------
+ init : np.ndarray
+ Array specifying subset of the initial population. The array should
+ have shape (S, N), where N is the number of parameters.
+ The population is clipped to the lower and upper bounds.
+ """
+ # make sure you're using a float array
+ popn = np.asarray(init, dtype=np.float64)
+
+ if (np.size(popn, 0) < 5 or
+ popn.shape[1] != self.parameter_count or
+ len(popn.shape) != 2):
+ raise ValueError("The population supplied needs to have shape"
+ " (S, len(x)), where S > 4.")
+
+ # scale values and clip to bounds, assigning to population
+ self.population = np.clip(self._unscale_parameters(popn), 0, 1)
+
+ self.num_population_members = np.size(self.population, 0)
+
+ self.population_shape = (self.num_population_members,
+ self.parameter_count)
+
+ # reset population energies
+ self.population_energies = np.full(self.num_population_members,
+ np.inf)
+
+ # reset number of function evaluations counter
+ self._nfev = 0
+
+ @property
+ def x(self):
+ """
+ The best solution from the solver
+ """
+ return self._scale_parameters(self.population[0])
+
+ @property
+ def convergence(self):
+ """
+ The standard deviation of the population energies divided by their
+ mean.
+ """
+ if np.any(np.isinf(self.population_energies)):
+ return np.inf
+ return (np.std(self.population_energies) /
+ (np.abs(np.mean(self.population_energies)) + _MACHEPS))
+
+ def converged(self):
+ """
+ Return True if the solver has converged.
+ """
+ if np.any(np.isinf(self.population_energies)):
+ return False
+
+ return (np.std(self.population_energies) <=
+ self.atol +
+ self.tol * np.abs(np.mean(self.population_energies)))
+
+ def solve(self):
+ """
+ Runs the DifferentialEvolutionSolver.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a `OptimizeResult` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully,
+ ``message`` which describes the cause of the termination,
+ ``population`` the solution vectors present in the population, and
+ ``population_energies`` the value of the objective function for
+ each entry in ``population``.
+ See `OptimizeResult` for a description of other attributes. If
+ `polish` was employed, and a lower minimum was obtained by the
+ polishing, then OptimizeResult also contains the ``jac`` attribute.
+ If the eventual solution does not satisfy the applied constraints
+ ``success`` will be `False`.
+ """
+ nit, warning_flag = 0, False
+ status_message = _status_message['success']
+
+ # The population may have just been initialized (all entries are
+ # np.inf). If it has you have to calculate the initial energies.
+ # Although this is also done in the evolve generator it's possible
+ # that someone can set maxiter=0, at which point we still want the
+ # initial energies to be calculated (the following loop isn't run).
+ if np.all(np.isinf(self.population_energies)):
+ self.feasible, self.constraint_violation = (
+ self._calculate_population_feasibilities(self.population))
+
+ # only work out population energies for feasible solutions
+ self.population_energies[self.feasible] = (
+ self._calculate_population_energies(
+ self.population[self.feasible]))
+
+ self._promote_lowest_energy()
+
+ # do the optimization.
+ for nit in range(1, self.maxiter + 1):
+ # evolve the population by a generation
+ try:
+ next(self)
+ except StopIteration:
+ warning_flag = True
+ if self._nfev > self.maxfun:
+ status_message = _status_message['maxfev']
+ elif self._nfev == self.maxfun:
+ status_message = ('Maximum number of function evaluations'
+ ' has been reached.')
+ break
+
+ if self.disp:
+ print(f"differential_evolution step {nit}: f(x)="
+ f" {self.population_energies[0]}"
+ )
+
+ if self.callback:
+ c = self.tol / (self.convergence + _MACHEPS)
+ res = self._result(nit=nit, message="in progress")
+ res.convergence = c
+ try:
+ warning_flag = bool(self.callback(res))
+ except StopIteration:
+ warning_flag = True
+
+ if warning_flag:
+ status_message = 'callback function requested stop early'
+
+ # should the solver terminate?
+ if warning_flag or self.converged():
+ break
+
+ else:
+ status_message = _status_message['maxiter']
+ warning_flag = True
+
+ DE_result = self._result(
+ nit=nit, message=status_message, warning_flag=warning_flag
+ )
+
+ if self.polish and not np.all(self.integrality):
+ # can't polish if all the parameters are integers
+ if np.any(self.integrality):
+ # set the lower/upper bounds equal so that any integrality
+ # constraints work.
+ limits, integrality = self.limits, self.integrality
+ limits[0, integrality] = DE_result.x[integrality]
+ limits[1, integrality] = DE_result.x[integrality]
+
+ polish_method = 'L-BFGS-B'
+
+ if self._wrapped_constraints:
+ polish_method = 'trust-constr'
+
+ constr_violation = self._constraint_violation_fn(DE_result.x)
+ if np.any(constr_violation > 0.):
+ warnings.warn("differential evolution didn't find a "
+ "solution satisfying the constraints, "
+ "attempting to polish from the least "
+ "infeasible solution",
+ UserWarning, stacklevel=2)
+
+ pf = self.polish
+ _f = self.original_func
+ if not callable(pf):
+ pf = partial(minimize, method=polish_method)
+ def _f(x):
+ return list(self._mapwrapper(self.func, np.atleast_2d(x)))[0]
+
+ if self.disp:
+ print(f"Polishing solution with '{polish_method}'")
+
+ result = pf(
+ _f,
+ np.copy(DE_result.x),
+ bounds=Bounds(lb=self.limits[0], ub=self.limits[1]),
+ constraints=self.constraints
+ )
+
+ if not isinstance(result, OptimizeResult):
+ raise ValueError(
+ "The result from a user defined polishing function "
+ "should return an OptimizeResult."
+ )
+
+ self._nfev += result.get("nfev", 0)
+ DE_result.nfev = self._nfev
+
+ # Polishing solution is only accepted if there is an improvement in
+ # cost function, the polishing was successful and the solution lies
+ # within the bounds.
+ if (result.fun < DE_result.fun and
+ result.success and
+ np.all(result.x <= self.limits[1]) and
+ np.all(self.limits[0] <= result.x)):
+ DE_result.fun = result.fun
+ DE_result.x = result.x
+ DE_result.jac = result.get("jac", None)
+ # to keep internal state consistent
+ self.population_energies[0] = result.fun
+ self.population[0] = self._unscale_parameters(result.x)
+
+ if self._wrapped_constraints:
+ DE_result.constr = [c.violation(DE_result.x) for
+ c in self._wrapped_constraints]
+ DE_result.constr_violation = np.max(
+ np.concatenate(DE_result.constr))
+ DE_result.maxcv = DE_result.constr_violation
+ if DE_result.maxcv > 0:
+ # if the result is infeasible then success must be False
+ DE_result.success = False
+ DE_result.message = ("The solution does not satisfy the "
+ f"constraints, MAXCV = {DE_result.maxcv}")
+
+ return DE_result
+
+ def _result(self, **kwds):
+ # form an intermediate OptimizeResult
+ nit = kwds.get('nit', None)
+ message = kwds.get('message', None)
+ warning_flag = kwds.get('warning_flag', False)
+ result = OptimizeResult(
+ x=self.x,
+ fun=self.population_energies[0],
+ nfev=self._nfev,
+ nit=nit,
+ message=message,
+ success=(warning_flag is not True),
+ population=self._scale_parameters(self.population),
+ population_energies=self.population_energies
+ )
+ if self._wrapped_constraints:
+ result.constr = [c.violation(result.x)
+ for c in self._wrapped_constraints]
+ result.constr_violation = np.max(np.concatenate(result.constr))
+ result.maxcv = result.constr_violation
+ if result.maxcv > 0:
+ result.success = False
+
+ return result
+
+ def _calculate_population_energies(self, population):
+ """
+ Calculate the energies of a population.
+
+ Parameters
+ ----------
+ population : ndarray
+ An array of parameter vectors normalised to [0, 1] using lower
+ and upper limits. Has shape ``(np.size(population, 0), N)``.
+
+ Returns
+ -------
+ energies : ndarray
+ An array of energies corresponding to each population member. If
+ maxfun will be exceeded during this call, then the number of
+ function evaluations will be reduced and energies will be
+ right-padded with np.inf. Has shape ``(np.size(population, 0),)``
+ """
+ num_members = np.size(population, 0)
+ # S is the number of function evals left to stay under the
+ # maxfun budget
+ S = min(num_members, self.maxfun - self._nfev)
+
+ energies = np.full(num_members, np.inf)
+
+ parameters_pop = self._scale_parameters(population)
+ try:
+ calc_energies = list(
+ self._mapwrapper(self.func, parameters_pop[0:S])
+ )
+ calc_energies = np.squeeze(calc_energies)
+ except (TypeError, ValueError) as e:
+ # wrong number of arguments for _mapwrapper
+ # or wrong length returned from the mapper
+ raise RuntimeError(
+ "The map-like callable must be of the form f(func, iterable), "
+ "returning a sequence of numbers the same length as 'iterable'"
+ ) from e
+
+ if calc_energies.size != S:
+ if self.vectorized:
+ raise RuntimeError("The vectorized function must return an"
+ " array of shape (S,) when given an array"
+ " of shape (len(x), S)")
+ raise RuntimeError("func(x, *args) must return a scalar value")
+
+ energies[0:S] = calc_energies
+
+ if self.vectorized:
+ self._nfev += 1
+ else:
+ self._nfev += S
+
+ return energies
+
+ def _promote_lowest_energy(self):
+ # swaps 'best solution' into first population entry
+
+ idx = np.arange(self.num_population_members)
+ feasible_solutions = idx[self.feasible]
+ if feasible_solutions.size:
+ # find the best feasible solution
+ idx_t = np.argmin(self.population_energies[feasible_solutions])
+ l = feasible_solutions[idx_t]
+ else:
+ # no solution was feasible, use 'best' infeasible solution, which
+ # will violate constraints the least
+ l = np.argmin(np.sum(self.constraint_violation, axis=1))
+
+ self.population_energies[[0, l]] = self.population_energies[[l, 0]]
+ self.population[[0, l], :] = self.population[[l, 0], :]
+ self.feasible[[0, l]] = self.feasible[[l, 0]]
+ self.constraint_violation[[0, l], :] = (
+ self.constraint_violation[[l, 0], :])
+
+ def _constraint_violation_fn(self, x):
+ """
+ Calculates total constraint violation for all the constraints, for a
+ set of solutions.
+
+ Parameters
+ ----------
+ x : ndarray
+ Solution vector(s). Has shape (S, N), or (N,), where S is the
+ number of solutions to investigate and N is the number of
+ parameters.
+
+ Returns
+ -------
+ cv : ndarray
+ Total violation of constraints. Has shape ``(S, M)``, where M is
+ the total number of constraint components (which is not necessarily
+ equal to len(self._wrapped_constraints)).
+ """
+ # how many solution vectors you're calculating constraint violations
+ # for
+ S = np.size(x) // self.parameter_count
+ _out = np.zeros((S, self.total_constraints))
+ offset = 0
+ for con in self._wrapped_constraints:
+ # the input/output of the (vectorized) constraint function is
+ # {(N, S), (N,)} --> (M, S)
+ # The input to _constraint_violation_fn is (S, N) or (N,), so
+ # transpose to pass it to the constraint. The output is transposed
+ # from (M, S) to (S, M) for further use.
+ c = con.violation(x.T).T
+
+ # The shape of c should be (M,), (1, M), or (S, M). Check for
+ # those shapes, as an incorrect shape indicates that the
+ # user constraint function didn't return the right thing, and
+ # the reshape operation will fail. Intercept the wrong shape
+ # to give a reasonable error message. I'm not sure what failure
+ # modes an inventive user will come up with.
+ if c.shape[-1] != con.num_constr or (S > 1 and c.shape[0] != S):
+ raise RuntimeError("An array returned from a Constraint has"
+ " the wrong shape. If `vectorized is False`"
+ " the Constraint should return an array of"
+ " shape (M,). If `vectorized is True` then"
+ " the Constraint must return an array of"
+ " shape (M, S), where S is the number of"
+ " solution vectors and M is the number of"
+ " constraint components in a given"
+ " Constraint object.")
+
+ # the violation function may return a 1D array, but is it a
+ # sequence of constraints for one solution (S=1, M>=1), or the
+ # value of a single constraint for a sequence of solutions
+ # (S>=1, M=1)
+ c = np.reshape(c, (S, con.num_constr))
+ _out[:, offset:offset + con.num_constr] = c
+ offset += con.num_constr
+
+ return _out
+
+ def _calculate_population_feasibilities(self, population):
+ """
+ Calculate the feasibilities of a population.
+
+ Parameters
+ ----------
+ population : ndarray
+ An array of parameter vectors normalised to [0, 1] using lower
+ and upper limits. Has shape ``(np.size(population, 0), N)``.
+
+ Returns
+ -------
+ feasible, constraint_violation : ndarray, ndarray
+ Boolean array of feasibility for each population member, and an
+ array of the constraint violation for each population member.
+ constraint_violation has shape ``(np.size(population, 0), M)``,
+ where M is the number of constraints.
+ """
+ num_members = np.size(population, 0)
+ if not self._wrapped_constraints:
+ # shortcut for no constraints
+ return np.ones(num_members, bool), np.zeros((num_members, 1))
+
+ # (S, N)
+ parameters_pop = self._scale_parameters(population)
+
+ if self.vectorized:
+ # (S, M)
+ constraint_violation = np.array(
+ self._constraint_violation_fn(parameters_pop)
+ )
+ else:
+ # (S, 1, M)
+ constraint_violation = np.array([self._constraint_violation_fn(x)
+ for x in parameters_pop])
+ # if you use the list comprehension in the line above it will
+ # create an array of shape (S, 1, M), because each iteration
+ # generates an array of (1, M). In comparison the vectorized
+ # version returns (S, M). It's therefore necessary to remove axis 1
+ constraint_violation = constraint_violation[:, 0]
+
+ feasible = ~(np.sum(constraint_violation, axis=1) > 0)
+
+ return feasible, constraint_violation
+
+ def __iter__(self):
+ return self
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return self._mapwrapper.__exit__(*args)
+
+ def _accept_trial(self, energy_trial, feasible_trial, cv_trial,
+ energy_orig, feasible_orig, cv_orig):
+ """
+ Trial is accepted if:
+ * it satisfies all constraints and provides a lower or equal objective
+ function value, while both the compared solutions are feasible
+ - or -
+ * it is feasible while the original solution is infeasible,
+ - or -
+ * it is infeasible, but provides a lower or equal constraint violation
+ for all constraint functions.
+
+ This test corresponds to section III of Lampinen [1]_.
+
+ Parameters
+ ----------
+ energy_trial : float
+ Energy of the trial solution
+ feasible_trial : float
+ Feasibility of trial solution
+ cv_trial : array-like
+ Excess constraint violation for the trial solution
+ energy_orig : float
+ Energy of the original solution
+ feasible_orig : float
+ Feasibility of original solution
+ cv_orig : array-like
+ Excess constraint violation for the original solution
+
+ Returns
+ -------
+ accepted : bool
+
+ """
+ if feasible_orig and feasible_trial:
+ return energy_trial <= energy_orig
+ elif feasible_trial and not feasible_orig:
+ return True
+ elif not feasible_trial and (cv_trial <= cv_orig).all():
+ # cv_trial < cv_orig would imply that both trial and orig are not
+ # feasible
+ return True
+
+ return False
+
+ def __next__(self):
+ """
+ Evolve the population by a single generation
+
+ Returns
+ -------
+ x : ndarray
+ The best solution from the solver.
+ fun : float
+ Value of objective function obtained from the best solution.
+ """
+ # the population may have just been initialized (all entries are
+ # np.inf). If it has you have to calculate the initial energies
+ if np.all(np.isinf(self.population_energies)):
+ self.feasible, self.constraint_violation = (
+ self._calculate_population_feasibilities(self.population))
+
+ # only need to work out population energies for those that are
+ # feasible
+ self.population_energies[self.feasible] = (
+ self._calculate_population_energies(
+ self.population[self.feasible]))
+
+ self._promote_lowest_energy()
+
+ if self.dither is not None:
+ self.scale = self.random_number_generator.uniform(self.dither[0],
+ self.dither[1])
+
+ if self._updating == 'immediate':
+ # update best solution immediately
+ for candidate in range(self.num_population_members):
+ if self._nfev > self.maxfun:
+ raise StopIteration
+
+ # create a trial solution
+ trial = self._mutate(candidate)
+
+ # ensuring that it's in the range [0, 1)
+ self._ensure_constraint(trial)
+
+ # scale from [0, 1) to the actual parameter value
+ parameters = self._scale_parameters(trial)
+
+ # determine the energy of the objective function
+ if self._wrapped_constraints:
+ cv = self._constraint_violation_fn(parameters)
+ feasible = False
+ energy = np.inf
+ if not np.sum(cv) > 0:
+ # solution is feasible
+ feasible = True
+ energy = self.func(parameters)
+ self._nfev += 1
+ else:
+ feasible = True
+ cv = np.atleast_2d([0.])
+ energy = self.func(parameters)
+ self._nfev += 1
+
+ # compare trial and population member
+ if self._accept_trial(energy, feasible, cv,
+ self.population_energies[candidate],
+ self.feasible[candidate],
+ self.constraint_violation[candidate]):
+ self.population[candidate] = trial
+ self.population_energies[candidate] = np.squeeze(energy)
+ self.feasible[candidate] = feasible
+ self.constraint_violation[candidate] = cv
+
+ # if the trial candidate is also better than the best
+ # solution then promote it.
+ if self._accept_trial(energy, feasible, cv,
+ self.population_energies[0],
+ self.feasible[0],
+ self.constraint_violation[0]):
+ self._promote_lowest_energy()
+
+ elif self._updating == 'deferred':
+ # update best solution once per generation
+ if self._nfev >= self.maxfun:
+ raise StopIteration
+
+ # 'deferred' approach, vectorised form.
+ # create trial solutions
+ trial_pop = self._mutate_many(
+ np.arange(self.num_population_members)
+ )
+
+ # enforce bounds
+ self._ensure_constraint(trial_pop)
+
+ # determine the energies of the objective function, but only for
+ # feasible trials
+ feasible, cv = self._calculate_population_feasibilities(trial_pop)
+ trial_energies = np.full(self.num_population_members, np.inf)
+
+ # only calculate for feasible entries
+ trial_energies[feasible] = self._calculate_population_energies(
+ trial_pop[feasible])
+
+ # which solutions are 'improved'?
+ loc = [self._accept_trial(*val) for val in
+ zip(trial_energies, feasible, cv, self.population_energies,
+ self.feasible, self.constraint_violation)]
+ loc = np.array(loc)
+ self.population = np.where(loc[:, np.newaxis],
+ trial_pop,
+ self.population)
+ self.population_energies = np.where(loc,
+ trial_energies,
+ self.population_energies)
+ self.feasible = np.where(loc,
+ feasible,
+ self.feasible)
+ self.constraint_violation = np.where(loc[:, np.newaxis],
+ cv,
+ self.constraint_violation)
+
+ # make sure the best solution is updated if updating='deferred'.
+ # put the lowest energy into the best solution position.
+ self._promote_lowest_energy()
+
+ return self.x, self.population_energies[0]
+
+ def _scale_parameters(self, trial):
+ """Scale from a number between 0 and 1 to parameters."""
+ # trial either has shape (N, ) or (L, N), where L is the number of
+ # solutions being scaled
+ scaled = self.__scale_arg1 + (trial - 0.5) * self.__scale_arg2
+ if np.count_nonzero(self.integrality):
+ i = np.broadcast_to(self.integrality, scaled.shape)
+ scaled[i] = np.round(scaled[i])
+ return scaled
+
+ def _unscale_parameters(self, parameters):
+ """Scale from parameters to a number between 0 and 1."""
+ return (parameters - self.__scale_arg1) * self.__recip_scale_arg2 + 0.5
+
+ def _ensure_constraint(self, trial):
+ """Make sure the parameters lie between the limits."""
+ mask = np.bitwise_or(trial > 1, trial < 0)
+ if oob := np.count_nonzero(mask):
+ trial[mask] = self.random_number_generator.uniform(size=oob)
+
+ def _mutate_custom(self, candidate):
+ rng = self.random_number_generator
+ msg = (
+ "strategy must have signature"
+ " f(candidate: int, population: np.ndarray, rng=None) returning an"
+ " array of shape (N,)"
+ )
+ _population = self._scale_parameters(self.population)
+ if not len(np.shape(candidate)):
+ # single entry in population
+ trial = self.strategy(candidate, _population, rng=rng)
+ if trial.shape != (self.parameter_count,):
+ raise RuntimeError(msg)
+ else:
+ S = candidate.shape[0]
+ trial = np.array(
+ [self.strategy(c, _population, rng=rng) for c in candidate],
+ dtype=float
+ )
+ if trial.shape != (S, self.parameter_count):
+ raise RuntimeError(msg)
+ return self._unscale_parameters(trial)
+
+ def _mutate_many(self, candidates):
+ """Create trial vectors based on a mutation strategy."""
+ rng = self.random_number_generator
+
+ S = len(candidates)
+ if callable(self.strategy):
+ return self._mutate_custom(candidates)
+
+ trial = np.copy(self.population[candidates])
+ samples = np.array([self._select_samples(c, 5) for c in candidates])
+
+ if self.strategy in ['currenttobest1exp', 'currenttobest1bin']:
+ bprime = self.mutation_func(candidates, samples)
+ else:
+ bprime = self.mutation_func(samples)
+
+ fill_point = rng_integers(rng, self.parameter_count, size=S)
+ crossovers = rng.uniform(size=(S, self.parameter_count))
+ crossovers = crossovers < self.cross_over_probability
+ if self.strategy in self._binomial:
+ # A randomly selected parameter is always from the bprime vector for
+ # binomial crossover. The fill_point ensures at least one parameter
+ # comes from bprime, preventing the possibility of no mutation
+ # influence in the trial vector.
+ i = np.arange(S)
+ crossovers[i, fill_point[i]] = True
+ trial = np.where(crossovers, bprime, trial)
+ return trial
+
+ elif self.strategy in self._exponential:
+ # For exponential crossover, fill_point determines the starting index
+ # for a consecutive sequence of parameters from bprime. The sequence
+ # continues until a crossover probability check fails. The starting
+ # index is always from the bprime vector ensuring at least one
+ # parameter comes from bprime.
+ crossovers[..., 0] = True
+ for j in range(S):
+ i = 0
+ init_fill = fill_point[j]
+ while (i < self.parameter_count and crossovers[j, i]):
+ trial[j, init_fill] = bprime[j, init_fill]
+ init_fill = (init_fill + 1) % self.parameter_count
+ i += 1
+
+ return trial
+
+ def _mutate(self, candidate):
+ """Create a trial vector based on a mutation strategy."""
+ rng = self.random_number_generator
+
+ if callable(self.strategy):
+ return self._mutate_custom(candidate)
+
+ fill_point = rng_integers(rng, self.parameter_count)
+ samples = self._select_samples(candidate, 5)
+
+ trial = np.copy(self.population[candidate])
+
+ if self.strategy in ['currenttobest1exp', 'currenttobest1bin']:
+ bprime = self.mutation_func(candidate, samples)
+ else:
+ bprime = self.mutation_func(samples)
+
+ crossovers = rng.uniform(size=self.parameter_count)
+ crossovers = crossovers < self.cross_over_probability
+ if self.strategy in self._binomial:
+ # A randomly selected parameter is always from the bprime vector for
+ # binomial crossover. The fill_point ensures at least one parameter
+ # comes from bprime, preventing the possibility of no mutation
+ # influence in the trial vector.
+ crossovers[fill_point] = True
+ trial = np.where(crossovers, bprime, trial)
+ return trial
+
+ elif self.strategy in self._exponential:
+ # For exponential crossover, fill_point determines the starting index
+ # for a consecutive sequence of parameters from bprime. The sequence
+ # continues until a crossover probability check fails. The starting
+ # index is always from the bprime vector ensuring at least one
+ # parameter comes from bprime.
+ i = 0
+ crossovers[0] = True
+ while i < self.parameter_count and crossovers[i]:
+ trial[fill_point] = bprime[fill_point]
+ fill_point = (fill_point + 1) % self.parameter_count
+ i += 1
+
+ return trial
+
+ def _best1(self, samples):
+ """best1bin, best1exp"""
+ # samples.shape == (S, 5)
+ # or
+ # samples.shape(5,)
+ r0, r1 = samples[..., :2].T
+ return (self.population[0] + self.scale *
+ (self.population[r0] - self.population[r1]))
+
+ def _rand1(self, samples):
+ """rand1bin, rand1exp"""
+ r0, r1, r2 = samples[..., :3].T
+ return (self.population[r0] + self.scale *
+ (self.population[r1] - self.population[r2]))
+
+ def _randtobest1(self, samples):
+ """randtobest1bin, randtobest1exp"""
+ r0, r1, r2 = samples[..., :3].T
+ bprime = np.copy(self.population[r0])
+ bprime += self.scale * (self.population[0] - bprime)
+ bprime += self.scale * (self.population[r1] -
+ self.population[r2])
+ return bprime
+
+ def _currenttobest1(self, candidate, samples):
+ """currenttobest1bin, currenttobest1exp"""
+ r0, r1 = samples[..., :2].T
+ bprime = (self.population[candidate] + self.scale *
+ (self.population[0] - self.population[candidate] +
+ self.population[r0] - self.population[r1]))
+ return bprime
+
+ def _best2(self, samples):
+ """best2bin, best2exp"""
+ r0, r1, r2, r3 = samples[..., :4].T
+ bprime = (self.population[0] + self.scale *
+ (self.population[r0] + self.population[r1] -
+ self.population[r2] - self.population[r3]))
+
+ return bprime
+
+ def _rand2(self, samples):
+ """rand2bin, rand2exp"""
+ r0, r1, r2, r3, r4 = samples[..., :5].T
+ bprime = (self.population[r0] + self.scale *
+ (self.population[r1] + self.population[r2] -
+ self.population[r3] - self.population[r4]))
+
+ return bprime
+
+ def _select_samples(self, candidate, number_samples):
+ """
+ obtain random integers from range(self.num_population_members),
+ without replacement. You can't have the original candidate either.
+ """
+ self.random_number_generator.shuffle(self._random_population_index)
+ idxs = self._random_population_index[:number_samples + 1]
+ return idxs[idxs != candidate][:number_samples]
+
+
+class _ConstraintWrapper:
+ """Object to wrap/evaluate user defined constraints.
+
+ Very similar in practice to `PreparedConstraint`, except that no evaluation
+ of jac/hess is performed (explicit or implicit).
+
+ If created successfully, it will contain the attributes listed below.
+
+ Parameters
+ ----------
+ constraint : {`NonlinearConstraint`, `LinearConstraint`, `Bounds`}
+ Constraint to check and prepare.
+ x0 : array_like
+ Initial vector of independent variables, shape (N,)
+
+ Attributes
+ ----------
+ fun : callable
+ Function defining the constraint wrapped by one of the convenience
+ classes.
+ bounds : 2-tuple
+ Contains lower and upper bounds for the constraints --- lb and ub.
+ These are converted to ndarray and have a size equal to the number of
+ the constraints.
+
+ Notes
+ -----
+ _ConstraintWrapper.fun and _ConstraintWrapper.violation can get sent
+ arrays of shape (N, S) or (N,), where S is the number of vectors of shape
+ (N,) to consider constraints for.
+ """
+ def __init__(self, constraint, x0):
+ self.constraint = constraint
+
+ if isinstance(constraint, NonlinearConstraint):
+ def fun(x):
+ x = np.asarray(x)
+ return np.atleast_1d(constraint.fun(x))
+ elif isinstance(constraint, LinearConstraint):
+ def fun(x):
+ if issparse(constraint.A):
+ A = constraint.A
+ else:
+ A = np.atleast_2d(constraint.A)
+
+ res = A.dot(x)
+ # x either has shape (N, S) or (N)
+ # (M, N) x (N, S) --> (M, S)
+ # (M, N) x (N,) --> (M,)
+ # However, if (M, N) is a matrix then:
+ # (M, N) * (N,) --> (M, 1), we need this to be (M,)
+ if x.ndim == 1 and res.ndim == 2:
+ # deal with case that constraint.A is an np.matrix
+ # see gh20041
+ res = np.asarray(res)[:, 0]
+
+ return res
+ elif isinstance(constraint, Bounds):
+ def fun(x):
+ return np.asarray(x)
+ else:
+ raise ValueError("`constraint` of an unknown type is passed.")
+
+ self.fun = fun
+
+ lb = np.asarray(constraint.lb, dtype=float)
+ ub = np.asarray(constraint.ub, dtype=float)
+
+ x0 = np.asarray(x0)
+
+ # find out the number of constraints
+ f0 = fun(x0)
+ self.num_constr = m = f0.size
+ self.parameter_count = x0.size
+
+ if lb.ndim == 0:
+ lb = np.resize(lb, m)
+ if ub.ndim == 0:
+ ub = np.resize(ub, m)
+
+ self.bounds = (lb, ub)
+
+ def __call__(self, x):
+ return np.atleast_1d(self.fun(x))
+
+ def violation(self, x):
+ """How much the constraint is exceeded by.
+
+ Parameters
+ ----------
+ x : array-like
+ Vector of independent variables, (N, S), where N is number of
+ parameters and S is the number of solutions to be investigated.
+
+ Returns
+ -------
+ excess : array-like
+ How much the constraint is exceeded by, for each of the
+ constraints specified by `_ConstraintWrapper.fun`.
+ Has shape (M, S) where M is the number of constraint components.
+ """
+ # expect ev to have shape (num_constr, S) or (num_constr,)
+ ev = self.fun(np.asarray(x))
+
+ try:
+ excess_lb = np.maximum(self.bounds[0] - ev.T, 0)
+ excess_ub = np.maximum(ev.T - self.bounds[1], 0)
+ except ValueError as e:
+ raise RuntimeError("An array returned from a Constraint has"
+ " the wrong shape. If `vectorized is False`"
+ " the Constraint should return an array of"
+ " shape (M,). If `vectorized is True` then"
+ " the Constraint must return an array of"
+ " shape (M, S), where S is the number of"
+ " solution vectors and M is the number of"
+ " constraint components in a given"
+ " Constraint object.") from e
+
+ v = (excess_lb + excess_ub).T
+ return v
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_direct.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_direct.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..d939dfc8140dc680445be554738b87c8d1006c35
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_direct.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_direct_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_direct_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e2d33ea607c7ec4e13fa37aee87bf7599777cce
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_direct_py.py
@@ -0,0 +1,280 @@
+from typing import ( # noqa: UP035
+ Any, Callable, Iterable
+)
+
+import numpy as np
+from scipy.optimize import OptimizeResult
+from ._constraints import old_bound_to_new, Bounds
+from ._direct import direct as _direct # type: ignore
+
+__all__ = ['direct']
+
+ERROR_MESSAGES = (
+ "Number of function evaluations done is larger than maxfun={}",
+ "Number of iterations is larger than maxiter={}",
+ "u[i] < l[i] for some i",
+ "maxfun is too large",
+ "Initialization failed",
+ "There was an error in the creation of the sample points",
+ "An error occurred while the function was sampled",
+ "Maximum number of levels has been reached.",
+ "Forced stop",
+ "Invalid arguments",
+ "Out of memory",
+)
+
+SUCCESS_MESSAGES = (
+ ("The best function value found is within a relative error={} "
+ "of the (known) global optimum f_min"),
+ ("The volume of the hyperrectangle containing the lowest function value "
+ "found is below vol_tol={}"),
+ ("The side length measure of the hyperrectangle containing the lowest "
+ "function value found is below len_tol={}"),
+)
+
+
+def direct(
+ func: Callable[
+ [np.ndarray[tuple[int], np.dtype[np.float64]]],
+ float | np.floating[Any] | np.integer[Any] | np.bool_,
+ ],
+ bounds: Iterable | Bounds,
+ *,
+ args: tuple = (),
+ eps: float = 1e-4,
+ maxfun: int | None = None,
+ maxiter: int = 1000,
+ locally_biased: bool = True,
+ f_min: float = -np.inf,
+ f_min_rtol: float = 1e-4,
+ vol_tol: float = 1e-16,
+ len_tol: float = 1e-6,
+ callback: Callable[
+ [np.ndarray[tuple[int], np.dtype[np.float64]]],
+ object,
+ ] | None = None,
+) -> OptimizeResult:
+ """
+ Finds the global minimum of a function using the
+ DIRECT algorithm.
+
+ Parameters
+ ----------
+ func : callable
+ The objective function to be minimized.
+ ``func(x, *args) -> float``
+ where ``x`` is a 1-D array with shape (n,) and ``args`` is a tuple of
+ the fixed parameters needed to completely specify the function.
+ bounds : sequence or `Bounds`
+ Bounds for variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. ``(min, max)`` pairs for each element in ``x``.
+
+ args : tuple, optional
+ Any additional fixed parameters needed to
+ completely specify the objective function.
+ eps : float, optional
+ Minimal required difference of the objective function values
+ between the current best hyperrectangle and the next potentially
+ optimal hyperrectangle to be divided. In consequence, `eps` serves as a
+ tradeoff between local and global search: the smaller, the more local
+ the search becomes. Default is 1e-4.
+ maxfun : int or None, optional
+ Approximate upper bound on objective function evaluations.
+ If `None`, will be automatically set to ``1000 * N`` where ``N``
+ represents the number of dimensions. Will be capped if necessary to
+ limit DIRECT's RAM usage to app. 1GiB. This will only occur for very
+ high dimensional problems and excessive `max_fun`. Default is `None`.
+ maxiter : int, optional
+ Maximum number of iterations. Default is 1000.
+ locally_biased : bool, optional
+ If `True` (default), use the locally biased variant of the
+ algorithm known as DIRECT_L. If `False`, use the original unbiased
+ DIRECT algorithm. For hard problems with many local minima,
+ `False` is recommended.
+ f_min : float, optional
+ Function value of the global optimum. Set this value only if the
+ global optimum is known. Default is ``-np.inf``, so that this
+ termination criterion is deactivated.
+ f_min_rtol : float, optional
+ Terminate the optimization once the relative error between the
+ current best minimum `f` and the supplied global minimum `f_min`
+ is smaller than `f_min_rtol`. This parameter is only used if
+ `f_min` is also set. Must lie between 0 and 1. Default is 1e-4.
+ vol_tol : float, optional
+ Terminate the optimization once the volume of the hyperrectangle
+ containing the lowest function value is smaller than `vol_tol`
+ of the complete search space. Must lie between 0 and 1.
+ Default is 1e-16.
+ len_tol : float, optional
+ If ``locally_biased=True``, terminate the optimization once half of
+ the normalized maximal side length of the hyperrectangle containing
+ the lowest function value is smaller than `len_tol`.
+ If ``locally_biased=False``, terminate the optimization once half of
+ the normalized diagonal of the hyperrectangle containing the lowest
+ function value is smaller than `len_tol`. Must lie between 0 and 1.
+ Default is 1e-6.
+ callback : callable, optional
+ A callback function with signature ``callback(xk)`` where ``xk``
+ represents the best function value found so far.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a ``OptimizeResult`` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully and
+ ``message`` which describes the cause of the termination. See
+ `OptimizeResult` for a description of other attributes.
+
+ Notes
+ -----
+ DIviding RECTangles (DIRECT) is a deterministic global
+ optimization algorithm capable of minimizing a black box function with
+ its variables subject to lower and upper bound constraints by sampling
+ potential solutions in the search space [1]_. The algorithm starts by
+ normalising the search space to an n-dimensional unit hypercube.
+ It samples the function at the center of this hypercube and at 2n
+ (n is the number of variables) more points, 2 in each coordinate
+ direction. Using these function values, DIRECT then divides the
+ domain into hyperrectangles, each having exactly one of the sampling
+ points as its center. In each iteration, DIRECT chooses, using the `eps`
+ parameter which defaults to 1e-4, some of the existing hyperrectangles
+ to be further divided. This division process continues until either the
+ maximum number of iterations or maximum function evaluations allowed
+ are exceeded, or the hyperrectangle containing the minimal value found
+ so far becomes small enough. If `f_min` is specified, the optimization
+ will stop once this function value is reached within a relative tolerance.
+ The locally biased variant of DIRECT (originally called DIRECT_L) [2]_ is
+ used by default. It makes the search more locally biased and more
+ efficient for cases with only a few local minima.
+
+ A note about termination criteria: `vol_tol` refers to the volume of the
+ hyperrectangle containing the lowest function value found so far. This
+ volume decreases exponentially with increasing dimensionality of the
+ problem. Therefore `vol_tol` should be decreased to avoid premature
+ termination of the algorithm for higher dimensions. This does not hold
+ for `len_tol`: it refers either to half of the maximal side length
+ (for ``locally_biased=True``) or half of the diagonal of the
+ hyperrectangle (for ``locally_biased=False``).
+
+ This code is based on the DIRECT 2.0.4 Fortran code by Gablonsky et al. at
+ https://ctk.math.ncsu.edu/SOFTWARE/DIRECTv204.tar.gz .
+ This original version was initially converted via f2c and then cleaned up
+ and reorganized by Steven G. Johnson, August 2007, for the NLopt project.
+ The `direct` function wraps the C implementation.
+
+ .. versionadded:: 1.9.0
+
+ References
+ ----------
+ .. [1] Jones, D.R., Perttunen, C.D. & Stuckman, B.E. Lipschitzian
+ optimization without the Lipschitz constant. J Optim Theory Appl
+ 79, 157-181 (1993).
+ .. [2] Gablonsky, J., Kelley, C. A Locally-Biased form of the DIRECT
+ Algorithm. Journal of Global Optimization 21, 27-37 (2001).
+
+ Examples
+ --------
+ The following example is a 2-D problem with four local minima: minimizing
+ the Styblinski-Tang function
+ (https://en.wikipedia.org/wiki/Test_functions_for_optimization).
+
+ >>> from scipy.optimize import direct, Bounds
+ >>> def styblinski_tang(pos):
+ ... x, y = pos
+ ... return 0.5 * (x**4 - 16*x**2 + 5*x + y**4 - 16*y**2 + 5*y)
+ >>> bounds = Bounds([-4., -4.], [4., 4.])
+ >>> result = direct(styblinski_tang, bounds)
+ >>> result.x, result.fun, result.nfev
+ array([-2.90321597, -2.90321597]), -78.3323279095383, 2011
+
+ The correct global minimum was found but with a huge number of function
+ evaluations (2011). Loosening the termination tolerances `vol_tol` and
+ `len_tol` can be used to stop DIRECT earlier.
+
+ >>> result = direct(styblinski_tang, bounds, len_tol=1e-3)
+ >>> result.x, result.fun, result.nfev
+ array([-2.9044353, -2.9044353]), -78.33230330754142, 207
+
+ """
+ # convert bounds to new Bounds class if necessary
+ if not isinstance(bounds, Bounds):
+ if isinstance(bounds, list) or isinstance(bounds, tuple):
+ lb, ub = old_bound_to_new(bounds)
+ bounds = Bounds(lb, ub)
+ else:
+ message = ("bounds must be a sequence or "
+ "instance of Bounds class")
+ raise ValueError(message)
+
+ lb = np.ascontiguousarray(bounds.lb, dtype=np.float64)
+ ub = np.ascontiguousarray(bounds.ub, dtype=np.float64)
+
+ # validate bounds
+ # check that lower bounds are smaller than upper bounds
+ if not np.all(lb < ub):
+ raise ValueError('Bounds are not consistent min < max')
+ # check for infs
+ if (np.any(np.isinf(lb)) or np.any(np.isinf(ub))):
+ raise ValueError("Bounds must not be inf.")
+
+ # validate tolerances
+ if (vol_tol < 0 or vol_tol > 1):
+ raise ValueError("vol_tol must be between 0 and 1.")
+ if (len_tol < 0 or len_tol > 1):
+ raise ValueError("len_tol must be between 0 and 1.")
+ if (f_min_rtol < 0 or f_min_rtol > 1):
+ raise ValueError("f_min_rtol must be between 0 and 1.")
+
+ # validate maxfun and maxiter
+ if maxfun is None:
+ maxfun = 1000 * lb.shape[0]
+ if not isinstance(maxfun, int):
+ raise ValueError("maxfun must be of type int.")
+ if maxfun < 0:
+ raise ValueError("maxfun must be > 0.")
+ if not isinstance(maxiter, int):
+ raise ValueError("maxiter must be of type int.")
+ if maxiter < 0:
+ raise ValueError("maxiter must be > 0.")
+
+ # validate boolean parameters
+ if not isinstance(locally_biased, bool):
+ raise ValueError("locally_biased must be True or False.")
+
+ def _func_wrap(x, args=None):
+ x = np.asarray(x)
+ if args is None:
+ f = func(x)
+ else:
+ f = func(x, *args)
+ # always return a float
+ return np.asarray(f).item()
+
+ # TODO: fix disp argument
+ x, fun, ret_code, nfev, nit = _direct(
+ _func_wrap,
+ np.asarray(lb), np.asarray(ub),
+ args,
+ False, eps, maxfun, maxiter,
+ locally_biased,
+ f_min, f_min_rtol,
+ vol_tol, len_tol, callback
+ )
+
+ format_val = (maxfun, maxiter, f_min_rtol, vol_tol, len_tol)
+ if ret_code > 2:
+ message = SUCCESS_MESSAGES[ret_code - 3].format(
+ format_val[ret_code - 1])
+ elif 0 < ret_code <= 2:
+ message = ERROR_MESSAGES[ret_code - 1].format(format_val[ret_code - 1])
+ elif 0 > ret_code > -100:
+ message = ERROR_MESSAGES[abs(ret_code) + 1]
+ else:
+ message = ERROR_MESSAGES[ret_code + 99]
+
+ return OptimizeResult(x=np.asarray(x), fun=fun, status=ret_code,
+ success=ret_code > 2, message=message,
+ nfev=nfev, nit=nit)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_dual_annealing.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_dual_annealing.py
new file mode 100644
index 0000000000000000000000000000000000000000..e76f02b883ed8166106995b783014fc3811f8688
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/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 (1988).
+ .. [2] Tsallis C, Stariolo DA. Generalized Simulated Annealing.
+ Physica A, 233, 395-406 (1996).
+ .. [3] Xiang Y, Sun DY, Fan W, Gong XG. Generalized Simulated
+ Annealing Algorithm and Its Application to the Thomson Model.
+ Physics Letters A, 233, 216-220 (1997).
+ .. [4] Xiang Y, Gong XG. Efficiency of Generalized Simulated
+ Annealing. Physical Review E, 62, 4473 (2000).
+ .. [5] Xiang Y, Gubian S, Suomela B, Hoeng J. Generalized
+ Simulated Annealing for Efficient Global Optimization: the GenSA
+ Package for R. The R Journal, Volume 5/1 (2013).
+ .. [6] Mullen, K. Continuous Global Optimization in R. Journal of
+ Statistical Software, 60(6), 1 - 45, (2014).
+ :doi:`10.18637/jss.v060.i06`
+
+ Examples
+ --------
+ The following example is a 10-D problem, with many local minima.
+ The function involved is called Rastrigin
+ (https://en.wikipedia.org/wiki/Rastrigin_function)
+
+ >>> import numpy as np
+ >>> from scipy.optimize import dual_annealing
+ >>> func = lambda x: np.sum(x*x - 10*np.cos(2*np.pi*x)) + 10*np.size(x)
+ >>> lw = [-5.12] * 10
+ >>> up = [5.12] * 10
+ >>> ret = dual_annealing(func, bounds=list(zip(lw, up)))
+ >>> ret.x
+ array([-4.26437714e-09, -3.91699361e-09, -1.86149218e-09, -3.97165720e-09,
+ -6.29151648e-09, -6.53145322e-09, -3.93616815e-09, -6.55623025e-09,
+ -6.05775280e-09, -5.00668935e-09]) # random
+ >>> ret.fun
+ 0.000000
+
+ """
+
+ if isinstance(bounds, Bounds):
+ bounds = new_bounds_to_old(bounds.lb, bounds.ub, len(bounds.lb))
+
+ if x0 is not None and not len(x0) == len(bounds):
+ raise ValueError('Bounds size does not match x0')
+
+ lu = list(zip(*bounds))
+ lower = np.array(lu[0])
+ upper = np.array(lu[1])
+ # Check that restart temperature ratio is correct
+ if restart_temp_ratio <= 0. or restart_temp_ratio >= 1.:
+ raise ValueError('Restart temperature ratio has to be in range (0, 1)')
+ # Checking bounds are valid
+ if (np.any(np.isinf(lower)) or np.any(np.isinf(upper)) or np.any(
+ np.isnan(lower)) or np.any(np.isnan(upper))):
+ raise ValueError('Some bounds values are inf values or nan values')
+ # Checking that bounds are consistent
+ if not np.all(lower < upper):
+ raise ValueError('Bounds are not consistent min < max')
+ # Checking that bounds are the same length
+ if not len(lower) == len(upper):
+ raise ValueError('Bounds do not have the same dimensions')
+
+ # Wrapper for the objective function
+ func_wrapper = ObjectiveFunWrapper(func, maxfun, *args)
+
+ # minimizer_kwargs has to be a dict, not None
+ minimizer_kwargs = minimizer_kwargs or {}
+
+ minimizer_wrapper = LocalSearchWrapper(
+ bounds, func_wrapper, *args, **minimizer_kwargs)
+
+ # Initialization of random Generator for reproducible runs if rng provided
+ rng_gen = check_random_state(rng)
+ # Initialization of the energy state
+ energy_state = EnergyState(lower, upper, callback)
+ energy_state.reset(func_wrapper, rng_gen, x0)
+ # Minimum value of annealing temperature reached to perform
+ # re-annealing
+ temperature_restart = initial_temp * restart_temp_ratio
+ # VisitingDistribution instance
+ visit_dist = VisitingDistribution(lower, upper, visit, rng_gen)
+ # Strategy chain instance
+ strategy_chain = StrategyChain(accept, visit_dist, func_wrapper,
+ minimizer_wrapper, rng_gen, energy_state)
+ need_to_stop = False
+ iteration = 0
+ message = []
+ # OptimizeResult object to be returned
+ optimize_res = OptimizeResult()
+ optimize_res.success = True
+ optimize_res.status = 0
+
+ t1 = np.exp((visit - 1) * np.log(2.0)) - 1.0
+ # Run the search loop
+ while not need_to_stop:
+ for i in range(maxiter):
+ # Compute temperature for this step
+ s = float(i) + 2.0
+ t2 = np.exp((visit - 1) * np.log(s)) - 1.0
+ temperature = initial_temp * t1 / t2
+ if iteration >= maxiter:
+ message.append("Maximum number of iteration reached")
+ need_to_stop = True
+ break
+ # Need a re-annealing process?
+ if temperature < temperature_restart:
+ energy_state.reset(func_wrapper, rng_gen)
+ break
+ # starting strategy chain
+ val = strategy_chain.run(i, temperature)
+ if val is not None:
+ message.append(val)
+ need_to_stop = True
+ optimize_res.success = False
+ break
+ # Possible local search at the end of the strategy chain
+ if not no_local_search:
+ val = strategy_chain.local_search()
+ if val is not None:
+ message.append(val)
+ need_to_stop = True
+ optimize_res.success = False
+ break
+ iteration += 1
+
+ # Setting the OptimizeResult values
+ optimize_res.x = energy_state.xbest
+ optimize_res.fun = energy_state.ebest
+ optimize_res.nit = iteration
+ optimize_res.nfev = func_wrapper.nfev
+ optimize_res.njev = func_wrapper.ngev
+ optimize_res.nhev = func_wrapper.nhev
+ optimize_res.message = message
+ return optimize_res
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_elementwise.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_elementwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3fd1ee634e64760e981e8be641159c372fe7b84
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_elementwise.py
@@ -0,0 +1,816 @@
+from scipy.optimize._bracket import _bracket_root, _bracket_minimum
+from scipy.optimize._chandrupatla import _chandrupatla, _chandrupatla_minimize
+from scipy._lib._util import _RichResult
+from scipy._lib._array_api import xp_capabilities
+
+
+@xp_capabilities(
+ skip_backends=[('dask.array', 'boolean indexing assignment'),
+ ('array_api_strict', 'Currently uses fancy indexing assignment.'),
+ ('jax.numpy', 'JAX arrays do not support item assignment.')])
+def find_root(f, init, /, *, args=(), 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)
+
+
+@xp_capabilities(
+ skip_backends=[('dask.array', 'boolean indexing assignment'),
+ ('array_api_strict', 'Currently uses fancy indexing assignment.'),
+ ('jax.numpy', 'JAX arrays do not support item assignment.')])
+def find_minimum(f, init, /, *, args=(), 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:
+
+ - ``abs(xr - xm)/2 <= abs(xm)*xrtol + xatol`` or
+ - ``(fl - 2*fm + fr)/2 <= abs(fm)*frtol + fatol``.
+
+ The default value of `xrtol` is the square root of the precision of the
+ appropriate dtype, and ``xatol = fatol = frtol`` is the smallest normal
+ number of the appropriate dtype.
+
+ References
+ ----------
+
+ .. [1] Chandrupatla, Tirupathi R. (1998).
+ "An efficient quadratic fit-sectioning algorithm for minimization
+ without derivatives".
+ Computer Methods in Applied Mechanics and Engineering, 152 (1-2),
+ 211-217. 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)
+
+
+@xp_capabilities(
+ skip_backends=[('dask.array', 'boolean indexing assignment'),
+ ('array_api_strict', 'Currently uses fancy indexing assignment.'),
+ ('jax.numpy', 'JAX arrays do not support item assignment.')])
+def bracket_root(f, xl0, xr0=None, *, xmin=None, xmax=None, factor=None, args=(),
+ 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
+
+
+@xp_capabilities(
+ skip_backends=[('dask.array', 'boolean indexing assignment'),
+ ('array_api_strict', 'Currently uses fancy indexing assignment.'),
+ ('jax.numpy', 'JAX arrays do not support item assignment.'),
+ ('torch', 'data-apis/array-api-compat#271')])
+def bracket_minimum(f, xm0, *, xl0=None, xr0=None, xmin=None, xmax=None,
+ factor=None, args=(), maxiter=1000):
+ """Bracket the minimum of a unimodal, real-valued function of a real variable.
+
+ For each element of the output of `f`, `bracket_minimum` seeks the scalar
+ bracket points ``xl < xm < xr`` such that ``fl >= fm <= fr`` where one of the
+ inequalities is strict.
+
+ The function is guaranteed to find a valid bracket if the function is
+ strongly unimodal, but it may find a bracket under other conditions.
+
+ This function works elementwise when `xm0`, `xl0`, `xr0`, `xmin`, `xmax`, `factor`,
+ and the elements of `args` are (mutually broadcastable) arrays.
+
+ Parameters
+ ----------
+ f : callable
+ The function for which the root is to be bracketed. The signature must be::
+
+ f(x: array, *args) -> array
+
+ where each element of ``x`` is a finite real and ``args`` is a tuple,
+ which may contain an arbitrary number of arrays that are broadcastable
+ with ``x``.
+
+ `f` must be an elementwise function: each element ``f(x)[i]``
+ must equal ``f(x[i])`` for all indices ``i``. It must not mutate the
+ array ``x`` or the arrays in ``args``.
+ xm0: float array_like
+ Starting guess for middle point of bracket.
+ xl0, xr0: float array_like, optional
+ Starting guesses for left and right endpoints of the bracket. Must
+ be broadcastable with all other array inputs.
+ xmin, xmax : float array_like, optional
+ Minimum and maximum allowable endpoints of the bracket, inclusive. Must
+ be broadcastable with all other array inputs.
+ factor : float array_like, default: 2
+ The factor used to grow the bracket. See Notes.
+ args : tuple of array_like, optional
+ Additional positional array arguments to be passed to `f`.
+ If the callable for which the root is desired requires arguments that are
+ not broadcastable with `x`, wrap that callable with `f` such that `f`
+ accepts only `x` and broadcastable ``*args``.
+ maxiter : int, default: 1000
+ The maximum number of iterations of the algorithm to perform.
+
+ Returns
+ -------
+ res : _RichResult
+ An object similar to an instance of `scipy.optimize.OptimizeResult` with the
+ following attributes. The descriptions are written as though the values will
+ be scalars; however, if `f` returns an array, the outputs will be
+ arrays of the same shape.
+
+ success : bool array
+ ``True`` where the algorithm terminated successfully (status ``0``);
+ ``False`` otherwise.
+ status : int array
+ An integer representing the exit status of the algorithm.
+
+ - ``0`` : The algorithm produced a valid bracket.
+ - ``-1`` : The bracket expanded to the allowable limits. Assuming
+ unimodality, this implies the endpoint at the limit is a minimizer.
+ - ``-2`` : The maximum number of iterations was reached.
+ - ``-3`` : A non-finite value was encountered.
+ - ``-4`` : ``None`` shall pass.
+ - ``-5`` : The initial bracket does not satisfy
+ `xmin <= xl0 < xm0 < xr0 <= xmax`.
+
+ bracket : 3-tuple of float arrays
+ The left, middle, and right points of the bracket, if the algorithm
+ terminated successfully.
+ f_bracket : 3-tuple of float arrays
+ The function value at the left, middle, and right points of the bracket.
+ nfev : int array
+ The number of abscissae at which `f` was evaluated to find the root.
+ This is distinct from the number of times `f` is *called* because the
+ the function may evaluated at multiple points in a single call.
+ nit : int array
+ The number of iterations of the algorithm that were performed.
+
+ Notes
+ -----
+ Similar to `scipy.optimize.bracket`, this function seeks to find real
+ points ``xl < xm < xr`` such that ``f(xl) >= f(xm)`` and ``f(xr) >= f(xm)``,
+ where at least one of the inequalities is strict. Unlike `scipy.optimize.bracket`,
+ this function can operate in a vectorized manner on array input, so long as
+ the input arrays are broadcastable with each other. Also unlike
+ `scipy.optimize.bracket`, users may specify minimum and maximum endpoints
+ for the desired bracket.
+
+ Given an initial trio of points ``xl = xl0``, ``xm = xm0``, ``xr = xr0``,
+ the algorithm checks if these points already give a valid bracket. If not,
+ a new endpoint, ``w`` is chosen in the "downhill" direction, ``xm`` becomes the new
+ opposite endpoint, and either `xl` or `xr` becomes the new middle point,
+ depending on which direction is downhill. The algorithm repeats from here.
+
+ The new endpoint `w` is chosen differently depending on whether or not a
+ boundary `xmin` or `xmax` has been set in the downhill direction. Without
+ loss of generality, suppose the downhill direction is to the right, so that
+ ``f(xl) > f(xm) > f(xr)``. If there is no boundary to the right, then `w`
+ is chosen to be ``xr + factor * (xr - xm)`` where `factor` is controlled by
+ the user (defaults to 2.0) so that step sizes increase in geometric proportion.
+ If there is a boundary, `xmax` in this case, then `w` is chosen to be
+ ``xmax - (xmax - xr)/factor``, with steps slowing to a stop at
+ `xmax`. This cautious approach ensures that a minimum near but distinct from
+ the boundary isn't missed while also detecting whether or not the `xmax` is
+ a minimizer when `xmax` is reached after a finite number of steps.
+
+ See Also
+ --------
+ scipy.optimize.bracket
+ scipy.optimize.elementwise.find_minimum
+
+ Examples
+ --------
+ Suppose we wish to minimize the following function.
+
+ >>> def f(x, c=1):
+ ... return (x - c)**2 + 2
+
+ First, we must find a valid bracket. The function is unimodal,
+ so `bracket_minium` will easily find a bracket.
+
+ >>> from scipy.optimize import elementwise
+ >>> res_bracket = elementwise.bracket_minimum(f, 0)
+ >>> res_bracket.success
+ True
+ >>> res_bracket.bracket
+ (0.0, 0.5, 1.5)
+
+ Indeed, the bracket points are ordered and the function value
+ at the middle bracket point is less than at the surrounding
+ points.
+
+ >>> xl, xm, xr = res_bracket.bracket
+ >>> fl, fm, fr = res_bracket.f_bracket
+ >>> (xl < xm < xr) and (fl > fm <= fr)
+ True
+
+ Once we have a valid bracket, `find_minimum` can be used to provide
+ an estimate of the minimizer.
+
+ >>> res_minimum = elementwise.find_minimum(f, res_bracket.bracket)
+ >>> res_minimum.x
+ 1.0000000149011612
+
+ `bracket_minimum` and `find_minimum` accept arrays for most arguments.
+ For instance, to find the minimizers and minima for a few values of the
+ parameter ``c`` at once:
+
+ >>> import numpy as np
+ >>> c = np.asarray([1, 1.5, 2])
+ >>> res_bracket = elementwise.bracket_minimum(f, 0, args=(c,))
+ >>> res_bracket.bracket
+ (array([0. , 0.5, 0.5]), array([0.5, 1.5, 1.5]), array([1.5, 2.5, 2.5]))
+ >>> res_minimum = elementwise.find_minimum(f, res_bracket.bracket, args=(c,))
+ >>> res_minimum.x
+ array([1.00000001, 1.5 , 2. ])
+ >>> res_minimum.f_x
+ array([2., 2., 2.])
+
+ """ # noqa: E501
+
+ res = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax,
+ factor=factor, args=args, maxiter=maxiter)
+ res.bracket = res.xl, res.xm, res.xr
+ res.f_bracket = res.fl, res.fm, res.fr
+ del res.xl
+ del res.xm
+ del res.xr
+ del res.fl
+ del res.fm
+ del res.fr
+ return res
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_group_columns.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_group_columns.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..db324c87b71333f8e34444fef0834f4b2f69bfef
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_group_columns.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_hessian_update_strategy.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_hessian_update_strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..15989969349025fd42fba9836b4f5d882c3f6791
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_hessian_update_strategy.py
@@ -0,0 +1,479 @@
+"""Hessian update strategies for quasi-Newton optimization methods."""
+import numpy as np
+from numpy.linalg import norm
+from scipy.linalg import get_blas_funcs, issymmetric
+from warnings import warn
+
+
+__all__ = ['HessianUpdateStrategy', 'BFGS', 'SR1']
+
+
+class HessianUpdateStrategy:
+ """Interface for implementing Hessian update strategies.
+
+ Many optimization methods make use of Hessian (or inverse Hessian)
+ approximations, such as the quasi-Newton methods BFGS, SR1, L-BFGS.
+ Some of these approximations, however, do not actually need to store
+ the entire matrix or can compute the internal matrix product with a
+ given vector in a very efficiently manner. This class serves as an
+ abstract interface between the optimization algorithm and the
+ quasi-Newton update strategies, giving freedom of implementation
+ to store and update the internal matrix as efficiently as possible.
+ Different choices of initialization and update procedure will result
+ in different quasi-Newton strategies.
+
+ Four methods should be implemented in derived classes: ``initialize``,
+ ``update``, ``dot`` and ``get_matrix``. The matrix multiplication
+ operator ``@`` is also defined to call the ``dot`` method.
+
+ Notes
+ -----
+ Any instance of a class that implements this interface,
+ can be accepted by the method ``minimize`` and used by
+ the compatible solvers to approximate the Hessian (or
+ inverse Hessian) used by the optimization algorithms.
+ """
+
+ def initialize(self, n, approx_type):
+ """Initialize internal matrix.
+
+ Allocate internal memory for storing and updating
+ the Hessian or its inverse.
+
+ Parameters
+ ----------
+ n : int
+ Problem dimension.
+ approx_type : {'hess', 'inv_hess'}
+ Selects either the Hessian or the inverse Hessian.
+ When set to 'hess' the Hessian will be stored and updated.
+ When set to 'inv_hess' its inverse will be used instead.
+ """
+ raise NotImplementedError("The method ``initialize(n, approx_type)``"
+ " is not implemented.")
+
+ def update(self, delta_x, delta_grad):
+ """Update internal matrix.
+
+ Update Hessian matrix or its inverse (depending on how 'approx_type'
+ is defined) using information about the last evaluated points.
+
+ Parameters
+ ----------
+ delta_x : ndarray
+ The difference between two points the gradient
+ function have been evaluated at: ``delta_x = x2 - x1``.
+ delta_grad : ndarray
+ The difference between the gradients:
+ ``delta_grad = grad(x2) - grad(x1)``.
+ """
+ raise NotImplementedError("The method ``update(delta_x, delta_grad)``"
+ " is not implemented.")
+
+ def dot(self, p):
+ """Compute the product of the internal matrix with the given vector.
+
+ Parameters
+ ----------
+ p : array_like
+ 1-D array representing a vector.
+
+ Returns
+ -------
+ Hp : array
+ 1-D represents the result of multiplying the approximation matrix
+ by vector p.
+ """
+ raise NotImplementedError("The method ``dot(p)``"
+ " is not implemented.")
+
+ def get_matrix(self):
+ """Return current internal matrix.
+
+ Returns
+ -------
+ H : ndarray, shape (n, n)
+ Dense matrix containing either the Hessian
+ or its inverse (depending on how 'approx_type'
+ is defined).
+ """
+ raise NotImplementedError("The method ``get_matrix(p)``"
+ " is not implemented.")
+
+ def __matmul__(self, p):
+ return self.dot(p)
+
+
+class FullHessianUpdateStrategy(HessianUpdateStrategy):
+ """Hessian update strategy with full dimensional internal representation.
+ """
+ _syr = get_blas_funcs('syr', dtype='d') # Symmetric rank 1 update
+ _syr2 = get_blas_funcs('syr2', dtype='d') # Symmetric rank 2 update
+ # Symmetric matrix-vector product
+ _symv = get_blas_funcs('symv', dtype='d')
+
+ def __init__(self, init_scale='auto'):
+ self.init_scale = init_scale
+ # Until initialize is called we can't really use the class,
+ # so it makes sense to set everything to None.
+ self.first_iteration = None
+ self.approx_type = None
+ self.B = None
+ self.H = None
+
+ def initialize(self, n, approx_type):
+ """Initialize internal matrix.
+
+ Allocate internal memory for storing and updating
+ the Hessian or its inverse.
+
+ Parameters
+ ----------
+ n : int
+ Problem dimension.
+ approx_type : {'hess', 'inv_hess'}
+ Selects either the Hessian or the inverse Hessian.
+ When set to 'hess' the Hessian will be stored and updated.
+ When set to 'inv_hess' its inverse will be used instead.
+ """
+ self.first_iteration = True
+ self.n = n
+ self.approx_type = approx_type
+ if approx_type not in ('hess', 'inv_hess'):
+ raise ValueError("`approx_type` must be 'hess' or 'inv_hess'.")
+ # Create matrix
+ if self.approx_type == 'hess':
+ self.B = np.eye(n, dtype=float)
+ else:
+ self.H = np.eye(n, dtype=float)
+
+ def _auto_scale(self, delta_x, delta_grad):
+ # Heuristic to scale matrix at first iteration.
+ # Described in Nocedal and Wright "Numerical Optimization"
+ # p.143 formula (6.20).
+ s_norm2 = np.dot(delta_x, delta_x)
+ y_norm2 = np.dot(delta_grad, delta_grad)
+ ys = np.abs(np.dot(delta_grad, delta_x))
+ if ys == 0.0 or y_norm2 == 0 or s_norm2 == 0:
+ return 1
+ if self.approx_type == 'hess':
+ return y_norm2 / ys
+ else:
+ return ys / y_norm2
+
+ def _update_implementation(self, delta_x, delta_grad):
+ raise NotImplementedError("The method ``_update_implementation``"
+ " is not implemented.")
+
+ def update(self, delta_x, delta_grad):
+ """Update internal matrix.
+
+ Update Hessian matrix or its inverse (depending on how 'approx_type'
+ is defined) using information about the last evaluated points.
+
+ Parameters
+ ----------
+ delta_x : ndarray
+ The difference between two points the gradient
+ function have been evaluated at: ``delta_x = x2 - x1``.
+ delta_grad : ndarray
+ The difference between the gradients:
+ ``delta_grad = grad(x2) - grad(x1)``.
+ """
+ if np.all(delta_x == 0.0):
+ return
+ if np.all(delta_grad == 0.0):
+ warn('delta_grad == 0.0. Check if the approximated '
+ 'function is linear. If the function is linear '
+ 'better results can be obtained by defining the '
+ 'Hessian as zero instead of using quasi-Newton '
+ 'approximations.',
+ UserWarning, stacklevel=2)
+ return
+ if self.first_iteration:
+ # Get user specific scale
+ if isinstance(self.init_scale, str) and self.init_scale == "auto":
+ scale = self._auto_scale(delta_x, delta_grad)
+ else:
+ scale = self.init_scale
+
+ # Check for complex: numpy will silently cast a complex array to
+ # a real one but not so for scalar as it raises a TypeError.
+ # Checking here brings a consistent behavior.
+ replace = False
+ if np.size(scale) == 1:
+ # to account for the legacy behavior having the exact same cast
+ scale = float(scale)
+ elif np.iscomplexobj(scale):
+ raise TypeError("init_scale contains complex elements, "
+ "must be real.")
+ else: # test explicitly for allowed shapes and values
+ replace = True
+ if self.approx_type == 'hess':
+ shape = np.shape(self.B)
+ dtype = self.B.dtype
+ else:
+ shape = np.shape(self.H)
+ dtype = self.H.dtype
+ # copy, will replace the original
+ scale = np.array(scale, dtype=dtype, copy=True)
+
+ # it has to match the shape of the matrix for the multiplication,
+ # no implicit broadcasting is allowed
+ if shape != (init_shape := np.shape(scale)):
+ raise ValueError("If init_scale is an array, it must have the "
+ f"dimensions of the hess/inv_hess: {shape}."
+ f" Got {init_shape}.")
+ if not issymmetric(scale):
+ raise ValueError("If init_scale is an array, it must be"
+ " symmetric (passing scipy.linalg.issymmetric)"
+ " to be an approximation of a hess/inv_hess.")
+
+ # Scale initial matrix with ``scale * np.eye(n)`` or replace
+ # This is not ideal, we could assign the scale directly in
+ # initialize, but we would need to
+ if self.approx_type == 'hess':
+ if replace:
+ self.B = scale
+ else:
+ self.B *= scale
+ else:
+ if replace:
+ self.H = scale
+ else:
+ self.H *= scale
+ self.first_iteration = False
+ self._update_implementation(delta_x, delta_grad)
+
+ def dot(self, p):
+ """Compute the product of the internal matrix with the given vector.
+
+ Parameters
+ ----------
+ p : array_like
+ 1-D array representing a vector.
+
+ Returns
+ -------
+ Hp : array
+ 1-D represents the result of multiplying the approximation matrix
+ by vector p.
+ """
+ if self.approx_type == 'hess':
+ return self._symv(1, self.B, p)
+ else:
+ return self._symv(1, self.H, p)
+
+ def get_matrix(self):
+ """Return the current internal matrix.
+
+ Returns
+ -------
+ M : ndarray, shape (n, n)
+ Dense matrix containing either the Hessian or its inverse
+ (depending on how `approx_type` was defined).
+ """
+ if self.approx_type == 'hess':
+ M = np.copy(self.B)
+ else:
+ M = np.copy(self.H)
+ li = np.tril_indices_from(M, k=-1)
+ M[li] = M.T[li]
+ return M
+
+
+class BFGS(FullHessianUpdateStrategy):
+ """Broyden-Fletcher-Goldfarb-Shanno (BFGS) Hessian update strategy.
+
+ Parameters
+ ----------
+ exception_strategy : {'skip_update', 'damp_update'}, optional
+ Define how to proceed when the curvature condition is violated.
+ Set it to 'skip_update' to just skip the update. Or, alternatively,
+ set it to 'damp_update' to interpolate between the actual BFGS
+ result and the unmodified matrix. Both exceptions strategies
+ are explained in [1]_, p.536-537.
+ min_curvature : float
+ This number, scaled by a normalization factor, defines the
+ minimum curvature ``dot(delta_grad, delta_x)`` allowed to go
+ unaffected by the exception strategy. By default is equal to
+ 1e-8 when ``exception_strategy = 'skip_update'`` and equal
+ to 0.2 when ``exception_strategy = 'damp_update'``.
+ init_scale : {float, np.array, 'auto'}
+ This parameter can be used to initialize the Hessian or its
+ inverse. When a float is given, the relevant array is initialized
+ to ``np.eye(n) * init_scale``, where ``n`` is the problem dimension.
+ Alternatively, if a precisely ``(n, n)`` shaped, symmetric array is given,
+ this array will be used. Otherwise an error is generated.
+ Set it to 'auto' in order to use an automatic heuristic for choosing
+ the initial scale. The heuristic is described in [1]_, p.143.
+ The default is 'auto'.
+
+ Notes
+ -----
+ The update is based on the description in [1]_, p.140.
+
+ References
+ ----------
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+ """
+
+ def __init__(self, exception_strategy='skip_update', min_curvature=None,
+ init_scale='auto'):
+ if exception_strategy == 'skip_update':
+ if min_curvature is not None:
+ self.min_curvature = min_curvature
+ else:
+ self.min_curvature = 1e-8
+ elif exception_strategy == 'damp_update':
+ if min_curvature is not None:
+ self.min_curvature = min_curvature
+ else:
+ self.min_curvature = 0.2
+ else:
+ raise ValueError("`exception_strategy` must be 'skip_update' "
+ "or 'damp_update'.")
+
+ super().__init__(init_scale)
+ self.exception_strategy = exception_strategy
+
+ def _update_inverse_hessian(self, ys, Hy, yHy, s):
+ """Update the inverse Hessian matrix.
+
+ BFGS update using the formula:
+
+ ``H <- H + ((H*y).T*y + s.T*y)/(s.T*y)^2 * (s*s.T)
+ - 1/(s.T*y) * ((H*y)*s.T + s*(H*y).T)``
+
+ where ``s = delta_x`` and ``y = delta_grad``. This formula is
+ equivalent to (6.17) in [1]_ written in a more efficient way
+ for implementation.
+
+ References
+ ----------
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+ """
+ self.H = self._syr2(-1.0 / ys, s, Hy, a=self.H)
+ self.H = self._syr((ys + yHy) / ys ** 2, s, a=self.H)
+
+ def _update_hessian(self, ys, Bs, sBs, y):
+ """Update the Hessian matrix.
+
+ BFGS update using the formula:
+
+ ``B <- B - (B*s)*(B*s).T/s.T*(B*s) + y*y^T/s.T*y``
+
+ where ``s`` is short for ``delta_x`` and ``y`` is short
+ for ``delta_grad``. Formula (6.19) in [1]_.
+
+ References
+ ----------
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+ """
+ self.B = self._syr(1.0 / ys, y, a=self.B)
+ self.B = self._syr(-1.0 / sBs, Bs, a=self.B)
+
+ def _update_implementation(self, delta_x, delta_grad):
+ # Auxiliary variables w and z
+ if self.approx_type == 'hess':
+ w = delta_x
+ z = delta_grad
+ else:
+ w = delta_grad
+ z = delta_x
+ # Do some common operations
+ wz = np.dot(w, z)
+ Mw = self @ w
+ wMw = Mw.dot(w)
+ # Guarantee that wMw > 0 by reinitializing matrix.
+ # While this is always true in exact arithmetic,
+ # indefinite matrix may appear due to roundoff errors.
+ if wMw <= 0.0:
+ scale = self._auto_scale(delta_x, delta_grad)
+ # Reinitialize matrix
+ if self.approx_type == 'hess':
+ self.B = scale * np.eye(self.n, dtype=float)
+ else:
+ self.H = scale * np.eye(self.n, dtype=float)
+ # Do common operations for new matrix
+ Mw = self @ w
+ wMw = Mw.dot(w)
+ # Check if curvature condition is violated
+ if wz <= self.min_curvature * wMw:
+ # If the option 'skip_update' is set
+ # we just skip the update when the condition
+ # is violated.
+ if self.exception_strategy == 'skip_update':
+ return
+ # If the option 'damp_update' is set we
+ # interpolate between the actual BFGS
+ # result and the unmodified matrix.
+ elif self.exception_strategy == 'damp_update':
+ update_factor = (1-self.min_curvature) / (1 - wz/wMw)
+ z = update_factor*z + (1-update_factor)*Mw
+ wz = np.dot(w, z)
+ # Update matrix
+ if self.approx_type == 'hess':
+ self._update_hessian(wz, Mw, wMw, z)
+ else:
+ self._update_inverse_hessian(wz, Mw, wMw, z)
+
+
+class SR1(FullHessianUpdateStrategy):
+ """Symmetric-rank-1 Hessian update strategy.
+
+ Parameters
+ ----------
+ min_denominator : float
+ This number, scaled by a normalization factor,
+ defines the minimum denominator magnitude allowed
+ in the update. When the condition is violated we skip
+ the update. By default uses ``1e-8``.
+ init_scale : {float, np.array, 'auto'}, optional
+ This parameter can be used to initialize the Hessian or its
+ inverse. When a float is given, the relevant array is initialized
+ to ``np.eye(n) * init_scale``, where ``n`` is the problem dimension.
+ Alternatively, if a precisely ``(n, n)`` shaped, symmetric array is given,
+ this array will be used. Otherwise an error is generated.
+ Set it to 'auto' in order to use an automatic heuristic for choosing
+ the initial scale. The heuristic is described in [1]_, p.143.
+ The default is 'auto'.
+
+ Notes
+ -----
+ The update is based on the description in [1]_, p.144-146.
+
+ References
+ ----------
+ .. [1] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+ """
+
+ def __init__(self, min_denominator=1e-8, init_scale='auto'):
+ self.min_denominator = min_denominator
+ super().__init__(init_scale)
+
+ def _update_implementation(self, delta_x, delta_grad):
+ # Auxiliary variables w and z
+ if self.approx_type == 'hess':
+ w = delta_x
+ z = delta_grad
+ else:
+ w = delta_grad
+ z = delta_x
+ # Do some common operations
+ Mw = self @ w
+ z_minus_Mw = z - Mw
+ denominator = np.dot(w, z_minus_Mw)
+ # If the denominator is too small
+ # we just skip the update.
+ if np.abs(denominator) <= self.min_denominator*norm(w)*norm(z_minus_Mw):
+ return
+ # Update matrix
+ if self.approx_type == 'hess':
+ self.B = self._syr(1/denominator, z_minus_Mw, a=self.B)
+ else:
+ self.H = self._syr(1/denominator, z_minus_Mw, a=self.H)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.__core.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.__core.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.__core.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.__highs_options.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.__highs_options.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.__highs_options.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.__highs_wrapper.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.__highs_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/.__highs_wrapper.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..9cd022a7a0c3dd2e1e35fc54593583834cfdcea5
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_core.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d4055513c1bf675720d702eaefaece699666fadc0a7717b992d51902731e6f4c
+size 5294616
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..200533e213458b73d993a1851c7381c52336673c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_options.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:070e87f8fb2f878475629beac6bc932bbc7959f01348620a03a64d07a0ede40d
+size 405928
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_wrapper.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_wrapper.py
new file mode 100644
index 0000000000000000000000000000000000000000..c88f0fb14c627b10584995fbde17f3a0e445b0cf
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_highspy/_highs_wrapper.py
@@ -0,0 +1,338 @@
+from warnings import warn
+
+import numpy as np
+import scipy.optimize._highspy._core as _h # type: ignore[import-not-found]
+from scipy.optimize._highspy import _highs_options as hopt # type: ignore[attr-defined]
+from scipy.optimize import OptimizeWarning
+
+
+def _highs_wrapper(c, indptr, indices, data, lhs, rhs, lb, ub, integrality, options):
+ '''Solve linear programs using HiGHS [1]_.
+
+ Assume problems of the form:
+
+ MIN c.T @ x
+ s.t. lhs <= A @ x <= rhs
+ lb <= x <= ub
+
+ Parameters
+ ----------
+ c : 1-D array, (n,)
+ Array of objective value coefficients.
+ astart : 1-D array
+ CSC format index array.
+ aindex : 1-D array
+ CSC format index array.
+ avalue : 1-D array
+ Data array of the matrix.
+ lhs : 1-D array (or None), (m,)
+ Array of left hand side values of the inequality constraints.
+ If ``lhs=None``, then an array of ``-inf`` is assumed.
+ rhs : 1-D array, (m,)
+ Array of right hand side values of the inequality constraints.
+ lb : 1-D array (or None), (n,)
+ Lower bounds on solution variables x. If ``lb=None``, then an
+ array of all `0` is assumed.
+ ub : 1-D array (or None), (n,)
+ Upper bounds on solution variables x. If ``ub=None``, then an
+ array of ``inf`` is assumed.
+ options : dict
+ A dictionary of solver options
+
+ Returns
+ -------
+ res : dict
+
+ If model_status is one of kOptimal,
+ kObjectiveBound, kTimeLimit,
+ kIterationLimit:
+
+ - ``status`` : HighsModelStatus
+ Model status code.
+
+ - ``message`` : str
+ Message corresponding to model status code.
+
+ - ``x`` : list
+ Solution variables.
+
+ - ``slack`` : list
+ Slack variables.
+
+ - ``lambda`` : list
+ Lagrange multipliers associated with the constraints
+ Ax = b.
+
+ - ``s`` : list
+ Lagrange multipliers associated with the constraints
+ x >= 0.
+
+ - ``fun``
+ Final objective value.
+
+ - ``simplex_nit`` : int
+ Number of iterations accomplished by the simplex
+ solver.
+
+ - ``ipm_nit`` : int
+ Number of iterations accomplished by the interior-
+ point solver.
+
+ If model_status is not one of the above:
+
+ - ``status`` : HighsModelStatus
+ Model status code.
+
+ - ``message`` : str
+ Message corresponding to model status code.
+
+ Notes
+ -----
+ If ``options['write_solution_to_file']`` is ``True`` but
+ ``options['solution_file']`` is unset or ``''``, then the solution
+ will be printed to ``stdout``.
+
+ If any iteration limit is reached, no solution will be
+ available.
+
+ ``OptimizeWarning`` will be raised if any option value set by
+ the user is found to be incorrect.
+
+ References
+ ----------
+ .. [1] https://highs.dev/
+ .. [2] https://www.maths.ed.ac.uk/hall/HiGHS/HighsOptions.html
+ '''
+ numcol = c.size
+ numrow = rhs.size
+ isMip = integrality is not None and np.sum(integrality) > 0
+
+ # default "null" return values
+ res = {
+ "x": None,
+ "fun": None,
+ }
+
+ # Fill up a HighsLp object
+ lp = _h.HighsLp()
+ lp.num_col_ = numcol
+ lp.num_row_ = numrow
+ lp.a_matrix_.num_col_ = numcol
+ lp.a_matrix_.num_row_ = numrow
+ lp.a_matrix_.format_ = _h.MatrixFormat.kColwise
+ lp.col_cost_ = c
+ lp.col_lower_ = lb
+ lp.col_upper_ = ub
+ lp.row_lower_ = lhs
+ lp.row_upper_ = rhs
+ lp.a_matrix_.start_ = indptr
+ lp.a_matrix_.index_ = indices
+ lp.a_matrix_.value_ = data
+ if integrality.size > 0:
+ lp.integrality_ = [_h.HighsVarType(i) for i in integrality]
+
+ # Make a Highs object and pass it everything
+ highs = _h._Highs()
+ highs_options = _h.HighsOptions()
+ hoptmanager = hopt.HighsOptionsManager()
+ for key, val in options.items():
+ # handle filtering of unsupported and default options
+ if val is None or key in ("sense",):
+ continue
+
+ # ask for the option type
+ opt_type = hoptmanager.get_option_type(key)
+ if -1 == opt_type:
+ warn(
+ f"Unrecognized options detected: {dict({key: val})}",
+ OptimizeWarning,
+ stacklevel=2,
+ )
+ continue
+ else:
+ if key in ("presolve", "parallel"):
+ # handle fake bools (require bool -> str conversions)
+ if isinstance(val, bool):
+ val = "on" if val else "off"
+ else:
+ warn(
+ f'Option f"{key}" is "{val}", but only True or False is '
+ f"allowed. Using default.",
+ OptimizeWarning,
+ stacklevel=2,
+ )
+ continue
+ opt_type = _h.HighsOptionType(opt_type)
+ status, msg = check_option(highs, key, val)
+ if opt_type == _h.HighsOptionType.kBool:
+ if not isinstance(val, bool):
+ warn(
+ f'Option f"{key}" is "{val}", but only True or False is '
+ f"allowed. Using default.",
+ OptimizeWarning,
+ stacklevel=2,
+ )
+ continue
+
+ # warn or set option
+ if status != 0:
+ warn(msg, OptimizeWarning, stacklevel=2)
+ else:
+ setattr(highs_options, key, val)
+
+ opt_status = highs.passOptions(highs_options)
+ if opt_status == _h.HighsStatus.kError:
+ res.update(
+ {
+ "status": highs.getModelStatus(),
+ "message": highs.modelStatusToString(highs.getModelStatus()),
+ }
+ )
+ return res
+
+ init_status = highs.passModel(lp)
+ if init_status == _h.HighsStatus.kError:
+ # if model fails to load, highs.getModelStatus() will be NOT_SET
+ err_model_status = _h.HighsModelStatus.kModelError
+ res.update(
+ {
+ "status": err_model_status,
+ "message": highs.modelStatusToString(err_model_status),
+ }
+ )
+ return res
+
+ # Solve the LP
+ run_status = highs.run()
+ if run_status == _h.HighsStatus.kError:
+ res.update(
+ {
+ "status": highs.getModelStatus(),
+ "message": highs.modelStatusToString(highs.getModelStatus()),
+ }
+ )
+ return res
+
+ # Extract what we need from the solution
+ model_status = highs.getModelStatus()
+
+ # it should always be safe to get the info object
+ info = highs.getInfo()
+
+ # Failure modes:
+ # LP: if we have anything other than an Optimal status, it
+ # is unsafe (and unhelpful) to read any results
+ # MIP: has a non-Optimal status or has timed out/reached max iterations
+ # 1) If not Optimal/TimedOut/MaxIter status, there is no solution
+ # 2) If TimedOut/MaxIter status, there may be a feasible solution.
+ # if the objective function value is not Infinity, then the
+ # current solution is feasible and can be returned. Else, there
+ # is no solution.
+ mipFailCondition = model_status not in (
+ _h.HighsModelStatus.kOptimal,
+ _h.HighsModelStatus.kTimeLimit,
+ _h.HighsModelStatus.kIterationLimit,
+ _h.HighsModelStatus.kSolutionLimit,
+ ) or (
+ model_status
+ in {
+ _h.HighsModelStatus.kTimeLimit,
+ _h.HighsModelStatus.kIterationLimit,
+ _h.HighsModelStatus.kSolutionLimit,
+ }
+ and (info.objective_function_value == _h.kHighsInf)
+ )
+ lpFailCondition = model_status != _h.HighsModelStatus.kOptimal
+ if (isMip and mipFailCondition) or (not isMip and lpFailCondition):
+ res.update(
+ {
+ "status": model_status,
+ "message": "model_status is "
+ f"{highs.modelStatusToString(model_status)}; "
+ "primal_status is "
+ f"{highs.solutionStatusToString(info.primal_solution_status)}",
+ "simplex_nit": info.simplex_iteration_count,
+ "ipm_nit": info.ipm_iteration_count,
+ "crossover_nit": info.crossover_iteration_count,
+ }
+ )
+ return res
+
+ # Should be safe to read the solution:
+ solution = highs.getSolution()
+ basis = highs.getBasis()
+
+ # Lagrangians for bounds based on column statuses
+ marg_bnds = np.zeros((2, numcol))
+ basis_col_status = basis.col_status
+ solution_col_dual = solution.col_dual
+ for ii in range(numcol):
+ if basis_col_status[ii] == _h.HighsBasisStatus.kLower:
+ marg_bnds[0, ii] = solution_col_dual[ii]
+ elif basis_col_status[ii] == _h.HighsBasisStatus.kUpper:
+ marg_bnds[1, ii] = solution_col_dual[ii]
+
+ res.update(
+ {
+ "status": model_status,
+ "message": highs.modelStatusToString(model_status),
+ # Primal solution
+ "x": np.array(solution.col_value),
+ # Ax + s = b => Ax = b - s
+ # Note: this is for all constraints (A_ub and A_eq)
+ "slack": rhs - solution.row_value,
+ # lambda are the lagrange multipliers associated with Ax=b
+ "lambda": np.array(solution.row_dual),
+ "marg_bnds": marg_bnds,
+ "fun": info.objective_function_value,
+ "simplex_nit": info.simplex_iteration_count,
+ "ipm_nit": info.ipm_iteration_count,
+ "crossover_nit": info.crossover_iteration_count,
+ }
+ )
+
+ if isMip:
+ res.update(
+ {
+ "mip_node_count": info.mip_node_count,
+ "mip_dual_bound": info.mip_dual_bound,
+ "mip_gap": info.mip_gap,
+ }
+ )
+
+ return res
+
+
+def check_option(highs_inst, option, value):
+ status, option_type = highs_inst.getOptionType(option)
+ hoptmanager = hopt.HighsOptionsManager()
+
+ if status != _h.HighsStatus.kOk:
+ return -1, "Invalid option name."
+
+ valid_types = {
+ _h.HighsOptionType.kBool: bool,
+ _h.HighsOptionType.kInt: int,
+ _h.HighsOptionType.kDouble: float,
+ _h.HighsOptionType.kString: str,
+ }
+
+ expected_type = valid_types.get(option_type, None)
+
+ if expected_type is str:
+ if not hoptmanager.check_string_option(option, value):
+ return -1, "Invalid option value."
+ if expected_type is float:
+ if not hoptmanager.check_double_option(option, value):
+ return -1, "Invalid option value."
+ if expected_type is int:
+ if not hoptmanager.check_int_option(option, value):
+ return -1, "Invalid option value."
+
+ if expected_type is None:
+ return 3, "Unknown option type."
+
+ status, current_value = highs_inst.getOptionValue(option)
+ if status != _h.HighsStatus.kOk:
+ return 4, "Failed to validate option value."
+ return 0, "Check option succeeded."
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_isotonic.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_isotonic.py
new file mode 100644
index 0000000000000000000000000000000000000000..825576535402a9acf8bbff009a5f76282cb4f500
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_isotonic.py
@@ -0,0 +1,157 @@
+from typing import TYPE_CHECKING
+
+import numpy as np
+
+from ._optimize import OptimizeResult
+from ._pava_pybind import pava
+
+if TYPE_CHECKING:
+ import numpy.typing as npt
+
+
+__all__ = ["isotonic_regression"]
+
+
+def isotonic_regression(
+ y: "npt.ArrayLike",
+ *,
+ weights: "npt.ArrayLike | None" = None,
+ increasing: bool = True,
+) -> OptimizeResult:
+ r"""Nonparametric isotonic regression.
+
+ A (not strictly) monotonically increasing array `x` with the same length
+ as `y` is calculated by the pool adjacent violators algorithm (PAVA), see
+ [1]_. See the Notes section for more details.
+
+ Parameters
+ ----------
+ y : (N,) array_like
+ Response variable.
+ weights : (N,) array_like or None
+ Case weights.
+ increasing : bool
+ If True, fit monotonic increasing, i.e. isotonic, regression.
+ If False, fit a monotonic decreasing, i.e. antitonic, regression.
+ Default is True.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a ``OptimizeResult`` object.
+ Important attributes are:
+
+ - ``x``: The isotonic regression solution, i.e. an increasing (or
+ decreasing) array of the same length than y, with elements in the
+ range from min(y) to max(y).
+ - ``weights`` : Array with the sum of case weights for each block
+ (or pool) B.
+ - ``blocks``: Array of length B+1 with the indices of the start
+ positions of each block (or pool) B. The j-th block is given by
+ ``x[blocks[j]:blocks[j+1]]`` for which all values are the same.
+
+ Notes
+ -----
+ Given data :math:`y` and case weights :math:`w`, the isotonic regression
+ solves the following optimization problem:
+
+ .. math::
+
+ \operatorname{argmin}_{x_i} \sum_i w_i (y_i - x_i)^2 \quad
+ \text{subject to } x_i \leq x_j \text{ whenever } i \leq j \,.
+
+ For every input value :math:`y_i`, it generates a value :math:`x_i` such
+ that :math:`x` is increasing (but not strictly), i.e.
+ :math:`x_i \leq x_{i+1}`. This is accomplished by the PAVA.
+ The solution consists of pools or blocks, i.e. neighboring elements of
+ :math:`x`, e.g. :math:`x_i` and :math:`x_{i+1}`, that all have the same
+ value.
+
+ Most interestingly, the solution stays the same if the squared loss is
+ replaced by the wide class of Bregman functions which are the unique
+ class of strictly consistent scoring functions for the mean, see [2]_
+ and references therein.
+
+ The implemented version of PAVA according to [1]_ has a computational
+ complexity of O(N) with input size N.
+
+ References
+ ----------
+ .. [1] Busing, F. M. T. A. (2022).
+ Monotone Regression: A Simple and Fast O(n) PAVA Implementation.
+ Journal of Statistical Software, Code Snippets, 102(1), 1-25.
+ :doi:`10.18637/jss.v102.c01`
+ .. [2] Jordan, A.I., Mühlemann, A. & Ziegel, J.F.
+ Characterizing the optimal solutions to the isotonic regression
+ problem for identifiable functionals.
+ Ann Inst Stat Math 74, 489-514 (2022).
+ :doi:`10.1007/s10463-021-00808-0`
+
+ Examples
+ --------
+ This example demonstrates that ``isotonic_regression`` really solves a
+ constrained optimization problem.
+
+ >>> import numpy as np
+ >>> from scipy.optimize import isotonic_regression, minimize
+ >>> y = [1.5, 1.0, 4.0, 6.0, 5.7, 5.0, 7.8, 9.0, 7.5, 9.5, 9.0]
+ >>> def objective(yhat, y):
+ ... return np.sum((yhat - y)**2)
+ >>> def constraint(yhat, y):
+ ... # This is for a monotonically increasing regression.
+ ... return np.diff(yhat)
+ >>> result = minimize(objective, x0=y, args=(y,),
+ ... constraints=[{'type': 'ineq',
+ ... 'fun': lambda x: constraint(x, y)}])
+ >>> result.x
+ array([1.25 , 1.25 , 4. , 5.56666667, 5.56666667,
+ 5.56666667, 7.8 , 8.25 , 8.25 , 9.25 ,
+ 9.25 ])
+ >>> result = isotonic_regression(y)
+ >>> result.x
+ array([1.25 , 1.25 , 4. , 5.56666667, 5.56666667,
+ 5.56666667, 7.8 , 8.25 , 8.25 , 9.25 ,
+ 9.25 ])
+
+ The big advantage of ``isotonic_regression`` compared to calling
+ ``minimize`` is that it is more user friendly, i.e. one does not need to
+ define objective and constraint functions, and that it is orders of
+ magnitudes faster. On commodity hardware (in 2023), for normal distributed
+ input y of length 1000, the minimizer takes about 4 seconds, while
+ ``isotonic_regression`` takes about 200 microseconds.
+ """
+ yarr = np.atleast_1d(y) # Check yarr.ndim == 1 is implicit (pybind11) in pava.
+ order = slice(None) if increasing else slice(None, None, -1)
+ x = np.array(yarr[order], order="C", dtype=np.float64, copy=True)
+ if weights is None:
+ wx = np.ones_like(yarr, dtype=np.float64)
+ else:
+ warr = np.atleast_1d(weights)
+
+ if not (yarr.ndim == warr.ndim == 1 and yarr.shape[0] == warr.shape[0]):
+ raise ValueError(
+ "Input arrays y and w must have one dimension of equal length."
+ )
+ if np.any(warr <= 0):
+ raise ValueError("Weights w must be strictly positive.")
+
+ wx = np.array(warr[order], order="C", dtype=np.float64, copy=True)
+ n = x.shape[0]
+ r = np.full(shape=n + 1, fill_value=-1, dtype=np.intp)
+ x, wx, r, b = pava(x, wx, r)
+ # Now that we know the number of blocks b, we only keep the relevant part
+ # of r and wx.
+ # As information: Due to the pava implementation, after the last block
+ # index, there might be smaller numbers appended to r, e.g.
+ # r = [0, 10, 8, 7] which in the end should be r = [0, 10].
+ r = r[:b + 1] # type: ignore[assignment]
+ wx = wx[:b]
+ if not increasing:
+ x = x[::-1]
+ wx = wx[::-1]
+ r = r[-1] - r[::-1]
+ return OptimizeResult(
+ x=x,
+ weights=wx,
+ blocks=r,
+ )
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lbfgsb.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lbfgsb.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..c012236c9e31d84b79cd977a5ff9bdad0992eafb
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lbfgsb.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lbfgsb_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lbfgsb_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..114c7bf7e0c136c39de082a072ac20304b62f6f7
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lbfgsb_py.py
@@ -0,0 +1,634 @@
+"""
+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
+from scipy._lib.deprecation import _NoValue
+import warnings
+
+__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=_NoValue, maxfun=15000, maxiter=15000, disp=_NoValue,
+ 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.18.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.18.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 = {'disp': disp,
+ 'iprint': iprint,
+ '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=_NoValue, maxcor=10, ftol=2.2204460492503131e-09,
+ gtol=1e-5, eps=1e-8, maxfun=15000, maxiter=15000,
+ iprint=_NoValue, callback=None, maxls=20,
+ finite_diff_rel_step=None, workers=None,
+ **unknown_options):
+ """
+ Minimize a scalar function of one or more variables using the L-BFGS-B
+ algorithm.
+
+ Options
+ -------
+ 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.18.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 before minimization terminates.
+ Note that this function may violate the limit if the gradients
+ are evaluated by numerical differentiation.
+ maxiter : int
+ Maximum number of algorithm iterations.
+ 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.18.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.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Notes
+ -----
+ The option `ftol` is exposed via the `scipy.optimize.minimize` interface,
+ but calling `scipy.optimize.fmin_l_bfgs_b` directly exposes `factr`. The
+ relationship between the two is ``ftol = factr * numpy.finfo(float).eps``.
+ I.e., `factr` multiplies the default machine floating-point precision to
+ arrive at `ftol`.
+ If the minimization is slow to converge the optimizer may halt if the
+ total number of function evaluations exceeds `maxfun`, or the number of
+ algorithm iterations has reached `maxiter` (whichever comes first). If
+ this is the case then ``result.success=False``, and an appropriate
+ error message is contained in ``result.message``.
+
+ """
+ _check_unknown_options(unknown_options)
+ m = maxcor
+ pgtol = gtol
+ factr = ftol / np.finfo(float).eps
+
+ x0 = asarray(x0).ravel()
+ n, = x0.shape
+ if disp is not _NoValue:
+ warnings.warn("scipy.optimize: The `disp` and `iprint` options of the "
+ "L-BFGS-B solver are deprecated and will be removed in "
+ "SciPy 1.18.0.",
+ DeprecationWarning, stacklevel=3)
+
+ if iprint is not _NoValue:
+ warnings.warn("scipy.optimize: The `disp` and `iprint` options of the "
+ "L-BFGS-B solver are deprecated and will be removed in "
+ "SciPy 1.18.0.",
+ DeprecationWarning, stacklevel=3)
+
+ # historically old-style bounds were/are expected by lbfgsb.
+ # That's still the case but we'll deal with new-style from here on,
+ # it's easier
+ if bounds is None:
+ pass
+ elif len(bounds) != n:
+ raise ValueError('length of x0 != length of bounds')
+ else:
+ bounds = np.array(old_bound_to_new(bounds))
+
+ # check bounds
+ if (bounds[0] > bounds[1]).any():
+ raise ValueError(
+ "LBFGSB - one of the lower bounds is greater than an upper bound."
+ )
+
+ # initial vector must lie within the bounds. Otherwise ScalarFunction and
+ # approx_derivative will cause problems
+ x0 = np.clip(x0, bounds[0], bounds[1])
+
+ # _prepare_scalar_function can use bounds=None to represent no bounds
+ sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
+ bounds=bounds,
+ finite_diff_rel_step=finite_diff_rel_step,
+ workers=workers)
+
+ func_and_grad = sf.fun_and_grad
+
+ 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.float64)
+ g = zeros((n,), dtype=np.float64)
+ 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 _matmat(self, X):
+ """Efficient matrix-matrix multiply with the BFGS matrices.
+
+ This calculation is described in Section (4) of [1].
+
+ Parameters
+ ----------
+ X : ndarray
+ An array with shape (n,m)
+
+ Returns
+ -------
+ Y : ndarray
+ The matrix-matrix product
+
+ Notes
+ -----
+ This implementation is written starting from _matvec and broadcasting
+ all expressions along the second axis of X.
+
+ """
+ s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
+ Q = np.array(X, dtype=self.dtype, copy=True)
+
+ alpha = np.empty((n_corrs, Q.shape[1]))
+
+ for i in range(n_corrs-1, -1, -1):
+ alpha[i] = rho[i] * np.dot(s[i], Q)
+ Q -= alpha[i]*y[i][:, np.newaxis]
+
+ R = Q
+ for i in range(n_corrs):
+ beta = rho[i] * np.dot(y[i], R)
+ R += s[i][:, np.newaxis] * (alpha[i] - beta)
+
+ return R
+
+ def todense(self):
+ """Return a dense array representation of this operator.
+
+ Returns
+ -------
+ arr : ndarray, shape=(n, n)
+ An array with the same shape and containing
+ the same data represented by this `LinearOperator`.
+
+ """
+ I_arr = np.eye(*self.shape, dtype=self.dtype)
+ return self._matmat(I_arr)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linesearch.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..36ebec841f3f1222992b16ae1eeb437f9dd51903
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/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
+
+ An objective function and its gradient are defined.
+
+ >>> def obj_func(x):
+ ... return (x[0])**2+(x[1])**2
+ >>> def obj_grad(x):
+ ... return [2*x[0], 2*x[1]]
+
+ We can find alpha that satisfies strong Wolfe conditions.
+
+ >>> start_point = np.array([1.8, 1.7])
+ >>> search_gradient = np.array([-1.0, -1.0])
+ >>> line_search(obj_func, obj_grad, start_point, search_gradient)
+ (1.0, 2, 1, 1.1300000000000001, 6.13, [1.6, 1.4])
+
+ """
+ fc = [0]
+ gc = [0]
+ gval = [None]
+ gval_alpha = [None]
+
+ def phi(alpha):
+ fc[0] += 1
+ return f(xk + alpha * pk, *args)
+
+ fprime = myfprime
+
+ def derphi(alpha):
+ gc[0] += 1
+ gval[0] = fprime(xk + alpha * pk, *args) # store for later use
+ gval_alpha[0] = alpha
+ return np.dot(gval[0], pk)
+
+ if gfk is None:
+ gfk = fprime(xk, *args)
+ derphi0 = np.dot(gfk, pk)
+
+ if extra_condition is not None:
+ # Add the current gradient as argument, to avoid needless
+ # re-evaluation
+ def extra_condition2(alpha, phi):
+ if gval_alpha[0] != alpha:
+ derphi(alpha)
+ x = xk + alpha * pk
+ return extra_condition(alpha, x, phi, gval[0])
+ else:
+ extra_condition2 = None
+
+ alpha_star, phi_star, old_fval, derphi_star = scalar_search_wolfe2(
+ phi, derphi, old_fval, old_old_fval, derphi0, c1, c2, amax,
+ extra_condition2, maxiter=maxiter)
+
+ if derphi_star is None:
+ warn('The line search algorithm did not converge',
+ LineSearchWarning, stacklevel=2)
+ else:
+ # derphi_star is a number (derphi) -- so use the most recently
+ # calculated gradient used in computing it derphi = gfk*pk
+ # this is the gradient at the next step no need to compute it
+ # again in the outer loop.
+ derphi_star = gval[0]
+
+ return alpha_star, fc[0], gc[0], phi_star, old_fval, derphi_star
+
+
+def scalar_search_wolfe2(phi, derphi, phi0=None,
+ old_phi0=None, derphi0=None,
+ c1=1e-4, c2=0.9, amax=None,
+ extra_condition=None, maxiter=10):
+ """Find alpha that satisfies strong Wolfe conditions.
+
+ alpha > 0 is assumed to be a descent direction.
+
+ Parameters
+ ----------
+ phi : callable phi(alpha)
+ Objective scalar function.
+ derphi : callable phi'(alpha)
+ Objective function derivative. Returns a scalar.
+ phi0 : float, optional
+ Value of phi at 0.
+ old_phi0 : float, optional
+ Value of phi at previous point.
+ derphi0 : float, optional
+ Value of derphi at 0
+ c1 : float, optional
+ Parameter for Armijo condition rule.
+ c2 : float, optional
+ Parameter for curvature condition rule.
+ amax : float, optional
+ Maximum step size.
+ extra_condition : callable, optional
+ A callable of the form ``extra_condition(alpha, phi_value)``
+ returning a boolean. The line search accepts the value
+ of ``alpha`` only if this callable returns ``True``.
+ If the callable returns ``False`` for the step length,
+ the algorithm will continue with new iterates.
+ The callable is only called for iterates satisfying
+ the strong Wolfe conditions.
+ maxiter : int, optional
+ Maximum number of iterations to perform.
+
+ Returns
+ -------
+ alpha_star : float or None
+ Best alpha, or None if the line search algorithm did not converge.
+ phi_star : float
+ phi at alpha_star.
+ phi0 : float
+ phi at 0.
+ derphi_star : float or None
+ derphi at alpha_star, or None if the line search algorithm
+ did not converge.
+
+ Notes
+ -----
+ Uses the line search algorithm to enforce strong Wolfe
+ conditions. See Wright and Nocedal, 'Numerical Optimization',
+ 1999, pp. 59-61.
+
+ """
+ _check_c1_c2(c1, c2)
+
+ if phi0 is None:
+ phi0 = phi(0.)
+
+ if derphi0 is None:
+ derphi0 = derphi(0.)
+
+ alpha0 = 0
+ if old_phi0 is not None and derphi0 != 0:
+ alpha1 = min(1.0, 1.01*2*(phi0 - old_phi0)/derphi0)
+ else:
+ alpha1 = 1.0
+
+ if alpha1 < 0:
+ alpha1 = 1.0
+
+ if amax is not None:
+ alpha1 = min(alpha1, amax)
+
+ phi_a1 = phi(alpha1)
+ #derphi_a1 = derphi(alpha1) evaluated below
+
+ phi_a0 = phi0
+ derphi_a0 = derphi0
+
+ if extra_condition is None:
+ def extra_condition(alpha, phi):
+ return True
+
+ for i in range(maxiter):
+ if alpha1 == 0 or (amax is not None and alpha0 > amax):
+ # alpha1 == 0: This shouldn't happen. Perhaps the increment has
+ # slipped below machine precision?
+ alpha_star = None
+ phi_star = phi0
+ phi0 = old_phi0
+ derphi_star = None
+
+ if alpha1 == 0:
+ msg = 'Rounding errors prevent the line search from converging'
+ else:
+ msg = "The line search algorithm could not find a solution " + \
+ f"less than or equal to amax: {amax}"
+
+ warn(msg, LineSearchWarning, stacklevel=2)
+ break
+
+ not_first_iteration = i > 0
+ if (phi_a1 > phi0 + c1 * alpha1 * derphi0) or \
+ ((phi_a1 >= phi_a0) and not_first_iteration):
+ alpha_star, phi_star, derphi_star = \
+ _zoom(alpha0, alpha1, phi_a0,
+ phi_a1, derphi_a0, phi, derphi,
+ phi0, derphi0, c1, c2, extra_condition)
+ break
+
+ derphi_a1 = derphi(alpha1)
+ if (abs(derphi_a1) <= -c2*derphi0):
+ if extra_condition(alpha1, phi_a1):
+ alpha_star = alpha1
+ phi_star = phi_a1
+ derphi_star = derphi_a1
+ break
+
+ if (derphi_a1 >= 0):
+ alpha_star, phi_star, derphi_star = \
+ _zoom(alpha1, alpha0, phi_a1,
+ phi_a0, derphi_a1, phi, derphi,
+ phi0, derphi0, c1, c2, extra_condition)
+ break
+
+ alpha2 = 2 * alpha1 # increase by factor of two on each iteration
+ if amax is not None:
+ alpha2 = min(alpha2, amax)
+ alpha0 = alpha1
+ alpha1 = alpha2
+ phi_a0 = phi_a1
+ phi_a1 = phi(alpha1)
+ derphi_a0 = derphi_a1
+
+ else:
+ # stopping test maxiter reached
+ alpha_star = alpha1
+ phi_star = phi_a1
+ derphi_star = None
+ warn('The line search algorithm did not converge',
+ LineSearchWarning, stacklevel=2)
+
+ return alpha_star, phi_star, phi0, derphi_star
+
+
+def _cubicmin(a, fa, fpa, b, fb, c, fc):
+ """
+ Finds the minimizer for a cubic polynomial that goes through the
+ points (a,fa), (b,fb), and (c,fc) with derivative at a of fpa.
+
+ If no minimizer can be found, return None.
+
+ """
+ # f(x) = A *(x-a)^3 + B*(x-a)^2 + C*(x-a) + D
+
+ with np.errstate(divide='raise', over='raise', invalid='raise'):
+ try:
+ C = fpa
+ db = b - a
+ dc = c - a
+ denom = (db * dc) ** 2 * (db - dc)
+ d1 = np.empty((2, 2))
+ d1[0, 0] = dc ** 2
+ d1[0, 1] = -db ** 2
+ d1[1, 0] = -dc ** 3
+ d1[1, 1] = db ** 3
+ [A, B] = np.dot(d1, np.asarray([fb - fa - C * db,
+ fc - fa - C * dc]).flatten())
+ A /= denom
+ B /= denom
+ radical = B * B - 3 * A * C
+ xmin = a + (-B + np.sqrt(radical)) / (3 * A)
+ except ArithmeticError:
+ return None
+ if not np.isfinite(xmin):
+ return None
+ return xmin
+
+
+def _quadmin(a, fa, fpa, b, fb):
+ """
+ Finds the minimizer for a quadratic polynomial that goes through
+ the points (a,fa), (b,fb) with derivative at a of fpa.
+
+ """
+ # f(x) = B*(x-a)^2 + C*(x-a) + D
+ with np.errstate(divide='raise', over='raise', invalid='raise'):
+ try:
+ D = fa
+ C = fpa
+ db = b - a * 1.0
+ B = (fb - D - C * db) / (db * db)
+ xmin = a - C / (2.0 * B)
+ except ArithmeticError:
+ return None
+ if not np.isfinite(xmin):
+ return None
+ return xmin
+
+
+def _zoom(a_lo, a_hi, phi_lo, phi_hi, derphi_lo,
+ phi, derphi, phi0, derphi0, c1, c2, extra_condition):
+ """Zoom stage of approximate linesearch satisfying strong Wolfe conditions.
+
+ Part of the optimization algorithm in `scalar_search_wolfe2`.
+
+ Notes
+ -----
+ Implements Algorithm 3.6 (zoom) in Wright and Nocedal,
+ 'Numerical Optimization', 1999, pp. 61.
+
+ """
+
+ maxiter = 10
+ i = 0
+ delta1 = 0.2 # cubic interpolant check
+ delta2 = 0.1 # quadratic interpolant check
+ phi_rec = phi0
+ a_rec = 0
+ while True:
+ # interpolate to find a trial step length between a_lo and
+ # a_hi Need to choose interpolation here. Use cubic
+ # interpolation and then if the result is within delta *
+ # dalpha or outside of the interval bounded by a_lo or a_hi
+ # then use quadratic interpolation, if the result is still too
+ # close, then use bisection
+
+ dalpha = a_hi - a_lo
+ if dalpha < 0:
+ a, b = a_hi, a_lo
+ else:
+ a, b = a_lo, a_hi
+
+ # minimizer of cubic interpolant
+ # (uses phi_lo, derphi_lo, phi_hi, and the most recent value of phi)
+ #
+ # if the result is too close to the end points (or out of the
+ # interval), then use quadratic interpolation with phi_lo,
+ # derphi_lo and phi_hi if the result is still too close to the
+ # end points (or out of the interval) then use bisection
+
+ if (i > 0):
+ cchk = delta1 * dalpha
+ a_j = _cubicmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi,
+ a_rec, phi_rec)
+ if (i == 0) or (a_j is None) or (a_j > b - cchk) or (a_j < a + cchk):
+ qchk = delta2 * dalpha
+ a_j = _quadmin(a_lo, phi_lo, derphi_lo, a_hi, phi_hi)
+ if (a_j is None) or (a_j > b-qchk) or (a_j < a+qchk):
+ a_j = a_lo + 0.5*dalpha
+
+ # Check new value of a_j
+
+ phi_aj = phi(a_j)
+ if (phi_aj > phi0 + c1*a_j*derphi0) or (phi_aj >= phi_lo):
+ phi_rec = phi_hi
+ a_rec = a_hi
+ a_hi = a_j
+ phi_hi = phi_aj
+ else:
+ derphi_aj = derphi(a_j)
+ if abs(derphi_aj) <= -c2*derphi0 and extra_condition(a_j, phi_aj):
+ a_star = a_j
+ val_star = phi_aj
+ valprime_star = derphi_aj
+ break
+ if derphi_aj*(a_hi - a_lo) >= 0:
+ phi_rec = phi_hi
+ a_rec = a_hi
+ a_hi = a_lo
+ phi_hi = phi_lo
+ else:
+ phi_rec = phi_lo
+ a_rec = a_lo
+ a_lo = a_j
+ phi_lo = phi_aj
+ derphi_lo = derphi_aj
+ i += 1
+ if (i > maxiter):
+ # Failed to find a conforming step size
+ a_star = None
+ val_star = None
+ valprime_star = None
+ break
+ return a_star, val_star, valprime_star
+
+
+#------------------------------------------------------------------------------
+# Armijo line and scalar searches
+#------------------------------------------------------------------------------
+
+def line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1):
+ """Minimize over alpha, the function ``f(xk+alpha pk)``.
+
+ Parameters
+ ----------
+ f : callable
+ Function to be minimized.
+ xk : array_like
+ Current point.
+ pk : array_like
+ Search direction.
+ gfk : array_like
+ Gradient of `f` at point `xk`.
+ old_fval : float
+ Value of `f` at point `xk`.
+ args : tuple, optional
+ Optional arguments.
+ c1 : float, optional
+ Value to control stopping criterion.
+ alpha0 : scalar, optional
+ Value of `alpha` at start of the optimization.
+
+ Returns
+ -------
+ alpha
+ f_count
+ f_val_at_alpha
+
+ Notes
+ -----
+ Uses the interpolation algorithm (Armijo backtracking) as suggested by
+ Wright and Nocedal in 'Numerical Optimization', 1999, pp. 56-57
+
+ """
+ xk = np.atleast_1d(xk)
+ fc = [0]
+
+ def phi(alpha1):
+ fc[0] += 1
+ return f(xk + alpha1*pk, *args)
+
+ if old_fval is None:
+ phi0 = phi(0.)
+ else:
+ phi0 = old_fval # compute f(xk) -- done in past loop
+
+ derphi0 = np.dot(gfk, pk)
+ alpha, phi1 = scalar_search_armijo(phi, phi0, derphi0, c1=c1,
+ alpha0=alpha0)
+ return alpha, fc[0], phi1
+
+
+def line_search_BFGS(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=1):
+ """
+ Compatibility wrapper for `line_search_armijo`
+ """
+ r = line_search_armijo(f, xk, pk, gfk, old_fval, args=args, c1=c1,
+ alpha0=alpha0)
+ return r[0], r[1], 0, r[2]
+
+
+def scalar_search_armijo(phi, phi0, derphi0, c1=1e-4, alpha0=1, amin=0):
+ """Minimize over alpha, the function ``phi(alpha)``.
+
+ Uses the interpolation algorithm (Armijo backtracking) as suggested by
+ Wright and Nocedal in 'Numerical Optimization', 1999, pp. 56-57
+
+ alpha > 0 is assumed to be a descent direction.
+
+ Returns
+ -------
+ alpha
+ phi1
+
+ """
+ phi_a0 = phi(alpha0)
+ if phi_a0 <= phi0 + c1*alpha0*derphi0:
+ return alpha0, phi_a0
+
+ # Otherwise, compute the minimizer of a quadratic interpolant:
+
+ alpha1 = -(derphi0) * alpha0**2 / 2.0 / (phi_a0 - phi0 - derphi0 * alpha0)
+ phi_a1 = phi(alpha1)
+
+ if (phi_a1 <= phi0 + c1*alpha1*derphi0):
+ return alpha1, phi_a1
+
+ # Otherwise, loop with cubic interpolation until we find an alpha which
+ # satisfies the first Wolfe condition (since we are backtracking, we will
+ # assume that the value of alpha is not too small and satisfies the second
+ # condition.
+
+ while alpha1 > amin: # we are assuming alpha>0 is a descent direction
+ factor = alpha0**2 * alpha1**2 * (alpha1-alpha0)
+ a = alpha0**2 * (phi_a1 - phi0 - derphi0*alpha1) - \
+ alpha1**2 * (phi_a0 - phi0 - derphi0*alpha0)
+ a = a / factor
+ b = -alpha0**3 * (phi_a1 - phi0 - derphi0*alpha1) + \
+ alpha1**3 * (phi_a0 - phi0 - derphi0*alpha0)
+ b = b / factor
+
+ alpha2 = (-b + np.sqrt(abs(b**2 - 3 * a * derphi0))) / (3.0*a)
+ phi_a2 = phi(alpha2)
+
+ if (phi_a2 <= phi0 + c1*alpha2*derphi0):
+ return alpha2, phi_a2
+
+ if (alpha1 - alpha2) > alpha1 / 2.0 or (1 - alpha2/alpha1) < 0.96:
+ alpha2 = alpha1 / 2.0
+
+ alpha0 = alpha1
+ alpha1 = alpha2
+ phi_a0 = phi_a1
+ phi_a1 = phi_a2
+
+ # Failed to find a suitable step length
+ return None, phi_a1
+
+
+#------------------------------------------------------------------------------
+# Non-monotone line search for DF-SANE
+#------------------------------------------------------------------------------
+
+def _nonmonotone_line_search_cruz(f, x_k, d, prev_fs, eta,
+ gamma=1e-4, tau_min=0.1, tau_max=0.5):
+ """
+ Nonmonotone backtracking line search as described in [1]_
+
+ Parameters
+ ----------
+ f : callable
+ Function returning a tuple ``(f, F)`` where ``f`` is the value
+ of a merit function and ``F`` the residual.
+ x_k : ndarray
+ Initial position.
+ d : ndarray
+ Search direction.
+ prev_fs : float
+ List of previous merit function values. Should have ``len(prev_fs) <= M``
+ where ``M`` is the nonmonotonicity window parameter.
+ eta : float
+ Allowed merit function increase, see [1]_
+ gamma, tau_min, tau_max : float, optional
+ Search parameters, see [1]_
+
+ Returns
+ -------
+ alpha : float
+ Step length
+ xp : ndarray
+ Next position
+ fp : float
+ Merit function value at next position
+ Fp : ndarray
+ Residual at next position
+
+ References
+ ----------
+ [1] "Spectral residual method without gradient information for solving
+ large-scale nonlinear systems of equations." W. La Cruz,
+ J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006).
+
+ """
+ f_k = prev_fs[-1]
+ f_bar = max(prev_fs)
+
+ alpha_p = 1
+ alpha_m = 1
+ alpha = 1
+
+ while True:
+ xp = x_k + alpha_p * d
+ fp, Fp = f(xp)
+
+ if fp <= f_bar + eta - gamma * alpha_p**2 * f_k:
+ alpha = alpha_p
+ break
+
+ alpha_tp = alpha_p**2 * f_k / (fp + (2*alpha_p - 1)*f_k)
+
+ xp = x_k - alpha_m * d
+ fp, Fp = f(xp)
+
+ if fp <= f_bar + eta - gamma * alpha_m**2 * f_k:
+ alpha = -alpha_m
+ break
+
+ alpha_tm = alpha_m**2 * f_k / (fp + (2*alpha_m - 1)*f_k)
+
+ alpha_p = np.clip(alpha_tp, tau_min * alpha_p, tau_max * alpha_p)
+ alpha_m = np.clip(alpha_tm, tau_min * alpha_m, tau_max * alpha_m)
+
+ return alpha, xp, fp, Fp
+
+
+def _nonmonotone_line_search_cheng(f, x_k, d, f_k, C, Q, eta,
+ gamma=1e-4, tau_min=0.1, tau_max=0.5,
+ nu=0.85):
+ """
+ Nonmonotone line search from [1]
+
+ Parameters
+ ----------
+ f : callable
+ Function returning a tuple ``(f, F)`` where ``f`` is the value
+ of a merit function and ``F`` the residual.
+ x_k : ndarray
+ Initial position.
+ d : ndarray
+ Search direction.
+ f_k : float
+ Initial merit function value.
+ C, Q : float
+ Control parameters. On the first iteration, give values
+ Q=1.0, C=f_k
+ eta : float
+ Allowed merit function increase, see [1]_
+ nu, gamma, tau_min, tau_max : float, optional
+ Search parameters, see [1]_
+
+ Returns
+ -------
+ alpha : float
+ Step length
+ xp : ndarray
+ Next position
+ fp : float
+ Merit function value at next position
+ Fp : ndarray
+ Residual at next position
+ C : float
+ New value for the control parameter C
+ Q : float
+ New value for the control parameter Q
+
+ References
+ ----------
+ .. [1] W. Cheng & D.-H. Li, ''A derivative-free nonmonotone line
+ search and its application to the spectral residual
+ method'', IMA J. Numer. Anal. 29, 814 (2009).
+
+ """
+ alpha_p = 1
+ alpha_m = 1
+ alpha = 1
+
+ while True:
+ xp = x_k + alpha_p * d
+ fp, Fp = f(xp)
+
+ if fp <= C + eta - gamma * alpha_p**2 * f_k:
+ alpha = alpha_p
+ break
+
+ alpha_tp = alpha_p**2 * f_k / (fp + (2*alpha_p - 1)*f_k)
+
+ xp = x_k - alpha_m * d
+ fp, Fp = f(xp)
+
+ if fp <= C + eta - gamma * alpha_m**2 * f_k:
+ alpha = -alpha_m
+ break
+
+ alpha_tm = alpha_m**2 * f_k / (fp + (2*alpha_m - 1)*f_k)
+
+ alpha_p = np.clip(alpha_tp, tau_min * alpha_p, tau_max * alpha_p)
+ alpha_m = np.clip(alpha_tm, tau_min * alpha_m, tau_max * alpha_m)
+
+ # Update C and Q
+ Q_next = nu * Q + 1
+ C = (nu * Q * (C + eta) + fp) / Q_next
+ Q = Q_next
+
+ return alpha, xp, fp, Fp, C, Q
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog.py
new file mode 100644
index 0000000000000000000000000000000000000000..054ba471dcbd4622ab9c2fb9dda313bb124c0451
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog.py
@@ -0,0 +1,733 @@
+"""
+A top-level linear programming interface.
+
+.. versionadded:: 0.15.0
+
+Functions
+---------
+.. autosummary::
+ :toctree: generated/
+
+ linprog
+ linprog_verbose_callback
+ linprog_terse_callback
+
+"""
+
+import numpy as np
+
+from ._optimize import OptimizeResult, OptimizeWarning
+from warnings import warn
+from ._linprog_highs import _linprog_highs
+from ._linprog_ip import _linprog_ip
+from ._linprog_simplex import _linprog_simplex
+from ._linprog_rs import _linprog_rs
+from ._linprog_doc import (_linprog_highs_doc, _linprog_ip_doc, # noqa: F401
+ _linprog_rs_doc, _linprog_simplex_doc,
+ _linprog_highs_ipm_doc, _linprog_highs_ds_doc)
+from ._linprog_util import (
+ _parse_linprog, _presolve, _get_Abc, _LPProblem, _autoscale,
+ _postsolve, _check_result, _display_summary)
+from copy import deepcopy
+
+__all__ = ['linprog', 'linprog_verbose_callback', 'linprog_terse_callback']
+
+__docformat__ = "restructuredtext en"
+
+LINPROG_METHODS = [
+ 'simplex', 'revised simplex', 'interior-point', 'highs', 'highs-ds', 'highs-ipm'
+]
+
+
+def linprog_verbose_callback(res):
+ """
+ A sample callback function demonstrating the linprog callback interface.
+ This callback produces detailed output to sys.stdout before each iteration
+ and after the final iteration of the simplex algorithm.
+
+ Parameters
+ ----------
+ res : A `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ The independent variable vector which optimizes the linear
+ programming problem.
+ fun : float
+ Value of the objective function.
+ success : bool
+ True if the algorithm succeeded in finding an optimal solution.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable corresponds
+ to an inequality constraint. If the slack is zero, then the
+ corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints, that is,
+ ``b - A_eq @ x``
+ phase : int
+ The phase of the optimization being executed. In phase 1 a basic
+ feasible solution is sought and the T has an additional row
+ representing an alternate objective function.
+ status : int
+ An integer representing the exit status of the optimization:
+
+ ``0`` : Optimization terminated successfully
+
+ ``1`` : Iteration limit reached
+
+ ``2`` : Problem appears to be infeasible
+
+ ``3`` : Problem appears to be unbounded
+
+ ``4`` : Serious numerical difficulties encountered
+
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ """
+ x = res['x']
+ fun = res['fun']
+ phase = res['phase']
+ status = res['status']
+ nit = res['nit']
+ message = res['message']
+ complete = res['complete']
+
+ saved_printoptions = np.get_printoptions()
+ np.set_printoptions(linewidth=500,
+ formatter={'float': lambda x: f"{x: 12.4f}"})
+ if status:
+ print('--------- Simplex Early Exit -------\n')
+ print(f'The simplex method exited early with status {status:d}')
+ print(message)
+ elif complete:
+ print('--------- Simplex Complete --------\n')
+ print(f'Iterations required: {nit}')
+ else:
+ print(f'--------- Iteration {nit:d} ---------\n')
+
+ if nit > 0:
+ if phase == 1:
+ print('Current Pseudo-Objective Value:')
+ else:
+ print('Current Objective Value:')
+ print('f = ', fun)
+ print()
+ print('Current Solution Vector:')
+ print('x = ', x)
+ print()
+
+ np.set_printoptions(**saved_printoptions)
+
+
+def linprog_terse_callback(res):
+ """
+ A sample callback function demonstrating the linprog callback interface.
+ This callback produces brief output to sys.stdout before each iteration
+ and after the final iteration of the simplex algorithm.
+
+ Parameters
+ ----------
+ res : A `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ The independent variable vector which optimizes the linear
+ programming problem.
+ fun : float
+ Value of the objective function.
+ success : bool
+ True if the algorithm succeeded in finding an optimal solution.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable corresponds
+ to an inequality constraint. If the slack is zero, then the
+ corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints, that is,
+ ``b - A_eq @ x``.
+ phase : int
+ The phase of the optimization being executed. In phase 1 a basic
+ feasible solution is sought and the T has an additional row
+ representing an alternate objective function.
+ status : int
+ An integer representing the exit status of the optimization:
+
+ ``0`` : Optimization terminated successfully
+
+ ``1`` : Iteration limit reached
+
+ ``2`` : Problem appears to be infeasible
+
+ ``3`` : Problem appears to be unbounded
+
+ ``4`` : Serious numerical difficulties encountered
+
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ """
+ nit = res['nit']
+ x = res['x']
+
+ if nit == 0:
+ print("Iter: X:")
+ print(f"{nit: <5d} ", end="")
+ print(x)
+
+
+def linprog(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=(0, None), method='highs', callback=None,
+ options=None, x0=None, integrality=None):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ - minimize ::
+
+ c @ x
+
+ - such that ::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None``. Other bounds can be
+ specified with ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable.
+ If a single tuple ``(min, max)`` is provided, then ``min`` and ``max``
+ will serve as bounds for all decision variables.
+ Use ``None`` to indicate that there is no bound. For instance, the
+ default bound ``(0, None)`` means that all decision variables are
+ non-negative, and the pair ``(None, None)`` means no bounds at all,
+ i.e. all variables are allowed to be any real.
+ method : str, optional
+ The algorithm used to solve the standard form problem.
+ The following are supported.
+
+ - :ref:`'highs' ` (default)
+ - :ref:`'highs-ds' `
+ - :ref:`'highs-ipm' `
+ - :ref:`'interior-point' ` (legacy)
+ - :ref:`'revised simplex' ` (legacy)
+ - :ref:`'simplex' ` (legacy)
+
+ The legacy methods are deprecated and will be removed in SciPy 1.11.0.
+ callback : callable, optional
+ If a callback function is provided, it will be called at least once per
+ iteration of the algorithm. The callback function must accept a single
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ The current solution vector.
+ fun : float
+ The current value of the objective function ``c @ x``.
+ success : bool
+ ``True`` when the algorithm has completed successfully.
+ slack : 1-D array
+ The (nominally positive) values of the slack,
+ ``b_ub - A_ub @ x``.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ phase : int
+ The phase of the algorithm being executed.
+ status : int
+ An integer representing the status of the algorithm.
+
+ ``0`` : Optimization proceeding nominally.
+
+ ``1`` : Iteration limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : Numerical difficulties encountered.
+
+ nit : int
+ The current iteration number.
+ message : str
+ A string descriptor of the algorithm status.
+
+ Callback functions are not currently supported by the HiGHS methods.
+
+ options : dict, optional
+ A dictionary of solver options. All methods accept the following
+ options:
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ Default: see method-specific documentation.
+ disp : bool
+ Set to ``True`` to print convergence messages.
+ Default: ``False``.
+ presolve : bool
+ Set to ``False`` to disable automatic presolve.
+ Default: ``True``.
+
+ All methods except the HiGHS solvers also accept:
+
+ tol : float
+ A tolerance which determines when a residual is "close enough" to
+ zero to be considered exactly zero.
+ autoscale : bool
+ Set to ``True`` to automatically perform equilibration.
+ Consider using this option if the numerical values in the
+ constraints are separated by several orders of magnitude.
+ Default: ``False``.
+ rr : bool
+ Set to ``False`` to disable automatic redundancy removal.
+ Default: ``True``.
+ rr_method : string
+ Method used to identify and remove redundant rows from the
+ equality constraint matrix after presolve. For problems with
+ dense input, the available methods for redundancy removal are:
+
+ ``SVD``:
+ Repeatedly performs singular value decomposition on
+ the matrix, detecting redundant rows based on nonzeros
+ in the left singular vectors that correspond with
+ zero singular values. May be fast when the matrix is
+ nearly full rank.
+ ``pivot``:
+ Uses the algorithm presented in [5]_ to identify
+ redundant rows.
+ ``ID``:
+ Uses a randomized interpolative decomposition.
+ Identifies columns of the matrix transpose not used in
+ a full-rank interpolative decomposition of the matrix.
+ ``None``:
+ Uses ``svd`` if the matrix is nearly full rank, that is,
+ the difference between the matrix rank and the number
+ of rows is less than five. If not, uses ``pivot``. The
+ behavior of this default is subject to change without
+ prior notice.
+
+ Default: None.
+ For problems with sparse input, this option is ignored, and the
+ pivot-based algorithm presented in [5]_ is used.
+
+ For method-specific options, see
+ :func:`show_options('linprog') `.
+
+ x0 : 1-D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ :ref:`'revised simplex' ` method,
+ and can only be used if `x0` represents a basic feasible solution.
+
+ integrality : 1-D array or int, optional
+ Indicates the type of integrality constraint on each decision variable.
+
+ ``0`` : Continuous variable; no integrality constraint.
+
+ ``1`` : Integer variable; decision variable must be an integer
+ within `bounds`.
+
+ ``2`` : Semi-continuous variable; decision variable must be within
+ `bounds` or take value ``0``.
+
+ ``3`` : Semi-integer variable; decision variable must be an integer
+ within `bounds` or take value ``0``.
+
+ By default, all variables are continuous.
+
+ For mixed integrality constraints, supply an array of shape ``c.shape``.
+ To infer a constraint on each decision variable from shorter inputs,
+ the argument will be broadcast to ``c.shape`` using `numpy.broadcast_to`.
+
+ This argument is currently used only by the
+ :ref:`'highs' ` method and is ignored otherwise.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields
+ below. Note that the return types of the fields may depend on whether
+ the optimization was successful, therefore it is recommended to check
+ `OptimizeResult.status` before relying on the other fields:
+
+ x : 1-D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1-D array
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : Numerical difficulties encountered.
+
+ nit : int
+ The total number of iterations performed in all phases.
+ message : str
+ A string descriptor of the exit status of the algorithm.
+
+ See Also
+ --------
+ show_options : Additional options accepted by the solvers.
+
+ Notes
+ -----
+ This section describes the available solvers that can be selected by the
+ 'method' parameter.
+
+ :ref:`'highs-ds' `, and
+ :ref:`'highs-ipm' ` are interfaces to the
+ HiGHS simplex and interior-point method solvers [13]_, respectively.
+ :ref:`'highs' ` (default) chooses between
+ the two automatically. These are the fastest linear
+ programming solvers in SciPy, especially for large, sparse problems;
+ which of these two is faster is problem-dependent.
+ The other solvers are legacy methods and will be removed when `callback` is
+ supported by the HiGHS methods.
+
+ Method :ref:`'highs-ds' `, is a wrapper of the C++ high
+ performance dual revised simplex implementation (HSOL) [13]_, [14]_.
+ Method :ref:`'highs-ipm' ` is a wrapper of a C++
+ implementation of an **i**\ nterior-\ **p**\ oint **m**\ ethod [13]_; it
+ features a crossover routine, so it is as accurate as a simplex solver.
+ Method :ref:`'highs' ` chooses between the two
+ automatically.
+ For new code involving `linprog`, we recommend explicitly choosing one of
+ these three method values.
+
+ .. versionadded:: 1.6.0
+
+ Method :ref:`'interior-point' `
+ uses the primal-dual path following algorithm
+ as outlined in [4]_. This algorithm supports sparse constraint matrices and
+ is typically faster than the simplex methods, especially for large, sparse
+ problems. Note, however, that the solution returned may be slightly less
+ accurate than those of the simplex methods and will not, in general,
+ correspond with a vertex of the polytope defined by the constraints.
+
+ .. versionadded:: 1.0.0
+
+ Method :ref:`'revised simplex' `
+ uses the revised simplex method as described in
+ [9]_, except that a factorization [11]_ of the basis matrix, rather than
+ its inverse, is efficiently maintained and used to solve the linear systems
+ at each iteration of the algorithm.
+
+ .. versionadded:: 1.3.0
+
+ Method :ref:`'simplex' ` uses a traditional,
+ full-tableau implementation of
+ Dantzig's simplex algorithm [1]_, [2]_ (*not* the
+ Nelder-Mead simplex). This algorithm is included for backwards
+ compatibility and educational purposes.
+
+ .. versionadded:: 0.15.0
+
+ Before applying :ref:`'interior-point' `,
+ :ref:`'revised simplex' `, or
+ :ref:`'simplex' `,
+ a presolve procedure based on [8]_ attempts
+ to identify trivial infeasibilities, trivial unboundedness, and potential
+ problem simplifications. Specifically, it checks for:
+
+ - rows of zeros in ``A_eq`` or ``A_ub``, representing trivial constraints;
+ - columns of zeros in ``A_eq`` `and` ``A_ub``, representing unconstrained
+ variables;
+ - column singletons in ``A_eq``, representing fixed variables; and
+ - column singletons in ``A_ub``, representing simple bounds.
+
+ If presolve reveals that the problem is unbounded (e.g. an unconstrained
+ and unbounded variable has negative cost) or infeasible (e.g., a row of
+ zeros in ``A_eq`` corresponds with a nonzero in ``b_eq``), the solver
+ terminates with the appropriate status code. Note that presolve terminates
+ as soon as any sign of unboundedness is detected; consequently, a problem
+ may be reported as unbounded when in reality the problem is infeasible
+ (but infeasibility has not been detected yet). Therefore, if it is
+ important to know whether the problem is actually infeasible, solve the
+ problem again with option ``presolve=False``.
+
+ If neither infeasibility nor unboundedness are detected in a single pass
+ of the presolve, bounds are tightened where possible and fixed
+ variables are removed from the problem. Then, linearly dependent rows
+ of the ``A_eq`` matrix are removed, (unless they represent an
+ infeasibility) to avoid numerical difficulties in the primary solve
+ routine. Note that rows that are nearly linearly dependent (within a
+ prescribed tolerance) may also be removed, which can change the optimal
+ solution in rare cases. If this is a concern, eliminate redundancy from
+ your problem formulation and run with option ``rr=False`` or
+ ``presolve=False``.
+
+ Several potential improvements can be made here: additional presolve
+ checks outlined in [8]_ should be implemented, the presolve routine should
+ be run multiple times (until no further simplifications can be made), and
+ more of the efficiency improvements from [5]_ should be implemented in the
+ redundancy removal routines.
+
+ After presolve, the problem is transformed to standard form by converting
+ the (tightened) simple bounds to upper bound constraints, introducing
+ non-negative slack variables for inequality constraints, and expressing
+ unbounded variables as the difference between two non-negative variables.
+ Optionally, the problem is automatically scaled via equilibration [12]_.
+ The selected algorithm solves the standard form problem, and a
+ postprocessing routine converts the result to a solution to the original
+ problem.
+
+ References
+ ----------
+ .. [1] Dantzig, George B., Linear programming and extensions. Rand
+ Corporation Research Study Princeton Univ. Press, Princeton, NJ,
+ 1963
+ .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
+ Mathematical Programming", McGraw-Hill, Chapter 4.
+ .. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
+ Mathematics of Operations Research (2), 1977: pp. 103-107.
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+ .. [5] Andersen, Erling D. "Finding all linearly dependent rows in
+ large-scale linear programming." Optimization Methods and Software
+ 6.3 (1995): 219-227.
+ .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
+ Programming based on Newton's Method." Unpublished Course Notes,
+ March 2004. Available 2/25/2017 at
+ https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
+ .. [7] Fourer, Robert. "Solving Linear Programs by Interior-Point Methods."
+ Unpublished Course Notes, August 26, 2005. Available 2/25/2017 at
+ http://www.4er.org/CourseNotes/Book%20B/B-III.pdf
+ .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
+ programming." Mathematical Programming 71.2 (1995): 221-245.
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+ .. [10] Andersen, Erling D., et al. Implementation of interior point
+ methods for large scale linear programming. HEC/Universite de
+ Geneve, 1996.
+ .. [11] Bartels, Richard H. "A stabilization of the simplex method."
+ Journal in Numerische Mathematik 16.5 (1971): 414-434.
+ .. [12] Tomlin, J. A. "On scaling linear programming problems."
+ Mathematical Programming Study 4 (1975): 146-166.
+ .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
+ "HiGHS - high performance software for linear optimization."
+ https://highs.dev/
+ .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
+ simplex method." Mathematical Programming Computation, 10 (1),
+ 119-142, 2018. DOI: 10.1007/s12532-017-0130-5
+
+ Examples
+ --------
+ Consider the following problem:
+
+ .. math::
+
+ \min_{x_0, x_1} \ -x_0 + 4x_1 & \\
+ \mbox{such that} \ -3x_0 + x_1 & \leq 6,\\
+ -x_0 - 2x_1 & \geq -4,\\
+ x_1 & \geq -3.
+
+ The problem is not presented in the form accepted by `linprog`. This is
+ easily remedied by converting the "greater than" inequality
+ constraint to a "less than" inequality constraint by
+ multiplying both sides by a factor of :math:`-1`. Note also that the last
+ constraint is really the simple bound :math:`-3 \leq x_1 \leq \infty`.
+ Finally, since there are no bounds on :math:`x_0`, we must explicitly
+ specify the bounds :math:`-\infty \leq x_0 \leq \infty`, as the
+ default is for variables to be non-negative. After collecting coeffecients
+ into arrays and tuples, the input for this problem is:
+
+ >>> from scipy.optimize import linprog
+ >>> c = [-1, 4]
+ >>> A = [[-3, 1], [1, 2]]
+ >>> b = [6, 4]
+ >>> x0_bounds = (None, None)
+ >>> x1_bounds = (-3, None)
+ >>> res = linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds])
+ >>> res.fun
+ -22.0
+ >>> res.x
+ array([10., -3.])
+ >>> res.message
+ 'Optimization terminated successfully. (HiGHS Status 7: Optimal)'
+
+ The marginals (AKA dual values / shadow prices / Lagrange multipliers)
+ and residuals (slacks) are also available.
+
+ >>> res.ineqlin
+ residual: [ 3.900e+01 0.000e+00]
+ marginals: [-0.000e+00 -1.000e+00]
+
+ For example, because the marginal associated with the second inequality
+ constraint is -1, we expect the optimal value of the objective function
+ to decrease by ``eps`` if we add a small amount ``eps`` to the right hand
+ side of the second inequality constraint:
+
+ >>> eps = 0.05
+ >>> b[1] += eps
+ >>> linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun
+ -22.05
+
+ Also, because the residual on the first inequality constraint is 39, we
+ can decrease the right hand side of the first constraint by 39 without
+ affecting the optimal solution.
+
+ >>> b = [6, 4] # reset to original values
+ >>> b[0] -= 39
+ >>> linprog(c, A_ub=A, b_ub=b, bounds=[x0_bounds, x1_bounds]).fun
+ -22.0
+
+ """
+
+ meth = method.lower()
+ methods = {"highs", "highs-ds", "highs-ipm",
+ "simplex", "revised simplex", "interior-point"}
+
+ if meth not in methods:
+ raise ValueError(f"Unknown solver '{method}'")
+
+ if x0 is not None and meth != "revised simplex":
+ warning_message = "x0 is used only when method is 'revised simplex'. "
+ warn(warning_message, OptimizeWarning, stacklevel=2)
+
+ if np.any(integrality) and not meth == "highs":
+ integrality = None
+ warning_message = ("Only `method='highs'` supports integer "
+ "constraints. Ignoring `integrality`.")
+ warn(warning_message, OptimizeWarning, stacklevel=2)
+ elif np.any(integrality):
+ integrality = np.broadcast_to(integrality, np.shape(c))
+ else:
+ integrality = None
+
+ lp = _LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality)
+ lp, solver_options = _parse_linprog(lp, options, meth)
+ tol = solver_options.get('tol', 1e-9)
+
+ # Give unmodified problem to HiGHS
+ if meth.startswith('highs'):
+ if callback is not None:
+ raise NotImplementedError("HiGHS solvers do not support the "
+ "callback interface.")
+ highs_solvers = {'highs-ipm': 'ipm', 'highs-ds': 'simplex',
+ 'highs': None}
+
+ sol = _linprog_highs(lp, solver=highs_solvers[meth],
+ **solver_options)
+ sol['status'], sol['message'] = (
+ _check_result(sol['x'], sol['fun'], sol['status'], sol['slack'],
+ sol['con'], lp.bounds, tol, sol['message'],
+ integrality))
+ sol['success'] = sol['status'] == 0
+ return OptimizeResult(sol)
+
+ warn(f"`method='{meth}'` is deprecated and will be removed in SciPy "
+ "1.11.0. Please use one of the HiGHS solvers (e.g. "
+ "`method='highs'`) in new code.", DeprecationWarning, stacklevel=2)
+
+ iteration = 0
+ complete = False # will become True if solved in presolve
+ undo = []
+
+ # Keep the original arrays to calculate slack/residuals for original
+ # problem.
+ lp_o = deepcopy(lp)
+
+ # Solve trivial problem, eliminate variables, tighten bounds, etc.
+ rr_method = solver_options.pop('rr_method', None) # need to pop these;
+ rr = solver_options.pop('rr', True) # they're not passed to methods
+ c0 = 0 # we might get a constant term in the objective
+ if solver_options.pop('presolve', True):
+ (lp, c0, x, undo, complete, status, message) = _presolve(lp, rr,
+ rr_method,
+ tol)
+
+ C, b_scale = 1, 1 # for trivial unscaling if autoscale is not used
+ postsolve_args = (lp_o._replace(bounds=lp.bounds), undo, C, b_scale)
+
+ if not complete:
+ A, b, c, c0, x0 = _get_Abc(lp, c0)
+ if solver_options.pop('autoscale', False):
+ A, b, c, x0, C, b_scale = _autoscale(A, b, c, x0)
+ postsolve_args = postsolve_args[:-2] + (C, b_scale)
+
+ if meth == 'simplex':
+ x, status, message, iteration = _linprog_simplex(
+ c, c0=c0, A=A, b=b, callback=callback,
+ postsolve_args=postsolve_args, **solver_options)
+ elif meth == 'interior-point':
+ x, status, message, iteration = _linprog_ip(
+ c, c0=c0, A=A, b=b, callback=callback,
+ postsolve_args=postsolve_args, **solver_options)
+ elif meth == 'revised simplex':
+ x, status, message, iteration = _linprog_rs(
+ c, c0=c0, A=A, b=b, x0=x0, callback=callback,
+ postsolve_args=postsolve_args, **solver_options)
+
+ # Eliminate artificial variables, re-introduce presolved variables, etc.
+ disp = solver_options.get('disp', False)
+
+ x, fun, slack, con = _postsolve(x, postsolve_args, complete)
+
+ status, message = _check_result(x, fun, status, slack, con, lp_o.bounds,
+ tol, message, integrality)
+
+ if disp:
+ _display_summary(message, status, fun, iteration)
+
+ sol = {
+ 'x': x,
+ 'fun': fun,
+ 'slack': slack,
+ 'con': con,
+ 'status': status,
+ 'message': message,
+ 'nit': iteration,
+ 'success': status == 0}
+
+ return OptimizeResult(sol)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_doc.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_doc.py
new file mode 100644
index 0000000000000000000000000000000000000000..9a34a79dfcbdfacb4d9effe1248a8b6b189ba5ba
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_doc.py
@@ -0,0 +1,1434 @@
+"""
+Created on Sat Aug 22 19:49:17 2020
+
+@author: matth
+"""
+
+
+def _linprog_highs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='highs', callback=None,
+ maxiter=None, disp=False, presolve=True,
+ time_limit=None,
+ dual_feasibility_tolerance=None,
+ primal_feasibility_tolerance=None,
+ ipm_optimality_tolerance=None,
+ simplex_dual_edge_weight_strategy=None,
+ mip_rel_gap=None,
+ **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using one of the HiGHS solvers.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+
+ This is the method-specific documentation for 'highs', which chooses
+ automatically between
+ :ref:`'highs-ds' ` and
+ :ref:`'highs-ipm' `.
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy)
+ are also available.
+ integrality : 1-D array or int, optional
+ Indicates the type of integrality constraint on each decision variable.
+
+ ``0`` : Continuous variable; no integrality constraint.
+
+ ``1`` : Integer variable; decision variable must be an integer
+ within `bounds`.
+
+ ``2`` : Semi-continuous variable; decision variable must be within
+ `bounds` or take value ``0``.
+
+ ``3`` : Semi-integer variable; decision variable must be an integer
+ within `bounds` or take value ``0``.
+
+ By default, all variables are continuous.
+
+ For mixed integrality constraints, supply an array of shape `c.shape`.
+ To infer a constraint on each decision variable from shorter inputs,
+ the argument will be broadcast to `c.shape` using `np.broadcast_to`.
+
+ This argument is currently used only by the ``'highs'`` method and
+ ignored otherwise.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform in either phase.
+ For :ref:`'highs-ipm' `, this does not
+ include the number of crossover iterations. Default is the largest
+ possible value for an ``int`` on the platform.
+ disp : bool (default: ``False``)
+ Set to ``True`` if indicators of optimization status are to be
+ printed to the console during optimization.
+ presolve : bool (default: ``True``)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ time_limit : float
+ The maximum time in seconds allotted to solve the problem;
+ default is the largest possible value for a ``double`` on the
+ platform.
+ dual_feasibility_tolerance : double (default: 1e-07)
+ Dual feasibility tolerance for
+ :ref:`'highs-ds' `.
+ The minimum of this and ``primal_feasibility_tolerance``
+ is used for the feasibility tolerance of
+ :ref:`'highs-ipm' `.
+ primal_feasibility_tolerance : double (default: 1e-07)
+ Primal feasibility tolerance for
+ :ref:`'highs-ds' `.
+ The minimum of this and ``dual_feasibility_tolerance``
+ is used for the feasibility tolerance of
+ :ref:`'highs-ipm' `.
+ ipm_optimality_tolerance : double (default: ``1e-08``)
+ Optimality tolerance for
+ :ref:`'highs-ipm' `.
+ Minimum allowable value is 1e-12.
+ simplex_dual_edge_weight_strategy : str (default: None)
+ Strategy for simplex dual edge weights. The default, ``None``,
+ automatically selects one of the following.
+
+ ``'dantzig'`` uses Dantzig's original strategy of choosing the most
+ negative reduced cost.
+
+ ``'devex'`` uses the strategy described in [15]_.
+
+ ``steepest`` uses the exact steepest edge strategy as described in
+ [16]_.
+
+ ``'steepest-devex'`` begins with the exact steepest edge strategy
+ until the computation is too costly or inexact and then switches to
+ the devex method.
+
+ Currently, ``None`` always selects ``'steepest-devex'``, but this
+ may change as new options become available.
+ mip_rel_gap : double (default: None)
+ Termination criterion for MIP solver: solver will terminate when the
+ gap between the primal objective value and the dual objective bound,
+ scaled by the primal objective value, is <= mip_rel_gap.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ ``unknown_options`` is non-empty, a warning is issued listing
+ all unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1D array
+ The (nominally positive) values of the slack,
+ ``b_ub - A_ub @ x``.
+ con : 1D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration or time limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : The HiGHS solver ran into a problem.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed.
+ For the HiGHS simplex method, this includes iterations in all
+ phases. For the HiGHS interior-point method, this does not include
+ crossover iterations.
+ crossover_nit : int
+ The number of primal/dual pushes performed during the
+ crossover routine for the HiGHS interior-point method.
+ This is ``0`` for the HiGHS simplex method.
+ ineqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ inequality constraints, `b_ub`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndnarray
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``. This quantity is also commonly
+ referred to as "slack".
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ inequality constraints, `b_ub`.
+
+ eqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ equality constraints, `b_eq`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndarray
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ equality constraints, `b_eq`.
+
+ lower, upper : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ lower and upper bounds on decision variables, `bounds`.
+
+ residual : np.ndarray
+ The (nominally positive) values of the quantity
+ ``x - lb`` (lower) or ``ub - x`` (upper).
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the lower and upper
+ `bounds`.
+
+ Notes
+ -----
+
+ Method :ref:`'highs-ds' ` is a wrapper
+ of the C++ high performance dual revised simplex implementation (HSOL)
+ [13]_, [14]_. Method :ref:`'highs-ipm' `
+ is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint
+ **m**\ ethod [13]_; it features a crossover routine, so it is as accurate
+ as a simplex solver. Method :ref:`'highs' ` chooses
+ between the two automatically. For new code involving `linprog`, we
+ recommend explicitly choosing one of these three method values instead of
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy).
+
+ The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
+ `marginals`, or partial derivatives of the objective function with respect
+ to the right-hand side of each constraint. These partial derivatives are
+ also referred to as "Lagrange multipliers", "dual values", and
+ "shadow prices". The sign convention of `marginals` is opposite that
+ of Lagrange multipliers produced by many nonlinear solvers.
+
+ References
+ ----------
+ .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
+ "HiGHS - high performance software for linear optimization."
+ https://highs.dev/
+ .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
+ simplex method." Mathematical Programming Computation, 10 (1),
+ 119-142, 2018. DOI: 10.1007/s12532-017-0130-5
+ .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code."
+ Mathematical programming 5.1 (1973): 1-28.
+ .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge
+ simplex algorithm." Mathematical Programming 12.1 (1977): 361-371.
+ """
+ pass
+
+
+def _linprog_highs_ds_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='highs-ds', callback=None,
+ maxiter=None, disp=False, presolve=True,
+ time_limit=None,
+ dual_feasibility_tolerance=None,
+ primal_feasibility_tolerance=None,
+ simplex_dual_edge_weight_strategy=None,
+ **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using the HiGHS dual simplex solver.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+
+ This is the method-specific documentation for 'highs-ds'.
+ :ref:`'highs' `,
+ :ref:`'highs-ipm' `,
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy)
+ are also available.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform in either phase.
+ Default is the largest possible value for an ``int`` on the platform.
+ disp : bool (default: ``False``)
+ Set to ``True`` if indicators of optimization status are to be
+ printed to the console during optimization.
+ presolve : bool (default: ``True``)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ time_limit : float
+ The maximum time in seconds allotted to solve the problem;
+ default is the largest possible value for a ``double`` on the
+ platform.
+ dual_feasibility_tolerance : double (default: 1e-07)
+ Dual feasibility tolerance for
+ :ref:`'highs-ds' `.
+ primal_feasibility_tolerance : double (default: 1e-07)
+ Primal feasibility tolerance for
+ :ref:`'highs-ds' `.
+ simplex_dual_edge_weight_strategy : str (default: None)
+ Strategy for simplex dual edge weights. The default, ``None``,
+ automatically selects one of the following.
+
+ ``'dantzig'`` uses Dantzig's original strategy of choosing the most
+ negative reduced cost.
+
+ ``'devex'`` uses the strategy described in [15]_.
+
+ ``steepest`` uses the exact steepest edge strategy as described in
+ [16]_.
+
+ ``'steepest-devex'`` begins with the exact steepest edge strategy
+ until the computation is too costly or inexact and then switches to
+ the devex method.
+
+ Currently, ``None`` always selects ``'steepest-devex'``, but this
+ may change as new options become available.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ ``unknown_options`` is non-empty, a warning is issued listing
+ all unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1D array
+ The (nominally positive) values of the slack,
+ ``b_ub - A_ub @ x``.
+ con : 1D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration or time limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : The HiGHS solver ran into a problem.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed. This includes iterations
+ in all phases.
+ crossover_nit : int
+ This is always ``0`` for the HiGHS simplex method.
+ For the HiGHS interior-point method, this is the number of
+ primal/dual pushes performed during the crossover routine.
+ ineqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ inequality constraints, `b_ub`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndnarray
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``. This quantity is also commonly
+ referred to as "slack".
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ inequality constraints, `b_ub`.
+
+ eqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ equality constraints, `b_eq`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndarray
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ equality constraints, `b_eq`.
+
+ lower, upper : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ lower and upper bounds on decision variables, `bounds`.
+
+ residual : np.ndarray
+ The (nominally positive) values of the quantity
+ ``x - lb`` (lower) or ``ub - x`` (upper).
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the lower and upper
+ `bounds`.
+
+ Notes
+ -----
+
+ Method :ref:`'highs-ds' ` is a wrapper
+ of the C++ high performance dual revised simplex implementation (HSOL)
+ [13]_, [14]_. Method :ref:`'highs-ipm' `
+ is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint
+ **m**\ ethod [13]_; it features a crossover routine, so it is as accurate
+ as a simplex solver. Method :ref:`'highs' ` chooses
+ between the two automatically. For new code involving `linprog`, we
+ recommend explicitly choosing one of these three method values instead of
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy).
+
+ The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
+ `marginals`, or partial derivatives of the objective function with respect
+ to the right-hand side of each constraint. These partial derivatives are
+ also referred to as "Lagrange multipliers", "dual values", and
+ "shadow prices". The sign convention of `marginals` is opposite that
+ of Lagrange multipliers produced by many nonlinear solvers.
+
+ References
+ ----------
+ .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
+ "HiGHS - high performance software for linear optimization."
+ https://highs.dev/
+ .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
+ simplex method." Mathematical Programming Computation, 10 (1),
+ 119-142, 2018. DOI: 10.1007/s12532-017-0130-5
+ .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code."
+ Mathematical programming 5.1 (1973): 1-28.
+ .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge
+ simplex algorithm." Mathematical Programming 12.1 (1977): 361-371.
+ """
+ pass
+
+
+def _linprog_highs_ipm_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='highs-ipm', callback=None,
+ maxiter=None, disp=False, presolve=True,
+ time_limit=None,
+ dual_feasibility_tolerance=None,
+ primal_feasibility_tolerance=None,
+ ipm_optimality_tolerance=None,
+ **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using the HiGHS interior point solver.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+
+ This is the method-specific documentation for 'highs-ipm'.
+ :ref:`'highs-ipm' `,
+ :ref:`'highs-ds' `,
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy)
+ are also available.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform in either phase.
+ For :ref:`'highs-ipm' `, this does not
+ include the number of crossover iterations. Default is the largest
+ possible value for an ``int`` on the platform.
+ disp : bool (default: ``False``)
+ Set to ``True`` if indicators of optimization status are to be
+ printed to the console during optimization.
+ presolve : bool (default: ``True``)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ time_limit : float
+ The maximum time in seconds allotted to solve the problem;
+ default is the largest possible value for a ``double`` on the
+ platform.
+ dual_feasibility_tolerance : double (default: 1e-07)
+ The minimum of this and ``primal_feasibility_tolerance``
+ is used for the feasibility tolerance of
+ :ref:`'highs-ipm' `.
+ primal_feasibility_tolerance : double (default: 1e-07)
+ The minimum of this and ``dual_feasibility_tolerance``
+ is used for the feasibility tolerance of
+ :ref:`'highs-ipm' `.
+ ipm_optimality_tolerance : double (default: ``1e-08``)
+ Optimality tolerance for
+ :ref:`'highs-ipm' `.
+ Minimum allowable value is 1e-12.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ ``unknown_options`` is non-empty, a warning is issued listing
+ all unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1D array
+ The (nominally positive) values of the slack,
+ ``b_ub - A_ub @ x``.
+ con : 1D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration or time limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : The HiGHS solver ran into a problem.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed.
+ For the HiGHS interior-point method, this does not include
+ crossover iterations.
+ crossover_nit : int
+ The number of primal/dual pushes performed during the
+ crossover routine for the HiGHS interior-point method.
+ ineqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ inequality constraints, `b_ub`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndnarray
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``. This quantity is also commonly
+ referred to as "slack".
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ inequality constraints, `b_ub`.
+
+ eqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ equality constraints, `b_eq`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndarray
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ equality constraints, `b_eq`.
+
+ lower, upper : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ lower and upper bounds on decision variables, `bounds`.
+
+ residual : np.ndarray
+ The (nominally positive) values of the quantity
+ ``x - lb`` (lower) or ``ub - x`` (upper).
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the lower and upper
+ `bounds`.
+
+ Notes
+ -----
+
+ Method :ref:`'highs-ipm' `
+ is a wrapper of a C++ implementation of an **i**\ nterior-\ **p**\ oint
+ **m**\ ethod [13]_; it features a crossover routine, so it is as accurate
+ as a simplex solver.
+ Method :ref:`'highs-ds' ` is a wrapper
+ of the C++ high performance dual revised simplex implementation (HSOL)
+ [13]_, [14]_. Method :ref:`'highs' ` chooses
+ between the two automatically. For new code involving `linprog`, we
+ recommend explicitly choosing one of these three method values instead of
+ :ref:`'interior-point' ` (default),
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy).
+
+ The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
+ `marginals`, or partial derivatives of the objective function with respect
+ to the right-hand side of each constraint. These partial derivatives are
+ also referred to as "Lagrange multipliers", "dual values", and
+ "shadow prices". The sign convention of `marginals` is opposite that
+ of Lagrange multipliers produced by many nonlinear solvers.
+
+ References
+ ----------
+ .. [13] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
+ "HiGHS - high performance software for linear optimization."
+ https://highs.dev/
+ .. [14] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
+ simplex method." Mathematical Programming Computation, 10 (1),
+ 119-142, 2018. DOI: 10.1007/s12532-017-0130-5
+ """
+ pass
+
+
+def _linprog_ip_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='interior-point', callback=None,
+ maxiter=1000, disp=False, presolve=True,
+ tol=1e-8, autoscale=False, rr=True,
+ alpha0=.99995, beta=0.1, sparse=False,
+ lstsq=False, sym_pos=True, cholesky=True, pc=True,
+ ip=False, permc_spec='MMD_AT_PLUS_A', **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using the interior-point method of
+ [4]_.
+
+ .. deprecated:: 1.9.0
+ `method='interior-point'` will be removed in SciPy 1.11.0.
+ It is replaced by `method='highs'` because the latter is
+ faster and more robust.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+ This is the method-specific documentation for 'interior-point'.
+ :ref:`'highs' `,
+ :ref:`'highs-ds' `,
+ :ref:`'highs-ipm' `,
+ :ref:`'revised simplex' `, and
+ :ref:`'simplex' ` (legacy)
+ are also available.
+ callback : callable, optional
+ Callback function to be executed once per iteration.
+
+ Options
+ -------
+ maxiter : int (default: 1000)
+ The maximum number of iterations of the algorithm.
+ disp : bool (default: False)
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ presolve : bool (default: True)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ tol : float (default: 1e-8)
+ Termination tolerance to be used for all termination criteria;
+ see [4]_ Section 4.5.
+ autoscale : bool (default: False)
+ Set to ``True`` to automatically perform equilibration.
+ Consider using this option if the numerical values in the
+ constraints are separated by several orders of magnitude.
+ rr : bool (default: True)
+ Set to ``False`` to disable automatic redundancy removal.
+ alpha0 : float (default: 0.99995)
+ The maximal step size for Mehrota's predictor-corrector search
+ direction; see :math:`\beta_{3}` of [4]_ Table 8.1.
+ beta : float (default: 0.1)
+ The desired reduction of the path parameter :math:`\mu` (see [6]_)
+ when Mehrota's predictor-corrector is not in use (uncommon).
+ sparse : bool (default: False)
+ Set to ``True`` if the problem is to be treated as sparse after
+ presolve. If either ``A_eq`` or ``A_ub`` is sparse,
+ this option will automatically be set ``True``, and the problem
+ will be treated as sparse even during presolve. If your constraint
+ matrices contain mostly zeros and the problem is not very small (less
+ than about 100 constraints or variables), consider setting ``True``
+ or providing ``A_eq`` and ``A_ub`` as sparse arrays.
+ lstsq : bool (default: ``False``)
+ Set to ``True`` if the problem is expected to be very poorly
+ conditioned. This should always be left ``False`` unless severe
+ numerical difficulties are encountered. Leave this at the default
+ unless you receive a warning message suggesting otherwise.
+ sym_pos : bool (default: True)
+ Leave ``True`` if the problem is expected to yield a well conditioned
+ symmetric positive definite normal equation matrix
+ (almost always). Leave this at the default unless you receive
+ a warning message suggesting otherwise.
+ cholesky : bool (default: True)
+ Set to ``True`` if the normal equations are to be solved by explicit
+ Cholesky decomposition followed by explicit forward/backward
+ substitution. This is typically faster for problems
+ that are numerically well-behaved.
+ pc : bool (default: True)
+ Leave ``True`` if the predictor-corrector method of Mehrota is to be
+ used. This is almost always (if not always) beneficial.
+ ip : bool (default: False)
+ Set to ``True`` if the improved initial point suggestion due to [4]_
+ Section 4.3 is desired. Whether this is beneficial or not
+ depends on the problem.
+ permc_spec : str (default: 'MMD_AT_PLUS_A')
+ (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
+ True``, and no SuiteSparse.)
+ A matrix is factorized in each iteration of the algorithm.
+ This option specifies how to permute the columns of the matrix for
+ sparsity preservation. Acceptable values are:
+
+ - ``NATURAL``: natural ordering.
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+ - ``COLAMD``: approximate minimum degree column ordering.
+
+ This option can impact the convergence of the
+ interior point algorithm; test different values to determine which
+ performs best for your problem. For more information, refer to
+ ``scipy.sparse.linalg.splu``.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1-D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1-D array
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : Numerical difficulties encountered.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed in all phases.
+
+
+ Notes
+ -----
+ This method implements the algorithm outlined in [4]_ with ideas from [8]_
+ and a structure inspired by the simpler methods of [6]_.
+
+ The primal-dual path following method begins with initial 'guesses' of
+ the primal and dual variables of the standard form problem and iteratively
+ attempts to solve the (nonlinear) Karush-Kuhn-Tucker conditions for the
+ problem with a gradually reduced logarithmic barrier term added to the
+ objective. This particular implementation uses a homogeneous self-dual
+ formulation, which provides certificates of infeasibility or unboundedness
+ where applicable.
+
+ The default initial point for the primal and dual variables is that
+ defined in [4]_ Section 4.4 Equation 8.22. Optionally (by setting initial
+ point option ``ip=True``), an alternate (potentially improved) starting
+ point can be calculated according to the additional recommendations of
+ [4]_ Section 4.4.
+
+ A search direction is calculated using the predictor-corrector method
+ (single correction) proposed by Mehrota and detailed in [4]_ Section 4.1.
+ (A potential improvement would be to implement the method of multiple
+ corrections described in [4]_ Section 4.2.) In practice, this is
+ accomplished by solving the normal equations, [4]_ Section 5.1 Equations
+ 8.31 and 8.32, derived from the Newton equations [4]_ Section 5 Equations
+ 8.25 (compare to [4]_ Section 4 Equations 8.6-8.8). The advantage of
+ solving the normal equations rather than 8.25 directly is that the
+ matrices involved are symmetric positive definite, so Cholesky
+ decomposition can be used rather than the more expensive LU factorization.
+
+ With default options, the solver used to perform the factorization depends
+ on third-party software availability and the conditioning of the problem.
+
+ For dense problems, solvers are tried in the following order:
+
+ 1. ``scipy.linalg.cho_factor``
+
+ 2. ``scipy.linalg.solve`` with option ``sym_pos=True``
+
+ 3. ``scipy.linalg.solve`` with option ``sym_pos=False``
+
+ 4. ``scipy.linalg.lstsq``
+
+ For sparse problems:
+
+ 1. ``sksparse.cholmod.cholesky`` (if scikit-sparse and SuiteSparse are
+ installed)
+
+ 2. ``scipy.sparse.linalg.factorized`` (if scikit-umfpack and SuiteSparse
+ are installed)
+
+ 3. ``scipy.sparse.linalg.splu`` (which uses SuperLU distributed with SciPy)
+
+ 4. ``scipy.sparse.linalg.lsqr``
+
+ If the solver fails for any reason, successively more robust (but slower)
+ solvers are attempted in the order indicated. Attempting, failing, and
+ re-starting factorization can be time consuming, so if the problem is
+ numerically challenging, options can be set to bypass solvers that are
+ failing. Setting ``cholesky=False`` skips to solver 2,
+ ``sym_pos=False`` skips to solver 3, and ``lstsq=True`` skips
+ to solver 4 for both sparse and dense problems.
+
+ Potential improvements for combating issues associated with dense
+ columns in otherwise sparse problems are outlined in [4]_ Section 5.3 and
+ [10]_ Section 4.1-4.2; the latter also discusses the alleviation of
+ accuracy issues associated with the substitution approach to free
+ variables.
+
+ After calculating the search direction, the maximum possible step size
+ that does not activate the non-negativity constraints is calculated, and
+ the smaller of this step size and unity is applied (as in [4]_ Section
+ 4.1.) [4]_ Section 4.3 suggests improvements for choosing the step size.
+
+ The new point is tested according to the termination conditions of [4]_
+ Section 4.5. The same tolerance, which can be set using the ``tol`` option,
+ is used for all checks. (A potential improvement would be to expose
+ the different tolerances to be set independently.) If optimality,
+ unboundedness, or infeasibility is detected, the solve procedure
+ terminates; otherwise it repeats.
+
+ Whereas the top level ``linprog`` module expects a problem of form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ where ``lb = 0`` and ``ub = None`` unless set in ``bounds``. The problem
+ is automatically converted to the form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ for solution. That is, the original problem contains equality, upper-bound
+ and variable constraints whereas the method specific solver requires
+ equality constraints and variable non-negativity. ``linprog`` converts the
+ original problem to standard form by converting the simple bounds to upper
+ bound constraints, introducing non-negative slack variables for inequality
+ constraints, and expressing unbounded variables as the difference between
+ two non-negative variables. The problem is converted back to the original
+ form before results are reported.
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+ .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
+ Programming based on Newton's Method." Unpublished Course Notes,
+ March 2004. Available 2/25/2017 at
+ https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
+ .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
+ programming." Mathematical Programming 71.2 (1995): 221-245.
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+ .. [10] Andersen, Erling D., et al. Implementation of interior point
+ methods for large scale linear programming. HEC/Universite de
+ Geneve, 1996.
+ """
+ pass
+
+
+def _linprog_rs_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='interior-point', callback=None,
+ x0=None, maxiter=5000, disp=False, presolve=True,
+ tol=1e-12, autoscale=False, rr=True, maxupdate=10,
+ mast=False, pivot="mrc", **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using the revised simplex method.
+
+ .. deprecated:: 1.9.0
+ `method='revised simplex'` will be removed in SciPy 1.11.0.
+ It is replaced by `method='highs'` because the latter is
+ faster and more robust.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+ This is the method-specific documentation for 'revised simplex'.
+ :ref:`'highs' `,
+ :ref:`'highs-ds' `,
+ :ref:`'highs-ipm' `,
+ :ref:`'interior-point' ` (default),
+ and :ref:`'simplex' ` (legacy)
+ are also available.
+ callback : callable, optional
+ Callback function to be executed once per iteration.
+ x0 : 1-D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ Options
+ -------
+ maxiter : int (default: 5000)
+ The maximum number of iterations to perform in either phase.
+ disp : bool (default: False)
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ presolve : bool (default: True)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ tol : float (default: 1e-12)
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+ autoscale : bool (default: False)
+ Set to ``True`` to automatically perform equilibration.
+ Consider using this option if the numerical values in the
+ constraints are separated by several orders of magnitude.
+ rr : bool (default: True)
+ Set to ``False`` to disable automatic redundancy removal.
+ maxupdate : int (default: 10)
+ The maximum number of updates performed on the LU factorization.
+ After this many updates is reached, the basis matrix is factorized
+ from scratch.
+ mast : bool (default: False)
+ Minimize Amortized Solve Time. If enabled, the average time to solve
+ a linear system using the basis factorization is measured. Typically,
+ the average solve time will decrease with each successive solve after
+ initial factorization, as factorization takes much more time than the
+ solve operation (and updates). Eventually, however, the updated
+ factorization becomes sufficiently complex that the average solve time
+ begins to increase. When this is detected, the basis is refactorized
+ from scratch. Enable this option to maximize speed at the risk of
+ nondeterministic behavior. Ignored if ``maxupdate`` is 0.
+ pivot : "mrc" or "bland" (default: "mrc")
+ Pivot rule: Minimum Reduced Cost ("mrc") or Bland's rule ("bland").
+ Choose Bland's rule if iteration limit is reached and cycling is
+ suspected.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1-D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1-D array
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : Numerical difficulties encountered.
+
+ ``5`` : Problem has no constraints; turn presolve on.
+
+ ``6`` : Invalid guess provided.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed in all phases.
+
+
+ Notes
+ -----
+ Method *revised simplex* uses the revised simplex method as described in
+ [9]_, except that a factorization [11]_ of the basis matrix, rather than
+ its inverse, is efficiently maintained and used to solve the linear systems
+ at each iteration of the algorithm.
+
+ References
+ ----------
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+ .. [11] Bartels, Richard H. "A stabilization of the simplex method."
+ Journal in Numerische Mathematik 16.5 (1971): 414-434.
+ """
+ pass
+
+
+def _linprog_simplex_doc(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None,
+ bounds=None, method='interior-point', callback=None,
+ maxiter=5000, disp=False, presolve=True,
+ tol=1e-12, autoscale=False, rr=True, bland=False,
+ **unknown_options):
+ r"""
+ Linear programming: minimize a linear objective function subject to linear
+ equality and inequality constraints using the tableau-based simplex method.
+
+ .. deprecated:: 1.9.0
+ `method='simplex'` will be removed in SciPy 1.11.0.
+ It is replaced by `method='highs'` because the latter is
+ faster and more robust.
+
+ Linear programming solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & A_{ub} x \leq b_{ub},\\
+ & A_{eq} x = b_{eq},\\
+ & l \leq x \leq u ,
+
+ where :math:`x` is a vector of decision variables; :math:`c`,
+ :math:`b_{ub}`, :math:`b_{eq}`, :math:`l`, and :math:`u` are vectors; and
+ :math:`A_{ub}` and :math:`A_{eq}` are matrices.
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ Note that by default ``lb = 0`` and ``ub = None`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1-D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2-D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1-D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2-D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1-D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : sequence, optional
+ A sequence of ``(min, max)`` pairs for each element in ``x``, defining
+ the minimum and maximum values of that decision variable. Use ``None``
+ to indicate that there is no bound. By default, bounds are
+ ``(0, None)`` (all decision variables are non-negative).
+ If a single tuple ``(min, max)`` is provided, then ``min`` and
+ ``max`` will serve as bounds for all decision variables.
+ method : str
+ This is the method-specific documentation for 'simplex'.
+ :ref:`'highs' `,
+ :ref:`'highs-ds' `,
+ :ref:`'highs-ipm' `,
+ :ref:`'interior-point' ` (default),
+ and :ref:`'revised simplex' `
+ are also available.
+ callback : callable, optional
+ Callback function to be executed once per iteration.
+
+ Options
+ -------
+ maxiter : int (default: 5000)
+ The maximum number of iterations to perform in either phase.
+ disp : bool (default: False)
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ presolve : bool (default: True)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if
+ presolve is to be disabled.
+ tol : float (default: 1e-12)
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+ autoscale : bool (default: False)
+ Set to ``True`` to automatically perform equilibration.
+ Consider using this option if the numerical values in the
+ constraints are separated by several orders of magnitude.
+ rr : bool (default: True)
+ Set to ``False`` to disable automatic redundancy removal.
+ bland : bool
+ If True, use Bland's anti-cycling rule [3]_ to choose pivots to
+ prevent cycling. If False, choose pivots which should lead to a
+ converged solution more quickly. The latter method is subject to
+ cycling (non-convergence) in rare instances.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ A :class:`scipy.optimize.OptimizeResult` consisting of the fields:
+
+ x : 1-D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1-D array
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : Numerical difficulties encountered.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed in all phases.
+
+ References
+ ----------
+ .. [1] Dantzig, George B., Linear programming and extensions. Rand
+ Corporation Research Study Princeton Univ. Press, Princeton, NJ,
+ 1963
+ .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
+ Mathematical Programming", McGraw-Hill, Chapter 4.
+ .. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
+ Mathematics of Operations Research (2), 1977: pp. 103-107.
+ """
+ pass
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_highs.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_highs.py
new file mode 100644
index 0000000000000000000000000000000000000000..98a70ef8b1d42ca7d23e57a2a608ac336443e25f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_highs.py
@@ -0,0 +1,422 @@
+"""HiGHS Linear Optimization Methods
+
+Interface to HiGHS linear optimization software.
+https://highs.dev/
+
+.. versionadded:: 1.5.0
+
+References
+----------
+.. [1] Q. Huangfu and J.A.J. Hall. "Parallelizing the dual revised simplex
+ method." Mathematical Programming Computation, 10 (1), 119-142,
+ 2018. DOI: 10.1007/s12532-017-0130-5
+
+"""
+
+import inspect
+import numpy as np
+from ._optimize import OptimizeWarning, OptimizeResult
+from warnings import warn
+from ._highspy._highs_wrapper import _highs_wrapper
+from ._highspy._core import(
+ kHighsInf,
+ HighsDebugLevel,
+ ObjSense,
+ HighsModelStatus,
+ simplex_constants as s_c, # [1]
+)
+from scipy.sparse import csc_array, vstack, issparse
+
+# [1]: Directly importing from "._highspy._core.simplex_constants"
+# causes problems when reloading.
+# See https://github.com/scipy/scipy/pull/22869 for details.
+
+def _highs_to_scipy_status_message(highs_status, highs_message):
+ """Converts HiGHS status number/message to SciPy status number/message"""
+
+ scipy_statuses_messages = {
+ None: (4, "HiGHS did not provide a status code. "),
+ HighsModelStatus.kNotset: (4, ""),
+ HighsModelStatus.kLoadError: (4, ""),
+ HighsModelStatus.kModelError: (2, ""),
+ HighsModelStatus.kPresolveError: (4, ""),
+ HighsModelStatus.kSolveError: (4, ""),
+ HighsModelStatus.kPostsolveError: (4, ""),
+ HighsModelStatus.kModelEmpty: (4, ""),
+ HighsModelStatus.kObjectiveBound: (4, ""),
+ HighsModelStatus.kObjectiveTarget: (4, ""),
+ HighsModelStatus.kOptimal: (0, "Optimization terminated successfully. "),
+ HighsModelStatus.kTimeLimit: (1, "Time limit reached. "),
+ HighsModelStatus.kIterationLimit: (1, "Iteration limit reached. "),
+ HighsModelStatus.kInfeasible: (2, "The problem is infeasible. "),
+ HighsModelStatus.kUnbounded: (3, "The problem is unbounded. "),
+ HighsModelStatus.kUnboundedOrInfeasible: (4, "The problem is unbounded "
+ "or infeasible. ")}
+ unrecognized = (4, "The HiGHS status code was not recognized. ")
+ scipy_status, scipy_message = (
+ scipy_statuses_messages.get(highs_status, unrecognized))
+ hstat = int(highs_status) if highs_status is not None else None
+ scipy_message = (f"{scipy_message}"
+ f"(HiGHS Status {hstat}: {highs_message})")
+ return scipy_status, scipy_message
+
+
+def _replace_inf(x):
+ # Replace `np.inf` with kHighsInf
+ infs = np.isinf(x)
+ with np.errstate(invalid="ignore"):
+ x[infs] = np.sign(x[infs])*kHighsInf
+ return x
+
+
+def _convert_to_highs_enum(option, option_str, choices):
+ # If option is in the choices we can look it up, if not use
+ # the default value taken from function signature and warn:
+ try:
+ return choices[option.lower()]
+ except AttributeError:
+ return choices[option]
+ except KeyError:
+ sig = inspect.signature(_linprog_highs)
+ default_str = sig.parameters[option_str].default
+ warn(f"Option {option_str} is {option}, but only values in "
+ f"{set(choices.keys())} are allowed. Using default: "
+ f"{default_str}.",
+ OptimizeWarning, stacklevel=3)
+ return choices[default_str]
+
+
+def _linprog_highs(lp, solver, time_limit=None, presolve=True,
+ disp=False, maxiter=None,
+ dual_feasibility_tolerance=None,
+ primal_feasibility_tolerance=None,
+ ipm_optimality_tolerance=None,
+ simplex_dual_edge_weight_strategy=None,
+ mip_rel_gap=None,
+ mip_max_nodes=None,
+ **unknown_options):
+ r"""
+ Solve the following linear programming problem using one of the HiGHS
+ solvers:
+
+ User-facing documentation is in _linprog_doc.py.
+
+ Parameters
+ ----------
+ lp : _LPProblem
+ A ``scipy.optimize._linprog_util._LPProblem`` ``namedtuple``.
+ solver : "ipm" or "simplex" or None
+ Which HiGHS solver to use. If ``None``, "simplex" will be used.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform in either phase. For
+ ``solver='ipm'``, this does not include the number of crossover
+ iterations. Default is the largest possible value for an ``int``
+ on the platform.
+ disp : bool
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration; default ``False``.
+ time_limit : float
+ The maximum time in seconds allotted to solve the problem; default is
+ the largest possible value for a ``double`` on the platform.
+ presolve : bool
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver. It is generally recommended
+ to keep the default setting ``True``; set to ``False`` if presolve is
+ to be disabled.
+ dual_feasibility_tolerance : double
+ Dual feasibility tolerance. Default is 1e-07.
+ The minimum of this and ``primal_feasibility_tolerance``
+ is used for the feasibility tolerance when ``solver='ipm'``.
+ primal_feasibility_tolerance : double
+ Primal feasibility tolerance. Default is 1e-07.
+ The minimum of this and ``dual_feasibility_tolerance``
+ is used for the feasibility tolerance when ``solver='ipm'``.
+ ipm_optimality_tolerance : double
+ Optimality tolerance for ``solver='ipm'``. Default is 1e-08.
+ Minimum possible value is 1e-12 and must be smaller than the largest
+ possible value for a ``double`` on the platform.
+ simplex_dual_edge_weight_strategy : str (default: None)
+ Strategy for simplex dual edge weights. The default, ``None``,
+ automatically selects one of the following.
+
+ ``'dantzig'`` uses Dantzig's original strategy of choosing the most
+ negative reduced cost.
+
+ ``'devex'`` uses the strategy described in [15]_.
+
+ ``steepest`` uses the exact steepest edge strategy as described in
+ [16]_.
+
+ ``'steepest-devex'`` begins with the exact steepest edge strategy
+ until the computation is too costly or inexact and then switches to
+ the devex method.
+
+ Currently, using ``None`` always selects ``'steepest-devex'``, but this
+ may change as new options become available.
+
+ mip_max_nodes : int
+ The maximum number of nodes allotted to solve the problem; default is
+ the largest possible value for a ``HighsInt`` on the platform.
+ Ignored if not using the MIP solver.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ ``unknown_options`` is non-empty, a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ sol : dict
+ A dictionary consisting of the fields:
+
+ x : 1D array
+ The values of the decision variables that minimizes the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ slack : 1D array
+ The (nominally positive) values of the slack,
+ ``b_ub - A_ub @ x``.
+ con : 1D array
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+ success : bool
+ ``True`` when the algorithm succeeds in finding an optimal
+ solution.
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimization terminated successfully.
+
+ ``1`` : Iteration or time limit reached.
+
+ ``2`` : Problem appears to be infeasible.
+
+ ``3`` : Problem appears to be unbounded.
+
+ ``4`` : The HiGHS solver ran into a problem.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+ nit : int
+ The total number of iterations performed.
+ For ``solver='simplex'``, this includes iterations in all
+ phases. For ``solver='ipm'``, this does not include
+ crossover iterations.
+ crossover_nit : int
+ The number of primal/dual pushes performed during the
+ crossover routine for ``solver='ipm'``. This is ``0``
+ for ``solver='simplex'``.
+ ineqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ inequality constraints, `b_ub`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndnarray
+ The (nominally positive) values of the slack variables,
+ ``b_ub - A_ub @ x``. This quantity is also commonly
+ referred to as "slack".
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ inequality constraints, `b_ub`.
+
+ eqlin : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ equality constraints, `b_eq`. A dictionary consisting of the
+ fields:
+
+ residual : np.ndarray
+ The (nominally zero) residuals of the equality constraints,
+ ``b_eq - A_eq @ x``.
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the right-hand side of the
+ equality constraints, `b_eq`.
+
+ lower, upper : OptimizeResult
+ Solution and sensitivity information corresponding to the
+ lower and upper bounds on decision variables, `bounds`.
+
+ residual : np.ndarray
+ The (nominally positive) values of the quantity
+ ``x - lb`` (lower) or ``ub - x`` (upper).
+
+ marginals : np.ndarray
+ The sensitivity (partial derivative) of the objective
+ function with respect to the lower and upper
+ `bounds`.
+
+ mip_node_count : int
+ The number of subproblems or "nodes" solved by the MILP
+ solver. Only present when `integrality` is not `None`.
+
+ mip_dual_bound : float
+ The MILP solver's final estimate of the lower bound on the
+ optimal solution. Only present when `integrality` is not
+ `None`.
+
+ mip_gap : float
+ The difference between the final objective function value
+ and the final dual bound, scaled by the final objective
+ function value. Only present when `integrality` is not
+ `None`.
+
+ Notes
+ -----
+ The result fields `ineqlin`, `eqlin`, `lower`, and `upper` all contain
+ `marginals`, or partial derivatives of the objective function with respect
+ to the right-hand side of each constraint. These partial derivatives are
+ also referred to as "Lagrange multipliers", "dual values", and
+ "shadow prices". The sign convention of `marginals` is opposite that
+ of Lagrange multipliers produced by many nonlinear solvers.
+
+ References
+ ----------
+ .. [15] Harris, Paula MJ. "Pivot selection methods of the Devex LP code."
+ Mathematical programming 5.1 (1973): 1-28.
+ .. [16] Goldfarb, Donald, and John Ker Reid. "A practicable steepest-edge
+ simplex algorithm." Mathematical Programming 12.1 (1977): 361-371.
+ """
+ if unknown_options:
+ message = (f"Unrecognized options detected: {unknown_options}. "
+ "These will be passed to HiGHS verbatim.")
+ warn(message, OptimizeWarning, stacklevel=3)
+
+ # Map options to HiGHS enum values
+ simplex_dual_edge_weight_strategy_enum = _convert_to_highs_enum(
+ simplex_dual_edge_weight_strategy,
+ 'simplex_dual_edge_weight_strategy',
+ choices={'dantzig': \
+ s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyDantzig,
+ 'devex': \
+ s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyDevex,
+ 'steepest-devex': \
+ s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategyChoose,
+ 'steepest': \
+ s_c.SimplexEdgeWeightStrategy.kSimplexEdgeWeightStrategySteepestEdge,
+ None: None})
+
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp
+
+ lb, ub = bounds.T.copy() # separate bounds, copy->C-cntgs
+ # highs_wrapper solves LHS <= A*x <= RHS, not equality constraints
+ with np.errstate(invalid="ignore"):
+ lhs_ub = -np.ones_like(b_ub)*np.inf # LHS of UB constraints is -inf
+ rhs_ub = b_ub # RHS of UB constraints is b_ub
+ lhs_eq = b_eq # Equality constraint is inequality
+ rhs_eq = b_eq # constraint with LHS=RHS
+ lhs = np.concatenate((lhs_ub, lhs_eq))
+ rhs = np.concatenate((rhs_ub, rhs_eq))
+
+ if issparse(A_ub) or issparse(A_eq):
+ A = vstack((A_ub, A_eq))
+ else:
+ A = np.vstack((A_ub, A_eq))
+ A = csc_array(A)
+
+ options = {
+ 'presolve': presolve,
+ 'sense': ObjSense.kMinimize,
+ 'solver': solver,
+ 'time_limit': time_limit,
+ 'highs_debug_level': HighsDebugLevel.kHighsDebugLevelNone,
+ 'dual_feasibility_tolerance': dual_feasibility_tolerance,
+ 'ipm_optimality_tolerance': ipm_optimality_tolerance,
+ 'log_to_console': disp,
+ 'mip_max_nodes': mip_max_nodes,
+ 'output_flag': disp,
+ 'primal_feasibility_tolerance': primal_feasibility_tolerance,
+ 'simplex_dual_edge_weight_strategy':
+ simplex_dual_edge_weight_strategy_enum,
+ 'simplex_strategy': s_c.SimplexStrategy.kSimplexStrategyDual,
+ 'ipm_iteration_limit': maxiter,
+ 'simplex_iteration_limit': maxiter,
+ 'mip_rel_gap': mip_rel_gap,
+ }
+ options.update(unknown_options)
+
+ # np.inf doesn't work; use very large constant
+ rhs = _replace_inf(rhs)
+ lhs = _replace_inf(lhs)
+ lb = _replace_inf(lb)
+ ub = _replace_inf(ub)
+
+ if integrality is None or np.sum(integrality) == 0:
+ integrality = np.empty(0)
+ else:
+ integrality = np.array(integrality)
+
+ res = _highs_wrapper(c, A.indptr, A.indices, A.data, lhs, rhs,
+ lb, ub, integrality.astype(np.uint8), options)
+
+ # HiGHS represents constraints as lhs/rhs, so
+ # Ax + s = b => Ax = b - s
+ # and we need to split up s by A_ub and A_eq
+ if 'slack' in res:
+ slack = res['slack']
+ con = np.array(slack[len(b_ub):])
+ slack = np.array(slack[:len(b_ub)])
+ else:
+ slack, con = None, None
+
+ # lagrange multipliers for equalities/inequalities and upper/lower bounds
+ if 'lambda' in res:
+ lamda = res['lambda']
+ marg_ineqlin = np.array(lamda[:len(b_ub)])
+ marg_eqlin = np.array(lamda[len(b_ub):])
+ marg_upper = np.array(res['marg_bnds'][1, :])
+ marg_lower = np.array(res['marg_bnds'][0, :])
+ else:
+ marg_ineqlin, marg_eqlin = None, None
+ marg_upper, marg_lower = None, None
+
+ # this needs to be updated if we start choosing the solver intelligently
+
+ # Convert to scipy-style status and message
+ highs_status = res.get('status', None)
+ highs_message = res.get('message', None)
+ status, message = _highs_to_scipy_status_message(highs_status,
+ highs_message)
+
+ x = res['x'] # is None if not set
+ sol = {'x': x,
+ 'slack': slack,
+ 'con': con,
+ 'ineqlin': OptimizeResult({
+ 'residual': slack,
+ 'marginals': marg_ineqlin,
+ }),
+ 'eqlin': OptimizeResult({
+ 'residual': con,
+ 'marginals': marg_eqlin,
+ }),
+ 'lower': OptimizeResult({
+ 'residual': None if x is None else x - lb,
+ 'marginals': marg_lower,
+ }),
+ 'upper': OptimizeResult({
+ 'residual': None if x is None else ub - x,
+ 'marginals': marg_upper
+ }),
+ 'fun': res.get('fun'),
+ 'status': status,
+ 'success': res['status'] == HighsModelStatus.kOptimal,
+ 'message': message,
+ 'nit': res.get('simplex_nit', 0) or res.get('ipm_nit', 0),
+ 'crossover_nit': res.get('crossover_nit'),
+ }
+
+ if np.any(x) and integrality is not None:
+ sol.update({
+ 'mip_node_count': res.get('mip_node_count', 0),
+ 'mip_dual_bound': res.get('mip_dual_bound', 0.0),
+ 'mip_gap': res.get('mip_gap', 0.0),
+ })
+
+ return sol
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_ip.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_ip.py
new file mode 100644
index 0000000000000000000000000000000000000000..c6d035632e0039564c89d03a93397401f9f13ce6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_ip.py
@@ -0,0 +1,1141 @@
+"""Interior-point method for linear programming
+
+The *interior-point* method uses the primal-dual path following algorithm
+outlined in [1]_. This algorithm supports sparse constraint matrices and
+is typically faster than the simplex methods, especially for large, sparse
+problems. Note, however, that the solution returned may be slightly less
+accurate than those of the simplex methods and will not, in general,
+correspond with a vertex of the polytope defined by the constraints.
+
+ .. versionadded:: 1.0.0
+
+References
+----------
+.. [1] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+"""
+# Author: Matt Haberland
+
+import numpy as np
+import scipy as sp
+import scipy.sparse as sps
+from warnings import warn
+from scipy.linalg import LinAlgError
+from ._optimize import OptimizeWarning, OptimizeResult, _check_unknown_options
+from ._linprog_util import _postsolve
+has_umfpack = True
+has_cholmod = True
+try:
+ import sksparse # noqa: F401
+ from sksparse.cholmod import cholesky as cholmod # noqa: F401
+ from sksparse.cholmod import analyze as cholmod_analyze
+ from sksparse.cholmod import CholmodTypeConversionWarning
+ from warnings import catch_warnings
+except ImportError:
+ has_cholmod = False
+try:
+ import scikits.umfpack # test whether to use factorized # noqa: F401
+except ImportError:
+ has_umfpack = False
+
+
+def _get_solver(M, sparse=False, lstsq=False, sym_pos=True,
+ cholesky=True, permc_spec='MMD_AT_PLUS_A'):
+ """
+ Given solver options, return a handle to the appropriate linear system
+ solver.
+
+ Parameters
+ ----------
+ M : 2-D array
+ As defined in [4] Equation 8.31
+ sparse : bool (default = False)
+ True if the system to be solved is sparse. This is typically set
+ True when the original ``A_ub`` and ``A_eq`` arrays are sparse.
+ lstsq : bool (default = False)
+ True if the system is ill-conditioned and/or (nearly) singular and
+ thus a more robust least-squares solver is desired. This is sometimes
+ needed as the solution is approached.
+ sym_pos : bool (default = True)
+ True if the system matrix is symmetric positive definite
+ Sometimes this needs to be set false as the solution is approached,
+ even when the system should be symmetric positive definite, due to
+ numerical difficulties.
+ cholesky : bool (default = True)
+ True if the system is to be solved by Cholesky, rather than LU,
+ decomposition. This is typically faster unless the problem is very
+ small or prone to numerical difficulties.
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
+ Sparsity preservation strategy used by SuperLU. Acceptable values are:
+
+ - ``NATURAL``: natural ordering.
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+ - ``COLAMD``: approximate minimum degree column ordering.
+
+ See SuperLU documentation.
+
+ Returns
+ -------
+ solve : function
+ Handle to the appropriate solver function
+
+ """
+ try:
+ if sparse:
+ if lstsq:
+ def solve(r, sym_pos=False):
+ return sps.linalg.lsqr(M, r)[0]
+ elif cholesky:
+ # TODO: revert this suppress_warning once the warning bug fix in
+ # sksparse is merged/released
+ # Suppress spurious warning bug from sksparse with csc_array gh-22089
+ # try:
+ # # Will raise an exception in the first call,
+ # # or when the matrix changes due to a new problem
+ # _get_solver.cholmod_factor.cholesky_inplace(M)
+ # except Exception:
+ # _get_solver.cholmod_factor = cholmod_analyze(M)
+ # _get_solver.cholmod_factor.cholesky_inplace(M)
+ with catch_warnings(
+ action='ignore', category=CholmodTypeConversionWarning
+ ):
+ try:
+ # Will raise an exception in the first call,
+ # or when the matrix changes due to a new problem
+ _get_solver.cholmod_factor.cholesky_inplace(M)
+ except Exception:
+ _get_solver.cholmod_factor = cholmod_analyze(M)
+ _get_solver.cholmod_factor.cholesky_inplace(M)
+ solve = _get_solver.cholmod_factor
+ else:
+ if has_umfpack and sym_pos:
+ solve = sps.linalg.factorized(M)
+ else: # factorized doesn't pass permc_spec
+ solve = sps.linalg.splu(M, permc_spec=permc_spec).solve
+
+ else:
+ if lstsq: # sometimes necessary as solution is approached
+ def solve(r):
+ return sp.linalg.lstsq(M, r)[0]
+ elif cholesky:
+ L = sp.linalg.cho_factor(M)
+
+ def solve(r):
+ return sp.linalg.cho_solve(L, r)
+ else:
+ # this seems to cache the matrix factorization, so solving
+ # with multiple right hand sides is much faster
+ def solve(r, sym_pos=sym_pos):
+ if sym_pos:
+ return sp.linalg.solve(M, r, assume_a="pos")
+ else:
+ return sp.linalg.solve(M, r)
+ # There are many things that can go wrong here, and it's hard to say
+ # what all of them are. It doesn't really matter: if the matrix can't be
+ # factorized, return None. get_solver will be called again with different
+ # inputs, and a new routine will try to factorize the matrix.
+ except KeyboardInterrupt:
+ raise
+ except Exception:
+ return None
+ return solve
+
+
+def _get_delta(A, b, c, x, y, z, tau, kappa, gamma, eta, sparse=False,
+ lstsq=False, sym_pos=True, cholesky=True, pc=True, ip=False,
+ permc_spec='MMD_AT_PLUS_A'):
+ """
+ Given standard form problem defined by ``A``, ``b``, and ``c``;
+ current variable estimates ``x``, ``y``, ``z``, ``tau``, and ``kappa``;
+ algorithmic parameters ``gamma and ``eta;
+ and options ``sparse``, ``lstsq``, ``sym_pos``, ``cholesky``, ``pc``
+ (predictor-corrector), and ``ip`` (initial point improvement),
+ get the search direction for increments to the variable estimates.
+
+ Parameters
+ ----------
+ As defined in [4], except:
+ sparse : bool
+ True if the system to be solved is sparse. This is typically set
+ True when the original ``A_ub`` and ``A_eq`` arrays are sparse.
+ lstsq : bool
+ True if the system is ill-conditioned and/or (nearly) singular and
+ thus a more robust least-squares solver is desired. This is sometimes
+ needed as the solution is approached.
+ sym_pos : bool
+ True if the system matrix is symmetric positive definite
+ Sometimes this needs to be set false as the solution is approached,
+ even when the system should be symmetric positive definite, due to
+ numerical difficulties.
+ cholesky : bool
+ True if the system is to be solved by Cholesky, rather than LU,
+ decomposition. This is typically faster unless the problem is very
+ small or prone to numerical difficulties.
+ pc : bool
+ True if the predictor-corrector method of Mehrota is to be used. This
+ is almost always (if not always) beneficial. Even though it requires
+ the solution of an additional linear system, the factorization
+ is typically (implicitly) reused so solution is efficient, and the
+ number of algorithm iterations is typically reduced.
+ ip : bool
+ True if the improved initial point suggestion due to [4] section 4.3
+ is desired. It's unclear whether this is beneficial.
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
+ (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
+ True``.) A matrix is factorized in each iteration of the algorithm.
+ This option specifies how to permute the columns of the matrix for
+ sparsity preservation. Acceptable values are:
+
+ - ``NATURAL``: natural ordering.
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+ - ``COLAMD``: approximate minimum degree column ordering.
+
+ This option can impact the convergence of the
+ interior point algorithm; test different values to determine which
+ performs best for your problem. For more information, refer to
+ ``scipy.sparse.linalg.splu``.
+
+ Returns
+ -------
+ Search directions as defined in [4]
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ if A.shape[0] == 0:
+ # If there are no constraints, some solvers fail (understandably)
+ # rather than returning empty solution. This gets the job done.
+ lstsq, sym_pos, cholesky = False, True, False
+ n_x = len(x)
+
+ # [4] Equation 8.8
+ r_P = b * tau - A.dot(x)
+ r_D = c * tau - A.T.dot(y) - z
+ r_G = c.dot(x) - b.transpose().dot(y) + kappa
+ mu = (x.dot(z) + tau * kappa) / (n_x + 1)
+
+ # Assemble M from [4] Equation 8.31
+ Dinv = x / z
+
+ if sparse:
+ M = A.dot(sps.diags_array(Dinv, format="csc").dot(A.T))
+ else:
+ M = A.dot(Dinv.reshape(-1, 1) * A.T)
+ solve = _get_solver(M, sparse, lstsq, sym_pos, cholesky, permc_spec)
+
+ # pc: "predictor-corrector" [4] Section 4.1
+ # In development this option could be turned off
+ # but it always seems to improve performance substantially
+ n_corrections = 1 if pc else 0
+
+ i = 0
+ alpha, d_x, d_z, d_tau, d_kappa = 0, 0, 0, 0, 0
+ while i <= n_corrections:
+ # Reference [4] Eq. 8.6
+ rhatp = eta(gamma) * r_P
+ rhatd = eta(gamma) * r_D
+ rhatg = eta(gamma) * r_G
+
+ # Reference [4] Eq. 8.7
+ rhatxs = gamma * mu - x * z
+ rhattk = gamma * mu - tau * kappa
+
+ if i == 1:
+ if ip: # if the correction is to get "initial point"
+ # Reference [4] Eq. 8.23
+ rhatxs = ((1 - alpha) * gamma * mu -
+ x * z - alpha**2 * d_x * d_z)
+ rhattk = ((1 - alpha) * gamma * mu -
+ tau * kappa -
+ alpha**2 * d_tau * d_kappa)
+ else: # if the correction is for "predictor-corrector"
+ # Reference [4] Eq. 8.13
+ rhatxs -= d_x * d_z
+ rhattk -= d_tau * d_kappa
+
+ # sometimes numerical difficulties arise as the solution is approached
+ # this loop tries to solve the equations using a sequence of functions
+ # for solve. For dense systems, the order is:
+ # 1. scipy.linalg.cho_factor/scipy.linalg.cho_solve,
+ # 2. scipy.linalg.solve w/ sym_pos = True,
+ # 3. scipy.linalg.solve w/ sym_pos = False, and if all else fails
+ # 4. scipy.linalg.lstsq
+ # For sparse systems, the order is:
+ # 1. sksparse.cholmod.cholesky (if available)
+ # 2. scipy.sparse.linalg.factorized (if umfpack available)
+ # 3. scipy.sparse.linalg.splu
+ # 4. scipy.sparse.linalg.lsqr
+ solved = False
+ while not solved:
+ try:
+ # [4] Equation 8.28
+ p, q = _sym_solve(Dinv, A, c, b, solve)
+ # [4] Equation 8.29
+ u, v = _sym_solve(Dinv, A, rhatd -
+ (1 / x) * rhatxs, rhatp, solve)
+ if np.any(np.isnan(p)) or np.any(np.isnan(q)):
+ raise LinAlgError
+ solved = True
+ except (LinAlgError, ValueError, TypeError) as e:
+ # Usually this doesn't happen. If it does, it happens when
+ # there are redundant constraints or when approaching the
+ # solution. If so, change solver.
+ if cholesky:
+ cholesky = False
+ warn(
+ "Solving system with option 'cholesky':True "
+ "failed. It is normal for this to happen "
+ "occasionally, especially as the solution is "
+ "approached. However, if you see this frequently, "
+ "consider setting option 'cholesky' to False.",
+ OptimizeWarning, stacklevel=5)
+ elif sym_pos:
+ sym_pos = False
+ warn(
+ "Solving system with option 'sym_pos':True "
+ "failed. It is normal for this to happen "
+ "occasionally, especially as the solution is "
+ "approached. However, if you see this frequently, "
+ "consider setting option 'sym_pos' to False.",
+ OptimizeWarning, stacklevel=5)
+ elif not lstsq:
+ lstsq = True
+ warn(
+ "Solving system with option 'sym_pos':False "
+ "failed. This may happen occasionally, "
+ "especially as the solution is "
+ "approached. However, if you see this frequently, "
+ "your problem may be numerically challenging. "
+ "If you cannot improve the formulation, consider "
+ "setting 'lstsq' to True. Consider also setting "
+ "`presolve` to True, if it is not already.",
+ OptimizeWarning, stacklevel=5)
+ else:
+ raise e
+ solve = _get_solver(M, sparse, lstsq, sym_pos,
+ cholesky, permc_spec)
+ # [4] Results after 8.29
+ d_tau = ((rhatg + 1 / tau * rhattk - (-c.dot(u) + b.dot(v))) /
+ (1 / tau * kappa + (-c.dot(p) + b.dot(q))))
+ d_x = u + p * d_tau
+ d_y = v + q * d_tau
+
+ # [4] Relations between after 8.25 and 8.26
+ d_z = (1 / x) * (rhatxs - z * d_x)
+ d_kappa = 1 / tau * (rhattk - kappa * d_tau)
+
+ # [4] 8.12 and "Let alpha be the maximal possible step..." before 8.23
+ alpha = _get_step(x, d_x, z, d_z, tau, d_tau, kappa, d_kappa, 1)
+ if ip: # initial point - see [4] 4.4
+ gamma = 10
+ else: # predictor-corrector, [4] definition after 8.12
+ beta1 = 0.1 # [4] pg. 220 (Table 8.1)
+ gamma = (1 - alpha)**2 * min(beta1, (1 - alpha))
+ i += 1
+
+ return d_x, d_y, d_z, d_tau, d_kappa
+
+
+def _sym_solve(Dinv, A, r1, r2, solve):
+ """
+ An implementation of [4] equation 8.31 and 8.32
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ # [4] 8.31
+ r = r2 + A.dot(Dinv * r1)
+ v = solve(r)
+ # [4] 8.32
+ u = Dinv * (A.T.dot(v) - r1)
+ return u, v
+
+
+def _get_step(x, d_x, z, d_z, tau, d_tau, kappa, d_kappa, alpha0):
+ """
+ An implementation of [4] equation 8.21
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ # [4] 4.3 Equation 8.21, ignoring 8.20 requirement
+ # same step is taken in primal and dual spaces
+ # alpha0 is basically beta3 from [4] Table 8.1, but instead of beta3
+ # the value 1 is used in Mehrota corrector and initial point correction
+ i_x = d_x < 0
+ i_z = d_z < 0
+ alpha_x = alpha0 * np.min(x[i_x] / -d_x[i_x]) if np.any(i_x) else 1
+ alpha_tau = alpha0 * tau / -d_tau if d_tau < 0 else 1
+ alpha_z = alpha0 * np.min(z[i_z] / -d_z[i_z]) if np.any(i_z) else 1
+ alpha_kappa = alpha0 * kappa / -d_kappa if d_kappa < 0 else 1
+ alpha = np.min([1, alpha_x, alpha_tau, alpha_z, alpha_kappa])
+ return alpha
+
+
+def _get_message(status):
+ """
+ Given problem status code, return a more detailed message.
+
+ Parameters
+ ----------
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ Returns
+ -------
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ """
+ messages = (
+ ["Optimization terminated successfully.",
+ "The iteration limit was reached before the algorithm converged.",
+ "The algorithm terminated successfully and determined that the "
+ "problem is infeasible.",
+ "The algorithm terminated successfully and determined that the "
+ "problem is unbounded.",
+ "Numerical difficulties were encountered before the problem "
+ "converged. Please check your problem formulation for errors, "
+ "independence of linear equality constraints, and reasonable "
+ "scaling and matrix condition numbers. If you continue to "
+ "encounter this error, please submit a bug report."
+ ])
+ return messages[status]
+
+
+def _do_step(x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha):
+ """
+ An implementation of [4] Equation 8.9
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ x = x + alpha * d_x
+ tau = tau + alpha * d_tau
+ z = z + alpha * d_z
+ kappa = kappa + alpha * d_kappa
+ y = y + alpha * d_y
+ return x, y, z, tau, kappa
+
+
+def _get_blind_start(shape):
+ """
+ Return the starting point from [4] 4.4
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ m, n = shape
+ x0 = np.ones(n)
+ y0 = np.zeros(m)
+ z0 = np.ones(n)
+ tau0 = 1
+ kappa0 = 1
+ return x0, y0, z0, tau0, kappa0
+
+
+def _indicators(A, b, c, c0, x, y, z, tau, kappa):
+ """
+ Implementation of several equations from [4] used as indicators of
+ the status of optimization.
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+
+ # residuals for termination are relative to initial values
+ x0, y0, z0, tau0, kappa0 = _get_blind_start(A.shape)
+
+ # See [4], Section 4 - The Homogeneous Algorithm, Equation 8.8
+ def r_p(x, tau):
+ return b * tau - A.dot(x)
+
+ def r_d(y, z, tau):
+ return c * tau - A.T.dot(y) - z
+
+ def r_g(x, y, kappa):
+ return kappa + c.dot(x) - b.dot(y)
+
+ # np.dot unpacks if they are arrays of size one
+ def mu(x, tau, z, kappa):
+ return (x.dot(z) + np.dot(tau, kappa)) / (len(x) + 1)
+
+ obj = c.dot(x / tau) + c0
+
+ def norm(a):
+ return np.linalg.norm(a)
+
+ # See [4], Section 4.5 - The Stopping Criteria
+ r_p0 = r_p(x0, tau0)
+ r_d0 = r_d(y0, z0, tau0)
+ r_g0 = r_g(x0, y0, kappa0)
+ mu_0 = mu(x0, tau0, z0, kappa0)
+ rho_A = norm(c.T.dot(x) - b.T.dot(y)) / (tau + norm(b.T.dot(y)))
+ rho_p = norm(r_p(x, tau)) / max(1, norm(r_p0))
+ rho_d = norm(r_d(y, z, tau)) / max(1, norm(r_d0))
+ rho_g = norm(r_g(x, y, kappa)) / max(1, norm(r_g0))
+ rho_mu = mu(x, tau, z, kappa) / mu_0
+ return rho_p, rho_d, rho_A, rho_g, rho_mu, obj
+
+
+def _display_iter(rho_p, rho_d, rho_g, alpha, rho_mu, obj, header=False):
+ """
+ Print indicators of optimization status to the console.
+
+ Parameters
+ ----------
+ rho_p : float
+ The (normalized) primal feasibility, see [4] 4.5
+ rho_d : float
+ The (normalized) dual feasibility, see [4] 4.5
+ rho_g : float
+ The (normalized) duality gap, see [4] 4.5
+ alpha : float
+ The step size, see [4] 4.3
+ rho_mu : float
+ The (normalized) path parameter, see [4] 4.5
+ obj : float
+ The objective function value of the current iterate
+ header : bool
+ True if a header is to be printed
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+
+ """
+ if header:
+ print("Primal Feasibility ",
+ "Dual Feasibility ",
+ "Duality Gap ",
+ "Step ",
+ "Path Parameter ",
+ "Objective ")
+
+ # no clue why this works
+ fmt = '{0:<20.13}{1:<20.13}{2:<20.13}{3:<17.13}{4:<20.13}{5:<20.13}'
+ print(fmt.format(
+ float(rho_p),
+ float(rho_d),
+ float(rho_g),
+ alpha if isinstance(alpha, str) else float(alpha),
+ float(rho_mu),
+ float(obj)))
+
+
+def _ip_hsd(A, b, c, c0, alpha0, beta, maxiter, disp, tol, sparse, lstsq,
+ sym_pos, cholesky, pc, ip, permc_spec, callback, postsolve_args):
+ r"""
+ Solve a linear programming problem in standard form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ using the interior point method of [4].
+
+ Parameters
+ ----------
+ A : 2-D array
+ 2-D array such that ``A @ x``, gives the values of the equality
+ constraints at ``x``.
+ b : 1-D array
+ 1-D array of values representing the RHS of each equality constraint
+ (row) in ``A`` (for standard form problem).
+ c : 1-D array
+ Coefficients of the linear objective function to be minimized (for
+ standard form problem).
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables. (Purely for display.)
+ alpha0 : float
+ The maximal step size for Mehrota's predictor-corrector search
+ direction; see :math:`\beta_3`of [4] Table 8.1
+ beta : float
+ The desired reduction of the path parameter :math:`\mu` (see [6]_)
+ maxiter : int
+ The maximum number of iterations of the algorithm.
+ disp : bool
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ tol : float
+ Termination tolerance; see [4]_ Section 4.5.
+ sparse : bool
+ Set to ``True`` if the problem is to be treated as sparse. However,
+ the inputs ``A_eq`` and ``A_ub`` should nonetheless be provided as
+ (dense) arrays rather than sparse matrices.
+ lstsq : bool
+ Set to ``True`` if the problem is expected to be very poorly
+ conditioned. This should always be left as ``False`` unless severe
+ numerical difficulties are frequently encountered, and a better option
+ would be to improve the formulation of the problem.
+ sym_pos : bool
+ Leave ``True`` if the problem is expected to yield a well conditioned
+ symmetric positive definite normal equation matrix (almost always).
+ cholesky : bool
+ Set to ``True`` if the normal equations are to be solved by explicit
+ Cholesky decomposition followed by explicit forward/backward
+ substitution. This is typically faster for moderate, dense problems
+ that are numerically well-behaved.
+ pc : bool
+ Leave ``True`` if the predictor-corrector method of Mehrota is to be
+ used. This is almost always (if not always) beneficial.
+ ip : bool
+ Set to ``True`` if the improved initial point suggestion due to [4]_
+ Section 4.3 is desired. It's unclear whether this is beneficial.
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
+ (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
+ True``.) A matrix is factorized in each iteration of the algorithm.
+ This option specifies how to permute the columns of the matrix for
+ sparsity preservation. Acceptable values are:
+
+ - ``NATURAL``: natural ordering.
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+ - ``COLAMD``: approximate minimum degree column ordering.
+
+ This option can impact the convergence of the
+ interior point algorithm; test different values to determine which
+ performs best for your problem. For more information, refer to
+ ``scipy.sparse.linalg.splu``.
+ callback : callable, optional
+ If a callback function is provided, it will be called within each
+ iteration of the algorithm. The callback function must accept a single
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ Current solution vector
+ fun : float
+ Current value of the objective function
+ success : bool
+ True only when an algorithm has completed successfully,
+ so this is always False as the callback function is called
+ only while the algorithm is still iterating.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable
+ corresponds to an inequality constraint. If the slack is zero,
+ the corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ that is, ``b - A_eq @ x``
+ phase : int
+ The phase of the algorithm being executed. This is always
+ 1 for the interior-point method because it has only one phase.
+ status : int
+ For revised simplex, this is always 0 because if a different
+ status is detected, the algorithm terminates.
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem.
+
+ Returns
+ -------
+ x_hat : float
+ Solution vector (for standard form problem).
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+ iteration : int
+ The number of iterations taken to solve the problem
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+ .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
+ Programming based on Newton's Method." Unpublished Course Notes,
+ March 2004. Available 2/25/2017 at:
+ https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
+
+ """
+
+ iteration = 0
+
+ # default initial point
+ x, y, z, tau, kappa = _get_blind_start(A.shape)
+
+ # first iteration is special improvement of initial point
+ ip = ip if pc else False
+
+ # [4] 4.5
+ rho_p, rho_d, rho_A, rho_g, rho_mu, obj = _indicators(
+ A, b, c, c0, x, y, z, tau, kappa)
+ go = rho_p > tol or rho_d > tol or rho_A > tol # we might get lucky : )
+
+ if disp:
+ _display_iter(rho_p, rho_d, rho_g, "-", rho_mu, obj, header=True)
+ if callback is not None:
+ x_o, fun, slack, con = _postsolve(x/tau, postsolve_args)
+ res = OptimizeResult({'x': x_o, 'fun': fun, 'slack': slack,
+ 'con': con, 'nit': iteration, 'phase': 1,
+ 'complete': False, 'status': 0,
+ 'message': "", 'success': False})
+ callback(res)
+
+ status = 0
+ message = "Optimization terminated successfully."
+
+ if sparse:
+ A = sps.csc_array(A)
+
+ while go:
+
+ iteration += 1
+
+ if ip: # initial point
+ # [4] Section 4.4
+ gamma = 1
+
+ def eta(g):
+ return 1
+ else:
+ # gamma = 0 in predictor step according to [4] 4.1
+ # if predictor/corrector is off, use mean of complementarity [6]
+ # 5.1 / [4] Below Figure 10-4
+ gamma = 0 if pc else beta * np.mean(z * x)
+ # [4] Section 4.1
+
+ def eta(g=gamma):
+ return 1 - g
+
+ try:
+ # Solve [4] 8.6 and 8.7/8.13/8.23
+ d_x, d_y, d_z, d_tau, d_kappa = _get_delta(
+ A, b, c, x, y, z, tau, kappa, gamma, eta,
+ sparse, lstsq, sym_pos, cholesky, pc, ip, permc_spec)
+
+ if ip: # initial point
+ # [4] 4.4
+ # Formula after 8.23 takes a full step regardless if this will
+ # take it negative
+ alpha = 1.0
+ x, y, z, tau, kappa = _do_step(
+ x, y, z, tau, kappa, d_x, d_y,
+ d_z, d_tau, d_kappa, alpha)
+ x[x < 1] = 1
+ z[z < 1] = 1
+ tau = max(1, tau)
+ kappa = max(1, kappa)
+ ip = False # done with initial point
+ else:
+ # [4] Section 4.3
+ alpha = _get_step(x, d_x, z, d_z, tau,
+ d_tau, kappa, d_kappa, alpha0)
+ # [4] Equation 8.9
+ x, y, z, tau, kappa = _do_step(
+ x, y, z, tau, kappa, d_x, d_y, d_z, d_tau, d_kappa, alpha)
+
+ except (LinAlgError, FloatingPointError,
+ ValueError, ZeroDivisionError):
+ # this can happen when sparse solver is used and presolve
+ # is turned off. Also observed ValueError in AppVeyor Python 3.6
+ # Win32 build (PR #8676). I've never seen it otherwise.
+ status = 4
+ message = _get_message(status)
+ break
+
+ # [4] 4.5
+ rho_p, rho_d, rho_A, rho_g, rho_mu, obj = _indicators(
+ A, b, c, c0, x, y, z, tau, kappa)
+ go = rho_p > tol or rho_d > tol or rho_A > tol
+
+ if disp:
+ _display_iter(rho_p, rho_d, rho_g, alpha, rho_mu, obj)
+ if callback is not None:
+ x_o, fun, slack, con = _postsolve(x/tau, postsolve_args)
+ res = OptimizeResult({'x': x_o, 'fun': fun, 'slack': slack,
+ 'con': con, 'nit': iteration, 'phase': 1,
+ 'complete': False, 'status': 0,
+ 'message': "", 'success': False})
+ callback(res)
+
+ # [4] 4.5
+ inf1 = (rho_p < tol and rho_d < tol and rho_g < tol and tau < tol *
+ max(1, kappa))
+ inf2 = rho_mu < tol and tau < tol * min(1, kappa)
+ if inf1 or inf2:
+ # [4] Lemma 8.4 / Theorem 8.3
+ if b.transpose().dot(y) > tol:
+ status = 2
+ else: # elif c.T.dot(x) < tol: ? Probably not necessary.
+ status = 3
+ message = _get_message(status)
+ break
+ elif iteration >= maxiter:
+ status = 1
+ message = _get_message(status)
+ break
+
+ x_hat = x / tau
+ # [4] Statement after Theorem 8.2
+ return x_hat, status, message, iteration
+
+
+def _linprog_ip(c, c0, A, b, callback, postsolve_args, maxiter=1000, tol=1e-8,
+ disp=False, alpha0=.99995, beta=0.1, sparse=False, lstsq=False,
+ sym_pos=True, cholesky=None, pc=True, ip=False,
+ permc_spec='MMD_AT_PLUS_A', **unknown_options):
+ r"""
+ Minimize a linear objective function subject to linear
+ equality and non-negativity constraints using the interior point method
+ of [4]_. Linear programming is intended to solve problems
+ of the following form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ User-facing documentation is in _linprog_doc.py.
+
+ Parameters
+ ----------
+ c : 1-D array
+ Coefficients of the linear objective function to be minimized.
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables. (Purely for display.)
+ A : 2-D array
+ 2-D array such that ``A @ x``, gives the values of the equality
+ constraints at ``x``.
+ b : 1-D array
+ 1-D array of values representing the right hand side of each equality
+ constraint (row) in ``A``.
+ callback : callable, optional
+ Callback function to be executed once per iteration.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem.
+
+ Options
+ -------
+ maxiter : int (default = 1000)
+ The maximum number of iterations of the algorithm.
+ tol : float (default = 1e-8)
+ Termination tolerance to be used for all termination criteria;
+ see [4]_ Section 4.5.
+ disp : bool (default = False)
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ alpha0 : float (default = 0.99995)
+ The maximal step size for Mehrota's predictor-corrector search
+ direction; see :math:`\beta_{3}` of [4]_ Table 8.1.
+ beta : float (default = 0.1)
+ The desired reduction of the path parameter :math:`\mu` (see [6]_)
+ when Mehrota's predictor-corrector is not in use (uncommon).
+ sparse : bool (default = False)
+ Set to ``True`` if the problem is to be treated as sparse after
+ presolve. If either ``A_eq`` or ``A_ub`` is a sparse matrix,
+ this option will automatically be set ``True``, and the problem
+ will be treated as sparse even during presolve. If your constraint
+ matrices contain mostly zeros and the problem is not very small (less
+ than about 100 constraints or variables), consider setting ``True``
+ or providing ``A_eq`` and ``A_ub`` as sparse matrices.
+ lstsq : bool (default = False)
+ Set to ``True`` if the problem is expected to be very poorly
+ conditioned. This should always be left ``False`` unless severe
+ numerical difficulties are encountered. Leave this at the default
+ unless you receive a warning message suggesting otherwise.
+ sym_pos : bool (default = True)
+ Leave ``True`` if the problem is expected to yield a well conditioned
+ symmetric positive definite normal equation matrix
+ (almost always). Leave this at the default unless you receive
+ a warning message suggesting otherwise.
+ cholesky : bool (default = True)
+ Set to ``True`` if the normal equations are to be solved by explicit
+ Cholesky decomposition followed by explicit forward/backward
+ substitution. This is typically faster for problems
+ that are numerically well-behaved.
+ pc : bool (default = True)
+ Leave ``True`` if the predictor-corrector method of Mehrota is to be
+ used. This is almost always (if not always) beneficial.
+ ip : bool (default = False)
+ Set to ``True`` if the improved initial point suggestion due to [4]_
+ Section 4.3 is desired. Whether this is beneficial or not
+ depends on the problem.
+ permc_spec : str (default = 'MMD_AT_PLUS_A')
+ (Has effect only with ``sparse = True``, ``lstsq = False``, ``sym_pos =
+ True``, and no SuiteSparse.)
+ A matrix is factorized in each iteration of the algorithm.
+ This option specifies how to permute the columns of the matrix for
+ sparsity preservation. Acceptable values are:
+
+ - ``NATURAL``: natural ordering.
+ - ``MMD_ATA``: minimum degree ordering on the structure of A^T A.
+ - ``MMD_AT_PLUS_A``: minimum degree ordering on the structure of A^T+A.
+ - ``COLAMD``: approximate minimum degree column ordering.
+
+ This option can impact the convergence of the
+ interior point algorithm; test different values to determine which
+ performs best for your problem. For more information, refer to
+ ``scipy.sparse.linalg.splu``.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ x : 1-D array
+ Solution vector.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+ iteration : int
+ The number of iterations taken to solve the problem.
+
+ Notes
+ -----
+ This method implements the algorithm outlined in [4]_ with ideas from [8]_
+ and a structure inspired by the simpler methods of [6]_.
+
+ The primal-dual path following method begins with initial 'guesses' of
+ the primal and dual variables of the standard form problem and iteratively
+ attempts to solve the (nonlinear) Karush-Kuhn-Tucker conditions for the
+ problem with a gradually reduced logarithmic barrier term added to the
+ objective. This particular implementation uses a homogeneous self-dual
+ formulation, which provides certificates of infeasibility or unboundedness
+ where applicable.
+
+ The default initial point for the primal and dual variables is that
+ defined in [4]_ Section 4.4 Equation 8.22. Optionally (by setting initial
+ point option ``ip=True``), an alternate (potentially improved) starting
+ point can be calculated according to the additional recommendations of
+ [4]_ Section 4.4.
+
+ A search direction is calculated using the predictor-corrector method
+ (single correction) proposed by Mehrota and detailed in [4]_ Section 4.1.
+ (A potential improvement would be to implement the method of multiple
+ corrections described in [4]_ Section 4.2.) In practice, this is
+ accomplished by solving the normal equations, [4]_ Section 5.1 Equations
+ 8.31 and 8.32, derived from the Newton equations [4]_ Section 5 Equations
+ 8.25 (compare to [4]_ Section 4 Equations 8.6-8.8). The advantage of
+ solving the normal equations rather than 8.25 directly is that the
+ matrices involved are symmetric positive definite, so Cholesky
+ decomposition can be used rather than the more expensive LU factorization.
+
+ With default options, the solver used to perform the factorization depends
+ on third-party software availability and the conditioning of the problem.
+
+ For dense problems, solvers are tried in the following order:
+
+ 1. ``scipy.linalg.cho_factor``
+
+ 2. ``scipy.linalg.solve`` with option ``sym_pos=True``
+
+ 3. ``scipy.linalg.solve`` with option ``sym_pos=False``
+
+ 4. ``scipy.linalg.lstsq``
+
+ For sparse problems:
+
+ 1. ``sksparse.cholmod.cholesky`` (if scikit-sparse and SuiteSparse are installed)
+
+ 2. ``scipy.sparse.linalg.factorized``
+ (if scikit-umfpack and SuiteSparse are installed)
+
+ 3. ``scipy.sparse.linalg.splu`` (which uses SuperLU distributed with SciPy)
+
+ 4. ``scipy.sparse.linalg.lsqr``
+
+ If the solver fails for any reason, successively more robust (but slower)
+ solvers are attempted in the order indicated. Attempting, failing, and
+ re-starting factorization can be time consuming, so if the problem is
+ numerically challenging, options can be set to bypass solvers that are
+ failing. Setting ``cholesky=False`` skips to solver 2,
+ ``sym_pos=False`` skips to solver 3, and ``lstsq=True`` skips
+ to solver 4 for both sparse and dense problems.
+
+ Potential improvements for combating issues associated with dense
+ columns in otherwise sparse problems are outlined in [4]_ Section 5.3 and
+ [10]_ Section 4.1-4.2; the latter also discusses the alleviation of
+ accuracy issues associated with the substitution approach to free
+ variables.
+
+ After calculating the search direction, the maximum possible step size
+ that does not activate the non-negativity constraints is calculated, and
+ the smaller of this step size and unity is applied (as in [4]_ Section
+ 4.1.) [4]_ Section 4.3 suggests improvements for choosing the step size.
+
+ The new point is tested according to the termination conditions of [4]_
+ Section 4.5. The same tolerance, which can be set using the ``tol`` option,
+ is used for all checks. (A potential improvement would be to expose
+ the different tolerances to be set independently.) If optimality,
+ unboundedness, or infeasibility is detected, the solve procedure
+ terminates; otherwise it repeats.
+
+ The expected problem formulation differs between the top level ``linprog``
+ module and the method specific solvers. The method specific solvers expect a
+ problem in standard form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ Whereas the top level ``linprog`` module expects a problem of form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ where ``lb = 0`` and ``ub = None`` unless set in ``bounds``.
+
+ The original problem contains equality, upper-bound and variable constraints
+ whereas the method specific solver requires equality constraints and
+ variable non-negativity.
+
+ ``linprog`` module converts the original problem to standard form by
+ converting the simple bounds to upper bound constraints, introducing
+ non-negative slack variables for inequality constraints, and expressing
+ unbounded variables as the difference between two non-negative variables.
+
+
+ References
+ ----------
+ .. [4] Andersen, Erling D., and Knud D. Andersen. "The MOSEK interior point
+ optimizer for linear programming: an implementation of the
+ homogeneous algorithm." High performance optimization. Springer US,
+ 2000. 197-232.
+ .. [6] Freund, Robert M. "Primal-Dual Interior-Point Methods for Linear
+ Programming based on Newton's Method." Unpublished Course Notes,
+ March 2004. Available 2/25/2017 at
+ https://ocw.mit.edu/courses/sloan-school-of-management/15-084j-nonlinear-programming-spring-2004/lecture-notes/lec14_int_pt_mthd.pdf
+ .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
+ programming." Mathematical Programming 71.2 (1995): 221-245.
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+ .. [10] Andersen, Erling D., et al. Implementation of interior point methods
+ for large scale linear programming. HEC/Universite de Geneve, 1996.
+
+ """
+
+ _check_unknown_options(unknown_options)
+
+ # These should be warnings, not errors
+ if (cholesky or cholesky is None) and sparse and not has_cholmod:
+ if cholesky:
+ warn("Sparse cholesky is only available with scikit-sparse. "
+ "Setting `cholesky = False`",
+ OptimizeWarning, stacklevel=3)
+ cholesky = False
+
+ if sparse and lstsq:
+ warn("Option combination 'sparse':True and 'lstsq':True "
+ "is not recommended.",
+ OptimizeWarning, stacklevel=3)
+
+ if lstsq and cholesky:
+ warn("Invalid option combination 'lstsq':True "
+ "and 'cholesky':True; option 'cholesky' has no effect when "
+ "'lstsq' is set True.",
+ OptimizeWarning, stacklevel=3)
+
+ valid_permc_spec = ('NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A', 'COLAMD')
+ if permc_spec.upper() not in valid_permc_spec:
+ warn("Invalid permc_spec option: '" + str(permc_spec) + "'. "
+ "Acceptable values are 'NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A', "
+ "and 'COLAMD'. Reverting to default.",
+ OptimizeWarning, stacklevel=3)
+ permc_spec = 'MMD_AT_PLUS_A'
+
+ # This can be an error
+ if not sym_pos and cholesky:
+ raise ValueError(
+ "Invalid option combination 'sym_pos':False "
+ "and 'cholesky':True: Cholesky decomposition is only possible "
+ "for symmetric positive definite matrices.")
+
+ cholesky = cholesky or (cholesky is None and sym_pos and not lstsq)
+
+ x, status, message, iteration = _ip_hsd(A, b, c, c0, alpha0, beta,
+ maxiter, disp, tol, sparse,
+ lstsq, sym_pos, cholesky,
+ pc, ip, permc_spec, callback,
+ postsolve_args)
+
+ return x, status, message, iteration
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_rs.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_rs.py
new file mode 100644
index 0000000000000000000000000000000000000000..43fed5805c4e40f0c38de91f053e3926cf1478e4
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_rs.py
@@ -0,0 +1,572 @@
+"""Revised simplex method for linear programming
+
+The *revised simplex* method uses the method described in [1]_, except
+that a factorization [2]_ of the basis matrix, rather than its inverse,
+is efficiently maintained and used to solve the linear systems at each
+iteration of the algorithm.
+
+.. versionadded:: 1.3.0
+
+References
+----------
+.. [1] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+.. [2] Bartels, Richard H. "A stabilization of the simplex method."
+ Journal in Numerische Mathematik 16.5 (1971): 414-434.
+
+"""
+# Author: Matt Haberland
+
+import numpy as np
+from numpy.linalg import LinAlgError
+
+from scipy.linalg import solve
+from ._optimize import _check_unknown_options
+from ._bglu_dense import LU
+from ._bglu_dense import BGLU as BGLU
+from ._linprog_util import _postsolve
+from ._optimize import OptimizeResult
+
+
+def _phase_one(A, b, x0, callback, postsolve_args, maxiter, tol, disp,
+ maxupdate, mast, pivot):
+ """
+ The purpose of phase one is to find an initial basic feasible solution
+ (BFS) to the original problem.
+
+ Generates an auxiliary problem with a trivial BFS and an objective that
+ minimizes infeasibility of the original problem. Solves the auxiliary
+ problem using the main simplex routine (phase two). This either yields
+ a BFS to the original problem or determines that the original problem is
+ infeasible. If feasible, phase one detects redundant rows in the original
+ constraint matrix and removes them, then chooses additional indices as
+ necessary to complete a basis/BFS for the original problem.
+ """
+
+ m, n = A.shape
+ status = 0
+
+ # generate auxiliary problem to get initial BFS
+ A, b, c, basis, x, status = _generate_auxiliary_problem(A, b, x0, tol)
+
+ if status == 6:
+ residual = c.dot(x)
+ iter_k = 0
+ return x, basis, A, b, residual, status, iter_k
+
+ # solve auxiliary problem
+ phase_one_n = n
+ iter_k = 0
+ x, basis, status, iter_k = _phase_two(c, A, x, basis, callback,
+ postsolve_args,
+ maxiter, tol, disp,
+ maxupdate, mast, pivot,
+ iter_k, phase_one_n)
+
+ # check for infeasibility
+ residual = c.dot(x)
+ if status == 0 and residual > tol:
+ status = 2
+
+ # drive artificial variables out of basis
+ # TODO: test redundant row removal better
+ # TODO: make solve more efficient with BGLU? This could take a while.
+ keep_rows = np.ones(m, dtype=bool)
+ for basis_column in basis[basis >= n]:
+ B = A[:, basis]
+ try:
+ basis_finder = np.abs(solve(B, A)) # inefficient
+ pertinent_row = np.argmax(basis_finder[:, basis_column])
+ eligible_columns = np.ones(n, dtype=bool)
+ eligible_columns[basis[basis < n]] = 0
+ eligible_column_indices = np.where(eligible_columns)[0]
+ index = np.argmax(basis_finder[:, :n]
+ [pertinent_row, eligible_columns])
+ new_basis_column = eligible_column_indices[index]
+ if basis_finder[pertinent_row, new_basis_column] < tol:
+ keep_rows[pertinent_row] = False
+ else:
+ basis[basis == basis_column] = new_basis_column
+ except LinAlgError:
+ status = 4
+
+ # form solution to original problem
+ A = A[keep_rows, :n]
+ basis = basis[keep_rows]
+ x = x[:n]
+ m = A.shape[0]
+ return x, basis, A, b, residual, status, iter_k
+
+
+def _get_more_basis_columns(A, basis):
+ """
+ Called when the auxiliary problem terminates with artificial columns in
+ the basis, which must be removed and replaced with non-artificial
+ columns. Finds additional columns that do not make the matrix singular.
+ """
+ m, n = A.shape
+
+ # options for inclusion are those that aren't already in the basis
+ a = np.arange(m+n)
+ bl = np.zeros(len(a), dtype=bool)
+ bl[basis] = 1
+ options = a[~bl]
+ options = options[options < n] # and they have to be non-artificial
+
+ # form basis matrix
+ B = np.zeros((m, m))
+ B[:, 0:len(basis)] = A[:, basis]
+
+ if (basis.size > 0 and
+ np.linalg.matrix_rank(B[:, :len(basis)]) < len(basis)):
+ raise Exception("Basis has dependent columns")
+
+ rank = 0 # just enter the loop
+ for i in range(n): # somewhat arbitrary, but we need another way out
+ # permute the options, and take as many as needed
+ new_basis = np.random.permutation(options)[:m-len(basis)]
+ B[:, len(basis):] = A[:, new_basis] # update the basis matrix
+ rank = np.linalg.matrix_rank(B) # check the rank
+ if rank == m:
+ break
+
+ return np.concatenate((basis, new_basis))
+
+
+def _generate_auxiliary_problem(A, b, x0, tol):
+ """
+ Modifies original problem to create an auxiliary problem with a trivial
+ initial basic feasible solution and an objective that minimizes
+ infeasibility in the original problem.
+
+ Conceptually, this is done by stacking an identity matrix on the right of
+ the original constraint matrix, adding artificial variables to correspond
+ with each of these new columns, and generating a cost vector that is all
+ zeros except for ones corresponding with each of the new variables.
+
+ A initial basic feasible solution is trivial: all variables are zero
+ except for the artificial variables, which are set equal to the
+ corresponding element of the right hand side `b`.
+
+ Running the simplex method on this auxiliary problem drives all of the
+ artificial variables - and thus the cost - to zero if the original problem
+ is feasible. The original problem is declared infeasible otherwise.
+
+ Much of the complexity below is to improve efficiency by using singleton
+ columns in the original problem where possible, thus generating artificial
+ variables only as necessary, and using an initial 'guess' basic feasible
+ solution.
+ """
+ status = 0
+ m, n = A.shape
+
+ if x0 is not None:
+ x = x0
+ else:
+ x = np.zeros(n)
+
+ r = b - A@x # residual; this must be all zeros for feasibility
+
+ A[r < 0] = -A[r < 0] # express problem with RHS positive for trivial BFS
+ b[r < 0] = -b[r < 0] # to the auxiliary problem
+ r[r < 0] *= -1
+
+ # Rows which we will need to find a trivial way to zero.
+ # This should just be the rows where there is a nonzero residual.
+ # But then we would not necessarily have a column singleton in every row.
+ # This makes it difficult to find an initial basis.
+ if x0 is None:
+ nonzero_constraints = np.arange(m)
+ else:
+ nonzero_constraints = np.where(r > tol)[0]
+
+ # these are (at least some of) the initial basis columns
+ basis = np.where(np.abs(x) > tol)[0]
+
+ if len(nonzero_constraints) == 0 and len(basis) <= m: # already a BFS
+ c = np.zeros(n)
+ basis = _get_more_basis_columns(A, basis)
+ return A, b, c, basis, x, status
+ elif (len(nonzero_constraints) > m - len(basis) or
+ np.any(x < 0)): # can't get trivial BFS
+ c = np.zeros(n)
+ status = 6
+ return A, b, c, basis, x, status
+
+ # chooses existing columns appropriate for inclusion in initial basis
+ cols, rows = _select_singleton_columns(A, r)
+
+ # find the rows we need to zero that we _can_ zero with column singletons
+ i_tofix = np.isin(rows, nonzero_constraints)
+ # these columns can't already be in the basis, though
+ # we are going to add them to the basis and change the corresponding x val
+ i_notinbasis = np.logical_not(np.isin(cols, basis))
+ i_fix_without_aux = np.logical_and(i_tofix, i_notinbasis)
+ rows = rows[i_fix_without_aux]
+ cols = cols[i_fix_without_aux]
+
+ # indices of the rows we can only zero with auxiliary variable
+ # these rows will get a one in each auxiliary column
+ arows = nonzero_constraints[np.logical_not(
+ np.isin(nonzero_constraints, rows))]
+ n_aux = len(arows)
+ acols = n + np.arange(n_aux) # indices of auxiliary columns
+
+ basis_ng = np.concatenate((cols, acols)) # basis columns not from guess
+ basis_ng_rows = np.concatenate((rows, arows)) # rows we need to zero
+
+ # add auxiliary singleton columns
+ A = np.hstack((A, np.zeros((m, n_aux))))
+ A[arows, acols] = 1
+
+ # generate initial BFS
+ x = np.concatenate((x, np.zeros(n_aux)))
+ x[basis_ng] = r[basis_ng_rows]/A[basis_ng_rows, basis_ng]
+
+ # generate costs to minimize infeasibility
+ c = np.zeros(n_aux + n)
+ c[acols] = 1
+
+ # basis columns correspond with nonzeros in guess, those with column
+ # singletons we used to zero remaining constraints, and any additional
+ # columns to get a full set (m columns)
+ basis = np.concatenate((basis, basis_ng))
+ basis = _get_more_basis_columns(A, basis) # add columns as needed
+
+ return A, b, c, basis, x, status
+
+
+def _select_singleton_columns(A, b):
+ """
+ Finds singleton columns for which the singleton entry is of the same sign
+ as the right-hand side; these columns are eligible for inclusion in an
+ initial basis. Determines the rows in which the singleton entries are
+ located. For each of these rows, returns the indices of the one singleton
+ column and its corresponding row.
+ """
+ # find indices of all singleton columns and corresponding row indices
+ column_indices = np.nonzero(np.sum(np.abs(A) != 0, axis=0) == 1)[0]
+ columns = A[:, column_indices] # array of singleton columns
+ row_indices = np.zeros(len(column_indices), dtype=int)
+ nonzero_rows, nonzero_columns = np.nonzero(columns)
+ row_indices[nonzero_columns] = nonzero_rows # corresponding row indices
+
+ # keep only singletons with entries that have same sign as RHS
+ # this is necessary because all elements of BFS must be non-negative
+ same_sign = A[row_indices, column_indices]*b[row_indices] >= 0
+ column_indices = column_indices[same_sign][::-1]
+ row_indices = row_indices[same_sign][::-1]
+ # Reversing the order so that steps below select rightmost columns
+ # for initial basis, which will tend to be slack variables. (If the
+ # guess corresponds with a basic feasible solution but a constraint
+ # is not satisfied with the corresponding slack variable zero, the slack
+ # variable must be basic.)
+
+ # for each row, keep rightmost singleton column with an entry in that row
+ unique_row_indices, first_columns = np.unique(row_indices,
+ return_index=True)
+ return column_indices[first_columns], unique_row_indices
+
+
+def _find_nonzero_rows(A, tol):
+ """
+ Returns logical array indicating the locations of rows with at least
+ one nonzero element.
+ """
+ return np.any(np.abs(A) > tol, axis=1)
+
+
+def _select_enter_pivot(c_hat, bl, a, rule="bland", tol=1e-12):
+ """
+ Selects a pivot to enter the basis. Currently Bland's rule - the smallest
+ index that has a negative reduced cost - is the default.
+ """
+ if rule.lower() == "mrc": # index with minimum reduced cost
+ return a[~bl][np.argmin(c_hat)]
+ else: # smallest index w/ negative reduced cost
+ return a[~bl][c_hat < -tol][0]
+
+
+def _display_iter(phase, iteration, slack, con, fun):
+ """
+ Print indicators of optimization status to the console.
+ """
+ header = True if not iteration % 20 else False
+
+ if header:
+ print("Phase",
+ "Iteration",
+ "Minimum Slack ",
+ "Constraint Residual",
+ "Objective ")
+
+ # := -tol): # all reduced costs positive -> terminate
+ break
+
+ j = _select_enter_pivot(c_hat, bl, a, rule=pivot, tol=tol)
+ u = B.solve(A[:, j]) # similar to u = solve(B, A[:, j])
+
+ i = u > tol # if none of the u are positive, unbounded
+ if not np.any(i):
+ status = 3
+ break
+
+ th = xb[i]/u[i]
+ l = np.argmin(th) # implicitly selects smallest subscript
+ th_star = th[l] # step size
+
+ x[b] = x[b] - th_star*u # take step
+ x[j] = th_star
+ B.update(ab[i][l], j) # modify basis
+ b = B.b # similar to b[ab[i][l]] =
+
+ else:
+ # If the end of the for loop is reached (without a break statement),
+ # then another step has been taken, so the iteration counter should
+ # increment, info should be displayed, and callback should be called.
+ iteration += 1
+ status = 1
+ if disp or callback is not None:
+ _display_and_callback(phase_one_n, x, postsolve_args, status,
+ iteration, disp, callback)
+
+ return x, b, status, iteration
+
+
+def _linprog_rs(c, c0, A, b, x0, callback, postsolve_args,
+ maxiter=5000, tol=1e-12, disp=False,
+ maxupdate=10, mast=False, pivot="mrc",
+ **unknown_options):
+ """
+ Solve the following linear programming problem via a two-phase
+ revised simplex algorithm.::
+
+ minimize: c @ x
+
+ subject to: A @ x == b
+ 0 <= x < oo
+
+ User-facing documentation is in _linprog_doc.py.
+
+ Parameters
+ ----------
+ c : 1-D array
+ Coefficients of the linear objective function to be minimized.
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables. (Currently unused.)
+ A : 2-D array
+ 2-D array which, when matrix-multiplied by ``x``, gives the values of
+ the equality constraints at ``x``.
+ b : 1-D array
+ 1-D array of values representing the RHS of each equality constraint
+ (row) in ``A_eq``.
+ x0 : 1-D array, optional
+ Starting values of the independent variables, which will be refined by
+ the optimization algorithm. For the revised simplex method, these must
+ correspond with a basic feasible solution.
+ callback : callable, optional
+ If a callback function is provided, it will be called within each
+ iteration of the algorithm. The callback function must accept a single
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ Current solution vector.
+ fun : float
+ Current value of the objective function ``c @ x``.
+ success : bool
+ True only when an algorithm has completed successfully,
+ so this is always False as the callback function is called
+ only while the algorithm is still iterating.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable
+ corresponds to an inequality constraint. If the slack is zero,
+ the corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ that is, ``b - A_eq @ x``.
+ phase : int
+ The phase of the algorithm being executed.
+ status : int
+ For revised simplex, this is always 0 because if a different
+ status is detected, the algorithm terminates.
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform in either phase.
+ tol : float
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+ disp : bool
+ Set to ``True`` if indicators of optimization status are to be printed
+ to the console each iteration.
+ maxupdate : int
+ The maximum number of updates performed on the LU factorization.
+ After this many updates is reached, the basis matrix is factorized
+ from scratch.
+ mast : bool
+ Minimize Amortized Solve Time. If enabled, the average time to solve
+ a linear system using the basis factorization is measured. Typically,
+ the average solve time will decrease with each successive solve after
+ initial factorization, as factorization takes much more time than the
+ solve operation (and updates). Eventually, however, the updated
+ factorization becomes sufficiently complex that the average solve time
+ begins to increase. When this is detected, the basis is refactorized
+ from scratch. Enable this option to maximize speed at the risk of
+ nondeterministic behavior. Ignored if ``maxupdate`` is 0.
+ pivot : "mrc" or "bland"
+ Pivot rule: Minimum Reduced Cost (default) or Bland's rule. Choose
+ Bland's rule if iteration limit is reached and cycling is suspected.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ x : 1-D array
+ Solution vector.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Numerical difficulties encountered
+ 5 : No constraints; turn presolve on
+ 6 : Guess x0 cannot be converted to a basic feasible solution
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+ iteration : int
+ The number of iterations taken to solve the problem.
+ """
+
+ _check_unknown_options(unknown_options)
+
+ messages = ["Optimization terminated successfully.",
+ "Iteration limit reached.",
+ "The problem appears infeasible, as the phase one auxiliary "
+ "problem terminated successfully with a residual of {0:.1e}, "
+ "greater than the tolerance {1} required for the solution to "
+ "be considered feasible. Consider increasing the tolerance to "
+ "be greater than {0:.1e}. If this tolerance is unacceptably "
+ "large, the problem is likely infeasible.",
+ "The problem is unbounded, as the simplex algorithm found "
+ "a basic feasible solution from which there is a direction "
+ "with negative reduced cost in which all decision variables "
+ "increase.",
+ "Numerical difficulties encountered; consider trying "
+ "method='interior-point'.",
+ "Problems with no constraints are trivially solved; please "
+ "turn presolve on.",
+ "The guess x0 cannot be converted to a basic feasible "
+ "solution. "
+ ]
+
+ if A.size == 0: # address test_unbounded_below_no_presolve_corrected
+ return np.zeros(c.shape), 5, messages[5], 0
+
+ x, basis, A, b, residual, status, iteration = (
+ _phase_one(A, b, x0, callback, postsolve_args,
+ maxiter, tol, disp, maxupdate, mast, pivot))
+
+ if status == 0:
+ x, basis, status, iteration = _phase_two(c, A, x, basis, callback,
+ postsolve_args,
+ maxiter, tol, disp,
+ maxupdate, mast, pivot,
+ iteration)
+
+ return x, status, messages[status].format(residual, tol), iteration
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_simplex.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_simplex.py
new file mode 100644
index 0000000000000000000000000000000000000000..c47806c9a595f756b9f86d268c5c146ea86c77c6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_simplex.py
@@ -0,0 +1,663 @@
+"""Simplex method for linear programming
+
+The *simplex* method uses a traditional, full-tableau implementation of
+Dantzig's simplex algorithm [1]_, [2]_ (*not* the Nelder-Mead simplex).
+This algorithm is included for backwards compatibility and educational
+purposes.
+
+ .. versionadded:: 0.15.0
+
+Warnings
+--------
+
+The simplex method may encounter numerical difficulties when pivot
+values are close to the specified tolerance. If encountered try
+remove any redundant constraints, change the pivot strategy to Bland's
+rule or increase the tolerance value.
+
+Alternatively, more robust methods maybe be used. See
+:ref:`'interior-point' ` and
+:ref:`'revised simplex' `.
+
+References
+----------
+.. [1] Dantzig, George B., Linear programming and extensions. Rand
+ Corporation Research Study Princeton Univ. Press, Princeton, NJ,
+ 1963
+.. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
+ Mathematical Programming", McGraw-Hill, Chapter 4.
+"""
+
+import numpy as np
+from warnings import warn
+from ._optimize import OptimizeResult, OptimizeWarning, _check_unknown_options
+from ._linprog_util import _postsolve
+
+
+def _pivot_col(T, tol=1e-9, bland=False):
+ """
+ Given a linear programming simplex tableau, determine the column
+ of the variable to enter the basis.
+
+ Parameters
+ ----------
+ T : 2-D array
+ A 2-D array representing the simplex tableau, T, corresponding to the
+ linear programming problem. It should have the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0]]
+
+ for a Phase 2 problem, or the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0],
+ [c'[0], c'[1], ..., c'[n_total], 0]]
+
+ for a Phase 1 problem (a problem in which a basic feasible solution is
+ sought prior to maximizing the actual objective. ``T`` is modified in
+ place by ``_solve_simplex``.
+ tol : float
+ Elements in the objective row larger than -tol will not be considered
+ for pivoting. Nominally this value is zero, but numerical issues
+ cause a tolerance about zero to be necessary.
+ bland : bool
+ If True, use Bland's rule for selection of the column (select the
+ first column with a negative coefficient in the objective row,
+ regardless of magnitude).
+
+ Returns
+ -------
+ status: bool
+ True if a suitable pivot column was found, otherwise False.
+ A return of False indicates that the linear programming simplex
+ algorithm is complete.
+ col: int
+ The index of the column of the pivot element.
+ If status is False, col will be returned as nan.
+ """
+ ma = np.ma.masked_where(T[-1, :-1] >= -tol, T[-1, :-1], copy=False)
+ if ma.count() == 0:
+ return False, np.nan
+ if bland:
+ # ma.mask is sometimes 0d
+ return True, np.nonzero(np.logical_not(np.atleast_1d(ma.mask)))[0][0]
+ return True, np.ma.nonzero(ma == ma.min())[0][0]
+
+
+def _pivot_row(T, basis, pivcol, phase, tol=1e-9, bland=False):
+ """
+ Given a linear programming simplex tableau, determine the row for the
+ pivot operation.
+
+ Parameters
+ ----------
+ T : 2-D array
+ A 2-D array representing the simplex tableau, T, corresponding to the
+ linear programming problem. It should have the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0]]
+
+ for a Phase 2 problem, or the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0],
+ [c'[0], c'[1], ..., c'[n_total], 0]]
+
+ for a Phase 1 problem (a Problem in which a basic feasible solution is
+ sought prior to maximizing the actual objective. ``T`` is modified in
+ place by ``_solve_simplex``.
+ basis : array
+ A list of the current basic variables.
+ pivcol : int
+ The index of the pivot column.
+ phase : int
+ The phase of the simplex algorithm (1 or 2).
+ tol : float
+ Elements in the pivot column smaller than tol will not be considered
+ for pivoting. Nominally this value is zero, but numerical issues
+ cause a tolerance about zero to be necessary.
+ bland : bool
+ If True, use Bland's rule for selection of the row (if more than one
+ row can be used, choose the one with the lowest variable index).
+
+ Returns
+ -------
+ status: bool
+ True if a suitable pivot row was found, otherwise False. A return
+ of False indicates that the linear programming problem is unbounded.
+ row: int
+ The index of the row of the pivot element. If status is False, row
+ will be returned as nan.
+ """
+ if phase == 1:
+ k = 2
+ else:
+ k = 1
+ ma = np.ma.masked_where(T[:-k, pivcol] <= tol, T[:-k, pivcol], copy=False)
+ if ma.count() == 0:
+ return False, np.nan
+ mb = np.ma.masked_where(T[:-k, pivcol] <= tol, T[:-k, -1], copy=False)
+ q = mb / ma
+ min_rows = np.ma.nonzero(q == q.min())[0]
+ if bland:
+ return True, min_rows[np.argmin(np.take(basis, min_rows))]
+ return True, min_rows[0]
+
+
+def _apply_pivot(T, basis, pivrow, pivcol, tol=1e-9):
+ """
+ Pivot the simplex tableau inplace on the element given by (pivrow, pivol).
+ The entering variable corresponds to the column given by pivcol forcing
+ the variable basis[pivrow] to leave the basis.
+
+ Parameters
+ ----------
+ T : 2-D array
+ A 2-D array representing the simplex tableau, T, corresponding to the
+ linear programming problem. It should have the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0]]
+
+ for a Phase 2 problem, or the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0],
+ [c'[0], c'[1], ..., c'[n_total], 0]]
+
+ for a Phase 1 problem (a problem in which a basic feasible solution is
+ sought prior to maximizing the actual objective. ``T`` is modified in
+ place by ``_solve_simplex``.
+ basis : 1-D array
+ An array of the indices of the basic variables, such that basis[i]
+ contains the column corresponding to the basic variable for row i.
+ Basis is modified in place by _apply_pivot.
+ pivrow : int
+ Row index of the pivot.
+ pivcol : int
+ Column index of the pivot.
+ """
+ basis[pivrow] = pivcol
+ pivval = T[pivrow, pivcol]
+ T[pivrow] = T[pivrow] / pivval
+ for irow in range(T.shape[0]):
+ if irow != pivrow:
+ T[irow] = T[irow] - T[pivrow] * T[irow, pivcol]
+
+ # The selected pivot should never lead to a pivot value less than the tol.
+ if np.isclose(pivval, tol, atol=0, rtol=1e4):
+ message = (
+ f"The pivot operation produces a pivot value of:{pivval: .1e}, "
+ "which is only slightly greater than the specified "
+ f"tolerance{tol: .1e}. This may lead to issues regarding the "
+ "numerical stability of the simplex method. "
+ "Removing redundant constraints, changing the pivot strategy "
+ "via Bland's rule or increasing the tolerance may "
+ "help reduce the issue.")
+ warn(message, OptimizeWarning, stacklevel=5)
+
+
+def _solve_simplex(T, n, basis, callback, postsolve_args,
+ maxiter=1000, tol=1e-9, phase=2, bland=False, nit0=0,
+ ):
+ """
+ Solve a linear programming problem in "standard form" using the Simplex
+ Method. Linear Programming is intended to solve the following problem form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ Parameters
+ ----------
+ T : 2-D array
+ A 2-D array representing the simplex tableau, T, corresponding to the
+ linear programming problem. It should have the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0]]
+
+ for a Phase 2 problem, or the form:
+
+ [[A[0, 0], A[0, 1], ..., A[0, n_total], b[0]],
+ [A[1, 0], A[1, 1], ..., A[1, n_total], b[1]],
+ .
+ .
+ .
+ [A[m, 0], A[m, 1], ..., A[m, n_total], b[m]],
+ [c[0], c[1], ..., c[n_total], 0],
+ [c'[0], c'[1], ..., c'[n_total], 0]]
+
+ for a Phase 1 problem (a problem in which a basic feasible solution is
+ sought prior to maximizing the actual objective. ``T`` is modified in
+ place by ``_solve_simplex``.
+ n : int
+ The number of true variables in the problem.
+ basis : 1-D array
+ An array of the indices of the basic variables, such that basis[i]
+ contains the column corresponding to the basic variable for row i.
+ Basis is modified in place by _solve_simplex
+ callback : callable, optional
+ If a callback function is provided, it will be called within each
+ iteration of the algorithm. The callback must accept a
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ Current solution vector
+ fun : float
+ Current value of the objective function
+ success : bool
+ True only when a phase has completed successfully. This
+ will be False for most iterations.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable
+ corresponds to an inequality constraint. If the slack is zero,
+ the corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ that is, ``b - A_eq @ x``
+ phase : int
+ The phase of the optimization being executed. In phase 1 a basic
+ feasible solution is sought and the T has an additional row
+ representing an alternate objective function.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem.
+ maxiter : int
+ The maximum number of iterations to perform before aborting the
+ optimization.
+ tol : float
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+ phase : int
+ The phase of the optimization being executed. In phase 1 a basic
+ feasible solution is sought and the T has an additional row
+ representing an alternate objective function.
+ bland : bool
+ If True, choose pivots using Bland's rule [3]_. In problems which
+ fail to converge due to cycling, using Bland's rule can provide
+ convergence at the expense of a less optimal path about the simplex.
+ nit0 : int
+ The initial iteration number used to keep an accurate iteration total
+ in a two-phase problem.
+
+ Returns
+ -------
+ nit : int
+ The number of iterations. Used to keep an accurate iteration total
+ in the two-phase problem.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ """
+ nit = nit0
+ status = 0
+ message = ''
+ complete = False
+
+ if phase == 1:
+ m = T.shape[1]-2
+ elif phase == 2:
+ m = T.shape[1]-1
+ else:
+ raise ValueError("Argument 'phase' to _solve_simplex must be 1 or 2")
+
+ if phase == 2:
+ # Check if any artificial variables are still in the basis.
+ # If yes, check if any coefficients from this row and a column
+ # corresponding to one of the non-artificial variable is non-zero.
+ # If found, pivot at this term. If not, start phase 2.
+ # Do this for all artificial variables in the basis.
+ # Ref: "An Introduction to Linear Programming and Game Theory"
+ # by Paul R. Thie, Gerard E. Keough, 3rd Ed,
+ # Chapter 3.7 Redundant Systems (pag 102)
+ for pivrow in [row for row in range(basis.size)
+ if basis[row] > T.shape[1] - 2]:
+ non_zero_row = [col for col in range(T.shape[1] - 1)
+ if abs(T[pivrow, col]) > tol]
+ if len(non_zero_row) > 0:
+ pivcol = non_zero_row[0]
+ _apply_pivot(T, basis, pivrow, pivcol, tol)
+ nit += 1
+
+ if len(basis[:m]) == 0:
+ solution = np.empty(T.shape[1] - 1, dtype=np.float64)
+ else:
+ solution = np.empty(max(T.shape[1] - 1, max(basis[:m]) + 1),
+ dtype=np.float64)
+
+ while not complete:
+ # Find the pivot column
+ pivcol_found, pivcol = _pivot_col(T, tol, bland)
+ if not pivcol_found:
+ pivcol = np.nan
+ pivrow = np.nan
+ status = 0
+ complete = True
+ else:
+ # Find the pivot row
+ pivrow_found, pivrow = _pivot_row(T, basis, pivcol, phase, tol, bland)
+ if not pivrow_found:
+ status = 3
+ complete = True
+
+ if callback is not None:
+ solution[:] = 0
+ solution[basis[:n]] = T[:n, -1]
+ x = solution[:m]
+ x, fun, slack, con = _postsolve(
+ x, postsolve_args
+ )
+ res = OptimizeResult({
+ 'x': x,
+ 'fun': fun,
+ 'slack': slack,
+ 'con': con,
+ 'status': status,
+ 'message': message,
+ 'nit': nit,
+ 'success': status == 0 and complete,
+ 'phase': phase,
+ 'complete': complete,
+ })
+ callback(res)
+
+ if not complete:
+ if nit >= maxiter:
+ # Iteration limit exceeded
+ status = 1
+ complete = True
+ else:
+ _apply_pivot(T, basis, pivrow, pivcol, tol)
+ nit += 1
+ return nit, status
+
+
+def _linprog_simplex(c, c0, A, b, callback, postsolve_args,
+ maxiter=1000, tol=1e-9, disp=False, bland=False,
+ **unknown_options):
+ """
+ Minimize a linear objective function subject to linear equality and
+ non-negativity constraints using the two phase simplex method.
+ Linear programming is intended to solve problems of the following form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ User-facing documentation is in _linprog_doc.py.
+
+ Parameters
+ ----------
+ c : 1-D array
+ Coefficients of the linear objective function to be minimized.
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables. (Purely for display.)
+ A : 2-D array
+ 2-D array such that ``A @ x``, gives the values of the equality
+ constraints at ``x``.
+ b : 1-D array
+ 1-D array of values representing the right hand side of each equality
+ constraint (row) in ``A``.
+ callback : callable, optional
+ If a callback function is provided, it will be called within each
+ iteration of the algorithm. The callback function must accept a single
+ `scipy.optimize.OptimizeResult` consisting of the following fields:
+
+ x : 1-D array
+ Current solution vector
+ fun : float
+ Current value of the objective function
+ success : bool
+ True when an algorithm has completed successfully.
+ slack : 1-D array
+ The values of the slack variables. Each slack variable
+ corresponds to an inequality constraint. If the slack is zero,
+ the corresponding constraint is active.
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints,
+ that is, ``b - A_eq @ x``
+ phase : int
+ The phase of the algorithm being executed.
+ status : int
+ An integer representing the status of the optimization::
+
+ 0 : Algorithm proceeding nominally
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+ nit : int
+ The number of iterations performed.
+ message : str
+ A string descriptor of the exit status of the optimization.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem.
+
+ Options
+ -------
+ maxiter : int
+ The maximum number of iterations to perform.
+ disp : bool
+ If True, print exit status message to sys.stdout
+ tol : float
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+ bland : bool
+ If True, use Bland's anti-cycling rule [3]_ to choose pivots to
+ prevent cycling. If False, choose pivots which should lead to a
+ converged solution more quickly. The latter method is subject to
+ cycling (non-convergence) in rare instances.
+ unknown_options : dict
+ Optional arguments not used by this particular solver. If
+ `unknown_options` is non-empty a warning is issued listing all
+ unused options.
+
+ Returns
+ -------
+ x : 1-D array
+ Solution vector.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+ iteration : int
+ The number of iterations taken to solve the problem.
+
+ References
+ ----------
+ .. [1] Dantzig, George B., Linear programming and extensions. Rand
+ Corporation Research Study Princeton Univ. Press, Princeton, NJ,
+ 1963
+ .. [2] Hillier, S.H. and Lieberman, G.J. (1995), "Introduction to
+ Mathematical Programming", McGraw-Hill, Chapter 4.
+ .. [3] Bland, Robert G. New finite pivoting rules for the simplex method.
+ Mathematics of Operations Research (2), 1977: pp. 103-107.
+
+
+ Notes
+ -----
+ The expected problem formulation differs between the top level ``linprog``
+ module and the method specific solvers. The method specific solvers expect a
+ problem in standard form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ Whereas the top level ``linprog`` module expects a problem of form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ where ``lb = 0`` and ``ub = None`` unless set in ``bounds``.
+
+ The original problem contains equality, upper-bound and variable constraints
+ whereas the method specific solver requires equality constraints and
+ variable non-negativity.
+
+ ``linprog`` module converts the original problem to standard form by
+ converting the simple bounds to upper bound constraints, introducing
+ non-negative slack variables for inequality constraints, and expressing
+ unbounded variables as the difference between two non-negative variables.
+ """
+ _check_unknown_options(unknown_options)
+
+ status = 0
+ messages = {0: "Optimization terminated successfully.",
+ 1: "Iteration limit reached.",
+ 2: "Optimization failed. Unable to find a feasible"
+ " starting point.",
+ 3: "Optimization failed. The problem appears to be unbounded.",
+ 4: "Optimization failed. Singular matrix encountered."}
+
+ n, m = A.shape
+
+ # All constraints must have b >= 0.
+ is_negative_constraint = np.less(b, 0)
+ A[is_negative_constraint] *= -1
+ b[is_negative_constraint] *= -1
+
+ # As all constraints are equality constraints the artificial variables
+ # will also be basic variables.
+ av = np.arange(n) + m
+ basis = av.copy()
+
+ # Format the phase one tableau by adding artificial variables and stacking
+ # the constraints, the objective row and pseudo-objective row.
+ row_constraints = np.hstack((A, np.eye(n), b[:, np.newaxis]))
+ row_objective = np.hstack((c, np.zeros(n), c0))
+ row_pseudo_objective = -row_constraints.sum(axis=0)
+ row_pseudo_objective[av] = 0
+ T = np.vstack((row_constraints, row_objective, row_pseudo_objective))
+
+ nit1, status = _solve_simplex(T, n, basis, callback=callback,
+ postsolve_args=postsolve_args,
+ maxiter=maxiter, tol=tol, phase=1,
+ bland=bland
+ )
+ # if pseudo objective is zero, remove the last row from the tableau and
+ # proceed to phase 2
+ nit2 = nit1
+ if abs(T[-1, -1]) < tol:
+ # Remove the pseudo-objective row from the tableau
+ T = T[:-1, :]
+ # Remove the artificial variable columns from the tableau
+ T = np.delete(T, av, 1)
+ else:
+ # Failure to find a feasible starting point
+ status = 2
+ messages[status] = (
+ "Phase 1 of the simplex method failed to find a feasible "
+ "solution. The pseudo-objective function evaluates to "
+ f"{abs(T[-1, -1]):.1e} "
+ f"which exceeds the required tolerance of {tol} for a solution to be "
+ "considered 'close enough' to zero to be a basic solution. "
+ "Consider increasing the tolerance to be greater than "
+ f"{abs(T[-1, -1]):.1e}. "
+ "If this tolerance is unacceptably large the problem may be "
+ "infeasible."
+ )
+
+ if status == 0:
+ # Phase 2
+ nit2, status = _solve_simplex(T, n, basis, callback=callback,
+ postsolve_args=postsolve_args,
+ maxiter=maxiter, tol=tol, phase=2,
+ bland=bland, nit0=nit1
+ )
+
+ solution = np.zeros(n + m)
+ solution[basis[:n]] = T[:n, -1]
+ x = solution[:m]
+
+ return x, status, messages[status], int(nit2)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_util.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_util.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7a956ef349ee02acd5db0b888cc78cd249c9f70
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_linprog_util.py
@@ -0,0 +1,1521 @@
+"""
+Method agnostic utility functions for linear programming
+"""
+
+import numpy as np
+import scipy.sparse as sps
+from warnings import warn
+from ._optimize import OptimizeWarning
+from scipy.optimize._remove_redundancy import (
+ _remove_redundancy_svd, _remove_redundancy_pivot_sparse,
+ _remove_redundancy_pivot_dense, _remove_redundancy_id
+ )
+from collections import namedtuple
+
+_LPProblem = namedtuple('_LPProblem',
+ 'c A_ub b_ub A_eq b_eq bounds x0 integrality')
+_LPProblem.__new__.__defaults__ = (None,) * 7 # make c the only required arg
+_LPProblem.__doc__ = \
+ """ Represents a linear-programming problem.
+
+ Attributes
+ ----------
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : various valid formats, optional
+ The bounds of ``x``, as ``min`` and ``max`` pairs.
+ If bounds are specified for all N variables separately, valid formats
+ are:
+ * a 2D array (N x 2);
+ * a sequence of N sequences, each with 2 values.
+ If all variables have the same bounds, the bounds can be specified as
+ a 1-D or 2-D array or sequence with 2 scalar values.
+ If all variables have a lower bound of 0 and no upper bound, the bounds
+ parameter can be omitted (or given as None).
+ Absent lower and/or upper bounds can be specified as -numpy.inf (no
+ lower bound), numpy.inf (no upper bound) or None (both).
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+ integrality : 1-D array or int, optional
+ Indicates the type of integrality constraint on each decision variable.
+
+ ``0`` : Continuous variable; no integrality constraint.
+
+ ``1`` : Integer variable; decision variable must be an integer
+ within `bounds`.
+
+ ``2`` : Semi-continuous variable; decision variable must be within
+ `bounds` or take value ``0``.
+
+ ``3`` : Semi-integer variable; decision variable must be an integer
+ within `bounds` or take value ``0``.
+
+ By default, all variables are continuous.
+
+ For mixed integrality constraints, supply an array of shape `c.shape`.
+ To infer a constraint on each decision variable from shorter inputs,
+ the argument will be broadcast to `c.shape` using `np.broadcast_to`.
+
+ This argument is currently used only by the ``'highs'`` method and
+ ignored otherwise.
+
+ Notes
+ -----
+ This namedtuple supports 2 ways of initialization:
+ >>> lp1 = _LPProblem(c=[-1, 4], A_ub=[[-3, 1], [1, 2]], b_ub=[6, 4])
+ >>> lp2 = _LPProblem([-1, 4], [[-3, 1], [1, 2]], [6, 4])
+
+ Note that only ``c`` is a required argument here, whereas all other arguments
+ ``A_ub``, ``b_ub``, ``A_eq``, ``b_eq``, ``bounds``, ``x0`` are optional with
+ default values of None.
+ For example, ``A_eq`` and ``b_eq`` can be set without ``A_ub`` or ``b_ub``:
+ >>> lp3 = _LPProblem(c=[-1, 4], A_eq=[[2, 1]], b_eq=[10])
+ """
+
+
+def _check_sparse_inputs(options, meth, A_ub, A_eq):
+ """
+ Check the provided ``A_ub`` and ``A_eq`` matrices conform to the specified
+ optional sparsity variables.
+
+ Parameters
+ ----------
+ A_ub : 2-D array, optional
+ 2-D array such that ``A_ub @ x`` gives the values of the upper-bound
+ inequality constraints at ``x``.
+ A_eq : 2-D array, optional
+ 2-D array such that ``A_eq @ x`` gives the values of the equality
+ constraints at ``x``.
+ options : dict
+ A dictionary of solver options. All methods accept the following
+ generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ Set to True to print convergence messages.
+
+ For method-specific options, see :func:`show_options('linprog')`.
+ method : str, optional
+ The algorithm used to solve the standard form problem.
+
+ Returns
+ -------
+ A_ub : 2-D array, optional
+ 2-D array such that ``A_ub @ x`` gives the values of the upper-bound
+ inequality constraints at ``x``.
+ A_eq : 2-D array, optional
+ 2-D array such that ``A_eq @ x`` gives the values of the equality
+ constraints at ``x``.
+ options : dict
+ A dictionary of solver options. All methods accept the following
+ generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ Set to True to print convergence messages.
+
+ For method-specific options, see :func:`show_options('linprog')`.
+ """
+ # This is an undocumented option for unit testing sparse presolve
+ _sparse_presolve = options.pop('_sparse_presolve', False)
+ if _sparse_presolve and A_eq is not None:
+ A_eq = sps.coo_array(A_eq)
+ if _sparse_presolve and A_ub is not None:
+ A_ub = sps.coo_array(A_ub)
+
+ sparse_constraint = sps.issparse(A_eq) or sps.issparse(A_ub)
+
+ preferred_methods = {"highs", "highs-ds", "highs-ipm"}
+ dense_methods = {"simplex", "revised simplex"}
+ if meth in dense_methods and sparse_constraint:
+ raise ValueError(f"Method '{meth}' does not support sparse "
+ "constraint matrices. Please consider using one of "
+ f"{preferred_methods}.")
+
+ sparse = options.get('sparse', False)
+ if not sparse and sparse_constraint and meth == 'interior-point':
+ options['sparse'] = True
+ warn("Sparse constraint matrix detected; setting 'sparse':True.",
+ OptimizeWarning, stacklevel=4)
+ return options, A_ub, A_eq
+
+
+def _format_A_constraints(A, n_x, sparse_lhs=False):
+ """Format the left hand side of the constraints to a 2-D array
+
+ Parameters
+ ----------
+ A : 2-D array
+ 2-D array such that ``A @ x`` gives the values of the upper-bound
+ (in)equality constraints at ``x``.
+ n_x : int
+ The number of variables in the linear programming problem.
+ sparse_lhs : bool
+ Whether either of `A_ub` or `A_eq` are sparse. If true return a
+ coo_array instead of a numpy array.
+
+ Returns
+ -------
+ np.ndarray or sparse.coo_array
+ 2-D array such that ``A @ x`` gives the values of the upper-bound
+ (in)equality constraints at ``x``.
+
+ """
+ if sparse_lhs:
+ return sps.coo_array(
+ (0, n_x) if A is None else A, dtype=float, copy=True
+ )
+ elif A is None:
+ return np.zeros((0, n_x), dtype=float)
+ else:
+ return np.array(A, dtype=float, copy=True)
+
+
+def _format_b_constraints(b):
+ """Format the upper bounds of the constraints to a 1-D array
+
+ Parameters
+ ----------
+ b : 1-D array
+ 1-D array of values representing the upper-bound of each (in)equality
+ constraint (row) in ``A``.
+
+ Returns
+ -------
+ 1-D np.array
+ 1-D array of values representing the upper-bound of each (in)equality
+ constraint (row) in ``A``.
+
+ """
+ if b is None:
+ return np.array([], dtype=float)
+ b = np.array(b, dtype=float, copy=True).squeeze()
+ return b if b.size != 1 else b.reshape(-1)
+
+
+def _clean_inputs(lp):
+ """
+ Given user inputs for a linear programming problem, return the
+ objective vector, upper bound constraints, equality constraints,
+ and simple bounds in a preferred format.
+
+ Parameters
+ ----------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : various valid formats, optional
+ The bounds of ``x``, as ``min`` and ``max`` pairs.
+ If bounds are specified for all N variables separately, valid formats are:
+ * a 2D array (2 x N or N x 2);
+ * a sequence of N sequences, each with 2 values.
+ If all variables have the same bounds, a single pair of values can
+ be specified. Valid formats are:
+ * a sequence with 2 scalar values;
+ * a sequence with a single element containing 2 scalar values.
+ If all variables have a lower bound of 0 and no upper bound, the bounds
+ parameter can be omitted (or given as None).
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ Returns
+ -------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N
+ elements of ``x``. The N x 2 array contains lower bounds in the first
+ column and upper bounds in the 2nd. Unbounded variables have lower
+ bound -np.inf and/or upper bound np.inf.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ """
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp
+
+ if c is None:
+ raise TypeError
+
+ try:
+ c = np.array(c, dtype=np.float64, copy=True).squeeze()
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: c must be a 1-D array of numerical "
+ "coefficients") from e
+ else:
+ # If c is a single value, convert it to a 1-D array.
+ if c.size == 1:
+ c = c.reshape(-1)
+
+ n_x = len(c)
+ if n_x == 0 or len(c.shape) != 1:
+ raise ValueError(
+ "Invalid input for linprog: c must be a 1-D array and must "
+ "not have more than one non-singleton dimension")
+ if not np.isfinite(c).all():
+ raise ValueError(
+ "Invalid input for linprog: c must not contain values "
+ "inf, nan, or None")
+
+ sparse_lhs = sps.issparse(A_eq) or sps.issparse(A_ub)
+ try:
+ A_ub = _format_A_constraints(A_ub, n_x, sparse_lhs=sparse_lhs)
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: A_ub must be a 2-D array "
+ "of numerical values") from e
+ else:
+ n_ub = A_ub.shape[0]
+ if len(A_ub.shape) != 2 or A_ub.shape[1] != n_x:
+ raise ValueError(
+ "Invalid input for linprog: A_ub must have exactly two "
+ "dimensions, and the number of columns in A_ub must be "
+ "equal to the size of c")
+ if (sps.issparse(A_ub) and not np.isfinite(A_ub.data).all()
+ or not sps.issparse(A_ub) and not np.isfinite(A_ub).all()):
+ raise ValueError(
+ "Invalid input for linprog: A_ub must not contain values "
+ "inf, nan, or None")
+
+ try:
+ b_ub = _format_b_constraints(b_ub)
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: b_ub must be a 1-D array of "
+ "numerical values, each representing the upper bound of an "
+ "inequality constraint (row) in A_ub") from e
+ else:
+ if b_ub.shape != (n_ub,):
+ raise ValueError(
+ "Invalid input for linprog: b_ub must be a 1-D array; b_ub "
+ "must not have more than one non-singleton dimension and "
+ "the number of rows in A_ub must equal the number of values "
+ "in b_ub")
+ if not np.isfinite(b_ub).all():
+ raise ValueError(
+ "Invalid input for linprog: b_ub must not contain values "
+ "inf, nan, or None")
+
+ try:
+ A_eq = _format_A_constraints(A_eq, n_x, sparse_lhs=sparse_lhs)
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: A_eq must be a 2-D array "
+ "of numerical values") from e
+ else:
+ n_eq = A_eq.shape[0]
+ if len(A_eq.shape) != 2 or A_eq.shape[1] != n_x:
+ raise ValueError(
+ "Invalid input for linprog: A_eq must have exactly two "
+ "dimensions, and the number of columns in A_eq must be "
+ "equal to the size of c")
+
+ if (sps.issparse(A_eq) and not np.isfinite(A_eq.data).all()
+ or not sps.issparse(A_eq) and not np.isfinite(A_eq).all()):
+ raise ValueError(
+ "Invalid input for linprog: A_eq must not contain values "
+ "inf, nan, or None")
+
+ try:
+ b_eq = _format_b_constraints(b_eq)
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: b_eq must be a dense, 1-D array of "
+ "numerical values, each representing the right hand side of an "
+ "equality constraint (row) in A_eq") from e
+ else:
+ if b_eq.shape != (n_eq,):
+ raise ValueError(
+ "Invalid input for linprog: b_eq must be a 1-D array; b_eq "
+ "must not have more than one non-singleton dimension and "
+ "the number of rows in A_eq must equal the number of values "
+ "in b_eq")
+ if not np.isfinite(b_eq).all():
+ raise ValueError(
+ "Invalid input for linprog: b_eq must not contain values "
+ "inf, nan, or None")
+
+ # x0 gives a (optional) starting solution to the solver. If x0 is None,
+ # skip the checks. Initial solution will be generated automatically.
+ if x0 is not None:
+ try:
+ x0 = np.array(x0, dtype=float, copy=True).squeeze()
+ except ValueError as e:
+ raise TypeError(
+ "Invalid input for linprog: x0 must be a 1-D array of "
+ "numerical coefficients") from e
+ if x0.ndim == 0:
+ x0 = x0.reshape(-1)
+ if len(x0) == 0 or x0.ndim != 1:
+ raise ValueError(
+ "Invalid input for linprog: x0 should be a 1-D array; it "
+ "must not have more than one non-singleton dimension")
+ if not x0.size == c.size:
+ raise ValueError(
+ "Invalid input for linprog: x0 and c should contain the "
+ "same number of elements")
+ if not np.isfinite(x0).all():
+ raise ValueError(
+ "Invalid input for linprog: x0 must not contain values "
+ "inf, nan, or None")
+
+ # Bounds can be one of these formats:
+ # (1) a 2-D array or sequence, with shape N x 2
+ # (2) a 1-D or 2-D sequence or array with 2 scalars
+ # (3) None (or an empty sequence or array)
+ # Unspecified bounds can be represented by None or (-)np.inf.
+ # All formats are converted into an N x 2 np.array with (-)np.inf where
+ # bounds are unspecified.
+
+ # Prepare clean bounds array
+ bounds_clean = np.zeros((n_x, 2), dtype=float)
+
+ # Convert to a numpy array.
+ # np.array(..,dtype=float) raises an error if dimensions are inconsistent
+ # or if there are invalid data types in bounds. Just add a linprog prefix
+ # to the error and re-raise.
+ # Creating at least a 2-D array simplifies the cases to distinguish below.
+ if bounds is None or np.array_equal(bounds, []) or np.array_equal(bounds, [[]]):
+ bounds = (0, np.inf)
+ try:
+ bounds_conv = np.atleast_2d(np.array(bounds, dtype=float))
+ except ValueError as e:
+ raise ValueError(
+ "Invalid input for linprog: unable to interpret bounds, "
+ "check values and dimensions: " + e.args[0]) from e
+ except TypeError as e:
+ raise TypeError(
+ "Invalid input for linprog: unable to interpret bounds, "
+ "check values and dimensions: " + e.args[0]) from e
+
+ # Check bounds options
+ bsh = bounds_conv.shape
+ if len(bsh) > 2:
+ # Do not try to handle multidimensional bounds input
+ raise ValueError(
+ "Invalid input for linprog: provide a 2-D array for bounds, "
+ f"not a {len(bsh):d}-D array.")
+ elif np.all(bsh == (n_x, 2)):
+ # Regular N x 2 array
+ bounds_clean = bounds_conv
+ elif (np.all(bsh == (2, 1)) or np.all(bsh == (1, 2))):
+ # 2 values: interpret as overall lower and upper bound
+ bounds_flat = bounds_conv.flatten()
+ bounds_clean[:, 0] = bounds_flat[0]
+ bounds_clean[:, 1] = bounds_flat[1]
+ elif np.all(bsh == (2, n_x)):
+ # Reject a 2 x N array
+ raise ValueError(
+ f"Invalid input for linprog: provide a {n_x:d} x 2 array for bounds, "
+ f"not a 2 x {n_x:d} array.")
+ else:
+ raise ValueError(
+ "Invalid input for linprog: unable to interpret bounds with this "
+ f"dimension tuple: {bsh}.")
+
+ # The process above creates nan-s where the input specified None
+ # Convert the nan-s in the 1st column to -np.inf and in the 2nd column
+ # to np.inf
+ i_none = np.isnan(bounds_clean[:, 0])
+ bounds_clean[i_none, 0] = -np.inf
+ i_none = np.isnan(bounds_clean[:, 1])
+ bounds_clean[i_none, 1] = np.inf
+
+ return _LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds_clean, x0, integrality)
+
+
+def _presolve(lp, rr, rr_method, tol=1e-9):
+ """
+ Given inputs for a linear programming problem in preferred format,
+ presolve the problem: identify trivial infeasibilities, redundancies,
+ and unboundedness, tighten bounds where possible, and eliminate fixed
+ variables.
+
+ Parameters
+ ----------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N
+ elements of ``x``. The N x 2 array contains lower bounds in the first
+ column and upper bounds in the 2nd. Unbounded variables have lower
+ bound -np.inf and/or upper bound np.inf.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ rr : bool
+ If ``True`` attempts to eliminate any redundant rows in ``A_eq``.
+ Set False if ``A_eq`` is known to be of full row rank, or if you are
+ looking for a potential speedup (at the expense of reliability).
+ rr_method : string
+ Method used to identify and remove redundant rows from the
+ equality constraint matrix after presolve.
+ tol : float
+ The tolerance which determines when a solution is "close enough" to
+ zero in Phase 1 to be considered a basic feasible solution or close
+ enough to positive to serve as an optimal solution.
+
+ Returns
+ -------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, as ``min`` and ``max`` pairs, possibly tightened.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ c0 : 1D array
+ Constant term in objective function due to fixed (and eliminated)
+ variables.
+ x : 1D array
+ Solution vector (when the solution is trivial and can be determined
+ in presolve)
+ revstack: list of functions
+ the functions in the list reverse the operations of _presolve()
+ the function signature is x_org = f(x_mod), where x_mod is the result
+ of a presolve step and x_org the value at the start of the step
+ (currently, the revstack contains only one function)
+ complete: bool
+ Whether the solution is complete (solved or determined to be infeasible
+ or unbounded in presolve)
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ References
+ ----------
+ .. [5] Andersen, Erling D. "Finding all linearly dependent rows in
+ large-scale linear programming." Optimization Methods and Software
+ 6.3 (1995): 219-227.
+ .. [8] Andersen, Erling D., and Knud D. Andersen. "Presolving in linear
+ programming." Mathematical Programming 71.2 (1995): 221-245.
+
+ """
+ # ideas from Reference [5] by Andersen and Andersen
+ # however, unlike the reference, this is performed before converting
+ # problem to standard form
+ # There are a few advantages:
+ # * artificial variables have not been added, so matrices are smaller
+ # * bounds have not been converted to constraints yet. (It is better to
+ # do that after presolve because presolve may adjust the simple bounds.)
+ # There are many improvements that can be made, namely:
+ # * implement remaining checks from [5]
+ # * loop presolve until no additional changes are made
+ # * implement additional efficiency improvements in redundancy removal [2]
+
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, _ = lp
+
+ revstack = [] # record of variables eliminated from problem
+ # constant term in cost function may be added if variables are eliminated
+ c0 = 0
+ complete = False # complete is True if detected infeasible/unbounded
+ x = np.zeros(c.shape) # this is solution vector if completed in presolve
+
+ status = 0 # all OK unless determined otherwise
+ message = ""
+
+ # Lower and upper bounds. Copy to prevent feedback.
+ lb = bounds[:, 0].copy()
+ ub = bounds[:, 1].copy()
+
+ m_eq, n = A_eq.shape
+ m_ub, n = A_ub.shape
+
+ if (rr_method is not None
+ and rr_method.lower() not in {"svd", "pivot", "id"}):
+ message = ("'" + str(rr_method) + "' is not a valid option "
+ "for redundancy removal. Valid options are 'SVD', "
+ "'pivot', and 'ID'.")
+ raise ValueError(message)
+
+ if sps.issparse(A_eq):
+ A_eq = A_eq.tocsr()
+ A_ub = A_ub.tocsr()
+
+ def where(A):
+ return A.nonzero()
+
+ vstack = sps.vstack
+ else:
+ where = np.where
+ vstack = np.vstack
+
+ # upper bounds > lower bounds
+ if np.any(ub < lb) or np.any(lb == np.inf) or np.any(ub == -np.inf):
+ status = 2
+ message = ("The problem is (trivially) infeasible since one "
+ "or more upper bounds are smaller than the corresponding "
+ "lower bounds, a lower bound is np.inf or an upper bound "
+ "is -np.inf.")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+
+ # zero row in equality constraints
+ zero_row = np.array(np.sum(A_eq != 0, axis=1) == 0).flatten()
+ if np.any(zero_row):
+ if np.any(
+ np.logical_and(
+ zero_row,
+ np.abs(b_eq) > tol)): # test_zero_row_1
+ # infeasible if RHS is not zero
+ status = 2
+ message = ("The problem is (trivially) infeasible due to a row "
+ "of zeros in the equality constraint matrix with a "
+ "nonzero corresponding constraint value.")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+ else: # test_zero_row_2
+ # if RHS is zero, we can eliminate this equation entirely
+ A_eq = A_eq[np.logical_not(zero_row), :]
+ b_eq = b_eq[np.logical_not(zero_row)]
+
+ # zero row in inequality constraints
+ zero_row = np.array(np.sum(A_ub != 0, axis=1) == 0).flatten()
+ if np.any(zero_row):
+ if np.any(np.logical_and(zero_row, b_ub < -tol)): # test_zero_row_1
+ # infeasible if RHS is less than zero (because LHS is zero)
+ status = 2
+ message = ("The problem is (trivially) infeasible due to a row "
+ "of zeros in the equality constraint matrix with a "
+ "nonzero corresponding constraint value.")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+ else: # test_zero_row_2
+ # if LHS is >= 0, we can eliminate this constraint entirely
+ A_ub = A_ub[np.logical_not(zero_row), :]
+ b_ub = b_ub[np.logical_not(zero_row)]
+
+ # zero column in (both) constraints
+ # this indicates that a variable isn't constrained and can be removed
+ A = vstack((A_eq, A_ub))
+ if A.shape[0] > 0:
+ zero_col = np.array(np.sum(A != 0, axis=0) == 0).flatten()
+ # variable will be at upper or lower bound, depending on objective
+ x[np.logical_and(zero_col, c < 0)] = ub[
+ np.logical_and(zero_col, c < 0)]
+ x[np.logical_and(zero_col, c > 0)] = lb[
+ np.logical_and(zero_col, c > 0)]
+ if np.any(np.isinf(x)): # if an unconstrained variable has no bound
+ status = 3
+ message = ("If feasible, the problem is (trivially) unbounded "
+ "due to a zero column in the constraint matrices. If "
+ "you wish to check whether the problem is infeasible, "
+ "turn presolve off.")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+ # variables will equal upper/lower bounds will be removed later
+ lb[np.logical_and(zero_col, c < 0)] = ub[
+ np.logical_and(zero_col, c < 0)]
+ ub[np.logical_and(zero_col, c > 0)] = lb[
+ np.logical_and(zero_col, c > 0)]
+
+ # row singleton in equality constraints
+ # this fixes a variable and removes the constraint
+ singleton_row = np.array(np.sum(A_eq != 0, axis=1) == 1).flatten()
+ rows = where(singleton_row)[0]
+ cols = where(A_eq[rows, :])[1]
+ if len(rows) > 0:
+ for row, col in zip(rows, cols):
+ val = b_eq[row] / A_eq[row, col]
+ if not lb[col] - tol <= val <= ub[col] + tol:
+ # infeasible if fixed value is not within bounds
+ status = 2
+ message = ("The problem is (trivially) infeasible because a "
+ "singleton row in the equality constraints is "
+ "inconsistent with the bounds.")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+ else:
+ # sets upper and lower bounds at that fixed value - variable
+ # will be removed later
+ lb[col] = val
+ ub[col] = val
+ A_eq = A_eq[np.logical_not(singleton_row), :]
+ b_eq = b_eq[np.logical_not(singleton_row)]
+
+ # row singleton in inequality constraints
+ # this indicates a simple bound and the constraint can be removed
+ # simple bounds may be adjusted here
+ # After all of the simple bound information is combined here, get_Abc will
+ # turn the simple bounds into constraints
+ singleton_row = np.array(np.sum(A_ub != 0, axis=1) == 1).flatten()
+ cols = where(A_ub[singleton_row, :])[1]
+ rows = where(singleton_row)[0]
+ if len(rows) > 0:
+ for row, col in zip(rows, cols):
+ val = b_ub[row] / A_ub[row, col]
+ if A_ub[row, col] > 0: # upper bound
+ if val < lb[col] - tol: # infeasible
+ complete = True
+ elif val < ub[col]: # new upper bound
+ ub[col] = val
+ else: # lower bound
+ if val > ub[col] + tol: # infeasible
+ complete = True
+ elif val > lb[col]: # new lower bound
+ lb[col] = val
+ if complete:
+ status = 2
+ message = ("The problem is (trivially) infeasible because a "
+ "singleton row in the upper bound constraints is "
+ "inconsistent with the bounds.")
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+ A_ub = A_ub[np.logical_not(singleton_row), :]
+ b_ub = b_ub[np.logical_not(singleton_row)]
+
+ # identical bounds indicate that variable can be removed
+ i_f = np.abs(lb - ub) < tol # indices of "fixed" variables
+ i_nf = np.logical_not(i_f) # indices of "not fixed" variables
+
+ # test_bounds_equal_but_infeasible
+ if np.all(i_f): # if bounds define solution, check for consistency
+ residual = b_eq - A_eq.dot(lb)
+ slack = b_ub - A_ub.dot(lb)
+ if ((A_ub.size > 0 and np.any(slack < 0)) or
+ (A_eq.size > 0 and not np.allclose(residual, 0))):
+ status = 2
+ message = ("The problem is (trivially) infeasible because the "
+ "bounds fix all variables to values inconsistent with "
+ "the constraints")
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+
+ ub_mod = ub
+ lb_mod = lb
+ if np.any(i_f):
+ c0 += c[i_f].dot(lb[i_f])
+ b_eq = b_eq - A_eq[:, i_f].dot(lb[i_f])
+ b_ub = b_ub - A_ub[:, i_f].dot(lb[i_f])
+ c = c[i_nf]
+ x_undo = lb[i_f] # not x[i_f], x is just zeroes
+ x = x[i_nf]
+ # user guess x0 stays separate from presolve solution x
+ if x0 is not None:
+ x0 = x0[i_nf]
+ A_eq = A_eq[:, i_nf]
+ A_ub = A_ub[:, i_nf]
+ # modify bounds
+ lb_mod = lb[i_nf]
+ ub_mod = ub[i_nf]
+
+ def rev(x_mod):
+ # Function to restore x: insert x_undo into x_mod.
+ # When elements have been removed at positions k1, k2, k3, ...
+ # then these must be replaced at (after) positions k1-1, k2-2,
+ # k3-3, ... in the modified array to recreate the original
+ i = np.flatnonzero(i_f)
+ # Number of variables to restore
+ N = len(i)
+ index_offset = np.arange(N)
+ # Create insert indices
+ insert_indices = i - index_offset
+ x_rev = np.insert(x_mod.astype(float), insert_indices, x_undo)
+ return x_rev
+
+ # Use revstack as a list of functions, currently just this one.
+ revstack.append(rev)
+
+ # no constraints indicates that problem is trivial
+ if A_eq.size == 0 and A_ub.size == 0:
+ b_eq = np.array([])
+ b_ub = np.array([])
+ # test_empty_constraint_1
+ if c.size == 0:
+ status = 0
+ message = ("The solution was determined in presolve as there are "
+ "no non-trivial constraints.")
+ elif (np.any(np.logical_and(c < 0, ub_mod == np.inf)) or
+ np.any(np.logical_and(c > 0, lb_mod == -np.inf))):
+ # test_no_constraints()
+ # test_unbounded_no_nontrivial_constraints_1
+ # test_unbounded_no_nontrivial_constraints_2
+ status = 3
+ message = ("The problem is (trivially) unbounded "
+ "because there are no non-trivial constraints and "
+ "a) at least one decision variable is unbounded "
+ "above and its corresponding cost is negative, or "
+ "b) at least one decision variable is unbounded below "
+ "and its corresponding cost is positive. ")
+ else: # test_empty_constraint_2
+ status = 0
+ message = ("The solution was determined in presolve as there are "
+ "no non-trivial constraints.")
+ complete = True
+ x[c < 0] = ub_mod[c < 0]
+ x[c > 0] = lb_mod[c > 0]
+ # where c is zero, set x to a finite bound or zero
+ x_zero_c = ub_mod[c == 0]
+ x_zero_c[np.isinf(x_zero_c)] = ub_mod[c == 0][np.isinf(x_zero_c)]
+ x_zero_c[np.isinf(x_zero_c)] = 0
+ x[c == 0] = x_zero_c
+ # if this is not the last step of presolve, should convert bounds back
+ # to array and return here
+
+ # Convert modified lb and ub back into N x 2 bounds
+ bounds = np.hstack((lb_mod[:, np.newaxis], ub_mod[:, np.newaxis]))
+
+ # remove redundant (linearly dependent) rows from equality constraints
+ n_rows_A = A_eq.shape[0]
+ redundancy_warning = ("A_eq does not appear to be of full row rank. To "
+ "improve performance, check the problem formulation "
+ "for redundant equality constraints.")
+ if (sps.issparse(A_eq)):
+ if rr and A_eq.size > 0: # TODO: Fast sparse rank check?
+ rr_res = _remove_redundancy_pivot_sparse(A_eq, b_eq)
+ A_eq, b_eq, status, message = rr_res
+ if A_eq.shape[0] < n_rows_A:
+ warn(redundancy_warning, OptimizeWarning, stacklevel=1)
+ if status != 0:
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+
+ # This is a wild guess for which redundancy removal algorithm will be
+ # faster. More testing would be good.
+ small_nullspace = 5
+ if rr and A_eq.size > 0:
+ try: # TODO: use results of first SVD in _remove_redundancy_svd
+ rank = np.linalg.matrix_rank(A_eq)
+ # oh well, we'll have to go with _remove_redundancy_pivot_dense
+ except Exception:
+ rank = 0
+ if rr and A_eq.size > 0 and rank < A_eq.shape[0]:
+ warn(redundancy_warning, OptimizeWarning, stacklevel=3)
+ dim_row_nullspace = A_eq.shape[0]-rank
+ if rr_method is None:
+ if dim_row_nullspace <= small_nullspace:
+ rr_res = _remove_redundancy_svd(A_eq, b_eq)
+ A_eq, b_eq, status, message = rr_res
+ if dim_row_nullspace > small_nullspace or status == 4:
+ rr_res = _remove_redundancy_pivot_dense(A_eq, b_eq)
+ A_eq, b_eq, status, message = rr_res
+
+ else:
+ rr_method = rr_method.lower()
+ if rr_method == "svd":
+ rr_res = _remove_redundancy_svd(A_eq, b_eq)
+ A_eq, b_eq, status, message = rr_res
+ elif rr_method == "pivot":
+ rr_res = _remove_redundancy_pivot_dense(A_eq, b_eq)
+ A_eq, b_eq, status, message = rr_res
+ elif rr_method == "id":
+ rr_res = _remove_redundancy_id(A_eq, b_eq, rank)
+ A_eq, b_eq, status, message = rr_res
+ else: # shouldn't get here; option validity checked above
+ pass
+ if A_eq.shape[0] < rank:
+ message = ("Due to numerical issues, redundant equality "
+ "constraints could not be removed automatically. "
+ "Try providing your constraint matrices as sparse "
+ "matrices to activate sparse presolve, try turning "
+ "off redundancy removal, or try turning off presolve "
+ "altogether.")
+ status = 4
+ if status != 0:
+ complete = True
+ return (_LPProblem(c, A_ub, b_ub, A_eq, b_eq, bounds, x0),
+ c0, x, revstack, complete, status, message)
+
+
+def _parse_linprog(lp, options, meth):
+ """
+ Parse the provided linear programming problem
+
+ ``_parse_linprog`` employs two main steps ``_check_sparse_inputs`` and
+ ``_clean_inputs``. ``_check_sparse_inputs`` checks for sparsity in the
+ provided constraints (``A_ub`` and ``A_eq) and if these match the provided
+ sparsity optional values.
+
+ ``_clean inputs`` checks of the provided inputs. If no violations are
+ identified the objective vector, upper bound constraints, equality
+ constraints, and simple bounds are returned in the expected format.
+
+ Parameters
+ ----------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : various valid formats, optional
+ The bounds of ``x``, as ``min`` and ``max`` pairs.
+ If bounds are specified for all N variables separately, valid formats are:
+ * a 2D array (2 x N or N x 2);
+ * a sequence of N sequences, each with 2 values.
+ If all variables have the same bounds, a single pair of values can
+ be specified. Valid formats are:
+ * a sequence with 2 scalar values;
+ * a sequence with a single element containing 2 scalar values.
+ If all variables have a lower bound of 0 and no upper bound, the bounds
+ parameter can be omitted (or given as None).
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ options : dict
+ A dictionary of solver options. All methods accept the following
+ generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ Set to True to print convergence messages.
+
+ For method-specific options, see :func:`show_options('linprog')`.
+
+ Returns
+ -------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, as ``min`` and ``max`` pairs, one for each of the N
+ elements of ``x``. The N x 2 array contains lower bounds in the first
+ column and upper bounds in the 2nd. Unbounded variables have lower
+ bound -np.inf and/or upper bound np.inf.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ options : dict, optional
+ A dictionary of solver options. All methods accept the following
+ generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ Set to True to print convergence messages.
+
+ For method-specific options, see :func:`show_options('linprog')`.
+
+ """
+ if options is None:
+ options = {}
+
+ solver_options = {k: v for k, v in options.items()}
+ solver_options, A_ub, A_eq = _check_sparse_inputs(solver_options, meth,
+ lp.A_ub, lp.A_eq)
+ # Convert lists to numpy arrays, etc...
+ lp = _clean_inputs(lp._replace(A_ub=A_ub, A_eq=A_eq))
+ return lp, solver_options
+
+
+def _get_Abc(lp, c0):
+ """
+ Given a linear programming problem of the form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A_ub @ x <= b_ub
+ A_eq @ x == b_eq
+ lb <= x <= ub
+
+ where ``lb = 0`` and ``ub = None`` unless set in ``bounds``.
+
+ Return the problem in standard form:
+
+ Minimize::
+
+ c @ x
+
+ Subject to::
+
+ A @ x == b
+ x >= 0
+
+ by adding slack variables and making variable substitutions as necessary.
+
+ Parameters
+ ----------
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, lower bounds in the 1st column, upper
+ bounds in the 2nd column. The bounds are possibly tightened
+ by the presolve procedure.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables.
+
+ Returns
+ -------
+ A : 2-D array
+ 2-D array such that ``A`` @ ``x``, gives the values of the equality
+ constraints at ``x``.
+ b : 1-D array
+ 1-D array of values representing the RHS of each equality constraint
+ (row) in A (for standard form problem).
+ c : 1-D array
+ Coefficients of the linear objective function to be minimized (for
+ standard form problem).
+ c0 : float
+ Constant term in objective function due to fixed (and eliminated)
+ variables.
+ x0 : 1-D array
+ Starting values of the independent variables, which will be refined by
+ the optimization algorithm
+
+ References
+ ----------
+ .. [9] Bertsimas, Dimitris, and J. Tsitsiklis. "Introduction to linear
+ programming." Athena Scientific 1 (1997): 997.
+
+ """
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = lp
+
+ if sps.issparse(A_eq):
+ sparse = True
+ A_eq = sps.csr_array(A_eq)
+ A_ub = sps.csr_array(A_ub)
+
+ def hstack(blocks):
+ return sps.hstack(blocks, format="csr")
+
+ def vstack(blocks):
+ return sps.vstack(blocks, format="csr")
+
+ zeros = sps.csr_array
+ eye = sps.eye_array
+ else:
+ sparse = False
+ hstack = np.hstack
+ vstack = np.vstack
+ zeros = np.zeros
+ eye = np.eye
+
+ # Variables lbs and ubs (see below) may be changed, which feeds back into
+ # bounds, so copy.
+ bounds = np.array(bounds, copy=True)
+
+ # modify problem such that all variables have only non-negativity bounds
+ lbs = bounds[:, 0]
+ ubs = bounds[:, 1]
+ m_ub, n_ub = A_ub.shape
+
+ lb_none = np.equal(lbs, -np.inf)
+ ub_none = np.equal(ubs, np.inf)
+ lb_some = np.logical_not(lb_none)
+ ub_some = np.logical_not(ub_none)
+
+ # unbounded below: substitute xi = -xi' (unbounded above)
+ # if -inf <= xi <= ub, then -ub <= -xi <= inf, so swap and invert bounds
+ l_nolb_someub = np.logical_and(lb_none, ub_some)
+ i_nolb = np.nonzero(l_nolb_someub)[0]
+ lbs[l_nolb_someub], ubs[l_nolb_someub] = (
+ -ubs[l_nolb_someub], -lbs[l_nolb_someub])
+ lb_none = np.equal(lbs, -np.inf)
+ ub_none = np.equal(ubs, np.inf)
+ lb_some = np.logical_not(lb_none)
+ ub_some = np.logical_not(ub_none)
+ c[i_nolb] *= -1
+ if x0 is not None:
+ x0[i_nolb] *= -1
+ if len(i_nolb) > 0:
+ if A_ub.shape[0] > 0: # sometimes needed for sparse arrays... weird
+ A_ub[:, i_nolb] *= -1
+ if A_eq.shape[0] > 0:
+ A_eq[:, i_nolb] *= -1
+
+ # upper bound: add inequality constraint
+ i_newub, = ub_some.nonzero()
+ ub_newub = ubs[ub_some]
+ n_bounds = len(i_newub)
+ if n_bounds > 0:
+ shape = (n_bounds, A_ub.shape[1])
+ if sparse:
+ idxs = (np.arange(n_bounds), i_newub)
+ A_ub = vstack((A_ub, sps.csr_array((np.ones(n_bounds), idxs),
+ shape=shape)))
+ else:
+ A_ub = vstack((A_ub, np.zeros(shape)))
+ A_ub[np.arange(m_ub, A_ub.shape[0]), i_newub] = 1
+ b_ub = np.concatenate((b_ub, np.zeros(n_bounds)))
+ b_ub[m_ub:] = ub_newub
+
+ A1 = vstack((A_ub, A_eq))
+ b = np.concatenate((b_ub, b_eq))
+ c = np.concatenate((c, np.zeros((A_ub.shape[0],))))
+ if x0 is not None:
+ x0 = np.concatenate((x0, np.zeros((A_ub.shape[0],))))
+ # unbounded: substitute xi = xi+ + xi-
+ l_free = np.logical_and(lb_none, ub_none)
+ i_free = np.nonzero(l_free)[0]
+ n_free = len(i_free)
+ c = np.concatenate((c, np.zeros(n_free)))
+ if x0 is not None:
+ x0 = np.concatenate((x0, np.zeros(n_free)))
+ A1 = hstack((A1[:, :n_ub], -A1[:, i_free]))
+ c[n_ub:n_ub+n_free] = -c[i_free]
+ if x0 is not None:
+ i_free_neg = x0[i_free] < 0
+ x0[np.arange(n_ub, A1.shape[1])[i_free_neg]] = -x0[i_free[i_free_neg]]
+ x0[i_free[i_free_neg]] = 0
+
+ # add slack variables
+ A2 = vstack([eye(A_ub.shape[0]), zeros((A_eq.shape[0], A_ub.shape[0]))])
+
+ A = hstack([A1, A2])
+
+ # lower bound: substitute xi = xi' + lb
+ # now there is a constant term in objective
+ i_shift = np.nonzero(lb_some)[0]
+ lb_shift = lbs[lb_some].astype(float)
+ c0 += np.sum(lb_shift * c[i_shift])
+ if sparse:
+ A = A.tocsc()
+ b -= (A[:, i_shift] @ sps.diags_array(lb_shift)).sum(axis=1)
+ else:
+ b -= (A[:, i_shift] * lb_shift).sum(axis=1)
+ if x0 is not None:
+ x0[i_shift] -= lb_shift
+
+ return A, b, c, c0, x0
+
+
+def _round_to_power_of_two(x):
+ """
+ Round elements of the array to the nearest power of two.
+ """
+ return 2**np.around(np.log2(x))
+
+
+def _autoscale(A, b, c, x0):
+ """
+ Scales the problem according to equilibration from [12].
+ Also normalizes the right hand side vector by its maximum element.
+ """
+ m, n = A.shape
+
+ C = 1
+ R = 1
+
+ if A.size > 0:
+
+ R = np.max(np.abs(A), axis=1)
+ if sps.issparse(A):
+ R = R.toarray().flatten()
+ R[R == 0] = 1
+ R = 1/_round_to_power_of_two(R)
+ A = sps.diags_array(R)@A if sps.issparse(A) else A*R.reshape(m, 1)
+ b = b*R
+
+ C = np.max(np.abs(A), axis=0)
+ if sps.issparse(A):
+ C = C.toarray().flatten()
+ C[C == 0] = 1
+ C = 1/_round_to_power_of_two(C)
+ A = A@sps.diags_array(C) if sps.issparse(A) else A*C
+ c = c*C
+
+ b_scale = np.max(np.abs(b)) if b.size > 0 else 1
+ if b_scale == 0:
+ b_scale = 1.
+ b = b/b_scale
+
+ if x0 is not None:
+ x0 = x0/b_scale*(1/C)
+ return A, b, c, x0, C, b_scale
+
+
+def _unscale(x, C, b_scale):
+ """
+ Converts solution to _autoscale problem -> solution to original problem.
+ """
+
+ try:
+ n = len(C)
+ # fails if sparse or scalar; that's OK.
+ # this is only needed for original simplex (never sparse)
+ except TypeError:
+ n = len(x)
+
+ return x[:n]*b_scale*C
+
+
+def _display_summary(message, status, fun, iteration):
+ """
+ Print the termination summary of the linear program
+
+ Parameters
+ ----------
+ message : str
+ A string descriptor of the exit status of the optimization.
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ fun : float
+ Value of the objective function.
+ iteration : iteration
+ The number of iterations performed.
+ """
+ print(message)
+ if status in (0, 1):
+ print(f" Current function value: {fun: <12.6f}")
+ print(f" Iterations: {iteration:d}")
+
+
+def _postsolve(x, postsolve_args, complete=False):
+ """
+ Given solution x to presolved, standard form linear program x, add
+ fixed variables back into the problem and undo the variable substitutions
+ to get solution to original linear program. Also, calculate the objective
+ function value, slack in original upper bound constraints, and residuals
+ in original equality constraints.
+
+ Parameters
+ ----------
+ x : 1-D array
+ Solution vector to the standard-form problem.
+ postsolve_args : tuple
+ Data needed by _postsolve to convert the solution to the standard-form
+ problem into the solution to the original problem, including:
+
+ lp : A `scipy.optimize._linprog_util._LPProblem` consisting of the following fields:
+
+ c : 1D array
+ The coefficients of the linear objective function to be minimized.
+ A_ub : 2D array, optional
+ The inequality constraint matrix. Each row of ``A_ub`` specifies the
+ coefficients of a linear inequality constraint on ``x``.
+ b_ub : 1D array, optional
+ The inequality constraint vector. Each element represents an
+ upper bound on the corresponding value of ``A_ub @ x``.
+ A_eq : 2D array, optional
+ The equality constraint matrix. Each row of ``A_eq`` specifies the
+ coefficients of a linear equality constraint on ``x``.
+ b_eq : 1D array, optional
+ The equality constraint vector. Each element of ``A_eq @ x`` must equal
+ the corresponding element of ``b_eq``.
+ bounds : 2D array
+ The bounds of ``x``, lower bounds in the 1st column, upper
+ bounds in the 2nd column. The bounds are possibly tightened
+ by the presolve procedure.
+ x0 : 1D array, optional
+ Guess values of the decision variables, which will be refined by
+ the optimization algorithm. This argument is currently used only by the
+ 'revised simplex' method, and can only be used if `x0` represents a
+ basic feasible solution.
+
+ revstack: list of functions
+ the functions in the list reverse the operations of _presolve()
+ the function signature is x_org = f(x_mod), where x_mod is the result
+ of a presolve step and x_org the value at the start of the step
+ complete : bool
+ Whether the solution is was determined in presolve (``True`` if so)
+
+ Returns
+ -------
+ x : 1-D array
+ Solution vector to original linear programming problem
+ fun: float
+ optimal objective value for original problem
+ slack : 1-D array
+ The (non-negative) slack in the upper bound constraints, that is,
+ ``b_ub - A_ub @ x``
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints, that is,
+ ``b - A_eq @ x``
+ """
+ # note that all the inputs are the ORIGINAL, unmodified versions
+ # no rows, columns have been removed
+
+ c, A_ub, b_ub, A_eq, b_eq, bounds, x0, integrality = postsolve_args[0]
+ revstack, C, b_scale = postsolve_args[1:]
+
+ x = _unscale(x, C, b_scale)
+
+ # Undo variable substitutions of _get_Abc()
+ # if "complete", problem was solved in presolve; don't do anything here
+ n_x = bounds.shape[0]
+ if not complete and bounds is not None: # bounds are never none, probably
+ n_unbounded = 0
+ for i, bi in enumerate(bounds):
+ lbi = bi[0]
+ ubi = bi[1]
+ if lbi == -np.inf and ubi == np.inf:
+ n_unbounded += 1
+ x[i] = x[i] - x[n_x + n_unbounded - 1]
+ else:
+ if lbi == -np.inf:
+ x[i] = ubi - x[i]
+ else:
+ x[i] += lbi
+ # all the rest of the variables were artificial
+ x = x[:n_x]
+
+ # If there were variables removed from the problem, add them back into the
+ # solution vector
+ # Apply the functions in revstack (reverse direction)
+ for rev in reversed(revstack):
+ x = rev(x)
+
+ fun = x.dot(c)
+ with np.errstate(invalid="ignore"):
+ slack = b_ub - A_ub.dot(x) # report slack for ORIGINAL UB constraints
+ # report residuals of ORIGINAL EQ constraints
+ con = b_eq - A_eq.dot(x)
+
+ return x, fun, slack, con
+
+
+def _check_result(x, fun, status, slack, con, bounds, tol, message,
+ integrality):
+ """
+ Check the validity of the provided solution.
+
+ A valid (optimal) solution satisfies all bounds, all slack variables are
+ negative and all equality constraint residuals are strictly non-zero.
+ Further, the lower-bounds, upper-bounds, slack and residuals contain
+ no nan values.
+
+ Parameters
+ ----------
+ x : 1-D array
+ Solution vector to original linear programming problem
+ fun: float
+ optimal objective value for original problem
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ slack : 1-D array
+ The (non-negative) slack in the upper bound constraints, that is,
+ ``b_ub - A_ub @ x``
+ con : 1-D array
+ The (nominally zero) residuals of the equality constraints, that is,
+ ``b - A_eq @ x``
+ bounds : 2D array
+ The bounds on the original variables ``x``
+ message : str
+ A string descriptor of the exit status of the optimization.
+ tol : float
+ Termination tolerance; see [1]_ Section 4.5.
+
+ Returns
+ -------
+ status : int
+ An integer representing the exit status of the optimization::
+
+ 0 : Optimization terminated successfully
+ 1 : Iteration limit reached
+ 2 : Problem appears to be infeasible
+ 3 : Problem appears to be unbounded
+ 4 : Serious numerical difficulties encountered
+
+ message : str
+ A string descriptor of the exit status of the optimization.
+ """
+ # Somewhat arbitrary
+ tol = np.sqrt(tol) * 10
+
+ if x is None:
+ # HiGHS does not provide x if infeasible/unbounded
+ if status == 0: # Observed with HiGHS Simplex Primal
+ status = 4
+ message = ("The solver did not provide a solution nor did it "
+ "report a failure. Please submit a bug report.")
+ return status, message
+
+ contains_nans = (
+ np.isnan(x).any()
+ or np.isnan(fun)
+ or np.isnan(slack).any()
+ or np.isnan(con).any()
+ )
+
+ if contains_nans:
+ is_feasible = False
+ else:
+ if integrality is None:
+ integrality = 0
+ valid_bounds = (x >= bounds[:, 0] - tol) & (x <= bounds[:, 1] + tol)
+ # When integrality is 2 or 3, x must be within bounds OR take value 0
+ valid_bounds |= (integrality > 1) & np.isclose(x, 0, atol=tol)
+ invalid_bounds = not np.all(valid_bounds)
+
+ invalid_slack = status != 3 and (slack < -tol).any()
+ invalid_con = status != 3 and (np.abs(con) > tol).any()
+ is_feasible = not (invalid_bounds or invalid_slack or invalid_con)
+
+ if status == 0 and not is_feasible:
+ status = 4
+ message = ("The solution does not satisfy the constraints within the "
+ "required tolerance of " + f"{tol:.2E}" + ", yet "
+ "no errors were raised and there is no certificate of "
+ "infeasibility or unboundedness. Check whether "
+ "the slack and constraint residuals are acceptable; "
+ "if not, consider enabling presolve, adjusting the "
+ "tolerance option(s), and/or using a different method. "
+ "Please consider submitting a bug report.")
+ elif status == 2 and is_feasible:
+ # Occurs if the simplex method exits after phase one with a very
+ # nearly basic feasible solution. Postsolving can make the solution
+ # basic, however, this solution is NOT optimal
+ status = 4
+ message = ("The solution is feasible, but the solver did not report "
+ "that the solution was optimal. Please try a different "
+ "method.")
+
+ return status, message
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsap.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsap.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..3b5f978414414ccde7fe9e5b67bac7abacf452f6
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsap.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._bvls.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._bvls.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._bvls.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._common.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._common.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._common.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._dogbox.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._dogbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._dogbox.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._givens_elimination.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._givens_elimination.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._givens_elimination.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._least_squares.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._least_squares.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._least_squares.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._lsq_linear.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._lsq_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._lsq_linear.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._trf.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._trf.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._trf.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._trf_linear.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._trf_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/._trf_linear.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f60adcc891304e34ac9d85d108b6a232b4bf0c93
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/__init__.py
@@ -0,0 +1,5 @@
+"""This module contains least-squares algorithms."""
+from .least_squares import least_squares
+from .lsq_linear import lsq_linear
+
+__all__ = ['least_squares', 'lsq_linear']
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/bvls.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/bvls.py
new file mode 100644
index 0000000000000000000000000000000000000000..8f34ead4a1fc4edbb3c2ab50a204aa9a3cc21cff
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/bvls.py
@@ -0,0 +1,183 @@
+"""Bounded-variable least-squares algorithm."""
+import numpy as np
+from numpy.linalg import norm, lstsq
+from scipy.optimize import OptimizeResult
+
+from .common import print_header_linear, print_iteration_linear
+
+
+def compute_kkt_optimality(g, on_bound):
+ """Compute the maximum violation of KKT conditions."""
+ g_kkt = g * on_bound
+ free_set = on_bound == 0
+ g_kkt[free_set] = np.abs(g[free_set])
+ return np.max(g_kkt)
+
+
+def bvls(A, b, x_lsq, lb, ub, tol, max_iter, verbose, rcond=None):
+ m, n = A.shape
+
+ x = x_lsq.copy()
+ on_bound = np.zeros(n)
+
+ mask = x <= lb
+ x[mask] = lb[mask]
+ on_bound[mask] = -1
+
+ mask = x >= ub
+ x[mask] = ub[mask]
+ on_bound[mask] = 1
+
+ free_set = on_bound == 0
+ active_set = ~free_set
+ free_set, = np.nonzero(free_set)
+
+ r = A.dot(x) - b
+ cost = 0.5 * np.dot(r, r)
+ initial_cost = cost
+ g = A.T.dot(r)
+
+ cost_change = None
+ step_norm = None
+ iteration = 0
+
+ if verbose == 2:
+ print_header_linear()
+
+ # This is the initialization loop. The requirement is that the
+ # least-squares solution on free variables is feasible before BVLS starts.
+ # One possible initialization is to set all variables to lower or upper
+ # bounds, but many iterations may be required from this state later on.
+ # The implemented ad-hoc procedure which intuitively should give a better
+ # initial state: find the least-squares solution on current free variables,
+ # if its feasible then stop, otherwise, set violating variables to
+ # corresponding bounds and continue on the reduced set of free variables.
+
+ while free_set.size > 0:
+ if verbose == 2:
+ optimality = compute_kkt_optimality(g, on_bound)
+ print_iteration_linear(iteration, cost, cost_change, step_norm,
+ optimality)
+
+ iteration += 1
+ x_free_old = x[free_set].copy()
+
+ A_free = A[:, free_set]
+ b_free = b - A.dot(x * active_set)
+ z = lstsq(A_free, b_free, rcond=rcond)[0]
+
+ lbv = z < lb[free_set]
+ ubv = z > ub[free_set]
+ v = lbv | ubv
+
+ if np.any(lbv):
+ ind = free_set[lbv]
+ x[ind] = lb[ind]
+ active_set[ind] = True
+ on_bound[ind] = -1
+
+ if np.any(ubv):
+ ind = free_set[ubv]
+ x[ind] = ub[ind]
+ active_set[ind] = True
+ on_bound[ind] = 1
+
+ ind = free_set[~v]
+ x[ind] = z[~v]
+
+ r = A.dot(x) - b
+ cost_new = 0.5 * np.dot(r, r)
+ cost_change = cost - cost_new
+ cost = cost_new
+ g = A.T.dot(r)
+ step_norm = norm(x[free_set] - x_free_old)
+
+ if np.any(v):
+ free_set = free_set[~v]
+ else:
+ break
+
+ if max_iter is None:
+ max_iter = n
+ max_iter += iteration
+
+ termination_status = None
+
+ # Main BVLS loop.
+
+ optimality = compute_kkt_optimality(g, on_bound)
+ for iteration in range(iteration, max_iter): # BVLS Loop A
+ if verbose == 2:
+ print_iteration_linear(iteration, cost, cost_change,
+ step_norm, optimality)
+
+ if optimality < tol:
+ termination_status = 1
+
+ if termination_status is not None:
+ break
+
+ move_to_free = np.argmax(g * on_bound)
+ on_bound[move_to_free] = 0
+
+ while True: # BVLS Loop B
+
+ free_set = on_bound == 0
+ active_set = ~free_set
+ free_set, = np.nonzero(free_set)
+
+ x_free = x[free_set]
+ x_free_old = x_free.copy()
+ lb_free = lb[free_set]
+ ub_free = ub[free_set]
+
+ A_free = A[:, free_set]
+ b_free = b - A.dot(x * active_set)
+ z = lstsq(A_free, b_free, rcond=rcond)[0]
+
+ lbv, = np.nonzero(z < lb_free)
+ ubv, = np.nonzero(z > ub_free)
+ v = np.hstack((lbv, ubv))
+
+ if v.size > 0:
+ alphas = np.hstack((
+ lb_free[lbv] - x_free[lbv],
+ ub_free[ubv] - x_free[ubv])) / (z[v] - x_free[v])
+
+ i = np.argmin(alphas)
+ i_free = v[i]
+ alpha = alphas[i]
+
+ x_free *= 1 - alpha
+ x_free += alpha * z
+ x[free_set] = x_free
+
+ if i < lbv.size:
+ on_bound[free_set[i_free]] = -1
+ else:
+ on_bound[free_set[i_free]] = 1
+ else:
+ x_free = z
+ x[free_set] = x_free
+ break
+
+ step_norm = norm(x_free - x_free_old)
+
+ r = A.dot(x) - b
+ cost_new = 0.5 * np.dot(r, r)
+ cost_change = cost - cost_new
+
+ if cost_change < tol * cost:
+ termination_status = 2
+ cost = cost_new
+
+ g = A.T.dot(r)
+ optimality = compute_kkt_optimality(g, on_bound)
+
+ if termination_status is None:
+ termination_status = 0
+
+ return OptimizeResult(
+ x=x, fun=r, cost=cost, optimality=optimality, active_mask=on_bound,
+ nit=iteration + 1, status=termination_status,
+ initial_cost=initial_cost)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/common.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/common.py
new file mode 100644
index 0000000000000000000000000000000000000000..2ac5112c61431dac556b5e62d5aa8e699069771c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/common.py
@@ -0,0 +1,731 @@
+"""Functions used by least-squares algorithms."""
+from math import copysign
+
+import numpy as np
+from numpy.linalg import norm
+
+from scipy.linalg import cho_factor, cho_solve, LinAlgError
+from scipy.sparse.linalg import LinearOperator, aslinearoperator
+from scipy._lib._sparse import issparse
+
+
+EPS = np.finfo(float).eps
+
+
+# Functions related to a trust-region problem.
+
+
+def intersect_trust_region(x, s, Delta):
+ """Find the intersection of a line with the boundary of a trust region.
+
+ This function solves the quadratic equation with respect to t
+ ||(x + s*t)||**2 = Delta**2.
+
+ Returns
+ -------
+ t_neg, t_pos : tuple of float
+ Negative and positive roots.
+
+ Raises
+ ------
+ ValueError
+ If `s` is zero or `x` is not within the trust region.
+ """
+ a = np.dot(s, s)
+ if a == 0:
+ raise ValueError("`s` is zero.")
+
+ b = np.dot(x, s)
+
+ c = np.dot(x, x) - Delta**2
+ if c > 0:
+ raise ValueError("`x` is not within the trust region.")
+
+ d = np.sqrt(b*b - a*c) # Root from one fourth of the discriminant.
+
+ # Computations below avoid loss of significance, see "Numerical Recipes".
+ q = -(b + copysign(d, b))
+ t1 = q / a
+ t2 = c / q
+
+ if t1 < t2:
+ return t1, t2
+ else:
+ return t2, t1
+
+
+def solve_lsq_trust_region(n, m, uf, s, V, Delta, initial_alpha=None,
+ rtol=0.01, max_iter=10):
+ """Solve a trust-region problem arising in least-squares minimization.
+
+ This function implements a method described by J. J. More [1]_ and used
+ in MINPACK, but it relies on a single SVD of Jacobian instead of series
+ of Cholesky decompositions. Before running this function, compute:
+ ``U, s, VT = svd(J, full_matrices=False)``.
+
+ Parameters
+ ----------
+ n : int
+ Number of variables.
+ m : int
+ Number of residuals.
+ uf : ndarray
+ Computed as U.T.dot(f).
+ s : ndarray
+ Singular values of J.
+ V : ndarray
+ Transpose of VT.
+ Delta : float
+ Radius of a trust region.
+ initial_alpha : float, optional
+ Initial guess for alpha, which might be available from a previous
+ iteration. If None, determined automatically.
+ rtol : float, optional
+ Stopping tolerance for the root-finding procedure. Namely, the
+ solution ``p`` will satisfy ``abs(norm(p) - Delta) < rtol * Delta``.
+ max_iter : int, optional
+ Maximum allowed number of iterations for the root-finding procedure.
+
+ Returns
+ -------
+ p : ndarray, shape (n,)
+ Found solution of a trust-region problem.
+ alpha : float
+ Positive value such that (J.T*J + alpha*I)*p = -J.T*f.
+ Sometimes called Levenberg-Marquardt parameter.
+ n_iter : int
+ Number of iterations made by root-finding procedure. Zero means
+ that Gauss-Newton step was selected as the solution.
+
+ References
+ ----------
+ .. [1] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation
+ and Theory," Numerical Analysis, ed. G. A. Watson, Lecture Notes
+ in Mathematics 630, Springer Verlag, pp. 105-116, 1977.
+ """
+ def phi_and_derivative(alpha, suf, s, Delta):
+ """Function of which to find zero.
+
+ It is defined as "norm of regularized (by alpha) least-squares
+ solution minus `Delta`". Refer to [1]_.
+ """
+ denom = s**2 + alpha
+ p_norm = norm(suf / denom)
+ phi = p_norm - Delta
+ phi_prime = -np.sum(suf ** 2 / denom**3) / p_norm
+ return phi, phi_prime
+
+ suf = s * uf
+
+ # Check if J has full rank and try Gauss-Newton step.
+ if m >= n:
+ threshold = EPS * m * s[0]
+ full_rank = s[-1] > threshold
+ else:
+ full_rank = False
+
+ if full_rank:
+ p = -V.dot(uf / s)
+ if norm(p) <= Delta:
+ return p, 0.0, 0
+
+ alpha_upper = norm(suf) / Delta
+
+ if full_rank:
+ phi, phi_prime = phi_and_derivative(0.0, suf, s, Delta)
+ alpha_lower = -phi / phi_prime
+ else:
+ alpha_lower = 0.0
+
+ if initial_alpha is None or not full_rank and initial_alpha == 0:
+ alpha = max(0.001 * alpha_upper, (alpha_lower * alpha_upper)**0.5)
+ else:
+ alpha = initial_alpha
+
+ for it in range(max_iter):
+ if alpha < alpha_lower or alpha > alpha_upper:
+ alpha = max(0.001 * alpha_upper, (alpha_lower * alpha_upper)**0.5)
+
+ phi, phi_prime = phi_and_derivative(alpha, suf, s, Delta)
+
+ if phi < 0:
+ alpha_upper = alpha
+
+ ratio = phi / phi_prime
+ alpha_lower = max(alpha_lower, alpha - ratio)
+ alpha -= (phi + Delta) * ratio / Delta
+
+ if np.abs(phi) < rtol * Delta:
+ break
+
+ p = -V.dot(suf / (s**2 + alpha))
+
+ # Make the norm of p equal to Delta, p is changed only slightly during
+ # this. It is done to prevent p lie outside the trust region (which can
+ # cause problems later).
+ p *= Delta / norm(p)
+
+ return p, alpha, it + 1
+
+
+def solve_trust_region_2d(B, g, Delta):
+ """Solve a general trust-region problem in 2 dimensions.
+
+ The problem is reformulated as a 4th order algebraic equation,
+ the solution of which is found by numpy.roots.
+
+ Parameters
+ ----------
+ B : ndarray, shape (2, 2)
+ Symmetric matrix, defines a quadratic term of the function.
+ g : ndarray, shape (2,)
+ Defines a linear term of the function.
+ Delta : float
+ Radius of a trust region.
+
+ Returns
+ -------
+ p : ndarray, shape (2,)
+ Found solution.
+ newton_step : bool
+ Whether the returned solution is the Newton step which lies within
+ the trust region.
+ """
+ try:
+ R, lower = cho_factor(B)
+ p = -cho_solve((R, lower), g)
+ if np.dot(p, p) <= Delta**2:
+ return p, True
+ except LinAlgError:
+ pass
+
+ a = B[0, 0] * Delta**2
+ b = B[0, 1] * Delta**2
+ c = B[1, 1] * Delta**2
+
+ d = g[0] * Delta
+ f = g[1] * Delta
+
+ coeffs = np.array(
+ [-b + d, 2 * (a - c + f), 6 * b, 2 * (-a + c + f), -b - d])
+ t = np.roots(coeffs) # Can handle leading zeros.
+ t = np.real(t[np.isreal(t)])
+
+ p = Delta * np.vstack((2 * t / (1 + t**2), (1 - t**2) / (1 + t**2)))
+ value = 0.5 * np.sum(p * B.dot(p), axis=0) + np.dot(g, p)
+ i = np.argmin(value)
+ p = p[:, i]
+
+ return p, False
+
+
+def update_tr_radius(Delta, actual_reduction, predicted_reduction,
+ step_norm, bound_hit):
+ """Update the radius of a trust region based on the cost reduction.
+
+ Returns
+ -------
+ Delta : float
+ New radius.
+ ratio : float
+ Ratio between actual and predicted reductions.
+ """
+ if predicted_reduction > 0:
+ ratio = actual_reduction / predicted_reduction
+ elif predicted_reduction == actual_reduction == 0:
+ ratio = 1
+ else:
+ ratio = 0
+
+ if ratio < 0.25:
+ Delta = 0.25 * step_norm
+ elif ratio > 0.75 and bound_hit:
+ Delta *= 2.0
+
+ return Delta, ratio
+
+
+# Construction and minimization of quadratic functions.
+
+
+def build_quadratic_1d(J, g, s, diag=None, s0=None):
+ """Parameterize a multivariate quadratic function along a line.
+
+ The resulting univariate quadratic function is given as follows::
+
+ f(t) = 0.5 * (s0 + s*t).T * (J.T*J + diag) * (s0 + s*t) +
+ g.T * (s0 + s*t)
+
+ Parameters
+ ----------
+ J : ndarray, sparse array or LinearOperator shape (m, n)
+ Jacobian matrix, affects the quadratic term.
+ g : ndarray, shape (n,)
+ Gradient, defines the linear term.
+ s : ndarray, shape (n,)
+ Direction vector of a line.
+ diag : None or ndarray with shape (n,), optional
+ Addition diagonal part, affects the quadratic term.
+ If None, assumed to be 0.
+ s0 : None or ndarray with shape (n,), optional
+ Initial point. If None, assumed to be 0.
+
+ Returns
+ -------
+ a : float
+ Coefficient for t**2.
+ b : float
+ Coefficient for t.
+ c : float
+ Free term. Returned only if `s0` is provided.
+ """
+ v = J.dot(s)
+ a = np.dot(v, v)
+ if diag is not None:
+ a += np.dot(s * diag, s)
+ a *= 0.5
+
+ b = np.dot(g, s)
+
+ if s0 is not None:
+ u = J.dot(s0)
+ b += np.dot(u, v)
+ c = 0.5 * np.dot(u, u) + np.dot(g, s0)
+ if diag is not None:
+ b += np.dot(s0 * diag, s)
+ c += 0.5 * np.dot(s0 * diag, s0)
+ return a, b, c
+ else:
+ return a, b
+
+
+def minimize_quadratic_1d(a, b, lb, ub, c=0):
+ """Minimize a 1-D quadratic function subject to bounds.
+
+ The free term `c` is 0 by default. Bounds must be finite.
+
+ Returns
+ -------
+ t : float
+ Minimum point.
+ y : float
+ Minimum value.
+ """
+ t = [lb, ub]
+ if a != 0:
+ extremum = -0.5 * b / a
+ if lb < extremum < ub:
+ t.append(extremum)
+ t = np.asarray(t)
+ y = t * (a * t + b) + c
+ min_index = np.argmin(y)
+ return t[min_index], y[min_index]
+
+
+def evaluate_quadratic(J, g, s, diag=None):
+ """Compute values of a quadratic function arising in least squares.
+
+ The function is 0.5 * s.T * (J.T * J + diag) * s + g.T * s.
+
+ Parameters
+ ----------
+ J : ndarray, sparse array or LinearOperator, shape (m, n)
+ Jacobian matrix, affects the quadratic term.
+ g : ndarray, shape (n,)
+ Gradient, defines the linear term.
+ s : ndarray, shape (k, n) or (n,)
+ Array containing steps as rows.
+ diag : ndarray, shape (n,), optional
+ Addition diagonal part, affects the quadratic term.
+ If None, assumed to be 0.
+
+ Returns
+ -------
+ values : ndarray with shape (k,) or float
+ Values of the function. If `s` was 2-D, then ndarray is
+ returned, otherwise, float is returned.
+ """
+ if s.ndim == 1:
+ Js = J.dot(s)
+ q = np.dot(Js, Js)
+ if diag is not None:
+ q += np.dot(s * diag, s)
+ else:
+ Js = J.dot(s.T)
+ q = np.sum(Js**2, axis=0)
+ if diag is not None:
+ q += np.sum(diag * s**2, axis=1)
+
+ l = np.dot(s, g)
+
+ return 0.5 * q + l
+
+
+# Utility functions to work with bound constraints.
+
+
+def in_bounds(x, lb, ub):
+ """Check if a point lies within bounds."""
+ return np.all((x >= lb) & (x <= ub))
+
+
+def step_size_to_bound(x, s, lb, ub):
+ """Compute a min_step size required to reach a bound.
+
+ The function computes a positive scalar t, such that x + s * t is on
+ the bound.
+
+ Returns
+ -------
+ step : float
+ Computed step. Non-negative value.
+ hits : ndarray of int with shape of x
+ Each element indicates whether a corresponding variable reaches the
+ bound:
+
+ * 0 - the bound was not hit.
+ * -1 - the lower bound was hit.
+ * 1 - the upper bound was hit.
+ """
+ non_zero = np.nonzero(s)
+ s_non_zero = s[non_zero]
+ steps = np.empty_like(x)
+ steps.fill(np.inf)
+ with np.errstate(over='ignore'):
+ steps[non_zero] = np.maximum((lb - x)[non_zero] / s_non_zero,
+ (ub - x)[non_zero] / s_non_zero)
+ min_step = np.min(steps)
+ return min_step, np.equal(steps, min_step) * np.sign(s).astype(int)
+
+
+def find_active_constraints(x, lb, ub, rtol=1e-10):
+ """Determine which constraints are active in a given point.
+
+ The threshold is computed using `rtol` and the absolute value of the
+ closest bound.
+
+ Returns
+ -------
+ active : ndarray of int with shape of x
+ Each component shows whether the corresponding constraint is active:
+
+ * 0 - a constraint is not active.
+ * -1 - a lower bound is active.
+ * 1 - a upper bound is active.
+ """
+ active = np.zeros_like(x, dtype=int)
+
+ if rtol == 0:
+ active[x <= lb] = -1
+ active[x >= ub] = 1
+ return active
+
+ lower_dist = x - lb
+ upper_dist = ub - x
+
+ lower_threshold = rtol * np.maximum(1, np.abs(lb))
+ upper_threshold = rtol * np.maximum(1, np.abs(ub))
+
+ lower_active = (np.isfinite(lb) &
+ (lower_dist <= np.minimum(upper_dist, lower_threshold)))
+ active[lower_active] = -1
+
+ upper_active = (np.isfinite(ub) &
+ (upper_dist <= np.minimum(lower_dist, upper_threshold)))
+ active[upper_active] = 1
+
+ return active
+
+
+def make_strictly_feasible(x, lb, ub, rstep=1e-10):
+ """Shift a point to the interior of a feasible region.
+
+ Each element of the returned vector is at least at a relative distance
+ `rstep` from the closest bound. If ``rstep=0`` then `np.nextafter` is used.
+ """
+ x_new = x.copy()
+
+ active = find_active_constraints(x, lb, ub, rstep)
+ lower_mask = np.equal(active, -1)
+ upper_mask = np.equal(active, 1)
+
+ if rstep == 0:
+ x_new[lower_mask] = np.nextafter(lb[lower_mask], ub[lower_mask])
+ x_new[upper_mask] = np.nextafter(ub[upper_mask], lb[upper_mask])
+ else:
+ x_new[lower_mask] = (lb[lower_mask] +
+ rstep * np.maximum(1, np.abs(lb[lower_mask])))
+ x_new[upper_mask] = (ub[upper_mask] -
+ rstep * np.maximum(1, np.abs(ub[upper_mask])))
+
+ tight_bounds = (x_new < lb) | (x_new > ub)
+ x_new[tight_bounds] = 0.5 * (lb[tight_bounds] + ub[tight_bounds])
+
+ return x_new
+
+
+def CL_scaling_vector(x, g, lb, ub):
+ """Compute Coleman-Li scaling vector and its derivatives.
+
+ Components of a vector v are defined as follows::
+
+ | ub[i] - x[i], if g[i] < 0 and ub[i] < np.inf
+ v[i] = | x[i] - lb[i], if g[i] > 0 and lb[i] > -np.inf
+ | 1, otherwise
+
+ According to this definition v[i] >= 0 for all i. It differs from the
+ definition in paper [1]_ (eq. (2.2)), where the absolute value of v is
+ used. Both definitions are equivalent down the line.
+ Derivatives of v with respect to x take value 1, -1 or 0 depending on a
+ case.
+
+ Returns
+ -------
+ v : ndarray with shape of x
+ Scaling vector.
+ dv : ndarray with shape of x
+ Derivatives of v[i] with respect to x[i], diagonal elements of v's
+ Jacobian.
+
+ References
+ ----------
+ .. [1] M.A. Branch, T.F. Coleman, and Y. Li, "A Subspace, Interior,
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
+ Minimization Problems," SIAM Journal on Scientific Computing,
+ Vol. 21, Number 1, pp 1-23, 1999.
+ """
+ v = np.ones_like(x)
+ dv = np.zeros_like(x)
+
+ mask = (g < 0) & np.isfinite(ub)
+ v[mask] = ub[mask] - x[mask]
+ dv[mask] = -1
+
+ mask = (g > 0) & np.isfinite(lb)
+ v[mask] = x[mask] - lb[mask]
+ dv[mask] = 1
+
+ return v, dv
+
+
+def reflective_transformation(y, lb, ub):
+ """Compute reflective transformation and its gradient."""
+ if in_bounds(y, lb, ub):
+ return y, np.ones_like(y)
+
+ lb_finite = np.isfinite(lb)
+ ub_finite = np.isfinite(ub)
+
+ x = y.copy()
+ g_negative = np.zeros_like(y, dtype=bool)
+
+ mask = lb_finite & ~ub_finite
+ x[mask] = np.maximum(y[mask], 2 * lb[mask] - y[mask])
+ g_negative[mask] = y[mask] < lb[mask]
+
+ mask = ~lb_finite & ub_finite
+ x[mask] = np.minimum(y[mask], 2 * ub[mask] - y[mask])
+ g_negative[mask] = y[mask] > ub[mask]
+
+ mask = lb_finite & ub_finite
+ d = ub - lb
+ t = np.remainder(y[mask] - lb[mask], 2 * d[mask])
+ x[mask] = lb[mask] + np.minimum(t, 2 * d[mask] - t)
+ g_negative[mask] = t > d[mask]
+
+ g = np.ones_like(y)
+ g[g_negative] = -1
+
+ return x, g
+
+
+# Functions to display algorithm's progress.
+
+
+def print_header_nonlinear():
+ print("{:^15}{:^15}{:^15}{:^15}{:^15}{:^15}"
+ .format("Iteration", "Total nfev", "Cost", "Cost reduction",
+ "Step norm", "Optimality"))
+
+
+def print_iteration_nonlinear(iteration, nfev, cost, cost_reduction,
+ step_norm, optimality):
+ if cost_reduction is None:
+ cost_reduction = " " * 15
+ else:
+ cost_reduction = f"{cost_reduction:^15.2e}"
+
+ if step_norm is None:
+ step_norm = " " * 15
+ else:
+ step_norm = f"{step_norm:^15.2e}"
+
+ print(f"{iteration:^15}{nfev:^15}{cost:^15.4e}{cost_reduction}{step_norm}{optimality:^15.2e}")
+
+
+def print_header_linear():
+ print("{:^15}{:^15}{:^15}{:^15}{:^15}"
+ .format("Iteration", "Cost", "Cost reduction", "Step norm",
+ "Optimality"))
+
+
+def print_iteration_linear(iteration, cost, cost_reduction, step_norm,
+ optimality):
+ if cost_reduction is None:
+ cost_reduction = " " * 15
+ else:
+ cost_reduction = f"{cost_reduction:^15.2e}"
+
+ if step_norm is None:
+ step_norm = " " * 15
+ else:
+ step_norm = f"{step_norm:^15.2e}"
+
+ print(f"{iteration:^15}{cost:^15.4e}{cost_reduction}{step_norm}{optimality:^15.2e}")
+
+
+# Simple helper functions.
+
+
+def compute_grad(J, f):
+ """Compute gradient of the least-squares cost function."""
+ if isinstance(J, LinearOperator):
+ return J.rmatvec(f)
+ else:
+ return J.T.dot(f)
+
+
+def compute_jac_scale(J, scale_inv_old=None):
+ """Compute variables scale based on the Jacobian matrix."""
+ if issparse(J):
+ scale_inv = np.asarray(J.power(2).sum(axis=0)).ravel()**0.5
+ else:
+ scale_inv = np.sum(J**2, axis=0)**0.5
+
+ if scale_inv_old is None:
+ scale_inv[scale_inv == 0] = 1
+ else:
+ scale_inv = np.maximum(scale_inv, scale_inv_old)
+
+ return 1 / scale_inv, scale_inv
+
+
+def left_multiplied_operator(J, d):
+ """Return diag(d) J as LinearOperator."""
+ J = aslinearoperator(J)
+
+ def matvec(x):
+ return d * J.matvec(x)
+
+ def matmat(X):
+ return d[:, np.newaxis] * J.matmat(X)
+
+ def rmatvec(x):
+ return J.rmatvec(x.ravel() * d)
+
+ return LinearOperator(J.shape, matvec=matvec, matmat=matmat,
+ rmatvec=rmatvec)
+
+
+def right_multiplied_operator(J, d):
+ """Return J diag(d) as LinearOperator."""
+ J = aslinearoperator(J)
+
+ def matvec(x):
+ return J.matvec(np.ravel(x) * d)
+
+ def matmat(X):
+ return J.matmat(X * d[:, np.newaxis])
+
+ def rmatvec(x):
+ return d * J.rmatvec(x)
+
+ return LinearOperator(J.shape, matvec=matvec, matmat=matmat,
+ rmatvec=rmatvec)
+
+
+def regularized_lsq_operator(J, diag):
+ """Return a matrix arising in regularized least squares as LinearOperator.
+
+ The matrix is
+ [ J ]
+ [ D ]
+ where D is diagonal matrix with elements from `diag`.
+ """
+ J = aslinearoperator(J)
+ m, n = J.shape
+
+ def matvec(x):
+ return np.hstack((J.matvec(x), diag * x))
+
+ def rmatvec(x):
+ x1 = x[:m]
+ x2 = x[m:]
+ return J.rmatvec(x1) + diag * x2
+
+ return LinearOperator((m + n, n), matvec=matvec, rmatvec=rmatvec)
+
+
+def right_multiply(J, d, copy=True):
+ """Compute J diag(d).
+
+ If `copy` is False, `J` is modified in place (unless being LinearOperator).
+ """
+ if copy and not isinstance(J, LinearOperator):
+ J = J.copy()
+
+ if issparse(J):
+ J.data *= d.take(J.indices, mode='clip') # scikit-learn recipe.
+ elif isinstance(J, LinearOperator):
+ J = right_multiplied_operator(J, d)
+ else:
+ J *= d
+
+ return J
+
+
+def left_multiply(J, d, copy=True):
+ """Compute diag(d) J.
+
+ If `copy` is False, `J` is modified in place (unless being LinearOperator).
+ """
+ if copy and not isinstance(J, LinearOperator):
+ J = J.copy()
+
+ if issparse(J):
+ J.data *= np.repeat(d, np.diff(J.indptr)) # scikit-learn recipe.
+ elif isinstance(J, LinearOperator):
+ J = left_multiplied_operator(J, d)
+ else:
+ J *= d[:, np.newaxis]
+
+ return J
+
+
+def check_termination(dF, F, dx_norm, x_norm, ratio, ftol, xtol):
+ """Check termination condition for nonlinear least squares."""
+ ftol_satisfied = dF < ftol * F and ratio > 0.25
+ xtol_satisfied = dx_norm < xtol * (xtol + x_norm)
+
+ if ftol_satisfied and xtol_satisfied:
+ return 4
+ elif ftol_satisfied:
+ return 2
+ elif xtol_satisfied:
+ return 3
+ else:
+ return None
+
+
+def scale_for_robust_loss_function(J, f, rho):
+ """Scale Jacobian and residuals for a robust loss function.
+
+ Arrays are modified in place.
+ """
+ J_scale = rho[1] + 2 * rho[2] * f**2
+ J_scale[J_scale < EPS] = EPS
+ J_scale **= 0.5
+
+ f *= rho[1] / J_scale
+
+ return left_multiply(J, J_scale, copy=False), f
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/dogbox.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/dogbox.py
new file mode 100644
index 0000000000000000000000000000000000000000..7694c75d491bb014ff8e9b338d37cafdf9bec8a0
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/dogbox.py
@@ -0,0 +1,345 @@
+"""
+Dogleg algorithm with rectangular trust regions for least-squares minimization.
+
+The description of the algorithm can be found in [Voglis]_. The algorithm does
+trust-region iterations, but the shape of trust regions is rectangular as
+opposed to conventional elliptical. The intersection of a trust region and
+an initial feasible region is again some rectangle. Thus, on each iteration a
+bound-constrained quadratic optimization problem is solved.
+
+A quadratic problem is solved by well-known dogleg approach, where the
+function is minimized along piecewise-linear "dogleg" path [NumOpt]_,
+Chapter 4. If Jacobian is not rank-deficient then the function is decreasing
+along this path, and optimization amounts to simply following along this
+path as long as a point stays within the bounds. A constrained Cauchy step
+(along the anti-gradient) is considered for safety in rank deficient cases,
+in this situations the convergence might be slow.
+
+If during iterations some variable hit the initial bound and the component
+of anti-gradient points outside the feasible region, then a next dogleg step
+won't make any progress. At this state such variables satisfy first-order
+optimality conditions and they are excluded before computing a next dogleg
+step.
+
+Gauss-Newton step can be computed exactly by `numpy.linalg.lstsq` (for dense
+Jacobian matrices) or by iterative procedure `scipy.sparse.linalg.lsmr` (for
+dense and sparse matrices, or Jacobian being LinearOperator). The second
+option allows to solve very large problems (up to couple of millions of
+residuals on a regular PC), provided the Jacobian matrix is sufficiently
+sparse. But note that dogbox is not very good for solving problems with
+large number of constraints, because of variables exclusion-inclusion on each
+iteration (a required number of function evaluations might be high or accuracy
+of a solution will be poor), thus its large-scale usage is probably limited
+to unconstrained problems.
+
+References
+----------
+.. [Voglis] C. Voglis and I. E. Lagaris, "A Rectangular Trust Region Dogleg
+ Approach for Unconstrained and Bound Constrained Nonlinear
+ Optimization", WSEAS International Conference on Applied
+ Mathematics, Corfu, Greece, 2004.
+.. [NumOpt] J. Nocedal and S. J. Wright, "Numerical optimization, 2nd edition".
+"""
+import numpy as np
+from numpy.linalg import lstsq, norm
+
+from scipy.sparse.linalg import LinearOperator, aslinearoperator, lsmr
+from scipy.optimize import OptimizeResult
+from scipy._lib._util import _call_callback_maybe_halt
+
+
+from .common import (
+ step_size_to_bound, in_bounds, update_tr_radius, evaluate_quadratic,
+ build_quadratic_1d, minimize_quadratic_1d, compute_grad,
+ compute_jac_scale, check_termination, scale_for_robust_loss_function,
+ print_header_nonlinear, print_iteration_nonlinear)
+
+
+def lsmr_operator(Jop, d, active_set):
+ """Compute LinearOperator to use in LSMR by dogbox algorithm.
+
+ `active_set` mask is used to excluded active variables from computations
+ of matrix-vector products.
+ """
+ m, n = Jop.shape
+
+ def matvec(x):
+ x_free = x.ravel().copy()
+ x_free[active_set] = 0
+ return Jop.matvec(x * d)
+
+ def rmatvec(x):
+ r = d * Jop.rmatvec(x)
+ r[active_set] = 0
+ return r
+
+ return LinearOperator((m, n), matvec=matvec, rmatvec=rmatvec, dtype=float)
+
+
+def find_intersection(x, tr_bounds, lb, ub):
+ """Find intersection of trust-region bounds and initial bounds.
+
+ Returns
+ -------
+ lb_total, ub_total : ndarray with shape of x
+ Lower and upper bounds of the intersection region.
+ orig_l, orig_u : ndarray of bool with shape of x
+ True means that an original bound is taken as a corresponding bound
+ in the intersection region.
+ tr_l, tr_u : ndarray of bool with shape of x
+ True means that a trust-region bound is taken as a corresponding bound
+ in the intersection region.
+ """
+ lb_centered = lb - x
+ ub_centered = ub - x
+
+ lb_total = np.maximum(lb_centered, -tr_bounds)
+ ub_total = np.minimum(ub_centered, tr_bounds)
+
+ orig_l = np.equal(lb_total, lb_centered)
+ orig_u = np.equal(ub_total, ub_centered)
+
+ tr_l = np.equal(lb_total, -tr_bounds)
+ tr_u = np.equal(ub_total, tr_bounds)
+
+ return lb_total, ub_total, orig_l, orig_u, tr_l, tr_u
+
+
+def dogleg_step(x, newton_step, g, a, b, tr_bounds, lb, ub):
+ """Find dogleg step in a rectangular region.
+
+ Returns
+ -------
+ step : ndarray, shape (n,)
+ Computed dogleg step.
+ bound_hits : ndarray of int, shape (n,)
+ Each component shows whether a corresponding variable hits the
+ initial bound after the step is taken:
+ * 0 - a variable doesn't hit the bound.
+ * -1 - lower bound is hit.
+ * 1 - upper bound is hit.
+ tr_hit : bool
+ Whether the step hit the boundary of the trust-region.
+ """
+ lb_total, ub_total, orig_l, orig_u, tr_l, tr_u = find_intersection(
+ x, tr_bounds, lb, ub
+ )
+ bound_hits = np.zeros_like(x, dtype=int)
+
+ if in_bounds(newton_step, lb_total, ub_total):
+ return newton_step, bound_hits, False
+
+ to_bounds, _ = step_size_to_bound(np.zeros_like(x), -g, lb_total, ub_total)
+
+ # The classical dogleg algorithm would check if Cauchy step fits into
+ # the bounds, and just return it constrained version if not. But in a
+ # rectangular trust region it makes sense to try to improve constrained
+ # Cauchy step too. Thus, we don't distinguish these two cases.
+
+ cauchy_step = -minimize_quadratic_1d(a, b, 0, to_bounds)[0] * g
+
+ step_diff = newton_step - cauchy_step
+ step_size, hits = step_size_to_bound(cauchy_step, step_diff,
+ lb_total, ub_total)
+ bound_hits[(hits < 0) & orig_l] = -1
+ bound_hits[(hits > 0) & orig_u] = 1
+ tr_hit = np.any((hits < 0) & tr_l | (hits > 0) & tr_u)
+
+ return cauchy_step + step_size * step_diff, bound_hits, tr_hit
+
+
+def dogbox(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
+ loss_function, tr_solver, tr_options, verbose, callback=None):
+ f = f0
+ f_true = f.copy()
+ nfev = 1
+
+ J = J0
+ njev = 1
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ cost = 0.5 * np.sum(rho[0])
+ J, f = scale_for_robust_loss_function(J, f, rho)
+ else:
+ cost = 0.5 * np.dot(f, f)
+
+ g = compute_grad(J, f)
+
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J)
+ else:
+ scale, scale_inv = x_scale, 1 / x_scale
+
+ Delta = norm(x0 * scale_inv, ord=np.inf)
+ if Delta == 0:
+ Delta = 1.0
+
+ on_bound = np.zeros_like(x0, dtype=int)
+ on_bound[np.equal(x0, lb)] = -1
+ on_bound[np.equal(x0, ub)] = 1
+
+ x = x0
+ step = np.empty_like(x0)
+
+ if max_nfev is None:
+ max_nfev = x0.size * 100
+
+ termination_status = None
+ iteration = 0
+ step_norm = None
+ actual_reduction = None
+
+ if verbose == 2:
+ print_header_nonlinear()
+
+ while True:
+ active_set = on_bound * g < 0
+ free_set = ~active_set
+
+ g_free = g[free_set]
+ g_full = g.copy()
+ g[active_set] = 0
+
+ g_norm = norm(g, ord=np.inf)
+ if g_norm < gtol:
+ termination_status = 1
+
+ if verbose == 2:
+ print_iteration_nonlinear(iteration, nfev, cost, actual_reduction,
+ step_norm, g_norm)
+
+ if termination_status is not None or nfev == max_nfev:
+ break
+
+ x_free = x[free_set]
+ lb_free = lb[free_set]
+ ub_free = ub[free_set]
+ scale_free = scale[free_set]
+
+ # Compute (Gauss-)Newton and build quadratic model for Cauchy step.
+ if tr_solver == 'exact':
+ J_free = J[:, free_set]
+ newton_step = lstsq(J_free, -f, rcond=-1)[0]
+
+ # Coefficients for the quadratic model along the anti-gradient.
+ a, b = build_quadratic_1d(J_free, g_free, -g_free)
+ elif tr_solver == 'lsmr':
+ Jop = aslinearoperator(J)
+
+ # We compute lsmr step in scaled variables and then
+ # transform back to normal variables, if lsmr would give exact lsq
+ # solution, this would be equivalent to not doing any
+ # transformations, but from experience it's better this way.
+
+ # We pass active_set to make computations as if we selected
+ # the free subset of J columns, but without actually doing any
+ # slicing, which is expensive for sparse matrices and impossible
+ # for LinearOperator.
+
+ lsmr_op = lsmr_operator(Jop, scale, active_set)
+ newton_step = -lsmr(lsmr_op, f, **tr_options)[0][free_set]
+ newton_step *= scale_free
+
+ # Components of g for active variables were zeroed, so this call
+ # is correct and equivalent to using J_free and g_free.
+ a, b = build_quadratic_1d(Jop, g, -g)
+
+ actual_reduction = -1.0
+ while actual_reduction <= 0 and nfev < max_nfev:
+ tr_bounds = Delta * scale_free
+
+ step_free, on_bound_free, tr_hit = dogleg_step(
+ x_free, newton_step, g_free, a, b, tr_bounds, lb_free, ub_free)
+
+ step.fill(0.0)
+ step[free_set] = step_free
+
+ if tr_solver == 'exact':
+ predicted_reduction = -evaluate_quadratic(J_free, g_free,
+ step_free)
+ elif tr_solver == 'lsmr':
+ predicted_reduction = -evaluate_quadratic(Jop, g, step)
+
+ # gh11403 ensure that solution is fully within bounds.
+ x_new = np.clip(x + step, lb, ub)
+
+ f_new = fun(x_new)
+ nfev += 1
+
+ step_h_norm = norm(step * scale_inv, ord=np.inf)
+
+ if not np.all(np.isfinite(f_new)):
+ Delta = 0.25 * step_h_norm
+ continue
+
+ # Usual trust-region step quality estimation.
+ if loss_function is not None:
+ cost_new = loss_function(f_new, cost_only=True)
+ else:
+ cost_new = 0.5 * np.dot(f_new, f_new)
+ actual_reduction = cost - cost_new
+
+ Delta, ratio = update_tr_radius(
+ Delta, actual_reduction, predicted_reduction,
+ step_h_norm, tr_hit
+ )
+
+ step_norm = norm(step)
+ termination_status = check_termination(
+ actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol)
+
+ if termination_status is not None:
+ break
+
+ if actual_reduction > 0:
+ on_bound[free_set] = on_bound_free
+
+ x = x_new
+ # Set variables exactly at the boundary.
+ mask = on_bound == -1
+ x[mask] = lb[mask]
+ mask = on_bound == 1
+ x[mask] = ub[mask]
+
+ f = f_new
+ f_true = f.copy()
+
+ cost = cost_new
+
+ J = jac(x)
+ njev += 1
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ J, f = scale_for_robust_loss_function(J, f, rho)
+
+ g = compute_grad(J, f)
+
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J, scale_inv)
+ else:
+ step_norm = 0
+ actual_reduction = 0
+
+ iteration += 1
+
+ # Call callback function and possibly stop optimization
+ if callback is not None:
+ intermediate_result = OptimizeResult(
+ x=x, fun=f, nit=iteration, nfev=nfev)
+ intermediate_result["cost"] = cost_new
+
+ if _call_callback_maybe_halt(
+ callback, intermediate_result
+ ):
+ termination_status = -2
+ break
+
+ if termination_status is None:
+ termination_status = 0
+
+ return OptimizeResult(
+ x=x, cost=cost, fun=f_true, jac=J, grad=g_full, optimality=g_norm,
+ active_mask=on_bound, nfev=nfev, njev=njev, status=termination_status)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/givens_elimination.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/givens_elimination.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..c90511f852ec221c60977cf165a5655bad5cfa47
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/givens_elimination.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/least_squares.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/least_squares.py
new file mode 100644
index 0000000000000000000000000000000000000000..a6e58508dee7f67f1e5ddbf7c7cb6f215bb8d563
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/least_squares.py
@@ -0,0 +1,1044 @@
+"""Generic interface for least-squares minimization."""
+from warnings import warn
+
+import numpy as np
+from numpy.linalg import norm
+
+from scipy.sparse.linalg import LinearOperator
+from scipy.optimize import _minpack, OptimizeResult
+from scipy.optimize._differentiable_functions import VectorFunction
+from scipy.optimize._numdiff import group_columns
+from scipy.optimize._minimize import Bounds
+from scipy._lib._sparse import issparse
+from scipy._lib._array_api import array_namespace
+from scipy._lib._util import _workers_wrapper
+
+from .trf import trf
+from .dogbox import dogbox
+from .common import EPS, in_bounds, make_strictly_feasible
+
+
+from scipy.optimize._optimize import _wrap_callback
+
+TERMINATION_MESSAGES = {
+ -2: "Stopped because `callback` function raised `StopIteration` or returned `True`",
+ -1: "Improper input parameters status returned from `leastsq`",
+ 0: "The maximum number of function evaluations is exceeded.",
+ 1: "`gtol` termination condition is satisfied.",
+ 2: "`ftol` termination condition is satisfied.",
+ 3: "`xtol` termination condition is satisfied.",
+ 4: "Both `ftol` and `xtol` termination conditions are satisfied."
+}
+
+
+FROM_MINPACK_TO_COMMON = {
+ 0: -1, # Improper input parameters from MINPACK.
+ 1: 2,
+ 2: 3,
+ 3: 4,
+ 4: 1,
+ 5: 0
+ # There are 6, 7, 8 for too small tolerance parameters,
+ # but we guard against it by checking ftol, xtol, gtol beforehand.
+}
+
+
+def call_minpack(fun, x0, jac, ftol, xtol, gtol, max_nfev, x_scale, jac_method=None):
+ n = x0.size
+
+ # Compute MINPACK's `diag`, which is inverse of our `x_scale` and
+ # ``x_scale='jac'`` corresponds to ``diag=None``.
+
+ # 1.16.0 - default x_scale changed to 'jac', with diag=None
+ if x_scale is None or (isinstance(x_scale, str) and x_scale == 'jac'):
+ diag = None
+ else:
+ # x_scale specified, so use that
+ diag = 1 / x_scale
+
+ full_output = True
+ col_deriv = False
+ factor = 100.0
+
+ if max_nfev is None:
+ max_nfev = 100 * n
+
+ # lmder is typically used for systems with analytic jacobians, with lmdif being
+ # used if there is only an objective fun (lmdif uses finite differences to estimate
+ # jacobian). Otherwise they're very similar internally.
+ # We now do all the finite differencing in VectorFunction, which means we can drop
+ # lmdif and just use lmder.
+
+ # for sending a copy of x0 into _lmder
+ xp = array_namespace(x0)
+
+ x, info, status = _minpack._lmder(
+ fun, jac, xp.astype(x0, x0.dtype), (), full_output, col_deriv,
+ ftol, xtol, gtol, max_nfev, factor, diag)
+
+ f = info['fvec']
+ J = jac(x)
+
+ cost = 0.5 * np.dot(f, f)
+ g = J.T.dot(f)
+ g_norm = norm(g, ord=np.inf)
+
+ nfev = info['nfev']
+ if callable(jac_method):
+ # user supplied a callable ("analytic") jac
+ njev = info.get('njev', None)
+ else:
+ # If there are no analytic jacobian evaluations we need to set `njev=None`.
+ njev = None
+
+ status = FROM_MINPACK_TO_COMMON[status]
+ active_mask = np.zeros_like(x0, dtype=int)
+
+ return OptimizeResult(
+ x=x, cost=cost, fun=f, jac=J, grad=g, optimality=g_norm,
+ active_mask=active_mask, nfev=nfev, njev=njev, status=status)
+
+
+def prepare_bounds(bounds, n):
+ lb, ub = (np.asarray(b, dtype=float) for b in bounds)
+ if lb.ndim == 0:
+ lb = np.resize(lb, n)
+
+ if ub.ndim == 0:
+ ub = np.resize(ub, n)
+
+ return lb, ub
+
+
+def check_tolerance(ftol, xtol, gtol, method):
+ def check(tol, name):
+ if tol is None:
+ tol = 0
+ elif tol < EPS:
+ warn(f"Setting `{name}` below the machine epsilon ({EPS:.2e}) effectively "
+ f"disables the corresponding termination condition.",
+ stacklevel=3)
+ return tol
+
+ ftol = check(ftol, "ftol")
+ xtol = check(xtol, "xtol")
+ gtol = check(gtol, "gtol")
+
+ if method == "lm" and (ftol < EPS or xtol < EPS or gtol < EPS):
+ raise ValueError("All tolerances must be higher than machine epsilon "
+ f"({EPS:.2e}) for method 'lm'.")
+ elif ftol < EPS and xtol < EPS and gtol < EPS:
+ raise ValueError("At least one of the tolerances must be higher than "
+ f"machine epsilon ({EPS:.2e}).")
+
+ return ftol, xtol, gtol
+
+
+def check_x_scale(x_scale, x0, method):
+ # normalise the default scaling
+ if x_scale is None:
+ if method == 'lm':
+ return 'jac'
+ else: # dogbox, trf
+ x_scale = 1.0
+
+ if isinstance(x_scale, str) and x_scale == 'jac':
+ return x_scale
+
+ try:
+ x_scale = np.asarray(x_scale, dtype=float)
+ valid = np.all(np.isfinite(x_scale)) and np.all(x_scale > 0)
+ except (ValueError, TypeError):
+ valid = False
+
+ if not valid:
+ raise ValueError("`x_scale` must be 'jac' or array_like with "
+ "positive numbers.")
+
+ if x_scale.ndim == 0:
+ x_scale = np.resize(x_scale, x0.shape)
+
+ if x_scale.shape != x0.shape:
+ raise ValueError("Inconsistent shapes between `x_scale` and `x0`.")
+
+ return x_scale
+
+
+def check_jac_sparsity(jac_sparsity, m, n):
+ if jac_sparsity is None:
+ return None
+
+ if not issparse(jac_sparsity):
+ jac_sparsity = np.atleast_2d(jac_sparsity)
+
+ if jac_sparsity.shape != (m, n):
+ raise ValueError("`jac_sparsity` has wrong shape.")
+
+ return jac_sparsity, group_columns(jac_sparsity)
+
+
+# Loss functions.
+
+
+def huber(z, rho, cost_only):
+ mask = z <= 1
+ rho[0, mask] = z[mask]
+ rho[0, ~mask] = 2 * z[~mask]**0.5 - 1
+ if cost_only:
+ return
+ rho[1, mask] = 1
+ rho[1, ~mask] = z[~mask]**-0.5
+ rho[2, mask] = 0
+ rho[2, ~mask] = -0.5 * z[~mask]**-1.5
+
+
+def soft_l1(z, rho, cost_only):
+ t = 1 + z
+ rho[0] = 2 * (t**0.5 - 1)
+ if cost_only:
+ return
+ rho[1] = t**-0.5
+ rho[2] = -0.5 * t**-1.5
+
+
+def cauchy(z, rho, cost_only):
+ rho[0] = np.log1p(z)
+ if cost_only:
+ return
+ t = 1 + z
+ rho[1] = 1 / t
+ rho[2] = -1 / t**2
+
+
+def arctan(z, rho, cost_only):
+ rho[0] = np.arctan(z)
+ if cost_only:
+ return
+ t = 1 + z**2
+ rho[1] = 1 / t
+ rho[2] = -2 * z / t**2
+
+
+IMPLEMENTED_LOSSES = dict(linear=None, huber=huber, soft_l1=soft_l1,
+ cauchy=cauchy, arctan=arctan)
+
+
+def construct_loss_function(m, loss, f_scale):
+ if loss == 'linear':
+ return None
+
+ if not callable(loss):
+ loss = IMPLEMENTED_LOSSES[loss]
+ rho = np.empty((3, m))
+
+ def loss_function(f, cost_only=False):
+ z = (f / f_scale) ** 2
+ loss(z, rho, cost_only=cost_only)
+ if cost_only:
+ return 0.5 * f_scale ** 2 * np.sum(rho[0])
+ rho[0] *= f_scale ** 2
+ rho[2] /= f_scale ** 2
+ return rho
+ else:
+ def loss_function(f, cost_only=False):
+ z = (f / f_scale) ** 2
+ rho = loss(z)
+ if cost_only:
+ return 0.5 * f_scale ** 2 * np.sum(rho[0])
+ rho[0] *= f_scale ** 2
+ rho[2] /= f_scale ** 2
+ return rho
+
+ return loss_function
+
+
+class _WrapArgsKwargs:
+ # Supplies a user function with args and kwargs.
+ def __init__(self, f, args=(), kwargs=None):
+ self.f = f
+ self.args = args
+ self.kwargs = kwargs or {}
+
+ def __call__(self, x):
+ return self.f(x, *self.args, **self.kwargs)
+
+
+@_workers_wrapper
+def least_squares(
+ fun, x0, jac='2-point', bounds=(-np.inf, np.inf), method='trf',
+ ftol=1e-8, xtol=1e-8, gtol=1e-8, x_scale=None, loss='linear',
+ f_scale=1.0, diff_step=None, tr_solver=None, tr_options=None,
+ jac_sparsity=None, max_nfev=None, verbose=0, args=(), kwargs=None,
+ callback=None, workers=None
+):
+ """Solve a nonlinear least-squares problem with bounds on the variables.
+
+ Given the residuals f(x) (an m-D real function of n real
+ variables) and the loss function rho(s) (a scalar function), `least_squares`
+ finds a local minimum of the cost function F(x)::
+
+ minimize F(x) = 0.5 * sum(rho(f_i(x)**2), i = 0, ..., m - 1)
+ subject to lb <= x <= ub
+
+ The purpose of the loss function rho(s) is to reduce the influence of
+ outliers on the solution.
+
+ Parameters
+ ----------
+ fun : callable
+ Function which computes the vector of residuals, with the signature
+ ``fun(x, *args, **kwargs)``, i.e., the minimization proceeds with
+ respect to its first argument. The argument ``x`` passed to this
+ function is an ndarray of shape (n,) (never a scalar, even for n=1).
+ It must allocate and return a 1-D array_like of shape (m,) or a scalar.
+ If the argument ``x`` is complex or the function ``fun`` returns
+ complex residuals, it must be wrapped in a real function of real
+ arguments, as shown at the end of the Examples section.
+ x0 : array_like with shape (n,) or float
+ Initial guess on independent variables. If float, it will be treated
+ as a 1-D array with one element. When `method` is 'trf', the initial
+ guess might be slightly adjusted to lie sufficiently within the given
+ `bounds`.
+ jac : {'2-point', '3-point', 'cs', callable}, optional
+ Method of computing the Jacobian matrix (an m-by-n matrix, where
+ element (i, j) is the partial derivative of f[i] with respect to
+ x[j]). The keywords select a finite difference scheme for numerical
+ estimation. The scheme '3-point' is more accurate, but requires
+ twice as many operations as '2-point' (default). The scheme 'cs'
+ uses complex steps, and while potentially the most accurate, it is
+ applicable only when `fun` correctly handles complex inputs and
+ can be analytically continued to the complex plane. If callable, it is used as
+ ``jac(x, *args, **kwargs)`` and should return a good approximation
+ (or the exact value) for the Jacobian as an array_like (np.atleast_2d
+ is applied), a sparse array (csr_array preferred for performance) or
+ a `scipy.sparse.linalg.LinearOperator`.
+
+ .. versionchanged:: 1.16.0
+ An ability to use the '3-point', 'cs' keywords with the 'lm' method.
+ Previously 'lm' was limited to '2-point' and callable.
+
+ bounds : 2-tuple of array_like or `Bounds`, optional
+ There are two ways to specify bounds:
+
+ 1. Instance of `Bounds` class
+ 2. Lower and upper bounds on independent variables. Defaults to no
+ bounds. Each array must match the size of `x0` or be a scalar,
+ in the latter case a bound will be the same for all variables.
+ Use ``np.inf`` with an appropriate sign to disable bounds on all
+ or some variables.
+
+ method : {'trf', 'dogbox', 'lm'}, optional
+ Algorithm to perform minimization.
+
+ * 'trf' : Trust Region Reflective algorithm, particularly suitable
+ for large sparse problems with bounds. Generally robust method.
+ * 'dogbox' : dogleg algorithm with rectangular trust regions,
+ typical use case is small problems with bounds. Not recommended
+ for problems with rank-deficient Jacobian.
+ * 'lm' : Levenberg-Marquardt algorithm as implemented in MINPACK.
+ Doesn't handle bounds and sparse Jacobians. Usually the most
+ efficient method for small unconstrained problems.
+
+ Default is 'trf'. See Notes for more information.
+ ftol : float or None, optional
+ Tolerance for termination by the change of the cost function. Default
+ is 1e-8. The optimization process is stopped when ``dF < ftol * F``,
+ and there was an adequate agreement between a local quadratic model and
+ the true model in the last step.
+
+ If None and 'method' is not 'lm', the termination by this condition is
+ disabled. If 'method' is 'lm', this tolerance must be higher than
+ machine epsilon.
+ xtol : float or None, optional
+ Tolerance for termination by the change of the independent variables.
+ Default is 1e-8. The exact condition depends on the `method` used:
+
+ * For 'trf' and 'dogbox' : ``norm(dx) < xtol * (xtol + norm(x))``.
+ * For 'lm' : ``Delta < xtol * norm(xs)``, where ``Delta`` is
+ a trust-region radius and ``xs`` is the value of ``x``
+ scaled according to `x_scale` parameter (see below).
+
+ If None and 'method' is not 'lm', the termination by this condition is
+ disabled. If 'method' is 'lm', this tolerance must be higher than
+ machine epsilon.
+ gtol : float or None, optional
+ Tolerance for termination by the norm of the gradient. Default is 1e-8.
+ The exact condition depends on a `method` used:
+
+ * For 'trf' : ``norm(g_scaled, ord=np.inf) < gtol``, where
+ ``g_scaled`` is the value of the gradient scaled to account for
+ the presence of the bounds [STIR]_.
+ * For 'dogbox' : ``norm(g_free, ord=np.inf) < gtol``, where
+ ``g_free`` is the gradient with respect to the variables which
+ are not in the optimal state on the boundary.
+ * For 'lm' : the maximum absolute value of the cosine of angles
+ between columns of the Jacobian and the residual vector is less
+ than `gtol`, or the residual vector is zero.
+
+ If None and 'method' is not 'lm', the termination by this condition is
+ disabled. If 'method' is 'lm', this tolerance must be higher than
+ machine epsilon.
+ x_scale : {None, array_like, 'jac'}, optional
+ Characteristic scale of each variable. Setting `x_scale` is equivalent
+ to reformulating the problem in scaled variables ``xs = x / x_scale``.
+ An alternative view is that the size of a trust region along jth
+ dimension is proportional to ``x_scale[j]``. Improved convergence may
+ be achieved by setting `x_scale` such that a step of a given size
+ along any of the scaled variables has a similar effect on the cost
+ function. If set to 'jac', the scale is iteratively updated using the
+ inverse norms of the columns of the Jacobian matrix (as described in
+ [JJMore]_). The default scaling for each method (i.e.
+ if ``x_scale is None``) is as follows:
+
+ * For 'trf' : ``x_scale == 1``
+ * For 'dogbox' : ``x_scale == 1``
+ * For 'lm' : ``x_scale == 'jac'``
+
+ .. versionchanged:: 1.16.0
+ The default keyword value is changed from 1 to None to indicate that
+ a default approach to scaling is used.
+ For the 'lm' method the default scaling is changed from 1 to 'jac'.
+ This has been found to give better performance, and is the same
+ scaling as performed by ``leastsq``.
+
+ loss : str or callable, optional
+ Determines the loss function. The following keyword values are allowed:
+
+ * 'linear' (default) : ``rho(z) = z``. Gives a standard
+ least-squares problem.
+ * 'soft_l1' : ``rho(z) = 2 * ((1 + z)**0.5 - 1)``. The smooth
+ approximation of l1 (absolute value) loss. Usually a good
+ choice for robust least squares.
+ * 'huber' : ``rho(z) = z if z <= 1 else 2*z**0.5 - 1``. Works
+ similarly to 'soft_l1'.
+ * 'cauchy' : ``rho(z) = ln(1 + z)``. Severely weakens outliers
+ influence, but may cause difficulties in optimization process.
+ * 'arctan' : ``rho(z) = arctan(z)``. Limits a maximum loss on
+ a single residual, has properties similar to 'cauchy'.
+
+ If callable, it must take a 1-D ndarray ``z=f**2`` and return an
+ array_like with shape (3, m) where row 0 contains function values,
+ row 1 contains first derivatives and row 2 contains second
+ derivatives. Method 'lm' supports only 'linear' loss.
+ f_scale : float, optional
+ Value of soft margin between inlier and outlier residuals, default
+ is 1.0. The loss function is evaluated as follows
+ ``rho_(f**2) = C**2 * rho(f**2 / C**2)``, where ``C`` is `f_scale`,
+ and ``rho`` is determined by `loss` parameter. This parameter has
+ no effect with ``loss='linear'``, but for other `loss` values it is
+ of crucial importance.
+ max_nfev : None or int, optional
+ For all methods this parameter controls the maximum number of function
+ evaluations used by each method, separate to those used in numerical
+ approximation of the jacobian.
+ If None (default), the value is chosen automatically as 100 * n.
+
+ .. versionchanged:: 1.16.0
+ The default for the 'lm' method is changed to 100 * n, for both a callable
+ and a numerically estimated jacobian. Previously the default when using an
+ estimated jacobian was 100 * n * (n + 1), because the method included
+ evaluations used in the estimation.
+
+ diff_step : None or array_like, optional
+ Determines the relative step size for the finite difference
+ approximation of the Jacobian. The actual step is computed as
+ ``x * diff_step``. If None (default), then `diff_step` is taken to be
+ a conventional "optimal" power of machine epsilon for the finite
+ difference scheme used [NR]_.
+ tr_solver : {None, 'exact', 'lsmr'}, optional
+ Method for solving trust-region subproblems, relevant only for 'trf'
+ and 'dogbox' methods.
+
+ * 'exact' is suitable for not very large problems with dense
+ Jacobian matrices. The computational complexity per iteration is
+ comparable to a singular value decomposition of the Jacobian
+ matrix.
+ * 'lsmr' is suitable for problems with sparse and large Jacobian
+ matrices. It uses the iterative procedure
+ `scipy.sparse.linalg.lsmr` for finding a solution of a linear
+ least-squares problem and only requires matrix-vector product
+ evaluations.
+
+ If None (default), the solver is chosen based on the type of Jacobian
+ returned on the first iteration.
+ tr_options : dict, optional
+ Keyword options passed to trust-region solver.
+
+ * ``tr_solver='exact'``: `tr_options` are ignored.
+ * ``tr_solver='lsmr'``: options for `scipy.sparse.linalg.lsmr`.
+ Additionally, ``method='trf'`` supports 'regularize' option
+ (bool, default is True), which adds a regularization term to the
+ normal equation, which improves convergence if the Jacobian is
+ rank-deficient [Byrd]_ (eq. 3.4).
+
+ jac_sparsity : {None, array_like, sparse array}, optional
+ Defines the sparsity structure of the Jacobian matrix for finite
+ difference estimation, its shape must be (m, n). If the Jacobian has
+ only few non-zero elements in *each* row, providing the sparsity
+ structure will greatly speed up the computations [Curtis]_. A zero
+ entry means that a corresponding element in the Jacobian is identically
+ zero. If provided, forces the use of 'lsmr' trust-region solver.
+ If None (default), then dense differencing will be used. Has no effect
+ for 'lm' method.
+ verbose : {0, 1, 2}, optional
+ Level of algorithm's verbosity:
+
+ * 0 (default) : work silently.
+ * 1 : display a termination report.
+ * 2 : display progress during iterations (not supported by 'lm'
+ method).
+
+ args, kwargs : tuple and dict, optional
+ Additional arguments passed to `fun` and `jac`. Both empty by default.
+ The calling signature is ``fun(x, *args, **kwargs)`` and the same for
+ `jac`.
+ callback : None or callable, optional
+ Callback function that is called by the algorithm on each iteration.
+ This can be used to print or plot the optimization results at each
+ step, and to stop the optimization algorithm based on some user-defined
+ condition. Only implemented for the `trf` and `dogbox` methods.
+
+ The signature is ``callback(intermediate_result: OptimizeResult)``
+
+ `intermediate_result is a `scipy.optimize.OptimizeResult`
+ which contains the intermediate results of the optimization at the
+ current iteration.
+
+ The callback also supports a signature like: ``callback(x)``
+
+ Introspection is used to determine which of the signatures is invoked.
+
+ If the `callback` function raises `StopIteration` the optimization algorithm
+ will stop and return with status code -2.
+
+ .. versionadded:: 1.16.0
+ workers : map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Returns
+ -------
+ result : OptimizeResult
+ `OptimizeResult` with the following fields defined:
+
+ x : ndarray, shape (n,)
+ Solution found.
+ cost : float
+ Value of the cost function at the solution.
+ fun : ndarray, shape (m,)
+ Vector of residuals at the solution.
+ jac : ndarray, sparse array or LinearOperator, shape (m, n)
+ Modified Jacobian matrix at the solution, in the sense that J^T J
+ is a Gauss-Newton approximation of the Hessian of the cost function.
+ The type is the same as the one used by the algorithm.
+ grad : ndarray, shape (m,)
+ Gradient of the cost function at the solution.
+ optimality : float
+ First-order optimality measure. In unconstrained problems, it is
+ always the uniform norm of the gradient. In constrained problems,
+ it is the quantity which was compared with `gtol` during iterations.
+ active_mask : ndarray of int, shape (n,)
+ Each component shows whether a corresponding constraint is active
+ (that is, whether a variable is at the bound):
+
+ * 0 : a constraint is not active.
+ * -1 : a lower bound is active.
+ * 1 : an upper bound is active.
+
+ Might be somewhat arbitrary for 'trf' method as it generates a
+ sequence of strictly feasible iterates and `active_mask` is
+ determined within a tolerance threshold.
+ nfev : int
+ Number of function evaluations done. This number does not include
+ the function calls used for numerical Jacobian approximation.
+
+ .. versionchanged:: 1.16.0
+ For the 'lm' method the number of function calls used in numerical
+ Jacobian approximation is no longer included. This is to bring all
+ methods into line.
+
+ njev : int or None
+ Number of Jacobian evaluations done. If numerical Jacobian
+ approximation is used in 'lm' method, it is set to None.
+ status : int
+ The reason for algorithm termination:
+
+ * -2 : terminated because callback raised StopIteration.
+ * -1 : improper input parameters status returned from MINPACK.
+ * 0 : the maximum number of function evaluations is exceeded.
+ * 1 : `gtol` termination condition is satisfied.
+ * 2 : `ftol` termination condition is satisfied.
+ * 3 : `xtol` termination condition is satisfied.
+ * 4 : Both `ftol` and `xtol` termination conditions are satisfied.
+
+ message : str
+ Verbal description of the termination reason.
+ success : bool
+ True if one of the convergence criteria is satisfied (`status` > 0).
+
+ See Also
+ --------
+ leastsq : A legacy wrapper for the MINPACK implementation of the
+ Levenberg-Marquadt algorithm.
+ curve_fit : Least-squares minimization applied to a curve-fitting problem.
+
+ Notes
+ -----
+ Method 'lm' (Levenberg-Marquardt) calls a wrapper over a least-squares
+ algorithm implemented in MINPACK (lmder). It runs the
+ Levenberg-Marquardt algorithm formulated as a trust-region type algorithm.
+ The implementation is based on paper [JJMore]_, it is very robust and
+ efficient with a lot of smart tricks. It should be your first choice
+ for unconstrained problems. Note that it doesn't support bounds. Also,
+ it doesn't work when m < n.
+
+ Method 'trf' (Trust Region Reflective) is motivated by the process of
+ solving a system of equations, which constitute the first-order optimality
+ condition for a bound-constrained minimization problem as formulated in
+ [STIR]_. The algorithm iteratively solves trust-region subproblems
+ augmented by a special diagonal quadratic term and with trust-region shape
+ determined by the distance from the bounds and the direction of the
+ gradient. This enhancements help to avoid making steps directly into bounds
+ and efficiently explore the whole space of variables. To further improve
+ convergence, the algorithm considers search directions reflected from the
+ bounds. To obey theoretical requirements, the algorithm keeps iterates
+ strictly feasible. With dense Jacobians trust-region subproblems are
+ solved by an exact method very similar to the one described in [JJMore]_
+ (and implemented in MINPACK). The difference from the MINPACK
+ implementation is that a singular value decomposition of a Jacobian
+ matrix is done once per iteration, instead of a QR decomposition and series
+ of Givens rotation eliminations. For large sparse Jacobians a 2-D subspace
+ approach of solving trust-region subproblems is used [STIR]_, [Byrd]_.
+ The subspace is spanned by a scaled gradient and an approximate
+ Gauss-Newton solution delivered by `scipy.sparse.linalg.lsmr`. When no
+ constraints are imposed the algorithm is very similar to MINPACK and has
+ generally comparable performance. The algorithm works quite robust in
+ unbounded and bounded problems, thus it is chosen as a default algorithm.
+
+ Method 'dogbox' operates in a trust-region framework, but considers
+ rectangular trust regions as opposed to conventional ellipsoids [Voglis]_.
+ The intersection of a current trust region and initial bounds is again
+ rectangular, so on each iteration a quadratic minimization problem subject
+ to bound constraints is solved approximately by Powell's dogleg method
+ [NumOpt]_. The required Gauss-Newton step can be computed exactly for
+ dense Jacobians or approximately by `scipy.sparse.linalg.lsmr` for large
+ sparse Jacobians. The algorithm is likely to exhibit slow convergence when
+ the rank of Jacobian is less than the number of variables. The algorithm
+ often outperforms 'trf' in bounded problems with a small number of
+ variables.
+
+ Robust loss functions are implemented as described in [BA]_. The idea
+ is to modify a residual vector and a Jacobian matrix on each iteration
+ such that computed gradient and Gauss-Newton Hessian approximation match
+ the true gradient and Hessian approximation of the cost function. Then
+ the algorithm proceeds in a normal way, i.e., robust loss functions are
+ implemented as a simple wrapper over standard least-squares algorithms.
+
+ .. versionadded:: 0.17.0
+
+ References
+ ----------
+ .. [STIR] M. A. Branch, T. F. Coleman, and Y. Li, "A Subspace, Interior,
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
+ Minimization Problems," SIAM Journal on Scientific Computing,
+ Vol. 21, Number 1, pp 1-23, 1999.
+ .. [NR] William H. Press et. al., "Numerical Recipes. The Art of Scientific
+ Computing. 3rd edition", Sec. 5.7.
+ .. [Byrd] R. H. Byrd, R. B. Schnabel and G. A. Shultz, "Approximate
+ solution of the trust region problem by minimization over
+ two-dimensional subspaces", Math. Programming, 40, pp. 247-263,
+ 1988.
+ .. [Curtis] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+ sparse Jacobian matrices", Journal of the Institute of
+ Mathematics and its Applications, 13, pp. 117-120, 1974.
+ .. [JJMore] J. J. More, "The Levenberg-Marquardt Algorithm: Implementation
+ and Theory," Numerical Analysis, ed. G. A. Watson, Lecture
+ Notes in Mathematics 630, Springer Verlag, pp. 105-116, 1977.
+ .. [Voglis] C. Voglis and I. E. Lagaris, "A Rectangular Trust Region
+ Dogleg Approach for Unconstrained and Bound Constrained
+ Nonlinear Optimization", WSEAS International Conference on
+ Applied Mathematics, Corfu, Greece, 2004.
+ .. [NumOpt] J. Nocedal and S. J. Wright, "Numerical optimization,
+ 2nd edition", Chapter 4.
+ .. [BA] B. Triggs et. al., "Bundle Adjustment - A Modern Synthesis",
+ Proceedings of the International Workshop on Vision Algorithms:
+ Theory and Practice, pp. 298-372, 1999.
+
+ Examples
+ --------
+ In this example we find a minimum of the Rosenbrock function without bounds
+ on independent variables.
+
+ >>> import numpy as np
+ >>> def fun_rosenbrock(x):
+ ... return np.array([10 * (x[1] - x[0]**2), (1 - x[0])])
+
+ Notice that we only provide the vector of the residuals. The algorithm
+ constructs the cost function as a sum of squares of the residuals, which
+ gives the Rosenbrock function. The exact minimum is at ``x = [1.0, 1.0]``.
+
+ >>> from scipy.optimize import least_squares
+ >>> x0_rosenbrock = np.array([2, 2])
+ >>> res_1 = least_squares(fun_rosenbrock, x0_rosenbrock)
+ >>> res_1.x
+ array([ 1., 1.])
+ >>> res_1.cost
+ 9.8669242910846867e-30
+ >>> res_1.optimality
+ 8.8928864934219529e-14
+
+ We now constrain the variables, in such a way that the previous solution
+ becomes infeasible. Specifically, we require that ``x[1] >= 1.5``, and
+ ``x[0]`` left unconstrained. To this end, we specify the `bounds` parameter
+ to `least_squares` in the form ``bounds=([-np.inf, 1.5], np.inf)``.
+
+ We also provide the analytic Jacobian:
+
+ >>> def jac_rosenbrock(x):
+ ... return np.array([
+ ... [-20 * x[0], 10],
+ ... [-1, 0]])
+
+ Putting this all together, we see that the new solution lies on the bound:
+
+ >>> res_2 = least_squares(fun_rosenbrock, x0_rosenbrock, jac_rosenbrock,
+ ... bounds=([-np.inf, 1.5], np.inf))
+ >>> res_2.x
+ array([ 1.22437075, 1.5 ])
+ >>> res_2.cost
+ 0.025213093946805685
+ >>> res_2.optimality
+ 1.5885401433157753e-07
+
+ Now we solve a system of equations (i.e., the cost function should be zero
+ at a minimum) for a Broyden tridiagonal vector-valued function of 100000
+ variables:
+
+ >>> def fun_broyden(x):
+ ... f = (3 - x) * x + 1
+ ... f[1:] -= x[:-1]
+ ... f[:-1] -= 2 * x[1:]
+ ... return f
+
+ The corresponding Jacobian matrix is sparse. We tell the algorithm to
+ estimate it by finite differences and provide the sparsity structure of
+ Jacobian to significantly speed up this process.
+
+ >>> from scipy.sparse import lil_array
+ >>> def sparsity_broyden(n):
+ ... sparsity = lil_array((n, n), dtype=int)
+ ... i = np.arange(n)
+ ... sparsity[i, i] = 1
+ ... i = np.arange(1, n)
+ ... sparsity[i, i - 1] = 1
+ ... i = np.arange(n - 1)
+ ... sparsity[i, i + 1] = 1
+ ... return sparsity
+ ...
+ >>> n = 100000
+ >>> x0_broyden = -np.ones(n)
+ ...
+ >>> res_3 = least_squares(fun_broyden, x0_broyden,
+ ... jac_sparsity=sparsity_broyden(n))
+ >>> res_3.cost
+ 4.5687069299604613e-23
+ >>> res_3.optimality
+ 1.1650454296851518e-11
+
+ Let's also solve a curve fitting problem using robust loss function to
+ take care of outliers in the data. Define the model function as
+ ``y = a + b * exp(c * t)``, where t is a predictor variable, y is an
+ observation and a, b, c are parameters to estimate.
+
+ First, define the function which generates the data with noise and
+ outliers, define the model parameters, and generate data:
+
+ >>> from numpy.random import default_rng
+ >>> rng = default_rng()
+ >>> def gen_data(t, a, b, c, noise=0., n_outliers=0, seed=None):
+ ... rng = default_rng(seed)
+ ...
+ ... y = a + b * np.exp(t * c)
+ ...
+ ... error = noise * rng.standard_normal(t.size)
+ ... outliers = rng.integers(0, t.size, n_outliers)
+ ... error[outliers] *= 10
+ ...
+ ... return y + error
+ ...
+ >>> a = 0.5
+ >>> b = 2.0
+ >>> c = -1
+ >>> t_min = 0
+ >>> t_max = 10
+ >>> n_points = 15
+ ...
+ >>> t_train = np.linspace(t_min, t_max, n_points)
+ >>> y_train = gen_data(t_train, a, b, c, noise=0.1, n_outliers=3)
+
+ Define function for computing residuals and initial estimate of
+ parameters.
+
+ >>> def fun(x, t, y):
+ ... return x[0] + x[1] * np.exp(x[2] * t) - y
+ ...
+ >>> x0 = np.array([1.0, 1.0, 0.0])
+
+ Compute a standard least-squares solution:
+
+ >>> res_lsq = least_squares(fun, x0, args=(t_train, y_train))
+
+ Now compute two solutions with two different robust loss functions. The
+ parameter `f_scale` is set to 0.1, meaning that inlier residuals should
+ not significantly exceed 0.1 (the noise level used).
+
+ >>> res_soft_l1 = least_squares(fun, x0, loss='soft_l1', f_scale=0.1,
+ ... args=(t_train, y_train))
+ >>> res_log = least_squares(fun, x0, loss='cauchy', f_scale=0.1,
+ ... args=(t_train, y_train))
+
+ And, finally, plot all the curves. We see that by selecting an appropriate
+ `loss` we can get estimates close to optimal even in the presence of
+ strong outliers. But keep in mind that generally it is recommended to try
+ 'soft_l1' or 'huber' losses first (if at all necessary) as the other two
+ options may cause difficulties in optimization process.
+
+ >>> t_test = np.linspace(t_min, t_max, n_points * 10)
+ >>> y_true = gen_data(t_test, a, b, c)
+ >>> y_lsq = gen_data(t_test, *res_lsq.x)
+ >>> y_soft_l1 = gen_data(t_test, *res_soft_l1.x)
+ >>> y_log = gen_data(t_test, *res_log.x)
+ ...
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(t_train, y_train, 'o')
+ >>> plt.plot(t_test, y_true, 'k', linewidth=2, label='true')
+ >>> plt.plot(t_test, y_lsq, label='linear loss')
+ >>> plt.plot(t_test, y_soft_l1, label='soft_l1 loss')
+ >>> plt.plot(t_test, y_log, label='cauchy loss')
+ >>> plt.xlabel("t")
+ >>> plt.ylabel("y")
+ >>> plt.legend()
+ >>> plt.show()
+
+ In the next example, we show how complex-valued residual functions of
+ complex variables can be optimized with ``least_squares()``. Consider the
+ following function:
+
+ >>> def f(z):
+ ... return z - (0.5 + 0.5j)
+
+ We wrap it into a function of real variables that returns real residuals
+ by simply handling the real and imaginary parts as independent variables:
+
+ >>> def f_wrap(x):
+ ... fx = f(x[0] + 1j*x[1])
+ ... return np.array([fx.real, fx.imag])
+
+ Thus, instead of the original m-D complex function of n complex
+ variables we optimize a 2m-D real function of 2n real variables:
+
+ >>> from scipy.optimize import least_squares
+ >>> res_wrapped = least_squares(f_wrap, (0.1, 0.1), bounds=([0, 0], [1, 1]))
+ >>> z = res_wrapped.x[0] + res_wrapped.x[1]*1j
+ >>> z
+ (0.49999999999925893+0.49999999999925893j)
+
+ """
+ if method not in ['trf', 'dogbox', 'lm']:
+ raise ValueError("`method` must be 'trf', 'dogbox' or 'lm'.")
+
+ if jac not in ['2-point', '3-point', 'cs'] and not callable(jac):
+ raise ValueError("`jac` must be '2-point', '3-point', 'cs' or "
+ "callable.")
+
+ if tr_solver not in [None, 'exact', 'lsmr']:
+ raise ValueError("`tr_solver` must be None, 'exact' or 'lsmr'.")
+
+ if loss not in IMPLEMENTED_LOSSES and not callable(loss):
+ raise ValueError(f"`loss` must be one of {IMPLEMENTED_LOSSES.keys()}"
+ " or a callable.")
+
+ if method == 'lm' and loss != 'linear':
+ raise ValueError("method='lm' supports only 'linear' loss function.")
+
+ if verbose not in [0, 1, 2]:
+ raise ValueError("`verbose` must be in [0, 1, 2].")
+
+ if max_nfev is not None and max_nfev <= 0:
+ raise ValueError("`max_nfev` must be None or positive integer.")
+
+ if np.iscomplexobj(x0):
+ raise ValueError("`x0` must be real.")
+
+ x0 = np.atleast_1d(x0).astype(float)
+
+ if x0.ndim > 1:
+ raise ValueError("`x0` must have at most 1 dimension.")
+
+ if isinstance(bounds, Bounds):
+ lb, ub = bounds.lb, bounds.ub
+ bounds = (lb, ub)
+ else:
+ if len(bounds) == 2:
+ lb, ub = prepare_bounds(bounds, x0.shape[0])
+ else:
+ raise ValueError("`bounds` must contain 2 elements.")
+
+ if method == 'lm' and not np.all((lb == -np.inf) & (ub == np.inf)):
+ raise ValueError("Method 'lm' doesn't support bounds.")
+
+ if lb.shape != x0.shape or ub.shape != x0.shape:
+ raise ValueError("Inconsistent shapes between bounds and `x0`.")
+
+ if np.any(lb >= ub):
+ raise ValueError("Each lower bound must be strictly less than each "
+ "upper bound.")
+
+ if not in_bounds(x0, lb, ub):
+ raise ValueError("Initial guess is outside of provided bounds")
+
+ x_scale = check_x_scale(x_scale, x0, method)
+
+ ftol, xtol, gtol = check_tolerance(ftol, xtol, gtol, method)
+
+ if method == 'trf':
+ x0 = make_strictly_feasible(x0, lb, ub)
+
+ if tr_options is None:
+ tr_options = {}
+
+ ###########################################################################
+ # assemble VectorFunction
+ ###########################################################################
+ # first wrap the args/kwargs
+ fun_wrapped = _WrapArgsKwargs(fun, args=args, kwargs=kwargs)
+ jac_wrapped = jac
+ if callable(jac):
+ jac_wrapped = _WrapArgsKwargs(jac, args=args, kwargs=kwargs)
+
+ def _dummy_hess(x, *args):
+ # we don't care about Hessian evaluations
+ return x
+
+ vector_fun = VectorFunction(
+ fun_wrapped,
+ x0,
+ jac_wrapped,
+ _dummy_hess,
+ finite_diff_rel_step=diff_step,
+ finite_diff_jac_sparsity=jac_sparsity,
+ finite_diff_bounds=bounds,
+ workers=workers
+ )
+ ###########################################################################
+
+ f0 = vector_fun.fun(x0)
+ J0 = vector_fun.jac(x0)
+
+ if f0.ndim != 1:
+ raise ValueError("`fun` must return at most 1-d array_like. "
+ f"f0.shape: {f0.shape}")
+
+ if not np.all(np.isfinite(f0)):
+ raise ValueError("Residuals are not finite in the initial point.")
+
+ n = x0.size
+ m = f0.size
+
+ if method == 'lm' and m < n:
+ raise ValueError("Method 'lm' doesn't work when the number of "
+ "residuals is less than the number of variables.")
+
+ loss_function = construct_loss_function(m, loss, f_scale)
+ if callable(loss):
+ rho = loss_function(f0)
+ if rho.shape != (3, m):
+ raise ValueError("The return value of `loss` callable has wrong "
+ "shape.")
+ initial_cost = 0.5 * np.sum(rho[0])
+ elif loss_function is not None:
+ initial_cost = loss_function(f0, cost_only=True)
+ else:
+ initial_cost = 0.5 * np.dot(f0, f0)
+
+ if not callable(jac):
+ # Estimate Jacobian by finite differences.
+ if method == 'lm':
+ if jac_sparsity is not None:
+ raise ValueError("method='lm' does not support "
+ "`jac_sparsity`.")
+ else:
+ # this will raise a ValueError if the jac_sparsity isn't correct
+ _ = check_jac_sparsity(jac_sparsity, m, n)
+
+ if jac_sparsity is not None and tr_solver == 'exact':
+ raise ValueError("tr_solver='exact' is incompatible "
+ "with `jac_sparsity`.")
+
+ if J0.shape != (m, n):
+ raise ValueError(
+ f"The return value of `jac` has wrong shape: expected {(m, n)}, "
+ f"actual {J0.shape}."
+ )
+
+ if not isinstance(J0, np.ndarray):
+ if method == 'lm':
+ raise ValueError("method='lm' works only with dense "
+ "Jacobian matrices.")
+
+ if tr_solver == 'exact':
+ raise ValueError(
+ "tr_solver='exact' works only with dense "
+ "Jacobian matrices.")
+
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
+ if isinstance(J0, LinearOperator) and jac_scale:
+ raise ValueError("x_scale='jac' can't be used when `jac` "
+ "returns LinearOperator.")
+
+ if tr_solver is None:
+ if isinstance(J0, np.ndarray):
+ tr_solver = 'exact'
+ else:
+ tr_solver = 'lsmr'
+
+ # Wrap callback function. If callback is None, callback_wrapped also is None
+ callback_wrapped = _wrap_callback(callback)
+
+ if method == 'lm':
+ if callback is not None:
+ warn("Callback function specified, but not supported with `lm` method.",
+ stacklevel=2)
+ result = call_minpack(vector_fun.fun, x0, vector_fun.jac, ftol, xtol, gtol,
+ max_nfev, x_scale, jac_method=jac)
+
+ elif method == 'trf':
+ result = trf(vector_fun.fun, vector_fun.jac, x0, f0, J0, lb, ub, ftol, xtol,
+ gtol, max_nfev, x_scale, loss_function, tr_solver,
+ tr_options.copy(), verbose, callback=callback_wrapped)
+
+ elif method == 'dogbox':
+ if tr_solver == 'lsmr' and 'regularize' in tr_options:
+ warn("The keyword 'regularize' in `tr_options` is not relevant "
+ "for 'dogbox' method.",
+ stacklevel=2)
+ tr_options = tr_options.copy()
+ del tr_options['regularize']
+
+ result = dogbox(vector_fun.fun, vector_fun.jac, x0, f0, J0, lb, ub, ftol,
+ xtol, gtol, max_nfev, x_scale, loss_function,
+ tr_solver, tr_options, verbose, callback=callback_wrapped)
+
+ result.message = TERMINATION_MESSAGES[result.status]
+ result.success = result.status > 0
+
+ if verbose >= 1:
+ print(result.message)
+ print(f"Function evaluations {result.nfev}, initial cost {initial_cost:.4e}, "
+ f"final cost {result.cost:.4e}, "
+ f"first-order optimality {result.optimality:.2e}.")
+
+ return result
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/lsq_linear.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/lsq_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..a8d7c8e09d0b55ee0e7a939b206c102a6f069bdb
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/lsq_linear.py
@@ -0,0 +1,361 @@
+"""Linear least squares with bound constraints on independent variables."""
+import numpy as np
+from numpy.linalg import norm
+from scipy.sparse import issparse, csr_array
+from scipy.sparse.linalg import LinearOperator, lsmr
+from scipy.optimize import OptimizeResult
+from scipy.optimize._minimize import Bounds
+
+from .common import in_bounds, compute_grad
+from .trf_linear import trf_linear
+from .bvls import bvls
+
+
+def prepare_bounds(bounds, n):
+ if len(bounds) != 2:
+ raise ValueError("`bounds` must contain 2 elements.")
+ lb, ub = (np.asarray(b, dtype=float) for b in bounds)
+
+ if lb.ndim == 0:
+ lb = np.resize(lb, n)
+
+ if ub.ndim == 0:
+ ub = np.resize(ub, n)
+
+ return lb, ub
+
+
+TERMINATION_MESSAGES = {
+ -1: "The algorithm was not able to make progress on the last iteration.",
+ 0: "The maximum number of iterations is exceeded.",
+ 1: "The first-order optimality measure is less than `tol`.",
+ 2: "The relative change of the cost function is less than `tol`.",
+ 3: "The unconstrained solution is optimal."
+}
+
+
+def lsq_linear(A, b, bounds=(-np.inf, np.inf), method='trf', tol=1e-10,
+ lsq_solver=None, lsmr_tol=None, max_iter=None,
+ verbose=0, *, lsmr_maxiter=None,):
+ r"""Solve a linear least-squares problem with bounds on the variables.
+
+ Given an m-by-n design matrix A and a target vector b with m elements,
+ `lsq_linear` solves the following optimization problem::
+
+ minimize 0.5 * ||A x - b||**2
+ subject to lb <= x <= ub
+
+ This optimization problem is convex, hence a found minimum (if iterations
+ have converged) is guaranteed to be global.
+
+ Parameters
+ ----------
+ A : array_like, sparse array or LinearOperator, shape (m, n)
+ Design matrix. Can be `scipy.sparse.linalg.LinearOperator`.
+ b : array_like, shape (m,)
+ Target vector.
+ bounds : 2-tuple of array_like or `Bounds`, optional
+ Lower and upper bounds on parameters. Defaults to no bounds.
+ There are two ways to specify the bounds:
+
+ - Instance of `Bounds` class.
+ - 2-tuple of array_like: Each element of the tuple must be either
+ an array with the length equal to the number of parameters, or a
+ scalar (in which case the bound is taken to be the same for all
+ parameters). Use ``np.inf`` with an appropriate sign to disable
+ bounds on all or some parameters.
+
+ method : 'trf' or 'bvls', optional
+ Method to perform minimization.
+
+ * 'trf' : Trust Region Reflective algorithm adapted for a linear
+ least-squares problem. This is an interior-point-like method
+ and the required number of iterations is weakly correlated with
+ the number of variables.
+ * 'bvls' : Bounded-variable least-squares algorithm. This is
+ an active set method, which requires the number of iterations
+ comparable to the number of variables. Can't be used when `A` is
+ sparse or LinearOperator.
+
+ Default is 'trf'.
+ tol : float, optional
+ Tolerance parameter. The algorithm terminates if a relative change
+ of the cost function is less than `tol` on the last iteration.
+ Additionally, the first-order optimality measure is considered:
+
+ * ``method='trf'`` terminates if the uniform norm of the gradient,
+ scaled to account for the presence of the bounds, is less than
+ `tol`.
+ * ``method='bvls'`` terminates if Karush-Kuhn-Tucker conditions
+ are satisfied within `tol` tolerance.
+
+ lsq_solver : {None, 'exact', 'lsmr'}, optional
+ Method of solving unbounded least-squares problems throughout
+ iterations:
+
+ * 'exact' : Use dense QR or SVD decomposition approach. Can't be
+ used when `A` is sparse or LinearOperator.
+ * 'lsmr' : Use `scipy.sparse.linalg.lsmr` iterative procedure
+ which requires only matrix-vector product evaluations. Can't
+ be used with ``method='bvls'``.
+
+ If None (default), the solver is chosen based on type of `A`.
+ lsmr_tol : None, float or 'auto', optional
+ Tolerance parameters 'atol' and 'btol' for `scipy.sparse.linalg.lsmr`
+ If None (default), it is set to ``1e-2 * tol``. If 'auto', the
+ tolerance will be adjusted based on the optimality of the current
+ iterate, which can speed up the optimization process, but is not always
+ reliable.
+ max_iter : None or int, optional
+ Maximum number of iterations before termination. If None (default), it
+ is set to 100 for ``method='trf'`` or to the number of variables for
+ ``method='bvls'`` (not counting iterations for 'bvls' initialization).
+ verbose : {0, 1, 2}, optional
+ Level of algorithm's verbosity:
+
+ * 0 : work silently (default).
+ * 1 : display a termination report.
+ * 2 : display progress during iterations.
+
+ lsmr_maxiter : None or int, optional
+ Maximum number of iterations for the lsmr least squares solver,
+ if it is used (by setting ``lsq_solver='lsmr'``). If None (default), it
+ uses lsmr's default of ``min(m, n)`` where ``m`` and ``n`` are the
+ number of rows and columns of `A`, respectively. Has no effect if
+ ``lsq_solver='exact'``.
+
+ Returns
+ -------
+ OptimizeResult with the following fields defined:
+ x : ndarray, shape (n,)
+ Solution found.
+ cost : float
+ Value of the cost function at the solution.
+ fun : ndarray, shape (m,)
+ Vector of residuals at the solution.
+ optimality : float
+ First-order optimality measure. The exact meaning depends on `method`,
+ refer to the description of `tol` parameter.
+ active_mask : ndarray of int, shape (n,)
+ Each component shows whether a corresponding constraint is active
+ (that is, whether a variable is at the bound):
+
+ * 0 : a constraint is not active.
+ * -1 : a lower bound is active.
+ * 1 : an upper bound is active.
+
+ Might be somewhat arbitrary for the `trf` method as it generates a
+ sequence of strictly feasible iterates and active_mask is determined
+ within a tolerance threshold.
+ unbounded_sol : tuple
+ Unbounded least squares solution tuple returned by the least squares
+ solver (set with `lsq_solver` option). If `lsq_solver` is not set or is
+ set to ``'exact'``, the tuple contains an ndarray of shape (n,) with
+ the unbounded solution, an ndarray with the sum of squared residuals,
+ an int with the rank of `A`, and an ndarray with the singular values
+ of `A` (see NumPy's ``linalg.lstsq`` for more information). If
+ `lsq_solver` is set to ``'lsmr'``, the tuple contains an ndarray of
+ shape (n,) with the unbounded solution, an int with the exit code,
+ an int with the number of iterations, and five floats with
+ various norms and the condition number of `A` (see SciPy's
+ ``sparse.linalg.lsmr`` for more information). This output can be
+ useful for determining the convergence of the least squares solver,
+ particularly the iterative ``'lsmr'`` solver. The unbounded least
+ squares problem is to minimize ``0.5 * ||A x - b||**2``.
+ nit : int
+ Number of iterations. Zero if the unconstrained solution is optimal.
+ status : int
+ Reason for algorithm termination:
+
+ * -1 : the algorithm was not able to make progress on the last
+ iteration.
+ * 0 : the maximum number of iterations is exceeded.
+ * 1 : the first-order optimality measure is less than `tol`.
+ * 2 : the relative change of the cost function is less than `tol`.
+ * 3 : the unconstrained solution is optimal.
+
+ message : str
+ Verbal description of the termination reason.
+ success : bool
+ True if one of the convergence criteria is satisfied (`status` > 0).
+
+ See Also
+ --------
+ nnls : Linear least squares with non-negativity constraint.
+ least_squares : Nonlinear least squares with bounds on the variables.
+
+ Notes
+ -----
+ The algorithm first computes the unconstrained least-squares solution by
+ `numpy.linalg.lstsq` or `scipy.sparse.linalg.lsmr` depending on
+ `lsq_solver`. This solution is returned as optimal if it lies within the
+ bounds.
+
+ Method 'trf' runs the adaptation of the algorithm described in [STIR]_ for
+ a linear least-squares problem. The iterations are essentially the same as
+ in the nonlinear least-squares algorithm, but as the quadratic function
+ model is always accurate, we don't need to track or modify the radius of
+ a trust region. The line search (backtracking) is used as a safety net
+ when a selected step does not decrease the cost function. Read more
+ detailed description of the algorithm in `scipy.optimize.least_squares`.
+
+ Method 'bvls' runs a Python implementation of the algorithm described in
+ [BVLS]_. The algorithm maintains active and free sets of variables, on
+ each iteration chooses a new variable to move from the active set to the
+ free set and then solves the unconstrained least-squares problem on free
+ variables. This algorithm is guaranteed to give an accurate solution
+ eventually, but may require up to n iterations for a problem with n
+ variables. Additionally, an ad-hoc initialization procedure is
+ implemented, that determines which variables to set free or active
+ initially. It takes some number of iterations before actual BVLS starts,
+ but can significantly reduce the number of further iterations.
+
+ References
+ ----------
+ .. [STIR] M. A. Branch, T. F. Coleman, and Y. Li, "A Subspace, Interior,
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
+ Minimization Problems," SIAM Journal on Scientific Computing,
+ Vol. 21, Number 1, pp 1-23, 1999.
+ .. [BVLS] P. B. Start and R. L. Parker, "Bounded-Variable Least-Squares:
+ an Algorithm and Applications", Computational Statistics, 10,
+ 129-141, 1995.
+
+ Examples
+ --------
+ In this example, a problem with a large sparse arrays and bounds on the
+ variables is solved.
+
+ >>> import numpy as np
+ >>> from scipy.sparse import random_array
+ >>> from scipy.optimize import lsq_linear
+ >>> rng = np.random.default_rng()
+ ...
+ >>> m = 2000
+ >>> n = 1000
+ ...
+ >>> A = random_array((m, n), density=1e-4, random_state=rng)
+ >>> b = rng.standard_normal(m)
+ ...
+ >>> lb = rng.standard_normal(n)
+ >>> ub = lb + 1
+ ...
+ >>> res = lsq_linear(A, b, bounds=(lb, ub), lsmr_tol='auto', verbose=1)
+ The relative change of the cost function is less than `tol`.
+ Number of iterations 10, initial cost 1.0070e+03, final cost 9.6602e+02,
+ first-order optimality 2.21e-09. # may vary
+ """
+ if method not in ['trf', 'bvls']:
+ raise ValueError("`method` must be 'trf' or 'bvls'")
+
+ if lsq_solver not in [None, 'exact', 'lsmr']:
+ raise ValueError("`solver` must be None, 'exact' or 'lsmr'.")
+
+ if verbose not in [0, 1, 2]:
+ raise ValueError("`verbose` must be in [0, 1, 2].")
+
+ if issparse(A):
+ A = csr_array(A)
+ elif not isinstance(A, LinearOperator):
+ A = np.atleast_2d(np.asarray(A))
+
+ if method == 'bvls':
+ if lsq_solver == 'lsmr':
+ raise ValueError("method='bvls' can't be used with "
+ "lsq_solver='lsmr'")
+
+ if not isinstance(A, np.ndarray):
+ raise ValueError("method='bvls' can't be used with `A` being "
+ "sparse or LinearOperator.")
+
+ if lsq_solver is None:
+ if isinstance(A, np.ndarray):
+ lsq_solver = 'exact'
+ else:
+ lsq_solver = 'lsmr'
+ elif lsq_solver == 'exact' and not isinstance(A, np.ndarray):
+ raise ValueError("`exact` solver can't be used when `A` is "
+ "sparse or LinearOperator.")
+
+ if len(A.shape) != 2: # No ndim for LinearOperator.
+ raise ValueError("`A` must have at most 2 dimensions.")
+
+ if max_iter is not None and max_iter <= 0:
+ raise ValueError("`max_iter` must be None or positive integer.")
+
+ m, n = A.shape
+
+ b = np.atleast_1d(b)
+ if b.ndim != 1:
+ raise ValueError("`b` must have at most 1 dimension.")
+
+ if b.size != m:
+ raise ValueError("Inconsistent shapes between `A` and `b`.")
+
+ if isinstance(bounds, Bounds):
+ lb = bounds.lb
+ ub = bounds.ub
+ else:
+ lb, ub = prepare_bounds(bounds, n)
+
+ if lb.shape != (n,) and ub.shape != (n,):
+ raise ValueError("Bounds have wrong shape.")
+
+ if np.any(lb >= ub):
+ raise ValueError("Each lower bound must be strictly less than each "
+ "upper bound.")
+
+ if lsmr_maxiter is not None and lsmr_maxiter < 1:
+ raise ValueError("`lsmr_maxiter` must be None or positive integer.")
+
+ if not ((isinstance(lsmr_tol, float) and lsmr_tol > 0) or
+ lsmr_tol in ('auto', None)):
+ raise ValueError("`lsmr_tol` must be None, 'auto', or positive float.")
+
+ if lsq_solver == 'exact':
+ unbd_lsq = np.linalg.lstsq(A, b, rcond=-1)
+ elif lsq_solver == 'lsmr':
+ first_lsmr_tol = lsmr_tol # tol of first call to lsmr
+ if lsmr_tol is None or lsmr_tol == 'auto':
+ first_lsmr_tol = 1e-2 * tol # default if lsmr_tol not defined
+ unbd_lsq = lsmr(A, b, maxiter=lsmr_maxiter,
+ atol=first_lsmr_tol, btol=first_lsmr_tol)
+ x_lsq = unbd_lsq[0] # extract the solution from the least squares solver
+
+ if in_bounds(x_lsq, lb, ub):
+ r = A @ x_lsq - b
+ cost = 0.5 * np.dot(r, r)
+ termination_status = 3
+ termination_message = TERMINATION_MESSAGES[termination_status]
+ g = compute_grad(A, r)
+ g_norm = norm(g, ord=np.inf)
+
+ if verbose > 0:
+ print(termination_message)
+ print(f"Final cost {cost:.4e}, first-order optimality {g_norm:.2e}")
+
+ return OptimizeResult(
+ x=x_lsq, fun=r, cost=cost, optimality=g_norm,
+ active_mask=np.zeros(n), unbounded_sol=unbd_lsq,
+ nit=0, status=termination_status,
+ message=termination_message, success=True)
+
+ if method == 'trf':
+ res = trf_linear(A, b, x_lsq, lb, ub, tol, lsq_solver, lsmr_tol,
+ max_iter, verbose, lsmr_maxiter=lsmr_maxiter)
+ elif method == 'bvls':
+ res = bvls(A, b, x_lsq, lb, ub, tol, max_iter, verbose)
+
+ res.unbounded_sol = unbd_lsq
+ res.message = TERMINATION_MESSAGES[res.status]
+ res.success = res.status > 0
+
+ if verbose > 0:
+ print(res.message)
+ print(
+ f"Number of iterations {res.nit}, initial cost {res.initial_cost:.4e}, "
+ f"final cost {res.cost:.4e}, first-order optimality {res.optimality:.2e}."
+ )
+
+ del res.initial_cost
+
+ return res
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/trf.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/trf.py
new file mode 100644
index 0000000000000000000000000000000000000000..f17ec17a68fa7de88982dd8287c4fa8be635a14e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/trf.py
@@ -0,0 +1,587 @@
+"""Trust Region Reflective algorithm for least-squares optimization.
+
+The algorithm is based on ideas from paper [STIR]_. The main idea is to
+account for the presence of the bounds by appropriate scaling of the variables (or,
+equivalently, changing a trust-region shape). Let's introduce a vector v:
+
+ | ub[i] - x[i], if g[i] < 0 and ub[i] < np.inf
+ v[i] = | x[i] - lb[i], if g[i] > 0 and lb[i] > -np.inf
+ | 1, otherwise
+
+where g is the gradient of a cost function and lb, ub are the bounds. Its
+components are distances to the bounds at which the anti-gradient points (if
+this distance is finite). Define a scaling matrix D = diag(v**0.5).
+First-order optimality conditions can be stated as
+
+ D^2 g(x) = 0.
+
+Meaning that components of the gradient should be zero for strictly interior
+variables, and components must point inside the feasible region for variables
+on the bound.
+
+Now consider this system of equations as a new optimization problem. If the
+point x is strictly interior (not on the bound), then the left-hand side is
+differentiable and the Newton step for it satisfies
+
+ (D^2 H + diag(g) Jv) p = -D^2 g
+
+where H is the Hessian matrix (or its J^T J approximation in least squares),
+Jv is the Jacobian matrix of v with components -1, 1 or 0, such that all
+elements of matrix C = diag(g) Jv are non-negative. Introduce the change
+of the variables x = D x_h (_h would be "hat" in LaTeX). In the new variables,
+we have a Newton step satisfying
+
+ B_h p_h = -g_h,
+
+where B_h = D H D + C, g_h = D g. In least squares B_h = J_h^T J_h, where
+J_h = J D. Note that J_h and g_h are proper Jacobian and gradient with respect
+to "hat" variables. To guarantee global convergence we formulate a
+trust-region problem based on the Newton step in the new variables:
+
+ 0.5 * p_h^T B_h p + g_h^T p_h -> min, ||p_h|| <= Delta
+
+In the original space B = H + D^{-1} C D^{-1}, and the equivalent trust-region
+problem is
+
+ 0.5 * p^T B p + g^T p -> min, ||D^{-1} p|| <= Delta
+
+Here, the meaning of the matrix D becomes more clear: it alters the shape
+of a trust-region, such that large steps towards the bounds are not allowed.
+In the implementation, the trust-region problem is solved in "hat" space,
+but handling of the bounds is done in the original space (see below and read
+the code).
+
+The introduction of the matrix D doesn't allow to ignore bounds, the algorithm
+must keep iterates strictly feasible (to satisfy aforementioned
+differentiability), the parameter theta controls step back from the boundary
+(see the code for details).
+
+The algorithm does another important trick. If the trust-region solution
+doesn't fit into the bounds, then a reflected (from a firstly encountered
+bound) search direction is considered. For motivation and analysis refer to
+[STIR]_ paper (and other papers of the authors). In practice, it doesn't need
+a lot of justifications, the algorithm simply chooses the best step among
+three: a constrained trust-region step, a reflected step and a constrained
+Cauchy step (a minimizer along -g_h in "hat" space, or -D^2 g in the original
+space).
+
+Another feature is that a trust-region radius control strategy is modified to
+account for appearance of the diagonal C matrix (called diag_h in the code).
+
+Note that all described peculiarities are completely gone as we consider
+problems without bounds (the algorithm becomes a standard trust-region type
+algorithm very similar to ones implemented in MINPACK).
+
+The implementation supports two methods of solving the trust-region problem.
+The first, called 'exact', applies SVD on Jacobian and then solves the problem
+very accurately using the algorithm described in [JJMore]_. It is not
+applicable to large problem. The second, called 'lsmr', uses the 2-D subspace
+approach (sometimes called "indefinite dogleg"), where the problem is solved
+in a subspace spanned by the gradient and the approximate Gauss-Newton step
+found by ``scipy.sparse.linalg.lsmr``. A 2-D trust-region problem is
+reformulated as a 4th order algebraic equation and solved very accurately by
+``numpy.roots``. The subspace approach allows to solve very large problems
+(up to couple of millions of residuals on a regular PC), provided the Jacobian
+matrix is sufficiently sparse.
+
+References
+----------
+.. [STIR] Branch, M.A., T.F. Coleman, and Y. Li, "A Subspace, Interior,
+ and Conjugate Gradient Method for Large-Scale Bound-Constrained
+ Minimization Problems," SIAM Journal on Scientific Computing,
+ Vol. 21, Number 1, pp 1-23, 1999.
+.. [JJMore] More, J. J., "The Levenberg-Marquardt Algorithm: Implementation
+ and Theory," Numerical Analysis, ed. G. A. Watson, Lecture
+"""
+import numpy as np
+from numpy.linalg import norm
+from scipy.linalg import svd, qr
+from scipy.sparse.linalg import lsmr
+from scipy.optimize import OptimizeResult
+
+from .common import (
+ step_size_to_bound, find_active_constraints, in_bounds,
+ make_strictly_feasible, intersect_trust_region, solve_lsq_trust_region,
+ solve_trust_region_2d, minimize_quadratic_1d, build_quadratic_1d,
+ evaluate_quadratic, right_multiplied_operator, regularized_lsq_operator,
+ CL_scaling_vector, compute_grad, compute_jac_scale, check_termination,
+ update_tr_radius, scale_for_robust_loss_function, print_header_nonlinear,
+ print_iteration_nonlinear)
+from scipy._lib._util import _call_callback_maybe_halt
+
+
+def trf(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
+ loss_function, tr_solver, tr_options, verbose, callback=None):
+ # For efficiency, it makes sense to run the simplified version of the
+ # algorithm when no bounds are imposed. We decided to write the two
+ # separate functions. It violates the DRY principle, but the individual
+ # functions are kept the most readable.
+ if np.all(lb == -np.inf) and np.all(ub == np.inf):
+ return trf_no_bounds(
+ fun, jac, x0, f0, J0, ftol, xtol, gtol, max_nfev, x_scale,
+ loss_function, tr_solver, tr_options, verbose, callback=callback)
+ else:
+ return trf_bounds(
+ fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev, x_scale,
+ loss_function, tr_solver, tr_options, verbose, callback=callback)
+
+
+def select_step(x, J_h, diag_h, g_h, p, p_h, d, Delta, lb, ub, theta):
+ """Select the best step according to Trust Region Reflective algorithm."""
+ if in_bounds(x + p, lb, ub):
+ p_value = evaluate_quadratic(J_h, g_h, p_h, diag=diag_h)
+ return p, p_h, -p_value
+
+ p_stride, hits = step_size_to_bound(x, p, lb, ub)
+
+ # Compute the reflected direction.
+ r_h = np.copy(p_h)
+ r_h[hits.astype(bool)] *= -1
+ r = d * r_h
+
+ # Restrict trust-region step, such that it hits the bound.
+ p *= p_stride
+ p_h *= p_stride
+ x_on_bound = x + p
+
+ # Reflected direction will cross first either feasible region or trust
+ # region boundary.
+ _, to_tr = intersect_trust_region(p_h, r_h, Delta)
+ to_bound, _ = step_size_to_bound(x_on_bound, r, lb, ub)
+
+ # Find lower and upper bounds on a step size along the reflected
+ # direction, considering the strict feasibility requirement. There is no
+ # single correct way to do that, the chosen approach seems to work best
+ # on test problems.
+ r_stride = min(to_bound, to_tr)
+ if r_stride > 0:
+ r_stride_l = (1 - theta) * p_stride / r_stride
+ if r_stride == to_bound:
+ r_stride_u = theta * to_bound
+ else:
+ r_stride_u = to_tr
+ else:
+ r_stride_l = 0
+ r_stride_u = -1
+
+ # Check if reflection step is available.
+ if r_stride_l <= r_stride_u:
+ a, b, c = build_quadratic_1d(J_h, g_h, r_h, s0=p_h, diag=diag_h)
+ r_stride, r_value = minimize_quadratic_1d(
+ a, b, r_stride_l, r_stride_u, c=c)
+ r_h *= r_stride
+ r_h += p_h
+ r = r_h * d
+ else:
+ r_value = np.inf
+
+ # Now correct p_h to make it strictly interior.
+ p *= theta
+ p_h *= theta
+ p_value = evaluate_quadratic(J_h, g_h, p_h, diag=diag_h)
+
+ ag_h = -g_h
+ ag = d * ag_h
+
+ to_tr = Delta / norm(ag_h)
+ to_bound, _ = step_size_to_bound(x, ag, lb, ub)
+ if to_bound < to_tr:
+ ag_stride = theta * to_bound
+ else:
+ ag_stride = to_tr
+
+ a, b = build_quadratic_1d(J_h, g_h, ag_h, diag=diag_h)
+ ag_stride, ag_value = minimize_quadratic_1d(a, b, 0, ag_stride)
+ ag_h *= ag_stride
+ ag *= ag_stride
+
+ if p_value < r_value and p_value < ag_value:
+ return p, p_h, -p_value
+ elif r_value < p_value and r_value < ag_value:
+ return r, r_h, -r_value
+ else:
+ return ag, ag_h, -ag_value
+
+
+def trf_bounds(fun, jac, x0, f0, J0, lb, ub, ftol, xtol, gtol, max_nfev,
+ x_scale, loss_function, tr_solver, tr_options, verbose,
+ callback=None):
+ x = x0.copy()
+
+ f = f0
+ f_true = f.copy()
+ nfev = 1
+
+ J = J0
+ njev = 1
+ m, n = J.shape
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ cost = 0.5 * np.sum(rho[0])
+ J, f = scale_for_robust_loss_function(J, f, rho)
+ else:
+ cost = 0.5 * np.dot(f, f)
+
+ g = compute_grad(J, f)
+
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J)
+ else:
+ scale, scale_inv = x_scale, 1 / x_scale
+
+ v, dv = CL_scaling_vector(x, g, lb, ub)
+ v[dv != 0] *= scale_inv[dv != 0]
+ Delta = norm(x0 * scale_inv / v**0.5)
+ if Delta == 0:
+ Delta = 1.0
+
+ g_norm = norm(g * v, ord=np.inf)
+
+ f_augmented = np.zeros(m + n)
+ if tr_solver == 'exact':
+ J_augmented = np.empty((m + n, n))
+ elif tr_solver == 'lsmr':
+ reg_term = 0.0
+ regularize = tr_options.pop('regularize', True)
+
+ if max_nfev is None:
+ max_nfev = x0.size * 100
+
+ alpha = 0.0 # "Levenberg-Marquardt" parameter
+
+ termination_status = None
+ iteration = 0
+ step_norm = None
+ actual_reduction = None
+
+ if verbose == 2:
+ print_header_nonlinear()
+
+ while True:
+ v, dv = CL_scaling_vector(x, g, lb, ub)
+
+ g_norm = norm(g * v, ord=np.inf)
+ if g_norm < gtol:
+ termination_status = 1
+
+ if verbose == 2:
+ print_iteration_nonlinear(iteration, nfev, cost, actual_reduction,
+ step_norm, g_norm)
+
+ if termination_status is not None or nfev == max_nfev:
+ break
+
+ # Now compute variables in "hat" space. Here, we also account for
+ # scaling introduced by `x_scale` parameter. This part is a bit tricky,
+ # you have to write down the formulas and see how the trust-region
+ # problem is formulated when the two types of scaling are applied.
+ # The idea is that first we apply `x_scale` and then apply Coleman-Li
+ # approach in the new variables.
+
+ # v is recomputed in the variables after applying `x_scale`, note that
+ # components which were identically 1 not affected.
+ v[dv != 0] *= scale_inv[dv != 0]
+
+ # Here, we apply two types of scaling.
+ d = v**0.5 * scale
+
+ # C = diag(g * scale) Jv
+ diag_h = g * dv * scale
+
+ # After all this has been done, we continue normally.
+
+ # "hat" gradient.
+ g_h = d * g
+
+ f_augmented[:m] = f
+ if tr_solver == 'exact':
+ J_augmented[:m] = J * d
+ J_h = J_augmented[:m] # Memory view.
+ J_augmented[m:] = np.diag(diag_h**0.5)
+ U, s, V = svd(J_augmented, full_matrices=False)
+ V = V.T
+ uf = U.T.dot(f_augmented)
+ elif tr_solver == 'lsmr':
+ J_h = right_multiplied_operator(J, d)
+
+ if regularize:
+ a, b = build_quadratic_1d(J_h, g_h, -g_h, diag=diag_h)
+ to_tr = Delta / norm(g_h)
+ ag_value = minimize_quadratic_1d(a, b, 0, to_tr)[1]
+ reg_term = -ag_value / Delta**2
+
+ lsmr_op = regularized_lsq_operator(J_h, (diag_h + reg_term)**0.5)
+ gn_h = lsmr(lsmr_op, f_augmented, **tr_options)[0]
+ S = np.vstack((g_h, gn_h)).T
+ S, _ = qr(S, mode='economic')
+ JS = J_h.dot(S) # LinearOperator does dot too.
+ B_S = np.dot(JS.T, JS) + np.dot(S.T * diag_h, S)
+ g_S = S.T.dot(g_h)
+
+ # theta controls step back step ratio from the bounds.
+ theta = max(0.995, 1 - g_norm)
+
+ actual_reduction = -1
+ while actual_reduction <= 0 and nfev < max_nfev:
+ if tr_solver == 'exact':
+ p_h, alpha, n_iter = solve_lsq_trust_region(
+ n, m, uf, s, V, Delta, initial_alpha=alpha)
+ elif tr_solver == 'lsmr':
+ p_S, _ = solve_trust_region_2d(B_S, g_S, Delta)
+ p_h = S.dot(p_S)
+
+ p = d * p_h # Trust-region solution in the original space.
+ step, step_h, predicted_reduction = select_step(
+ x, J_h, diag_h, g_h, p, p_h, d, Delta, lb, ub, theta)
+
+ x_new = make_strictly_feasible(x + step, lb, ub, rstep=0)
+ f_new = fun(x_new)
+ nfev += 1
+
+ step_h_norm = norm(step_h)
+
+ if not np.all(np.isfinite(f_new)):
+ Delta = 0.25 * step_h_norm
+ continue
+
+ # Usual trust-region step quality estimation.
+ if loss_function is not None:
+ cost_new = loss_function(f_new, cost_only=True)
+ else:
+ cost_new = 0.5 * np.dot(f_new, f_new)
+ actual_reduction = cost - cost_new
+ Delta_new, ratio = update_tr_radius(
+ Delta, actual_reduction, predicted_reduction,
+ step_h_norm, step_h_norm > 0.95 * Delta)
+
+ step_norm = norm(step)
+ termination_status = check_termination(
+ actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol)
+ if termination_status is not None:
+ break
+
+ alpha *= Delta / Delta_new
+ Delta = Delta_new
+
+ if actual_reduction > 0:
+ x = x_new
+
+ f = f_new
+ f_true = f.copy()
+
+ cost = cost_new
+
+ J = jac(x)
+ njev += 1
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ J, f = scale_for_robust_loss_function(J, f, rho)
+
+ g = compute_grad(J, f)
+
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J, scale_inv)
+ else:
+ step_norm = 0
+ actual_reduction = 0
+
+ iteration += 1
+
+ # Call callback function and possibly stop optimization
+ if callback is not None:
+ intermediate_result = OptimizeResult(
+ x=x, fun=f_true, nit=iteration, nfev=nfev)
+ intermediate_result["cost"] = cost
+
+ if _call_callback_maybe_halt(
+ callback, intermediate_result
+ ):
+ termination_status = -2
+ break
+
+ if termination_status is None:
+ termination_status = 0
+
+ active_mask = find_active_constraints(x, lb, ub, rtol=xtol)
+ return OptimizeResult(
+ x=x, cost=cost, fun=f_true, jac=J, grad=g, optimality=g_norm,
+ active_mask=active_mask, nfev=nfev, njev=njev,
+ status=termination_status)
+
+
+def trf_no_bounds(fun, jac, x0, f0, J0, ftol, xtol, gtol, max_nfev,
+ x_scale, loss_function, tr_solver, tr_options, verbose,
+ callback=None):
+ x = x0.copy()
+
+ f = f0
+ f_true = f.copy()
+ nfev = 1
+
+ J = J0
+ njev = 1
+ m, n = J.shape
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ cost = 0.5 * np.sum(rho[0])
+ J, f = scale_for_robust_loss_function(J, f, rho)
+ else:
+ cost = 0.5 * np.dot(f, f)
+
+ g = compute_grad(J, f)
+
+ jac_scale = isinstance(x_scale, str) and x_scale == 'jac'
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J)
+ else:
+ scale, scale_inv = x_scale, 1 / x_scale
+
+ Delta = norm(x0 * scale_inv)
+ if Delta == 0:
+ Delta = 1.0
+
+ if tr_solver == 'lsmr':
+ reg_term = 0
+ damp = tr_options.pop('damp', 0.0)
+ regularize = tr_options.pop('regularize', True)
+
+ if max_nfev is None:
+ max_nfev = x0.size * 100
+
+ alpha = 0.0 # "Levenberg-Marquardt" parameter
+
+ termination_status = None
+ iteration = 0
+ step_norm = None
+ actual_reduction = None
+
+ if verbose == 2:
+ print_header_nonlinear()
+
+ while True:
+ g_norm = norm(g, ord=np.inf)
+ if g_norm < gtol:
+ termination_status = 1
+
+ if verbose == 2:
+ print_iteration_nonlinear(iteration, nfev, cost, actual_reduction,
+ step_norm, g_norm)
+
+ if termination_status is not None or nfev == max_nfev:
+ break
+
+ d = scale
+ g_h = d * g
+
+ if tr_solver == 'exact':
+ J_h = J * d
+ U, s, V = svd(J_h, full_matrices=False)
+ V = V.T
+ uf = U.T.dot(f)
+ elif tr_solver == 'lsmr':
+ J_h = right_multiplied_operator(J, d)
+
+ if regularize:
+ a, b = build_quadratic_1d(J_h, g_h, -g_h)
+ to_tr = Delta / norm(g_h)
+ ag_value = minimize_quadratic_1d(a, b, 0, to_tr)[1]
+ reg_term = -ag_value / Delta**2
+
+ damp_full = (damp**2 + reg_term)**0.5
+ gn_h = lsmr(J_h, f, damp=damp_full, **tr_options)[0]
+ S = np.vstack((g_h, gn_h)).T
+ S, _ = qr(S, mode='economic')
+ JS = J_h.dot(S)
+ B_S = np.dot(JS.T, JS)
+ g_S = S.T.dot(g_h)
+
+ actual_reduction = -1
+ while actual_reduction <= 0 and nfev < max_nfev:
+ if tr_solver == 'exact':
+ step_h, alpha, n_iter = solve_lsq_trust_region(
+ n, m, uf, s, V, Delta, initial_alpha=alpha)
+ elif tr_solver == 'lsmr':
+ p_S, _ = solve_trust_region_2d(B_S, g_S, Delta)
+ step_h = S.dot(p_S)
+
+ predicted_reduction = -evaluate_quadratic(J_h, g_h, step_h)
+ step = d * step_h
+ x_new = x + step
+ f_new = fun(x_new)
+ nfev += 1
+
+ step_h_norm = norm(step_h)
+
+ if not np.all(np.isfinite(f_new)):
+ Delta = 0.25 * step_h_norm
+ continue
+
+ # Usual trust-region step quality estimation.
+ if loss_function is not None:
+ cost_new = loss_function(f_new, cost_only=True)
+ else:
+ cost_new = 0.5 * np.dot(f_new, f_new)
+ actual_reduction = cost - cost_new
+
+ Delta_new, ratio = update_tr_radius(
+ Delta, actual_reduction, predicted_reduction,
+ step_h_norm, step_h_norm > 0.95 * Delta)
+
+ step_norm = norm(step)
+ termination_status = check_termination(
+ actual_reduction, cost, step_norm, norm(x), ratio, ftol, xtol)
+ if termination_status is not None:
+ break
+
+ alpha *= Delta / Delta_new
+ Delta = Delta_new
+
+ if actual_reduction > 0:
+ x = x_new
+
+ f = f_new
+ f_true = f.copy()
+
+ cost = cost_new
+
+ J = jac(x)
+ njev += 1
+
+ if loss_function is not None:
+ rho = loss_function(f)
+ J, f = scale_for_robust_loss_function(J, f, rho)
+
+ g = compute_grad(J, f)
+
+ if jac_scale:
+ scale, scale_inv = compute_jac_scale(J, scale_inv)
+ else:
+ step_norm = 0
+ actual_reduction = 0
+
+ iteration += 1
+
+ # Call callback function and possibly stop optimization
+ if callback is not None:
+ intermediate_result = OptimizeResult(
+ x=x, fun=f_true, nit=iteration, nfev=nfev)
+ intermediate_result["cost"] = cost
+
+ if _call_callback_maybe_halt(
+ callback, intermediate_result
+ ):
+ termination_status = -2
+ break
+
+ if termination_status is None:
+ termination_status = 0
+
+ active_mask = np.zeros_like(x)
+ return OptimizeResult(
+ x=x, cost=cost, fun=f_true, jac=J, grad=g, optimality=g_norm,
+ active_mask=active_mask, nfev=nfev, njev=njev,
+ status=termination_status)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/trf_linear.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/trf_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..dd752763179bcf97945c7f34ce6a9e49e85c819e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_lsq/trf_linear.py
@@ -0,0 +1,249 @@
+"""The adaptation of Trust Region Reflective algorithm for a linear
+least-squares problem."""
+import numpy as np
+from numpy.linalg import norm
+from scipy.linalg import qr, solve_triangular
+from scipy.sparse.linalg import lsmr
+from scipy.optimize import OptimizeResult
+
+from .givens_elimination import givens_elimination
+from .common import (
+ EPS, step_size_to_bound, find_active_constraints, in_bounds,
+ make_strictly_feasible, build_quadratic_1d, evaluate_quadratic,
+ minimize_quadratic_1d, CL_scaling_vector, reflective_transformation,
+ print_header_linear, print_iteration_linear, compute_grad,
+ regularized_lsq_operator, right_multiplied_operator)
+
+
+def regularized_lsq_with_qr(m, n, R, QTb, perm, diag, copy_R=True):
+ """Solve regularized least squares using information from QR-decomposition.
+
+ The initial problem is to solve the following system in a least-squares
+ sense::
+
+ A x = b
+ D x = 0
+
+ where D is diagonal matrix. The method is based on QR decomposition
+ of the form A P = Q R, where P is a column permutation matrix, Q is an
+ orthogonal matrix and R is an upper triangular matrix.
+
+ Parameters
+ ----------
+ m, n : int
+ Initial shape of A.
+ R : ndarray, shape (n, n)
+ Upper triangular matrix from QR decomposition of A.
+ QTb : ndarray, shape (n,)
+ First n components of Q^T b.
+ perm : ndarray, shape (n,)
+ Array defining column permutation of A, such that ith column of
+ P is perm[i]-th column of identity matrix.
+ diag : ndarray, shape (n,)
+ Array containing diagonal elements of D.
+
+ Returns
+ -------
+ x : ndarray, shape (n,)
+ Found least-squares solution.
+ """
+ if copy_R:
+ R = R.copy()
+ v = QTb.copy()
+
+ givens_elimination(R, v, diag[perm])
+
+ abs_diag_R = np.abs(np.diag(R))
+ threshold = EPS * max(m, n) * np.max(abs_diag_R)
+ nns, = np.nonzero(abs_diag_R > threshold)
+
+ R = R[np.ix_(nns, nns)]
+ v = v[nns]
+
+ x = np.zeros(n)
+ x[perm[nns]] = solve_triangular(R, v)
+
+ return x
+
+
+def backtracking(A, g, x, p, theta, p_dot_g, lb, ub):
+ """Find an appropriate step size using backtracking line search."""
+ alpha = 1
+ while True:
+ x_new, _ = reflective_transformation(x + alpha * p, lb, ub)
+ step = x_new - x
+ cost_change = -evaluate_quadratic(A, g, step)
+ if cost_change > -0.1 * alpha * p_dot_g:
+ break
+ alpha *= 0.5
+
+ active = find_active_constraints(x_new, lb, ub)
+ if np.any(active != 0):
+ x_new, _ = reflective_transformation(x + theta * alpha * p, lb, ub)
+ x_new = make_strictly_feasible(x_new, lb, ub, rstep=0)
+ step = x_new - x
+ cost_change = -evaluate_quadratic(A, g, step)
+
+ return x, step, cost_change
+
+
+def select_step(x, A_h, g_h, c_h, p, p_h, d, lb, ub, theta):
+ """Select the best step according to Trust Region Reflective algorithm."""
+ if in_bounds(x + p, lb, ub):
+ return p
+
+ p_stride, hits = step_size_to_bound(x, p, lb, ub)
+ r_h = np.copy(p_h)
+ r_h[hits.astype(bool)] *= -1
+ r = d * r_h
+
+ # Restrict step, such that it hits the bound.
+ p *= p_stride
+ p_h *= p_stride
+ x_on_bound = x + p
+
+ # Find the step size along reflected direction.
+ r_stride_u, _ = step_size_to_bound(x_on_bound, r, lb, ub)
+
+ # Stay interior.
+ r_stride_l = (1 - theta) * r_stride_u
+ r_stride_u *= theta
+
+ if r_stride_u > 0:
+ a, b, c = build_quadratic_1d(A_h, g_h, r_h, s0=p_h, diag=c_h)
+ r_stride, r_value = minimize_quadratic_1d(
+ a, b, r_stride_l, r_stride_u, c=c)
+ r_h = p_h + r_h * r_stride
+ r = d * r_h
+ else:
+ r_value = np.inf
+
+ # Now correct p_h to make it strictly interior.
+ p_h *= theta
+ p *= theta
+ p_value = evaluate_quadratic(A_h, g_h, p_h, diag=c_h)
+
+ ag_h = -g_h
+ ag = d * ag_h
+ ag_stride_u, _ = step_size_to_bound(x, ag, lb, ub)
+ ag_stride_u *= theta
+ a, b = build_quadratic_1d(A_h, g_h, ag_h, diag=c_h)
+ ag_stride, ag_value = minimize_quadratic_1d(a, b, 0, ag_stride_u)
+ ag *= ag_stride
+
+ if p_value < r_value and p_value < ag_value:
+ return p
+ elif r_value < p_value and r_value < ag_value:
+ return r
+ else:
+ return ag
+
+
+def trf_linear(A, b, x_lsq, lb, ub, tol, lsq_solver, lsmr_tol,
+ max_iter, verbose, *, lsmr_maxiter=None):
+ m, n = A.shape
+ x, _ = reflective_transformation(x_lsq, lb, ub)
+ x = make_strictly_feasible(x, lb, ub, rstep=0.1)
+
+ if lsq_solver == 'exact':
+ QT, R, perm = qr(A, mode='economic', pivoting=True)
+ QT = QT.T
+
+ if m < n:
+ R = np.vstack((R, np.zeros((n - m, n))))
+
+ QTr = np.zeros(n)
+ k = min(m, n)
+ elif lsq_solver == 'lsmr':
+ r_aug = np.zeros(m + n)
+ auto_lsmr_tol = False
+ if lsmr_tol is None:
+ lsmr_tol = 1e-2 * tol
+ elif lsmr_tol == 'auto':
+ auto_lsmr_tol = True
+
+ r = A.dot(x) - b
+ g = compute_grad(A, r)
+ cost = 0.5 * np.dot(r, r)
+ initial_cost = cost
+
+ termination_status = None
+ step_norm = None
+ cost_change = None
+
+ if max_iter is None:
+ max_iter = 100
+
+ if verbose == 2:
+ print_header_linear()
+
+ for iteration in range(max_iter):
+ v, dv = CL_scaling_vector(x, g, lb, ub)
+ g_scaled = g * v
+ g_norm = norm(g_scaled, ord=np.inf)
+ if g_norm < tol:
+ termination_status = 1
+
+ if verbose == 2:
+ print_iteration_linear(iteration, cost, cost_change,
+ step_norm, g_norm)
+
+ if termination_status is not None:
+ break
+
+ diag_h = g * dv
+ diag_root_h = diag_h ** 0.5
+ d = v ** 0.5
+ g_h = d * g
+
+ A_h = right_multiplied_operator(A, d)
+ if lsq_solver == 'exact':
+ QTr[:k] = QT.dot(r)
+ p_h = -regularized_lsq_with_qr(m, n, R * d[perm], QTr, perm,
+ diag_root_h, copy_R=False)
+ elif lsq_solver == 'lsmr':
+ lsmr_op = regularized_lsq_operator(A_h, diag_root_h)
+ r_aug[:m] = r
+ if auto_lsmr_tol:
+ eta = 1e-2 * min(0.5, g_norm)
+ lsmr_tol = max(EPS, min(0.1, eta * g_norm))
+ p_h = -lsmr(lsmr_op, r_aug, maxiter=lsmr_maxiter,
+ atol=lsmr_tol, btol=lsmr_tol)[0]
+
+ p = d * p_h
+
+ p_dot_g = np.dot(p, g)
+ if p_dot_g > 0:
+ termination_status = -1
+
+ theta = 1 - min(0.005, g_norm)
+ step = select_step(x, A_h, g_h, diag_h, p, p_h, d, lb, ub, theta)
+ cost_change = -evaluate_quadratic(A, g, step)
+
+ # Perhaps almost never executed, the idea is that `p` is descent
+ # direction thus we must find acceptable cost decrease using simple
+ # "backtracking", otherwise the algorithm's logic would break.
+ if cost_change < 0:
+ x, step, cost_change = backtracking(
+ A, g, x, p, theta, p_dot_g, lb, ub)
+ else:
+ x = make_strictly_feasible(x + step, lb, ub, rstep=0)
+
+ step_norm = norm(step)
+ r = A.dot(x) - b
+ g = compute_grad(A, r)
+
+ if cost_change < tol * cost:
+ termination_status = 2
+
+ cost = 0.5 * np.dot(r, r)
+
+ if termination_status is None:
+ termination_status = 0
+
+ active_mask = find_active_constraints(x, lb, ub, rtol=tol)
+
+ return OptimizeResult(
+ x=x, fun=r, cost=cost, optimality=g_norm, active_mask=active_mask,
+ nit=iteration + 1, status=termination_status,
+ initial_cost=initial_cost)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_milp.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_milp.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9c793fba39fbbc98b86449fc2fd76084cd8d146
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_milp.py
@@ -0,0 +1,394 @@
+import warnings
+
+import numpy as np
+from numpy.exceptions import VisibleDeprecationWarning
+
+from scipy.sparse import csc_array, vstack, issparse
+from ._highspy._highs_wrapper import _highs_wrapper # type: ignore[import-not-found,import-untyped]
+from ._constraints import LinearConstraint, Bounds
+from ._optimize import OptimizeResult
+from ._linprog_highs import _highs_to_scipy_status_message
+
+
+def _constraints_to_components(constraints):
+ """
+ Convert sequence of constraints to a single set of components A, b_l, b_u.
+
+ `constraints` could be
+
+ 1. A LinearConstraint
+ 2. A tuple representing a LinearConstraint
+ 3. An invalid object
+ 4. A sequence of composed entirely of objects of type 1/2
+ 5. A sequence containing at least one object of type 3
+
+ We want to accept 1, 2, and 4 and reject 3 and 5.
+ """
+ message = ("`constraints` (or each element within `constraints`) must be "
+ "convertible into an instance of "
+ "`scipy.optimize.LinearConstraint`.")
+ As = []
+ b_ls = []
+ b_us = []
+
+ # Accept case 1 by standardizing as case 4
+ if isinstance(constraints, LinearConstraint):
+ constraints = [constraints]
+ else:
+ # Reject case 3
+ try:
+ iter(constraints)
+ except TypeError as exc:
+ raise ValueError(message) from exc
+
+ # Accept case 2 by standardizing as case 4
+ if len(constraints) == 3:
+ # argument could be a single tuple representing a LinearConstraint
+ try:
+ constraints = [LinearConstraint(*constraints)]
+ except (TypeError, ValueError, VisibleDeprecationWarning):
+ # argument was not a tuple representing a LinearConstraint
+ pass
+
+ # Address cases 4/5
+ for constraint in constraints:
+ # if it's not a LinearConstraint or something that represents a
+ # LinearConstraint at this point, it's invalid
+ if not isinstance(constraint, LinearConstraint):
+ try:
+ constraint = LinearConstraint(*constraint)
+ except TypeError as exc:
+ raise ValueError(message) from exc
+ As.append(csc_array(constraint.A))
+ b_ls.append(np.atleast_1d(constraint.lb).astype(np.float64))
+ b_us.append(np.atleast_1d(constraint.ub).astype(np.float64))
+
+ if len(As) > 1:
+ A = vstack(As, format="csc")
+ b_l = np.concatenate(b_ls)
+ b_u = np.concatenate(b_us)
+ else: # avoid unnecessary copying
+ A = As[0]
+ b_l = b_ls[0]
+ b_u = b_us[0]
+
+ return A, b_l, b_u
+
+
+def _milp_iv(c, integrality, bounds, constraints, options):
+ # objective IV
+ if issparse(c):
+ raise ValueError("`c` must be a dense array.")
+ c = np.atleast_1d(c).astype(np.float64)
+ if c.ndim != 1 or c.size == 0 or not np.all(np.isfinite(c)):
+ message = ("`c` must be a one-dimensional array of finite numbers "
+ "with at least one element.")
+ raise ValueError(message)
+
+ # integrality IV
+ if issparse(integrality):
+ raise ValueError("`integrality` must be a dense array.")
+ message = ("`integrality` must contain integers 0-3 and be broadcastable "
+ "to `c.shape`.")
+ if integrality is None:
+ integrality = 0
+ try:
+ integrality = np.broadcast_to(integrality, c.shape).astype(np.uint8)
+ except ValueError:
+ raise ValueError(message)
+ if integrality.min() < 0 or integrality.max() > 3:
+ raise ValueError(message)
+
+ # bounds IV
+ if bounds is None:
+ bounds = Bounds(0, np.inf)
+ elif not isinstance(bounds, Bounds):
+ message = ("`bounds` must be convertible into an instance of "
+ "`scipy.optimize.Bounds`.")
+ try:
+ bounds = Bounds(*bounds)
+ except TypeError as exc:
+ raise ValueError(message) from exc
+
+ try:
+ lb = np.broadcast_to(bounds.lb, c.shape).astype(np.float64)
+ ub = np.broadcast_to(bounds.ub, c.shape).astype(np.float64)
+ except (ValueError, TypeError) as exc:
+ message = ("`bounds.lb` and `bounds.ub` must contain reals and "
+ "be broadcastable to `c.shape`.")
+ raise ValueError(message) from exc
+
+ # constraints IV
+ if not constraints:
+ constraints = [LinearConstraint(np.empty((0, c.size)),
+ np.empty((0,)), np.empty((0,)))]
+ try:
+ A, b_l, b_u = _constraints_to_components(constraints)
+ except ValueError as exc:
+ message = ("`constraints` (or each element within `constraints`) must "
+ "be convertible into an instance of "
+ "`scipy.optimize.LinearConstraint`.")
+ raise ValueError(message) from exc
+
+ if A.shape != (b_l.size, c.size):
+ message = "The shape of `A` must be (len(b_l), len(c))."
+ raise ValueError(message)
+ indptr, indices, data = A.indptr, A.indices, A.data.astype(np.float64)
+
+ # options IV
+ options = options or {}
+ supported_options = {'disp', 'presolve', 'time_limit', 'node_limit',
+ 'mip_rel_gap'}
+ unsupported_options = set(options).difference(supported_options)
+ if unsupported_options:
+ message = (f"Unrecognized options detected: {unsupported_options}. "
+ "These will be passed to HiGHS verbatim.")
+ warnings.warn(message, RuntimeWarning, stacklevel=3)
+ options_iv = {'log_to_console': options.pop("disp", False),
+ 'mip_max_nodes': options.pop("node_limit", None)}
+ options_iv.update(options)
+
+ return c, integrality, lb, ub, indptr, indices, data, b_l, b_u, options_iv
+
+
+def milp(c, *, integrality=None, bounds=None, constraints=None, options=None):
+ r"""
+ Mixed-integer linear programming
+
+ Solves problems of the following form:
+
+ .. math::
+
+ \min_x \ & c^T x \\
+ \mbox{such that} \ & b_l \leq A x \leq b_u,\\
+ & l \leq x \leq u, \\
+ & x_i \in \mathbb{Z}, i \in X_i
+
+ where :math:`x` is a vector of decision variables;
+ :math:`c`, :math:`b_l`, :math:`b_u`, :math:`l`, and :math:`u` are vectors;
+ :math:`A` is a matrix, and :math:`X_i` is the set of indices of
+ decision variables that must be integral. (In this context, a
+ variable that can assume only integer values is said to be "integral";
+ it has an "integrality" constraint.)
+
+ Alternatively, that's:
+
+ minimize::
+
+ c @ x
+
+ such that::
+
+ b_l <= A @ x <= b_u
+ l <= x <= u
+ Specified elements of x must be integers
+
+ By default, ``l = 0`` and ``u = np.inf`` unless specified with
+ ``bounds``.
+
+ Parameters
+ ----------
+ c : 1D dense array_like
+ The coefficients of the linear objective function to be minimized.
+ `c` is converted to a double precision array before the problem is
+ solved.
+ integrality : 1D dense array_like, optional
+ Indicates the type of integrality constraint on each decision variable.
+
+ ``0`` : Continuous variable; no integrality constraint.
+
+ ``1`` : Integer variable; decision variable must be an integer
+ within `bounds`.
+
+ ``2`` : Semi-continuous variable; decision variable must be within
+ `bounds` or take value ``0``.
+
+ ``3`` : Semi-integer variable; decision variable must be an integer
+ within `bounds` or take value ``0``.
+
+ By default, all variables are continuous. `integrality` is converted
+ to an array of integers before the problem is solved.
+
+ bounds : scipy.optimize.Bounds, optional
+ Bounds on the decision variables. Lower and upper bounds are converted
+ to double precision arrays before the problem is solved. The
+ ``keep_feasible`` parameter of the `Bounds` object is ignored. If
+ not specified, all decision variables are constrained to be
+ non-negative.
+ constraints : sequence of scipy.optimize.LinearConstraint, optional
+ Linear constraints of the optimization problem. Arguments may be
+ one of the following:
+
+ 1. A single `LinearConstraint` object
+ 2. A single tuple that can be converted to a `LinearConstraint` object
+ as ``LinearConstraint(*constraints)``
+ 3. A sequence composed entirely of objects of type 1. and 2.
+
+ Before the problem is solved, all values are converted to double
+ precision, and the matrices of constraint coefficients are converted to
+ instances of `scipy.sparse.csc_array`. The ``keep_feasible`` parameter
+ of `LinearConstraint` objects is ignored.
+ options : dict, optional
+ A dictionary of solver options. The following keys are recognized.
+
+ disp : bool (default: ``False``)
+ Set to ``True`` if indicators of optimization status are to be
+ printed to the console during optimization.
+ node_limit : int, optional
+ The maximum number of nodes (linear program relaxations) to solve
+ before stopping. Default is no maximum number of nodes.
+ presolve : bool (default: ``True``)
+ Presolve attempts to identify trivial infeasibilities,
+ identify trivial unboundedness, and simplify the problem before
+ sending it to the main solver.
+ time_limit : float, optional
+ The maximum number of seconds allotted to solve the problem.
+ Default is no time limit.
+ mip_rel_gap : float, optional
+ Termination criterion for MIP solver: solver will terminate when
+ the gap between the primal objective value and the dual objective
+ bound, scaled by the primal objective value, is <= mip_rel_gap.
+
+ Returns
+ -------
+ res : OptimizeResult
+ An instance of :class:`scipy.optimize.OptimizeResult`. The object
+ is guaranteed to have the following attributes.
+
+ status : int
+ An integer representing the exit status of the algorithm.
+
+ ``0`` : Optimal solution found.
+
+ ``1`` : Iteration or time limit reached.
+
+ ``2`` : Problem is infeasible.
+
+ ``3`` : Problem is unbounded.
+
+ ``4`` : Other; see message for details.
+
+ success : bool
+ ``True`` when an optimal solution is found and ``False`` otherwise.
+
+ message : str
+ A string descriptor of the exit status of the algorithm.
+
+ The following attributes will also be present, but the values may be
+ ``None``, depending on the solution status.
+
+ x : ndarray
+ The values of the decision variables that minimize the
+ objective function while satisfying the constraints.
+ fun : float
+ The optimal value of the objective function ``c @ x``.
+ mip_node_count : int
+ The number of subproblems or "nodes" solved by the MILP solver.
+ mip_dual_bound : float
+ The MILP solver's final estimate of the lower bound on the optimal
+ solution.
+ mip_gap : float
+ The difference between the primal objective value and the dual
+ objective bound, scaled by the primal objective value.
+
+ Notes
+ -----
+ `milp` is a wrapper of the HiGHS linear optimization software [1]_. The
+ algorithm is deterministic, and it typically finds the global optimum of
+ moderately challenging mixed-integer linear programs (when it exists).
+
+ References
+ ----------
+ .. [1] Huangfu, Q., Galabova, I., Feldmeier, M., and Hall, J. A. J.
+ "HiGHS - high performance software for linear optimization."
+ https://highs.dev/
+ .. [2] Huangfu, Q. and Hall, J. A. J. "Parallelizing the dual revised
+ simplex method." Mathematical Programming Computation, 10 (1),
+ 119-142, 2018. DOI: 10.1007/s12532-017-0130-5
+
+ Examples
+ --------
+ Consider the problem at
+ https://en.wikipedia.org/wiki/Integer_programming#Example, which is
+ expressed as a maximization problem of two variables. Since `milp` requires
+ that the problem be expressed as a minimization problem, the objective
+ function coefficients on the decision variables are:
+
+ >>> import numpy as np
+ >>> c = -np.array([0, 1])
+
+ Note the negative sign: we maximize the original objective function
+ by minimizing the negative of the objective function.
+
+ We collect the coefficients of the constraints into arrays like:
+
+ >>> A = np.array([[-1, 1], [3, 2], [2, 3]])
+ >>> b_u = np.array([1, 12, 12])
+ >>> b_l = np.full_like(b_u, -np.inf, dtype=float)
+
+ Because there is no lower limit on these constraints, we have defined a
+ variable ``b_l`` full of values representing negative infinity. This may
+ be unfamiliar to users of `scipy.optimize.linprog`, which only accepts
+ "less than" (or "upper bound") inequality constraints of the form
+ ``A_ub @ x <= b_u``. By accepting both ``b_l`` and ``b_u`` of constraints
+ ``b_l <= A_ub @ x <= b_u``, `milp` makes it easy to specify "greater than"
+ inequality constraints, "less than" inequality constraints, and equality
+ constraints concisely.
+
+ These arrays are collected into a single `LinearConstraint` object like:
+
+ >>> from scipy.optimize import LinearConstraint
+ >>> constraints = LinearConstraint(A, b_l, b_u)
+
+ The non-negativity bounds on the decision variables are enforced by
+ default, so we do not need to provide an argument for `bounds`.
+
+ Finally, the problem states that both decision variables must be integers:
+
+ >>> integrality = np.ones_like(c)
+
+ We solve the problem like:
+
+ >>> from scipy.optimize import milp
+ >>> res = milp(c=c, constraints=constraints, integrality=integrality)
+ >>> res.x
+ array([1., 2.])
+
+ Note that had we solved the relaxed problem (without integrality
+ constraints):
+
+ >>> res = milp(c=c, constraints=constraints) # OR:
+ >>> # from scipy.optimize import linprog; res = linprog(c, A, b_u)
+ >>> res.x
+ array([1.8, 2.8])
+
+ we would not have obtained the correct solution by rounding to the nearest
+ integers.
+
+ Other examples are given :ref:`in the tutorial `.
+
+ """
+ args_iv = _milp_iv(c, integrality, bounds, constraints, options)
+ c, integrality, lb, ub, indptr, indices, data, b_l, b_u, options = args_iv
+
+ highs_res = _highs_wrapper(c, indptr, indices, data, b_l, b_u,
+ lb, ub, integrality, options)
+
+ res = {}
+
+ # Convert to scipy-style status and message
+ highs_status = highs_res.get('status', None)
+ highs_message = highs_res.get('message', None)
+ status, message = _highs_to_scipy_status_message(highs_status,
+ highs_message)
+ res['status'] = status
+ res['message'] = message
+ res['success'] = (status == 0)
+ x = highs_res.get('x', None)
+ res['x'] = np.array(x) if x is not None else None
+ res['fun'] = highs_res.get('fun', None)
+ res['mip_node_count'] = highs_res.get('mip_node_count', None)
+ res['mip_dual_bound'] = highs_res.get('mip_dual_bound', None)
+ res['mip_gap'] = highs_res.get('mip_gap', None)
+
+ return OptimizeResult(res)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_minimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_minimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..f0930e2b742b3dca9957a7190828d1aef9799853
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_minimize.py
@@ -0,0 +1,1199 @@
+"""
+Unified interfaces to minimization algorithms.
+
+Functions
+---------
+- minimize : minimization of a function of several variables.
+- minimize_scalar : minimization of a function of one variable.
+"""
+
+__all__ = ['minimize', 'minimize_scalar']
+
+
+from warnings import warn
+
+import numpy as np
+from scipy._lib._util import wrapped_inspect_signature
+
+# unconstrained minimization
+from ._optimize import (_minimize_neldermead, _minimize_powell, _minimize_cg,
+ _minimize_bfgs, _minimize_newtoncg,
+ _minimize_scalar_brent, _minimize_scalar_bounded,
+ _minimize_scalar_golden, MemoizeJac, OptimizeResult,
+ _wrap_callback, _recover_from_bracket_error)
+from ._trustregion_dogleg import _minimize_dogleg
+from ._trustregion_ncg import _minimize_trust_ncg
+from ._trustregion_krylov import _minimize_trust_krylov
+from ._trustregion_exact import _minimize_trustregion_exact
+from ._trustregion_constr import _minimize_trustregion_constr
+
+# constrained minimization
+from ._lbfgsb_py import _minimize_lbfgsb
+from ._tnc import _minimize_tnc
+from ._cobyla_py import _minimize_cobyla
+from ._cobyqa_py import _minimize_cobyqa
+from ._slsqp_py import _minimize_slsqp
+from ._constraints import (old_bound_to_new, new_bounds_to_old,
+ old_constraint_to_new, new_constraint_to_old,
+ NonlinearConstraint, LinearConstraint, Bounds,
+ PreparedConstraint)
+from ._differentiable_functions import FD_METHODS
+
+MINIMIZE_METHODS = ['nelder-mead', 'powell', 'cg', 'bfgs', 'newton-cg',
+ 'l-bfgs-b', 'tnc', 'cobyla', 'cobyqa', 'slsqp',
+ 'trust-constr', 'dogleg', 'trust-ncg', 'trust-exact',
+ 'trust-krylov']
+
+# These methods support the new callback interface (passed an OptimizeResult)
+MINIMIZE_METHODS_NEW_CB = ['nelder-mead', 'powell', 'cg', 'bfgs', 'newton-cg',
+ 'l-bfgs-b', 'trust-constr', 'dogleg', 'trust-ncg',
+ 'trust-exact', 'trust-krylov', 'cobyqa', 'cobyla', 'slsqp']
+
+MINIMIZE_SCALAR_METHODS = ['brent', 'bounded', 'golden']
+
+def minimize(fun, x0, args=(), method=None, jac=None, hess=None,
+ hessp=None, bounds=None, constraints=(), tol=None,
+ callback=None, options=None):
+ """Minimization of scalar function of one or more variables.
+
+ Parameters
+ ----------
+ fun : callable
+ The objective function to be minimized::
+
+ fun(x, *args) -> float
+
+ where ``x`` is a 1-D array with shape (n,) and ``args``
+ is a tuple of the fixed parameters needed to completely
+ specify the function.
+
+ Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
+ ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
+ Rather than passing ``f0`` as the callable, wrap it to accept
+ only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
+ callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
+ gathered before invoking this function.
+ x0 : ndarray, shape (n,)
+ Initial guess. Array of real elements of size (n,),
+ where ``n`` is the number of independent variables.
+ args : tuple, optional
+ Extra arguments passed to the objective function and its
+ derivatives (`fun`, `jac` and `hess` functions).
+ method : str or callable, optional
+ Type of solver. Should be one of
+
+ - 'Nelder-Mead' :ref:`(see here) `
+ - 'Powell' :ref:`(see here) `
+ - 'CG' :ref:`(see here) `
+ - 'BFGS' :ref:`(see here) `
+ - 'Newton-CG' :ref:`(see here) `
+ - 'L-BFGS-B' :ref:`(see here) `
+ - 'TNC' :ref:`(see here) `
+ - 'COBYLA' :ref:`(see here) `
+ - 'COBYQA' :ref:`(see here) `
+ - 'SLSQP' :ref:`(see here) `
+ - 'trust-constr':ref:`(see here) `
+ - 'dogleg' :ref:`(see here) `
+ - 'trust-ncg' :ref:`(see here) `
+ - 'trust-exact' :ref:`(see here) `
+ - 'trust-krylov' :ref:`(see here) `
+ - custom - a callable object, see below for description.
+
+ If not given, chosen to be one of ``BFGS``, ``L-BFGS-B``, ``SLSQP``,
+ depending on whether or not the problem has constraints or bounds.
+ jac : {callable, '2-point', '3-point', 'cs', bool}, optional
+ Method for computing the gradient vector. Only for CG, BFGS,
+ Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg, trust-krylov,
+ trust-exact and trust-constr.
+ If it is a callable, it should be a function that returns the gradient
+ vector::
+
+ jac(x, *args) -> array_like, shape (n,)
+
+ where ``x`` is an array with shape (n,) and ``args`` is a tuple with
+ the fixed parameters. If `jac` is a Boolean and is True, `fun` is
+ assumed to return a tuple ``(f, g)`` containing the objective
+ function and the gradient.
+ Methods 'Newton-CG', 'trust-ncg', 'dogleg', 'trust-exact', and
+ 'trust-krylov' require that either a callable be supplied, or that
+ `fun` return the objective and gradient.
+ If None or False, the gradient will be estimated using 2-point finite
+ difference estimation with an absolute step size.
+ Alternatively, the keywords {'2-point', '3-point', 'cs'} can be used
+ to select a finite difference scheme for numerical estimation of the
+ gradient with a relative step size. These finite difference schemes
+ obey any specified `bounds`.
+ hess : {callable, '2-point', '3-point', 'cs', HessianUpdateStrategy}, optional
+ Method for computing the Hessian matrix. Only for Newton-CG, dogleg,
+ trust-ncg, trust-krylov, trust-exact and trust-constr.
+ If it is callable, it should return the Hessian matrix::
+
+ hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)
+
+ where ``x`` is a (n,) ndarray and ``args`` is a tuple with the fixed
+ parameters.
+ The keywords {'2-point', '3-point', 'cs'} can also be used to select
+ a finite difference scheme for numerical estimation of the hessian.
+ Alternatively, objects implementing the `HessianUpdateStrategy`
+ interface can be used to approximate the Hessian. Available
+ quasi-Newton methods implementing this interface are:
+
+ - `BFGS`
+ - `SR1`
+
+ Not all of the options are available for each of the methods; for
+ availability refer to the notes.
+ hessp : callable, optional
+ Hessian of objective function times an arbitrary vector p. Only for
+ Newton-CG, trust-ncg, trust-krylov, trust-constr.
+ Only one of `hessp` or `hess` needs to be given. If `hess` is
+ provided, then `hessp` will be ignored. `hessp` must compute the
+ Hessian times an arbitrary vector::
+
+ hessp(x, p, *args) -> ndarray shape (n,)
+
+ where ``x`` is a (n,) ndarray, ``p`` is an arbitrary vector with
+ dimension (n,) and ``args`` is a tuple with the fixed
+ parameters.
+ bounds : sequence or `Bounds`, optional
+ Bounds on variables for Nelder-Mead, L-BFGS-B, TNC, SLSQP, Powell,
+ trust-constr, COBYLA, and COBYQA methods. There are two ways to specify
+ the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. Sequence of ``(min, max)`` pairs for each element in `x`. None
+ is used to specify no bound.
+
+ constraints : {Constraint, dict} or List of {Constraint, dict}, optional
+ Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr.
+
+ Constraints for 'trust-constr', 'cobyqa', and 'cobyla' are defined as a single
+ object or a list of objects specifying constraints to the optimization problem.
+ Available constraints are:
+
+ - `LinearConstraint`
+ - `NonlinearConstraint`
+
+ Constraints for COBYLA, SLSQP are defined as a list of dictionaries.
+ Each dictionary with fields:
+
+ type : str
+ Constraint type: 'eq' for equality, 'ineq' for inequality.
+ fun : callable
+ The function defining the constraint.
+ jac : callable, optional
+ The Jacobian of `fun` (only for SLSQP).
+ args : sequence, optional
+ Extra arguments to be passed to the function and Jacobian.
+
+ Equality constraint means that the constraint function result is to
+ be zero whereas inequality means that it is to be non-negative.
+
+ tol : float, optional
+ Tolerance for termination. When `tol` is specified, the selected
+ minimization algorithm sets some relevant solver-specific tolerance(s)
+ equal to `tol`. For detailed control, use solver-specific
+ options.
+ options : dict, optional
+ A dictionary of solver options. All methods except `TNC` accept the
+ following generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform. Depending on the
+ method each iteration may use several function evaluations.
+
+ For `TNC` use `maxfun` instead of `maxiter`.
+ disp : bool
+ Set to True to print convergence messages.
+
+ For method-specific options, see :func:`show_options()`.
+ callback : callable, optional
+ A callable called after each iteration.
+
+ All methods except TNC support a callable with
+ the signature::
+
+ callback(intermediate_result: OptimizeResult)
+
+ where ``intermediate_result`` is a keyword parameter containing an
+ `OptimizeResult` with attributes ``x`` and ``fun``, the present values
+ of the parameter vector and objective function. Not all attributes of
+ `OptimizeResult` may be present. The name of the parameter must be
+ ``intermediate_result`` for the callback to be passed an `OptimizeResult`.
+ These methods will also terminate if the callback raises ``StopIteration``.
+
+ All methods except trust-constr (also) support a signature like::
+
+ callback(xk)
+
+ where ``xk`` is the current parameter vector.
+
+ Introspection is used to determine which of the signatures above to
+ invoke.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a ``OptimizeResult`` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully and
+ ``message`` which describes the cause of the termination. See
+ `OptimizeResult` for a description of other attributes.
+
+ See also
+ --------
+ minimize_scalar : Interface to minimization algorithms for scalar
+ univariate functions
+ show_options : Additional options accepted by the solvers
+
+ Notes
+ -----
+ This section describes the available solvers that can be selected by the
+ 'method' parameter. The default method is *BFGS*.
+
+ **Unconstrained minimization**
+
+ Method :ref:`CG ` uses a nonlinear conjugate
+ gradient algorithm by Polak and Ribiere, a variant of the
+ Fletcher-Reeves method described in [5]_ pp.120-122. Only the
+ first derivatives are used.
+
+ Method :ref:`BFGS ` uses the quasi-Newton
+ method of Broyden, Fletcher, Goldfarb, and Shanno (BFGS) [5]_
+ pp. 136. It uses the first derivatives only. BFGS has proven good
+ performance even for non-smooth optimizations. This method also
+ returns an approximation of the Hessian inverse, stored as
+ `hess_inv` in the OptimizeResult object.
+
+ Method :ref:`Newton-CG ` uses a
+ Newton-CG algorithm [5]_ pp. 168 (also known as the truncated
+ Newton method). It uses a CG method to the compute the search
+ direction. See also *TNC* method for a box-constrained
+ minimization with a similar algorithm. Suitable for large-scale
+ problems.
+
+ Method :ref:`dogleg ` uses the dog-leg
+ trust-region algorithm [5]_ for unconstrained minimization. This
+ algorithm requires the gradient and Hessian; furthermore the
+ Hessian is required to be positive definite.
+
+ Method :ref:`trust-ncg ` uses the
+ Newton conjugate gradient trust-region algorithm [5]_ for
+ unconstrained minimization. This algorithm requires the gradient
+ and either the Hessian or a function that computes the product of
+ the Hessian with a given vector. Suitable for large-scale problems.
+
+ Method :ref:`trust-krylov ` uses
+ the Newton GLTR trust-region algorithm [14]_, [15]_ for unconstrained
+ minimization. This algorithm requires the gradient
+ and either the Hessian or a function that computes the product of
+ the Hessian with a given vector. Suitable for large-scale problems.
+ On indefinite problems it requires usually less iterations than the
+ `trust-ncg` method and is recommended for medium and large-scale problems.
+
+ Method :ref:`trust-exact `
+ is a trust-region method for unconstrained minimization in which
+ quadratic subproblems are solved almost exactly [13]_. This
+ algorithm requires the gradient and the Hessian (which is
+ *not* required to be positive definite). It is, in many
+ situations, the Newton method to converge in fewer iterations
+ and the most recommended for small and medium-size problems.
+
+ **Bound-Constrained minimization**
+
+ Method :ref:`Nelder-Mead ` uses the
+ Simplex algorithm [1]_, [2]_. This algorithm is robust in many
+ applications. However, if numerical computation of derivative can be
+ trusted, other algorithms using the first and/or second derivatives
+ information might be preferred for their better performance in
+ general.
+
+ Method :ref:`L-BFGS-B ` uses the L-BFGS-B
+ algorithm [6]_, [7]_ for bound constrained minimization.
+
+ Method :ref:`Powell ` is a modification
+ of Powell's method [3]_, [4]_ which is a conjugate direction
+ method. It performs sequential one-dimensional minimizations along
+ each vector of the directions set (`direc` field in `options` and
+ `info`), which is updated at each iteration of the main
+ minimization loop. The function need not be differentiable, and no
+ derivatives are taken. If bounds are not provided, then an
+ unbounded line search will be used. If bounds are provided and
+ the initial guess is within the bounds, then every function
+ evaluation throughout the minimization procedure will be within
+ the bounds. If bounds are provided, the initial guess is outside
+ the bounds, and `direc` is full rank (default has full rank), then
+ some function evaluations during the first iteration may be
+ outside the bounds, but every function evaluation after the first
+ iteration will be within the bounds. If `direc` is not full rank,
+ then some parameters may not be optimized and the solution is not
+ guaranteed to be within the bounds.
+
+ Method :ref:`TNC ` uses a truncated Newton
+ algorithm [5]_, [8]_ to minimize a function with variables subject
+ to bounds. This algorithm uses gradient information; it is also
+ called Newton Conjugate-Gradient. It differs from the *Newton-CG*
+ method described above as it wraps a C implementation and allows
+ each variable to be given upper and lower bounds.
+
+ **Constrained Minimization**
+
+ Method :ref:`COBYLA ` uses the PRIMA
+ implementation [19]_ of the
+ Constrained Optimization BY Linear Approximation (COBYLA) method
+ [9]_, [10]_, [11]_. The algorithm is based on linear
+ approximations to the objective function and each constraint.
+
+ Method :ref:`COBYQA ` uses the Constrained
+ Optimization BY Quadratic Approximations (COBYQA) method [18]_. The
+ algorithm is a derivative-free trust-region SQP method based on quadratic
+ approximations to the objective function and each nonlinear constraint. The
+ bounds are treated as unrelaxable constraints, in the sense that the
+ algorithm always respects them throughout the optimization process.
+
+ Method :ref:`SLSQP ` uses Sequential
+ Least SQuares Programming to minimize a function of several
+ variables with any combination of bounds, equality and inequality
+ constraints. The method wraps the SLSQP Optimization subroutine
+ originally implemented by Dieter Kraft [12]_. Note that the
+ wrapper handles infinite values in bounds by converting them into
+ large floating values.
+
+ Method :ref:`trust-constr ` is a
+ trust-region algorithm for constrained optimization. It switches
+ between two implementations depending on the problem definition.
+ It is the most versatile constrained minimization algorithm
+ implemented in SciPy and the most appropriate for large-scale problems.
+ For equality constrained problems it is an implementation of Byrd-Omojokun
+ Trust-Region SQP method described in [17]_ and in [5]_, p. 549. When
+ inequality constraints are imposed as well, it switches to the trust-region
+ interior point method described in [16]_. This interior point algorithm,
+ in turn, solves inequality constraints by introducing slack variables
+ and solving a sequence of equality-constrained barrier problems
+ for progressively smaller values of the barrier parameter.
+ The previously described equality constrained SQP method is
+ used to solve the subproblems with increasing levels of accuracy
+ as the iterate gets closer to a solution.
+
+ **Finite-Difference Options**
+
+ For Method :ref:`trust-constr `
+ the gradient and the Hessian may be approximated using
+ three finite-difference schemes: {'2-point', '3-point', 'cs'}.
+ The scheme 'cs' is, potentially, the most accurate but it
+ requires the function to correctly handle complex inputs and to
+ be differentiable in the complex plane. The scheme '3-point' is more
+ accurate than '2-point' but requires twice as many operations. If the
+ gradient is estimated via finite-differences the Hessian must be
+ estimated using one of the quasi-Newton strategies.
+
+ **Method specific options for the** `hess` **keyword**
+
+ +--------------+------+----------+-------------------------+-----+
+ | method/Hess | None | callable | '2-point/'3-point'/'cs' | HUS |
+ +==============+======+==========+=========================+=====+
+ | Newton-CG | x | (n, n) | x | x |
+ | | | LO | | |
+ +--------------+------+----------+-------------------------+-----+
+ | dogleg | | (n, n) | | |
+ +--------------+------+----------+-------------------------+-----+
+ | trust-ncg | | (n, n) | x | x |
+ +--------------+------+----------+-------------------------+-----+
+ | trust-krylov | | (n, n) | x | x |
+ +--------------+------+----------+-------------------------+-----+
+ | trust-exact | | (n, n) | | |
+ +--------------+------+----------+-------------------------+-----+
+ | trust-constr | x | (n, n) | x | x |
+ | | | LO | | |
+ | | | sp | | |
+ +--------------+------+----------+-------------------------+-----+
+
+ where LO=LinearOperator, sp=Sparse matrix, HUS=HessianUpdateStrategy
+
+ **Custom minimizers**
+
+ It may be useful to pass a custom minimization method, for example
+ when using a frontend to this method such as `scipy.optimize.basinhopping`
+ or a different library. You can simply pass a callable as the ``method``
+ parameter.
+
+ The callable is called as ``method(fun, x0, args, **kwargs, **options)``
+ where ``kwargs`` corresponds to any other parameters passed to `minimize`
+ (such as `callback`, `hess`, etc.), except the `options` dict, which has
+ its contents also passed as `method` parameters pair by pair. Also, if
+ `jac` has been passed as a bool type, `jac` and `fun` are mangled so that
+ `fun` returns just the function values and `jac` is converted to a function
+ returning the Jacobian. The method shall return an `OptimizeResult`
+ object.
+
+ The provided `method` callable must be able to accept (and possibly ignore)
+ arbitrary parameters; the set of parameters accepted by `minimize` may
+ expand in future versions and then these parameters will be passed to
+ the method. You can find an example in the scipy.optimize tutorial.
+
+ References
+ ----------
+ .. [1] Nelder, J A, and R Mead. 1965. A Simplex Method for Function
+ Minimization. The Computer Journal 7: 308-13.
+ .. [2] Wright M H. 1996. Direct search methods: Once scorned, now
+ respectable, in Numerical Analysis 1995: Proceedings of the 1995
+ Dundee Biennial Conference in Numerical Analysis (Eds. D F
+ Griffiths and G A Watson). Addison Wesley Longman, Harlow, UK.
+ 191-208.
+ .. [3] Powell, M J D. 1964. An efficient method for finding the minimum of
+ a function of several variables without calculating derivatives. The
+ Computer Journal 7: 155-162.
+ .. [4] Press W, S A Teukolsky, W T Vetterling and B P Flannery.
+ Numerical Recipes (any edition), Cambridge University Press.
+ .. [5] Nocedal, J, and S J Wright. 2006. Numerical Optimization.
+ Springer New York.
+ .. [6] Byrd, R H and P Lu and J. Nocedal. 1995. A Limited Memory
+ Algorithm for Bound Constrained Optimization. SIAM Journal on
+ Scientific and Statistical Computing 16 (5): 1190-1208.
+ .. [7] Zhu, C and R H Byrd and J Nocedal. 1997. L-BFGS-B: Algorithm
+ 778: L-BFGS-B, FORTRAN routines for large scale bound constrained
+ optimization. ACM Transactions on Mathematical Software 23 (4):
+ 550-560.
+ .. [8] Nash, S G. Newton-Type Minimization Via the Lanczos Method.
+ 1984. SIAM Journal of Numerical Analysis 21: 770-778.
+ .. [9] Powell, M J D. A direct search optimization method that models
+ the objective and constraint functions by linear interpolation.
+ 1994. Advances in Optimization and Numerical Analysis, eds. S. Gomez
+ and J-P Hennart, Kluwer Academic (Dordrecht), 51-67.
+ .. [10] Powell M J D. Direct search algorithms for optimization
+ calculations. 1998. Acta Numerica 7: 287-336.
+ .. [11] Powell M J D. A view of algorithms for optimization without
+ derivatives. 2007.Cambridge University Technical Report DAMTP
+ 2007/NA03
+ .. [12] Kraft, D. A software package for sequential quadratic
+ programming. 1988. Tech. Rep. DFVLR-FB 88-28, DLR German Aerospace
+ Center -- Institute for Flight Mechanics, Koln, Germany.
+ .. [13] Conn, A. R., Gould, N. I., and Toint, P. L.
+ Trust region methods. 2000. Siam. pp. 169-200.
+ .. [14] F. Lenders, C. Kirches, A. Potschka: "trlib: A vector-free
+ implementation of the GLTR method for iterative solution of
+ the trust region problem", :arxiv:`1611.04718`
+ .. [15] N. Gould, S. Lucidi, M. Roma, P. Toint: "Solving the
+ Trust-Region Subproblem using the Lanczos Method",
+ SIAM J. Optim., 9(2), 504--525, (1999).
+ .. [16] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal. 1999.
+ An interior point algorithm for large-scale nonlinear programming.
+ SIAM Journal on Optimization 9.4: 877-900.
+ .. [17] Lalee, Marucha, Jorge Nocedal, and Todd Plantenga. 1998. On the
+ implementation of an algorithm for large-scale equality constrained
+ optimization. SIAM Journal on Optimization 8.3: 682-706.
+ .. [18] Ragonneau, T. M. *Model-Based Derivative-Free Optimization Methods
+ and Software*. PhD thesis, Department of Applied Mathematics, The Hong
+ Kong Polytechnic University, Hong Kong, China, 2022. URL:
+ https://theses.lib.polyu.edu.hk/handle/200/12294.
+ .. [19] Zhang, Z. "PRIMA: Reference Implementation for Powell's Methods with
+ Modernization and Amelioration", https://www.libprima.net,
+ :doi:`10.5281/zenodo.8052654`
+ .. [20] Karush-Kuhn-Tucker conditions,
+ https://en.wikipedia.org/wiki/Karush%E2%80%93Kuhn%E2%80%93Tucker_conditions
+
+ Examples
+ --------
+ Let us consider the problem of minimizing the Rosenbrock function. This
+ function (and its respective derivatives) is implemented in `rosen`
+ (resp. `rosen_der`, `rosen_hess`) in the `scipy.optimize`.
+
+ >>> from scipy.optimize import minimize, rosen, rosen_der
+
+ A simple application of the *Nelder-Mead* method is:
+
+ >>> x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
+ >>> res = minimize(rosen, x0, method='Nelder-Mead', tol=1e-6)
+ >>> res.x
+ array([ 1., 1., 1., 1., 1.])
+
+ Now using the *BFGS* algorithm, using the first derivative and a few
+ options:
+
+ >>> res = minimize(rosen, x0, method='BFGS', jac=rosen_der,
+ ... options={'gtol': 1e-6, 'disp': True})
+ Optimization terminated successfully.
+ Current function value: 0.000000
+ Iterations: 26
+ Function evaluations: 31
+ Gradient evaluations: 31
+ >>> res.x
+ array([ 1., 1., 1., 1., 1.])
+ >>> print(res.message)
+ Optimization terminated successfully.
+ >>> res.hess_inv
+ array([
+ [ 0.00749589, 0.01255155, 0.02396251, 0.04750988, 0.09495377], # may vary
+ [ 0.01255155, 0.02510441, 0.04794055, 0.09502834, 0.18996269],
+ [ 0.02396251, 0.04794055, 0.09631614, 0.19092151, 0.38165151],
+ [ 0.04750988, 0.09502834, 0.19092151, 0.38341252, 0.7664427 ],
+ [ 0.09495377, 0.18996269, 0.38165151, 0.7664427, 1.53713523]
+ ])
+
+ Next, consider a minimization problem with several constraints (namely
+ Example 16.4 from [5]_). The objective function is:
+
+ >>> fun = lambda x: (x[0] - 1)**2 + (x[1] - 2.5)**2
+
+ There are three constraints defined as:
+
+ >>> cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},
+ ... {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6},
+ ... {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2})
+
+ And variables must be positive, hence the following bounds:
+
+ >>> bnds = ((0, None), (0, None))
+
+ The optimization problem is solved using the SLSQP method as:
+
+ >>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds, constraints=cons)
+
+ It should converge to the theoretical solution ``[1.4 ,1.7]``. *SLSQP* also
+ returns the multipliers that are used in the solution of the problem. These
+ multipliers, when the problem constraints are linear, can be thought of as the
+ Karush-Kuhn-Tucker (KKT) multipliers, which are a generalization
+ of Lagrange multipliers to inequality-constrained optimization problems ([20]_).
+
+ Notice that at the solution, the first constraint is active. Let's evaluate the
+ function at solution:
+
+ >>> cons[0]['fun'](res.x)
+ np.float64(1.4901224698604665e-09)
+
+ Also, notice that at optimality there is a non-zero multiplier:
+
+ >>> res.multipliers
+ array([0.8, 0. , 0. ])
+
+ This can be understood as the local sensitivity of the optimal value of the
+ objective function with respect to changes in the first constraint. If we
+ tighten the constraint by a small amount ``eps``:
+
+ >>> eps = 0.01
+ >>> cons[0]['fun'] = lambda x: x[0] - 2 * x[1] + 2 - eps
+
+ we expect the optimal value of the objective function to increase by
+ approximately ``eps * res.multipliers[0]``:
+
+ >>> eps * res.multipliers[0] # Expected change in f0
+ np.float64(0.008000000027153205)
+ >>> f0 = res.fun # Keep track of the previous optimal value
+ >>> res = minimize(fun, (2, 0), method='SLSQP', bounds=bnds, constraints=cons)
+ >>> f1 = res.fun # New optimal value
+ >>> f1 - f0
+ np.float64(0.008019998807885509)
+
+ """
+ x0 = np.atleast_1d(np.asarray(x0))
+
+ if x0.ndim != 1:
+ raise ValueError("'x0' must only have one dimension.")
+
+ if x0.dtype.kind in np.typecodes["AllInteger"]:
+ x0 = np.asarray(x0, dtype=float)
+
+ if not isinstance(args, tuple):
+ args = (args,)
+
+ if method is None:
+ # Select automatically
+ if constraints:
+ method = 'SLSQP'
+ elif bounds is not None:
+ method = 'L-BFGS-B'
+ else:
+ method = 'BFGS'
+
+ if callable(method):
+ meth = "_custom"
+ else:
+ meth = method.lower()
+
+ if options is None:
+ options = {}
+ # check if optional parameters are supported by the selected method
+ # - jac
+ if meth in ('nelder-mead', 'powell', 'cobyla', 'cobyqa') and bool(jac):
+ warn(f'Method {method} does not use gradient information (jac).',
+ RuntimeWarning, stacklevel=2)
+ # - hess
+ if meth not in ('newton-cg', 'dogleg', 'trust-ncg', 'trust-constr',
+ 'trust-krylov', 'trust-exact', '_custom') and hess is not None:
+ warn(f'Method {method} does not use Hessian information (hess).',
+ RuntimeWarning, stacklevel=2)
+ # - hessp
+ if meth not in ('newton-cg', 'trust-ncg', 'trust-constr',
+ 'trust-krylov', '_custom') \
+ and hessp is not None:
+ warn(f'Method {method} does not use Hessian-vector product'
+ ' information (hessp).',
+ RuntimeWarning, stacklevel=2)
+ # - constraints or bounds
+ if (meth not in ('cobyla', 'cobyqa', 'slsqp', 'trust-constr', '_custom') and
+ np.any(constraints)):
+ warn(f'Method {method} cannot handle constraints.',
+ RuntimeWarning, stacklevel=2)
+ if meth not in (
+ 'nelder-mead', 'powell', 'l-bfgs-b', 'cobyla', 'cobyqa', 'slsqp',
+ 'tnc', 'trust-constr', '_custom') and bounds is not None:
+ warn(f'Method {method} cannot handle bounds.',
+ RuntimeWarning, stacklevel=2)
+ # - return_all
+ if (meth in ('l-bfgs-b', 'tnc', 'cobyla', 'cobyqa', 'slsqp') and
+ options.get('return_all', False)):
+ warn(f'Method {method} does not support the return_all option.',
+ RuntimeWarning, stacklevel=2)
+
+ # check gradient vector
+ if callable(jac):
+ pass
+ elif jac is True:
+ # fun returns func and grad
+ fun = MemoizeJac(fun)
+ jac = fun.derivative
+ elif (jac in FD_METHODS and
+ meth in ['trust-constr', 'bfgs', 'cg', 'l-bfgs-b', 'tnc', 'slsqp']):
+ # finite differences with relative step
+ pass
+ elif meth in ['trust-constr']:
+ # default jac calculation for this method
+ jac = '2-point'
+ elif jac is None or bool(jac) is False:
+ # this will cause e.g. LBFGS to use forward difference, absolute step
+ jac = None
+ else:
+ # default if jac option is not understood
+ jac = None
+
+ # set default tolerances
+ if tol is not None:
+ options = dict(options)
+ if meth == 'nelder-mead':
+ options.setdefault('xatol', tol)
+ options.setdefault('fatol', tol)
+ if meth in ('newton-cg', 'powell', 'tnc'):
+ options.setdefault('xtol', tol)
+ if meth in ('powell', 'l-bfgs-b', 'tnc', 'slsqp'):
+ options.setdefault('ftol', tol)
+ if meth in ('bfgs', 'cg', 'l-bfgs-b', 'tnc', 'dogleg',
+ 'trust-ncg', 'trust-exact', 'trust-krylov'):
+ options.setdefault('gtol', tol)
+ if meth in ('cobyla', '_custom'):
+ options.setdefault('tol', tol)
+ if meth == 'cobyqa':
+ options.setdefault('final_tr_radius', tol)
+ if meth == 'trust-constr':
+ options.setdefault('xtol', tol)
+ options.setdefault('gtol', tol)
+ options.setdefault('barrier_tol', tol)
+
+ if meth == '_custom':
+ # custom method called before bounds and constraints are 'standardised'
+ # custom method should be able to accept whatever bounds/constraints
+ # are provided to it.
+ return method(fun, x0, args=args, jac=jac, hess=hess, hessp=hessp,
+ bounds=bounds, constraints=constraints,
+ callback=callback, **options)
+
+ constraints = standardize_constraints(constraints, x0, meth)
+
+ remove_vars = False
+ if bounds is not None:
+ # convert to new-style bounds so we only have to consider one case
+ bounds = standardize_bounds(bounds, x0, 'new')
+ bounds = _validate_bounds(bounds, x0, meth)
+
+ if meth in {"tnc", "slsqp", "l-bfgs-b"}:
+ # These methods can't take the finite-difference derivatives they
+ # need when a variable is fixed by the bounds. To avoid this issue,
+ # remove fixed variables from the problem.
+ # NOTE: if this list is expanded, then be sure to update the
+ # accompanying tests and test_optimize.eb_data. Consider also if
+ # default OptimizeResult will need updating.
+
+ # determine whether any variables are fixed
+ i_fixed = (bounds.lb == bounds.ub)
+
+ if np.all(i_fixed):
+ # all the parameters are fixed, a minimizer is not able to do
+ # anything
+ return _optimize_result_for_equal_bounds(
+ fun, bounds, meth, args=args, constraints=constraints
+ )
+
+ # determine whether finite differences are needed for any grad/jac
+ fd_needed = (not callable(jac))
+ for con in constraints:
+ if not callable(con.get('jac', None)):
+ fd_needed = True
+
+ # If finite differences are ever used, remove all fixed variables
+ # Always remove fixed variables for TNC; see gh-14565
+ remove_vars = i_fixed.any() and (fd_needed or meth == "tnc")
+ if remove_vars:
+ x_fixed = (bounds.lb)[i_fixed]
+ x0 = x0[~i_fixed]
+ bounds = _remove_from_bounds(bounds, i_fixed)
+ fun = _Remove_From_Func(fun, i_fixed, x_fixed)
+
+ if callable(callback):
+ sig = wrapped_inspect_signature(callback)
+ if set(sig.parameters) == {'intermediate_result'}:
+ # callback(intermediate_result)
+ print(callback)
+ callback = _Patch_Callback_Equal_Variables(
+ callback, i_fixed, x_fixed
+ )
+ else:
+ # callback(x)
+ callback = _Remove_From_Func(callback, i_fixed, x_fixed)
+
+ if callable(jac):
+ jac = _Remove_From_Func(jac, i_fixed, x_fixed, remove=1)
+
+ # make a copy of the constraints so the user's version doesn't
+ # get changed. (Shallow copy is ok)
+ constraints = [con.copy() for con in constraints]
+ for con in constraints: # yes, guaranteed to be a list
+ con['fun'] = _Remove_From_Func(con['fun'], i_fixed,
+ x_fixed, min_dim=1,
+ remove=0)
+ if callable(con.get('jac', None)):
+ con['jac'] = _Remove_From_Func(con['jac'], i_fixed,
+ x_fixed, min_dim=2,
+ remove=1)
+ bounds = standardize_bounds(bounds, x0, meth)
+
+ # selects whether to use callback(x) or callback(intermediate_result)
+ callback = _wrap_callback(callback, meth)
+
+ if meth == 'nelder-mead':
+ res = _minimize_neldermead(fun, x0, args, callback, bounds=bounds,
+ **options)
+ elif meth == 'powell':
+ res = _minimize_powell(fun, x0, args, callback, bounds, **options)
+ elif meth == 'cg':
+ res = _minimize_cg(fun, x0, args, jac, callback, **options)
+ elif meth == 'bfgs':
+ res = _minimize_bfgs(fun, x0, args, jac, callback, **options)
+ elif meth == 'newton-cg':
+ res = _minimize_newtoncg(fun, x0, args, jac, hess, hessp, callback,
+ **options)
+ elif meth == 'l-bfgs-b':
+ res = _minimize_lbfgsb(fun, x0, args, jac, bounds,
+ callback=callback, **options)
+ elif meth == 'tnc':
+ res = _minimize_tnc(fun, x0, args, jac, bounds, callback=callback,
+ **options)
+ elif meth == 'cobyla':
+ res = _minimize_cobyla(fun, x0, args, constraints, callback=callback,
+ bounds=bounds, **options)
+ elif meth == 'cobyqa':
+ res = _minimize_cobyqa(fun, x0, args, bounds, constraints, callback,
+ **options)
+ elif meth == 'slsqp':
+ res = _minimize_slsqp(fun, x0, args, jac, bounds,
+ constraints, callback=callback, **options)
+ elif meth == 'trust-constr':
+ res = _minimize_trustregion_constr(fun, x0, args, jac, hess, hessp,
+ bounds, constraints,
+ callback=callback, **options)
+ elif meth == 'dogleg':
+ res = _minimize_dogleg(fun, x0, args, jac, hess,
+ callback=callback, **options)
+ elif meth == 'trust-ncg':
+ res = _minimize_trust_ncg(fun, x0, args, jac, hess, hessp,
+ callback=callback, **options)
+ elif meth == 'trust-krylov':
+ res = _minimize_trust_krylov(fun, x0, args, jac, hess, hessp,
+ callback=callback, **options)
+ elif meth == 'trust-exact':
+ res = _minimize_trustregion_exact(fun, x0, args, jac, hess,
+ callback=callback, **options)
+ else:
+ raise ValueError(f'Unknown solver {method}')
+
+ if remove_vars:
+ res.x = _add_to_array(res.x, i_fixed, x_fixed)
+ res.jac = _add_to_array(res.jac, i_fixed, np.nan)
+ if "hess_inv" in res:
+ res.hess_inv = None # unknown
+
+ if getattr(callback, 'stop_iteration', False):
+ res.success = False
+ res.status = 99
+ res.message = "`callback` raised `StopIteration`."
+
+ return res
+
+
+def minimize_scalar(fun, bracket=None, bounds=None, args=(),
+ method=None, tol=None, options=None):
+ """Local minimization of scalar function of one variable.
+
+ Parameters
+ ----------
+ fun : callable
+ Objective function.
+ Scalar function, must return a scalar.
+
+ Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
+ ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
+ Rather than passing ``f0`` as the callable, wrap it to accept
+ only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
+ callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
+ gathered before invoking this function.
+
+ bracket : sequence, optional
+ For methods 'brent' and 'golden', `bracket` defines the bracketing
+ interval and is required.
+ Either a triple ``(xa, xb, xc)`` satisfying ``xa < xb < xc`` and
+ ``func(xb) < func(xa) and func(xb) < func(xc)``, or a pair
+ ``(xa, xb)`` to be used as initial points for a downhill bracket search
+ (see `scipy.optimize.bracket`).
+ The minimizer ``res.x`` will not necessarily satisfy
+ ``xa <= res.x <= xb``.
+ bounds : sequence, optional
+ For method 'bounded', `bounds` is mandatory and must have two finite
+ items corresponding to the optimization bounds.
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ method : str or callable, optional
+ Type of solver. Should be one of:
+
+ - :ref:`Brent `
+ - :ref:`Bounded `
+ - :ref:`Golden `
+ - custom - a callable object (added in version 0.14.0), see below
+
+ Default is "Bounded" if bounds are provided and "Brent" otherwise.
+ See the 'Notes' section for details of each solver.
+
+ tol : float, optional
+ Tolerance for termination. For detailed control, use solver-specific
+ options.
+ options : dict, optional
+ A dictionary of solver options.
+
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ Set to True to print convergence messages.
+
+ See :func:`show_options()` for solver-specific options.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a ``OptimizeResult`` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully and
+ ``message`` which describes the cause of the termination. See
+ `OptimizeResult` for a description of other attributes.
+
+ See also
+ --------
+ minimize : Interface to minimization algorithms for scalar multivariate
+ functions
+ show_options : Additional options accepted by the solvers
+
+ Notes
+ -----
+ This section describes the available solvers that can be selected by the
+ 'method' parameter. The default method is the ``"Bounded"`` Brent method if
+ `bounds` are passed and unbounded ``"Brent"`` otherwise.
+
+ Method :ref:`Brent ` uses Brent's
+ algorithm [1]_ to find a local minimum. The algorithm uses inverse
+ parabolic interpolation when possible to speed up convergence of
+ the golden section method.
+
+ Method :ref:`Golden ` uses the
+ golden section search technique [1]_. It uses analog of the bisection
+ method to decrease the bracketed interval. It is usually
+ preferable to use the *Brent* method.
+
+ Method :ref:`Bounded ` can
+ perform bounded minimization [2]_ [3]_. It uses the Brent method to find a
+ local minimum in the interval x1 < xopt < x2.
+
+ Note that the Brent and Golden methods do not guarantee success unless a
+ valid ``bracket`` triple is provided. If a three-point bracket cannot be
+ found, consider `scipy.optimize.minimize`. Also, all methods are intended
+ only for local minimization. When the function of interest has more than
+ one local minimum, consider :ref:`global_optimization`.
+
+ **Custom minimizers**
+
+ It may be useful to pass a custom minimization method, for example
+ when using some library frontend to minimize_scalar. You can simply
+ pass a callable as the ``method`` parameter.
+
+ The callable is called as ``method(fun, args, **kwargs, **options)``
+ where ``kwargs`` corresponds to any other parameters passed to `minimize`
+ (such as `bracket`, `tol`, etc.), except the `options` dict, which has
+ its contents also passed as `method` parameters pair by pair. The method
+ shall return an `OptimizeResult` object.
+
+ The provided `method` callable must be able to accept (and possibly ignore)
+ arbitrary parameters; the set of parameters accepted by `minimize` may
+ expand in future versions and then these parameters will be passed to
+ the method. You can find an example in the scipy.optimize tutorial.
+
+ .. versionadded:: 0.11.0
+
+ References
+ ----------
+ .. [1] Press, W., S.A. Teukolsky, W.T. Vetterling, and B.P. Flannery.
+ Numerical Recipes in C. Cambridge University Press.
+ .. [2] Forsythe, G.E., M. A. Malcolm, and C. B. Moler. "Computer Methods
+ for Mathematical Computations." Prentice-Hall Series in Automatic
+ Computation 259 (1977).
+ .. [3] Brent, Richard P. Algorithms for Minimization Without Derivatives.
+ Courier Corporation, 2013.
+
+ Examples
+ --------
+ Consider the problem of minimizing the following function.
+
+ >>> def f(x):
+ ... return (x - 2) * x * (x + 2)**2
+
+ Using the *Brent* method, we find the local minimum as:
+
+ >>> from scipy.optimize import minimize_scalar
+ >>> res = minimize_scalar(f)
+ >>> res.fun
+ -9.9149495908
+
+ The minimizer is:
+
+ >>> res.x
+ 1.28077640403
+
+ Using the *Bounded* method, we find a local minimum with specified
+ bounds as:
+
+ >>> res = minimize_scalar(f, bounds=(-3, -1), method='bounded')
+ >>> res.fun # minimum
+ 3.28365179850e-13
+ >>> res.x # minimizer
+ -2.0000002026
+
+ """
+ if not isinstance(args, tuple):
+ args = (args,)
+
+ if callable(method):
+ meth = "_custom"
+ elif method is None:
+ meth = 'brent' if bounds is None else 'bounded'
+ else:
+ meth = method.lower()
+ if options is None:
+ options = {}
+
+ if bounds is not None and meth in {'brent', 'golden'}:
+ message = f"Use of `bounds` is incompatible with 'method={method}'."
+ raise ValueError(message)
+
+ if tol is not None:
+ options = dict(options)
+ if meth == 'bounded' and 'xatol' not in options:
+ warn("Method 'bounded' does not support relative tolerance in x; "
+ "defaulting to absolute tolerance.",
+ RuntimeWarning, stacklevel=2)
+ options['xatol'] = tol
+ elif meth == '_custom':
+ options.setdefault('tol', tol)
+ else:
+ options.setdefault('xtol', tol)
+
+ # replace boolean "disp" option, if specified, by an integer value.
+ disp = options.get('disp')
+ if isinstance(disp, bool):
+ options['disp'] = 2 * int(disp)
+
+ if meth == '_custom':
+ res = method(fun, args=args, bracket=bracket, bounds=bounds, **options)
+ elif meth == 'brent':
+ res = _recover_from_bracket_error(_minimize_scalar_brent,
+ fun, bracket, args, **options)
+ elif meth == 'bounded':
+ if bounds is None:
+ raise ValueError('The `bounds` parameter is mandatory for '
+ 'method `bounded`.')
+ res = _minimize_scalar_bounded(fun, bounds, args, **options)
+ elif meth == 'golden':
+ res = _recover_from_bracket_error(_minimize_scalar_golden,
+ fun, bracket, args, **options)
+ else:
+ raise ValueError(f'Unknown solver {method}')
+
+ # gh-16196 reported inconsistencies in the output shape of `res.x`. While
+ # fixing this, future-proof it for when the function is vectorized:
+ # the shape of `res.x` should match that of `res.fun`.
+ res.fun = np.asarray(res.fun)[()]
+ res.x = np.reshape(res.x, res.fun.shape)[()]
+ return res
+
+
+def _remove_from_bounds(bounds, i_fixed):
+ """Removes fixed variables from a `Bounds` instance"""
+ lb = bounds.lb[~i_fixed]
+ ub = bounds.ub[~i_fixed]
+ return Bounds(lb, ub) # don't mutate original Bounds object
+
+
+class _Patch_Callback_Equal_Variables:
+ # Patches a callback that accepts an intermediate_result
+ def __init__(self, callback, i_fixed, x_fixed):
+ self.callback = callback
+ self.i_fixed = i_fixed
+ self.x_fixed = x_fixed
+
+ def __call__(self, intermediate_result):
+ x_in = intermediate_result.x
+ x_out = np.zeros_like(self.i_fixed, dtype=x_in.dtype)
+ x_out[self.i_fixed] = self.x_fixed
+ x_out[~self.i_fixed] = x_in
+ intermediate_result.x = x_out
+ return self.callback(intermediate_result)
+
+
+class _Remove_From_Func:
+ """Wraps a function such that fixed variables need not be passed in"""
+ def __init__(self, fun_in, i_fixed, x_fixed, min_dim=None, remove=0):
+ self.fun_in = fun_in
+ self.i_fixed = i_fixed
+ self.x_fixed = x_fixed
+ self.min_dim = min_dim
+ self.remove = remove
+
+ def __call__(self, x_in, *args, **kwargs):
+ x_out = np.zeros_like(self.i_fixed, dtype=x_in.dtype)
+ x_out[self.i_fixed] = self.x_fixed
+ x_out[~self.i_fixed] = x_in
+ y_out = self.fun_in(x_out, *args, **kwargs)
+ y_out = np.array(y_out)
+
+ if self.min_dim == 1:
+ y_out = np.atleast_1d(y_out)
+ elif self.min_dim == 2:
+ y_out = np.atleast_2d(y_out)
+
+ if self.remove == 1:
+ y_out = y_out[..., ~self.i_fixed]
+ elif self.remove == 2:
+ y_out = y_out[~self.i_fixed, ~self.i_fixed]
+
+ return y_out
+
+
+def _add_to_array(x_in, i_fixed, x_fixed):
+ """Adds fixed variables back to an array"""
+ i_free = ~i_fixed
+ if x_in.ndim == 2:
+ i_free = i_free[:, None] @ i_free[None, :]
+ x_out = np.zeros_like(i_free, dtype=x_in.dtype)
+ x_out[~i_free] = x_fixed
+ x_out[i_free] = x_in.ravel()
+ return x_out
+
+
+def _validate_bounds(bounds, x0, meth):
+ """Check that bounds are valid."""
+
+ msg = "An upper bound is less than the corresponding lower bound."
+ if np.any(bounds.ub < bounds.lb):
+ raise ValueError(msg)
+
+ msg = "The number of bounds is not compatible with the length of `x0`."
+ try:
+ bounds.lb = np.broadcast_to(bounds.lb, x0.shape)
+ bounds.ub = np.broadcast_to(bounds.ub, x0.shape)
+ except Exception as e:
+ raise ValueError(msg) from e
+
+ return bounds
+
+def standardize_bounds(bounds, x0, meth):
+ """Converts bounds to the form required by the solver."""
+ if meth in {'trust-constr', 'powell', 'nelder-mead', 'cobyla', 'cobyqa',
+ 'new'}:
+ if not isinstance(bounds, Bounds):
+ lb, ub = old_bound_to_new(bounds)
+ bounds = Bounds(lb, ub)
+ elif meth in ('l-bfgs-b', 'tnc', 'slsqp', 'old'):
+ if isinstance(bounds, Bounds):
+ bounds = new_bounds_to_old(bounds.lb, bounds.ub, x0.shape[0])
+ return bounds
+
+
+def standardize_constraints(constraints, x0, meth):
+ """Converts constraints to the form required by the solver."""
+ all_constraint_types = (NonlinearConstraint, LinearConstraint, dict)
+ new_constraint_types = all_constraint_types[:-1]
+ if constraints is None:
+ constraints = []
+ elif isinstance(constraints, all_constraint_types):
+ constraints = [constraints]
+ else:
+ constraints = list(constraints) # ensure it's a mutable sequence
+
+ if meth in ['trust-constr', 'cobyqa', 'new', 'cobyla']:
+ for i, con in enumerate(constraints):
+ if not isinstance(con, new_constraint_types):
+ constraints[i] = old_constraint_to_new(i, con)
+ else:
+ # iterate over copy, changing original
+ for i, con in enumerate(list(constraints)):
+ if isinstance(con, new_constraint_types):
+ old_constraints = new_constraint_to_old(con, x0)
+ constraints[i] = old_constraints[0]
+ constraints.extend(old_constraints[1:]) # appends 1 if present
+
+ return constraints
+
+
+def _optimize_result_for_equal_bounds(
+ fun, bounds, method, args=(), constraints=()
+):
+ """
+ Provides a default OptimizeResult for when a bounded minimization method
+ has (lb == ub).all().
+
+ Parameters
+ ----------
+ fun: callable
+ bounds: Bounds
+ method: str
+ constraints: Constraint
+ """
+ success = True
+ message = 'All independent variables were fixed by bounds.'
+
+ # bounds is new-style
+ x0 = bounds.lb
+
+ if constraints:
+ message = ("All independent variables were fixed by bounds at values"
+ " that satisfy the constraints.")
+ constraints = standardize_constraints(constraints, x0, 'new')
+
+ maxcv = 0
+ for c in constraints:
+ pc = PreparedConstraint(c, x0)
+ violation = pc.violation(x0)
+ if np.sum(violation):
+ maxcv = max(maxcv, np.max(violation))
+ success = False
+ message = (f"All independent variables were fixed by bounds, but "
+ f"the independent variables do not satisfy the "
+ f"constraints exactly. (Maximum violation: {maxcv}).")
+
+ return OptimizeResult(
+ x=x0, fun=fun(x0, *args), success=success, message=message, nfev=1,
+ njev=0, nhev=0,
+ )
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_minpack.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_minpack.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..b00221409ca7694dd672e94c9be945573152b152
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_minpack.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:3d5eff5c6a12c7d14722ef67371c0a356e346d86dc4b9752c1795deae8d29a28
+size 103520
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_minpack_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_minpack_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..c8a1f4667a608068db40a356effae298612b2803
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_minpack_py.py
@@ -0,0 +1,1178 @@
+import warnings
+from . import _minpack
+
+import numpy as np
+from numpy import (atleast_1d, triu, shape, transpose, zeros, prod, greater,
+ asarray, inf,
+ finfo, inexact, issubdtype, dtype)
+from scipy import linalg
+from scipy.linalg import svd, cholesky, solve_triangular, LinAlgError
+from scipy._lib._util import _asarray_validated, _contains_nan
+from scipy._lib._util import getfullargspec_no_self as _getfullargspec
+import scipy._lib.array_api_extra as xpx
+from ._optimize import OptimizeResult, _check_unknown_options, OptimizeWarning
+from ._lsq import least_squares
+# from ._lsq.common import make_strictly_feasible
+from ._lsq.least_squares import prepare_bounds
+from scipy.optimize._minimize import Bounds
+
+__all__ = ['fsolve', 'leastsq', 'fixed_point', 'curve_fit']
+
+
+def _check_func(checker, argname, thefunc, x0, args, numinputs,
+ output_shape=None):
+ res = atleast_1d(thefunc(*((x0[:numinputs],) + args)))
+ if (output_shape is not None) and (shape(res) != output_shape):
+ if (output_shape[0] != 1):
+ if len(output_shape) > 1:
+ if output_shape[1] == 1:
+ return shape(res)
+ msg = f"{checker}: there is a mismatch between the input and output " \
+ f"shape of the '{argname}' argument"
+ func_name = getattr(thefunc, '__name__', None)
+ if func_name:
+ msg += f" '{func_name}'."
+ else:
+ msg += "."
+ msg += f'Shape should be {output_shape} but it is {shape(res)}.'
+ raise TypeError(msg)
+ if issubdtype(res.dtype, inexact):
+ dt = res.dtype
+ else:
+ dt = dtype(float)
+ return shape(res), dt
+
+
+def fsolve(func, x0, args=(), fprime=None, full_output=0,
+ col_deriv=0, xtol=1.49012e-8, maxfev=0, band=None,
+ epsfcn=None, factor=100, diag=None):
+ """
+ Find the roots of a function.
+
+ Return the roots of the (non-linear) equations defined by
+ ``func(x) = 0`` given a starting estimate.
+
+ Parameters
+ ----------
+ func : callable ``f(x, *args)``
+ A function that takes at least one (possibly vector) argument,
+ and returns a value of the same length.
+ x0 : ndarray
+ The starting estimate for the roots of ``func(x) = 0``.
+ args : tuple, optional
+ Any extra arguments to `func`.
+ fprime : callable ``f(x, *args)``, optional
+ A function to compute the Jacobian of `func` with derivatives
+ across the rows. By default, the Jacobian will be estimated.
+ full_output : bool, optional
+ If True, return optional outputs.
+ col_deriv : bool, optional
+ Specify whether the Jacobian function computes derivatives down
+ the columns (faster, because there is no transpose operation).
+ xtol : float, optional
+ The calculation will terminate if the relative error between two
+ consecutive iterates is at most `xtol`.
+ maxfev : int, optional
+ The maximum number of calls to the function. If zero, then
+ ``100*(N+1)`` is the maximum where N is the number of elements
+ in `x0`.
+ band : tuple, optional
+ If set to a two-sequence containing the number of sub- and
+ super-diagonals within the band of the Jacobi matrix, the
+ Jacobi matrix is considered banded (only for ``fprime=None``).
+ epsfcn : float, optional
+ A suitable step length for the forward-difference
+ approximation of the Jacobian (for ``fprime=None``). If
+ `epsfcn` is less than the machine precision, it is assumed
+ that the relative errors in the functions are of the order of
+ the machine precision.
+ factor : float, optional
+ A parameter determining the initial step bound
+ (``factor * || diag * x||``). Should be in the interval
+ ``(0.1, 100)``.
+ diag : sequence, optional
+ N positive entries that serve as a scale factors for the
+ variables.
+
+ Returns
+ -------
+ x : ndarray
+ The solution (or the result of the last iteration for
+ an unsuccessful call).
+ infodict : dict
+ A dictionary of optional outputs with the keys:
+
+ ``nfev``
+ number of function calls
+ ``njev``
+ number of Jacobian calls
+ ``fvec``
+ function evaluated at the output
+ ``fjac``
+ the orthogonal matrix, q, produced by the QR
+ factorization of the final approximate Jacobian
+ matrix, stored column wise
+ ``r``
+ upper triangular matrix produced by QR factorization
+ of the same matrix
+ ``qtf``
+ the vector ``(transpose(q) * fvec)``
+
+ ier : int
+ An integer flag. Set to 1 if a solution was found, otherwise refer
+ to `mesg` for more information.
+ mesg : str
+ If no solution is found, `mesg` details the cause of failure.
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See the ``method='hybr'`` in particular.
+
+ Notes
+ -----
+ ``fsolve`` is a wrapper around MINPACK's hybrd and hybrj algorithms.
+
+ Examples
+ --------
+ Find a solution to the system of equations:
+ ``x0*cos(x1) = 4, x1*x0 - x1 = 5``.
+
+ >>> import numpy as np
+ >>> from scipy.optimize import fsolve
+ >>> def func(x):
+ ... return [x[0] * np.cos(x[1]) - 4,
+ ... x[1] * x[0] - x[1] - 5]
+ >>> root = fsolve(func, [1, 1])
+ >>> root
+ array([6.50409711, 0.90841421])
+ >>> np.isclose(func(root), [0.0, 0.0]) # func(root) should be almost 0.0.
+ array([ True, True])
+
+ """
+ def _wrapped_func(*fargs):
+ """
+ Wrapped `func` to track the number of times
+ the function has been called.
+ """
+ _wrapped_func.nfev += 1
+ return func(*fargs)
+
+ _wrapped_func.nfev = 0
+
+ options = {'col_deriv': col_deriv,
+ 'xtol': xtol,
+ 'maxfev': maxfev,
+ 'band': band,
+ 'eps': epsfcn,
+ 'factor': factor,
+ 'diag': diag}
+
+ res = _root_hybr(_wrapped_func, x0, args, jac=fprime, **options)
+ res.nfev = _wrapped_func.nfev
+
+ if full_output:
+ x = res['x']
+ info = {k: res.get(k)
+ for k in ('nfev', 'njev', 'fjac', 'r', 'qtf') if k in res}
+ info['fvec'] = res['fun']
+ return x, info, res['status'], res['message']
+ else:
+ status = res['status']
+ msg = res['message']
+ if status == 0:
+ raise TypeError(msg)
+ elif status == 1:
+ pass
+ elif status in [2, 3, 4, 5]:
+ warnings.warn(msg, RuntimeWarning, stacklevel=2)
+ else:
+ raise TypeError(msg)
+ return res['x']
+
+
+def _root_hybr(func, x0, args=(), jac=None,
+ col_deriv=0, xtol=1.49012e-08, maxfev=0, band=None, eps=None,
+ factor=100, diag=None, **unknown_options):
+ """
+ Find the roots of a multivariate function using MINPACK's hybrd and
+ hybrj routines (modified Powell method).
+
+ Options
+ -------
+ col_deriv : bool
+ Specify whether the Jacobian function computes derivatives down
+ the columns (faster, because there is no transpose operation).
+ xtol : float
+ The calculation will terminate if the relative error between two
+ consecutive iterates is at most `xtol`.
+ maxfev : int
+ The maximum number of calls to the function. If zero, then
+ ``100*(N+1)`` is the maximum where N is the number of elements
+ in `x0`.
+ band : tuple
+ If set to a two-sequence containing the number of sub- and
+ super-diagonals within the band of the Jacobi matrix, the
+ Jacobi matrix is considered banded (only for ``jac=None``).
+ eps : float
+ A suitable step length for the forward-difference
+ approximation of the Jacobian (for ``jac=None``). If
+ `eps` is less than the machine precision, it is assumed
+ that the relative errors in the functions are of the order of
+ the machine precision.
+ factor : float
+ A parameter determining the initial step bound
+ (``factor * || diag * x||``). Should be in the interval
+ ``(0.1, 100)``.
+ diag : sequence
+ N positive entries that serve as a scale factors for the
+ variables.
+
+ """
+ _check_unknown_options(unknown_options)
+ epsfcn = eps
+
+ x0 = asarray(x0).flatten()
+ n = len(x0)
+ if not isinstance(args, tuple):
+ args = (args,)
+ shape, dtype = _check_func('fsolve', 'func', func, x0, args, n, (n,))
+ if epsfcn is None:
+ epsfcn = finfo(dtype).eps
+ Dfun = jac
+ if Dfun is None:
+ if band is None:
+ ml, mu = -10, -10
+ else:
+ ml, mu = band[:2]
+ if maxfev == 0:
+ maxfev = 200 * (n + 1)
+ retval = _minpack._hybrd(func, x0, args, 1, xtol, maxfev,
+ ml, mu, epsfcn, factor, diag)
+ else:
+ _check_func('fsolve', 'fprime', Dfun, x0, args, n, (n, n))
+ if (maxfev == 0):
+ maxfev = 100 * (n + 1)
+ retval = _minpack._hybrj(func, Dfun, x0, args, 1,
+ col_deriv, xtol, maxfev, factor, diag)
+
+ x, status = retval[0], retval[-1]
+
+ errors = {0: "Improper input parameters were entered.",
+ 1: "The solution converged.",
+ 2: "The number of calls to function has "
+ f"reached maxfev = {maxfev}.",
+ 3: f"xtol={xtol:f} is too small, no further improvement "
+ "in the approximate\n solution is possible.",
+ 4: "The iteration is not making good progress, as measured "
+ "by the \n improvement from the last five "
+ "Jacobian evaluations.",
+ 5: "The iteration is not making good progress, "
+ "as measured by the \n improvement from the last "
+ "ten iterations.",
+ 'unknown': "An error occurred."}
+
+ info = retval[1]
+ info['fun'] = info.pop('fvec')
+ sol = OptimizeResult(x=x, success=(status == 1), status=status,
+ method="hybr")
+ sol.update(info)
+ try:
+ sol['message'] = errors[status]
+ except KeyError:
+ sol['message'] = errors['unknown']
+
+ return sol
+
+
+LEASTSQ_SUCCESS = [1, 2, 3, 4]
+LEASTSQ_FAILURE = [5, 6, 7, 8]
+
+
+def leastsq(func, x0, args=(), Dfun=None, full_output=False,
+ col_deriv=False, ftol=1.49012e-8, xtol=1.49012e-8,
+ gtol=0.0, maxfev=0, epsfcn=None, factor=100, diag=None):
+ """
+ Minimize the sum of squares of a set of equations.
+
+ ::
+
+ x = arg min(sum(func(y)**2,axis=0))
+ y
+
+ Parameters
+ ----------
+ func : callable
+ Should take at least one (possibly length ``N`` vector) argument and
+ returns ``M`` floating point numbers. It must not return NaNs or
+ fitting might fail. ``M`` must be greater than or equal to ``N``.
+ x0 : ndarray
+ The starting estimate for the minimization.
+ args : tuple, optional
+ Any extra arguments to func are placed in this tuple.
+ Dfun : callable, optional
+ A function or method to compute the Jacobian of func with derivatives
+ across the rows. If this is None, the Jacobian will be estimated.
+ full_output : bool, optional
+ If ``True``, return all optional outputs (not just `x` and `ier`).
+ col_deriv : bool, optional
+ If ``True``, specify that the Jacobian function computes derivatives
+ down the columns (faster, because there is no transpose operation).
+ ftol : float, optional
+ Relative error desired in the sum of squares.
+ xtol : float, optional
+ Relative error desired in the approximate solution.
+ gtol : float, optional
+ Orthogonality desired between the function vector and the columns of
+ the Jacobian.
+ maxfev : int, optional
+ The maximum number of calls to the function. If `Dfun` is provided,
+ then the default `maxfev` is 100*(N+1) where N is the number of elements
+ in x0, otherwise the default `maxfev` is 200*(N+1).
+ epsfcn : float, optional
+ A variable used in determining a suitable step length for the forward-
+ difference approximation of the Jacobian (for Dfun=None).
+ Normally the actual step length will be sqrt(epsfcn)*x
+ If epsfcn is less than the machine precision, it is assumed that the
+ relative errors are of the order of the machine precision.
+ factor : float, optional
+ A parameter determining the initial step bound
+ (``factor * || diag * x||``). Should be in interval ``(0.1, 100)``.
+ diag : sequence, optional
+ N positive entries that serve as a scale factors for the variables.
+
+ Returns
+ -------
+ x : ndarray
+ The solution (or the result of the last iteration for an unsuccessful
+ call).
+ cov_x : ndarray
+ The inverse of the Hessian. `fjac` and `ipvt` are used to construct an
+ estimate of the Hessian. A value of None indicates a singular matrix,
+ which means the curvature in parameters `x` is numerically flat. To
+ obtain the covariance matrix of the parameters `x`, `cov_x` must be
+ multiplied by the variance of the residuals -- see curve_fit. Only
+ returned if `full_output` is ``True``.
+ infodict : dict
+ a dictionary of optional outputs with the keys:
+
+ ``nfev``
+ The number of function calls
+ ``fvec``
+ The function evaluated at the output
+ ``fjac``
+ A permutation of the R matrix of a QR
+ factorization of the final approximate
+ Jacobian matrix, stored column wise.
+ Together with ipvt, the covariance of the
+ estimate can be approximated.
+ ``ipvt``
+ An integer array of length N which defines
+ a permutation matrix, p, such that
+ fjac*p = q*r, where r is upper triangular
+ with diagonal elements of nonincreasing
+ magnitude. Column j of p is column ipvt(j)
+ of the identity matrix.
+ ``qtf``
+ The vector (transpose(q) * fvec).
+
+ Only returned if `full_output` is ``True``.
+ mesg : str
+ A string message giving information about the cause of failure.
+ Only returned if `full_output` is ``True``.
+ ier : int
+ An integer flag. If it is equal to 1, 2, 3 or 4, the solution was
+ found. Otherwise, the solution was not found. In either case, the
+ optional output variable 'mesg' gives more information.
+
+ See Also
+ --------
+ least_squares : Newer interface to solve nonlinear least-squares problems
+ with bounds on the variables. See ``method='lm'`` in particular.
+
+ Notes
+ -----
+ "leastsq" is a wrapper around MINPACK's lmdif and lmder algorithms.
+
+ cov_x is a Jacobian approximation to the Hessian of the least squares
+ objective function.
+ This approximation assumes that the objective function is based on the
+ difference between some observed target data (ydata) and a (non-linear)
+ function of the parameters `f(xdata, params)` ::
+
+ func(params) = ydata - f(xdata, params)
+
+ so that the objective function is ::
+
+ min sum((ydata - f(xdata, params))**2, axis=0)
+ params
+
+ The solution, `x`, is always a 1-D array, regardless of the shape of `x0`,
+ or whether `x0` is a scalar.
+
+ Examples
+ --------
+ >>> from scipy.optimize import leastsq
+ >>> def func(x):
+ ... return 2*(x-3)**2+1
+ >>> leastsq(func, 0)
+ (array([2.99999999]), 1)
+
+ """
+ x0 = asarray(x0).flatten()
+ n = len(x0)
+ if not isinstance(args, tuple):
+ args = (args,)
+ shape, dtype = _check_func('leastsq', 'func', func, x0, args, n)
+ m = shape[0]
+
+ if n > m:
+ raise TypeError(f"Improper input: func input vector length N={n} must"
+ f" not exceed func output vector length M={m}")
+
+ if epsfcn is None:
+ epsfcn = finfo(dtype).eps
+
+ if Dfun is None:
+ if maxfev == 0:
+ maxfev = 200*(n + 1)
+ retval = _minpack._lmdif(func, x0, args, full_output, ftol, xtol,
+ gtol, maxfev, epsfcn, factor, diag)
+ else:
+ if col_deriv:
+ _check_func('leastsq', 'Dfun', Dfun, x0, args, n, (n, m))
+ else:
+ _check_func('leastsq', 'Dfun', Dfun, x0, args, n, (m, n))
+ if maxfev == 0:
+ maxfev = 100 * (n + 1)
+ retval = _minpack._lmder(func, Dfun, x0, args, full_output,
+ col_deriv, ftol, xtol, gtol, maxfev,
+ factor, diag)
+
+ errors = {0: ["Improper input parameters.", TypeError],
+ 1: ["Both actual and predicted relative reductions "
+ f"in the sum of squares\n are at most {ftol:f}", None],
+ 2: ["The relative error between two consecutive "
+ f"iterates is at most {xtol:f}", None],
+ 3: ["Both actual and predicted relative reductions in "
+ f"the sum of squares\n are at most {ftol:f} and the "
+ "relative error between two consecutive "
+ f"iterates is at \n most {xtol:f}", None],
+ 4: ["The cosine of the angle between func(x) and any "
+ f"column of the\n Jacobian is at most {gtol:f} in "
+ "absolute value", None],
+ 5: ["Number of calls to function has reached "
+ f"maxfev = {maxfev}.", ValueError],
+ 6: [f"ftol={ftol:f} is too small, no further reduction "
+ "in the sum of squares\n is possible.",
+ ValueError],
+ 7: [f"xtol={xtol:f} is too small, no further improvement in "
+ "the approximate\n solution is possible.",
+ ValueError],
+ 8: [f"gtol={gtol:f} is too small, func(x) is orthogonal to the "
+ "columns of\n the Jacobian to machine precision.", ValueError]}
+
+ # The FORTRAN return value (possible return values are >= 0 and <= 8)
+ info = retval[-1]
+
+ if full_output:
+ cov_x = None
+ if info in LEASTSQ_SUCCESS:
+ # This was
+ # perm = take(eye(n), retval[1]['ipvt'] - 1, 0)
+ # r = triu(transpose(retval[1]['fjac'])[:n, :])
+ # R = dot(r, perm)
+ # cov_x = inv(dot(transpose(R), R))
+ # but the explicit dot product was not necessary and sometimes
+ # the result was not symmetric positive definite. See gh-4555.
+ perm = retval[1]['ipvt']
+ n = len(perm)
+ r = triu(transpose(retval[1]['fjac'])[:n, :])
+ inv_triu = linalg.get_lapack_funcs('trtri', (r,))
+ try:
+ # inverse of permuted matrix is a permutation of matrix inverse
+ invR, trtri_info = inv_triu(r) # default: upper, non-unit diag
+ if trtri_info != 0: # explicit comparison for readability
+ raise LinAlgError(f'trtri returned info {trtri_info}')
+ invR[perm] = invR.copy()
+ cov_x = invR @ invR.T
+ except (LinAlgError, ValueError):
+ pass
+ return (retval[0], cov_x) + retval[1:-1] + (errors[info][0], info)
+ else:
+ if info in LEASTSQ_FAILURE:
+ warnings.warn(errors[info][0], RuntimeWarning, stacklevel=2)
+ elif info == 0:
+ raise errors[info][1](errors[info][0])
+ return retval[0], info
+
+
+def _lightweight_memoizer(f):
+ # very shallow memoization to address gh-13670: only remember the first set
+ # of parameters and corresponding function value, and only attempt to use
+ # them twice (the number of times the function is evaluated at x0).
+ def _memoized_func(params):
+ if _memoized_func.skip_lookup:
+ return f(params)
+
+ if np.all(_memoized_func.last_params == params):
+ return _memoized_func.last_val
+ elif _memoized_func.last_params is not None:
+ _memoized_func.skip_lookup = True
+
+ val = f(params)
+
+ if _memoized_func.last_params is None:
+ _memoized_func.last_params = np.copy(params)
+ _memoized_func.last_val = val
+
+ return val
+
+ _memoized_func.last_params = None
+ _memoized_func.last_val = None
+ _memoized_func.skip_lookup = False
+ return _memoized_func
+
+
+def _wrap_func(func, xdata, ydata, transform):
+ if transform is None:
+ def func_wrapped(params):
+ return func(xdata, *params) - ydata
+ elif transform.size == 1 or transform.ndim == 1:
+ def func_wrapped(params):
+ return transform * (func(xdata, *params) - ydata)
+ else:
+ # Chisq = (y - yd)^T C^{-1} (y-yd)
+ # transform = L such that C = L L^T
+ # C^{-1} = L^{-T} L^{-1}
+ # Chisq = (y - yd)^T L^{-T} L^{-1} (y-yd)
+ # Define (y-yd)' = L^{-1} (y-yd)
+ # by solving
+ # L (y-yd)' = (y-yd)
+ # and minimize (y-yd)'^T (y-yd)'
+ def func_wrapped(params):
+ return solve_triangular(transform, func(xdata, *params) - ydata, lower=True)
+ return func_wrapped
+
+
+def _wrap_jac(jac, xdata, transform):
+ if transform is None:
+ def jac_wrapped(params):
+ return jac(xdata, *params)
+ elif transform.ndim == 1:
+ def jac_wrapped(params):
+ return transform[:, np.newaxis] * np.asarray(jac(xdata, *params))
+ else:
+ def jac_wrapped(params):
+ return solve_triangular(transform,
+ np.asarray(jac(xdata, *params)),
+ lower=True)
+ return jac_wrapped
+
+
+def _initialize_feasible(lb, ub):
+ p0 = np.ones_like(lb)
+ lb_finite = np.isfinite(lb)
+ ub_finite = np.isfinite(ub)
+
+ mask = lb_finite & ub_finite
+ p0[mask] = 0.5 * (lb[mask] + ub[mask])
+
+ mask = lb_finite & ~ub_finite
+ p0[mask] = lb[mask] + 1
+
+ mask = ~lb_finite & ub_finite
+ p0[mask] = ub[mask] - 1
+
+ return p0
+
+
+def curve_fit(f, xdata, ydata, p0=None, sigma=None, absolute_sigma=False,
+ check_finite=None, bounds=(-np.inf, np.inf), method=None,
+ jac=None, *, full_output=False, nan_policy=None,
+ **kwargs):
+ """
+ Use non-linear least squares to fit a function, f, to data.
+
+ Assumes ``ydata = f(xdata, *params) + eps``.
+
+ Parameters
+ ----------
+ f : callable
+ The model function, f(x, ...). It must take the independent
+ variable as the first argument and the parameters to fit as
+ separate remaining arguments.
+ xdata : array_like
+ The independent variable where the data is measured.
+ Should usually be an M-length sequence or an (k,M)-shaped array for
+ functions with k predictors, and each element should be float
+ convertible if it is an array like object.
+ ydata : array_like
+ The dependent data, a length M array - nominally ``f(xdata, ...)``.
+ p0 : array_like, optional
+ Initial guess for the parameters (length N). If None, then the
+ initial values will all be 1 (if the number of parameters for the
+ function can be determined using introspection, otherwise a
+ ValueError is raised).
+ sigma : None or scalar or M-length sequence or MxM array, optional
+ Determines the uncertainty in `ydata`. If we define residuals as
+ ``r = ydata - f(xdata, *popt)``, then the interpretation of `sigma`
+ depends on its number of dimensions:
+
+ - A scalar or 1-D `sigma` should contain values of standard deviations of
+ errors in `ydata`. In this case, the optimized function is
+ ``chisq = sum((r / sigma) ** 2)``.
+
+ - A 2-D `sigma` should contain the covariance matrix of
+ errors in `ydata`. In this case, the optimized function is
+ ``chisq = r.T @ inv(sigma) @ r``.
+
+ .. versionadded:: 0.19
+
+ None (default) is equivalent of 1-D `sigma` filled with ones.
+ absolute_sigma : bool, optional
+ If True, `sigma` is used in an absolute sense and the estimated parameter
+ covariance `pcov` reflects these absolute values.
+
+ If False (default), only the relative magnitudes of the `sigma` values matter.
+ The returned parameter covariance matrix `pcov` is based on scaling
+ `sigma` by a constant factor. This constant is set by demanding that the
+ reduced `chisq` for the optimal parameters `popt` when using the
+ *scaled* `sigma` equals unity. In other words, `sigma` is scaled to
+ match the sample variance of the residuals after the fit. Default is False.
+ Mathematically,
+ ``pcov(absolute_sigma=False) = pcov(absolute_sigma=True) * chisq(popt)/(M-N)``
+ check_finite : bool, optional
+ If True, check that the input arrays do not contain nans of infs,
+ and raise a ValueError if they do. Setting this parameter to
+ False may silently produce nonsensical results if the input arrays
+ do contain nans. Default is True if `nan_policy` is not specified
+ explicitly and False otherwise.
+ bounds : 2-tuple of array_like or `Bounds`, optional
+ Lower and upper bounds on parameters. Defaults to no bounds.
+ There are two ways to specify the bounds:
+
+ - Instance of `Bounds` class.
+
+ - 2-tuple of array_like: Each element of the tuple must be either
+ an array with the length equal to the number of parameters, or a
+ scalar (in which case the bound is taken to be the same for all
+ parameters). Use ``np.inf`` with an appropriate sign to disable
+ bounds on all or some parameters.
+
+ method : {'lm', 'trf', 'dogbox'}, optional
+ Method to use for optimization. See `least_squares` for more details.
+ Default is 'lm' for unconstrained problems and 'trf' if `bounds` are
+ provided. The method 'lm' won't work when the number of observations
+ is less than the number of variables, use 'trf' or 'dogbox' in this
+ case.
+
+ .. versionadded:: 0.17
+ jac : callable, string or None, optional
+ Function with signature ``jac(x, ...)`` which computes the Jacobian
+ matrix of the model function with respect to parameters as a dense
+ array_like structure. It will be scaled according to provided `sigma`.
+ If None (default), the Jacobian will be estimated numerically.
+ String keywords for 'trf' and 'dogbox' methods can be used to select
+ a finite difference scheme, see `least_squares`.
+
+ .. versionadded:: 0.18
+ full_output : boolean, optional
+ If True, this function returns additional information: `infodict`,
+ `mesg`, and `ier`.
+
+ .. versionadded:: 1.9
+ nan_policy : {'raise', 'omit', None}, optional
+ Defines how to handle when input contains nan.
+ The following options are available (default is None):
+
+ * 'raise': throws an error
+ * 'omit': performs the calculations ignoring nan values
+ * None: no special handling of NaNs is performed
+ (except what is done by check_finite); the behavior when NaNs
+ are present is implementation-dependent and may change.
+
+ Note that if this value is specified explicitly (not None),
+ `check_finite` will be set as False.
+
+ .. versionadded:: 1.11
+ **kwargs
+ Keyword arguments passed to `leastsq` for ``method='lm'`` or
+ `least_squares` otherwise.
+
+ Returns
+ -------
+ popt : array
+ Optimal values for the parameters so that the sum of the squared
+ residuals of ``f(xdata, *popt) - ydata`` is minimized.
+ pcov : 2-D array
+ The estimated approximate covariance of popt. The diagonals provide
+ the variance of the parameter estimate. To compute one standard
+ deviation errors on the parameters, use
+ ``perr = np.sqrt(np.diag(pcov))``. Note that the relationship between
+ `cov` and parameter error estimates is derived based on a linear
+ approximation to the model function around the optimum [1]_.
+ When this approximation becomes inaccurate, `cov` may not provide an
+ accurate measure of uncertainty.
+
+ How the `sigma` parameter affects the estimated covariance
+ depends on `absolute_sigma` argument, as described above.
+
+ If the Jacobian matrix at the solution doesn't have a full rank, then
+ 'lm' method returns a matrix filled with ``np.inf``, on the other hand
+ 'trf' and 'dogbox' methods use Moore-Penrose pseudoinverse to compute
+ the covariance matrix. Covariance matrices with large condition numbers
+ (e.g. computed with `numpy.linalg.cond`) may indicate that results are
+ unreliable.
+ infodict : dict (returned only if `full_output` is True)
+ a dictionary of optional outputs with the keys:
+
+ ``nfev``
+ The number of function calls. Methods 'trf' and 'dogbox' do not
+ count function calls for numerical Jacobian approximation,
+ as opposed to 'lm' method.
+ ``fvec``
+ The residual values evaluated at the solution, for a 1-D `sigma`
+ this is ``(f(x, *popt) - ydata)/sigma``.
+ ``fjac``
+ A permutation of the R matrix of a QR
+ factorization of the final approximate
+ Jacobian matrix, stored column wise.
+ Together with ipvt, the covariance of the
+ estimate can be approximated.
+ Method 'lm' only provides this information.
+ ``ipvt``
+ An integer array of length N which defines
+ a permutation matrix, p, such that
+ fjac*p = q*r, where r is upper triangular
+ with diagonal elements of nonincreasing
+ magnitude. Column j of p is column ipvt(j)
+ of the identity matrix.
+ Method 'lm' only provides this information.
+ ``qtf``
+ The vector (transpose(q) * fvec).
+ Method 'lm' only provides this information.
+
+ .. versionadded:: 1.9
+ mesg : str (returned only if `full_output` is True)
+ A string message giving information about the solution.
+
+ .. versionadded:: 1.9
+ ier : int (returned only if `full_output` is True)
+ An integer flag. If it is equal to 1, 2, 3 or 4, the solution was
+ found. Otherwise, the solution was not found. In either case, the
+ optional output variable `mesg` gives more information.
+
+ .. versionadded:: 1.9
+
+ Raises
+ ------
+ ValueError
+ if either `ydata` or `xdata` contain NaNs, or if incompatible options
+ are used.
+
+ RuntimeError
+ if the least-squares minimization fails.
+
+ OptimizeWarning
+ if covariance of the parameters can not be estimated.
+
+ See Also
+ --------
+ least_squares : Minimize the sum of squares of nonlinear functions.
+ scipy.stats.linregress : Calculate a linear least squares regression for
+ two sets of measurements.
+
+ Notes
+ -----
+ Users should ensure that inputs `xdata`, `ydata`, and the output of `f`
+ are ``float64``, or else the optimization may return incorrect results.
+
+ With ``method='lm'``, the algorithm uses the Levenberg-Marquardt algorithm
+ through `leastsq`. Note that this algorithm can only deal with
+ unconstrained problems.
+
+ Box constraints can be handled by methods 'trf' and 'dogbox'. Refer to
+ the docstring of `least_squares` for more information.
+
+ Parameters to be fitted must have similar scale. Differences of multiple
+ orders of magnitude can lead to incorrect results. For the 'trf' and
+ 'dogbox' methods, the `x_scale` keyword argument can be used to scale
+ the parameters.
+
+ `curve_fit` is for local optimization of parameters to minimize the sum of squares
+ of residuals. For global optimization, other choices of objective function, and
+ other advanced features, consider using SciPy's :ref:`tutorial_optimize_global`
+ tools or the `LMFIT `_ package.
+
+ References
+ ----------
+ .. [1] K. Vugrin et al. Confidence region estimation techniques for nonlinear
+ regression in groundwater flow: Three case studies. Water Resources
+ Research, Vol. 43, W03423, :doi:`10.1029/2005WR004804`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.optimize import curve_fit
+
+ >>> def func(x, a, b, c):
+ ... return a * np.exp(-b * x) + c
+
+ Define the data to be fit with some noise:
+
+ >>> xdata = np.linspace(0, 4, 50)
+ >>> y = func(xdata, 2.5, 1.3, 0.5)
+ >>> rng = np.random.default_rng()
+ >>> y_noise = 0.2 * rng.normal(size=xdata.size)
+ >>> ydata = y + y_noise
+ >>> plt.plot(xdata, ydata, 'b-', label='data')
+
+ Fit for the parameters a, b, c of the function `func`:
+
+ >>> popt, pcov = curve_fit(func, xdata, ydata)
+ >>> popt
+ array([2.56274217, 1.37268521, 0.47427475])
+ >>> plt.plot(xdata, func(xdata, *popt), 'r-',
+ ... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
+
+ Constrain the optimization to the region of ``0 <= a <= 3``,
+ ``0 <= b <= 1`` and ``0 <= c <= 0.5``:
+
+ >>> popt, pcov = curve_fit(func, xdata, ydata, bounds=(0, [3., 1., 0.5]))
+ >>> popt
+ array([2.43736712, 1. , 0.34463856])
+ >>> plt.plot(xdata, func(xdata, *popt), 'g--',
+ ... label='fit: a=%5.3f, b=%5.3f, c=%5.3f' % tuple(popt))
+
+ >>> plt.xlabel('x')
+ >>> plt.ylabel('y')
+ >>> plt.legend()
+ >>> plt.show()
+
+ For reliable results, the model `func` should not be overparametrized;
+ redundant parameters can cause unreliable covariance matrices and, in some
+ cases, poorer quality fits. As a quick check of whether the model may be
+ overparameterized, calculate the condition number of the covariance matrix:
+
+ >>> np.linalg.cond(pcov)
+ 34.571092161547405 # may vary
+
+ The value is small, so it does not raise much concern. If, however, we were
+ to add a fourth parameter ``d`` to `func` with the same effect as ``a``:
+
+ >>> def func2(x, a, b, c, d):
+ ... return a * d * np.exp(-b * x) + c # a and d are redundant
+ >>> popt, pcov = curve_fit(func2, xdata, ydata)
+ >>> np.linalg.cond(pcov)
+ 1.13250718925596e+32 # may vary
+
+ Such a large value is cause for concern. The diagonal elements of the
+ covariance matrix, which is related to uncertainty of the fit, gives more
+ information:
+
+ >>> np.diag(pcov)
+ array([1.48814742e+29, 3.78596560e-02, 5.39253738e-03, 2.76417220e+28]) # may vary
+
+ Note that the first and last terms are much larger than the other elements,
+ suggesting that the optimal values of these parameters are ambiguous and
+ that only one of these parameters is needed in the model.
+
+ If the optimal parameters of `f` differ by multiple orders of magnitude, the
+ resulting fit can be inaccurate. Sometimes, `curve_fit` can fail to find any
+ results:
+
+ >>> ydata = func(xdata, 500000, 0.01, 15)
+ >>> try:
+ ... popt, pcov = curve_fit(func, xdata, ydata, method = 'trf')
+ ... except RuntimeError as e:
+ ... print(e)
+ Optimal parameters not found: The maximum number of function evaluations is
+ exceeded.
+
+ If parameter scale is roughly known beforehand, it can be defined in
+ `x_scale` argument:
+
+ >>> popt, pcov = curve_fit(func, xdata, ydata, method = 'trf',
+ ... x_scale = [1000, 1, 1])
+ >>> popt
+ array([5.00000000e+05, 1.00000000e-02, 1.49999999e+01])
+ """
+ if p0 is None:
+ # determine number of parameters by inspecting the function
+ sig = _getfullargspec(f)
+ args = sig.args
+ if len(args) < 2:
+ raise ValueError("Unable to determine number of fit parameters.")
+ n = len(args) - 1
+ else:
+ p0 = np.atleast_1d(p0)
+ n = p0.size
+
+ if isinstance(bounds, Bounds):
+ lb, ub = bounds.lb, bounds.ub
+ else:
+ lb, ub = prepare_bounds(bounds, n)
+ if p0 is None:
+ p0 = _initialize_feasible(lb, ub)
+
+ bounded_problem = np.any((lb > -np.inf) | (ub < np.inf))
+ if method is None:
+ if bounded_problem:
+ method = 'trf'
+ else:
+ method = 'lm'
+
+ if method == 'lm' and bounded_problem:
+ raise ValueError("Method 'lm' only works for unconstrained problems. "
+ "Use 'trf' or 'dogbox' instead.")
+
+ if check_finite is None:
+ check_finite = True if nan_policy is None else False
+
+ # optimization may produce garbage for float32 inputs, cast them to float64
+ if check_finite:
+ ydata = np.asarray_chkfinite(ydata, float)
+ else:
+ ydata = np.asarray(ydata, float)
+
+ if isinstance(xdata, list | tuple | np.ndarray):
+ # `xdata` is passed straight to the user-defined `f`, so allow
+ # non-array_like `xdata`.
+ if check_finite:
+ xdata = np.asarray_chkfinite(xdata, float)
+ else:
+ xdata = np.asarray(xdata, float)
+
+ if ydata.size == 0:
+ raise ValueError("`ydata` must not be empty!")
+
+ # nan handling is needed only if check_finite is False because if True,
+ # the x-y data are already checked, and they don't contain nans.
+ if not check_finite and nan_policy is not None:
+ if nan_policy == "propagate":
+ msg = "`nan_policy='propagate'` is not supported by this function."
+ raise ValueError(msg)
+ if nan_policy not in ("raise", "omit"):
+ # Override error message raised by _contains_nan
+ msg = "nan_policy must be one of {None, 'raise', 'omit'}"
+ raise ValueError(msg)
+
+ x_contains_nan = _contains_nan(xdata, nan_policy)
+ y_contains_nan = _contains_nan(ydata, nan_policy)
+
+ if (x_contains_nan or y_contains_nan) and nan_policy == 'omit':
+ # ignore NaNs for N dimensional arrays
+ has_nan = np.isnan(xdata)
+ has_nan = has_nan.any(axis=tuple(range(has_nan.ndim-1)))
+ has_nan |= np.isnan(ydata)
+
+ xdata = xdata[..., ~has_nan]
+ ydata = ydata[~has_nan]
+
+ # Also omit the corresponding entries from sigma
+ if sigma is not None:
+ sigma = np.asarray(sigma)
+ if sigma.ndim == 1:
+ sigma = sigma[~has_nan]
+ elif sigma.ndim == 2:
+ sigma = sigma[~has_nan, :]
+ sigma = sigma[:, ~has_nan]
+
+ # Determine type of sigma
+ if sigma is not None:
+ sigma = np.asarray(sigma)
+
+ # if 1-D or a scalar, sigma are errors, define transform = 1/sigma
+ if sigma.size == 1 or sigma.shape == (ydata.size,):
+ transform = 1.0 / sigma
+ # if 2-D, sigma is the covariance matrix,
+ # define transform = L such that L L^T = C
+ elif sigma.shape == (ydata.size, ydata.size):
+ try:
+ # scipy.linalg.cholesky requires lower=True to return L L^T = A
+ transform = cholesky(sigma, lower=True)
+ except LinAlgError as e:
+ raise ValueError("`sigma` must be positive definite.") from e
+ else:
+ raise ValueError("`sigma` has incorrect shape.")
+ else:
+ transform = None
+
+ func = _lightweight_memoizer(_wrap_func(f, xdata, ydata, transform))
+
+ if callable(jac):
+ jac = _lightweight_memoizer(_wrap_jac(jac, xdata, transform))
+ elif jac is None and method != 'lm':
+ jac = '2-point'
+
+ if 'args' in kwargs:
+ # The specification for the model function `f` does not support
+ # additional arguments. Refer to the `curve_fit` docstring for
+ # acceptable call signatures of `f`.
+ raise ValueError("'args' is not a supported keyword argument.")
+
+ if method == 'lm':
+ # if ydata.size == 1, this might be used for broadcast.
+ if ydata.size != 1 and n > ydata.size:
+ raise TypeError(f"The number of func parameters={n} must not"
+ f" exceed the number of data points={ydata.size}")
+ res = leastsq(func, p0, Dfun=jac, full_output=1, **kwargs)
+ popt, pcov, infodict, errmsg, ier = res
+ ysize = len(infodict['fvec'])
+ cost = np.sum(infodict['fvec'] ** 2)
+ if ier not in [1, 2, 3, 4]:
+ raise RuntimeError("Optimal parameters not found: " + errmsg)
+ else:
+ # Rename maxfev (leastsq) to max_nfev (least_squares), if specified.
+ if 'max_nfev' not in kwargs:
+ kwargs['max_nfev'] = kwargs.pop('maxfev', None)
+
+ res = least_squares(func, p0, jac=jac, bounds=bounds, method=method,
+ **kwargs)
+
+ if not res.success:
+ raise RuntimeError("Optimal parameters not found: " + res.message)
+
+ infodict = dict(nfev=res.nfev, fvec=res.fun)
+ ier = res.status
+ errmsg = res.message
+
+ ysize = len(res.fun)
+ cost = 2 * res.cost # res.cost is half sum of squares!
+ popt = res.x
+
+ # Do Moore-Penrose inverse discarding zero singular values.
+ _, s, VT = svd(res.jac, full_matrices=False)
+ threshold = np.finfo(float).eps * max(res.jac.shape) * s[0]
+ s = s[s > threshold]
+ VT = VT[:s.size]
+ pcov = np.dot(VT.T / s**2, VT)
+
+ warn_cov = False
+ if pcov is None or np.isnan(pcov).any():
+ # indeterminate covariance
+ pcov = zeros((len(popt), len(popt)), dtype=float)
+ pcov.fill(inf)
+ warn_cov = True
+ elif not absolute_sigma:
+ if ysize > p0.size:
+ s_sq = cost / (ysize - p0.size)
+ pcov = pcov * s_sq
+ else:
+ pcov.fill(inf)
+ warn_cov = True
+
+ if warn_cov:
+ warnings.warn('Covariance of the parameters could not be estimated',
+ category=OptimizeWarning, stacklevel=2)
+
+ if full_output:
+ return popt, pcov, infodict, errmsg, ier
+ else:
+ return popt, pcov
+
+
+def check_gradient(fcn, Dfcn, x0, args=(), col_deriv=0):
+ """Perform a simple check on the gradient for correctness.
+
+ """
+
+ x = atleast_1d(x0)
+ n = len(x)
+ x = x.reshape((n,))
+ fvec = atleast_1d(fcn(x, *args))
+ m = len(fvec)
+ fvec = fvec.reshape((m,))
+ ldfjac = m
+ fjac = atleast_1d(Dfcn(x, *args))
+ fjac = fjac.reshape((m, n))
+ if col_deriv == 0:
+ fjac = transpose(fjac)
+
+ xp = zeros((n,), float)
+ err = zeros((m,), float)
+ fvecp = None
+ _minpack._chkder(m, n, x, fvec, fjac, ldfjac, xp, fvecp, 1, err)
+
+ fvecp = atleast_1d(fcn(xp, *args))
+ fvecp = fvecp.reshape((m,))
+ _minpack._chkder(m, n, x, fvec, fjac, ldfjac, xp, fvecp, 2, err)
+
+ good = (prod(greater(err, 0.5), axis=0))
+
+ return (good, err)
+
+
+def _del2(p0, p1, d):
+ return p0 - np.square(p1 - p0) / d
+
+
+def _relerr(actual, desired):
+ return (actual - desired) / desired
+
+
+def _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel):
+ p0 = x0
+ for i in range(maxiter):
+ p1 = func(p0, *args)
+ if use_accel:
+ p2 = func(p1, *args)
+ d = p2 - 2.0 * p1 + p0
+ p = xpx.apply_where(d != 0, (p0, p1, d), _del2, fill_value=p2)
+ else:
+ p = p1
+ relerr = xpx.apply_where(p0 != 0, (p, p0), _relerr, fill_value=p)
+ if np.all(np.abs(relerr) < xtol):
+ return p
+ p0 = p
+ msg = f"Failed to converge after {maxiter} iterations, value is {p}"
+ raise RuntimeError(msg)
+
+
+def fixed_point(func, x0, args=(), xtol=1e-8, maxiter=500, method='del2'):
+ """
+ Find a fixed point of the function.
+
+ Given a function of one or more variables and a starting point, find a
+ fixed point of the function: i.e., where ``func(x0) == x0``.
+
+ Parameters
+ ----------
+ func : function
+ Function to evaluate.
+ x0 : array_like
+ Fixed point of function.
+ args : tuple, optional
+ Extra arguments to `func`.
+ xtol : float, optional
+ Convergence tolerance, defaults to 1e-08.
+ maxiter : int, optional
+ Maximum number of iterations, defaults to 500.
+ method : {"del2", "iteration"}, optional
+ Method of finding the fixed-point, defaults to "del2",
+ which uses Steffensen's Method with Aitken's ``Del^2``
+ convergence acceleration [1]_. The "iteration" method simply iterates
+ the function until convergence is detected, without attempting to
+ accelerate the convergence.
+
+ References
+ ----------
+ .. [1] Burden, Faires, "Numerical Analysis", 5th edition, pg. 80
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import optimize
+ >>> def func(x, c1, c2):
+ ... return np.sqrt(c1/(x+c2))
+ >>> c1 = np.array([10,12.])
+ >>> c2 = np.array([3, 5.])
+ >>> optimize.fixed_point(func, [1.2, 1.3], args=(c1,c2))
+ array([ 1.4920333 , 1.37228132])
+
+ """
+ use_accel = {'del2': True, 'iteration': False}[method]
+ x0 = _asarray_validated(x0, as_inexact=True)
+ return _fixed_point_helper(func, x0, args, xtol, maxiter, use_accel)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..2e71d35a93f82327fbb49db5d89938746c3e7720
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_moduleTNC.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:e35be05f309a951cb366782f9e945d59e13b61c3d89071085f950c9a486d6cba
+size 145984
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_nnls.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_nnls.py
new file mode 100644
index 0000000000000000000000000000000000000000..9e74a48764a7e1182f72d1ba6ce63251d7c9aef2
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_nnls.py
@@ -0,0 +1,96 @@
+import numpy as np
+from ._slsqplib import nnls as _nnls
+from scipy._lib.deprecation import _deprecate_positional_args, _NoValue
+
+
+__all__ = ['nnls']
+
+
+@_deprecate_positional_args(version='1.18.0',
+ deprecated_args={'atol'})
+def nnls(A, b, *, maxiter=None, atol=_NoValue):
+ """
+ Solve ``argmin_x || Ax - b ||_2^2`` for ``x>=0``.
+
+ This problem, often called as NonNegative Least Squares, is a convex
+ optimization problem with convex constraints. It typically arises when
+ the ``x`` models quantities for which only nonnegative values are
+ attainable; weight of ingredients, component costs and so on.
+
+ Parameters
+ ----------
+ A : (m, n) ndarray
+ Coefficient array
+ b : (m,) ndarray, float
+ Right-hand side vector.
+ maxiter: int, optional
+ Maximum number of iterations, optional. Default value is ``3 * n``.
+ atol : float, optional
+ .. deprecated:: 1.18.0
+ This parameter is deprecated and will be removed in SciPy 1.18.0.
+ It is not used in the implementation.
+
+ Returns
+ -------
+ x : ndarray
+ Solution vector.
+ rnorm : float
+ The 2-norm of the residual, ``|| Ax-b ||_2``.
+
+ See Also
+ --------
+ lsq_linear : Linear least squares with bounds on the variables
+
+ Notes
+ -----
+ The code is based on the classical algorithm of [1]_. It utilizes an active
+ set method and solves the KKT (Karush-Kuhn-Tucker) conditions for the
+ non-negative least squares problem.
+
+ References
+ ----------
+ .. [1] : Lawson C., Hanson R.J., "Solving Least Squares Problems", SIAM,
+ 1995, :doi:`10.1137/1.9781611971217`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import nnls
+ ...
+ >>> A = np.array([[1, 0], [1, 0], [0, 1]])
+ >>> b = np.array([2, 1, 1])
+ >>> nnls(A, b)
+ (array([1.5, 1. ]), 0.7071067811865475)
+
+ >>> b = np.array([-1, -1, -1])
+ >>> nnls(A, b)
+ (array([0., 0.]), 1.7320508075688772)
+
+ """
+
+ A = np.asarray_chkfinite(A, dtype=np.float64, order='C')
+ b = np.asarray_chkfinite(b, dtype=np.float64)
+
+ if len(A.shape) != 2:
+ raise ValueError(f"Expected a 2D array, but the shape of A is {A.shape}")
+
+ if (b.ndim > 2) or ((b.ndim == 2) and (b.shape[1] != 1)):
+ raise ValueError("Expected a 1D array,(or 2D with one column), but the,"
+ f" shape of b is {b.shape}")
+ elif (b.ndim == 2) and (b.shape[1] == 1):
+ b = b.ravel()
+
+ m, n = A.shape
+
+ if m != b.shape[0]:
+ raise ValueError(
+ "Incompatible dimensions. The first dimension of " +
+ f"A is {m}, while the shape of b is {(b.shape[0], )}")
+
+ if not maxiter:
+ maxiter = 3*n
+ x, rnorm, info = _nnls(A, b, maxiter)
+ if info == 3:
+ raise RuntimeError("Maximum number of iterations reached.")
+
+ return x, rnorm
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_nonlin.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..f71bb5e4b2e3166860b2b91ea2411cd95e33caa2
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_nonlin.py
@@ -0,0 +1,1648 @@
+# Copyright (C) 2009, Pauli Virtanen
+# Distributed under the same license as SciPy.
+
+import inspect
+import sys
+import warnings
+
+import numpy as np
+from numpy import asarray, dot, vdot
+
+from scipy.linalg import norm, solve, inv, qr, svd, LinAlgError
+import scipy.sparse.linalg
+import scipy.sparse
+from scipy.linalg import get_blas_funcs
+from scipy._lib._util import copy_if_needed, _dedent_for_py313
+from scipy._lib._util import getfullargspec_no_self as _getfullargspec
+from ._linesearch import scalar_search_wolfe1, scalar_search_armijo
+from inspect import signature
+from difflib import get_close_matches
+from types import GenericAlias
+
+
+__all__ = [
+ 'broyden1', 'broyden2', 'anderson', 'linearmixing',
+ 'diagbroyden', 'excitingmixing', 'newton_krylov',
+ 'BroydenFirst', 'KrylovJacobian', 'InverseJacobian', 'NoConvergence']
+
+#------------------------------------------------------------------------------
+# Utility functions
+#------------------------------------------------------------------------------
+
+
+class NoConvergence(Exception):
+ """Exception raised when nonlinear solver fails to converge within the specified
+ `maxiter`."""
+ pass
+
+
+def maxnorm(x):
+ return np.absolute(x).max()
+
+
+def _as_inexact(x):
+ """Return `x` as an array, of either floats or complex floats"""
+ x = asarray(x)
+ if not np.issubdtype(x.dtype, np.inexact):
+ return asarray(x, dtype=np.float64)
+ return x
+
+
+def _array_like(x, x0):
+ """Return ndarray `x` as same array subclass and shape as `x0`"""
+ x = np.reshape(x, np.shape(x0))
+ wrap = getattr(x0, '__array_wrap__', x.__array_wrap__)
+ return wrap(x)
+
+
+def _safe_norm(v):
+ if not np.isfinite(v).all():
+ return np.array(np.inf)
+ return norm(v)
+
+#------------------------------------------------------------------------------
+# Generic nonlinear solver machinery
+#------------------------------------------------------------------------------
+
+
+_doc_parts = dict(
+ params_basic=_dedent_for_py313("""
+ F : function(x) -> f
+ Function whose root to find; should take and return an array-like
+ object.
+ xin : array_like
+ Initial guess for the solution
+ """).strip(),
+ params_extra=_dedent_for_py313("""
+ iter : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ verbose : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make. If more are needed to
+ meet convergence, `NoConvergence` is raised.
+ f_tol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ f_rtol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ x_tol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ x_rtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in the
+ direction given by the Jacobian approximation. Defaults to 'armijo'.
+ callback : function, optional
+ Optional callback function. It is called on every iteration as
+ ``callback(x, f)`` where `x` is the current solution and `f`
+ the corresponding residual.
+
+ Returns
+ -------
+ sol : ndarray
+ An array (of similar array type as `x0`) containing the final solution.
+
+ Raises
+ ------
+ NoConvergence
+ When a solution was not found.
+
+ """).strip()
+)
+
+
+def _set_doc(obj):
+ if obj.__doc__:
+ obj.__doc__ = obj.__doc__ % _doc_parts
+
+
+def nonlin_solve(F, x0, jacobian='krylov', iter=None, verbose=False,
+ maxiter=None, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
+ tol_norm=None, line_search='armijo', callback=None,
+ full_output=False, raise_exception=True):
+ """
+ Find a root of a function, in a way suitable for large-scale problems.
+
+ Parameters
+ ----------
+ %(params_basic)s
+ jacobian : Jacobian
+ A Jacobian approximation: `Jacobian` object or something that
+ `asjacobian` can transform to one. Alternatively, a string specifying
+ which of the builtin Jacobian approximations to use:
+
+ krylov, broyden1, broyden2, anderson
+ diagbroyden, linearmixing, excitingmixing
+
+ %(params_extra)s
+ full_output : bool
+ If true, returns a dictionary `info` containing convergence
+ information.
+ raise_exception : bool
+ If True, a `NoConvergence` exception is raise if no solution is found.
+
+ See Also
+ --------
+ asjacobian, Jacobian
+
+ Notes
+ -----
+ This algorithm implements the inexact Newton method, with
+ backtracking or full line searches. Several Jacobian
+ approximations are available, including Krylov and Quasi-Newton
+ methods.
+
+ References
+ ----------
+ .. [KIM] C. T. Kelley, \"Iterative Methods for Linear and Nonlinear
+ Equations\". Society for Industrial and Applied Mathematics. (1995)
+ https://archive.siam.org/books/kelley/fr16/
+
+ """
+ # Can't use default parameters because it's being explicitly passed as None
+ # from the calling function, so we need to set it here.
+ tol_norm = maxnorm if tol_norm is None else tol_norm
+ condition = TerminationCondition(f_tol=f_tol, f_rtol=f_rtol,
+ x_tol=x_tol, x_rtol=x_rtol,
+ iter=iter, norm=tol_norm)
+
+ x0 = _as_inexact(x0)
+ def func(z):
+ return _as_inexact(F(_array_like(z, x0))).flatten()
+ x = x0.flatten()
+
+ dx = np.full_like(x, np.inf)
+ Fx = func(x)
+ Fx_norm = norm(Fx)
+
+ jacobian = asjacobian(jacobian)
+ jacobian.setup(x.copy(), Fx, func)
+
+ if maxiter is None:
+ if iter is not None:
+ maxiter = iter + 1
+ else:
+ maxiter = 100*(x.size+1)
+
+ if line_search is True:
+ line_search = 'armijo'
+ elif line_search is False:
+ line_search = None
+
+ if line_search not in (None, 'armijo', 'wolfe'):
+ raise ValueError("Invalid line search")
+
+ # Solver tolerance selection
+ gamma = 0.9
+ eta_max = 0.9999
+ eta_treshold = 0.1
+ eta = 1e-3
+
+ for n in range(maxiter):
+ status = condition.check(Fx, x, dx)
+ if status:
+ break
+
+ # The tolerance, as computed for scipy.sparse.linalg.* routines
+ tol = min(eta, eta*Fx_norm)
+ dx = -jacobian.solve(Fx, tol=tol)
+
+ if norm(dx) == 0:
+ raise ValueError("Jacobian inversion yielded zero vector. "
+ "This indicates a bug in the Jacobian "
+ "approximation.")
+
+ # Line search, or Newton step
+ if line_search:
+ s, x, Fx, Fx_norm_new = _nonlin_line_search(func, x, Fx, dx,
+ line_search)
+ else:
+ s = 1.0
+ x = x + dx
+ Fx = func(x)
+ Fx_norm_new = norm(Fx)
+
+ jacobian.update(x.copy(), Fx)
+
+ if callback:
+ callback(x, Fx)
+
+ # Adjust forcing parameters for inexact methods
+ eta_A = gamma * Fx_norm_new**2 / Fx_norm**2
+ if gamma * eta**2 < eta_treshold:
+ eta = min(eta_max, eta_A)
+ else:
+ eta = min(eta_max, max(eta_A, gamma*eta**2))
+
+ Fx_norm = Fx_norm_new
+
+ # Print status
+ if verbose:
+ sys.stdout.write(f"{n}: |F(x)| = {tol_norm(Fx):g}; step {s:g}\n")
+ sys.stdout.flush()
+ else:
+ if raise_exception:
+ raise NoConvergence(_array_like(x, x0))
+ else:
+ status = 2
+
+ if full_output:
+ info = {'nit': condition.iteration,
+ 'fun': Fx,
+ 'status': status,
+ 'success': status == 1,
+ 'message': {1: 'A solution was found at the specified '
+ 'tolerance.',
+ 2: 'The maximum number of iterations allowed '
+ 'has been reached.'
+ }[status]
+ }
+ return _array_like(x, x0), info
+ else:
+ return _array_like(x, x0)
+
+
+_set_doc(nonlin_solve)
+
+
+def _nonlin_line_search(func, x, Fx, dx, search_type='armijo', rdiff=1e-8,
+ smin=1e-2):
+ tmp_s = [0]
+ tmp_Fx = [Fx]
+ tmp_phi = [norm(Fx)**2]
+ s_norm = norm(x) / norm(dx)
+
+ def phi(s, store=True):
+ if s == tmp_s[0]:
+ return tmp_phi[0]
+ xt = x + s*dx
+ v = func(xt)
+ p = _safe_norm(v)**2
+ if store:
+ tmp_s[0] = s
+ tmp_phi[0] = p
+ tmp_Fx[0] = v
+ return p
+
+ def derphi(s):
+ ds = (abs(s) + s_norm + 1) * rdiff
+ return (phi(s+ds, store=False) - phi(s)) / ds
+
+ if search_type == 'wolfe':
+ s, phi1, phi0 = scalar_search_wolfe1(phi, derphi, tmp_phi[0],
+ xtol=1e-2, amin=smin)
+ elif search_type == 'armijo':
+ s, phi1 = scalar_search_armijo(phi, tmp_phi[0], -tmp_phi[0],
+ amin=smin)
+
+ if s is None:
+ # XXX: No suitable step length found. Take the full Newton step,
+ # and hope for the best.
+ s = 1.0
+
+ x = x + s*dx
+ if s == tmp_s[0]:
+ Fx = tmp_Fx[0]
+ else:
+ Fx = func(x)
+ Fx_norm = norm(Fx)
+
+ return s, x, Fx, Fx_norm
+
+
+class TerminationCondition:
+ """
+ Termination condition for an iteration. It is terminated if
+
+ - |F| < f_rtol*|F_0|, AND
+ - |F| < f_tol
+
+ AND
+
+ - |dx| < x_rtol*|x|, AND
+ - |dx| < x_tol
+
+ """
+ def __init__(self, f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
+ iter=None, norm=maxnorm):
+
+ if f_tol is None:
+ f_tol = np.finfo(np.float64).eps ** (1./3)
+ if f_rtol is None:
+ f_rtol = np.inf
+ if x_tol is None:
+ x_tol = np.inf
+ if x_rtol is None:
+ x_rtol = np.inf
+
+ self.x_tol = x_tol
+ self.x_rtol = x_rtol
+ self.f_tol = f_tol
+ self.f_rtol = f_rtol
+
+ self.norm = norm
+
+ self.iter = iter
+
+ self.f0_norm = None
+ self.iteration = 0
+
+ def check(self, f, x, dx):
+ self.iteration += 1
+ f_norm = self.norm(f)
+ x_norm = self.norm(x)
+ dx_norm = self.norm(dx)
+
+ if self.f0_norm is None:
+ self.f0_norm = f_norm
+
+ if f_norm == 0:
+ return 1
+
+ if self.iter is not None:
+ # backwards compatibility with SciPy 0.6.0
+ return 2 * (self.iteration > self.iter)
+
+ # NB: condition must succeed for rtol=inf even if norm == 0
+ return int((f_norm <= self.f_tol
+ and f_norm/self.f_rtol <= self.f0_norm)
+ and (dx_norm <= self.x_tol
+ and dx_norm/self.x_rtol <= x_norm))
+
+
+#------------------------------------------------------------------------------
+# Generic Jacobian approximation
+#------------------------------------------------------------------------------
+
+class Jacobian:
+ """
+ Common interface for Jacobians or Jacobian approximations.
+
+ The optional methods come useful when implementing trust region
+ etc., algorithms that often require evaluating transposes of the
+ Jacobian.
+
+ Methods
+ -------
+ solve
+ Returns J^-1 * v
+ update
+ Updates Jacobian to point `x` (where the function has residual `Fx`)
+
+ matvec : optional
+ Returns J * v
+ rmatvec : optional
+ Returns A^H * v
+ rsolve : optional
+ Returns A^-H * v
+ matmat : optional
+ Returns A * V, where V is a dense matrix with dimensions (N,K).
+ todense : optional
+ Form the dense Jacobian matrix. Necessary for dense trust region
+ algorithms, and useful for testing.
+
+ Attributes
+ ----------
+ shape
+ Matrix dimensions (M, N)
+ dtype
+ Data type of the matrix.
+ func : callable, optional
+ Function the Jacobian corresponds to
+
+ """
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__ = classmethod(GenericAlias)
+
+ def __init__(self, **kw):
+ names = ["solve", "update", "matvec", "rmatvec", "rsolve",
+ "matmat", "todense", "shape", "dtype"]
+ for name, value in kw.items():
+ if name not in names:
+ raise ValueError(f"Unknown keyword argument {name}")
+ if value is not None:
+ setattr(self, name, kw[name])
+
+
+ if hasattr(self, "todense"):
+ def __array__(self, dtype=None, copy=None):
+ if dtype is not None:
+ raise ValueError(f"`dtype` must be None, was {dtype}")
+ return self.todense()
+
+ def aspreconditioner(self):
+ return InverseJacobian(self)
+
+ def solve(self, v, tol=0):
+ raise NotImplementedError
+
+ def update(self, x, F):
+ pass
+
+ def setup(self, x, F, func):
+ self.func = func
+ self.shape = (F.size, x.size)
+ self.dtype = F.dtype
+ if self.__class__.setup is Jacobian.setup:
+ # Call on the first point unless overridden
+ self.update(x, F)
+
+
+class InverseJacobian:
+ """
+ A simple wrapper that inverts the Jacobian using the `solve` method.
+
+ .. legacy:: class
+
+ See the newer, more consistent interfaces in :mod:`scipy.optimize`.
+
+ Parameters
+ ----------
+ jacobian : Jacobian
+ The Jacobian to invert.
+
+ Attributes
+ ----------
+ shape
+ Matrix dimensions (M, N)
+ dtype
+ Data type of the matrix.
+
+ """
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__ = classmethod(GenericAlias)
+
+ def __init__(self, jacobian):
+ self.jacobian = jacobian
+ self.matvec = jacobian.solve
+ self.update = jacobian.update
+ if hasattr(jacobian, 'setup'):
+ self.setup = jacobian.setup
+ if hasattr(jacobian, 'rsolve'):
+ self.rmatvec = jacobian.rsolve
+
+ @property
+ def shape(self):
+ return self.jacobian.shape
+
+ @property
+ def dtype(self):
+ return self.jacobian.dtype
+
+
+def asjacobian(J):
+ """
+ Convert given object to one suitable for use as a Jacobian.
+ """
+ spsolve = scipy.sparse.linalg.spsolve
+ if isinstance(J, Jacobian):
+ return J
+ elif inspect.isclass(J) and issubclass(J, Jacobian):
+ return J()
+ elif isinstance(J, np.ndarray):
+ if J.ndim > 2:
+ raise ValueError('array must have rank <= 2')
+ J = np.atleast_2d(np.asarray(J))
+ if J.shape[0] != J.shape[1]:
+ raise ValueError('array must be square')
+
+ return Jacobian(matvec=lambda v: dot(J, v),
+ rmatvec=lambda v: dot(J.conj().T, v),
+ solve=lambda v, tol=0: solve(J, v),
+ rsolve=lambda v, tol=0: solve(J.conj().T, v),
+ dtype=J.dtype, shape=J.shape)
+ elif scipy.sparse.issparse(J):
+ if J.shape[0] != J.shape[1]:
+ raise ValueError('matrix must be square')
+ return Jacobian(matvec=lambda v: J @ v,
+ rmatvec=lambda v: J.conj().T @ v,
+ solve=lambda v, tol=0: spsolve(J, v),
+ rsolve=lambda v, tol=0: spsolve(J.conj().T, v),
+ dtype=J.dtype, shape=J.shape)
+ elif hasattr(J, 'shape') and hasattr(J, 'dtype') and hasattr(J, 'solve'):
+ return Jacobian(matvec=getattr(J, 'matvec'),
+ rmatvec=getattr(J, 'rmatvec'),
+ solve=J.solve,
+ rsolve=getattr(J, 'rsolve'),
+ update=getattr(J, 'update'),
+ setup=getattr(J, 'setup'),
+ dtype=J.dtype,
+ shape=J.shape)
+ elif callable(J):
+ # Assume it's a function J(x) that returns the Jacobian
+ class Jac(Jacobian):
+ def update(self, x, F):
+ self.x = x
+
+ def solve(self, v, tol=0):
+ m = J(self.x)
+ if isinstance(m, np.ndarray):
+ return solve(m, v)
+ elif scipy.sparse.issparse(m):
+ return spsolve(m, v)
+ else:
+ raise ValueError("Unknown matrix type")
+
+ def matvec(self, v):
+ m = J(self.x)
+ if isinstance(m, np.ndarray):
+ return dot(m, v)
+ elif scipy.sparse.issparse(m):
+ return m @ v
+ else:
+ raise ValueError("Unknown matrix type")
+
+ def rsolve(self, v, tol=0):
+ m = J(self.x)
+ if isinstance(m, np.ndarray):
+ return solve(m.conj().T, v)
+ elif scipy.sparse.issparse(m):
+ return spsolve(m.conj().T, v)
+ else:
+ raise ValueError("Unknown matrix type")
+
+ def rmatvec(self, v):
+ m = J(self.x)
+ if isinstance(m, np.ndarray):
+ return dot(m.conj().T, v)
+ elif scipy.sparse.issparse(m):
+ return m.conj().T @ v
+ else:
+ raise ValueError("Unknown matrix type")
+ return Jac()
+ elif isinstance(J, str):
+ return dict(broyden1=BroydenFirst,
+ broyden2=BroydenSecond,
+ anderson=Anderson,
+ diagbroyden=DiagBroyden,
+ linearmixing=LinearMixing,
+ excitingmixing=ExcitingMixing,
+ krylov=KrylovJacobian)[J]()
+ else:
+ raise TypeError('Cannot convert object to a Jacobian')
+
+
+#------------------------------------------------------------------------------
+# Broyden
+#------------------------------------------------------------------------------
+
+class GenericBroyden(Jacobian):
+ # generic type compatibility with scipy-stubs
+ __class_getitem__ = classmethod(GenericAlias)
+
+ def setup(self, x0, f0, func):
+ Jacobian.setup(self, x0, f0, func)
+ self.last_f = f0
+ self.last_x = x0
+
+ if hasattr(self, 'alpha') and self.alpha is None:
+ # Autoscale the initial Jacobian parameter
+ # unless we have already guessed the solution.
+ normf0 = norm(f0)
+ if normf0:
+ self.alpha = 0.5*max(norm(x0), 1) / normf0
+ else:
+ self.alpha = 1.0
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ raise NotImplementedError
+
+ def update(self, x, f):
+ df = f - self.last_f
+ dx = x - self.last_x
+ self._update(x, f, dx, df, norm(dx), norm(df))
+ self.last_f = f
+ self.last_x = x
+
+
+class LowRankMatrix:
+ r"""
+ A matrix represented as
+
+ .. math:: \alpha I + \sum_{n=0}^{n=M} c_n d_n^\dagger
+
+ However, if the rank of the matrix reaches the dimension of the vectors,
+ full matrix representation will be used thereon.
+
+ """
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__ = classmethod(GenericAlias)
+
+ def __init__(self, alpha, n, dtype):
+ self.alpha = alpha
+ self.cs = []
+ self.ds = []
+ self.n = n
+ self.dtype = dtype
+ self.collapsed = None
+
+ @staticmethod
+ def _matvec(v, alpha, cs, ds):
+ axpy, scal, dotc = get_blas_funcs(['axpy', 'scal', 'dotc'],
+ cs[:1] + [v])
+ w = alpha * v
+ for c, d in zip(cs, ds):
+ a = dotc(d, v)
+ w = axpy(c, w, w.size, a)
+ return w
+
+ @staticmethod
+ def _solve(v, alpha, cs, ds):
+ """Evaluate w = M^-1 v"""
+ if len(cs) == 0:
+ return v/alpha
+
+ # (B + C D^H)^-1 = B^-1 - B^-1 C (I + D^H B^-1 C)^-1 D^H B^-1
+
+ axpy, dotc = get_blas_funcs(['axpy', 'dotc'], cs[:1] + [v])
+
+ c0 = cs[0]
+ A = alpha * np.identity(len(cs), dtype=c0.dtype)
+ for i, d in enumerate(ds):
+ for j, c in enumerate(cs):
+ A[i,j] += dotc(d, c)
+
+ q = np.zeros(len(cs), dtype=c0.dtype)
+ for j, d in enumerate(ds):
+ q[j] = dotc(d, v)
+ q /= alpha
+ q = solve(A, q)
+
+ w = v/alpha
+ for c, qc in zip(cs, q):
+ w = axpy(c, w, w.size, -qc)
+
+ return w
+
+ def matvec(self, v):
+ """Evaluate w = M v"""
+ if self.collapsed is not None:
+ return np.dot(self.collapsed, v)
+ return LowRankMatrix._matvec(v, self.alpha, self.cs, self.ds)
+
+ def rmatvec(self, v):
+ """Evaluate w = M^H v"""
+ if self.collapsed is not None:
+ return np.dot(self.collapsed.T.conj(), v)
+ return LowRankMatrix._matvec(v, np.conj(self.alpha), self.ds, self.cs)
+
+ def solve(self, v, tol=0):
+ """Evaluate w = M^-1 v"""
+ if self.collapsed is not None:
+ return solve(self.collapsed, v)
+ return LowRankMatrix._solve(v, self.alpha, self.cs, self.ds)
+
+ def rsolve(self, v, tol=0):
+ """Evaluate w = M^-H v"""
+ if self.collapsed is not None:
+ return solve(self.collapsed.T.conj(), v)
+ return LowRankMatrix._solve(v, np.conj(self.alpha), self.ds, self.cs)
+
+ def append(self, c, d):
+ if self.collapsed is not None:
+ self.collapsed += c[:,None] * d[None,:].conj()
+ return
+
+ self.cs.append(c)
+ self.ds.append(d)
+
+ if len(self.cs) > c.size:
+ self.collapse()
+
+ def __array__(self, dtype=None, copy=None):
+ if dtype is not None:
+ warnings.warn("LowRankMatrix is scipy-internal code, `dtype` "
+ f"should only be None but was {dtype} (not handled)",
+ stacklevel=3)
+ if copy is not None:
+ warnings.warn("LowRankMatrix is scipy-internal code, `copy` "
+ f"should only be None but was {copy} (not handled)",
+ stacklevel=3)
+ if self.collapsed is not None:
+ return self.collapsed
+
+ Gm = self.alpha*np.identity(self.n, dtype=self.dtype)
+ for c, d in zip(self.cs, self.ds):
+ Gm += c[:,None]*d[None,:].conj()
+ return Gm
+
+ def collapse(self):
+ """Collapse the low-rank matrix to a full-rank one."""
+ self.collapsed = np.array(self, copy=copy_if_needed)
+ self.cs = None
+ self.ds = None
+ self.alpha = None
+
+ def restart_reduce(self, rank):
+ """
+ Reduce the rank of the matrix by dropping all vectors.
+ """
+ if self.collapsed is not None:
+ return
+ assert rank > 0
+ if len(self.cs) > rank:
+ del self.cs[:]
+ del self.ds[:]
+
+ def simple_reduce(self, rank):
+ """
+ Reduce the rank of the matrix by dropping oldest vectors.
+ """
+ if self.collapsed is not None:
+ return
+ assert rank > 0
+ while len(self.cs) > rank:
+ del self.cs[0]
+ del self.ds[0]
+
+ def svd_reduce(self, max_rank, to_retain=None):
+ """
+ Reduce the rank of the matrix by retaining some SVD components.
+
+ This corresponds to the \"Broyden Rank Reduction Inverse\"
+ algorithm described in [1]_.
+
+ Note that the SVD decomposition can be done by solving only a
+ problem whose size is the effective rank of this matrix, which
+ is viable even for large problems.
+
+ Parameters
+ ----------
+ max_rank : int
+ Maximum rank of this matrix after reduction.
+ to_retain : int, optional
+ Number of SVD components to retain when reduction is done
+ (ie. rank > max_rank). Default is ``max_rank - 2``.
+
+ References
+ ----------
+ .. [1] B.A. van der Rotten, PhD thesis,
+ \"A limited memory Broyden method to solve high-dimensional
+ systems of nonlinear equations\". Mathematisch Instituut,
+ Universiteit Leiden, The Netherlands (2003).
+
+ https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf
+
+ """
+ if self.collapsed is not None:
+ return
+
+ p = max_rank
+ if to_retain is not None:
+ q = to_retain
+ else:
+ q = p - 2
+
+ if self.cs:
+ p = min(p, len(self.cs[0]))
+ q = max(0, min(q, p-1))
+
+ m = len(self.cs)
+ if m < p:
+ # nothing to do
+ return
+
+ C = np.array(self.cs).T
+ D = np.array(self.ds).T
+
+ D, R = qr(D, mode='economic')
+ C = dot(C, R.T.conj())
+
+ U, S, WH = svd(C, full_matrices=False)
+
+ C = dot(C, inv(WH))
+ D = dot(D, WH.T.conj())
+
+ for k in range(q):
+ self.cs[k] = C[:,k].copy()
+ self.ds[k] = D[:,k].copy()
+
+ del self.cs[q:]
+ del self.ds[q:]
+
+
+_doc_parts['broyden_params'] = _dedent_for_py313("""
+ alpha : float, optional
+ Initial guess for the Jacobian is ``(-1/alpha)``.
+ reduction_method : str or tuple, optional
+ Method used in ensuring that the rank of the Broyden matrix
+ stays low. Can either be a string giving the name of the method,
+ or a tuple of the form ``(method, param1, param2, ...)``
+ that gives the name of the method and values for additional parameters.
+
+ Methods available:
+
+ - ``restart``: drop all matrix columns. Has no extra parameters.
+ - ``simple``: drop oldest matrix column. Has no extra parameters.
+ - ``svd``: keep only the most significant SVD components.
+ Takes an extra parameter, ``to_retain``, which determines the
+ number of SVD components to retain when rank reduction is done.
+ Default is ``max_rank - 2``.
+
+ max_rank : int, optional
+ Maximum rank for the Broyden matrix.
+ Default is infinity (i.e., no rank reduction).
+ """).strip()
+
+
+class BroydenFirst(GenericBroyden):
+ """
+ Find a root of a function, using Broyden's first Jacobian approximation.
+
+ This method is also known as "Broyden's good method".
+
+ Parameters
+ ----------
+ %(params_basic)s
+ %(broyden_params)s
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='broyden1'`` in particular.
+
+ Notes
+ -----
+ This algorithm implements the inverse Jacobian Quasi-Newton update
+
+ .. math:: H_+ = H + (dx - H df) dx^\\dagger H / ( dx^\\dagger H df)
+
+ which corresponds to Broyden's first Jacobian update
+
+ .. math:: J_+ = J + (df - J dx) dx^\\dagger / dx^\\dagger dx
+
+
+ References
+ ----------
+ .. [1] B.A. van der Rotten, PhD thesis,
+ "A limited memory Broyden method to solve high-dimensional
+ systems of nonlinear equations". Mathematisch Instituut,
+ Universiteit Leiden, The Netherlands (2003).
+ https://math.leidenuniv.nl/scripties/Rotten.pdf
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations
+
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.broyden1(fun, [0, 0])
+ >>> sol
+ array([0.84116396, 0.15883641])
+
+ """
+
+ def __init__(self, alpha=None, reduction_method='restart', max_rank=None):
+ GenericBroyden.__init__(self)
+ self.alpha = alpha
+ self.Gm = None
+
+ if max_rank is None:
+ max_rank = np.inf
+ self.max_rank = max_rank
+
+ if isinstance(reduction_method, str):
+ reduce_params = ()
+ else:
+ reduce_params = reduction_method[1:]
+ reduction_method = reduction_method[0]
+ reduce_params = (max_rank - 1,) + reduce_params
+
+ if reduction_method == 'svd':
+ self._reduce = lambda: self.Gm.svd_reduce(*reduce_params)
+ elif reduction_method == 'simple':
+ self._reduce = lambda: self.Gm.simple_reduce(*reduce_params)
+ elif reduction_method == 'restart':
+ self._reduce = lambda: self.Gm.restart_reduce(*reduce_params)
+ else:
+ raise ValueError(f"Unknown rank reduction method '{reduction_method}'")
+
+ def setup(self, x, F, func):
+ GenericBroyden.setup(self, x, F, func)
+ self.Gm = LowRankMatrix(-self.alpha, self.shape[0], self.dtype)
+
+ def todense(self):
+ return inv(self.Gm)
+
+ def solve(self, f, tol=0):
+ r = self.Gm.matvec(f)
+ if not np.isfinite(r).all():
+ # singular; reset the Jacobian approximation
+ self.setup(self.last_x, self.last_f, self.func)
+ return self.Gm.matvec(f)
+ return r
+
+ def matvec(self, f):
+ return self.Gm.solve(f)
+
+ def rsolve(self, f, tol=0):
+ return self.Gm.rmatvec(f)
+
+ def rmatvec(self, f):
+ return self.Gm.rsolve(f)
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ self._reduce() # reduce first to preserve secant condition
+
+ v = self.Gm.rmatvec(dx)
+ c = dx - self.Gm.matvec(df)
+ d = v / vdot(df, v)
+
+ self.Gm.append(c, d)
+
+
+class BroydenSecond(BroydenFirst):
+ """
+ Find a root of a function, using Broyden\'s second Jacobian approximation.
+
+ This method is also known as \"Broyden's bad method\".
+
+ Parameters
+ ----------
+ %(params_basic)s
+ %(broyden_params)s
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='broyden2'`` in particular.
+
+ Notes
+ -----
+ This algorithm implements the inverse Jacobian Quasi-Newton update
+
+ .. math:: H_+ = H + (dx - H df) df^\\dagger / ( df^\\dagger df)
+
+ corresponding to Broyden's second method.
+
+ References
+ ----------
+ .. [1] B.A. van der Rotten, PhD thesis,
+ \"A limited memory Broyden method to solve high-dimensional
+ systems of nonlinear equations\". Mathematisch Instituut,
+ Universiteit Leiden, The Netherlands (2003).
+
+ https://web.archive.org/web/20161022015821/http://www.math.leidenuniv.nl/scripties/Rotten.pdf
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations
+
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.broyden2(fun, [0, 0])
+ >>> sol
+ array([0.84116365, 0.15883529])
+
+ """
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ self._reduce() # reduce first to preserve secant condition
+
+ v = df
+ c = dx - self.Gm.matvec(df)
+ d = v / df_norm**2
+ self.Gm.append(c, d)
+
+
+#------------------------------------------------------------------------------
+# Broyden-like (restricted memory)
+#------------------------------------------------------------------------------
+
+class Anderson(GenericBroyden):
+ """
+ Find a root of a function, using (extended) Anderson mixing.
+
+ The Jacobian is formed by for a 'best' solution in the space
+ spanned by last `M` vectors. As a result, only a MxM matrix
+ inversions and MxN multiplications are required. [Ey]_
+
+ Parameters
+ ----------
+ %(params_basic)s
+ alpha : float, optional
+ Initial guess for the Jacobian is (-1/alpha).
+ M : float, optional
+ Number of previous vectors to retain. Defaults to 5.
+ w0 : float, optional
+ Regularization parameter for numerical stability.
+ Compared to unity, good values of the order of 0.01.
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='anderson'`` in particular.
+
+ References
+ ----------
+ .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996).
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations
+
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.anderson(fun, [0, 0])
+ >>> sol
+ array([0.84116588, 0.15883789])
+
+ """
+
+ # Note:
+ #
+ # Anderson method maintains a rank M approximation of the inverse Jacobian,
+ #
+ # J^-1 v ~ -v*alpha + (dX + alpha dF) A^-1 dF^H v
+ # A = W + dF^H dF
+ # W = w0^2 diag(dF^H dF)
+ #
+ # so that for w0 = 0 the secant condition applies for last M iterates, i.e.,
+ #
+ # J^-1 df_j = dx_j
+ #
+ # for all j = 0 ... M-1.
+ #
+ # Moreover, (from Sherman-Morrison-Woodbury formula)
+ #
+ # J v ~ [ b I - b^2 C (I + b dF^H A^-1 C)^-1 dF^H ] v
+ # C = (dX + alpha dF) A^-1
+ # b = -1/alpha
+ #
+ # and after simplification
+ #
+ # J v ~ -v/alpha + (dX/alpha + dF) (dF^H dX - alpha W)^-1 dF^H v
+ #
+
+ def __init__(self, alpha=None, w0=0.01, M=5):
+ GenericBroyden.__init__(self)
+ self.alpha = alpha
+ self.M = M
+ self.dx = []
+ self.df = []
+ self.gamma = None
+ self.w0 = w0
+
+ def solve(self, f, tol=0):
+ dx = -self.alpha*f
+
+ n = len(self.dx)
+ if n == 0:
+ return dx
+
+ df_f = np.empty(n, dtype=f.dtype)
+ for k in range(n):
+ df_f[k] = vdot(self.df[k], f)
+
+ try:
+ gamma = solve(self.a, df_f)
+ except LinAlgError:
+ # singular; reset the Jacobian approximation
+ del self.dx[:]
+ del self.df[:]
+ return dx
+
+ for m in range(n):
+ dx += gamma[m]*(self.dx[m] + self.alpha*self.df[m])
+ return dx
+
+ def matvec(self, f):
+ dx = -f/self.alpha
+
+ n = len(self.dx)
+ if n == 0:
+ return dx
+
+ df_f = np.empty(n, dtype=f.dtype)
+ for k in range(n):
+ df_f[k] = vdot(self.df[k], f)
+
+ b = np.empty((n, n), dtype=f.dtype)
+ for i in range(n):
+ for j in range(n):
+ b[i,j] = vdot(self.df[i], self.dx[j])
+ if i == j and self.w0 != 0:
+ b[i,j] -= vdot(self.df[i], self.df[i])*self.w0**2*self.alpha
+ gamma = solve(b, df_f)
+
+ for m in range(n):
+ dx += gamma[m]*(self.df[m] + self.dx[m]/self.alpha)
+ return dx
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ if self.M == 0:
+ return
+
+ self.dx.append(dx)
+ self.df.append(df)
+
+ while len(self.dx) > self.M:
+ self.dx.pop(0)
+ self.df.pop(0)
+
+ n = len(self.dx)
+ a = np.zeros((n, n), dtype=f.dtype)
+
+ for i in range(n):
+ for j in range(i, n):
+ if i == j:
+ wd = self.w0**2
+ else:
+ wd = 0
+ a[i,j] = (1+wd)*vdot(self.df[i], self.df[j])
+
+ a += np.triu(a, 1).T.conj()
+ self.a = a
+
+#------------------------------------------------------------------------------
+# Simple iterations
+#------------------------------------------------------------------------------
+
+
+class DiagBroyden(GenericBroyden):
+ """
+ Find a root of a function, using diagonal Broyden Jacobian approximation.
+
+ The Jacobian approximation is derived from previous iterations, by
+ retaining only the diagonal of Broyden matrices.
+
+ .. warning::
+
+ This algorithm may be useful for specific problems, but whether
+ it will work may depend strongly on the problem.
+
+ Parameters
+ ----------
+ %(params_basic)s
+ alpha : float, optional
+ Initial guess for the Jacobian is (-1/alpha).
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='diagbroyden'`` in particular.
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations
+
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.diagbroyden(fun, [0, 0])
+ >>> sol
+ array([0.84116403, 0.15883384])
+
+ """
+
+ def __init__(self, alpha=None):
+ GenericBroyden.__init__(self)
+ self.alpha = alpha
+
+ def setup(self, x, F, func):
+ GenericBroyden.setup(self, x, F, func)
+ self.d = np.full((self.shape[0],), 1 / self.alpha, dtype=self.dtype)
+
+ def solve(self, f, tol=0):
+ return -f / self.d
+
+ def matvec(self, f):
+ return -f * self.d
+
+ def rsolve(self, f, tol=0):
+ return -f / self.d.conj()
+
+ def rmatvec(self, f):
+ return -f * self.d.conj()
+
+ def todense(self):
+ return np.diag(-self.d)
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ self.d -= (df + self.d*dx)*dx/dx_norm**2
+
+
+class LinearMixing(GenericBroyden):
+ """
+ Find a root of a function, using a scalar Jacobian approximation.
+
+ .. warning::
+
+ This algorithm may be useful for specific problems, but whether
+ it will work may depend strongly on the problem.
+
+ Parameters
+ ----------
+ %(params_basic)s
+ alpha : float, optional
+ The Jacobian approximation is (-1/alpha).
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='linearmixing'`` in particular.
+
+ """
+
+ def __init__(self, alpha=None):
+ GenericBroyden.__init__(self)
+ self.alpha = alpha
+
+ def solve(self, f, tol=0):
+ return -f*self.alpha
+
+ def matvec(self, f):
+ return -f/self.alpha
+
+ def rsolve(self, f, tol=0):
+ return -f*np.conj(self.alpha)
+
+ def rmatvec(self, f):
+ return -f/np.conj(self.alpha)
+
+ def todense(self):
+ return np.diag(np.full(self.shape[0], -1/self.alpha))
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ pass
+
+
+class ExcitingMixing(GenericBroyden):
+ """
+ Find a root of a function, using a tuned diagonal Jacobian approximation.
+
+ The Jacobian matrix is diagonal and is tuned on each iteration.
+
+ .. warning::
+
+ This algorithm may be useful for specific problems, but whether
+ it will work may depend strongly on the problem.
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='excitingmixing'`` in particular.
+
+ Parameters
+ ----------
+ %(params_basic)s
+ alpha : float, optional
+ Initial Jacobian approximation is (-1/alpha).
+ alphamax : float, optional
+ The entries of the diagonal Jacobian are kept in the range
+ ``[alpha, alphamax]``.
+ %(params_extra)s
+ """
+
+ def __init__(self, alpha=None, alphamax=1.0):
+ GenericBroyden.__init__(self)
+ self.alpha = alpha
+ self.alphamax = alphamax
+ self.beta = None
+
+ def setup(self, x, F, func):
+ GenericBroyden.setup(self, x, F, func)
+ self.beta = np.full((self.shape[0],), self.alpha, dtype=self.dtype)
+
+ def solve(self, f, tol=0):
+ return -f*self.beta
+
+ def matvec(self, f):
+ return -f/self.beta
+
+ def rsolve(self, f, tol=0):
+ return -f*self.beta.conj()
+
+ def rmatvec(self, f):
+ return -f/self.beta.conj()
+
+ def todense(self):
+ return np.diag(-1/self.beta)
+
+ def _update(self, x, f, dx, df, dx_norm, df_norm):
+ incr = f*self.last_f > 0
+ self.beta[incr] += self.alpha
+ self.beta[~incr] = self.alpha
+ np.clip(self.beta, 0, self.alphamax, out=self.beta)
+
+
+#------------------------------------------------------------------------------
+# Iterative/Krylov approximated Jacobians
+#------------------------------------------------------------------------------
+
+class KrylovJacobian(Jacobian):
+ """
+ Find a root of a function, using Krylov approximation for inverse Jacobian.
+
+ This method is suitable for solving large-scale problems.
+
+ Parameters
+ ----------
+ %(params_basic)s
+ rdiff : float, optional
+ Relative step size to use in numerical differentiation.
+ method : str or callable, optional
+ Krylov method to use to approximate the Jacobian. Can be a string,
+ or a function implementing the same interface as the iterative
+ solvers in `scipy.sparse.linalg`. If a string, needs to be one of:
+ ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``,
+ ``'tfqmr'``.
+
+ The default is `scipy.sparse.linalg.lgmres`.
+ inner_maxiter : int, optional
+ Parameter to pass to the "inner" Krylov solver: maximum number of
+ iterations. Iteration will stop after maxiter steps even if the
+ specified tolerance has not been achieved.
+ inner_M : LinearOperator or InverseJacobian
+ Preconditioner for the inner Krylov iteration.
+ Note that you can use also inverse Jacobians as (adaptive)
+ preconditioners. For example,
+
+ >>> from scipy.optimize import BroydenFirst, KrylovJacobian
+ >>> from scipy.optimize import InverseJacobian
+ >>> jac = BroydenFirst()
+ >>> kjac = KrylovJacobian(inner_M=InverseJacobian(jac))
+
+ If the preconditioner has a method named 'update', it will be called
+ as ``update(x, f)`` after each nonlinear step, with ``x`` giving
+ the current point, and ``f`` the current function value.
+ outer_k : int, optional
+ Size of the subspace kept across LGMRES nonlinear iterations.
+ See `scipy.sparse.linalg.lgmres` for details.
+ inner_kwargs : kwargs
+ Keyword parameters for the "inner" Krylov solver
+ (defined with `method`). Parameter names must start with
+ the `inner_` prefix which will be stripped before passing on
+ the inner method. See, e.g., `scipy.sparse.linalg.gmres` for details.
+ %(params_extra)s
+
+ See Also
+ --------
+ root : Interface to root finding algorithms for multivariate
+ functions. See ``method='krylov'`` in particular.
+ scipy.sparse.linalg.gmres
+ scipy.sparse.linalg.lgmres
+
+ Notes
+ -----
+ This function implements a Newton-Krylov solver. The basic idea is
+ to compute the inverse of the Jacobian with an iterative Krylov
+ method. These methods require only evaluating the Jacobian-vector
+ products, which are conveniently approximated by a finite difference:
+
+ .. math:: J v \\approx (f(x + \\omega*v/|v|) - f(x)) / \\omega
+
+ Due to the use of iterative matrix inverses, these methods can
+ deal with large nonlinear problems.
+
+ SciPy's `scipy.sparse.linalg` module offers a selection of Krylov
+ solvers to choose from. The default here is `lgmres`, which is a
+ variant of restarted GMRES iteration that reuses some of the
+ information obtained in the previous Newton steps to invert
+ Jacobians in subsequent steps.
+
+ For a review on Newton-Krylov methods, see for example [1]_,
+ and for the LGMRES sparse inverse method, see [2]_.
+
+ References
+ ----------
+ .. [1] C. T. Kelley, Solving Nonlinear Equations with Newton's Method,
+ SIAM, pp.57-83, 2003.
+ :doi:`10.1137/1.9780898718898.ch3`
+ .. [2] D.A. Knoll and D.E. Keyes, J. Comp. Phys. 193, 357 (2004).
+ :doi:`10.1016/j.jcp.2003.08.010`
+ .. [3] A.H. Baker and E.R. Jessup and T. Manteuffel,
+ SIAM J. Matrix Anal. Appl. 26, 962 (2005).
+ :doi:`10.1137/S0895479803422014`
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations
+
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * x[1] - 1.0,
+ ... 0.5 * (x[1] - x[0]) ** 2]
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.newton_krylov(fun, [0, 0])
+ >>> sol
+ array([0.66731771, 0.66536458])
+
+ """
+
+ def __init__(self, rdiff=None, method='lgmres', inner_maxiter=20,
+ inner_M=None, outer_k=10, **kw):
+ self.preconditioner = inner_M
+ self.rdiff = rdiff
+ # Note that this retrieves one of the named functions, or otherwise
+ # uses `method` as is (i.e., for a user-provided callable).
+ self.method = dict(
+ bicgstab=scipy.sparse.linalg.bicgstab,
+ gmres=scipy.sparse.linalg.gmres,
+ lgmres=scipy.sparse.linalg.lgmres,
+ cgs=scipy.sparse.linalg.cgs,
+ minres=scipy.sparse.linalg.minres,
+ tfqmr=scipy.sparse.linalg.tfqmr,
+ ).get(method, method)
+
+ self.method_kw = dict(maxiter=inner_maxiter, M=self.preconditioner)
+
+ if self.method is scipy.sparse.linalg.gmres:
+ # Replace GMRES's outer iteration with Newton steps
+ self.method_kw['restart'] = inner_maxiter
+ self.method_kw['maxiter'] = 1
+ self.method_kw.setdefault('atol', 0)
+ elif self.method in (scipy.sparse.linalg.gcrotmk,
+ scipy.sparse.linalg.bicgstab,
+ scipy.sparse.linalg.cgs):
+ self.method_kw.setdefault('atol', 0)
+ elif self.method is scipy.sparse.linalg.lgmres:
+ self.method_kw['outer_k'] = outer_k
+ # Replace LGMRES's outer iteration with Newton steps
+ self.method_kw['maxiter'] = 1
+ # Carry LGMRES's `outer_v` vectors across nonlinear iterations
+ self.method_kw.setdefault('outer_v', [])
+ self.method_kw.setdefault('prepend_outer_v', True)
+ # But don't carry the corresponding Jacobian*v products, in case
+ # the Jacobian changes a lot in the nonlinear step
+ #
+ # XXX: some trust-region inspired ideas might be more efficient...
+ # See e.g., Brown & Saad. But needs to be implemented separately
+ # since it's not an inexact Newton method.
+ self.method_kw.setdefault('store_outer_Av', False)
+ self.method_kw.setdefault('atol', 0)
+
+ # Retrieve the signature of the method to find the valid parameters
+ valid_inner_params = [
+ k for k in signature(self.method).parameters
+ if k not in ('self', 'args', 'kwargs')
+ ]
+
+ for key, value in kw.items():
+ if not key.startswith("inner_"):
+ raise ValueError(f"Unknown parameter {key}")
+ if key[6:] not in valid_inner_params:
+ # Use difflib to find close matches to the invalid key
+ inner_param_suggestions = get_close_matches(key[6:],
+ valid_inner_params,
+ n=1)
+ if inner_param_suggestions:
+ suggestion_msg = (f" Did you mean '"
+ f"{inner_param_suggestions[0]}'?")
+ else:
+ suggestion_msg = ""
+
+ # warn user that the parameter is not valid for the inner method
+ warnings.warn(
+ f"Option '{key}' is invalid for the inner method: {method}."
+ " It will be ignored."
+ "Please check inner method documentation for valid options."
+ + suggestion_msg,
+ stacklevel=3,
+ category=UserWarning,
+ # using `skip_file_prefixes` would be a good idea
+ # and should be added once we drop support for Python 3.11
+ )
+ # ignore this parameter and continue
+ continue
+ self.method_kw[key[6:]] = value
+
+ def _update_diff_step(self):
+ mx = abs(self.x0).max()
+ mf = abs(self.f0).max()
+ self.omega = self.rdiff * max(1, mx) / max(1, mf)
+
+ def matvec(self, v):
+ nv = norm(v)
+ if nv == 0:
+ return 0*v
+ sc = self.omega / nv
+ r = (self.func(self.x0 + sc*v) - self.f0) / sc
+ if not np.all(np.isfinite(r)) and np.all(np.isfinite(v)):
+ raise ValueError('Function returned non-finite results')
+ return r
+
+ def solve(self, rhs, tol=0):
+ if 'rtol' in self.method_kw:
+ sol, info = self.method(self.op, rhs, **self.method_kw)
+ else:
+ sol, info = self.method(self.op, rhs, rtol=tol, **self.method_kw)
+ return sol
+
+ def update(self, x, f):
+ self.x0 = x
+ self.f0 = f
+ self._update_diff_step()
+
+ # Update also the preconditioner, if possible
+ if self.preconditioner is not None:
+ if hasattr(self.preconditioner, 'update'):
+ self.preconditioner.update(x, f)
+
+ def setup(self, x, f, func):
+ Jacobian.setup(self, x, f, func)
+ self.x0 = x
+ self.f0 = f
+ self.op = scipy.sparse.linalg.aslinearoperator(self)
+
+ if self.rdiff is None:
+ self.rdiff = np.finfo(x.dtype).eps ** (1./2)
+
+ self._update_diff_step()
+
+ # Setup also the preconditioner, if possible
+ if self.preconditioner is not None:
+ if hasattr(self.preconditioner, 'setup'):
+ self.preconditioner.setup(x, f, func)
+
+
+#------------------------------------------------------------------------------
+# Wrapper functions
+#------------------------------------------------------------------------------
+
+def _nonlin_wrapper(name, jac):
+ """
+ Construct a solver wrapper with given name and Jacobian approx.
+
+ It inspects the keyword arguments of ``jac.__init__``, and allows to
+ use the same arguments in the wrapper function, in addition to the
+ keyword arguments of `nonlin_solve`
+
+ """
+ signature = _getfullargspec(jac.__init__)
+ args, varargs, varkw, defaults, kwonlyargs, kwdefaults, _ = signature
+ kwargs = list(zip(args[-len(defaults):], defaults))
+ kw_str = ", ".join([f"{k}={v!r}" for k, v in kwargs])
+ if kw_str:
+ kw_str = ", " + kw_str
+ kwkw_str = ", ".join([f"{k}={k}" for k, v in kwargs])
+ if kwkw_str:
+ kwkw_str = kwkw_str + ", "
+ if kwonlyargs:
+ raise ValueError(f'Unexpected signature {signature}')
+
+ # Construct the wrapper function so that its keyword arguments
+ # are visible in pydoc.help etc.
+ wrapper = """
+def %(name)s(F, xin, iter=None %(kw)s, verbose=False, maxiter=None,
+ f_tol=None, f_rtol=None, x_tol=None, x_rtol=None,
+ tol_norm=None, line_search='armijo', callback=None, **kw):
+ jac = %(jac)s(%(kwkw)s **kw)
+ return nonlin_solve(F, xin, jac, iter, verbose, maxiter,
+ f_tol, f_rtol, x_tol, x_rtol, tol_norm, line_search,
+ callback)
+"""
+
+ wrapper = wrapper % dict(name=name, kw=kw_str, jac=jac.__name__,
+ kwkw=kwkw_str)
+ ns = {}
+ ns.update(globals())
+ exec(wrapper, ns)
+ func = ns[name]
+ func.__doc__ = jac.__doc__
+ _set_doc(func)
+ return func
+
+
+broyden1 = _nonlin_wrapper('broyden1', BroydenFirst)
+broyden2 = _nonlin_wrapper('broyden2', BroydenSecond)
+anderson = _nonlin_wrapper('anderson', Anderson)
+linearmixing = _nonlin_wrapper('linearmixing', LinearMixing)
+diagbroyden = _nonlin_wrapper('diagbroyden', DiagBroyden)
+excitingmixing = _nonlin_wrapper('excitingmixing', ExcitingMixing)
+newton_krylov = _nonlin_wrapper('newton_krylov', KrylovJacobian)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_numdiff.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_numdiff.py
new file mode 100644
index 0000000000000000000000000000000000000000..98b137ed151a480128874bf662a6e4ec05c044f2
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_numdiff.py
@@ -0,0 +1,963 @@
+"""Routines for numerical differentiation."""
+import functools
+import numpy as np
+from numpy.linalg import norm
+
+from scipy.sparse.linalg import LinearOperator
+from ..sparse import issparse, isspmatrix, find, csc_array, csr_array, csr_matrix
+from ._group_columns import group_dense, group_sparse
+from scipy._lib._array_api import array_namespace
+from scipy._lib._util import MapWrapper
+from scipy._lib import array_api_extra as xpx
+
+
+def _adjust_scheme_to_bounds(x0, h, num_steps, scheme, lb, ub):
+ """Adjust final difference scheme to the presence of bounds.
+
+ Parameters
+ ----------
+ x0 : ndarray, shape (n,)
+ Point at which we wish to estimate derivative.
+ h : ndarray, shape (n,)
+ Desired absolute finite difference steps.
+ num_steps : int
+ Number of `h` steps in one direction required to implement finite
+ difference scheme. For example, 2 means that we need to evaluate
+ f(x0 + 2 * h) or f(x0 - 2 * h)
+ scheme : {'1-sided', '2-sided'}
+ Whether steps in one or both directions are required. In other
+ words '1-sided' applies to forward and backward schemes, '2-sided'
+ applies to center schemes.
+ lb : ndarray, shape (n,)
+ Lower bounds on independent variables.
+ ub : ndarray, shape (n,)
+ Upper bounds on independent variables.
+
+ Returns
+ -------
+ h_adjusted : ndarray, shape (n,)
+ Adjusted absolute step sizes. Step size decreases only if a sign flip
+ or switching to one-sided scheme doesn't allow to take a full step.
+ use_one_sided : ndarray of bool, shape (n,)
+ Whether to switch to one-sided scheme. Informative only for
+ ``scheme='2-sided'``.
+ """
+ if scheme == '1-sided':
+ use_one_sided = np.ones_like(h, dtype=bool)
+ elif scheme == '2-sided':
+ h = np.abs(h)
+ use_one_sided = np.zeros_like(h, dtype=bool)
+ else:
+ raise ValueError("`scheme` must be '1-sided' or '2-sided'.")
+
+ if np.all((lb == -np.inf) & (ub == np.inf)):
+ return h, use_one_sided
+
+ h_total = h * num_steps
+ h_adjusted = h.copy()
+
+ lower_dist = x0 - lb
+ upper_dist = ub - x0
+
+ if scheme == '1-sided':
+ x = x0 + h_total
+ violated = (x < lb) | (x > ub)
+ fitting = np.abs(h_total) <= np.maximum(lower_dist, upper_dist)
+ h_adjusted[violated & fitting] *= -1
+
+ forward = (upper_dist >= lower_dist) & ~fitting
+ h_adjusted[forward] = upper_dist[forward] / num_steps
+ backward = (upper_dist < lower_dist) & ~fitting
+ h_adjusted[backward] = -lower_dist[backward] / num_steps
+ elif scheme == '2-sided':
+ central = (lower_dist >= h_total) & (upper_dist >= h_total)
+
+ forward = (upper_dist >= lower_dist) & ~central
+ h_adjusted[forward] = np.minimum(
+ h[forward], 0.5 * upper_dist[forward] / num_steps)
+ use_one_sided[forward] = True
+
+ backward = (upper_dist < lower_dist) & ~central
+ h_adjusted[backward] = -np.minimum(
+ h[backward], 0.5 * lower_dist[backward] / num_steps)
+ use_one_sided[backward] = True
+
+ min_dist = np.minimum(upper_dist, lower_dist) / num_steps
+ adjusted_central = (~central & (np.abs(h_adjusted) <= min_dist))
+ h_adjusted[adjusted_central] = min_dist[adjusted_central]
+ use_one_sided[adjusted_central] = False
+
+ return h_adjusted, use_one_sided
+
+
+@functools.lru_cache
+def _eps_for_method(x0_dtype, f0_dtype, method):
+ """
+ Calculates relative EPS step to use for a given data type
+ and numdiff step method.
+
+ Progressively smaller steps are used for larger floating point types.
+
+ Parameters
+ ----------
+ f0_dtype: np.dtype
+ dtype of function evaluation
+
+ x0_dtype: np.dtype
+ dtype of parameter vector
+
+ method: {'2-point', '3-point', 'cs'}
+
+ Returns
+ -------
+ EPS: float
+ relative step size. May be np.float16, np.float32, np.float64
+
+ Notes
+ -----
+ The default relative step will be np.float64. However, if x0 or f0 are
+ smaller floating point types (np.float16, np.float32), then the smallest
+ floating point type is chosen.
+ """
+ # the default EPS value
+ EPS = np.finfo(np.float64).eps
+
+ x0_is_fp = False
+ if np.issubdtype(x0_dtype, np.inexact):
+ # if you're a floating point type then over-ride the default EPS
+ EPS = np.finfo(x0_dtype).eps
+ x0_itemsize = np.dtype(x0_dtype).itemsize
+ x0_is_fp = True
+
+ if np.issubdtype(f0_dtype, np.inexact):
+ f0_itemsize = np.dtype(f0_dtype).itemsize
+ # choose the smallest itemsize between x0 and f0
+ if x0_is_fp and f0_itemsize < x0_itemsize:
+ EPS = np.finfo(f0_dtype).eps
+
+ if method in ["2-point", "cs"]:
+ return EPS**0.5
+ elif method in ["3-point"]:
+ return EPS**(1/3)
+ else:
+ raise RuntimeError("Unknown step method, should be one of "
+ "{'2-point', '3-point', 'cs'}")
+
+
+def _compute_absolute_step(rel_step, x0, f0, method):
+ """
+ Computes an absolute step from a relative step for finite difference
+ calculation.
+
+ Parameters
+ ----------
+ rel_step: None or array-like
+ Relative step for the finite difference calculation
+ x0 : np.ndarray
+ Parameter vector
+ f0 : np.ndarray or scalar
+ method : {'2-point', '3-point', 'cs'}
+
+ Returns
+ -------
+ h : float
+ The absolute step size
+
+ Notes
+ -----
+ `h` will always be np.float64. However, if `x0` or `f0` are
+ smaller floating point dtypes (e.g. np.float32), then the absolute
+ step size will be calculated from the smallest floating point size.
+ """
+ # this is used instead of np.sign(x0) because we need
+ # sign_x0 to be 1 when x0 == 0.
+ sign_x0 = (x0 >= 0).astype(float) * 2 - 1
+
+ rstep = _eps_for_method(x0.dtype, f0.dtype, method)
+
+ if rel_step is None:
+ abs_step = rstep * sign_x0 * np.maximum(1.0, np.abs(x0))
+ else:
+ # User has requested specific relative steps.
+ # Don't multiply by max(1, abs(x0) because if x0 < 1 then their
+ # requested step is not used.
+ abs_step = rel_step * sign_x0 * np.abs(x0)
+
+ # however we don't want an abs_step of 0, which can happen if
+ # rel_step is 0, or x0 is 0. Instead, substitute a realistic step
+ dx = ((x0 + abs_step) - x0)
+ abs_step = np.where(dx == 0,
+ rstep * sign_x0 * np.maximum(1.0, np.abs(x0)),
+ abs_step)
+
+ return abs_step
+
+
+def _prepare_bounds(bounds, x0):
+ """
+ Prepares new-style bounds from a two-tuple specifying the lower and upper
+ limits for values in x0. If a value is not bound then the lower/upper bound
+ will be expected to be -np.inf/np.inf.
+
+ Examples
+ --------
+ >>> _prepare_bounds([(0, 1, 2), (1, 2, np.inf)], [0.5, 1.5, 2.5])
+ (array([0., 1., 2.]), array([ 1., 2., inf]))
+ """
+ lb, ub = (np.asarray(b, dtype=float) for b in bounds)
+ if lb.ndim == 0:
+ lb = np.resize(lb, x0.shape)
+
+ if ub.ndim == 0:
+ ub = np.resize(ub, x0.shape)
+
+ return lb, ub
+
+
+def group_columns(A, order=0):
+ """Group columns of a 2-D matrix for sparse finite differencing [1]_.
+
+ Two columns are in the same group if in each row at least one of them
+ has zero. A greedy sequential algorithm is used to construct groups.
+
+ Parameters
+ ----------
+ A : array_like or sparse array, shape (m, n)
+ Matrix of which to group columns.
+ order : int, iterable of int with shape (n,) or None
+ Permutation array which defines the order of columns enumeration.
+ If int or None, a random permutation is used with `order` used as
+ a random seed. Default is 0, that is use a random permutation but
+ guarantee repeatability.
+
+ Returns
+ -------
+ groups : ndarray of int, shape (n,)
+ Contains values from 0 to n_groups-1, where n_groups is the number
+ of found groups. Each value ``groups[i]`` is an index of a group to
+ which ith column assigned. The procedure was helpful only if
+ n_groups is significantly less than n.
+
+ References
+ ----------
+ .. [1] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+ sparse Jacobian matrices", Journal of the Institute of Mathematics
+ and its Applications, 13 (1974), pp. 117-120.
+ """
+ if issparse(A):
+ A = csc_array(A)
+ else:
+ A = np.atleast_2d(A)
+ A = (A != 0).astype(np.int32)
+
+ if A.ndim != 2:
+ raise ValueError("`A` must be 2-dimensional.")
+
+ m, n = A.shape
+
+ if order is None or np.isscalar(order):
+ rng = np.random.RandomState(order)
+ order = rng.permutation(n)
+ else:
+ order = np.asarray(order)
+ if order.shape != (n,):
+ raise ValueError("`order` has incorrect shape.")
+
+ A = A[:, order]
+
+ if issparse(A):
+ groups = group_sparse(m, n, A.indices, A.indptr)
+ else:
+ groups = group_dense(m, n, A)
+
+ groups[order] = groups.copy()
+
+ return groups
+
+
+def approx_derivative(fun, x0, method='3-point', rel_step=None, abs_step=None,
+ f0=None, bounds=(-np.inf, np.inf), sparsity=None,
+ as_linear_operator=False, args=(), kwargs=None,
+ full_output=False, workers=None):
+ """Compute finite difference approximation of the derivatives of a
+ vector-valued function.
+
+ If a function maps from R^n to R^m, its derivatives form m-by-n matrix
+ called the Jacobian, where an element (i, j) is a partial derivative of
+ f[i] with respect to x[j].
+
+ Parameters
+ ----------
+ fun : callable
+ Function of which to estimate the derivatives. The argument x
+ passed to this function is ndarray of shape (n,) (never a scalar
+ even if n=1). It must return 1-D array_like of shape (m,) or a scalar.
+ x0 : array_like of shape (n,) or float
+ Point at which to estimate the derivatives. Float will be converted
+ to a 1-D array.
+ method : {'3-point', '2-point', 'cs'}, optional
+ Finite difference method to use:
+ - '2-point' - use the first order accuracy forward or backward
+ difference.
+ - '3-point' - use central difference in interior points and the
+ second order accuracy forward or backward difference
+ near the boundary.
+ - 'cs' - use a complex-step finite difference scheme. This assumes
+ that the user function is real-valued and can be
+ analytically continued to the complex plane. Otherwise,
+ produces bogus results.
+ rel_step : None or array_like, optional
+ Relative step size to use. If None (default) the absolute step size is
+ computed as ``h = rel_step * sign(x0) * max(1, abs(x0))``, with
+ `rel_step` being selected automatically, see Notes. Otherwise
+ ``h = rel_step * sign(x0) * abs(x0)``. For ``method='3-point'`` the
+ sign of `h` is ignored. The calculated step size is possibly adjusted
+ to fit into the bounds.
+ abs_step : array_like, optional
+ Absolute step size to use, possibly adjusted to fit into the bounds.
+ For ``method='3-point'`` the sign of `abs_step` is ignored. By default
+ relative steps are used, only if ``abs_step is not None`` are absolute
+ steps used.
+ f0 : None or array_like, optional
+ If not None it is assumed to be equal to ``fun(x0)``, in this case
+ the ``fun(x0)`` is not called. Default is None.
+ bounds : tuple of array_like, optional
+ Lower and upper bounds on independent variables. Defaults to no bounds.
+ Each bound must match the size of `x0` or be a scalar, in the latter
+ case the bound will be the same for all variables. Use it to limit the
+ range of function evaluation. Bounds checking is not implemented
+ when `as_linear_operator` is True.
+ sparsity : {None, array_like, sparse array, 2-tuple}, optional
+ Defines a sparsity structure of the Jacobian matrix. If the Jacobian
+ matrix is known to have only few non-zero elements in each row, then
+ it's possible to estimate its several columns by a single function
+ evaluation [3]_. To perform such economic computations two ingredients
+ are required:
+
+ * structure : array_like or sparse array of shape (m, n). A zero
+ element means that a corresponding element of the Jacobian
+ identically equals to zero.
+ * groups : array_like of shape (n,). A column grouping for a given
+ sparsity structure, use `group_columns` to obtain it.
+
+ A single array or a sparse array is interpreted as a sparsity
+ structure, and groups are computed inside the function. A tuple is
+ interpreted as (structure, groups). If None (default), a standard
+ dense differencing will be used.
+
+ Note, that sparse differencing makes sense only for large Jacobian
+ matrices where each row contains few non-zero elements.
+ as_linear_operator : bool, optional
+ When True the function returns an `scipy.sparse.linalg.LinearOperator`.
+ Otherwise it returns a dense array or a sparse array depending on
+ `sparsity`. The linear operator provides an efficient way of computing
+ ``J.dot(p)`` for any vector ``p`` of shape (n,), but does not allow
+ direct access to individual elements of the matrix. By default
+ `as_linear_operator` is False.
+ args, kwargs : tuple and dict, optional
+ Additional arguments passed to `fun`. Both empty by default.
+ The calling signature is ``fun(x, *args, **kwargs)``.
+ full_output : bool, optional
+ If True then the function also returns a dictionary with extra information
+ about the calculation.
+ workers : int or map-like callable, optional
+ Supply a map-like callable, such as
+ `multiprocessing.Pool.map` for evaluating the population in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+ Alternatively, if `workers` is an int the task is subdivided into `workers`
+ sections and the fun evaluated in parallel
+ (uses `multiprocessing.Pool `).
+ Supply -1 to use all available CPU cores.
+ It is recommended that a map-like be used instead of int, as repeated
+ calls to `approx_derivative` will incur large overhead from setting up
+ new processes.
+
+ Returns
+ -------
+ J : {ndarray, sparse array, LinearOperator}
+ Finite difference approximation of the Jacobian matrix.
+ If `as_linear_operator` is True returns a LinearOperator
+ with shape (m, n). Otherwise it returns a dense array or sparse
+ array depending on how `sparsity` is defined. If `sparsity`
+ is None then a ndarray with shape (m, n) is returned. If
+ `sparsity` is not None returns a csr_array or csr_matrix with
+ shape (m, n) following the array/matrix type of the incoming structure.
+ For sparse arrays and linear operators it is always returned as
+ a 2-D structure. For ndarrays, if m=1 it is returned
+ as a 1-D gradient array with shape (n,).
+
+ info_dict : dict
+ Dictionary containing extra information about the calculation. The
+ keys include:
+
+ - `nfev`, number of function evaluations. If `as_linear_operator` is True
+ then `fun` is expected to track the number of evaluations itself.
+ This is because multiple calls may be made to the linear operator which
+ are not trackable here.
+
+ See Also
+ --------
+ check_derivative : Check correctness of a function computing derivatives.
+
+ Notes
+ -----
+ If `rel_step` is not provided, it assigned as ``EPS**(1/s)``, where EPS is
+ determined from the smallest floating point dtype of `x0` or `fun(x0)`,
+ ``np.finfo(x0.dtype).eps``, s=2 for '2-point' method and
+ s=3 for '3-point' method. Such relative step approximately minimizes a sum
+ of truncation and round-off errors, see [1]_. Relative steps are used by
+ default. However, absolute steps are used when ``abs_step is not None``.
+ If any of the absolute or relative steps produces an indistinguishable
+ difference from the original `x0`, ``(x0 + dx) - x0 == 0``, then a
+ automatic step size is substituted for that particular entry.
+
+ A finite difference scheme for '3-point' method is selected automatically.
+ The well-known central difference scheme is used for points sufficiently
+ far from the boundary, and 3-point forward or backward scheme is used for
+ points near the boundary. Both schemes have the second-order accuracy in
+ terms of Taylor expansion. Refer to [2]_ for the formulas of 3-point
+ forward and backward difference schemes.
+
+ For dense differencing when m=1 Jacobian is returned with a shape (n,),
+ on the other hand when n=1 Jacobian is returned with a shape (m, 1).
+ Our motivation is the following: a) It handles a case of gradient
+ computation (m=1) in a conventional way. b) It clearly separates these two
+ different cases. b) In all cases np.atleast_2d can be called to get 2-D
+ Jacobian with correct dimensions.
+
+ References
+ ----------
+ .. [1] W. H. Press et. al. "Numerical Recipes. The Art of Scientific
+ Computing. 3rd edition", sec. 5.7.
+
+ .. [2] A. Curtis, M. J. D. Powell, and J. Reid, "On the estimation of
+ sparse Jacobian matrices", Journal of the Institute of Mathematics
+ and its Applications, 13 (1974), pp. 117-120.
+
+ .. [3] B. Fornberg, "Generation of Finite Difference Formulas on
+ Arbitrarily Spaced Grids", Mathematics of Computation 51, 1988.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize._numdiff import approx_derivative
+ >>>
+ >>> def f(x, c1, c2):
+ ... return np.array([x[0] * np.sin(c1 * x[1]),
+ ... x[0] * np.cos(c2 * x[1])])
+ ...
+ >>> x0 = np.array([1.0, 0.5 * np.pi])
+ >>> approx_derivative(f, x0, args=(1, 2))
+ array([[ 1., 0.],
+ [-1., 0.]])
+
+ Bounds can be used to limit the region of function evaluation.
+ In the example below we compute left and right derivative at point 1.0.
+
+ >>> def g(x):
+ ... return x**2 if x >= 1 else x
+ ...
+ >>> x0 = 1.0
+ >>> approx_derivative(g, x0, bounds=(-np.inf, 1.0))
+ array([ 1.])
+ >>> approx_derivative(g, x0, bounds=(1.0, np.inf))
+ array([ 2.])
+
+ We can also parallelize the derivative calculation using the workers
+ keyword.
+
+ >>> from multiprocessing import Pool
+ >>> import time
+ >>> def fun2(x): # import from an external file for use with multiprocessing
+ ... time.sleep(0.002)
+ ... return rosen(x)
+
+ >>> rng = np.random.default_rng()
+ >>> x0 = rng.uniform(high=10, size=(2000,))
+ >>> f0 = rosen(x0)
+
+ >>> %timeit approx_derivative(fun2, x0, f0=f0) # may vary
+ 10.5 s ± 5.91 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
+
+ >>> elapsed = []
+ >>> with Pool() as workers:
+ ... for i in range(10):
+ ... t = time.perf_counter()
+ ... approx_derivative(fun2, x0, workers=workers.map, f0=f0)
+ ... et = time.perf_counter()
+ ... elapsed.append(et - t)
+ >>> np.mean(elapsed) # may vary
+ np.float64(1.442545195999901)
+
+ Create a map-like vectorized version. `x` is a generator, so first of all
+ a 2-D array, `xx`, is reconstituted. Here `xx` has shape `(Y, N)` where `Y`
+ is the number of function evaluations to perform and `N` is the dimensionality
+ of the objective function. The underlying objective function is `rosen`, which
+ requires `xx` to have shape `(N, Y)`, so a transpose is required.
+
+ >>> def fun(f, x, *args, **kwds):
+ ... xx = np.r_[[xs for xs in x]]
+ ... return f(xx.T)
+ >>> %timeit approx_derivative(fun2, x0, workers=fun, f0=f0) # may vary
+ 91.8 ms ± 755 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
+
+ """
+ if method not in ['2-point', '3-point', 'cs']:
+ raise ValueError(f"Unknown method '{method}'. ")
+
+ info_dict = {'nfev': None}
+
+ xp = array_namespace(x0)
+ _x = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ _dtype = xp.float64
+ if xp.isdtype(_x.dtype, "real floating"):
+ _dtype = _x.dtype
+
+ # promotes to floating
+ x0 = xp.astype(_x, _dtype)
+
+ if x0.ndim > 1:
+ raise ValueError("`x0` must have at most 1 dimension.")
+
+ lb, ub = _prepare_bounds(bounds, x0)
+
+ if lb.shape != x0.shape or ub.shape != x0.shape:
+ raise ValueError("Inconsistent shapes between bounds and `x0`.")
+
+ if as_linear_operator and not (np.all(np.isinf(lb))
+ and np.all(np.isinf(ub))):
+ raise ValueError("Bounds not supported when "
+ "`as_linear_operator` is True.")
+
+ if kwargs is None:
+ kwargs = {}
+
+ fun_wrapped = _Fun_Wrapper(fun, x0, args, kwargs)
+
+ # Record how function evaluations are consumed by `approx_derivative`.
+ # Historically this was done by upstream functions wrapping `fun`.
+ # However, with parallelization via workers it was going to be impossible to
+ # keep that counter updated across Processes. Counter synchronisation can
+ # be achieved via multiprocessing.Value and a Pool. However, workers can be
+ # any map-like, not necessarily a Pool, so initialization of the Value would
+ # be difficult.
+ nfev = _nfev = 0
+
+ if f0 is None:
+ f0 = fun_wrapped(x0)
+ nfev = 1
+ else:
+ f0 = np.atleast_1d(f0)
+ if f0.ndim > 1:
+ raise ValueError("`f0` passed has more than 1 dimension.")
+
+ if np.any((x0 < lb) | (x0 > ub)):
+ raise ValueError("`x0` violates bound constraints.")
+
+ if as_linear_operator:
+ if rel_step is None:
+ rel_step = _eps_for_method(x0.dtype, f0.dtype, method)
+
+ J, _ = _linear_operator_difference(fun_wrapped, x0,
+ f0, rel_step, method)
+ else:
+ # by default we use rel_step
+ if abs_step is None:
+ h = _compute_absolute_step(rel_step, x0, f0, method)
+ else:
+ # user specifies an absolute step
+ sign_x0 = (x0 >= 0).astype(float) * 2 - 1
+ h = abs_step
+
+ # cannot have a zero step. This might happen if x0 is very large
+ # or small. In which case fall back to relative step.
+ dx = ((x0 + h) - x0)
+ h = np.where(dx == 0,
+ _eps_for_method(x0.dtype, f0.dtype, method) *
+ sign_x0 * np.maximum(1.0, np.abs(x0)),
+ h)
+
+ if method == '2-point':
+ h, use_one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '1-sided', lb, ub)
+ elif method == '3-point':
+ h, use_one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '2-sided', lb, ub)
+ elif method == 'cs':
+ use_one_sided = False
+
+ # normalize workers
+ workers = workers or map
+ with MapWrapper(workers) as mf:
+ if sparsity is None:
+ J, _nfev = _dense_difference(fun_wrapped, x0, f0, h,
+ use_one_sided, method,
+ mf)
+ else:
+ if not issparse(sparsity) and len(sparsity) == 2:
+ structure, groups = sparsity
+ else:
+ structure = sparsity
+ groups = group_columns(sparsity)
+
+ if issparse(structure):
+ structure = structure.tocsc()
+ else:
+ structure = np.atleast_2d(structure)
+ groups = np.atleast_1d(groups)
+ J, _nfev = _sparse_difference(fun_wrapped, x0, f0, h,
+ use_one_sided, structure,
+ groups, method, mf)
+
+ if full_output:
+ nfev += _nfev
+ info_dict["nfev"] = nfev
+ return J, info_dict
+ else:
+ return J
+
+
+def _linear_operator_difference(fun, x0, f0, h, method):
+ m = f0.size
+ n = x0.size
+
+ if method == '2-point':
+ # nfev = 1
+ def matvec(p):
+ if np.array_equal(p, np.zeros_like(p)):
+ return np.zeros(m)
+ dx = h / norm(p)
+ x = x0 + dx*p
+ df = fun(x) - f0
+ return df / dx
+
+ elif method == '3-point':
+ # nfev = 2
+ def matvec(p):
+ if np.array_equal(p, np.zeros_like(p)):
+ return np.zeros(m)
+ dx = 2*h / norm(p)
+ x1 = x0 - (dx/2)*p
+ x2 = x0 + (dx/2)*p
+ f1 = fun(x1)
+ f2 = fun(x2)
+ df = f2 - f1
+ return df / dx
+
+ elif method == 'cs':
+ # nfev = 1
+ def matvec(p):
+ if np.array_equal(p, np.zeros_like(p)):
+ return np.zeros(m)
+ dx = h / norm(p)
+ x = x0 + dx*p*1.j
+ f1 = fun(x)
+ df = f1.imag
+ return df / dx
+ else:
+ raise RuntimeError("Never be here.")
+
+ return LinearOperator((m, n), matvec), 0
+
+
+def _dense_difference(fun, x0, f0, h, use_one_sided, method, workers):
+ m = f0.size
+ n = x0.size
+ J_transposed = np.empty((n, m))
+ nfev = 0
+
+ if method == '2-point':
+ def x_generator2(x0, h):
+ for i in range(n):
+ # If copying isn't done then it's possible for different workers
+ # to see the same values of x1. (At least that's what happened
+ # when I used `multiprocessing.dummy.Pool`).
+ # I also considered creating all the vectors at once, but that
+ # means assembling a very large N x N array. It's therefore a
+ # trade-off between N array copies or creating an NxN array.
+ x1 = np.copy(x0)
+ x1[i] = x0[i] + h[i]
+ yield x1
+
+ # only f_evals (numerator) needs parallelization, the denominator
+ # (the step size) is fast to calculate.
+ f_evals = workers(fun, x_generator2(x0, h))
+ dx = [(x0[i] + h[i]) - x0[i] for i in range(n)]
+ df = [f_eval - f0 for f_eval in f_evals]
+ df_dx = [delf / delx for delf, delx in zip(df, dx)]
+ nfev += len(df_dx)
+
+ elif method == '3-point':
+ def x_generator3(x0, h, use_one_sided):
+ for i, one_sided in enumerate(use_one_sided):
+ x1 = np.copy(x0)
+ x2 = np.copy(x0)
+ if one_sided:
+ x1[i] = x0[i] + h[i]
+ x2[i] = x0[i] + 2*h[i]
+ else:
+ x1[i] = x0[i] - h[i]
+ x2[i] = x0[i] + h[i]
+ yield x1
+ yield x2
+
+ # workers may return something like a list that needs to be turned
+ # into an iterable (can't call `next` on a list)
+ f_evals = iter(workers(fun, x_generator3(x0, h, use_one_sided)))
+ gen = x_generator3(x0, h, use_one_sided)
+ dx = list()
+ df = list()
+ for i, one_sided in enumerate(use_one_sided):
+ l = next(gen)
+ u = next(gen)
+
+ f1 = next(f_evals)
+ f2 = next(f_evals)
+ if one_sided:
+ dx.append(u[i] - x0[i])
+ df.append(-3.0 * f0 + 4 * f1 - f2)
+ else:
+ dx.append(u[i] - l[i])
+ df.append(f2 - f1)
+ df_dx = [delf / delx for delf, delx in zip(df, dx)]
+ nfev += 2 * len(df_dx)
+ elif method == 'cs':
+ def x_generator_cs(x0, h):
+ for i in range(n):
+ xc = x0.astype(complex, copy=True)
+ xc[i] += h[i] * 1.j
+ yield xc
+
+ f_evals = iter(workers(fun, x_generator_cs(x0, h)))
+ df_dx = [f1.imag / hi for f1, hi in zip(f_evals, h)]
+ nfev += len(df_dx)
+ else:
+ raise RuntimeError("Never be here.")
+
+ for i, v in enumerate(df_dx):
+ J_transposed[i] = v
+
+ if m == 1:
+ J_transposed = np.ravel(J_transposed)
+
+ return J_transposed.T, nfev
+
+
+def _sparse_difference(fun, x0, f0, h, use_one_sided,
+ structure, groups, method, workers):
+ m = f0.size
+ n = x0.size
+ row_indices = []
+ col_indices = []
+ fractions = []
+
+ n_groups = np.max(groups) + 1
+ nfev = 0
+
+ def e_generator():
+ # Perturb variables which are in the same group simultaneously.
+ for group in range(n_groups):
+ yield np.equal(group, groups)
+
+ def x_generator2():
+ e_gen = e_generator()
+ for e in e_gen:
+ h_vec = h * e
+ x = x0 + h_vec
+ yield x
+
+ def x_generator3():
+ e_gen = e_generator()
+ for e in e_gen:
+ h_vec = h * e
+ x1 = x0.copy()
+ x2 = x0.copy()
+
+ mask_1 = use_one_sided & e
+ x1[mask_1] += h_vec[mask_1]
+ x2[mask_1] += 2 * h_vec[mask_1]
+
+ mask_2 = ~use_one_sided & e
+ x1[mask_2] -= h_vec[mask_2]
+ x2[mask_2] += h_vec[mask_2]
+ yield x1
+ yield x2
+
+ def x_generator_cs():
+ e_gen = e_generator()
+ for e in e_gen:
+ h_vec = h * e
+ yield x0 + h_vec * 1.j
+
+ # evaluate the function for each of the groups
+ if method == '2-point':
+ f_evals = iter(workers(fun, x_generator2()))
+ xs = x_generator2()
+ elif method == '3-point':
+ f_evals = iter(workers(fun, x_generator3()))
+ xs = x_generator3()
+ elif method == 'cs':
+ f_evals = iter(workers(fun, x_generator_cs()))
+
+ for e in e_generator():
+ # The result is written to columns which correspond to perturbed
+ # variables.
+ cols, = np.nonzero(e)
+ # Find all non-zero elements in selected columns of Jacobian.
+ i, j, _ = find(structure[:, cols])
+ # Restore column indices in the full array.
+ j = cols[j]
+
+ if method == '2-point':
+ dx = next(xs) - x0
+ df = next(f_evals) - f0
+ nfev += 1
+ elif method == '3-point':
+ # Here we do conceptually the same but separate one-sided
+ # and two-sided schemes.
+ x1 = next(xs)
+ x2 = next(xs)
+
+ mask_1 = use_one_sided & e
+ mask_2 = ~use_one_sided & e
+
+ dx = np.zeros(n)
+ dx[mask_1] = x2[mask_1] - x0[mask_1]
+ dx[mask_2] = x2[mask_2] - x1[mask_2]
+
+ f1 = next(f_evals)
+ f2 = next(f_evals)
+ nfev += 2
+
+ mask = use_one_sided[j]
+ df = np.empty(m)
+
+ rows = i[mask]
+ df[rows] = -3 * f0[rows] + 4 * f1[rows] - f2[rows]
+
+ rows = i[~mask]
+ df[rows] = f2[rows] - f1[rows]
+ elif method == 'cs':
+ f1 = next(f_evals)
+ nfev += 1
+ df = f1.imag
+ dx = h * e
+ else:
+ raise ValueError("Never be here.")
+
+ # All that's left is to compute the fraction. We store i, j and
+ # fractions as separate arrays and later construct csr_array.
+ row_indices.append(i)
+ col_indices.append(j)
+ fractions.append(df[i] / dx[j])
+
+ row_indices = np.hstack(row_indices)
+ col_indices = np.hstack(col_indices)
+ fractions = np.hstack(fractions)
+
+ if isspmatrix(structure):
+ return csr_matrix((fractions, (row_indices, col_indices)), shape=(m, n)), nfev
+ return csr_array((fractions, (row_indices, col_indices)), shape=(m, n)), nfev
+
+
+class _Fun_Wrapper:
+ # Permits pickling of a wrapped function
+ def __init__(self, fun, x0, args, kwargs):
+ self.fun = fun
+ self.x0 = x0
+ self.args = args
+ self.kwargs = kwargs
+
+ def __call__(self, x):
+ # send user function same fp type as x0. (but only if cs is not being
+ # used
+ xp = array_namespace(self.x0)
+
+ if xp.isdtype(x.dtype, "real floating"):
+ x = xp.astype(x, self.x0.dtype)
+
+ f = np.atleast_1d(self.fun(x, *self.args, **self.kwargs))
+ if f.ndim > 1:
+ raise RuntimeError("`fun` return value has "
+ "more than 1 dimension.")
+ return f
+
+
+def check_derivative(fun, jac, x0, bounds=(-np.inf, np.inf), args=(),
+ kwargs=None):
+ """Check correctness of a function computing derivatives (Jacobian or
+ gradient) by comparison with a finite difference approximation.
+
+ Parameters
+ ----------
+ fun : callable
+ Function of which to estimate the derivatives. The argument x
+ passed to this function is ndarray of shape (n,) (never a scalar
+ even if n=1). It must return 1-D array_like of shape (m,) or a scalar.
+ jac : callable
+ Function which computes Jacobian matrix of `fun`. It must work with
+ argument x the same way as `fun`. The return value must be array_like
+ or sparse array with an appropriate shape.
+ x0 : array_like of shape (n,) or float
+ Point at which to estimate the derivatives. Float will be converted
+ to 1-D array.
+ bounds : 2-tuple of array_like, optional
+ Lower and upper bounds on independent variables. Defaults to no bounds.
+ Each bound must match the size of `x0` or be a scalar, in the latter
+ case the bound will be the same for all variables. Use it to limit the
+ range of function evaluation.
+ args, kwargs : tuple and dict, optional
+ Additional arguments passed to `fun` and `jac`. Both empty by default.
+ The calling signature is ``fun(x, *args, **kwargs)`` and the same
+ for `jac`.
+
+ Returns
+ -------
+ accuracy : float
+ The maximum among all relative errors for elements with absolute values
+ higher than 1 and absolute errors for elements with absolute values
+ less or equal than 1. If `accuracy` is on the order of 1e-6 or lower,
+ then it is likely that your `jac` implementation is correct.
+
+ See Also
+ --------
+ approx_derivative : Compute finite difference approximation of derivative.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize._numdiff import check_derivative
+ >>>
+ >>>
+ >>> def f(x, c1, c2):
+ ... return np.array([x[0] * np.sin(c1 * x[1]),
+ ... x[0] * np.cos(c2 * x[1])])
+ ...
+ >>> def jac(x, c1, c2):
+ ... return np.array([
+ ... [np.sin(c1 * x[1]), c1 * x[0] * np.cos(c1 * x[1])],
+ ... [np.cos(c2 * x[1]), -c2 * x[0] * np.sin(c2 * x[1])]
+ ... ])
+ ...
+ >>>
+ >>> x0 = np.array([1.0, 0.5 * np.pi])
+ >>> check_derivative(f, jac, x0, args=(1, 2))
+ 2.4492935982947064e-16
+ """
+ if kwargs is None:
+ kwargs = {}
+ J_to_test = jac(x0, *args, **kwargs)
+ if issparse(J_to_test):
+ J_diff = approx_derivative(fun, x0, bounds=bounds, sparsity=J_to_test,
+ args=args, kwargs=kwargs)
+ J_to_test = csr_array(J_to_test)
+ abs_err = J_to_test - J_diff
+ i, j, abs_err_data = find(abs_err)
+ J_diff_data = np.asarray(J_diff[i, j]).ravel()
+ return np.max(np.abs(abs_err_data) /
+ np.maximum(1, np.abs(J_diff_data)))
+ else:
+ J_diff = approx_derivative(fun, x0, bounds=bounds,
+ args=args, kwargs=kwargs)
+ abs_err = np.abs(J_to_test - J_diff)
+ return np.max(abs_err / np.maximum(1, np.abs(J_diff)))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_optimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..e9a6f9851338378c17e53435dbe6e56b2ee4873e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_optimize.py
@@ -0,0 +1,4169 @@
+#__docformat__ = "restructuredtext en"
+# ******NOTICE***************
+# optimize.py module by Travis E. Oliphant
+#
+# You may copy and use this module as you see fit with no
+# guarantee implied provided you keep this notice in all copies.
+# *****END NOTICE************
+
+# A collection of optimization algorithms. Version 0.5
+# CHANGES
+# Added fminbound (July 2001)
+# Added brute (Aug. 2002)
+# Finished line search satisfying strong Wolfe conditions (Mar. 2004)
+# Updated strong Wolfe conditions line search to use
+# cubic-interpolation (Mar. 2004)
+
+
+# Minimization routines
+
+__all__ = ['fmin', 'fmin_powell', 'fmin_bfgs', 'fmin_ncg', 'fmin_cg',
+ 'fminbound', 'brent', 'golden', 'bracket', 'rosen', 'rosen_der',
+ 'rosen_hess', 'rosen_hess_prod', 'brute', 'approx_fprime',
+ 'line_search', 'check_grad', 'OptimizeResult', 'show_options',
+ 'OptimizeWarning']
+
+__docformat__ = "restructuredtext en"
+
+import math
+import warnings
+import sys
+from numpy import eye, argmin, zeros, shape, asarray, sqrt
+import numpy as np
+from scipy.linalg import cholesky, issymmetric, LinAlgError
+from scipy.sparse.linalg import LinearOperator
+from ._linesearch import (line_search_wolfe1, line_search_wolfe2,
+ line_search_wolfe2 as line_search,
+ LineSearchWarning)
+from ._numdiff import approx_derivative
+from scipy._lib._util import getfullargspec_no_self as _getfullargspec
+from scipy._lib._util import (MapWrapper, check_random_state, _RichResult,
+ _call_callback_maybe_halt, _transition_to_rng,
+ wrapped_inspect_signature)
+from scipy.optimize._differentiable_functions import ScalarFunction, FD_METHODS
+from scipy._lib._array_api import array_namespace, xp_capabilities, xp_promote
+from scipy._lib import array_api_extra as xpx
+
+
+# standard status messages of optimizers
+_status_message = {'success': 'Optimization terminated successfully.',
+ 'maxfev': 'Maximum number of function evaluations has '
+ 'been exceeded.',
+ 'maxiter': 'Maximum number of iterations has been '
+ 'exceeded.',
+ 'pr_loss': 'Desired error not necessarily achieved due '
+ 'to precision loss.',
+ 'nan': 'NaN result encountered.',
+ 'out_of_bounds': 'The result is outside of the provided '
+ 'bounds.'}
+
+
+class MemoizeJac:
+ """Decorator that caches the return values of a function returning ``(fun, grad)``
+ each time it is called."""
+
+ def __init__(self, fun):
+ self.fun = fun
+ self.jac = None
+ self._value = None
+ self.x = None
+
+ def _compute_if_needed(self, x, *args):
+ if not np.all(x == self.x) or self._value is None or self.jac is None:
+ self.x = np.asarray(x).copy()
+ fg = self.fun(x, *args)
+ self.jac = fg[1]
+ self._value = fg[0]
+
+ def __call__(self, x, *args):
+ """ returns the function value """
+ self._compute_if_needed(x, *args)
+ return self._value
+
+ def derivative(self, x, *args):
+ self._compute_if_needed(x, *args)
+ return self.jac
+
+
+def _wrap_callback(callback, method=None):
+ """Wrap a user-provided callback so that attributes can be attached."""
+ if callback is None or method in {'tnc', 'cobyla', 'cobyqa'}:
+ return callback # don't wrap
+
+ sig = wrapped_inspect_signature(callback)
+
+ if set(sig.parameters) == {'intermediate_result'}:
+ def wrapped_callback(res):
+ return callback(intermediate_result=res)
+ elif method == 'trust-constr':
+ def wrapped_callback(res):
+ return callback(np.copy(res.x), res)
+ elif method == 'differential_evolution':
+ def wrapped_callback(res):
+ return callback(np.copy(res.x), res.convergence)
+ else:
+ def wrapped_callback(res):
+ return callback(np.copy(res.x))
+
+ wrapped_callback.stop_iteration = False
+ return wrapped_callback
+
+
+class OptimizeResult(_RichResult):
+ """
+ Represents the optimization result.
+
+ Attributes
+ ----------
+ x : ndarray
+ The solution of the optimization.
+ success : bool
+ Whether or not the optimizer exited successfully.
+ status : int
+ Termination status of the optimizer. Its value depends on the
+ underlying solver. Refer to `message` for details.
+ message : str
+ Description of the cause of the termination.
+ fun : float
+ Value of objective function at `x`.
+ jac, hess : ndarray
+ Values of objective function's Jacobian and its Hessian at `x` (if
+ available). The Hessian may be an approximation, see the documentation
+ of the function in question.
+ hess_inv : object
+ Inverse of the objective function's Hessian; may be an approximation.
+ Not available for all solvers. The type of this attribute may be
+ either np.ndarray or scipy.sparse.linalg.LinearOperator.
+ nfev, njev, nhev : int
+ Number of evaluations of the objective functions and of its
+ Jacobian and Hessian.
+ nit : int
+ Number of iterations performed by the optimizer.
+ maxcv : float
+ The maximum constraint violation.
+
+ Notes
+ -----
+ Depending on the specific solver being used, `OptimizeResult` may
+ not have all attributes listed here, and they may have additional
+ attributes not listed here. Since this class is essentially a
+ subclass of dict with attribute accessors, one can see which
+ attributes are available using the `OptimizeResult.keys` method.
+
+ """
+ pass
+
+
+class OptimizeWarning(UserWarning):
+ """General warning for :mod:`scipy.optimize`."""
+ pass
+
+def _check_positive_definite(Hk):
+ def is_pos_def(A):
+ if issymmetric(A):
+ try:
+ cholesky(A)
+ return True
+ except LinAlgError:
+ return False
+ else:
+ return False
+ if Hk is not None:
+ if not is_pos_def(Hk):
+ raise ValueError("'hess_inv0' matrix isn't positive definite.")
+
+
+def _check_unknown_options(unknown_options):
+ if unknown_options:
+ msg = ", ".join(map(str, unknown_options.keys()))
+ # Stack level 4: this is called from _minimize_*, which is
+ # called from another function in SciPy. Level 4 is the first
+ # level in user code.
+ warnings.warn(f"Unknown solver options: {msg}", OptimizeWarning, stacklevel=4)
+
+
+def is_finite_scalar(x):
+ """Test whether `x` is either a finite scalar or a finite array scalar.
+
+ """
+ return np.size(x) == 1 and np.isfinite(x)
+
+
+_epsilon = sqrt(np.finfo(float).eps)
+
+
+def vecnorm(x, ord=2):
+ if ord == np.inf:
+ return np.amax(np.abs(x))
+ elif ord == -np.inf:
+ return np.amin(np.abs(x))
+ else:
+ return np.sum(np.abs(x)**ord, axis=0)**(1.0 / ord)
+
+
+def _prepare_scalar_function(fun, x0, jac=None, args=(), bounds=None,
+ epsilon=None, finite_diff_rel_step=None,
+ hess=None, workers=None):
+ """
+ Creates a ScalarFunction object for use with scalar minimizers
+ (BFGS/LBFGSB/SLSQP/TNC/CG/etc).
+
+ Parameters
+ ----------
+ fun : callable
+ The objective function to be minimized.
+
+ ``fun(x, *args) -> float``
+
+ where ``x`` is a 1-D array with shape (n,) and ``args``
+ is a tuple of the fixed parameters needed to completely
+ specify the function.
+ x0 : ndarray, shape (n,)
+ Initial guess. Array of real elements of size (n,),
+ where 'n' is the number of independent variables.
+ jac : {callable, '2-point', '3-point', 'cs', None}, optional
+ Method for computing the gradient vector. If it is a callable, it
+ should be a function that returns the gradient vector:
+
+ ``jac(x, *args) -> array_like, shape (n,)``
+
+ If one of `{'2-point', '3-point', 'cs'}` is selected then the gradient
+ is calculated with a relative step for finite differences. If `None`,
+ then two-point finite differences with an absolute step is used.
+ args : tuple, optional
+ Extra arguments passed to the objective function and its
+ derivatives (`fun`, `jac` functions).
+ bounds : sequence, optional
+ Bounds on variables. 'new-style' bounds are required.
+ eps : float or ndarray
+ If ``jac is None`` the absolute step size used for numerical
+ approximation of the jacobian via forward differences.
+ finite_diff_rel_step : None or array_like, optional
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+ use for numerical approximation of the jacobian. The absolute step
+ size is computed as ``h = rel_step * sign(x0) * max(1, abs(x0))``,
+ possibly adjusted to fit into the bounds. For ``jac='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+ hess : {callable, '2-point', '3-point', 'cs', None}
+ Computes the Hessian matrix. If it is callable, it should return the
+ Hessian matrix:
+
+ ``hess(x, *args) -> {LinearOperator, spmatrix, array}, (n, n)``
+
+ Alternatively, the keywords {'2-point', '3-point', 'cs'} select a
+ finite difference scheme for numerical estimation.
+ Whenever the gradient is estimated via finite-differences, the Hessian
+ cannot be estimated with options {'2-point', '3-point', 'cs'} and needs
+ to be estimated using one of the quasi-Newton strategies.
+ workers : int or map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``, or
+ ``workers(grad, iterable)``, depending on what is being numerically
+ differentiated.
+ Alternatively, if `workers` is an int the task is subdivided into `workers`
+ sections and the function evaluated in parallel
+ (uses `multiprocessing.Pool `).
+ Supply -1 to use all available CPU cores.
+ It is recommended that a map-like be used instead of int, as repeated
+ calls to `approx_derivative` will incur large overhead from setting up
+ new processes.
+
+ .. versionadded:: 1.16.0
+
+ Returns
+ -------
+ sf : ScalarFunction
+ """
+ if callable(jac):
+ grad = jac
+ elif jac in FD_METHODS:
+ # epsilon is set to None so that ScalarFunction is made to use
+ # rel_step
+ epsilon = None
+ grad = jac
+ else:
+ # default (jac is None) is to do 2-point finite differences with
+ # absolute step size. ScalarFunction has to be provided an
+ # epsilon value that is not None to use absolute steps. This is
+ # normally the case from most _minimize* methods.
+ grad = '2-point'
+ epsilon = epsilon
+
+ if hess is None:
+ # ScalarFunction requires something for hess, so we give a dummy
+ # implementation here if nothing is provided, return a value of None
+ # so that downstream minimisers halt. The results of `fun.hess`
+ # should not be used.
+ def hess(x, *args):
+ return None
+
+ if bounds is None:
+ bounds = (-np.inf, np.inf)
+
+ # normalize workers
+ workers = workers or map
+
+ # ScalarFunction caches. Reuse of fun(x) during grad
+ # calculation reduces overall function evaluations.
+ sf = ScalarFunction(fun, x0, args, grad, hess,
+ finite_diff_rel_step, bounds, epsilon=epsilon,
+ workers=workers)
+
+ return sf
+
+
+def _clip_x_for_func(func, bounds):
+ # ensures that x values sent to func are clipped to bounds
+
+ # this is used as a mitigation for gh11403, slsqp/tnc sometimes
+ # suggest a move that is outside the limits by 1 or 2 ULP. This
+ # unclean fix makes sure x is strictly within bounds.
+ def eval(x):
+ x = _check_clip_x(x, bounds)
+ return func(x)
+
+ return eval
+
+
+def _check_clip_x(x, bounds):
+ if (x < bounds[0]).any() or (x > bounds[1]).any():
+ warnings.warn("Values in x were outside bounds during a "
+ "minimize step, clipping to bounds",
+ RuntimeWarning, stacklevel=3)
+ x = np.clip(x, bounds[0], bounds[1])
+ return x
+
+ return x
+
+
+@xp_capabilities()
+def rosen(x):
+ """
+ The Rosenbrock function.
+
+ The function computed is::
+
+ sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
+
+ Parameters
+ ----------
+ x : array_like
+ 1-D array of points at which the Rosenbrock function is to be computed.
+
+ Returns
+ -------
+ f : float
+ The value of the Rosenbrock function.
+
+ See Also
+ --------
+ rosen_der, rosen_hess, rosen_hess_prod
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import rosen
+ >>> X = 0.1 * np.arange(10)
+ >>> rosen(X)
+ 76.56
+
+ For higher-dimensional input ``rosen`` broadcasts.
+ In the following example, we use this to plot a 2D landscape.
+ Note that ``rosen_hess`` does not broadcast in this manner.
+
+ >>> import matplotlib.pyplot as plt
+ >>> from mpl_toolkits.mplot3d import Axes3D
+ >>> x = np.linspace(-1, 1, 50)
+ >>> X, Y = np.meshgrid(x, x)
+ >>> ax = plt.subplot(111, projection='3d')
+ >>> ax.plot_surface(X, Y, rosen([X, Y]))
+ >>> plt.show()
+ """
+ xp = array_namespace(x)
+ x = xp_promote(x, force_floating=True, xp=xp)
+ r = xp.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0,
+ axis=0, dtype=x.dtype)
+ return r
+
+
+@xp_capabilities(skip_backends=[('jax.numpy', "JAX doesn't allow item assignment.")])
+def rosen_der(x):
+ """
+ The derivative (i.e. gradient) of the Rosenbrock function.
+
+ Parameters
+ ----------
+ x : array_like
+ 1-D array of points at which the derivative is to be computed.
+
+ Returns
+ -------
+ rosen_der : (N,) ndarray
+ The gradient of the Rosenbrock function at `x`.
+
+ See Also
+ --------
+ rosen, rosen_hess, rosen_hess_prod
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import rosen_der
+ >>> X = 0.1 * np.arange(9)
+ >>> rosen_der(X)
+ array([ -2. , 10.6, 15.6, 13.4, 6.4, -3. , -12.4, -19.4, 62. ])
+
+ """
+ xp = array_namespace(x)
+ x = xp_promote(x, force_floating=True, xp=xp)
+ xm = x[1:-1]
+ xm_m1 = x[:-2]
+ xm_p1 = x[2:]
+ der = xp.zeros_like(x)
+ der[1:-1] = (200 * (xm - xm_m1**2) -
+ 400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm))
+ der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0])
+ der[-1] = 200 * (x[-1] - x[-2]**2)
+ return der
+
+
+@xp_capabilities()
+def rosen_hess(x):
+ """
+ The Hessian matrix of the Rosenbrock function.
+
+ Parameters
+ ----------
+ x : array_like
+ 1-D array of points at which the Hessian matrix is to be computed.
+
+ Returns
+ -------
+ rosen_hess : ndarray
+ The Hessian matrix of the Rosenbrock function at `x`.
+
+ See Also
+ --------
+ rosen, rosen_der, rosen_hess_prod
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import rosen_hess
+ >>> X = 0.1 * np.arange(4)
+ >>> rosen_hess(X)
+ array([[-38., 0., 0., 0.],
+ [ 0., 134., -40., 0.],
+ [ 0., -40., 130., -80.],
+ [ 0., 0., -80., 200.]])
+
+ """
+ xp = array_namespace(x)
+ x = xp_promote(x, force_floating=True, xp=xp)
+
+ H = (xpx.create_diagonal(-400 * x[:-1], offset=1, xp=xp)
+ - xpx.create_diagonal(400 * x[:-1], offset=-1, xp=xp))
+ diagonal = xp.zeros(x.shape[0], dtype=x.dtype)
+ diagonal = xpx.at(diagonal)[0].set(1200 * x[0]**2 - 400 * x[1] + 2)
+ diagonal = xpx.at(diagonal)[-1].set(200)
+ diagonal = xpx.at(diagonal)[1:-1].set(202 + 1200 * x[1:-1]**2 - 400 * x[2:])
+ return H + xpx.create_diagonal(diagonal, xp=xp)
+
+
+@xp_capabilities(skip_backends=[('jax.numpy', "JAX doesn't allow item assignment.")])
+def rosen_hess_prod(x, p):
+ """
+ Product of the Hessian matrix of the Rosenbrock function with a vector.
+
+ Parameters
+ ----------
+ x : array_like
+ 1-D array of points at which the Hessian matrix is to be computed.
+ p : array_like
+ 1-D array, the vector to be multiplied by the Hessian matrix.
+
+ Returns
+ -------
+ rosen_hess_prod : ndarray
+ The Hessian matrix of the Rosenbrock function at `x` multiplied
+ by the vector `p`.
+
+ See Also
+ --------
+ rosen, rosen_der, rosen_hess
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import rosen_hess_prod
+ >>> X = 0.1 * np.arange(9)
+ >>> p = 0.5 * np.arange(9)
+ >>> rosen_hess_prod(X, p)
+ array([ -0., 27., -10., -95., -192., -265., -278., -195., -180.])
+
+ """
+ xp = array_namespace(x, p)
+ x = xp_promote(x, force_floating=True, xp=xp)
+ x = xpx.atleast_nd(x, ndim=1, xp=xp)
+ p = xp.asarray(p, dtype=x.dtype)
+ Hp = xp.zeros(x.shape[0], dtype=x.dtype)
+ Hp[0] = (1200 * x[0]**2 - 400 * x[1] + 2) * p[0] - 400 * x[0] * p[1]
+ Hp[1:-1] = (-400 * x[:-2] * p[:-2] +
+ (202 + 1200 * x[1:-1]**2 - 400 * x[2:]) * p[1:-1] -
+ 400 * x[1:-1] * p[2:])
+ Hp[-1] = -400 * x[-2] * p[-2] + 200*p[-1]
+ return Hp
+
+
+def _wrap_scalar_function(function, args):
+ # wraps a minimizer function to count number of evaluations
+ # and to easily provide an args kwd.
+ ncalls = [0]
+ if function is None:
+ return ncalls, None
+
+ def function_wrapper(x, *wrapper_args):
+ ncalls[0] += 1
+ # A copy of x is sent to the user function (gh13740)
+ fx = function(np.copy(x), *(wrapper_args + args))
+ # Ideally, we'd like to a have a true scalar returned from f(x). For
+ # backwards-compatibility, also allow np.array([1.3]), np.array([[1.3]]) etc.
+ if not np.isscalar(fx):
+ try:
+ fx = np.asarray(fx).item()
+ except (TypeError, ValueError) as e:
+ raise ValueError("The user-provided objective function "
+ "must return a scalar value.") from e
+ return fx
+
+ return ncalls, function_wrapper
+
+
+class _MaxFuncCallError(RuntimeError):
+ pass
+
+
+def _wrap_scalar_function_maxfun_validation(function, args, maxfun):
+ # wraps a minimizer function to count number of evaluations
+ # and to easily provide an args kwd.
+ ncalls = [0]
+ if function is None:
+ return ncalls, None
+
+ def function_wrapper(x, *wrapper_args):
+ if ncalls[0] >= maxfun:
+ raise _MaxFuncCallError("Too many function calls")
+ ncalls[0] += 1
+ # A copy of x is sent to the user function (gh13740)
+ fx = function(np.copy(x), *(wrapper_args + args))
+ # Ideally, we'd like to a have a true scalar returned from f(x). For
+ # backwards-compatibility, also allow np.array([1.3]),
+ # np.array([[1.3]]) etc.
+ if not np.isscalar(fx):
+ try:
+ fx = np.asarray(fx).item()
+ except (TypeError, ValueError) as e:
+ raise ValueError("The user-provided objective function "
+ "must return a scalar value.") from e
+ return fx
+
+ return ncalls, function_wrapper
+
+
+def fmin(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None, maxfun=None,
+ full_output=0, disp=1, retall=0, callback=None, initial_simplex=None):
+ """
+ Minimize a function using the downhill simplex algorithm.
+
+ This algorithm only uses function values, not derivatives or second
+ derivatives.
+
+ Parameters
+ ----------
+ func : callable func(x,*args)
+ The objective function to be minimized.
+ x0 : ndarray
+ Initial guess.
+ args : tuple, optional
+ Extra arguments passed to func, i.e., ``f(x,*args)``.
+ xtol : float, optional
+ Absolute error in xopt between iterations that is acceptable for
+ convergence.
+ ftol : number, optional
+ Absolute error in func(xopt) between iterations that is acceptable for
+ convergence.
+ maxiter : int, optional
+ Maximum number of iterations to perform.
+ maxfun : number, optional
+ Maximum number of function evaluations to make.
+ full_output : bool, optional
+ Set to True if fopt and warnflag outputs are desired.
+ disp : bool, optional
+ Set to True to print convergence messages.
+ retall : bool, optional
+ Set to True to return list of solutions at each iteration.
+ callback : callable, optional
+ Called after each iteration, as callback(xk), where xk is the
+ current parameter vector.
+ initial_simplex : array_like of shape (N + 1, N), optional
+ Initial simplex. If given, overrides `x0`.
+ ``initial_simplex[j,:]`` should contain the coordinates of
+ the jth vertex of the ``N+1`` vertices in the simplex, where
+ ``N`` is the dimension.
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameter that minimizes function.
+ fopt : float
+ Value of function at minimum: ``fopt = func(xopt)``.
+ iter : int
+ Number of iterations performed.
+ funcalls : int
+ Number of function calls made.
+ warnflag : int
+ 1 : Maximum number of function evaluations made.
+ 2 : Maximum number of iterations reached.
+ allvecs : list
+ Solution at each iteration.
+
+ See also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'Nelder-Mead' `method` in particular.
+
+ Notes
+ -----
+ Uses a Nelder-Mead simplex algorithm to find the minimum of function of
+ one or more variables.
+
+ This algorithm has a long history of successful use in applications.
+ But it will usually be slower than an algorithm that uses first or
+ second derivative information. In practice, it can have poor
+ performance in high-dimensional problems and is not robust to
+ minimizing complicated functions. Additionally, there currently is no
+ complete theory describing when the algorithm will successfully
+ converge to the minimum, or how fast it will if it does. Both the ftol and
+ xtol criteria must be met for convergence.
+
+ Examples
+ --------
+ >>> def f(x):
+ ... return x**2
+
+ >>> from scipy import optimize
+
+ >>> minimum = optimize.fmin(f, 1)
+ Optimization terminated successfully.
+ Current function value: 0.000000
+ Iterations: 17
+ Function evaluations: 34
+ >>> minimum[0]
+ -8.8817841970012523e-16
+
+ References
+ ----------
+ .. [1] Nelder, J.A. and Mead, R. (1965), "A simplex method for function
+ minimization", The Computer Journal, 7, pp. 308-313
+
+ .. [2] Wright, M.H. (1996), "Direct Search Methods: Once Scorned, Now
+ Respectable", in Numerical Analysis 1995, Proceedings of the
+ 1995 Dundee Biennial Conference in Numerical Analysis, D.F.
+ Griffiths and G.A. Watson (Eds.), Addison Wesley Longman,
+ Harlow, UK, pp. 191-208.
+
+ """
+ opts = {'xatol': xtol,
+ 'fatol': ftol,
+ 'maxiter': maxiter,
+ 'maxfev': maxfun,
+ 'disp': disp,
+ 'return_all': retall,
+ 'initial_simplex': initial_simplex}
+
+ callback = _wrap_callback(callback)
+ res = _minimize_neldermead(func, x0, args, callback=callback, **opts)
+ if full_output:
+ retlist = res['x'], res['fun'], res['nit'], res['nfev'], res['status']
+ if retall:
+ retlist += (res['allvecs'], )
+ return retlist
+ else:
+ if retall:
+ return res['x'], res['allvecs']
+ else:
+ return res['x']
+
+
+def _minimize_neldermead(func, x0, args=(), callback=None,
+ maxiter=None, maxfev=None, disp=False,
+ return_all=False, initial_simplex=None,
+ xatol=1e-4, fatol=1e-4, adaptive=False, bounds=None,
+ **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using the
+ Nelder-Mead algorithm.
+
+ Options
+ -------
+ disp : bool
+ Set to True to print convergence messages.
+ maxiter, maxfev : int
+ Maximum allowed number of iterations and function evaluations.
+ Will default to ``N*200``, where ``N`` is the number of
+ variables, if neither `maxiter` or `maxfev` is set. If both
+ `maxiter` and `maxfev` are set, minimization will stop at the
+ first reached.
+ return_all : bool, optional
+ Set to True to return a list of the best solution at each of the
+ iterations.
+ initial_simplex : array_like of shape (N + 1, N)
+ Initial simplex. If given, overrides `x0`.
+ ``initial_simplex[j,:]`` should contain the coordinates of
+ the jth vertex of the ``N+1`` vertices in the simplex, where
+ ``N`` is the dimension.
+ xatol : float, optional
+ Absolute error in xopt between iterations that is acceptable for
+ convergence.
+ fatol : number, optional
+ Absolute error in func(xopt) between iterations that is acceptable for
+ convergence.
+ adaptive : bool, optional
+ Adapt algorithm parameters to dimensionality of problem. Useful for
+ high-dimensional minimization [1]_.
+ bounds : sequence or `Bounds`, optional
+ Bounds on variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. Sequence of ``(min, max)`` pairs for each element in `x`. None
+ is used to specify no bound.
+
+ Note that this just clips all vertices in simplex based on
+ the bounds.
+
+ References
+ ----------
+ .. [1] Gao, F. and Han, L.
+ Implementing the Nelder-Mead simplex algorithm with adaptive
+ parameters. 2012. Computational Optimization and Applications.
+ 51:1, pp. 259-277
+
+ """
+ _check_unknown_options(unknown_options)
+ maxfun = maxfev
+ retall = return_all
+
+ x0 = np.atleast_1d(x0).flatten()
+ dtype = x0.dtype if np.issubdtype(x0.dtype, np.inexact) else np.float64
+ x0 = np.asarray(x0, dtype=dtype)
+
+ if adaptive:
+ dim = float(len(x0))
+ rho = 1
+ chi = 1 + 2/dim
+ psi = 0.75 - 1/(2*dim)
+ sigma = 1 - 1/dim
+ else:
+ rho = 1
+ chi = 2
+ psi = 0.5
+ sigma = 0.5
+
+ nonzdelt = 0.05
+ zdelt = 0.00025
+
+ if bounds is not None:
+ lower_bound, upper_bound = bounds.lb, bounds.ub
+ # check bounds
+ if (lower_bound > upper_bound).any():
+ raise ValueError("Nelder Mead - one of the lower bounds "
+ "is greater than an upper bound.")
+ if np.any(lower_bound > x0) or np.any(x0 > upper_bound):
+ warnings.warn("Initial guess is not within the specified bounds",
+ OptimizeWarning, stacklevel=3)
+
+ if bounds is not None:
+ x0 = np.clip(x0, lower_bound, upper_bound)
+
+ if initial_simplex is None:
+ N = len(x0)
+
+ sim = np.empty((N + 1, N), dtype=x0.dtype)
+ sim[0] = x0
+ for k in range(N):
+ y = np.array(x0, copy=True)
+ if y[k] != 0:
+ y[k] = (1 + nonzdelt)*y[k]
+ else:
+ y[k] = zdelt
+ sim[k + 1] = y
+ else:
+ sim = np.atleast_2d(initial_simplex).copy()
+ dtype = sim.dtype if np.issubdtype(sim.dtype, np.inexact) else np.float64
+ sim = np.asarray(sim, dtype=dtype)
+ if sim.ndim != 2 or sim.shape[0] != sim.shape[1] + 1:
+ raise ValueError("`initial_simplex` should be an array of shape (N+1,N)")
+ if len(x0) != sim.shape[1]:
+ raise ValueError("Size of `initial_simplex` is not consistent with `x0`")
+ N = sim.shape[1]
+
+ if retall:
+ allvecs = [sim[0]]
+
+ # If neither are set, then set both to default
+ if maxiter is None and maxfun is None:
+ maxiter = N * 200
+ maxfun = N * 200
+ elif maxiter is None:
+ # Convert remaining Nones, to np.inf, unless the other is np.inf, in
+ # which case use the default to avoid unbounded iteration
+ if maxfun == np.inf:
+ maxiter = N * 200
+ else:
+ maxiter = np.inf
+ elif maxfun is None:
+ if maxiter == np.inf:
+ maxfun = N * 200
+ else:
+ maxfun = np.inf
+
+ if bounds is not None:
+ # The default simplex construction may make all entries (for a given
+ # parameter) greater than an upper bound if x0 is very close to the
+ # upper bound. If one simply clips the simplex to the bounds this could
+ # make the simplex entries degenerate. If that occurs reflect into the
+ # interior.
+ msk = sim > upper_bound
+ # reflect into the interior
+ sim = np.where(msk, 2*upper_bound - sim, sim)
+ # but make sure the reflection is no less than the lower_bound
+ sim = np.clip(sim, lower_bound, upper_bound)
+
+ one2np1 = list(range(1, N + 1))
+ fsim = np.full((N + 1,), np.inf, dtype=float)
+
+ fcalls, func = _wrap_scalar_function_maxfun_validation(func, args, maxfun)
+
+ try:
+ for k in range(N + 1):
+ fsim[k] = func(sim[k])
+ except _MaxFuncCallError:
+ pass
+ finally:
+ ind = np.argsort(fsim)
+ sim = np.take(sim, ind, 0)
+ fsim = np.take(fsim, ind, 0)
+
+ ind = np.argsort(fsim)
+ fsim = np.take(fsim, ind, 0)
+ # sort so sim[0,:] has the lowest function value
+ sim = np.take(sim, ind, 0)
+
+ iterations = 1
+
+ while (fcalls[0] < maxfun and iterations < maxiter):
+ try:
+ if (np.max(np.ravel(np.abs(sim[1:] - sim[0]))) <= xatol and
+ np.max(np.abs(fsim[0] - fsim[1:])) <= fatol):
+ break
+
+ xbar = np.add.reduce(sim[:-1], 0) / N
+ xr = (1 + rho) * xbar - rho * sim[-1]
+ if bounds is not None:
+ xr = np.clip(xr, lower_bound, upper_bound)
+ fxr = func(xr)
+ doshrink = 0
+
+ if fxr < fsim[0]:
+ xe = (1 + rho * chi) * xbar - rho * chi * sim[-1]
+ if bounds is not None:
+ xe = np.clip(xe, lower_bound, upper_bound)
+ fxe = func(xe)
+
+ if fxe < fxr:
+ sim[-1] = xe
+ fsim[-1] = fxe
+ else:
+ sim[-1] = xr
+ fsim[-1] = fxr
+ else: # fsim[0] <= fxr
+ if fxr < fsim[-2]:
+ sim[-1] = xr
+ fsim[-1] = fxr
+ else: # fxr >= fsim[-2]
+ # Perform contraction
+ if fxr < fsim[-1]:
+ xc = (1 + psi * rho) * xbar - psi * rho * sim[-1]
+ if bounds is not None:
+ xc = np.clip(xc, lower_bound, upper_bound)
+ fxc = func(xc)
+
+ if fxc <= fxr:
+ sim[-1] = xc
+ fsim[-1] = fxc
+ else:
+ doshrink = 1
+ else:
+ # Perform an inside contraction
+ xcc = (1 - psi) * xbar + psi * sim[-1]
+ if bounds is not None:
+ xcc = np.clip(xcc, lower_bound, upper_bound)
+ fxcc = func(xcc)
+
+ if fxcc < fsim[-1]:
+ sim[-1] = xcc
+ fsim[-1] = fxcc
+ else:
+ doshrink = 1
+
+ if doshrink:
+ for j in one2np1:
+ sim[j] = sim[0] + sigma * (sim[j] - sim[0])
+ if bounds is not None:
+ sim[j] = np.clip(
+ sim[j], lower_bound, upper_bound)
+ fsim[j] = func(sim[j])
+ iterations += 1
+ except _MaxFuncCallError:
+ pass
+ ind = np.argsort(fsim)
+ sim = np.take(sim, ind, 0)
+ fsim = np.take(fsim, ind, 0)
+ if retall:
+ allvecs.append(sim[0])
+ intermediate_result = OptimizeResult(x=sim[0], fun=fsim[0])
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+
+ x = sim[0]
+ fval = np.min(fsim)
+ warnflag = 0
+
+ if fcalls[0] >= maxfun:
+ warnflag = 1
+ msg = _status_message['maxfev']
+ if disp:
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
+ elif iterations >= maxiter:
+ warnflag = 2
+ msg = _status_message['maxiter']
+ if disp:
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
+ else:
+ msg = _status_message['success']
+ if disp:
+ print(msg)
+ print(f" Current function value: {fval:f}")
+ print(f" Iterations: {iterations:d}")
+ print(f" Function evaluations: {fcalls[0]:d}")
+
+ result = OptimizeResult(fun=fval, nit=iterations, nfev=fcalls[0],
+ status=warnflag, success=(warnflag == 0),
+ message=msg, x=x, final_simplex=(sim, fsim))
+ if retall:
+ result['allvecs'] = allvecs
+ return result
+
+
+def approx_fprime(xk, f, epsilon=_epsilon, *args):
+ """Finite difference approximation of the derivatives of a
+ scalar or vector-valued function.
+
+ If a function maps from :math:`R^n` to :math:`R^m`, its derivatives form
+ an m-by-n matrix
+ called the Jacobian, where an element :math:`(i, j)` is a partial
+ derivative of f[i] with respect to ``xk[j]``.
+
+ Parameters
+ ----------
+ xk : array_like
+ The coordinate vector at which to determine the gradient of `f`.
+ f : callable
+ Function of which to estimate the derivatives of. Has the signature
+ ``f(xk, *args)`` where `xk` is the argument in the form of a 1-D array
+ and `args` is a tuple of any additional fixed parameters needed to
+ completely specify the function. The argument `xk` passed to this
+ function is an ndarray of shape (n,) (never a scalar even if n=1).
+ It must return a 1-D array_like of shape (m,) or a scalar.
+
+ Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
+ ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
+ Rather than passing ``f0`` as the callable, wrap it to accept
+ only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
+ callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
+ gathered before invoking this function.
+
+ .. versionchanged:: 1.9.0
+ `f` is now able to return a 1-D array-like, with the :math:`(m, n)`
+ Jacobian being estimated.
+
+ epsilon : {float, array_like}, optional
+ Increment to `xk` to use for determining the function gradient.
+ If a scalar, uses the same finite difference delta for all partial
+ derivatives. If an array, should contain one value per element of
+ `xk`. Defaults to ``sqrt(np.finfo(float).eps)``, which is approximately
+ 1.49e-08.
+ \\*args : args, optional
+ Any other arguments that are to be passed to `f`.
+
+ Returns
+ -------
+ jac : ndarray
+ The partial derivatives of `f` to `xk`.
+
+ See Also
+ --------
+ check_grad : Check correctness of gradient function against approx_fprime.
+
+ Notes
+ -----
+ The function gradient is determined by the forward finite difference
+ formula::
+
+ f(xk[i] + epsilon[i]) - f(xk[i])
+ f'[i] = ---------------------------------
+ epsilon[i]
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import optimize
+ >>> def func(x, c0, c1):
+ ... "Coordinate vector `x` should be an array of size two."
+ ... return c0 * x[0]**2 + c1*x[1]**2
+
+ >>> x = np.ones(2)
+ >>> c0, c1 = (1, 200)
+ >>> eps = np.sqrt(np.finfo(float).eps)
+ >>> optimize.approx_fprime(x, func, [eps, np.sqrt(200) * eps], c0, c1)
+ array([ 2. , 400.00004208])
+
+ """
+ xk = np.asarray(xk, float)
+ f0 = f(xk, *args)
+
+ return approx_derivative(f, xk, method='2-point', abs_step=epsilon,
+ args=args, f0=f0)
+
+
+@_transition_to_rng("seed", position_num=6)
+def check_grad(func, grad, x0, *args, epsilon=_epsilon,
+ direction='all', rng=None):
+ r"""Check the correctness of a gradient function by comparing it against a
+ (forward) finite-difference approximation of the gradient.
+
+ Parameters
+ ----------
+ func : callable ``func(x0, *args)``
+ Function whose derivative is to be checked.
+ grad : callable ``grad(x0, *args)``
+ Jacobian of `func`.
+ x0 : ndarray
+ Points to check `grad` against forward difference approximation of grad
+ using `func`.
+ args : \\*args, optional
+ Extra arguments passed to `func` and `grad`.
+ epsilon : float, optional
+ Step size used for the finite difference approximation. It defaults to
+ ``sqrt(np.finfo(float).eps)``, which is approximately 1.49e-08.
+ direction : str, optional
+ If set to ``'random'``, then gradients along a random vector
+ are used to check `grad` against forward difference approximation
+ using `func`. By default it is ``'all'``, in which case, all
+ the one hot direction vectors are considered to check `grad`.
+ If `func` is a vector valued function then only ``'all'`` can be used.
+ rng : `numpy.random.Generator`, optional
+ Pseudorandom number generator state. When `rng` is None, a new
+ `numpy.random.Generator` is created using entropy from the
+ operating system. Types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+ The random numbers generated affect the random vector along which gradients
+ are computed to check ``grad``. Note that `rng` is only used when `direction`
+ argument is set to `'random'`.
+
+ Returns
+ -------
+ err : float
+ The square root of the sum of squares (i.e., the 2-norm) of the
+ difference between ``grad(x0, *args)`` and the finite difference
+ approximation of `grad` using func at the points `x0`.
+
+ See Also
+ --------
+ approx_fprime
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> def func(x):
+ ... return x[0]**2 - 0.5 * x[1]**3
+ >>> def grad(x):
+ ... return [2 * x[0], -1.5 * x[1]**2]
+ >>> from scipy.optimize import check_grad
+ >>> check_grad(func, grad, [1.5, -1.5])
+ 2.9802322387695312e-08 # may vary
+ >>> rng = np.random.default_rng()
+ >>> check_grad(func, grad, [1.5, -1.5],
+ ... direction='random', seed=rng)
+ 2.9802322387695312e-08
+
+ """
+ step = epsilon
+ x0 = np.asarray(x0)
+
+ def g(w, func, x0, v, *args):
+ return func(x0 + w*v, *args)
+
+ if direction == 'random':
+ _grad = np.asanyarray(grad(x0, *args))
+ if _grad.ndim > 1:
+ raise ValueError("'random' can only be used with scalar valued"
+ " func")
+ rng_gen = check_random_state(rng)
+ v = rng_gen.standard_normal(size=(x0.shape))
+ _args = (func, x0, v) + args
+ _func = g
+ vars = np.zeros((1,))
+ analytical_grad = np.dot(_grad, v)
+ elif direction == 'all':
+ _args = args
+ _func = func
+ vars = x0
+ analytical_grad = grad(x0, *args)
+ else:
+ raise ValueError(f"{direction} is not a valid string for "
+ "``direction`` argument")
+
+ return np.sqrt(np.sum(np.abs(
+ (analytical_grad - approx_fprime(vars, _func, step, *_args))**2
+ )))
+
+
+def approx_fhess_p(x0, p, fprime, epsilon, *args):
+ # calculate fprime(x0) first, as this may be cached by ScalarFunction
+ f1 = fprime(*((x0,) + args))
+ f2 = fprime(*((x0 + epsilon*p,) + args))
+ return (f2 - f1) / epsilon
+
+
+class _LineSearchError(RuntimeError):
+ pass
+
+
+def _line_search_wolfe12(f, fprime, xk, pk, gfk, old_fval, old_old_fval,
+ **kwargs):
+ """
+ Same as line_search_wolfe1, but fall back to line_search_wolfe2 if
+ suitable step length is not found, and raise an exception if a
+ suitable step length is not found.
+
+ Raises
+ ------
+ _LineSearchError
+ If no suitable step size is found
+
+ """
+
+ extra_condition = kwargs.pop('extra_condition', None)
+
+ ret = line_search_wolfe1(f, fprime, xk, pk, gfk,
+ old_fval, old_old_fval,
+ **kwargs)
+
+ if ret[0] is not None and extra_condition is not None:
+ xp1 = xk + ret[0] * pk
+ if not extra_condition(ret[0], xp1, ret[3], ret[5]):
+ # Reject step if extra_condition fails
+ ret = (None,)
+
+ if ret[0] is None:
+ # line search failed: try different one.
+ with warnings.catch_warnings():
+ warnings.simplefilter('ignore', LineSearchWarning)
+ kwargs2 = {}
+ for key in ('c1', 'c2', 'amax'):
+ if key in kwargs:
+ kwargs2[key] = kwargs[key]
+ ret = line_search_wolfe2(f, fprime, xk, pk, gfk,
+ old_fval, old_old_fval,
+ extra_condition=extra_condition,
+ **kwargs2)
+
+ if ret[0] is None:
+ raise _LineSearchError()
+
+ return ret
+
+
+def fmin_bfgs(f, x0, fprime=None, args=(), gtol=1e-5, norm=np.inf,
+ epsilon=_epsilon, maxiter=None, full_output=0, disp=1,
+ retall=0, callback=None, xrtol=0, c1=1e-4, c2=0.9,
+ hess_inv0=None):
+ """
+ Minimize a function using the BFGS algorithm.
+
+ Parameters
+ ----------
+ f : callable ``f(x,*args)``
+ Objective function to be minimized.
+ x0 : ndarray
+ Initial guess, shape (n,)
+ fprime : callable ``f'(x,*args)``, optional
+ Gradient of f.
+ args : tuple, optional
+ Extra arguments passed to f and fprime.
+ gtol : float, optional
+ Terminate successfully if gradient norm is less than `gtol`
+ norm : float, optional
+ Order of norm (Inf is max, -Inf is min)
+ epsilon : int or ndarray, optional
+ If `fprime` is approximated, use this value for the step size.
+ callback : callable, optional
+ An optional user-supplied function to call after each
+ iteration. Called as ``callback(xk)``, where ``xk`` is the
+ current parameter vector.
+ maxiter : int, optional
+ Maximum number of iterations to perform.
+ full_output : bool, optional
+ If True, return ``fopt``, ``func_calls``, ``grad_calls``, and
+ ``warnflag`` in addition to ``xopt``.
+ disp : bool, optional
+ Print convergence message if True.
+ retall : bool, optional
+ Return a list of results at each iteration if True.
+ xrtol : float, default: 0
+ Relative tolerance for `x`. Terminate successfully if step
+ size is less than ``xk * xrtol`` where ``xk`` is the current
+ parameter vector.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.9
+ Parameter for curvature condition rule.
+ hess_inv0 : None or ndarray, optional``
+ Initial inverse hessian estimate, shape (n, n). If None (default) then
+ the identity matrix is used.
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameters which minimize f, i.e., ``f(xopt) == fopt``.
+ fopt : float
+ Minimum value.
+ gopt : ndarray
+ Value of gradient at minimum, f'(xopt), which should be near 0.
+ Bopt : ndarray
+ Value of 1/f''(xopt), i.e., the inverse Hessian matrix.
+ func_calls : int
+ Number of function_calls made.
+ grad_calls : int
+ Number of gradient calls made.
+ warnflag : integer
+ 1 : Maximum number of iterations exceeded.
+ 2 : Gradient and/or function calls not changing.
+ 3 : NaN result encountered.
+ allvecs : list
+ The value of `xopt` at each iteration. Only returned if `retall` is
+ True.
+
+ Notes
+ -----
+ Optimize the function, `f`, whose gradient is given by `fprime`
+ using the quasi-Newton method of Broyden, Fletcher, Goldfarb,
+ and Shanno (BFGS).
+
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+
+ See Also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See ``method='BFGS'`` in particular.
+
+ References
+ ----------
+ Wright, and Nocedal 'Numerical Optimization', 1999, p. 198.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import fmin_bfgs
+ >>> def quadratic_cost(x, Q):
+ ... return x @ Q @ x
+ ...
+ >>> x0 = np.array([-3, -4])
+ >>> cost_weight = np.diag([1., 10.])
+ >>> # Note that a trailing comma is necessary for a tuple with single element
+ >>> fmin_bfgs(quadratic_cost, x0, args=(cost_weight,))
+ Optimization terminated successfully.
+ Current function value: 0.000000
+ Iterations: 7 # may vary
+ Function evaluations: 24 # may vary
+ Gradient evaluations: 8 # may vary
+ array([ 2.85169950e-06, -4.61820139e-07])
+
+ >>> def quadratic_cost_grad(x, Q):
+ ... return 2 * Q @ x
+ ...
+ >>> fmin_bfgs(quadratic_cost, x0, quadratic_cost_grad, args=(cost_weight,))
+ Optimization terminated successfully.
+ Current function value: 0.000000
+ Iterations: 7
+ Function evaluations: 8
+ Gradient evaluations: 8
+ array([ 2.85916637e-06, -4.54371951e-07])
+
+ """
+ opts = {'gtol': gtol,
+ 'norm': norm,
+ 'eps': epsilon,
+ 'disp': disp,
+ 'maxiter': maxiter,
+ 'return_all': retall,
+ 'xrtol': xrtol,
+ 'c1': c1,
+ 'c2': c2,
+ 'hess_inv0': hess_inv0}
+
+ callback = _wrap_callback(callback)
+ res = _minimize_bfgs(f, x0, args, fprime, callback=callback, **opts)
+
+ if full_output:
+ retlist = (res['x'], res['fun'], res['jac'], res['hess_inv'],
+ res['nfev'], res['njev'], res['status'])
+ if retall:
+ retlist += (res['allvecs'], )
+ return retlist
+ else:
+ if retall:
+ return res['x'], res['allvecs']
+ else:
+ return res['x']
+
+
+def _minimize_bfgs(fun, x0, args=(), jac=None, callback=None,
+ gtol=1e-5, norm=np.inf, eps=_epsilon, maxiter=None,
+ disp=False, return_all=False, finite_diff_rel_step=None,
+ xrtol=0, c1=1e-4, c2=0.9,
+ hess_inv0=None, workers=None, **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using the
+ BFGS algorithm.
+
+ Options
+ -------
+ disp : bool
+ Set to True to print convergence messages.
+ maxiter : int
+ Maximum number of iterations to perform.
+ gtol : float
+ Terminate successfully if gradient norm is less than `gtol`.
+ norm : float
+ Order of norm (Inf is max, -Inf is min).
+ eps : float or ndarray
+ If `jac is None` the absolute step size used for numerical
+ approximation of the jacobian via forward differences.
+ return_all : bool, optional
+ Set to True to return a list of the best solution at each of the
+ iterations.
+ finite_diff_rel_step : None or array_like, optional
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+ use for numerical approximation of the jacobian. The absolute step
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
+ possibly adjusted to fit into the bounds. For ``jac='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+ xrtol : float, default: 0
+ Relative tolerance for `x`. Terminate successfully if step size is
+ less than ``xk * xrtol`` where ``xk`` is the current parameter vector.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.9
+ Parameter for curvature condition rule.
+ hess_inv0 : None or ndarray, optional
+ Initial inverse hessian estimate, shape (n, n). If None (default) then
+ the identity matrix is used.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Notes
+ -----
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+
+ If minimization doesn't complete successfully, with an error message of
+ ``Desired error not necessarily achieved due to precision loss``, then
+ consider setting `gtol` to a higher value. This precision loss typically
+ occurs when the (finite difference) numerical differentiation cannot provide
+ sufficient precision to satisfy the `gtol` termination criterion.
+ This can happen when working in single precision and a callable jac is not
+ provided. For single precision problems a `gtol` of 1e-3 seems to work.
+ """
+ _check_unknown_options(unknown_options)
+ _check_positive_definite(hess_inv0)
+ retall = return_all
+
+ x0 = asarray(x0).flatten()
+ if x0.ndim == 0:
+ x0 = x0.reshape((1,))
+ if maxiter is None:
+ maxiter = len(x0) * 200
+
+ sf = _prepare_scalar_function(fun, x0, jac, args=args, epsilon=eps,
+ finite_diff_rel_step=finite_diff_rel_step,
+ workers=workers)
+
+ f = sf.fun
+ myfprime = sf.grad
+
+ old_fval = f(x0)
+ gfk = myfprime(x0)
+
+ k = 0
+ N = len(x0)
+ I = np.eye(N, dtype=int)
+ Hk = I if hess_inv0 is None else hess_inv0
+
+ # Sets the initial step guess to dx ~ 1
+ old_old_fval = old_fval + np.linalg.norm(gfk) / 2
+
+ xk = x0
+ if retall:
+ allvecs = [x0]
+ warnflag = 0
+ gnorm = vecnorm(gfk, ord=norm)
+ while (gnorm > gtol) and (k < maxiter):
+ pk = -np.dot(Hk, gfk)
+ try:
+ alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \
+ _line_search_wolfe12(f, myfprime, xk, pk, gfk,
+ old_fval, old_old_fval, amin=1e-100,
+ amax=1e100, c1=c1, c2=c2)
+ except _LineSearchError:
+ # Line search failed to find a better solution.
+ warnflag = 2
+ break
+
+ sk = alpha_k * pk
+ xkp1 = xk + sk
+
+ if retall:
+ allvecs.append(xkp1)
+ xk = xkp1
+ if gfkp1 is None:
+ gfkp1 = myfprime(xkp1)
+
+ yk = gfkp1 - gfk
+ gfk = gfkp1
+ k += 1
+ intermediate_result = OptimizeResult(x=xk, fun=old_fval)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+ gnorm = vecnorm(gfk, ord=norm)
+ if (gnorm <= gtol):
+ break
+
+ # See Chapter 5 in P.E. Frandsen, K. Jonasson, H.B. Nielsen,
+ # O. Tingleff: "Unconstrained Optimization", IMM, DTU. 1999.
+ # These notes are available here:
+ # http://www2.imm.dtu.dk/documents/ftp/publlec.html
+ if (alpha_k*vecnorm(pk) <= xrtol*(xrtol + vecnorm(xk))):
+ break
+
+ if not np.isfinite(old_fval):
+ # We correctly found +-Inf as optimal value, or something went
+ # wrong.
+ warnflag = 2
+ break
+
+ rhok_inv = np.dot(yk, sk)
+ # this was handled in numeric, let it remains for more safety
+ # Cryptic comment above is preserved for posterity. Future reader:
+ # consider change to condition below proposed in gh-1261/gh-17345.
+ if rhok_inv == 0.:
+ rhok = 1000.0
+ if disp:
+ msg = "Divide-by-zero encountered: rhok assumed large"
+ _print_success_message_or_warn(True, msg)
+ else:
+ rhok = 1. / rhok_inv
+
+ A1 = I - sk[:, np.newaxis] * yk[np.newaxis, :] * rhok
+ A2 = I - yk[:, np.newaxis] * sk[np.newaxis, :] * rhok
+ Hk = np.dot(A1, np.dot(Hk, A2)) + (rhok * sk[:, np.newaxis] *
+ sk[np.newaxis, :])
+
+ fval = old_fval
+
+ if warnflag == 2:
+ msg = _status_message['pr_loss']
+ elif k >= maxiter:
+ warnflag = 1
+ msg = _status_message['maxiter']
+ elif np.isnan(gnorm) or np.isnan(fval) or np.isnan(xk).any():
+ warnflag = 3
+ msg = _status_message['nan']
+ else:
+ msg = _status_message['success']
+
+ if disp:
+ _print_success_message_or_warn(warnflag, msg)
+ print(f" Current function value: {fval:f}")
+ print(f" Iterations: {k:d}")
+ print(f" Function evaluations: {sf.nfev:d}")
+ print(f" Gradient evaluations: {sf.ngev:d}")
+
+ result = OptimizeResult(fun=fval, jac=gfk, hess_inv=Hk, nfev=sf.nfev,
+ njev=sf.ngev, status=warnflag,
+ success=(warnflag == 0), message=msg, x=xk,
+ nit=k)
+ if retall:
+ result['allvecs'] = allvecs
+ return result
+
+
+def _print_success_message_or_warn(warnflag, message, warntype=None):
+ if not warnflag:
+ print(message)
+ else:
+ warnings.warn(message, warntype or OptimizeWarning, stacklevel=3)
+
+
+def fmin_cg(f, x0, fprime=None, args=(), gtol=1e-5, norm=np.inf,
+ epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0,
+ callback=None, c1=1e-4, c2=0.4):
+ """
+ Minimize a function using a nonlinear conjugate gradient algorithm.
+
+ Parameters
+ ----------
+ f : callable, ``f(x, *args)``
+ Objective function to be minimized. Here `x` must be a 1-D array of
+ the variables that are to be changed in the search for a minimum, and
+ `args` are the other (fixed) parameters of `f`.
+ x0 : ndarray
+ A user-supplied initial estimate of `xopt`, the optimal value of `x`.
+ It must be a 1-D array of values.
+ fprime : callable, ``fprime(x, *args)``, optional
+ A function that returns the gradient of `f` at `x`. Here `x` and `args`
+ are as described above for `f`. The returned value must be a 1-D array.
+ Defaults to None, in which case the gradient is approximated
+ numerically (see `epsilon`, below).
+ args : tuple, optional
+ Parameter values passed to `f` and `fprime`. Must be supplied whenever
+ additional fixed parameters are needed to completely specify the
+ functions `f` and `fprime`.
+ gtol : float, optional
+ Stop when the norm of the gradient is less than `gtol`.
+ norm : float, optional
+ Order to use for the norm of the gradient
+ (``-np.inf`` is min, ``np.inf`` is max).
+ epsilon : float or ndarray, optional
+ Step size(s) to use when `fprime` is approximated numerically. Can be a
+ scalar or a 1-D array. Defaults to ``sqrt(eps)``, with eps the
+ floating point machine precision. Usually ``sqrt(eps)`` is about
+ 1.5e-8.
+ maxiter : int, optional
+ Maximum number of iterations to perform. Default is ``200 * len(x0)``.
+ full_output : bool, optional
+ If True, return `fopt`, `func_calls`, `grad_calls`, and `warnflag` in
+ addition to `xopt`. See the Returns section below for additional
+ information on optional return values.
+ disp : bool, optional
+ If True, return a convergence message, followed by `xopt`.
+ retall : bool, optional
+ If True, add to the returned values the results of each iteration.
+ callback : callable, optional
+ An optional user-supplied function, called after each iteration.
+ Called as ``callback(xk)``, where ``xk`` is the current value of `x0`.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.4
+ Parameter for curvature condition rule.
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameters which minimize f, i.e., ``f(xopt) == fopt``.
+ fopt : float, optional
+ Minimum value found, f(xopt). Only returned if `full_output` is True.
+ func_calls : int, optional
+ The number of function_calls made. Only returned if `full_output`
+ is True.
+ grad_calls : int, optional
+ The number of gradient calls made. Only returned if `full_output` is
+ True.
+ warnflag : int, optional
+ Integer value with warning status, only returned if `full_output` is
+ True.
+
+ 0 : Success.
+
+ 1 : The maximum number of iterations was exceeded.
+
+ 2 : Gradient and/or function calls were not changing. May indicate
+ that precision was lost, i.e., the routine did not converge.
+
+ 3 : NaN result encountered.
+
+ allvecs : list of ndarray, optional
+ List of arrays, containing the results at each iteration.
+ Only returned if `retall` is True.
+
+ See Also
+ --------
+ minimize : common interface to all `scipy.optimize` algorithms for
+ unconstrained and constrained minimization of multivariate
+ functions. It provides an alternative way to call
+ ``fmin_cg``, by specifying ``method='CG'``.
+
+ Notes
+ -----
+ This conjugate gradient algorithm is based on that of Polak and Ribiere
+ [1]_.
+
+ Conjugate gradient methods tend to work better when:
+
+ 1. `f` has a unique global minimizing point, and no local minima or
+ other stationary points,
+ 2. `f` is, at least locally, reasonably well approximated by a
+ quadratic function of the variables,
+ 3. `f` is continuous and has a continuous gradient,
+ 4. `fprime` is not too large, e.g., has a norm less than 1000,
+ 5. The initial guess, `x0`, is reasonably close to `f` 's global
+ minimizing point, `xopt`.
+
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+
+ References
+ ----------
+ .. [1] Wright & Nocedal, "Numerical Optimization", 1999, pp. 120-122.
+
+ Examples
+ --------
+ Example 1: seek the minimum value of the expression
+ ``a*u**2 + b*u*v + c*v**2 + d*u + e*v + f`` for given values
+ of the parameters and an initial guess ``(u, v) = (0, 0)``.
+
+ >>> import numpy as np
+ >>> args = (2, 3, 7, 8, 9, 10) # parameter values
+ >>> def f(x, *args):
+ ... u, v = x
+ ... a, b, c, d, e, f = args
+ ... return a*u**2 + b*u*v + c*v**2 + d*u + e*v + f
+ >>> def gradf(x, *args):
+ ... u, v = x
+ ... a, b, c, d, e, f = args
+ ... gu = 2*a*u + b*v + d # u-component of the gradient
+ ... gv = b*u + 2*c*v + e # v-component of the gradient
+ ... return np.asarray((gu, gv))
+ >>> x0 = np.asarray((0, 0)) # Initial guess.
+ >>> from scipy import optimize
+ >>> res1 = optimize.fmin_cg(f, x0, fprime=gradf, args=args)
+ Optimization terminated successfully.
+ Current function value: 1.617021
+ Iterations: 4
+ Function evaluations: 8
+ Gradient evaluations: 8
+ >>> res1
+ array([-1.80851064, -0.25531915])
+
+ Example 2: solve the same problem using the `minimize` function.
+ (This `myopts` dictionary shows all of the available options,
+ although in practice only non-default values would be needed.
+ The returned value will be a dictionary.)
+
+ >>> opts = {'maxiter' : None, # default value.
+ ... 'disp' : True, # non-default value.
+ ... 'gtol' : 1e-5, # default value.
+ ... 'norm' : np.inf, # default value.
+ ... 'eps' : 1.4901161193847656e-08} # default value.
+ >>> res2 = optimize.minimize(f, x0, jac=gradf, args=args,
+ ... method='CG', options=opts)
+ Optimization terminated successfully.
+ Current function value: 1.617021
+ Iterations: 4
+ Function evaluations: 8
+ Gradient evaluations: 8
+ >>> res2.x # minimum found
+ array([-1.80851064, -0.25531915])
+
+ """
+ opts = {'gtol': gtol,
+ 'norm': norm,
+ 'eps': epsilon,
+ 'disp': disp,
+ 'maxiter': maxiter,
+ 'return_all': retall}
+
+ callback = _wrap_callback(callback)
+ res = _minimize_cg(f, x0, args, fprime, callback=callback, c1=c1, c2=c2,
+ **opts)
+
+ if full_output:
+ retlist = res['x'], res['fun'], res['nfev'], res['njev'], res['status']
+ if retall:
+ retlist += (res['allvecs'], )
+ return retlist
+ else:
+ if retall:
+ return res['x'], res['allvecs']
+ else:
+ return res['x']
+
+
+def _minimize_cg(fun, x0, args=(), jac=None, callback=None,
+ gtol=1e-5, norm=np.inf, eps=_epsilon, maxiter=None,
+ disp=False, return_all=False, finite_diff_rel_step=None,
+ c1=1e-4, c2=0.4, workers=None,
+ **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using the
+ conjugate gradient algorithm.
+
+ Options
+ -------
+ disp : bool
+ Set to True to print convergence messages.
+ maxiter : int
+ Maximum number of iterations to perform.
+ gtol : float
+ Gradient norm must be less than `gtol` before successful
+ termination.
+ norm : float
+ Order of norm (Inf is max, -Inf is min).
+ eps : float or ndarray
+ If `jac is None` the absolute step size used for numerical
+ approximation of the jacobian via forward differences.
+ return_all : bool, optional
+ Set to True to return a list of the best solution at each of the
+ iterations.
+ finite_diff_rel_step : None or array_like, optional
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+ use for numerical approximation of the jacobian. The absolute step
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
+ possibly adjusted to fit into the bounds. For ``jac='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.4
+ Parameter for curvature condition rule.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Notes
+ -----
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+ """
+ _check_unknown_options(unknown_options)
+
+ retall = return_all
+
+ x0 = asarray(x0).flatten()
+ if maxiter is None:
+ maxiter = len(x0) * 200
+
+ sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
+ finite_diff_rel_step=finite_diff_rel_step,
+ workers=workers)
+
+ f = sf.fun
+ myfprime = sf.grad
+
+ old_fval = f(x0)
+ gfk = myfprime(x0)
+
+ k = 0
+ xk = x0
+ # Sets the initial step guess to dx ~ 1
+ old_old_fval = old_fval + np.linalg.norm(gfk) / 2
+
+ if retall:
+ allvecs = [xk]
+ warnflag = 0
+ pk = -gfk
+ gnorm = vecnorm(gfk, ord=norm)
+
+ sigma_3 = 0.01
+
+ while (gnorm > gtol) and (k < maxiter):
+ deltak = np.dot(gfk, gfk)
+
+ cached_step = [None]
+
+ def polak_ribiere_powell_step(alpha, gfkp1=None):
+ xkp1 = xk + alpha * pk
+ if gfkp1 is None:
+ gfkp1 = myfprime(xkp1)
+ yk = gfkp1 - gfk
+ beta_k = max(0, np.dot(yk, gfkp1) / deltak)
+ pkp1 = -gfkp1 + beta_k * pk
+ gnorm = vecnorm(gfkp1, ord=norm)
+ return (alpha, xkp1, pkp1, gfkp1, gnorm)
+
+ def descent_condition(alpha, xkp1, fp1, gfkp1):
+ # Polak-Ribiere+ needs an explicit check of a sufficient
+ # descent condition, which is not guaranteed by strong Wolfe.
+ #
+ # See Gilbert & Nocedal, "Global convergence properties of
+ # conjugate gradient methods for optimization",
+ # SIAM J. Optimization 2, 21 (1992).
+ cached_step[:] = polak_ribiere_powell_step(alpha, gfkp1)
+ alpha, xk, pk, gfk, gnorm = cached_step
+
+ # Accept step if it leads to convergence.
+ if gnorm <= gtol:
+ return True
+
+ # Accept step if sufficient descent condition applies.
+ return np.dot(pk, gfk) <= -sigma_3 * np.dot(gfk, gfk)
+
+ try:
+ alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \
+ _line_search_wolfe12(f, myfprime, xk, pk, gfk, old_fval,
+ old_old_fval, c1=c1, c2=c2, amin=1e-100,
+ amax=1e100, extra_condition=descent_condition)
+ except _LineSearchError:
+ # Line search failed to find a better solution.
+ warnflag = 2
+ break
+
+ # Reuse already computed results if possible
+ if alpha_k == cached_step[0]:
+ alpha_k, xk, pk, gfk, gnorm = cached_step
+ else:
+ alpha_k, xk, pk, gfk, gnorm = polak_ribiere_powell_step(alpha_k, gfkp1)
+
+ if retall:
+ allvecs.append(xk)
+ k += 1
+ intermediate_result = OptimizeResult(x=xk, fun=old_fval)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+
+ fval = old_fval
+ if warnflag == 2:
+ msg = _status_message['pr_loss']
+ elif k >= maxiter:
+ warnflag = 1
+ msg = _status_message['maxiter']
+ elif np.isnan(gnorm) or np.isnan(fval) or np.isnan(xk).any():
+ warnflag = 3
+ msg = _status_message['nan']
+ else:
+ msg = _status_message['success']
+
+ if disp:
+ _print_success_message_or_warn(warnflag, msg)
+ print(f" Current function value: {fval:f}")
+ print(f" Iterations: {k:d}")
+ print(f" Function evaluations: {sf.nfev:d}")
+ print(f" Gradient evaluations: {sf.ngev:d}")
+
+ result = OptimizeResult(fun=fval, jac=gfk, nfev=sf.nfev,
+ njev=sf.ngev, status=warnflag,
+ success=(warnflag == 0), message=msg, x=xk,
+ nit=k)
+ if retall:
+ result['allvecs'] = allvecs
+ return result
+
+
+def fmin_ncg(f, x0, fprime, fhess_p=None, fhess=None, args=(), avextol=1e-5,
+ epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0,
+ callback=None, c1=1e-4, c2=0.9):
+ """
+ Unconstrained minimization of a function using the Newton-CG method.
+
+ Parameters
+ ----------
+ f : callable ``f(x, *args)``
+ Objective function to be minimized.
+ x0 : ndarray
+ Initial guess.
+ fprime : callable ``f'(x, *args)``
+ Gradient of f.
+ fhess_p : callable ``fhess_p(x, p, *args)``, optional
+ Function which computes the Hessian of f times an
+ arbitrary vector, p.
+ fhess : callable ``fhess(x, *args)``, optional
+ Function to compute the Hessian matrix of f.
+ args : tuple, optional
+ Extra arguments passed to f, fprime, fhess_p, and fhess
+ (the same set of extra arguments is supplied to all of
+ these functions).
+ epsilon : float or ndarray, optional
+ If fhess is approximated, use this value for the step size.
+ callback : callable, optional
+ An optional user-supplied function which is called after
+ each iteration. Called as callback(xk), where xk is the
+ current parameter vector.
+ avextol : float, optional
+ Convergence is assumed when the average relative error in
+ the minimizer falls below this amount.
+ maxiter : int, optional
+ Maximum number of iterations to perform.
+ full_output : bool, optional
+ If True, return the optional outputs.
+ disp : bool, optional
+ If True, print convergence message.
+ retall : bool, optional
+ If True, return a list of results at each iteration.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.9
+ Parameter for curvature condition rule
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameters which minimize f, i.e., ``f(xopt) == fopt``.
+ fopt : float
+ Value of the function at xopt, i.e., ``fopt = f(xopt)``.
+ fcalls : int
+ Number of function calls made.
+ gcalls : int
+ Number of gradient calls made.
+ hcalls : int
+ Number of Hessian calls made.
+ warnflag : int
+ Warnings generated by the algorithm.
+ 1 : Maximum number of iterations exceeded.
+ 2 : Line search failure (precision loss).
+ 3 : NaN result encountered.
+ allvecs : list
+ The result at each iteration, if retall is True (see below).
+
+ See also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'Newton-CG' `method` in particular.
+
+ Notes
+ -----
+ Only one of `fhess_p` or `fhess` need to be given. If `fhess`
+ is provided, then `fhess_p` will be ignored. If neither `fhess`
+ nor `fhess_p` is provided, then the hessian product will be
+ approximated using finite differences on `fprime`. `fhess_p`
+ must compute the hessian times an arbitrary vector. If it is not
+ given, finite-differences on `fprime` are used to compute
+ it.
+
+ Newton-CG methods are also called truncated Newton methods. This
+ function differs from scipy.optimize.fmin_tnc because
+
+ 1. scipy.optimize.fmin_ncg is written purely in Python using NumPy
+ and scipy while scipy.optimize.fmin_tnc calls a C function.
+ 2. scipy.optimize.fmin_ncg is only for unconstrained minimization
+ while scipy.optimize.fmin_tnc is for unconstrained minimization
+ or box constrained minimization. (Box constraints give
+ lower and upper bounds for each variable separately.)
+
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+
+ References
+ ----------
+ Wright & Nocedal, 'Numerical Optimization', 1999, p. 140.
+
+ """
+ opts = {'xtol': avextol,
+ 'eps': epsilon,
+ 'maxiter': maxiter,
+ 'disp': disp,
+ 'return_all': retall}
+
+ callback = _wrap_callback(callback)
+ res = _minimize_newtoncg(f, x0, args, fprime, fhess, fhess_p,
+ callback=callback, c1=c1, c2=c2, **opts)
+
+ if full_output:
+ retlist = (res['x'], res['fun'], res['nfev'], res['njev'],
+ res['nhev'], res['status'])
+ if retall:
+ retlist += (res['allvecs'], )
+ return retlist
+ else:
+ if retall:
+ return res['x'], res['allvecs']
+ else:
+ return res['x']
+
+
+def _minimize_newtoncg(fun, x0, args=(), jac=None, hess=None, hessp=None,
+ callback=None, xtol=1e-5, eps=_epsilon, maxiter=None,
+ disp=False, return_all=False, c1=1e-4, c2=0.9, workers=None,
+ **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using the
+ Newton-CG algorithm.
+
+ Note that the `jac` parameter (Jacobian) is required.
+
+ Options
+ -------
+ disp : bool
+ Set to True to print convergence messages.
+ xtol : float
+ Average relative error in solution `xopt` acceptable for
+ convergence.
+ maxiter : int
+ Maximum number of iterations to perform.
+ eps : float or ndarray
+ If `hessp` is approximated, use this value for the step size.
+ return_all : bool, optional
+ Set to True to return a list of the best solution at each of the
+ iterations.
+ c1 : float, default: 1e-4
+ Parameter for Armijo condition rule.
+ c2 : float, default: 0.9
+ Parameter for curvature condition rule.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Notes
+ -----
+ Parameters `c1` and `c2` must satisfy ``0 < c1 < c2 < 1``.
+ """
+ _check_unknown_options(unknown_options)
+ if jac is None:
+ raise ValueError('Jacobian is required for Newton-CG method')
+ fhess_p = hessp
+ fhess = hess
+ avextol = xtol
+ epsilon = eps
+ retall = return_all
+
+ x0 = asarray(x0).flatten()
+ # TODO: add hessp (callable or FD) to ScalarFunction?
+ sf = _prepare_scalar_function(
+ fun, x0, jac, args=args, epsilon=eps, hess=hess, workers=workers
+ )
+ f = sf.fun
+ fprime = sf.grad
+ _h = sf.hess(x0)
+
+ # Logic for hess/hessp
+ # - If a callable(hess) is provided, then use that
+ # - If hess is a FD_METHOD, or the output from hess(x) is a LinearOperator
+ # then create a hessp function using those.
+ # - If hess is None but you have callable(hessp) then use the hessp.
+ # - If hess and hessp are None then approximate hessp using the grad/jac.
+
+ if (hess in FD_METHODS or isinstance(_h, LinearOperator)):
+ fhess = None
+
+ def _hessp(x, p, *args):
+ return sf.hess(x).dot(p)
+
+ fhess_p = _hessp
+
+ def terminate(warnflag, msg):
+ if disp:
+ _print_success_message_or_warn(warnflag, msg)
+ print(f" Current function value: {old_fval:f}")
+ print(f" Iterations: {k:d}")
+ print(f" Function evaluations: {sf.nfev:d}")
+ print(f" Gradient evaluations: {sf.ngev:d}")
+ print(f" Hessian evaluations: {hcalls:d}")
+ fval = old_fval
+ result = OptimizeResult(fun=fval, jac=gfk, nfev=sf.nfev,
+ njev=sf.ngev, nhev=hcalls, status=warnflag,
+ success=(warnflag == 0), message=msg, x=xk,
+ nit=k)
+ if retall:
+ result['allvecs'] = allvecs
+ return result
+
+ hcalls = 0
+ if maxiter is None:
+ maxiter = len(x0)*200
+ cg_maxiter = 20*len(x0)
+
+ xtol = len(x0) * avextol
+ # Make sure we enter the while loop.
+ update_l1norm = np.finfo(float).max
+ xk = np.copy(x0)
+ if retall:
+ allvecs = [xk]
+ k = 0
+ gfk = None
+ old_fval = f(x0)
+ old_old_fval = None
+ float64eps = np.finfo(np.float64).eps
+ while update_l1norm > xtol:
+ if k >= maxiter:
+ msg = "Warning: " + _status_message['maxiter']
+ return terminate(1, msg)
+ # Compute a search direction pk by applying the CG method to
+ # del2 f(xk) p = - grad f(xk) starting from 0.
+ b = -fprime(xk)
+ maggrad = np.linalg.norm(b, ord=1)
+ eta = min(0.5, math.sqrt(maggrad))
+ termcond = eta * maggrad
+ xsupi = zeros(len(x0), dtype=x0.dtype)
+ ri = -b
+ psupi = -ri
+ i = 0
+ dri0 = np.dot(ri, ri)
+
+ if fhess is not None: # you want to compute hessian once.
+ A = sf.hess(xk)
+ hcalls += 1
+
+ for k2 in range(cg_maxiter):
+ if np.add.reduce(np.abs(ri)) <= termcond:
+ break
+ if fhess is None:
+ if fhess_p is None:
+ Ap = approx_fhess_p(xk, psupi, fprime, epsilon)
+ else:
+ Ap = fhess_p(xk, psupi, *args)
+ hcalls += 1
+ else:
+ # hess was supplied as a callable or hessian update strategy, so
+ # A is a dense numpy array or sparse array
+ Ap = A.dot(psupi)
+ # check curvature
+ Ap = asarray(Ap).squeeze() # get rid of matrices...
+ curv = np.dot(psupi, Ap)
+ if 0 <= curv <= 3 * float64eps:
+ break
+ elif curv < 0:
+ if (i > 0):
+ break
+ else:
+ # fall back to steepest descent direction
+ xsupi = dri0 / (-curv) * b
+ break
+ alphai = dri0 / curv
+ xsupi += alphai * psupi
+ ri += alphai * Ap
+ dri1 = np.dot(ri, ri)
+ betai = dri1 / dri0
+ psupi = -ri + betai * psupi
+ i += 1
+ dri0 = dri1 # update np.dot(ri,ri) for next time.
+ else:
+ # curvature keeps increasing, bail out
+ msg = ("Warning: CG iterations didn't converge. The Hessian is not "
+ "positive definite.")
+ return terminate(3, msg)
+
+ pk = xsupi # search direction is solution to system.
+ gfk = -b # gradient at xk
+
+ try:
+ alphak, fc, gc, old_fval, old_old_fval, gfkp1 = \
+ _line_search_wolfe12(f, fprime, xk, pk, gfk,
+ old_fval, old_old_fval, c1=c1, c2=c2)
+ except _LineSearchError:
+ # Line search failed to find a better solution.
+ msg = "Warning: " + _status_message['pr_loss']
+ return terminate(2, msg)
+
+ update = alphak * pk
+ xk += update # upcast if necessary
+ if retall:
+ allvecs.append(xk)
+ k += 1
+ intermediate_result = OptimizeResult(x=xk, fun=old_fval)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ return terminate(5, "")
+ update_l1norm = np.linalg.norm(update, ord=1)
+
+ else:
+ if np.isnan(old_fval) or np.isnan(update_l1norm):
+ return terminate(3, _status_message['nan'])
+
+ msg = _status_message['success']
+ return terminate(0, msg)
+
+
+def fminbound(func, x1, x2, args=(), xtol=1e-5, maxfun=500,
+ full_output=0, disp=1):
+ """Bounded minimization for scalar functions.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Objective function to be minimized (must accept and return scalars).
+ x1, x2 : float or array scalar
+ Finite optimization bounds.
+ args : tuple, optional
+ Extra arguments passed to function.
+ xtol : float, optional
+ The convergence tolerance.
+ maxfun : int, optional
+ Maximum number of function evaluations allowed.
+ full_output : bool, optional
+ If True, return optional outputs.
+ disp: int, optional
+ If non-zero, print messages.
+
+ ``0`` : no message printing.
+
+ ``1`` : non-convergence notification messages only.
+
+ ``2`` : print a message on convergence too.
+
+ ``3`` : print iteration results.
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameters (over given interval) which minimize the
+ objective function.
+ fval : number
+ (Optional output) The function value evaluated at the minimizer.
+ ierr : int
+ (Optional output) An error flag (0 if converged, 1 if maximum number of
+ function calls reached).
+ numfunc : int
+ (Optional output) The number of function calls made.
+
+ See also
+ --------
+ minimize_scalar: Interface to minimization algorithms for scalar
+ univariate functions. See the 'Bounded' `method` in particular.
+
+ Notes
+ -----
+ Finds a local minimizer of the scalar function `func` in the
+ interval x1 < xopt < x2 using Brent's method. (See `brent`
+ for auto-bracketing.)
+
+ References
+ ----------
+ .. [1] Forsythe, G.E., M. A. Malcolm, and C. B. Moler. "Computer Methods
+ for Mathematical Computations." Prentice-Hall Series in Automatic
+ Computation 259 (1977).
+ .. [2] Brent, Richard P. Algorithms for Minimization Without Derivatives.
+ Courier Corporation, 2013.
+
+ Examples
+ --------
+ `fminbound` finds the minimizer of the function in the given range.
+ The following examples illustrate this.
+
+ >>> from scipy import optimize
+ >>> def f(x):
+ ... return (x-1)**2
+ >>> minimizer = optimize.fminbound(f, -4, 4)
+ >>> minimizer
+ 1.0
+ >>> minimum = f(minimizer)
+ >>> minimum
+ 0.0
+ >>> res = optimize.fminbound(f, 3, 4, full_output=True)
+ >>> minimizer, fval, ierr, numfunc = res
+ >>> minimizer
+ 3.000005960860986
+ >>> minimum = f(minimizer)
+ >>> minimum, fval
+ (4.000023843479476, 4.000023843479476)
+ """
+ options = {'xatol': xtol,
+ 'maxiter': maxfun,
+ 'disp': disp}
+
+ res = _minimize_scalar_bounded(func, (x1, x2), args, **options)
+ if full_output:
+ return res['x'], res['fun'], res['status'], res['nfev']
+ else:
+ return res['x']
+
+
+def _minimize_scalar_bounded(func, bounds, args=(),
+ xatol=1e-5, maxiter=500, disp=0,
+ **unknown_options):
+ """
+ Options
+ -------
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp: int, optional
+ If non-zero, print messages.
+
+ ``0`` : no message printing.
+
+ ``1`` : non-convergence notification messages only.
+
+ ``2`` : print a message on convergence too.
+
+ ``3`` : print iteration results.
+
+ xatol : float
+ Absolute error in solution `xopt` acceptable for convergence.
+
+ """
+ _check_unknown_options(unknown_options)
+ maxfun = maxiter
+ # Test bounds are of correct form
+ if len(bounds) != 2:
+ raise ValueError('bounds must have two elements.')
+ x1, x2 = bounds
+
+ if not (is_finite_scalar(x1) and is_finite_scalar(x2)):
+ raise ValueError("Optimization bounds must be finite scalars.")
+
+ if x1 > x2:
+ raise ValueError("The lower bound exceeds the upper bound.")
+
+ flag = 0
+ header = ' Func-count x f(x) Procedure'
+ step = ' initial'
+
+ sqrt_eps = sqrt(2.2e-16)
+ golden_mean = 0.5 * (3.0 - sqrt(5.0))
+ a, b = x1, x2
+ fulc = a + golden_mean * (b - a)
+ nfc, xf = fulc, fulc
+ rat = e = 0.0
+ x = xf
+ fx = func(x, *args)
+ num = 1
+ fmin_data = (1, xf, fx)
+ fu = np.inf
+
+ ffulc = fnfc = fx
+ xm = 0.5 * (a + b)
+ tol1 = sqrt_eps * np.abs(xf) + xatol / 3.0
+ tol2 = 2.0 * tol1
+
+ if disp > 2:
+ print(" ")
+ print(header)
+ print("%5.0f %12.6g %12.6g %s" % (fmin_data + (step,)))
+
+ while (np.abs(xf - xm) > (tol2 - 0.5 * (b - a))):
+ golden = 1
+ # Check for parabolic fit
+ if np.abs(e) > tol1:
+ golden = 0
+ r = (xf - nfc) * (fx - ffulc)
+ q = (xf - fulc) * (fx - fnfc)
+ p = (xf - fulc) * q - (xf - nfc) * r
+ q = 2.0 * (q - r)
+ if q > 0.0:
+ p = -p
+ q = np.abs(q)
+ r = e
+ e = rat
+
+ # Check for acceptability of parabola
+ if ((np.abs(p) < np.abs(0.5*q*r)) and (p > q*(a - xf)) and
+ (p < q * (b - xf))):
+ rat = (p + 0.0) / q
+ x = xf + rat
+ step = ' parabolic'
+
+ if ((x - a) < tol2) or ((b - x) < tol2):
+ si = np.sign(xm - xf) + ((xm - xf) == 0)
+ rat = tol1 * si
+ else: # do a golden-section step
+ golden = 1
+
+ if golden: # do a golden-section step
+ if xf >= xm:
+ e = a - xf
+ else:
+ e = b - xf
+ rat = golden_mean*e
+ step = ' golden'
+
+ si = np.sign(rat) + (rat == 0)
+ x = xf + si * np.maximum(np.abs(rat), tol1)
+ fu = func(x, *args)
+ num += 1
+ fmin_data = (num, x, fu)
+ if disp > 2:
+ print("%5.0f %12.6g %12.6g %s" % (fmin_data + (step,)))
+
+ if fu <= fx:
+ if x >= xf:
+ a = xf
+ else:
+ b = xf
+ fulc, ffulc = nfc, fnfc
+ nfc, fnfc = xf, fx
+ xf, fx = x, fu
+ else:
+ if x < xf:
+ a = x
+ else:
+ b = x
+ if (fu <= fnfc) or (nfc == xf):
+ fulc, ffulc = nfc, fnfc
+ nfc, fnfc = x, fu
+ elif (fu <= ffulc) or (fulc == xf) or (fulc == nfc):
+ fulc, ffulc = x, fu
+
+ xm = 0.5 * (a + b)
+ tol1 = sqrt_eps * np.abs(xf) + xatol / 3.0
+ tol2 = 2.0 * tol1
+
+ if num >= maxfun:
+ flag = 1
+ break
+
+ if np.isnan(xf) or np.isnan(fx) or np.isnan(fu):
+ flag = 2
+
+ fval = fx
+ if disp > 0:
+ _endprint(x, flag, fval, maxfun, xatol, disp)
+
+ result = OptimizeResult(fun=fval, status=flag, success=(flag == 0),
+ message={0: 'Solution found.',
+ 1: 'Maximum number of function calls '
+ 'reached.',
+ 2: _status_message['nan']}.get(flag, ''),
+ x=xf, nfev=num, nit=num)
+
+ return result
+
+
+class Brent:
+ #need to rethink design of __init__
+ def __init__(self, func, args=(), tol=1.48e-8, maxiter=500,
+ full_output=0, disp=0):
+ self.func = func
+ self.args = args
+ self.tol = tol
+ self.maxiter = maxiter
+ self._mintol = 1.0e-11
+ self._cg = 0.3819660
+ self.xmin = None
+ self.fval = None
+ self.iter = 0
+ self.funcalls = 0
+ self.disp = disp
+
+ # need to rethink design of set_bracket (new options, etc.)
+ def set_bracket(self, brack=None):
+ self.brack = brack
+
+ def get_bracket_info(self):
+ #set up
+ func = self.func
+ args = self.args
+ brack = self.brack
+ ### BEGIN core bracket_info code ###
+ ### carefully DOCUMENT any CHANGES in core ##
+ if brack is None:
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, args=args)
+ elif len(brack) == 2:
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, xa=brack[0],
+ xb=brack[1], args=args)
+ elif len(brack) == 3:
+ xa, xb, xc = brack
+ if (xa > xc): # swap so xa < xc can be assumed
+ xc, xa = xa, xc
+ if not ((xa < xb) and (xb < xc)):
+ raise ValueError(
+ "Bracketing values (xa, xb, xc) do not"
+ " fulfill this requirement: (xa < xb) and (xb < xc)"
+ )
+ fa = func(*((xa,) + args))
+ fb = func(*((xb,) + args))
+ fc = func(*((xc,) + args))
+ if not ((fb < fa) and (fb < fc)):
+ raise ValueError(
+ "Bracketing values (xa, xb, xc) do not fulfill"
+ " this requirement: (f(xb) < f(xa)) and (f(xb) < f(xc))"
+ )
+
+ funcalls = 3
+ else:
+ raise ValueError("Bracketing interval must be "
+ "length 2 or 3 sequence.")
+ ### END core bracket_info code ###
+
+ return xa, xb, xc, fa, fb, fc, funcalls
+
+ def optimize(self):
+ # set up for optimization
+ func = self.func
+ xa, xb, xc, fa, fb, fc, funcalls = self.get_bracket_info()
+ _mintol = self._mintol
+ _cg = self._cg
+ #################################
+ #BEGIN CORE ALGORITHM
+ #################################
+ x = w = v = xb
+ fw = fv = fx = fb
+ if (xa < xc):
+ a = xa
+ b = xc
+ else:
+ a = xc
+ b = xa
+ deltax = 0.0
+ iter = 0
+
+ if self.disp > 2:
+ print(" ")
+ print(f"{'Func-count':^12} {'x':^12} {'f(x)': ^12}")
+ print(f"{funcalls:^12g} {x:^12.6g} {fx:^12.6g}")
+
+ while (iter < self.maxiter):
+ tol1 = self.tol * np.abs(x) + _mintol
+ tol2 = 2.0 * tol1
+ xmid = 0.5 * (a + b)
+ # check for convergence
+ if np.abs(x - xmid) < (tol2 - 0.5 * (b - a)):
+ break
+ # XXX In the first iteration, rat is only bound in the true case
+ # of this conditional. This used to cause an UnboundLocalError
+ # (gh-4140). It should be set before the if (but to what?).
+ if (np.abs(deltax) <= tol1):
+ if (x >= xmid):
+ deltax = a - x # do a golden section step
+ else:
+ deltax = b - x
+ rat = _cg * deltax
+ else: # do a parabolic step
+ tmp1 = (x - w) * (fx - fv)
+ tmp2 = (x - v) * (fx - fw)
+ p = (x - v) * tmp2 - (x - w) * tmp1
+ tmp2 = 2.0 * (tmp2 - tmp1)
+ if (tmp2 > 0.0):
+ p = -p
+ tmp2 = np.abs(tmp2)
+ dx_temp = deltax
+ deltax = rat
+ # check parabolic fit
+ if ((p > tmp2 * (a - x)) and (p < tmp2 * (b - x)) and
+ (np.abs(p) < np.abs(0.5 * tmp2 * dx_temp))):
+ rat = p * 1.0 / tmp2 # if parabolic step is useful.
+ u = x + rat
+ if ((u - a) < tol2 or (b - u) < tol2):
+ if xmid - x >= 0:
+ rat = tol1
+ else:
+ rat = -tol1
+ else:
+ if (x >= xmid):
+ deltax = a - x # if it's not do a golden section step
+ else:
+ deltax = b - x
+ rat = _cg * deltax
+
+ if (np.abs(rat) < tol1): # update by at least tol1
+ if rat >= 0:
+ u = x + tol1
+ else:
+ u = x - tol1
+ else:
+ u = x + rat
+ fu = func(*((u,) + self.args)) # calculate new output value
+ funcalls += 1
+
+ if (fu > fx): # if it's bigger than current
+ if (u < x):
+ a = u
+ else:
+ b = u
+ if (fu <= fw) or (w == x):
+ v = w
+ w = u
+ fv = fw
+ fw = fu
+ elif (fu <= fv) or (v == x) or (v == w):
+ v = u
+ fv = fu
+ else:
+ if (u >= x):
+ a = x
+ else:
+ b = x
+ v = w
+ w = x
+ x = u
+ fv = fw
+ fw = fx
+ fx = fu
+
+ if self.disp > 2:
+ print(f"{funcalls:^12g} {x:^12.6g} {fx:^12.6g}")
+
+ iter += 1
+ #################################
+ #END CORE ALGORITHM
+ #################################
+
+ self.xmin = x
+ self.fval = fx
+ self.iter = iter
+ self.funcalls = funcalls
+
+ def get_result(self, full_output=False):
+ if full_output:
+ return self.xmin, self.fval, self.iter, self.funcalls
+ else:
+ return self.xmin
+
+
+def brent(func, args=(), brack=None, tol=1.48e-8, full_output=0, maxiter=500):
+ """
+ Given a function of one variable and a possible bracket, return
+ a local minimizer of the function isolated to a fractional precision
+ of tol.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Objective function.
+ args : tuple, optional
+ Additional arguments (if present).
+ brack : tuple, optional
+ Either a triple ``(xa, xb, xc)`` satisfying ``xa < xb < xc`` and
+ ``func(xb) < func(xa) and func(xb) < func(xc)``, or a pair
+ ``(xa, xb)`` to be used as initial points for a downhill bracket search
+ (see `scipy.optimize.bracket`).
+ The minimizer ``x`` will not necessarily satisfy ``xa <= x <= xb``.
+ tol : float, optional
+ Relative error in solution `xopt` acceptable for convergence.
+ full_output : bool, optional
+ If True, return all output args (xmin, fval, iter,
+ funcalls).
+ maxiter : int, optional
+ Maximum number of iterations in solution.
+
+ Returns
+ -------
+ xmin : ndarray
+ Optimum point.
+ fval : float
+ (Optional output) Optimum function value.
+ iter : int
+ (Optional output) Number of iterations.
+ funcalls : int
+ (Optional output) Number of objective function evaluations made.
+
+ See also
+ --------
+ minimize_scalar: Interface to minimization algorithms for scalar
+ univariate functions. See the 'Brent' `method` in particular.
+
+ Notes
+ -----
+ Uses inverse parabolic interpolation when possible to speed up
+ convergence of golden section method.
+
+ Does not ensure that the minimum lies in the range specified by
+ `brack`. See `scipy.optimize.fminbound`.
+
+ Examples
+ --------
+ We illustrate the behaviour of the function when `brack` is of
+ size 2 and 3 respectively. In the case where `brack` is of the
+ form ``(xa, xb)``, we can see for the given values, the output does
+ not necessarily lie in the range ``(xa, xb)``.
+
+ >>> def f(x):
+ ... return (x-1)**2
+
+ >>> from scipy import optimize
+
+ >>> minimizer = optimize.brent(f, brack=(1, 2))
+ >>> minimizer
+ 1
+ >>> res = optimize.brent(f, brack=(-1, 0.5, 2), full_output=True)
+ >>> xmin, fval, iter, funcalls = res
+ >>> f(xmin), fval
+ (0.0, 0.0)
+
+ """
+ options = {'xtol': tol,
+ 'maxiter': maxiter}
+ res = _minimize_scalar_brent(func, brack, args, **options)
+ if full_output:
+ return res['x'], res['fun'], res['nit'], res['nfev']
+ else:
+ return res['x']
+
+
+def _minimize_scalar_brent(func, brack=None, args=(), xtol=1.48e-8,
+ maxiter=500, disp=0,
+ **unknown_options):
+ """
+ Options
+ -------
+ maxiter : int
+ Maximum number of iterations to perform.
+ xtol : float
+ Relative error in solution `xopt` acceptable for convergence.
+ disp : int, optional
+ If non-zero, print messages.
+
+ ``0`` : no message printing.
+
+ ``1`` : non-convergence notification messages only.
+
+ ``2`` : print a message on convergence too.
+
+ ``3`` : print iteration results.
+
+ Notes
+ -----
+ Uses inverse parabolic interpolation when possible to speed up
+ convergence of golden section method.
+
+ """
+ _check_unknown_options(unknown_options)
+ tol = xtol
+ if tol < 0:
+ raise ValueError(f'tolerance should be >= 0, got {tol!r}')
+
+ brent = Brent(func=func, args=args, tol=tol,
+ full_output=True, maxiter=maxiter, disp=disp)
+ brent.set_bracket(brack)
+ brent.optimize()
+ x, fval, nit, nfev = brent.get_result(full_output=True)
+
+ success = nit < maxiter and not (np.isnan(x) or np.isnan(fval))
+
+ if success:
+ message = ("\nOptimization terminated successfully;\n"
+ "The returned value satisfies the termination criteria\n"
+ f"(using xtol = {xtol} )")
+ else:
+ if nit >= maxiter:
+ message = "\nMaximum number of iterations exceeded"
+ if np.isnan(x) or np.isnan(fval):
+ message = f"{_status_message['nan']}"
+
+ if disp:
+ _print_success_message_or_warn(not success, message)
+
+ return OptimizeResult(fun=fval, x=x, nit=nit, nfev=nfev,
+ success=success, message=message)
+
+
+def golden(func, args=(), brack=None, tol=_epsilon,
+ full_output=0, maxiter=5000):
+ """
+ Return the minimizer of a function of one variable using the golden section
+ method.
+
+ Given a function of one variable and a possible bracketing interval,
+ return a minimizer of the function isolated to a fractional precision of
+ tol.
+
+ Parameters
+ ----------
+ func : callable func(x,*args)
+ Objective function to minimize.
+ args : tuple, optional
+ Additional arguments (if present), passed to func.
+ brack : tuple, optional
+ Either a triple ``(xa, xb, xc)`` where ``xa < xb < xc`` and
+ ``func(xb) < func(xa) and func(xb) < func(xc)``, or a pair (xa, xb)
+ to be used as initial points for a downhill bracket search (see
+ `scipy.optimize.bracket`).
+ The minimizer ``x`` will not necessarily satisfy ``xa <= x <= xb``.
+ tol : float, optional
+ x tolerance stop criterion
+ full_output : bool, optional
+ If True, return optional outputs.
+ maxiter : int
+ Maximum number of iterations to perform.
+
+ Returns
+ -------
+ xmin : ndarray
+ Optimum point.
+ fval : float
+ (Optional output) Optimum function value.
+ funcalls : int
+ (Optional output) Number of objective function evaluations made.
+
+ See also
+ --------
+ minimize_scalar: Interface to minimization algorithms for scalar
+ univariate functions. See the 'Golden' `method` in particular.
+
+ Notes
+ -----
+ Uses analog of bisection method to decrease the bracketed
+ interval.
+
+ Examples
+ --------
+ We illustrate the behaviour of the function when `brack` is of
+ size 2 and 3, respectively. In the case where `brack` is of the
+ form (xa,xb), we can see for the given values, the output need
+ not necessarily lie in the range ``(xa, xb)``.
+
+ >>> def f(x):
+ ... return (x-1)**2
+
+ >>> from scipy import optimize
+
+ >>> minimizer = optimize.golden(f, brack=(1, 2))
+ >>> minimizer
+ 1
+ >>> res = optimize.golden(f, brack=(-1, 0.5, 2), full_output=True)
+ >>> xmin, fval, funcalls = res
+ >>> f(xmin), fval
+ (9.925165290385052e-18, 9.925165290385052e-18)
+
+ """
+ options = {'xtol': tol, 'maxiter': maxiter}
+ res = _minimize_scalar_golden(func, brack, args, **options)
+ if full_output:
+ return res['x'], res['fun'], res['nfev']
+ else:
+ return res['x']
+
+
+def _minimize_scalar_golden(func, brack=None, args=(),
+ xtol=_epsilon, maxiter=5000, disp=0,
+ **unknown_options):
+ """
+ Options
+ -------
+ xtol : float
+ Relative error in solution `xopt` acceptable for convergence.
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp: int, optional
+ If non-zero, print messages.
+
+ ``0`` : no message printing.
+
+ ``1`` : non-convergence notification messages only.
+
+ ``2`` : print a message on convergence too.
+
+ ``3`` : print iteration results.
+ """
+ _check_unknown_options(unknown_options)
+ tol = xtol
+ if brack is None:
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, args=args)
+ elif len(brack) == 2:
+ xa, xb, xc, fa, fb, fc, funcalls = bracket(func, xa=brack[0],
+ xb=brack[1], args=args)
+ elif len(brack) == 3:
+ xa, xb, xc = brack
+ if (xa > xc): # swap so xa < xc can be assumed
+ xc, xa = xa, xc
+ if not ((xa < xb) and (xb < xc)):
+ raise ValueError(
+ "Bracketing values (xa, xb, xc) do not"
+ " fulfill this requirement: (xa < xb) and (xb < xc)"
+ )
+ fa = func(*((xa,) + args))
+ fb = func(*((xb,) + args))
+ fc = func(*((xc,) + args))
+ if not ((fb < fa) and (fb < fc)):
+ raise ValueError(
+ "Bracketing values (xa, xb, xc) do not fulfill"
+ " this requirement: (f(xb) < f(xa)) and (f(xb) < f(xc))"
+ )
+ funcalls = 3
+ else:
+ raise ValueError("Bracketing interval must be length 2 or 3 sequence.")
+
+ _gR = 0.61803399 # golden ratio conjugate: 2.0/(1.0+sqrt(5.0))
+ _gC = 1.0 - _gR
+ x3 = xc
+ x0 = xa
+ if (np.abs(xc - xb) > np.abs(xb - xa)):
+ x1 = xb
+ x2 = xb + _gC * (xc - xb)
+ else:
+ x2 = xb
+ x1 = xb - _gC * (xb - xa)
+ f1 = func(*((x1,) + args))
+ f2 = func(*((x2,) + args))
+ funcalls += 2
+ nit = 0
+
+ if disp > 2:
+ print(" ")
+ print(f"{'Func-count':^12} {'x':^12} {'f(x)': ^12}")
+
+ for i in range(maxiter):
+ if np.abs(x3 - x0) <= tol * (np.abs(x1) + np.abs(x2)):
+ break
+ if (f2 < f1):
+ x0 = x1
+ x1 = x2
+ x2 = _gR * x1 + _gC * x3
+ f1 = f2
+ f2 = func(*((x2,) + args))
+ else:
+ x3 = x2
+ x2 = x1
+ x1 = _gR * x2 + _gC * x0
+ f2 = f1
+ f1 = func(*((x1,) + args))
+ funcalls += 1
+ if disp > 2:
+ if (f1 < f2):
+ xmin, fval = x1, f1
+ else:
+ xmin, fval = x2, f2
+ print(f"{funcalls:^12g} {xmin:^12.6g} {fval:^12.6g}")
+
+ nit += 1
+ # end of iteration loop
+
+ if (f1 < f2):
+ xmin = x1
+ fval = f1
+ else:
+ xmin = x2
+ fval = f2
+
+ success = nit < maxiter and not (np.isnan(fval) or np.isnan(xmin))
+
+ if success:
+ message = ("\nOptimization terminated successfully;\n"
+ "The returned value satisfies the termination criteria\n"
+ f"(using xtol = {xtol} )")
+ else:
+ if nit >= maxiter:
+ message = "\nMaximum number of iterations exceeded"
+ if np.isnan(xmin) or np.isnan(fval):
+ message = f"{_status_message['nan']}"
+
+ if disp:
+ _print_success_message_or_warn(not success, message)
+
+ return OptimizeResult(fun=fval, nfev=funcalls, x=xmin, nit=nit,
+ success=success, message=message)
+
+
+def bracket(func, xa=0.0, xb=1.0, args=(), grow_limit=110.0, maxiter=1000):
+ """
+ Bracket the minimum of a function.
+
+ Given a function and distinct initial points, search in the
+ downhill direction (as defined by the initial points) and return
+ three points that bracket the minimum of the function.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Objective function to minimize.
+ xa, xb : float, optional
+ Initial points. Defaults `xa` to 0.0, and `xb` to 1.0.
+ A local minimum need not be contained within this interval.
+ args : tuple, optional
+ Additional arguments (if present), passed to `func`.
+ grow_limit : float, optional
+ Maximum grow limit. Defaults to 110.0
+ maxiter : int, optional
+ Maximum number of iterations to perform. Defaults to 1000.
+
+ Returns
+ -------
+ xa, xb, xc : float
+ Final points of the bracket.
+ fa, fb, fc : float
+ Objective function values at the bracket points.
+ funcalls : int
+ Number of function evaluations made.
+
+ Raises
+ ------
+ BracketError
+ If no valid bracket is found before the algorithm terminates.
+ See notes for conditions of a valid bracket.
+
+ Notes
+ -----
+ The algorithm attempts to find three strictly ordered points (i.e.
+ :math:`x_a < x_b < x_c` or :math:`x_c < x_b < x_a`) satisfying
+ :math:`f(x_b) ≤ f(x_a)` and :math:`f(x_b) ≤ f(x_c)`, where one of the
+ inequalities must be satisfied strictly and all :math:`x_i` must be
+ finite.
+
+ Examples
+ --------
+ This function can find a downward convex region of a function:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.optimize import bracket
+ >>> def f(x):
+ ... return 10*x**2 + 3*x + 5
+ >>> x = np.linspace(-2, 2)
+ >>> y = f(x)
+ >>> init_xa, init_xb = 0.1, 1
+ >>> xa, xb, xc, fa, fb, fc, funcalls = bracket(f, xa=init_xa, xb=init_xb)
+ >>> plt.axvline(x=init_xa, color="k", linestyle="--")
+ >>> plt.axvline(x=init_xb, color="k", linestyle="--")
+ >>> plt.plot(x, y, "-k")
+ >>> plt.plot(xa, fa, "bx")
+ >>> plt.plot(xb, fb, "rx")
+ >>> plt.plot(xc, fc, "bx")
+ >>> plt.show()
+
+ Note that both initial points were to the right of the minimum, and the
+ third point was found in the "downhill" direction: the direction
+ in which the function appeared to be decreasing (to the left).
+ The final points are strictly ordered, and the function value
+ at the middle point is less than the function values at the endpoints;
+ it follows that a minimum must lie within the bracket.
+
+ """
+ _gold = 1.618034 # golden ratio: (1.0+sqrt(5.0))/2.0
+ _verysmall_num = 1e-21
+ # convert to numpy floats if not already
+ xa, xb = np.asarray([xa, xb])
+ fa = func(*(xa,) + args)
+ fb = func(*(xb,) + args)
+ if (fa < fb): # Switch so fa > fb
+ xa, xb = xb, xa
+ fa, fb = fb, fa
+ xc = xb + _gold * (xb - xa)
+ fc = func(*((xc,) + args))
+ funcalls = 3
+ iter = 0
+ while (fc < fb):
+ tmp1 = (xb - xa) * (fb - fc)
+ tmp2 = (xb - xc) * (fb - fa)
+ val = tmp2 - tmp1
+ if np.abs(val) < _verysmall_num:
+ denom = 2.0 * _verysmall_num
+ else:
+ denom = 2.0 * val
+ w = xb - ((xb - xc) * tmp2 - (xb - xa) * tmp1) / denom
+ wlim = xb + grow_limit * (xc - xb)
+ msg = ("No valid bracket was found before the iteration limit was "
+ "reached. Consider trying different initial points or "
+ "increasing `maxiter`.")
+ if iter > maxiter:
+ raise RuntimeError(msg)
+ iter += 1
+ if (w - xc) * (xb - w) > 0.0:
+ fw = func(*((w,) + args))
+ funcalls += 1
+ if (fw < fc):
+ xa = xb
+ xb = w
+ fa = fb
+ fb = fw
+ break
+ elif (fw > fb):
+ xc = w
+ fc = fw
+ break
+ w = xc + _gold * (xc - xb)
+ fw = func(*((w,) + args))
+ funcalls += 1
+ elif (w - wlim)*(wlim - xc) >= 0.0:
+ w = wlim
+ fw = func(*((w,) + args))
+ funcalls += 1
+ elif (w - wlim)*(xc - w) > 0.0:
+ fw = func(*((w,) + args))
+ funcalls += 1
+ if (fw < fc):
+ xb = xc
+ xc = w
+ w = xc + _gold * (xc - xb)
+ fb = fc
+ fc = fw
+ fw = func(*((w,) + args))
+ funcalls += 1
+ else:
+ w = xc + _gold * (xc - xb)
+ fw = func(*((w,) + args))
+ funcalls += 1
+ xa = xb
+ xb = xc
+ xc = w
+ fa = fb
+ fb = fc
+ fc = fw
+
+ # three conditions for a valid bracket
+ cond1 = (fb < fc and fb <= fa) or (fb < fa and fb <= fc)
+ cond2 = (xa < xb < xc or xc < xb < xa)
+ cond3 = np.isfinite(xa) and np.isfinite(xb) and np.isfinite(xc)
+ msg = ("The algorithm terminated without finding a valid bracket. "
+ "Consider trying different initial points.")
+ if not (cond1 and cond2 and cond3):
+ e = BracketError(msg)
+ e.data = (xa, xb, xc, fa, fb, fc, funcalls)
+ raise e
+
+ return xa, xb, xc, fa, fb, fc, funcalls
+
+
+class BracketError(RuntimeError):
+ pass
+
+
+def _recover_from_bracket_error(solver, fun, bracket, args, **options):
+ # `bracket` was originally written without checking whether the resulting
+ # bracket is valid. `brent` and `golden` built on top of it without
+ # checking the returned bracket for validity, and their output can be
+ # incorrect without warning/error if the original bracket is invalid.
+ # gh-14858 noticed the problem, and the following is the desired
+ # behavior:
+ # - `scipy.optimize.bracket`, `scipy.optimize.brent`, and
+ # `scipy.optimize.golden` should raise an error if the bracket is
+ # invalid, as opposed to silently returning garbage
+ # - `scipy.optimize.minimize_scalar` should return with `success=False`
+ # and other information
+ # The changes that would be required to achieve this the traditional
+ # way (`return`ing all the required information from bracket all the way
+ # up to `minimizer_scalar`) are extensive and invasive. (See a6aa40d.)
+ # We can achieve the same thing by raising the error in `bracket`, but
+ # storing the information needed by `minimize_scalar` in the error object,
+ # and intercepting it here.
+ try:
+ res = solver(fun, bracket, args, **options)
+ except BracketError as e:
+ msg = str(e)
+ xa, xb, xc, fa, fb, fc, funcalls = e.data
+ xs, fs = [xa, xb, xc], [fa, fb, fc]
+ if np.any(np.isnan([xs, fs])):
+ x, fun = np.nan, np.nan
+ else:
+ imin = np.argmin(fs)
+ x, fun = xs[imin], fs[imin]
+ return OptimizeResult(fun=fun, nfev=funcalls, x=x,
+ nit=0, success=False, message=msg)
+ return res
+
+
+def _line_for_search(x0, alpha, lower_bound, upper_bound):
+ """
+ Given a parameter vector ``x0`` with length ``n`` and a direction
+ vector ``alpha`` with length ``n``, and lower and upper bounds on
+ each of the ``n`` parameters, what are the bounds on a scalar
+ ``l`` such that ``lower_bound <= x0 + alpha * l <= upper_bound``.
+
+
+ Parameters
+ ----------
+ x0 : np.array.
+ The vector representing the current location.
+ Note ``np.shape(x0) == (n,)``.
+ alpha : np.array.
+ The vector representing the direction.
+ Note ``np.shape(alpha) == (n,)``.
+ lower_bound : np.array.
+ The lower bounds for each parameter in ``x0``. If the ``i``th
+ parameter in ``x0`` is unbounded below, then ``lower_bound[i]``
+ should be ``-np.inf``.
+ Note ``np.shape(lower_bound) == (n,)``.
+ upper_bound : np.array.
+ The upper bounds for each parameter in ``x0``. If the ``i``th
+ parameter in ``x0`` is unbounded above, then ``upper_bound[i]``
+ should be ``np.inf``.
+ Note ``np.shape(upper_bound) == (n,)``.
+
+ Returns
+ -------
+ res : tuple ``(lmin, lmax)``
+ The bounds for ``l`` such that
+ ``lower_bound[i] <= x0[i] + alpha[i] * l <= upper_bound[i]``
+ for all ``i``.
+
+ """
+ # get nonzero indices of alpha so we don't get any zero division errors.
+ # alpha will not be all zero, since it is called from _linesearch_powell
+ # where we have a check for this.
+ nonzero, = alpha.nonzero()
+ lower_bound, upper_bound = lower_bound[nonzero], upper_bound[nonzero]
+ x0, alpha = x0[nonzero], alpha[nonzero]
+ low = (lower_bound - x0) / alpha
+ high = (upper_bound - x0) / alpha
+
+ # positive and negative indices
+ pos = alpha > 0
+
+ lmin_pos = np.where(pos, low, 0)
+ lmin_neg = np.where(pos, 0, high)
+ lmax_pos = np.where(pos, high, 0)
+ lmax_neg = np.where(pos, 0, low)
+
+ lmin = np.max(lmin_pos + lmin_neg)
+ lmax = np.min(lmax_pos + lmax_neg)
+
+ # if x0 is outside the bounds, then it is possible that there is
+ # no way to get back in the bounds for the parameters being updated
+ # with the current direction alpha.
+ # when this happens, lmax < lmin.
+ # If this is the case, then we can just return (0, 0)
+ return (lmin, lmax) if lmax >= lmin else (0, 0)
+
+
+def _linesearch_powell(func, p, xi, tol=1e-3,
+ lower_bound=None, upper_bound=None, fval=None):
+ """Line-search algorithm using fminbound.
+
+ Find the minimum of the function ``func(x0 + alpha*direc)``.
+
+ lower_bound : np.array.
+ The lower bounds for each parameter in ``x0``. If the ``i``th
+ parameter in ``x0`` is unbounded below, then ``lower_bound[i]``
+ should be ``-np.inf``.
+ Note ``np.shape(lower_bound) == (n,)``.
+ upper_bound : np.array.
+ The upper bounds for each parameter in ``x0``. If the ``i``th
+ parameter in ``x0`` is unbounded above, then ``upper_bound[i]``
+ should be ``np.inf``.
+ Note ``np.shape(upper_bound) == (n,)``.
+ fval : number.
+ ``fval`` is equal to ``func(p)``, the idea is just to avoid
+ recomputing it so we can limit the ``fevals``.
+
+ """
+ def myfunc(alpha):
+ return func(p + alpha*xi)
+
+ # if xi is zero, then don't optimize
+ if not np.any(xi):
+ return ((fval, p, xi) if fval is not None else (func(p), p, xi))
+ elif lower_bound is None and upper_bound is None:
+ # non-bounded minimization
+ res = _recover_from_bracket_error(_minimize_scalar_brent,
+ myfunc, None, tuple(), xtol=tol)
+ alpha_min, fret = res.x, res.fun
+ xi = alpha_min * xi
+ return fret, p + xi, xi
+ else:
+ bound = _line_for_search(p, xi, lower_bound, upper_bound)
+ if np.isneginf(bound[0]) and np.isposinf(bound[1]):
+ # equivalent to unbounded
+ return _linesearch_powell(func, p, xi, fval=fval, tol=tol)
+ elif not np.isneginf(bound[0]) and not np.isposinf(bound[1]):
+ # we can use a bounded scalar minimization
+ res = _minimize_scalar_bounded(myfunc, bound, xatol=tol / 100)
+ xi = res.x * xi
+ return res.fun, p + xi, xi
+ else:
+ # only bounded on one side. use the tangent function to convert
+ # the infinity bound to a finite bound. The new bounded region
+ # is a subregion of the region bounded by -np.pi/2 and np.pi/2.
+ bound = np.arctan(bound[0]), np.arctan(bound[1])
+ res = _minimize_scalar_bounded(
+ lambda x: myfunc(np.tan(x)),
+ bound,
+ xatol=tol / 100)
+ xi = np.tan(res.x) * xi
+ return res.fun, p + xi, xi
+
+
+def fmin_powell(func, x0, args=(), xtol=1e-4, ftol=1e-4, maxiter=None,
+ maxfun=None, full_output=0, disp=1, retall=0, callback=None,
+ direc=None):
+ """
+ Minimize a function using modified Powell's method.
+
+ This method only uses function values, not derivatives.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Objective function to be minimized.
+ x0 : ndarray
+ Initial guess.
+ args : tuple, optional
+ Extra arguments passed to func.
+ xtol : float, optional
+ Line-search error tolerance.
+ ftol : float, optional
+ Relative error in ``func(xopt)`` acceptable for convergence.
+ maxiter : int, optional
+ Maximum number of iterations to perform.
+ maxfun : int, optional
+ Maximum number of function evaluations to make.
+ full_output : bool, optional
+ If True, ``fopt``, ``xi``, ``direc``, ``iter``, ``funcalls``, and
+ ``warnflag`` are returned.
+ disp : bool, optional
+ If True, print convergence messages.
+ retall : bool, optional
+ If True, return a list of the solution at each iteration.
+ callback : callable, optional
+ An optional user-supplied function, called after each
+ iteration. Called as ``callback(xk)``, where ``xk`` is the
+ current parameter vector.
+ direc : ndarray, optional
+ Initial fitting step and parameter order set as an (N, N) array, where N
+ is the number of fitting parameters in `x0`. Defaults to step size 1.0
+ fitting all parameters simultaneously (``np.eye((N, N))``). To
+ prevent initial consideration of values in a step or to change initial
+ step size, set to 0 or desired step size in the Jth position in the Mth
+ block, where J is the position in `x0` and M is the desired evaluation
+ step, with steps being evaluated in index order. Step size and ordering
+ will change freely as minimization proceeds.
+
+ Returns
+ -------
+ xopt : ndarray
+ Parameter which minimizes `func`.
+ fopt : number
+ Value of function at minimum: ``fopt = func(xopt)``.
+ direc : ndarray
+ Current direction set.
+ iter : int
+ Number of iterations.
+ funcalls : int
+ Number of function calls made.
+ warnflag : int
+ Integer warning flag:
+ 1 : Maximum number of function evaluations.
+ 2 : Maximum number of iterations.
+ 3 : NaN result encountered.
+ 4 : The result is out of the provided bounds.
+ allvecs : list
+ List of solutions at each iteration.
+
+ See also
+ --------
+ minimize: Interface to unconstrained minimization algorithms for
+ multivariate functions. See the 'Powell' method in particular.
+
+ Notes
+ -----
+ Uses a modification of Powell's method to find the minimum of
+ a function of N variables. Powell's method is a conjugate
+ direction method.
+
+ The algorithm has two loops. The outer loop merely iterates over the inner
+ loop. The inner loop minimizes over each current direction in the direction
+ set. At the end of the inner loop, if certain conditions are met, the
+ direction that gave the largest decrease is dropped and replaced with the
+ difference between the current estimated x and the estimated x from the
+ beginning of the inner-loop.
+
+ The technical conditions for replacing the direction of greatest
+ increase amount to checking that
+
+ 1. No further gain can be made along the direction of greatest increase
+ from that iteration.
+ 2. The direction of greatest increase accounted for a large sufficient
+ fraction of the decrease in the function value from that iteration of
+ the inner loop.
+
+ References
+ ----------
+ Powell M.J.D. (1964) An efficient method for finding the minimum of a
+ function of several variables without calculating derivatives,
+ Computer Journal, 7 (2):155-162.
+
+ Press W., Teukolsky S.A., Vetterling W.T., and Flannery B.P.:
+ Numerical Recipes (any edition), Cambridge University Press
+
+ Examples
+ --------
+ >>> def f(x):
+ ... return x**2
+
+ >>> from scipy import optimize
+
+ >>> minimum = optimize.fmin_powell(f, -1)
+ Optimization terminated successfully.
+ Current function value: 0.000000
+ Iterations: 2
+ Function evaluations: 16
+ >>> minimum
+ array(0.0)
+
+ """
+ opts = {'xtol': xtol,
+ 'ftol': ftol,
+ 'maxiter': maxiter,
+ 'maxfev': maxfun,
+ 'disp': disp,
+ 'direc': direc,
+ 'return_all': retall}
+
+ callback = _wrap_callback(callback)
+ res = _minimize_powell(func, x0, args, callback=callback, **opts)
+
+ if full_output:
+ retlist = (res['x'], res['fun'], res['direc'], res['nit'],
+ res['nfev'], res['status'])
+ if retall:
+ retlist += (res['allvecs'], )
+ return retlist
+ else:
+ if retall:
+ return res['x'], res['allvecs']
+ else:
+ return res['x']
+
+
+def _minimize_powell(func, x0, args=(), callback=None, bounds=None,
+ xtol=1e-4, ftol=1e-4, maxiter=None, maxfev=None,
+ disp=False, direc=None, return_all=False,
+ **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using the
+ modified Powell algorithm.
+
+ Parameters
+ ----------
+ fun : callable
+ The objective function to be minimized::
+
+ fun(x, *args) -> float
+
+ where ``x`` is a 1-D array with shape (n,) and ``args``
+ is a tuple of the fixed parameters needed to completely
+ specify the function.
+ x0 : ndarray, shape (n,)
+ Initial guess. Array of real elements of size (n,),
+ where ``n`` is the number of independent variables.
+ args : tuple, optional
+ Extra arguments passed to the objective function and its
+ derivatives (`fun`, `jac` and `hess` functions).
+ method : str or callable, optional
+ The present documentation is specific to ``method='powell'``, but other
+ options are available. See documentation for `scipy.optimize.minimize`.
+ bounds : sequence or `Bounds`, optional
+ Bounds on decision variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. Sequence of ``(min, max)`` pairs for each element in `x`. None
+ is used to specify no bound.
+
+ If bounds are not provided, then an unbounded line search will be used.
+ If bounds are provided and the initial guess is within the bounds, then
+ every function evaluation throughout the minimization procedure will be
+ within the bounds. If bounds are provided, the initial guess is outside
+ the bounds, and `direc` is full rank (or left to default), then some
+ function evaluations during the first iteration may be outside the
+ bounds, but every function evaluation after the first iteration will be
+ within the bounds. If `direc` is not full rank, then some parameters
+ may not be optimized and the solution is not guaranteed to be within
+ the bounds.
+
+ options : dict, optional
+ A dictionary of solver options. All methods accept the following
+ generic options:
+
+ maxiter : int
+ Maximum number of iterations to perform. Depending on the
+ method each iteration may use several function evaluations.
+ disp : bool
+ Set to True to print convergence messages.
+
+ See method-specific options for ``method='powell'`` below.
+ callback : callable, optional
+ Called after each iteration. The signature is::
+
+ callback(xk)
+
+ where ``xk`` is the current parameter vector.
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a ``OptimizeResult`` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the optimizer exited successfully and
+ ``message`` which describes the cause of the termination. See
+ `OptimizeResult` for a description of other attributes.
+
+ Options
+ -------
+ disp : bool
+ Set to True to print convergence messages.
+ xtol : float
+ Relative error in solution `xopt` acceptable for convergence.
+ ftol : float
+ Relative error in ``fun(xopt)`` acceptable for convergence.
+ maxiter, maxfev : int
+ Maximum allowed number of iterations and function evaluations.
+ Will default to ``N*1000``, where ``N`` is the number of
+ variables, if neither `maxiter` or `maxfev` is set. If both
+ `maxiter` and `maxfev` are set, minimization will stop at the
+ first reached.
+ direc : ndarray
+ Initial set of direction vectors for the Powell method.
+ return_all : bool, optional
+ Set to True to return a list of the best solution at each of the
+ iterations.
+ """
+ _check_unknown_options(unknown_options)
+ maxfun = maxfev
+ retall = return_all
+
+ x = asarray(x0).flatten()
+ if retall:
+ allvecs = [x]
+ N = len(x)
+ # If neither are set, then set both to default
+ if maxiter is None and maxfun is None:
+ maxiter = N * 1000
+ maxfun = N * 1000
+ elif maxiter is None:
+ # Convert remaining Nones, to np.inf, unless the other is np.inf, in
+ # which case use the default to avoid unbounded iteration
+ if maxfun == np.inf:
+ maxiter = N * 1000
+ else:
+ maxiter = np.inf
+ elif maxfun is None:
+ if maxiter == np.inf:
+ maxfun = N * 1000
+ else:
+ maxfun = np.inf
+
+ # we need to use a mutable object here that we can update in the
+ # wrapper function
+ fcalls, func = _wrap_scalar_function_maxfun_validation(func, args, maxfun)
+
+ if direc is None:
+ direc = eye(N, dtype=float)
+ else:
+ direc = asarray(direc, dtype=float)
+ if np.linalg.matrix_rank(direc) != direc.shape[0]:
+ warnings.warn("direc input is not full rank, some parameters may "
+ "not be optimized",
+ OptimizeWarning, stacklevel=3)
+
+ if bounds is None:
+ # don't make these arrays of all +/- inf. because
+ # _linesearch_powell will do an unnecessary check of all the elements.
+ # just keep them None, _linesearch_powell will not have to check
+ # all the elements.
+ lower_bound, upper_bound = None, None
+ else:
+ # bounds is standardized in _minimize.py.
+ lower_bound, upper_bound = bounds.lb, bounds.ub
+ if np.any(lower_bound > x0) or np.any(x0 > upper_bound):
+ warnings.warn("Initial guess is not within the specified bounds",
+ OptimizeWarning, stacklevel=3)
+
+ fval = func(x)
+ x1 = x.copy()
+ iter = 0
+ while True:
+ try:
+ fx = fval
+ bigind = 0
+ delta = 0.0
+ for i in range(N):
+ direc1 = direc[i]
+ fx2 = fval
+ fval, x, direc1 = _linesearch_powell(func, x, direc1,
+ tol=xtol * 100,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ if (fx2 - fval) > delta:
+ delta = fx2 - fval
+ bigind = i
+ iter += 1
+ if retall:
+ allvecs.append(x)
+ intermediate_result = OptimizeResult(x=x, fun=fval)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+ bnd = ftol * (np.abs(fx) + np.abs(fval)) + 1e-20
+ if 2.0 * (fx - fval) <= bnd:
+ break
+ if fcalls[0] >= maxfun:
+ break
+ if iter >= maxiter:
+ break
+ if np.isnan(fx) and np.isnan(fval):
+ # Ended up in a nan-region: bail out
+ break
+
+ # Construct the extrapolated point
+ direc1 = x - x1
+ x1 = x.copy()
+ # make sure that we don't go outside the bounds when extrapolating
+ if lower_bound is None and upper_bound is None:
+ lmax = 1
+ else:
+ _, lmax = _line_for_search(x, direc1, lower_bound, upper_bound)
+ x2 = x + min(lmax, 1) * direc1
+ fx2 = func(x2)
+
+ if (fx > fx2):
+ t = 2.0*(fx + fx2 - 2.0*fval)
+ temp = (fx - fval - delta)
+ t *= temp*temp
+ temp = fx - fx2
+ t -= delta*temp*temp
+ if t < 0.0:
+ fval, x, direc1 = _linesearch_powell(
+ func, x, direc1,
+ tol=xtol * 100,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval
+ )
+ if np.any(direc1):
+ direc[bigind] = direc[-1]
+ direc[-1] = direc1
+ except _MaxFuncCallError:
+ break
+
+ warnflag = 0
+ msg = _status_message['success']
+ # out of bounds is more urgent than exceeding function evals or iters,
+ # but I don't want to cause inconsistencies by changing the
+ # established warning flags for maxfev and maxiter, so the out of bounds
+ # warning flag becomes 3, but is checked for first.
+ if bounds and (np.any(lower_bound > x) or np.any(x > upper_bound)):
+ warnflag = 4
+ msg = _status_message['out_of_bounds']
+ elif fcalls[0] >= maxfun:
+ warnflag = 1
+ msg = _status_message['maxfev']
+ elif iter >= maxiter:
+ warnflag = 2
+ msg = _status_message['maxiter']
+ elif np.isnan(fval) or np.isnan(x).any():
+ warnflag = 3
+ msg = _status_message['nan']
+
+ if disp:
+ _print_success_message_or_warn(warnflag, msg, RuntimeWarning)
+ print(f" Current function value: {fval:f}")
+ print(f" Iterations: {iter:d}")
+ print(f" Function evaluations: {fcalls[0]:d}")
+ result = OptimizeResult(fun=fval, direc=direc, nit=iter, nfev=fcalls[0],
+ status=warnflag, success=(warnflag == 0),
+ message=msg, x=x)
+ if retall:
+ result['allvecs'] = allvecs
+ return result
+
+
+def _endprint(x, flag, fval, maxfun, xtol, disp):
+ if flag == 0:
+ if disp > 1:
+ print("\nOptimization terminated successfully;\n"
+ "The returned value satisfies the termination criteria\n"
+ "(using xtol = ", xtol, ")")
+ return
+
+ if flag == 1:
+ msg = ("\nMaximum number of function evaluations exceeded --- "
+ "increase maxfun argument.\n")
+ elif flag == 2:
+ msg = f"\n{_status_message['nan']}"
+
+ _print_success_message_or_warn(flag, msg)
+ return
+
+
+def brute(func, ranges, args=(), Ns=20, full_output=0, finish=fmin,
+ disp=False, workers=1):
+ """Minimize a function over a given range by brute force.
+
+ Uses the "brute force" method, i.e., computes the function's value
+ at each point of a multidimensional grid of points, to find the global
+ minimum of the function.
+
+ The function is evaluated everywhere in the range with the datatype of the
+ first call to the function, as enforced by the ``vectorize`` NumPy
+ function. The value and type of the function evaluation returned when
+ ``full_output=True`` are affected in addition by the ``finish`` argument
+ (see Notes).
+
+ The brute force approach is inefficient because the number of grid points
+ increases exponentially - the number of grid points to evaluate is
+ ``Ns ** len(x)``. Consequently, even with coarse grid spacing, even
+ moderately sized problems can take a long time to run, and/or run into
+ memory limitations.
+
+ Parameters
+ ----------
+ func : callable
+ The objective function to be minimized. Must be in the
+ form ``f(x, *args)``, where ``x`` is the argument in
+ the form of a 1-D array and ``args`` is a tuple of any
+ additional fixed parameters needed to completely specify
+ the function.
+ ranges : tuple
+ Each component of the `ranges` tuple must be either a
+ "slice object" or a range tuple of the form ``(low, high)``.
+ The program uses these to create the grid of points on which
+ the objective function will be computed. See `Note 2` for
+ more detail.
+ args : tuple, optional
+ Any additional fixed parameters needed to completely specify
+ the function.
+ Ns : int, optional
+ Number of grid points along the axes, if not otherwise
+ specified. See `Note2`.
+ full_output : bool, optional
+ If True, return the evaluation grid and the objective function's
+ values on it.
+ finish : callable, optional
+ An optimization function that is called with the result of brute force
+ minimization as initial guess. `finish` should take `func` and
+ the initial guess as positional arguments, and take `args` as
+ keyword arguments. It may additionally take `full_output`
+ and/or `disp` as keyword arguments. Use None if no "polishing"
+ function is to be used. See Notes for more details.
+ disp : bool, optional
+ Set to True to print convergence messages from the `finish` callable.
+ workers : int or map-like callable, optional
+ If `workers` is an int the grid is subdivided into `workers`
+ sections and evaluated in parallel (uses
+ `multiprocessing.Pool `).
+ Supply `-1` to use all cores available to the Process.
+ Alternatively supply a map-like callable, such as
+ `multiprocessing.Pool.map` for evaluating the grid in parallel.
+ This evaluation is carried out as ``workers(func, iterable)``.
+ Requires that `func` be pickleable.
+
+ .. versionadded:: 1.3.0
+
+ Returns
+ -------
+ x0 : ndarray
+ A 1-D array containing the coordinates of a point at which the
+ objective function had its minimum value. (See `Note 1` for
+ which point is returned.)
+ fval : float
+ Function value at the point `x0`. (Returned when `full_output` is
+ True.)
+ grid : tuple
+ Representation of the evaluation grid. It has the same
+ length as `x0`. (Returned when `full_output` is True.)
+ Jout : ndarray
+ Function values at each point of the evaluation
+ grid, i.e., ``Jout = func(*grid)``. (Returned
+ when `full_output` is True.)
+
+ See Also
+ --------
+ basinhopping, differential_evolution
+
+ Notes
+ -----
+ *Note 1*: The program finds the gridpoint at which the lowest value
+ of the objective function occurs. If `finish` is None, that is the
+ point returned. When the global minimum occurs within (or not very far
+ outside) the grid's boundaries, and the grid is fine enough, that
+ point will be in the neighborhood of the global minimum.
+
+ However, users often employ some other optimization program to
+ "polish" the gridpoint values, i.e., to seek a more precise
+ (local) minimum near `brute's` best gridpoint.
+ The `brute` function's `finish` option provides a convenient way to do
+ that. Any polishing program used must take `brute's` output as its
+ initial guess as a positional argument, and take `brute's` input values
+ for `args` as keyword arguments, otherwise an error will be raised.
+ It may additionally take `full_output` and/or `disp` as keyword arguments.
+
+ `brute` assumes that the `finish` function returns either an
+ `OptimizeResult` object or a tuple in the form:
+ ``(xmin, Jmin, ... , statuscode)``, where ``xmin`` is the minimizing
+ value of the argument, ``Jmin`` is the minimum value of the objective
+ function, "..." may be some other returned values (which are not used
+ by `brute`), and ``statuscode`` is the status code of the `finish` program.
+
+ Note that when `finish` is not None, the values returned are those
+ of the `finish` program, *not* the gridpoint ones. Consequently,
+ while `brute` confines its search to the input grid points,
+ the `finish` program's results usually will not coincide with any
+ gridpoint, and may fall outside the grid's boundary. Thus, if a
+ minimum only needs to be found over the provided grid points, make
+ sure to pass in ``finish=None``.
+
+ *Note 2*: The grid of points is a `numpy.mgrid` object.
+ For `brute` the `ranges` and `Ns` inputs have the following effect.
+ Each component of the `ranges` tuple can be either a slice object or a
+ two-tuple giving a range of values, such as (0, 5). If the component is a
+ slice object, `brute` uses it directly. If the component is a two-tuple
+ range, `brute` internally converts it to a slice object that interpolates
+ `Ns` points from its low-value to its high-value, inclusive.
+
+ Examples
+ --------
+ We illustrate the use of `brute` to seek the global minimum of a function
+ of two variables that is given as the sum of a positive-definite
+ quadratic and two deep "Gaussian-shaped" craters. Specifically, define
+ the objective function `f` as the sum of three other functions,
+ ``f = f1 + f2 + f3``. We suppose each of these has a signature
+ ``(z, *params)``, where ``z = (x, y)``, and ``params`` and the functions
+ are as defined below.
+
+ >>> import numpy as np
+ >>> params = (2, 3, 7, 8, 9, 10, 44, -1, 2, 26, 1, -2, 0.5)
+ >>> def f1(z, *params):
+ ... x, y = z
+ ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ ... return (a * x**2 + b * x * y + c * y**2 + d*x + e*y + f)
+
+ >>> def f2(z, *params):
+ ... x, y = z
+ ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ ... return (-g*np.exp(-((x-h)**2 + (y-i)**2) / scale))
+
+ >>> def f3(z, *params):
+ ... x, y = z
+ ... a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ ... return (-j*np.exp(-((x-k)**2 + (y-l)**2) / scale))
+
+ >>> def f(z, *params):
+ ... return f1(z, *params) + f2(z, *params) + f3(z, *params)
+
+ Thus, the objective function may have local minima near the minimum
+ of each of the three functions of which it is composed. To
+ use `fmin` to polish its gridpoint result, we may then continue as
+ follows:
+
+ >>> rranges = (slice(-4, 4, 0.25), slice(-4, 4, 0.25))
+ >>> from scipy import optimize
+ >>> resbrute = optimize.brute(f, rranges, args=params, full_output=True,
+ ... finish=optimize.fmin)
+ >>> resbrute[0] # global minimum
+ array([-1.05665192, 1.80834843])
+ >>> resbrute[1] # function value at global minimum
+ -3.4085818767
+
+ Note that if `finish` had been set to None, we would have gotten the
+ gridpoint [-1.0 1.75] where the rounded function value is -2.892.
+
+ """
+ N = len(ranges)
+ if N > 40:
+ raise ValueError("Brute Force not possible with more "
+ "than 40 variables.")
+ lrange = list(ranges)
+ for k in range(N):
+ if not isinstance(lrange[k], slice):
+ if len(lrange[k]) < 3:
+ lrange[k] = tuple(lrange[k]) + (complex(Ns),)
+ lrange[k] = slice(*lrange[k])
+ if (N == 1):
+ lrange = lrange[0]
+
+ grid = np.mgrid[lrange]
+
+ # obtain an array of parameters that is iterable by a map-like callable
+ inpt_shape = grid.shape
+ if (N > 1):
+ grid = np.reshape(grid, (inpt_shape[0], np.prod(inpt_shape[1:]))).T
+
+ if not np.iterable(args):
+ args = (args,)
+
+ wrapped_func = _Brute_Wrapper(func, args)
+
+ # iterate over input arrays, possibly in parallel
+ with MapWrapper(pool=workers) as mapper:
+ Jout = np.array(list(mapper(wrapped_func, grid)))
+ if (N == 1):
+ grid = (grid,)
+ Jout = np.squeeze(Jout)
+ elif (N > 1):
+ Jout = np.reshape(Jout, inpt_shape[1:])
+ grid = np.reshape(grid.T, inpt_shape)
+
+ Nshape = shape(Jout)
+
+ indx = argmin(Jout.ravel(), axis=-1)
+ Nindx = np.empty(N, int)
+ xmin = np.empty(N, float)
+ for k in range(N - 1, -1, -1):
+ thisN = Nshape[k]
+ Nindx[k] = indx % Nshape[k]
+ indx = indx // thisN
+ for k in range(N):
+ xmin[k] = grid[k][tuple(Nindx)]
+
+ Jmin = Jout[tuple(Nindx)]
+ if (N == 1):
+ grid = grid[0]
+ xmin = xmin[0]
+
+ if callable(finish):
+ # set up kwargs for `finish` function
+ finish_args = _getfullargspec(finish).args
+ finish_kwargs = dict()
+ if 'full_output' in finish_args:
+ finish_kwargs['full_output'] = 1
+ if 'disp' in finish_args:
+ finish_kwargs['disp'] = disp
+ elif 'options' in finish_args:
+ # pass 'disp' as `options`
+ # (e.g., if `finish` is `minimize`)
+ finish_kwargs['options'] = {'disp': disp}
+
+ # run minimizer
+ res = finish(func, xmin, args=args, **finish_kwargs)
+
+ if isinstance(res, OptimizeResult):
+ xmin = res.x
+ Jmin = res.fun
+ success = res.success
+ else:
+ xmin = res[0]
+ Jmin = res[1]
+ success = res[-1] == 0
+ if not success:
+ if disp:
+ warnings.warn("Either final optimization did not succeed or `finish` "
+ "does not return `statuscode` as its last argument.",
+ RuntimeWarning, stacklevel=2)
+
+ if full_output:
+ return xmin, Jmin, grid, Jout
+ else:
+ return xmin
+
+
+class _Brute_Wrapper:
+ """
+ Object to wrap user cost function for optimize.brute, allowing picklability
+ """
+
+ def __init__(self, f, args):
+ self.f = f
+ self.args = [] if args is None else args
+
+ def __call__(self, x):
+ # flatten needed for one dimensional case.
+ return self.f(np.asarray(x).flatten(), *self.args)
+
+
+def show_options(solver=None, method=None, disp=True):
+ """
+ Show documentation for additional options of optimization solvers.
+
+ These are method-specific options that can be supplied through the
+ ``options`` dict.
+
+ Parameters
+ ----------
+ solver : str
+ Type of optimization solver. One of 'minimize', 'minimize_scalar',
+ 'root', 'root_scalar', 'linprog', or 'quadratic_assignment'.
+ method : str, optional
+ If not given, shows all methods of the specified solver. Otherwise,
+ show only the options for the specified method. Valid values
+ corresponds to methods' names of respective solver (e.g., 'BFGS' for
+ 'minimize').
+ disp : bool, optional
+ Whether to print the result rather than returning it.
+
+ Returns
+ -------
+ text
+ Either None (for disp=True) or the text string (disp=False)
+
+ Notes
+ -----
+ The solver-specific methods are:
+
+ `scipy.optimize.minimize`
+
+ - :ref:`Nelder-Mead `
+ - :ref:`Powell `
+ - :ref:`CG `
+ - :ref:`BFGS `
+ - :ref:`Newton-CG `
+ - :ref:`L-BFGS-B `
+ - :ref:`TNC `
+ - :ref:`COBYLA `
+ - :ref:`COBYQA `
+ - :ref:`SLSQP `
+ - :ref:`dogleg `
+ - :ref:`trust-ncg `
+
+ `scipy.optimize.root`
+
+ - :ref:`hybr `
+ - :ref:`lm `
+ - :ref:`broyden1 `
+ - :ref:`broyden2 `
+ - :ref:`anderson `
+ - :ref:`linearmixing `
+ - :ref:`diagbroyden `
+ - :ref:`excitingmixing `
+ - :ref:`krylov `
+ - :ref:`df-sane `
+
+ `scipy.optimize.minimize_scalar`
+
+ - :ref:`brent `
+ - :ref:`golden `
+ - :ref:`bounded `
+
+ `scipy.optimize.root_scalar`
+
+ - :ref:`bisect `
+ - :ref:`brentq `
+ - :ref:`brenth `
+ - :ref:`ridder `
+ - :ref:`toms748 `
+ - :ref:`newton `
+ - :ref:`secant `
+ - :ref:`halley `
+
+ `scipy.optimize.linprog`
+
+ - :ref:`simplex `
+ - :ref:`interior-point `
+ - :ref:`revised simplex `
+ - :ref:`highs `
+ - :ref:`highs-ds `
+ - :ref:`highs-ipm `
+
+ `scipy.optimize.quadratic_assignment`
+
+ - :ref:`faq `
+ - :ref:`2opt `
+
+ Examples
+ --------
+ We can print documentations of a solver in stdout:
+
+ >>> from scipy.optimize import show_options
+ >>> show_options(solver="minimize")
+ ...
+
+ Specifying a method is possible:
+
+ >>> show_options(solver="minimize", method="Nelder-Mead")
+ ...
+
+ We can also get the documentations as a string:
+
+ >>> show_options(solver="minimize", method="Nelder-Mead", disp=False)
+ Minimization of scalar function of one or more variables using the ...
+
+ """
+ import textwrap
+
+ doc_routines = {
+ 'minimize': (
+ ('bfgs', 'scipy.optimize._optimize._minimize_bfgs'),
+ ('cg', 'scipy.optimize._optimize._minimize_cg'),
+ ('cobyla', 'scipy.optimize._cobyla_py._minimize_cobyla'),
+ ('cobyqa', 'scipy.optimize._cobyqa_py._minimize_cobyqa'),
+ ('dogleg', 'scipy.optimize._trustregion_dogleg._minimize_dogleg'),
+ ('l-bfgs-b', 'scipy.optimize._lbfgsb_py._minimize_lbfgsb'),
+ ('nelder-mead', 'scipy.optimize._optimize._minimize_neldermead'),
+ ('newton-cg', 'scipy.optimize._optimize._minimize_newtoncg'),
+ ('powell', 'scipy.optimize._optimize._minimize_powell'),
+ ('slsqp', 'scipy.optimize._slsqp_py._minimize_slsqp'),
+ ('tnc', 'scipy.optimize._tnc._minimize_tnc'),
+ ('trust-ncg',
+ 'scipy.optimize._trustregion_ncg._minimize_trust_ncg'),
+ ('trust-constr',
+ 'scipy.optimize._trustregion_constr.'
+ '_minimize_trustregion_constr'),
+ ('trust-exact',
+ 'scipy.optimize._trustregion_exact._minimize_trustregion_exact'),
+ ('trust-krylov',
+ 'scipy.optimize._trustregion_krylov._minimize_trust_krylov'),
+ ),
+ 'root': (
+ ('hybr', 'scipy.optimize._minpack_py._root_hybr'),
+ ('lm', 'scipy.optimize._root._root_leastsq'),
+ ('broyden1', 'scipy.optimize._root._root_broyden1_doc'),
+ ('broyden2', 'scipy.optimize._root._root_broyden2_doc'),
+ ('anderson', 'scipy.optimize._root._root_anderson_doc'),
+ ('diagbroyden', 'scipy.optimize._root._root_diagbroyden_doc'),
+ ('excitingmixing', 'scipy.optimize._root._root_excitingmixing_doc'),
+ ('linearmixing', 'scipy.optimize._root._root_linearmixing_doc'),
+ ('krylov', 'scipy.optimize._root._root_krylov_doc'),
+ ('df-sane', 'scipy.optimize._spectral._root_df_sane'),
+ ),
+ 'root_scalar': (
+ ('bisect', 'scipy.optimize._root_scalar._root_scalar_bisect_doc'),
+ ('brentq', 'scipy.optimize._root_scalar._root_scalar_brentq_doc'),
+ ('brenth', 'scipy.optimize._root_scalar._root_scalar_brenth_doc'),
+ ('ridder', 'scipy.optimize._root_scalar._root_scalar_ridder_doc'),
+ ('toms748', 'scipy.optimize._root_scalar._root_scalar_toms748_doc'),
+ ('secant', 'scipy.optimize._root_scalar._root_scalar_secant_doc'),
+ ('newton', 'scipy.optimize._root_scalar._root_scalar_newton_doc'),
+ ('halley', 'scipy.optimize._root_scalar._root_scalar_halley_doc'),
+ ),
+ 'linprog': (
+ ('simplex', 'scipy.optimize._linprog._linprog_simplex_doc'),
+ ('interior-point', 'scipy.optimize._linprog._linprog_ip_doc'),
+ ('revised simplex', 'scipy.optimize._linprog._linprog_rs_doc'),
+ ('highs-ipm', 'scipy.optimize._linprog._linprog_highs_ipm_doc'),
+ ('highs-ds', 'scipy.optimize._linprog._linprog_highs_ds_doc'),
+ ('highs', 'scipy.optimize._linprog._linprog_highs_doc'),
+ ),
+ 'quadratic_assignment': (
+ ('faq', 'scipy.optimize._qap._quadratic_assignment_faq'),
+ ('2opt', 'scipy.optimize._qap._quadratic_assignment_2opt'),
+ ),
+ 'minimize_scalar': (
+ ('brent', 'scipy.optimize._optimize._minimize_scalar_brent'),
+ ('bounded', 'scipy.optimize._optimize._minimize_scalar_bounded'),
+ ('golden', 'scipy.optimize._optimize._minimize_scalar_golden'),
+ ),
+ }
+
+ if solver is None:
+ text = ["\n\n\n========\n", "minimize\n", "========\n"]
+ text.append(show_options('minimize', disp=False))
+ text.extend(["\n\n===============\n", "minimize_scalar\n",
+ "===============\n"])
+ text.append(show_options('minimize_scalar', disp=False))
+ text.extend(["\n\n\n====\n", "root\n",
+ "====\n"])
+ text.append(show_options('root', disp=False))
+ text.extend(['\n\n\n=======\n', 'linprog\n',
+ '=======\n'])
+ text.append(show_options('linprog', disp=False))
+ text = "".join(text)
+ else:
+ solver = solver.lower()
+ if solver not in doc_routines:
+ raise ValueError(f'Unknown solver {solver!r}')
+
+ if method is None:
+ text = []
+ for name, _ in doc_routines[solver]:
+ text.extend(["\n\n" + name, "\n" + "="*len(name) + "\n\n"])
+ text.append(show_options(solver, name, disp=False))
+ text = "".join(text)
+ else:
+ method = method.lower()
+ methods = dict(doc_routines[solver])
+ if method not in methods:
+ raise ValueError(f"Unknown method {method!r}")
+ name = methods[method]
+
+ # Import function object
+ parts = name.split('.')
+ mod_name = ".".join(parts[:-1])
+ __import__(mod_name)
+ obj = getattr(sys.modules[mod_name], parts[-1])
+
+ # Get doc
+ doc = obj.__doc__
+ if doc is not None:
+ text = textwrap.dedent(doc).strip()
+ else:
+ text = ""
+
+ if disp:
+ print(text)
+ return
+ else:
+ return text
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..2c8b3d413d67474d4032ca7ec68677f4396c067d
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_pava_pybind.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d88ee2035267e832646c86d7aa1e31a8863f22be16ae5da27973435ee68fae61
+size 226224
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_qap.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_qap.py
new file mode 100644
index 0000000000000000000000000000000000000000..03fe3b128c066adb21406021ec2e34effbf65703
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_qap.py
@@ -0,0 +1,760 @@
+import numpy as np
+import operator
+import warnings
+import numbers
+from . import (linear_sum_assignment, OptimizeResult)
+from ._optimize import _check_unknown_options
+
+from scipy._lib._util import check_random_state
+import itertools
+
+QUADRATIC_ASSIGNMENT_METHODS = ['faq', '2opt']
+
+
+def quadratic_assignment(A, B, method="faq", options=None):
+ r"""
+ Approximates solution to the quadratic assignment problem and
+ the graph matching problem.
+
+ Quadratic assignment solves problems of the following form:
+
+ .. math::
+
+ \min_P & \ {\ \text{trace}(A^T P B P^T)}\\
+ \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\
+
+ where :math:`\mathcal{P}` is the set of all permutation matrices,
+ and :math:`A` and :math:`B` are square matrices.
+
+ Graph matching tries to *maximize* the same objective function.
+ This algorithm can be thought of as finding the alignment of the
+ nodes of two graphs that minimizes the number of induced edge
+ disagreements, or, in the case of weighted graphs, the sum of squared
+ edge weight differences.
+
+ Note that the quadratic assignment problem is NP-hard. The results given
+ here are approximations and are not guaranteed to be optimal.
+
+
+ Parameters
+ ----------
+ A : 2-D array, square
+ The square matrix :math:`A` in the objective function above.
+
+ B : 2-D array, square
+ The square matrix :math:`B` in the objective function above.
+
+ method : str in {'faq', '2opt'} (default: 'faq')
+ The algorithm used to solve the problem.
+ :ref:`'faq' ` (default) and
+ :ref:`'2opt' ` are available.
+
+ options : dict, optional
+ A dictionary of solver options. All solvers support the following:
+
+ maximize : bool (default: False)
+ Maximizes the objective function if ``True``.
+
+ partial_match : 2-D array of integers, optional (default: None)
+ Fixes part of the matching. Also known as a "seed" [2]_.
+
+ Each row of `partial_match` specifies a pair of matched nodes:
+ node ``partial_match[i, 0]`` of `A` is matched to node
+ ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``,
+ where ``m`` is not greater than the number of nodes, :math:`n`.
+
+ rng : `numpy.random.Generator`, optional
+ Pseudorandom number generator state. When `rng` is None, a new
+ `numpy.random.Generator` is created using entropy from the
+ operating system. Types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+ .. versionchanged:: 1.15.0
+ As part of the `SPEC-007 `_
+ transition from use of `numpy.random.RandomState` to
+ `numpy.random.Generator` is occurring. Supplying
+ `np.random.RandomState` to this function will now emit a
+ `DeprecationWarning`. In SciPy 1.17 its use will raise an exception.
+ In addition relying on global state using `np.random.seed`
+ will emit a `FutureWarning`. In SciPy 1.17 the global random number
+ generator will no longer be used.
+ Use of an int-like seed will raise a `FutureWarning`, in SciPy 1.17 it
+ will be normalized via `np.random.default_rng` rather than
+ `np.random.RandomState`.
+
+ For method-specific options, see
+ :func:`show_options('quadratic_assignment') `.
+
+ Returns
+ -------
+ res : OptimizeResult
+ `OptimizeResult` containing the following fields.
+
+ col_ind : 1-D array
+ Column indices corresponding to the best permutation found of the
+ nodes of `B`.
+ fun : float
+ The objective value of the solution.
+ nit : int
+ The number of iterations performed during optimization.
+
+ Notes
+ -----
+ The default method :ref:`'faq' ` uses the Fast
+ Approximate QAP algorithm [1]_; it typically offers the best combination of
+ speed and accuracy.
+ Method :ref:`'2opt' ` can be computationally expensive,
+ but may be a useful alternative, or it can be used to refine the solution
+ returned by another method.
+
+ References
+ ----------
+ .. [1] J.T. Vogelstein, J.M. Conroy, V. Lyzinski, L.J. Podrazik,
+ S.G. Kratzer, E.T. Harley, D.E. Fishkind, R.J. Vogelstein, and
+ C.E. Priebe, "Fast approximate quadratic programming for graph
+ matching," PLOS one, vol. 10, no. 4, p. e0121002, 2015,
+ :doi:`10.1371/journal.pone.0121002`
+
+ .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski,
+ C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019):
+ 203-215, :doi:`10.1016/j.patcog.2018.09.014`
+
+ .. [3] "2-opt," Wikipedia.
+ https://en.wikipedia.org/wiki/2-opt
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.optimize import quadratic_assignment
+ >>> rng = np.random.default_rng()
+ >>> A = np.array([[0, 80, 150, 170], [80, 0, 130, 100],
+ ... [150, 130, 0, 120], [170, 100, 120, 0]])
+ >>> B = np.array([[0, 5, 2, 7], [0, 0, 3, 8],
+ ... [0, 0, 0, 3], [0, 0, 0, 0]])
+ >>> res = quadratic_assignment(A, B, options={'rng': rng})
+ >>> print(res)
+ fun: 3260
+ col_ind: [0 3 2 1]
+ nit: 9
+
+ The see the relationship between the returned ``col_ind`` and ``fun``,
+ use ``col_ind`` to form the best permutation matrix found, then evaluate
+ the objective function :math:`f(P) = trace(A^T P B P^T )`.
+
+ >>> perm = res['col_ind']
+ >>> P = np.eye(len(A), dtype=int)[perm]
+ >>> fun = np.trace(A.T @ P @ B @ P.T)
+ >>> print(fun)
+ 3260
+
+ Alternatively, to avoid constructing the permutation matrix explicitly,
+ directly permute the rows and columns of the distance matrix.
+
+ >>> fun = np.trace(A.T @ B[perm][:, perm])
+ >>> print(fun)
+ 3260
+
+ Although not guaranteed in general, ``quadratic_assignment`` happens to
+ have found the globally optimal solution.
+
+ >>> from itertools import permutations
+ >>> perm_opt, fun_opt = None, np.inf
+ >>> for perm in permutations([0, 1, 2, 3]):
+ ... perm = np.array(perm)
+ ... fun = np.trace(A.T @ B[perm][:, perm])
+ ... if fun < fun_opt:
+ ... fun_opt, perm_opt = fun, perm
+ >>> print(np.array_equal(perm_opt, res['col_ind']))
+ True
+
+ Here is an example for which the default method,
+ :ref:`'faq' `, does not find the global optimum.
+
+ >>> A = np.array([[0, 5, 8, 6], [5, 0, 5, 1],
+ ... [8, 5, 0, 2], [6, 1, 2, 0]])
+ >>> B = np.array([[0, 1, 8, 4], [1, 0, 5, 2],
+ ... [8, 5, 0, 5], [4, 2, 5, 0]])
+ >>> res = quadratic_assignment(A, B, options={'rng': rng})
+ >>> print(res)
+ fun: 178
+ col_ind: [1 0 3 2]
+ nit: 13
+
+ If accuracy is important, consider using :ref:`'2opt' `
+ to refine the solution.
+
+ >>> guess = np.array([np.arange(len(A)), res.col_ind]).T
+ >>> res = quadratic_assignment(A, B, method="2opt",
+ ... options = {'rng': rng, 'partial_guess': guess})
+ >>> print(res)
+ fun: 176
+ col_ind: [1 2 3 0]
+ nit: 17
+
+ """
+
+ if options is None:
+ options = {}
+
+ method = method.lower()
+ methods = {"faq": _quadratic_assignment_faq,
+ "2opt": _quadratic_assignment_2opt}
+ if method not in methods:
+ raise ValueError(f"method {method} must be in {methods}.")
+
+ _spec007_transition(options.get("rng", None))
+ res = methods[method](A, B, **options)
+ return res
+
+
+def _spec007_transition(rng):
+ if isinstance(rng, np.random.RandomState):
+ warnings.warn(
+ "Use of `RandomState` with `quadratic_assignment` is deprecated"
+ " and will result in an exception in SciPy 1.17",
+ DeprecationWarning,
+ stacklevel=2
+ )
+ if ((rng is None or rng is np.random) and
+ np.random.mtrand._rand._bit_generator._seed_seq is None):
+ warnings.warn(
+ "The NumPy global RNG was seeded by calling `np.random.seed`."
+ " From SciPy 1.17, this function will no longer use the global RNG.",
+ FutureWarning,
+ stacklevel=2
+ )
+ if isinstance(rng, numbers.Integral | np.integer):
+ warnings.warn(
+ "The behavior when the rng option is an integer is changing: the value"
+ " will be normalized using np.random.default_rng beginning in SciPy 1.17,"
+ " and the resulting Generator will be used to generate random numbers.",
+ FutureWarning,
+ stacklevel=2
+ )
+
+
+def _calc_score(A, B, perm):
+ # equivalent to objective function but avoids matmul
+ return np.sum(A * B[perm][:, perm])
+
+
+def _common_input_validation(A, B, partial_match):
+ A = np.atleast_2d(A)
+ B = np.atleast_2d(B)
+
+ if partial_match is None:
+ partial_match = np.array([[], []]).T
+ partial_match = np.atleast_2d(partial_match).astype(int)
+
+ msg = None
+ if A.shape[0] != A.shape[1]:
+ msg = "`A` must be square"
+ elif B.shape[0] != B.shape[1]:
+ msg = "`B` must be square"
+ elif A.ndim != 2 or B.ndim != 2:
+ msg = "`A` and `B` must have exactly two dimensions"
+ elif A.shape != B.shape:
+ msg = "`A` and `B` matrices must be of equal size"
+ elif partial_match.shape[0] > A.shape[0]:
+ msg = "`partial_match` can have only as many seeds as there are nodes"
+ elif partial_match.shape[1] != 2:
+ msg = "`partial_match` must have two columns"
+ elif partial_match.ndim != 2:
+ msg = "`partial_match` must have exactly two dimensions"
+ elif (partial_match < 0).any():
+ msg = "`partial_match` must contain only positive indices"
+ elif (partial_match >= len(A)).any():
+ msg = "`partial_match` entries must be less than number of nodes"
+ elif (not len(set(partial_match[:, 0])) == len(partial_match[:, 0]) or
+ not len(set(partial_match[:, 1])) == len(partial_match[:, 1])):
+ msg = "`partial_match` column entries must be unique"
+
+ if msg is not None:
+ raise ValueError(msg)
+
+ return A, B, partial_match
+
+
+def _quadratic_assignment_faq(A, B,
+ maximize=False, partial_match=None, rng=None,
+ P0="barycenter", shuffle_input=False, maxiter=30,
+ tol=0.03, **unknown_options):
+ r"""Solve the quadratic assignment problem (approximately).
+
+ This function solves the Quadratic Assignment Problem (QAP) and the
+ Graph Matching Problem (GMP) using the Fast Approximate QAP Algorithm
+ (FAQ) [1]_.
+
+ Quadratic assignment solves problems of the following form:
+
+ .. math::
+
+ \min_P & \ {\ \text{trace}(A^T P B P^T)}\\
+ \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\
+
+ where :math:`\mathcal{P}` is the set of all permutation matrices,
+ and :math:`A` and :math:`B` are square matrices.
+
+ Graph matching tries to *maximize* the same objective function.
+ This algorithm can be thought of as finding the alignment of the
+ nodes of two graphs that minimizes the number of induced edge
+ disagreements, or, in the case of weighted graphs, the sum of squared
+ edge weight differences.
+
+ Note that the quadratic assignment problem is NP-hard. The results given
+ here are approximations and are not guaranteed to be optimal.
+
+ Parameters
+ ----------
+ A : 2-D array, square
+ The square matrix :math:`A` in the objective function above.
+ B : 2-D array, square
+ The square matrix :math:`B` in the objective function above.
+ method : str in {'faq', '2opt'} (default: 'faq')
+ The algorithm used to solve the problem. This is the method-specific
+ documentation for 'faq'.
+ :ref:`'2opt' ` is also available.
+
+ Options
+ -------
+ maximize : bool (default: False)
+ Maximizes the objective function if ``True``.
+ partial_match : 2-D array of integers, optional (default: None)
+ Fixes part of the matching. Also known as a "seed" [2]_.
+
+ Each row of `partial_match` specifies a pair of matched nodes:
+ node ``partial_match[i, 0]`` of `A` is matched to node
+ ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``, where
+ ``m`` is not greater than the number of nodes, :math:`n`.
+
+ rng : {None, int, `numpy.random.Generator`}, optional
+ Pseudorandom number generator state. See `quadratic_assignment` for details.
+ P0 : 2-D array, "barycenter", or "randomized" (default: "barycenter")
+ Initial position. Must be a doubly-stochastic matrix [3]_.
+
+ If the initial position is an array, it must be a doubly stochastic
+ matrix of size :math:`m' \times m'` where :math:`m' = n - m`.
+
+ If ``"barycenter"`` (default), the initial position is the barycenter
+ of the Birkhoff polytope (the space of doubly stochastic matrices).
+ This is a :math:`m' \times m'` matrix with all entries equal to
+ :math:`1 / m'`.
+
+ If ``"randomized"`` the initial search position is
+ :math:`P_0 = (J + K) / 2`, where :math:`J` is the barycenter and
+ :math:`K` is a random doubly stochastic matrix.
+ shuffle_input : bool (default: False)
+ Set to `True` to resolve degenerate gradients randomly. For
+ non-degenerate gradients this option has no effect.
+ maxiter : int, positive (default: 30)
+ Integer specifying the max number of Frank-Wolfe iterations performed.
+ tol : float (default: 0.03)
+ Tolerance for termination. Frank-Wolfe iteration terminates when
+ :math:`\frac{||P_{i}-P_{i+1}||_F}{\sqrt{m'}} \leq tol`,
+ where :math:`i` is the iteration number.
+
+ Returns
+ -------
+ res : OptimizeResult
+ `OptimizeResult` containing the following fields.
+
+ col_ind : 1-D array
+ Column indices corresponding to the best permutation found of the
+ nodes of `B`.
+ fun : float
+ The objective value of the solution.
+ nit : int
+ The number of Frank-Wolfe iterations performed.
+
+ Notes
+ -----
+ The algorithm may be sensitive to the initial permutation matrix (or
+ search "position") due to the possibility of several local minima
+ within the feasible region. A barycenter initialization is more likely to
+ result in a better solution than a single random initialization. However,
+ calling ``quadratic_assignment`` several times with different random
+ initializations may result in a better optimum at the cost of longer
+ total execution time.
+
+ Examples
+ --------
+ As mentioned above, a barycenter initialization often results in a better
+ solution than a single random initialization.
+
+ >>> from scipy.optimize import quadratic_assignment
+ >>> import numpy as np
+ >>> rng = np.random.default_rng()
+ >>> n = 15
+ >>> A = rng.random((n, n))
+ >>> B = rng.random((n, n))
+ >>> options = {"rng": rng}
+ >>> res = quadratic_assignment(A, B, options=options) # FAQ is default method
+ >>> print(res.fun)
+ 47.797048706380636 # may vary
+
+ >>> options = {"rng": rng, "P0": "randomized"} # use randomized initialization
+ >>> res = quadratic_assignment(A, B, options=options)
+ >>> print(res.fun)
+ 47.37287069769966 # may vary
+
+ However, consider running from several randomized initializations and
+ keeping the best result.
+
+ >>> res = min([quadratic_assignment(A, B, options=options)
+ ... for i in range(30)], key=lambda x: x.fun)
+ >>> print(res.fun)
+ 46.55974835248574 # may vary
+
+ The '2-opt' method can be used to attempt to refine the results.
+
+ >>> options = {"partial_guess": np.array([np.arange(n), res.col_ind]).T, "rng": rng}
+ >>> res = quadratic_assignment(A, B, method="2opt", options=options)
+ >>> print(res.fun)
+ 46.55974835248574 # may vary
+
+ References
+ ----------
+ .. [1] J.T. Vogelstein, J.M. Conroy, V. Lyzinski, L.J. Podrazik,
+ S.G. Kratzer, E.T. Harley, D.E. Fishkind, R.J. Vogelstein, and
+ C.E. Priebe, "Fast approximate quadratic programming for graph
+ matching," PLOS one, vol. 10, no. 4, p. e0121002, 2015,
+ :doi:`10.1371/journal.pone.0121002`
+
+ .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski,
+ C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019):
+ 203-215, :doi:`10.1016/j.patcog.2018.09.014`
+
+ .. [3] "Doubly stochastic Matrix," Wikipedia.
+ https://en.wikipedia.org/wiki/Doubly_stochastic_matrix
+
+ """
+
+ _check_unknown_options(unknown_options)
+
+ maxiter = operator.index(maxiter)
+
+ # ValueError check
+ A, B, partial_match = _common_input_validation(A, B, partial_match)
+
+ msg = None
+ if isinstance(P0, str) and P0 not in {'barycenter', 'randomized'}:
+ msg = "Invalid 'P0' parameter string"
+ elif maxiter <= 0:
+ msg = "'maxiter' must be a positive integer"
+ elif tol <= 0:
+ msg = "'tol' must be a positive float"
+ if msg is not None:
+ raise ValueError(msg)
+
+ rng = check_random_state(rng)
+ n = len(A) # number of vertices in graphs
+ n_seeds = len(partial_match) # number of seeds
+ n_unseed = n - n_seeds
+
+ # [1] Algorithm 1 Line 1 - choose initialization
+ if not isinstance(P0, str):
+ P0 = np.atleast_2d(P0)
+ if P0.shape != (n_unseed, n_unseed):
+ msg = "`P0` matrix must have shape m' x m', where m'=n-m"
+ elif ((P0 < 0).any() or not np.allclose(np.sum(P0, axis=0), 1)
+ or not np.allclose(np.sum(P0, axis=1), 1)):
+ msg = "`P0` matrix must be doubly stochastic"
+ if msg is not None:
+ raise ValueError(msg)
+ elif P0 == 'barycenter':
+ P0 = np.ones((n_unseed, n_unseed)) / n_unseed
+ elif P0 == 'randomized':
+ J = np.ones((n_unseed, n_unseed)) / n_unseed
+ # generate a nxn matrix where each entry is a random number [0, 1]
+ # would use rand, but Generators don't have it
+ # would use random, but old mtrand.RandomStates don't have it
+ K = _doubly_stochastic(rng.uniform(size=(n_unseed, n_unseed)))
+ P0 = (J + K) / 2
+
+ # check trivial cases
+ if n == 0 or n_seeds == n:
+ score = _calc_score(A, B, partial_match[:, 1])
+ res = {"col_ind": partial_match[:, 1], "fun": score, "nit": 0}
+ return OptimizeResult(res)
+
+ obj_func_scalar = 1
+ if maximize:
+ obj_func_scalar = -1
+
+ nonseed_B = np.setdiff1d(range(n), partial_match[:, 1])
+ if shuffle_input:
+ nonseed_B = rng.permutation(nonseed_B)
+
+ nonseed_A = np.setdiff1d(range(n), partial_match[:, 0])
+ perm_A = np.concatenate([partial_match[:, 0], nonseed_A])
+ perm_B = np.concatenate([partial_match[:, 1], nonseed_B])
+
+ # definitions according to Seeded Graph Matching [2].
+ A11, A12, A21, A22 = _split_matrix(A[perm_A][:, perm_A], n_seeds)
+ B11, B12, B21, B22 = _split_matrix(B[perm_B][:, perm_B], n_seeds)
+ const_sum = A21 @ B21.T + A12.T @ B12
+
+ P = P0
+ # [1] Algorithm 1 Line 2 - loop while stopping criteria not met
+ for n_iter in range(1, maxiter+1):
+ # [1] Algorithm 1 Line 3 - compute the gradient of f(P) = -tr(APB^tP^t)
+ grad_fp = (const_sum + A22 @ P @ B22.T + A22.T @ P @ B22)
+ # [1] Algorithm 1 Line 4 - get direction Q by solving Eq. 8
+ _, cols = linear_sum_assignment(grad_fp, maximize=maximize)
+ Q = np.eye(n_unseed)[cols]
+
+ # [1] Algorithm 1 Line 5 - compute the step size
+ # Noting that e.g. trace(Ax) = trace(A)*x, expand and re-collect
+ # terms as ax**2 + bx + c. c does not affect location of minimum
+ # and can be ignored. Also, note that trace(A@B) = (A.T*B).sum();
+ # apply where possible for efficiency.
+ R = P - Q
+ b21 = ((R.T @ A21) * B21).sum()
+ b12 = ((R.T @ A12.T) * B12.T).sum()
+ AR22 = A22.T @ R
+ BR22 = B22 @ R.T
+ b22a = (AR22 * B22.T[cols]).sum()
+ b22b = (A22 * BR22[cols]).sum()
+ a = (AR22.T * BR22).sum()
+ b = b21 + b12 + b22a + b22b
+ # critical point of ax^2 + bx + c is at x = -d/(2*e)
+ # if a * obj_func_scalar > 0, it is a minimum
+ # if minimum is not in [0, 1], only endpoints need to be considered
+ if a*obj_func_scalar > 0 and 0 <= -b/(2*a) <= 1:
+ alpha = -b/(2*a)
+ else:
+ alpha = np.argmin([0, (b + a)*obj_func_scalar])
+
+ # [1] Algorithm 1 Line 6 - Update P
+ P_i1 = alpha * P + (1 - alpha) * Q
+ if np.linalg.norm(P - P_i1) / np.sqrt(n_unseed) < tol:
+ P = P_i1
+ break
+ P = P_i1
+ # [1] Algorithm 1 Line 7 - end main loop
+
+ # [1] Algorithm 1 Line 8 - project onto the set of permutation matrices
+ _, col = linear_sum_assignment(P, maximize=True)
+ perm = np.concatenate((np.arange(n_seeds), col + n_seeds))
+
+ unshuffled_perm = np.zeros(n, dtype=int)
+ unshuffled_perm[perm_A] = perm_B[perm]
+
+ score = _calc_score(A, B, unshuffled_perm)
+ res = {"col_ind": unshuffled_perm, "fun": score, "nit": n_iter}
+ return OptimizeResult(res)
+
+
+def _split_matrix(X, n):
+ # definitions according to Seeded Graph Matching [2].
+ upper, lower = X[:n], X[n:]
+ return upper[:, :n], upper[:, n:], lower[:, :n], lower[:, n:]
+
+
+def _doubly_stochastic(P, tol=1e-3):
+ # Adapted from @btaba implementation
+ # https://github.com/btaba/sinkhorn_knopp
+ # of Sinkhorn-Knopp algorithm
+ # https://projecteuclid.org/euclid.pjm/1102992505
+
+ max_iter = 1000
+ c = 1 / P.sum(axis=0)
+ r = 1 / (P @ c)
+ P_eps = P
+
+ for it in range(max_iter):
+ if ((np.abs(P_eps.sum(axis=1) - 1) < tol).all() and
+ (np.abs(P_eps.sum(axis=0) - 1) < tol).all()):
+ # All column/row sums ~= 1 within threshold
+ break
+
+ c = 1 / (r @ P)
+ r = 1 / (P @ c)
+ P_eps = r[:, None] * P * c
+
+ return P_eps
+
+
+def _quadratic_assignment_2opt(A, B, maximize=False, rng=None,
+ partial_match=None,
+ partial_guess=None,
+ **unknown_options):
+ r"""Solve the quadratic assignment problem (approximately).
+
+ This function solves the Quadratic Assignment Problem (QAP) and the
+ Graph Matching Problem (GMP) using the 2-opt algorithm [1]_.
+
+ Quadratic assignment solves problems of the following form:
+
+ .. math::
+
+ \min_P & \ {\ \text{trace}(A^T P B P^T)}\\
+ \mbox{s.t. } & {P \ \epsilon \ \mathcal{P}}\\
+
+ where :math:`\mathcal{P}` is the set of all permutation matrices,
+ and :math:`A` and :math:`B` are square matrices.
+
+ Graph matching tries to *maximize* the same objective function.
+ This algorithm can be thought of as finding the alignment of the
+ nodes of two graphs that minimizes the number of induced edge
+ disagreements, or, in the case of weighted graphs, the sum of squared
+ edge weight differences.
+
+ Note that the quadratic assignment problem is NP-hard. The results given
+ here are approximations and are not guaranteed to be optimal.
+
+ Parameters
+ ----------
+ A : 2-D array, square
+ The square matrix :math:`A` in the objective function above.
+ B : 2-D array, square
+ The square matrix :math:`B` in the objective function above.
+ method : str in {'faq', '2opt'} (default: 'faq')
+ The algorithm used to solve the problem. This is the method-specific
+ documentation for '2opt'.
+ :ref:`'faq' ` is also available.
+
+ Options
+ -------
+ maximize : bool (default: False)
+ Maximizes the objective function if ``True``.
+ rng : {None, int, `numpy.random.Generator`}, optional
+ Pseudorandom number generator state. See `quadratic_assignment` for details.
+ partial_match : 2-D array of integers, optional (default: None)
+ Fixes part of the matching. Also known as a "seed" [2]_.
+
+ Each row of `partial_match` specifies a pair of matched nodes: node
+ ``partial_match[i, 0]`` of `A` is matched to node
+ ``partial_match[i, 1]`` of `B`. The array has shape ``(m, 2)``,
+ where ``m`` is not greater than the number of nodes, :math:`n`.
+
+ .. note::
+ `partial_match` must be sorted by the first column.
+
+ partial_guess : 2-D array of integers, optional (default: None)
+ A guess for the matching between the two matrices. Unlike
+ `partial_match`, `partial_guess` does not fix the indices; they are
+ still free to be optimized.
+
+ Each row of `partial_guess` specifies a pair of matched nodes: node
+ ``partial_guess[i, 0]`` of `A` is matched to node
+ ``partial_guess[i, 1]`` of `B`. The array has shape ``(m, 2)``,
+ where ``m`` is not greater than the number of nodes, :math:`n`.
+
+ .. note::
+ `partial_guess` must be sorted by the first column.
+
+ Returns
+ -------
+ res : OptimizeResult
+ `OptimizeResult` containing the following fields.
+
+ col_ind : 1-D array
+ Column indices corresponding to the best permutation found of the
+ nodes of `B`.
+ fun : float
+ The objective value of the solution.
+ nit : int
+ The number of iterations performed during optimization.
+
+ Notes
+ -----
+ This is a greedy algorithm that works similarly to bubble sort: beginning
+ with an initial permutation, it iteratively swaps pairs of indices to
+ improve the objective function until no such improvements are possible.
+
+ References
+ ----------
+ .. [1] "2-opt," Wikipedia.
+ https://en.wikipedia.org/wiki/2-opt
+
+ .. [2] D. Fishkind, S. Adali, H. Patsolic, L. Meng, D. Singh, V. Lyzinski,
+ C. Priebe, "Seeded graph matching", Pattern Recognit. 87 (2019):
+ 203-215, https://doi.org/10.1016/j.patcog.2018.09.014
+
+ """
+ _check_unknown_options(unknown_options)
+ rng = check_random_state(rng)
+ A, B, partial_match = _common_input_validation(A, B, partial_match)
+
+ N = len(A)
+ # check trivial cases
+ if N == 0 or partial_match.shape[0] == N:
+ score = _calc_score(A, B, partial_match[:, 1])
+ res = {"col_ind": partial_match[:, 1], "fun": score, "nit": 0}
+ return OptimizeResult(res)
+
+ if partial_guess is None:
+ partial_guess = np.array([[], []]).T
+ partial_guess = np.atleast_2d(partial_guess).astype(int)
+
+ msg = None
+ if partial_guess.shape[0] > A.shape[0]:
+ msg = ("`partial_guess` can have only as "
+ "many entries as there are nodes")
+ elif partial_guess.shape[1] != 2:
+ msg = "`partial_guess` must have two columns"
+ elif partial_guess.ndim != 2:
+ msg = "`partial_guess` must have exactly two dimensions"
+ elif (partial_guess < 0).any():
+ msg = "`partial_guess` must contain only positive indices"
+ elif (partial_guess >= len(A)).any():
+ msg = "`partial_guess` entries must be less than number of nodes"
+ elif (not len(set(partial_guess[:, 0])) == len(partial_guess[:, 0]) or
+ not len(set(partial_guess[:, 1])) == len(partial_guess[:, 1])):
+ msg = "`partial_guess` column entries must be unique"
+ if msg is not None:
+ raise ValueError(msg)
+
+ fixed_rows = None
+ if partial_match.size or partial_guess.size:
+ # use partial_match and partial_guess for initial permutation,
+ # but randomly permute the rest.
+ guess_rows = np.zeros(N, dtype=bool)
+ guess_cols = np.zeros(N, dtype=bool)
+ fixed_rows = np.zeros(N, dtype=bool)
+ fixed_cols = np.zeros(N, dtype=bool)
+ perm = np.zeros(N, dtype=int)
+
+ rg, cg = partial_guess.T
+ guess_rows[rg] = True
+ guess_cols[cg] = True
+ perm[guess_rows] = cg
+
+ # match overrides guess
+ rf, cf = partial_match.T
+ fixed_rows[rf] = True
+ fixed_cols[cf] = True
+ perm[fixed_rows] = cf
+
+ random_rows = ~fixed_rows & ~guess_rows
+ random_cols = ~fixed_cols & ~guess_cols
+ perm[random_rows] = rng.permutation(np.arange(N)[random_cols])
+ else:
+ perm = rng.permutation(np.arange(N))
+
+ best_score = _calc_score(A, B, perm)
+
+ i_free = np.arange(N)
+ if fixed_rows is not None:
+ i_free = i_free[~fixed_rows]
+
+ better = operator.gt if maximize else operator.lt
+ n_iter = 0
+ done = False
+ while not done:
+ # equivalent to nested for loops i in range(N), j in range(i, N)
+ for i, j in itertools.combinations_with_replacement(i_free, 2):
+ n_iter += 1
+ perm[i], perm[j] = perm[j], perm[i]
+ score = _calc_score(A, B, perm)
+ if better(score, best_score):
+ best_score = score
+ break
+ # faster to swap back than to create a new list every time
+ perm[i], perm[j] = perm[j], perm[i]
+ else: # no swaps made
+ done = True
+
+ res = {"col_ind": perm, "fun": best_score, "nit": n_iter}
+ return OptimizeResult(res)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_remove_redundancy.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_remove_redundancy.py
new file mode 100644
index 0000000000000000000000000000000000000000..cf2d3e400d3d09b9cc51cdcc76c5573f19f21859
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_remove_redundancy.py
@@ -0,0 +1,522 @@
+"""
+Routines for removing redundant (linearly dependent) equations from linear
+programming equality constraints.
+"""
+# Author: Matt Haberland
+
+import numpy as np
+from scipy.linalg import svd
+from scipy.linalg.interpolative import interp_decomp
+import scipy
+from scipy.linalg.blas import dtrsm
+
+
+def _row_count(A):
+ """
+ Counts the number of nonzeros in each row of input array A.
+ Nonzeros are defined as any element with absolute value greater than
+ tol = 1e-13. This value should probably be an input to the function.
+
+ Parameters
+ ----------
+ A : 2-D array
+ An array representing a matrix
+
+ Returns
+ -------
+ rowcount : 1-D array
+ Number of nonzeros in each row of A
+
+ """
+ tol = 1e-13
+ return np.array((abs(A) > tol).sum(axis=1)).flatten()
+
+
+def _get_densest(A, eligibleRows):
+ """
+ Returns the index of the densest row of A. Ignores rows that are not
+ eligible for consideration.
+
+ Parameters
+ ----------
+ A : 2-D array
+ An array representing a matrix
+ eligibleRows : 1-D logical array
+ Values indicate whether the corresponding row of A is eligible
+ to be considered
+
+ Returns
+ -------
+ i_densest : int
+ Index of the densest row in A eligible for consideration
+
+ """
+ rowCounts = _row_count(A)
+ return np.argmax(rowCounts * eligibleRows)
+
+
+def _remove_zero_rows(A, b):
+ """
+ Eliminates trivial equations from system of equations defined by Ax = b
+ and identifies trivial infeasibilities
+
+ Parameters
+ ----------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ b : 1-D array
+ An array representing the right-hand side of a system of equations
+
+ Returns
+ -------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ b : 1-D array
+ An array representing the right-hand side of a system of equations
+ status: int
+ An integer indicating the status of the removal operation
+ 0: No infeasibility identified
+ 2: Trivially infeasible
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ """
+ status = 0
+ message = ""
+ i_zero = _row_count(A) == 0
+ A = A[np.logical_not(i_zero), :]
+ if not np.allclose(b[i_zero], 0):
+ status = 2
+ message = "There is a zero row in A_eq with a nonzero corresponding " \
+ "entry in b_eq. The problem is infeasible."
+ b = b[np.logical_not(i_zero)]
+ return A, b, status, message
+
+
+def bg_update_dense(plu, perm_r, v, j):
+ LU, p = plu
+
+ vperm = v[perm_r]
+ u = dtrsm(1, LU, vperm, lower=1, diag=1)
+ LU[:j+1, j] = u[:j+1]
+ l = u[j+1:]
+ piv = LU[j, j]
+ LU[j+1:, j] += (l/piv)
+ return LU, p
+
+
+def _remove_redundancy_pivot_dense(A, rhs, true_rank=None):
+ """
+ Eliminates redundant equations from system of equations defined by Ax = b
+ and identifies infeasibilities.
+
+ Parameters
+ ----------
+ A : 2-D array
+ An matrix representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+
+ Returns
+ -------
+ A : 2-D array
+ A matrix representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+ status: int
+ An integer indicating the status of the system
+ 0: No infeasibility identified
+ 2: Trivially infeasible
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ References
+ ----------
+ .. [2] Andersen, Erling D. "Finding all linearly dependent rows in
+ large-scale linear programming." Optimization Methods and Software
+ 6.3 (1995): 219-227.
+
+ """
+ tolapiv = 1e-8
+ tolprimal = 1e-8
+ status = 0
+ message = ""
+ inconsistent = ("There is a linear combination of rows of A_eq that "
+ "results in zero, suggesting a redundant constraint. "
+ "However the same linear combination of b_eq is "
+ "nonzero, suggesting that the constraints conflict "
+ "and the problem is infeasible.")
+ A, rhs, status, message = _remove_zero_rows(A, rhs)
+
+ if status != 0:
+ return A, rhs, status, message
+
+ m, n = A.shape
+
+ v = list(range(m)) # Artificial column indices.
+ b = list(v) # Basis column indices.
+ # This is better as a list than a set because column order of basis matrix
+ # needs to be consistent.
+ d = [] # Indices of dependent rows
+ perm_r = None
+
+ A_orig = A
+ A = np.zeros((m, m + n), order='F')
+ np.fill_diagonal(A, 1)
+ A[:, m:] = A_orig
+ e = np.zeros(m)
+
+ js_candidates = np.arange(m, m+n, dtype=int) # candidate columns for basis
+ # manual masking was faster than masked array
+ js_mask = np.ones(js_candidates.shape, dtype=bool)
+
+ # Implements basic algorithm from [2]
+ # Uses some of the suggested improvements (removing zero rows and
+ # Bartels-Golub update idea).
+ # Removing column singletons would be easy, but it is not as important
+ # because the procedure is performed only on the equality constraint
+ # matrix from the original problem - not on the canonical form matrix,
+ # which would have many more column singletons due to slack variables
+ # from the inequality constraints.
+ # The thoughts on "crashing" the initial basis are only really useful if
+ # the matrix is sparse.
+
+ lu = np.eye(m, order='F'), np.arange(m) # initial LU is trivial
+ perm_r = lu[1]
+ for i in v:
+
+ e[i] = 1
+ if i > 0:
+ e[i-1] = 0
+
+ try: # fails for i==0 and any time it gets ill-conditioned
+ j = b[i-1]
+ lu = bg_update_dense(lu, perm_r, A[:, j], i-1)
+ except Exception:
+ lu = scipy.linalg.lu_factor(A[:, b])
+ LU, p = lu
+ perm_r = list(range(m))
+ for i1, i2 in enumerate(p):
+ perm_r[i1], perm_r[i2] = perm_r[i2], perm_r[i1]
+
+ pi = scipy.linalg.lu_solve(lu, e, trans=1)
+
+ js = js_candidates[js_mask]
+ batch = 50
+
+ # This is a tiny bit faster than looping over columns individually,
+ # like for j in js: if abs(A[:,j].transpose().dot(pi)) > tolapiv:
+ for j_index in range(0, len(js), batch):
+ j_indices = js[j_index: min(j_index+batch, len(js))]
+
+ c = abs(A[:, j_indices].transpose().dot(pi))
+ if (c > tolapiv).any():
+ j = js[j_index + np.argmax(c)] # very independent column
+ b[i] = j
+ js_mask[j-m] = False
+ break
+ else:
+ bibar = pi.T.dot(rhs.reshape(-1, 1))
+ bnorm = np.linalg.norm(rhs)
+ if abs(bibar)/(1+bnorm) > tolprimal: # inconsistent
+ status = 2
+ message = inconsistent
+ return A_orig, rhs, status, message
+ else: # dependent
+ d.append(i)
+ if true_rank is not None and len(d) == m - true_rank:
+ break # found all redundancies
+
+ keep = set(range(m))
+ keep = list(keep - set(d))
+ return A_orig[keep, :], rhs[keep], status, message
+
+
+def _remove_redundancy_pivot_sparse(A, rhs):
+ """
+ Eliminates redundant equations from system of equations defined by Ax = b
+ and identifies infeasibilities.
+
+ Parameters
+ ----------
+ A : 2-D sparse array
+ An matrix representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+
+ Returns
+ -------
+ A : 2-D sparse array
+ A matrix representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+ status: int
+ An integer indicating the status of the system
+ 0: No infeasibility identified
+ 2: Trivially infeasible
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ References
+ ----------
+ .. [2] Andersen, Erling D. "Finding all linearly dependent rows in
+ large-scale linear programming." Optimization Methods and Software
+ 6.3 (1995): 219-227.
+
+ """
+
+ tolapiv = 1e-8
+ tolprimal = 1e-8
+ status = 0
+ message = ""
+ inconsistent = ("There is a linear combination of rows of A_eq that "
+ "results in zero, suggesting a redundant constraint. "
+ "However the same linear combination of b_eq is "
+ "nonzero, suggesting that the constraints conflict "
+ "and the problem is infeasible.")
+ A, rhs, status, message = _remove_zero_rows(A, rhs)
+
+ if status != 0:
+ return A, rhs, status, message
+
+ m, n = A.shape
+
+ v = list(range(m)) # Artificial column indices.
+ b = list(v) # Basis column indices.
+ # This is better as a list than a set because column order of basis matrix
+ # needs to be consistent.
+ k = set(range(m, m+n)) # Structural column indices.
+ d = [] # Indices of dependent rows
+
+ A_orig = A
+ A = scipy.sparse.hstack((scipy.sparse.eye_array(m), A)).tocsc()
+ e = np.zeros(m)
+
+ # Implements basic algorithm from [2]
+ # Uses only one of the suggested improvements (removing zero rows).
+ # Removing column singletons would be easy, but it is not as important
+ # because the procedure is performed only on the equality constraint
+ # matrix from the original problem - not on the canonical form matrix,
+ # which would have many more column singletons due to slack variables
+ # from the inequality constraints.
+ # The thoughts on "crashing" the initial basis sound useful, but the
+ # description of the procedure seems to assume a lot of familiarity with
+ # the subject; it is not very explicit. I already went through enough
+ # trouble getting the basic algorithm working, so I was not interested in
+ # trying to decipher this, too. (Overall, the paper is fraught with
+ # mistakes and ambiguities - which is strange, because the rest of
+ # Andersen's papers are quite good.)
+ # I tried and tried and tried to improve performance using the
+ # Bartels-Golub update. It works, but it's only practical if the LU
+ # factorization can be specialized as described, and that is not possible
+ # until the SciPy SuperLU interface permits control over column
+ # permutation - see issue #7700.
+
+ for i in v:
+ B = A[:, b]
+
+ e[i] = 1
+ if i > 0:
+ e[i-1] = 0
+
+ pi = scipy.sparse.linalg.spsolve(B.transpose(), e).reshape(-1, 1)
+
+ js = list(k-set(b)) # not efficient, but this is not the time sink...
+
+ # Due to overhead, it tends to be faster (for problems tested) to
+ # compute the full matrix-vector product rather than individual
+ # vector-vector products (with the chance of terminating as soon
+ # as any are nonzero). For very large matrices, it might be worth
+ # it to compute, say, 100 or 1000 at a time and stop when a nonzero
+ # is found.
+
+ c = (np.abs(A[:, js].transpose().dot(pi)) > tolapiv).nonzero()[0]
+ if len(c) > 0: # independent
+ j = js[c[0]]
+ # in a previous commit, the previous line was changed to choose
+ # index j corresponding with the maximum dot product.
+ # While this avoided issues with almost
+ # singular matrices, it slowed the routine in most NETLIB tests.
+ # I think this is because these columns were denser than the
+ # first column with nonzero dot product (c[0]).
+ # It would be nice to have a heuristic that balances sparsity with
+ # high dot product, but I don't think it's worth the time to
+ # develop one right now. Bartels-Golub update is a much higher
+ # priority.
+ b[i] = j # replace artificial column
+ else:
+ bibar = pi.T.dot(rhs.reshape(-1, 1))
+ bnorm = np.linalg.norm(rhs)
+ if abs(bibar)/(1 + bnorm) > tolprimal:
+ status = 2
+ message = inconsistent
+ return A_orig, rhs, status, message
+ else: # dependent
+ d.append(i)
+
+ keep = set(range(m))
+ keep = list(keep - set(d))
+ return A_orig[keep, :], rhs[keep], status, message
+
+
+def _remove_redundancy_svd(A, b):
+ """
+ Eliminates redundant equations from system of equations defined by Ax = b
+ and identifies infeasibilities.
+
+ Parameters
+ ----------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ b : 1-D array
+ An array representing the right-hand side of a system of equations
+
+ Returns
+ -------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ b : 1-D array
+ An array representing the right-hand side of a system of equations
+ status: int
+ An integer indicating the status of the system
+ 0: No infeasibility identified
+ 2: Trivially infeasible
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ References
+ ----------
+ .. [2] Andersen, Erling D. "Finding all linearly dependent rows in
+ large-scale linear programming." Optimization Methods and Software
+ 6.3 (1995): 219-227.
+
+ """
+
+ A, b, status, message = _remove_zero_rows(A, b)
+
+ if status != 0:
+ return A, b, status, message
+
+ U, s, Vh = svd(A)
+ eps = np.finfo(float).eps
+ tol = s.max() * max(A.shape) * eps
+
+ m, n = A.shape
+ s_min = s[-1] if m <= n else 0
+
+ # this algorithm is faster than that of [2] when the nullspace is small
+ # but it could probably be improvement by randomized algorithms and with
+ # a sparse implementation.
+ # it relies on repeated singular value decomposition to find linearly
+ # dependent rows (as identified by columns of U that correspond with zero
+ # singular values). Unfortunately, only one row can be removed per
+ # decomposition (I tried otherwise; doing so can cause problems.)
+ # It would be nice if we could do truncated SVD like sp.sparse.linalg.svds
+ # but that function is unreliable at finding singular values near zero.
+ # Finding max eigenvalue L of A A^T, then largest eigenvalue (and
+ # associated eigenvector) of -A A^T + L I (I is identity) via power
+ # iteration would also work in theory, but is only efficient if the
+ # smallest nonzero eigenvalue of A A^T is close to the largest nonzero
+ # eigenvalue.
+
+ while abs(s_min) < tol:
+ v = U[:, -1] # TODO: return these so user can eliminate from problem?
+ # rows need to be represented in significant amount
+ eligibleRows = np.abs(v) > tol * 10e6
+ if not np.any(eligibleRows) or np.any(np.abs(v.dot(A)) > tol):
+ status = 4
+ message = ("Due to numerical issues, redundant equality "
+ "constraints could not be removed automatically. "
+ "Try providing your constraint matrices as sparse "
+ "matrices to activate sparse presolve, try turning "
+ "off redundancy removal, or try turning off presolve "
+ "altogether.")
+ break
+ if np.any(np.abs(v.dot(b)) > tol * 100): # factor of 100 to fix 10038 and 10349
+ status = 2
+ message = ("There is a linear combination of rows of A_eq that "
+ "results in zero, suggesting a redundant constraint. "
+ "However the same linear combination of b_eq is "
+ "nonzero, suggesting that the constraints conflict "
+ "and the problem is infeasible.")
+ break
+
+ i_remove = _get_densest(A, eligibleRows)
+ A = np.delete(A, i_remove, axis=0)
+ b = np.delete(b, i_remove)
+ U, s, Vh = svd(A)
+ m, n = A.shape
+ s_min = s[-1] if m <= n else 0
+
+ return A, b, status, message
+
+
+def _remove_redundancy_id(A, rhs, rank=None, randomized=True):
+ """Eliminates redundant equations from a system of equations.
+
+ Eliminates redundant equations from system of equations defined by Ax = b
+ and identifies infeasibilities.
+
+ Parameters
+ ----------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+ rank : int, optional
+ The rank of A
+ randomized: bool, optional
+ True for randomized interpolative decomposition
+
+ Returns
+ -------
+ A : 2-D array
+ An array representing the left-hand side of a system of equations
+ rhs : 1-D array
+ An array representing the right-hand side of a system of equations
+ status: int
+ An integer indicating the status of the system
+ 0: No infeasibility identified
+ 2: Trivially infeasible
+ message : str
+ A string descriptor of the exit status of the optimization.
+
+ """
+
+ status = 0
+ message = ""
+ inconsistent = ("There is a linear combination of rows of A_eq that "
+ "results in zero, suggesting a redundant constraint. "
+ "However the same linear combination of b_eq is "
+ "nonzero, suggesting that the constraints conflict "
+ "and the problem is infeasible.")
+
+ A, rhs, status, message = _remove_zero_rows(A, rhs)
+
+ if status != 0:
+ return A, rhs, status, message
+
+ m, n = A.shape
+
+ k = rank
+ if rank is None:
+ k = np.linalg.matrix_rank(A)
+
+ idx, proj = interp_decomp(A.T, k, rand=randomized)
+
+ # first k entries in idx are indices of the independent rows
+ # remaining entries are the indices of the m-k dependent rows
+ # proj provides a linear combinations of rows of A2 that form the
+ # remaining m-k (dependent) rows. The same linear combination of entries
+ # in rhs2 must give the remaining m-k entries. If not, the system is
+ # inconsistent, and the problem is infeasible.
+ if not np.allclose(rhs[idx[:k]] @ proj, rhs[idx[k:]]):
+ status = 2
+ message = inconsistent
+
+ # sort indices because the other redundancy removal routines leave rows
+ # in original order and tests were written with that in mind
+ idx = sorted(idx[:k])
+ A2 = A[idx, :]
+ rhs2 = rhs[idx]
+ return A2, rhs2, status, message
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_root.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_root.py
new file mode 100644
index 0000000000000000000000000000000000000000..988c4155cf4f9b5759904991bf78d102e5e96c16
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_root.py
@@ -0,0 +1,733 @@
+"""
+Unified interfaces to root finding algorithms.
+
+Functions
+---------
+- root : find a root of a vector function.
+"""
+__all__ = ['root']
+
+import numpy as np
+
+from warnings import warn
+
+from ._optimize import MemoizeJac, OptimizeResult, _check_unknown_options
+from ._minpack_py import _root_hybr, leastsq
+from ._spectral import _root_df_sane
+from . import _nonlin as nonlin
+
+
+ROOT_METHODS = ['hybr', 'lm', 'broyden1', 'broyden2', 'anderson',
+ 'linearmixing', 'diagbroyden', 'excitingmixing', 'krylov',
+ 'df-sane']
+
+
+def root(fun, x0, args=(), method='hybr', jac=None, tol=None, callback=None,
+ options=None):
+ r"""
+ Find a root of a vector function.
+
+ Parameters
+ ----------
+ fun : callable
+ A vector function to find a root of.
+
+ Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
+ ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
+ Rather than passing ``f0`` as the callable, wrap it to accept
+ only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
+ callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
+ gathered before invoking this function.
+ x0 : ndarray
+ Initial guess.
+ args : tuple, optional
+ Extra arguments passed to the objective function and its Jacobian.
+ method : str, optional
+ Type of solver. Should be one of
+
+ - 'hybr' :ref:`(see here) `
+ - 'lm' :ref:`(see here) `
+ - 'broyden1' :ref:`(see here) `
+ - 'broyden2' :ref:`(see here) `
+ - 'anderson' :ref:`(see here) `
+ - 'linearmixing' :ref:`(see here) `
+ - 'diagbroyden' :ref:`(see here) `
+ - 'excitingmixing' :ref:`(see here) `
+ - 'krylov' :ref:`(see here) `
+ - 'df-sane' :ref:`(see here) `
+
+ jac : bool or callable, optional
+ If `jac` is a Boolean and is True, `fun` is assumed to return the
+ value of Jacobian along with the objective function. If False, the
+ Jacobian will be estimated numerically.
+ `jac` can also be a callable returning the Jacobian of `fun`. In
+ this case, it must accept the same arguments as `fun`.
+ tol : float, optional
+ Tolerance for termination. For detailed control, use solver-specific
+ options.
+ callback : function, optional
+ Optional callback function. It is called on every iteration as
+ ``callback(x, f)`` where `x` is the current solution and `f`
+ the corresponding residual. For all methods but 'hybr' and 'lm'.
+ options : dict, optional
+ A dictionary of solver options. E.g., `xtol` or `maxiter`, see
+ :obj:`show_options()` for details.
+
+ Returns
+ -------
+ sol : OptimizeResult
+ The solution represented as a ``OptimizeResult`` object.
+ Important attributes are: ``x`` the solution array, ``success`` a
+ Boolean flag indicating if the algorithm exited successfully and
+ ``message`` which describes the cause of the termination. See
+ `OptimizeResult` for a description of other attributes.
+
+ See also
+ --------
+ show_options : Additional options accepted by the solvers
+
+ Notes
+ -----
+ This section describes the available solvers that can be selected by the
+ 'method' parameter. The default method is *hybr*.
+
+ Method *hybr* uses a modification of the Powell hybrid method as
+ implemented in MINPACK [1]_.
+
+ Method *lm* solves the system of nonlinear equations in a least squares
+ sense using a modification of the Levenberg-Marquardt algorithm as
+ implemented in MINPACK [1]_.
+
+ Method *df-sane* is a derivative-free spectral method. [3]_
+
+ Methods *broyden1*, *broyden2*, *anderson*, *linearmixing*,
+ *diagbroyden*, *excitingmixing*, *krylov* are inexact Newton methods,
+ with backtracking or full line searches [2]_. Each method corresponds
+ to a particular Jacobian approximations.
+
+ - Method *broyden1* uses Broyden's first Jacobian approximation, it is
+ known as Broyden's good method.
+ - Method *broyden2* uses Broyden's second Jacobian approximation, it
+ is known as Broyden's bad method.
+ - Method *anderson* uses (extended) Anderson mixing.
+ - Method *Krylov* uses Krylov approximation for inverse Jacobian. It
+ is suitable for large-scale problem.
+ - Method *diagbroyden* uses diagonal Broyden Jacobian approximation.
+ - Method *linearmixing* uses a scalar Jacobian approximation.
+ - Method *excitingmixing* uses a tuned diagonal Jacobian
+ approximation.
+
+ .. warning::
+
+ The algorithms implemented for methods *diagbroyden*,
+ *linearmixing* and *excitingmixing* may be useful for specific
+ problems, but whether they will work may depend strongly on the
+ problem.
+
+ .. versionadded:: 0.11.0
+
+ References
+ ----------
+ .. [1] More, Jorge J., Burton S. Garbow, and Kenneth E. Hillstrom.
+ 1980. User Guide for MINPACK-1.
+ .. [2] C. T. Kelley. 1995. Iterative Methods for Linear and Nonlinear
+ Equations. Society for Industrial and Applied Mathematics.
+ :doi:`10.1137/1.9781611970944`
+ .. [3] W. La Cruz, J.M. Martinez, M. Raydan.
+ Math. Comp. 75, 1429 (2006).
+
+ Examples
+ --------
+ The following functions define a system of nonlinear equations and its
+ jacobian.
+
+ >>> import numpy as np
+ >>> def fun(x):
+ ... return [x[0] + 0.5 * (x[0] - x[1])**3 - 1.0,
+ ... 0.5 * (x[1] - x[0])**3 + x[1]]
+
+ >>> def jac(x):
+ ... return np.array([[1 + 1.5 * (x[0] - x[1])**2,
+ ... -1.5 * (x[0] - x[1])**2],
+ ... [-1.5 * (x[1] - x[0])**2,
+ ... 1 + 1.5 * (x[1] - x[0])**2]])
+
+ A solution can be obtained as follows.
+
+ >>> from scipy import optimize
+ >>> sol = optimize.root(fun, [0, 0], jac=jac, method='hybr')
+ >>> sol.x
+ array([ 0.8411639, 0.1588361])
+
+ **Large problem**
+
+ Suppose that we needed to solve the following integrodifferential
+ equation on the square :math:`[0,1]\times[0,1]`:
+
+ .. math::
+
+ \nabla^2 P = 10 \left(\int_0^1\int_0^1\cosh(P)\,dx\,dy\right)^2
+
+ with :math:`P(x,1) = 1` and :math:`P=0` elsewhere on the boundary of
+ the square.
+
+ The solution can be found using the ``method='krylov'`` solver:
+
+ >>> from scipy import optimize
+ >>> # parameters
+ >>> nx, ny = 75, 75
+ >>> hx, hy = 1./(nx-1), 1./(ny-1)
+
+ >>> P_left, P_right = 0, 0
+ >>> P_top, P_bottom = 1, 0
+
+ >>> def residual(P):
+ ... d2x = np.zeros_like(P)
+ ... d2y = np.zeros_like(P)
+ ...
+ ... d2x[1:-1] = (P[2:] - 2*P[1:-1] + P[:-2]) / hx/hx
+ ... d2x[0] = (P[1] - 2*P[0] + P_left)/hx/hx
+ ... d2x[-1] = (P_right - 2*P[-1] + P[-2])/hx/hx
+ ...
+ ... d2y[:,1:-1] = (P[:,2:] - 2*P[:,1:-1] + P[:,:-2])/hy/hy
+ ... d2y[:,0] = (P[:,1] - 2*P[:,0] + P_bottom)/hy/hy
+ ... d2y[:,-1] = (P_top - 2*P[:,-1] + P[:,-2])/hy/hy
+ ...
+ ... return d2x + d2y - 10*np.cosh(P).mean()**2
+
+ >>> guess = np.zeros((nx, ny), float)
+ >>> sol = optimize.root(residual, guess, method='krylov')
+ >>> print('Residual: %g' % abs(residual(sol.x)).max())
+ Residual: 5.7972e-06 # may vary
+
+ >>> import matplotlib.pyplot as plt
+ >>> x, y = np.mgrid[0:1:(nx*1j), 0:1:(ny*1j)]
+ >>> plt.pcolormesh(x, y, sol.x, shading='gouraud')
+ >>> plt.colorbar()
+ >>> plt.show()
+
+ """
+ def _wrapped_fun(*fargs):
+ """
+ Wrapped `func` to track the number of times
+ the function has been called.
+ """
+ _wrapped_fun.nfev += 1
+ return fun(*fargs)
+
+ _wrapped_fun.nfev = 0
+
+ if not isinstance(args, tuple):
+ args = (args,)
+
+ meth = method.lower()
+ if options is None:
+ options = {}
+
+ if callback is not None and meth in ('hybr', 'lm'):
+ warn(f'Method {method} does not accept callback.',
+ RuntimeWarning, stacklevel=2)
+
+ # fun also returns the Jacobian
+ if not callable(jac) and meth in ('hybr', 'lm'):
+ if bool(jac):
+ fun = MemoizeJac(fun)
+ jac = fun.derivative
+ else:
+ jac = None
+
+ # set default tolerances
+ if tol is not None:
+ options = dict(options)
+ if meth in ('hybr', 'lm'):
+ options.setdefault('xtol', tol)
+ elif meth in ('df-sane',):
+ options.setdefault('ftol', tol)
+ elif meth in ('broyden1', 'broyden2', 'anderson', 'linearmixing',
+ 'diagbroyden', 'excitingmixing', 'krylov'):
+ options.setdefault('xtol', tol)
+ options.setdefault('xatol', np.inf)
+ options.setdefault('ftol', np.inf)
+ options.setdefault('fatol', np.inf)
+
+ if meth == 'hybr':
+ sol = _root_hybr(_wrapped_fun, x0, args=args, jac=jac, **options)
+ elif meth == 'lm':
+ sol = _root_leastsq(_wrapped_fun, x0, args=args, jac=jac, **options)
+ elif meth == 'df-sane':
+ _warn_jac_unused(jac, method)
+ sol = _root_df_sane(_wrapped_fun, x0, args=args, callback=callback,
+ **options)
+ elif meth in ('broyden1', 'broyden2', 'anderson', 'linearmixing',
+ 'diagbroyden', 'excitingmixing', 'krylov'):
+ _warn_jac_unused(jac, method)
+ sol = _root_nonlin_solve(_wrapped_fun, x0, args=args, jac=jac,
+ _method=meth, _callback=callback,
+ **options)
+ else:
+ raise ValueError(f'Unknown solver {method}')
+
+ sol.nfev = _wrapped_fun.nfev
+ return sol
+
+
+def _warn_jac_unused(jac, method):
+ if jac is not None:
+ warn(f'Method {method} does not use the jacobian (jac).',
+ RuntimeWarning, stacklevel=2)
+
+
+def _root_leastsq(fun, x0, args=(), jac=None,
+ col_deriv=0, xtol=1.49012e-08, ftol=1.49012e-08,
+ gtol=0.0, maxiter=0, eps=0.0, factor=100, diag=None,
+ **unknown_options):
+ """
+ Solve for least squares with Levenberg-Marquardt
+
+ Options
+ -------
+ col_deriv : bool
+ non-zero to specify that the Jacobian function computes derivatives
+ down the columns (faster, because there is no transpose operation).
+ ftol : float
+ Relative error desired in the sum of squares.
+ xtol : float
+ Relative error desired in the approximate solution.
+ gtol : float
+ Orthogonality desired between the function vector and the columns
+ of the Jacobian.
+ maxiter : int
+ The maximum number of calls to the function. If zero, then
+ 100*(N+1) is the maximum where N is the number of elements in x0.
+ eps : float
+ A suitable step length for the forward-difference approximation of
+ the Jacobian (for Dfun=None). If `eps` is less than the machine
+ precision, it is assumed that the relative errors in the functions
+ are of the order of the machine precision.
+ factor : float
+ A parameter determining the initial step bound
+ (``factor * || diag * x||``). Should be in interval ``(0.1, 100)``.
+ diag : sequence
+ N positive entries that serve as a scale factors for the variables.
+ """
+ nfev = 0
+ def _wrapped_fun(*fargs):
+ """
+ Wrapped `func` to track the number of times
+ the function has been called.
+ """
+ nonlocal nfev
+ nfev += 1
+ return fun(*fargs)
+
+ _check_unknown_options(unknown_options)
+ x, cov_x, info, msg, ier = leastsq(_wrapped_fun, x0, args=args,
+ Dfun=jac, full_output=True,
+ col_deriv=col_deriv, xtol=xtol,
+ ftol=ftol, gtol=gtol,
+ maxfev=maxiter, epsfcn=eps,
+ factor=factor, diag=diag)
+ sol = OptimizeResult(x=x, message=msg, status=ier,
+ success=ier in (1, 2, 3, 4), cov_x=cov_x,
+ fun=info.pop('fvec'), method="lm")
+ sol.update(info)
+ sol.nfev = nfev
+ return sol
+
+
+def _root_nonlin_solve(fun, x0, args=(), jac=None,
+ _callback=None, _method=None,
+ nit=None, disp=False, maxiter=None,
+ ftol=None, fatol=None, xtol=None, xatol=None,
+ tol_norm=None, line_search='armijo', jac_options=None,
+ **unknown_options):
+ _check_unknown_options(unknown_options)
+
+ f_tol = fatol
+ f_rtol = ftol
+ x_tol = xatol
+ x_rtol = xtol
+ verbose = disp
+ if jac_options is None:
+ jac_options = dict()
+
+ jacobian = {'broyden1': nonlin.BroydenFirst,
+ 'broyden2': nonlin.BroydenSecond,
+ 'anderson': nonlin.Anderson,
+ 'linearmixing': nonlin.LinearMixing,
+ 'diagbroyden': nonlin.DiagBroyden,
+ 'excitingmixing': nonlin.ExcitingMixing,
+ 'krylov': nonlin.KrylovJacobian
+ }[_method]
+
+ if args:
+ if jac is True:
+ def f(x):
+ return fun(x, *args)[0]
+ else:
+ def f(x):
+ return fun(x, *args)
+ else:
+ f = fun
+
+ x, info = nonlin.nonlin_solve(f, x0, jacobian=jacobian(**jac_options),
+ iter=nit, verbose=verbose,
+ maxiter=maxiter, f_tol=f_tol,
+ f_rtol=f_rtol, x_tol=x_tol,
+ x_rtol=x_rtol, tol_norm=tol_norm,
+ line_search=line_search,
+ callback=_callback, full_output=True,
+ raise_exception=False)
+ sol = OptimizeResult(x=x, method=_method)
+ sol.update(info)
+ return sol
+
+def _root_broyden1_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ Initial guess for the Jacobian is (-1/alpha).
+ reduction_method : str or tuple, optional
+ Method used in ensuring that the rank of the Broyden
+ matrix stays low. Can either be a string giving the
+ name of the method, or a tuple of the form ``(method,
+ param1, param2, ...)`` that gives the name of the
+ method and values for additional parameters.
+
+ Methods available:
+
+ - ``restart``: drop all matrix columns. Has no extra parameters.
+ - ``simple``: drop oldest matrix column. Has no extra parameters.
+ - ``svd``: keep only the most significant SVD components.
+ Takes an extra parameter, ``to_retain``, which determines the
+ number of SVD components to retain when rank reduction is done.
+ Default is ``max_rank - 2``.
+
+ max_rank : int, optional
+ Maximum rank for the Broyden matrix.
+ Default is infinity (i.e., no rank reduction).
+
+ Examples
+ --------
+ >>> def func(x):
+ ... return np.cos(x) + x[::-1] - [1, 2, 3, 4]
+ ...
+ >>> from scipy import optimize
+ >>> res = optimize.root(func, [1, 1, 1, 1], method='broyden1', tol=1e-14)
+ >>> x = res.x
+ >>> x
+ array([4.04674914, 3.91158389, 2.71791677, 1.61756251])
+ >>> np.cos(x) + x[::-1]
+ array([1., 2., 3., 4.])
+
+ """
+ pass
+
+
+def _root_broyden2_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ Initial guess for the Jacobian is (-1/alpha).
+ reduction_method : str or tuple, optional
+ Method used in ensuring that the rank of the Broyden
+ matrix stays low. Can either be a string giving the
+ name of the method, or a tuple of the form ``(method,
+ param1, param2, ...)`` that gives the name of the
+ method and values for additional parameters.
+
+ Methods available:
+
+ - ``restart``: drop all matrix columns. Has no extra parameters.
+ - ``simple``: drop oldest matrix column. Has no extra parameters.
+ - ``svd``: keep only the most significant SVD components.
+ Takes an extra parameter, ``to_retain``, which determines the
+ number of SVD components to retain when rank reduction is done.
+ Default is ``max_rank - 2``.
+
+ max_rank : int, optional
+ Maximum rank for the Broyden matrix.
+ Default is infinity (i.e., no rank reduction).
+ """
+ pass
+
+
+def _root_anderson_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ Initial guess for the Jacobian is (-1/alpha).
+ M : float, optional
+ Number of previous vectors to retain. Defaults to 5.
+ w0 : float, optional
+ Regularization parameter for numerical stability.
+ Compared to unity, good values of the order of 0.01.
+ """
+ pass
+
+def _root_linearmixing_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ initial guess for the jacobian is (-1/alpha).
+ """
+ pass
+
+def _root_diagbroyden_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ initial guess for the jacobian is (-1/alpha).
+ """
+ pass
+
+def _root_excitingmixing_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ alpha : float, optional
+ Initial Jacobian approximation is (-1/alpha).
+ alphamax : float, optional
+ The entries of the diagonal Jacobian are kept in the range
+ ``[alpha, alphamax]``.
+ """
+ pass
+
+def _root_krylov_doc():
+ """
+ Options
+ -------
+ nit : int, optional
+ Number of iterations to make. If omitted (default), make as many
+ as required to meet tolerances.
+ disp : bool, optional
+ Print status to stdout on every iteration.
+ maxiter : int, optional
+ Maximum number of iterations to make.
+ ftol : float, optional
+ Relative tolerance for the residual. If omitted, not used.
+ fatol : float, optional
+ Absolute tolerance (in max-norm) for the residual.
+ If omitted, default is 6e-6.
+ xtol : float, optional
+ Relative minimum step size. If omitted, not used.
+ xatol : float, optional
+ Absolute minimum step size, as determined from the Jacobian
+ approximation. If the step size is smaller than this, optimization
+ is terminated as successful. If omitted, not used.
+ tol_norm : function(vector) -> scalar, optional
+ Norm to use in convergence check. Default is the maximum norm.
+ line_search : {None, 'armijo' (default), 'wolfe'}, optional
+ Which type of a line search to use to determine the step size in
+ the direction given by the Jacobian approximation. Defaults to
+ 'armijo'.
+ jac_options : dict, optional
+ Options for the respective Jacobian approximation.
+
+ rdiff : float, optional
+ Relative step size to use in numerical differentiation.
+ method : str or callable, optional
+ Krylov method to use to approximate the Jacobian. Can be a string,
+ or a function implementing the same interface as the iterative
+ solvers in `scipy.sparse.linalg`. If a string, needs to be one of:
+ ``'lgmres'``, ``'gmres'``, ``'bicgstab'``, ``'cgs'``, ``'minres'``,
+ ``'tfqmr'``.
+
+ The default is `scipy.sparse.linalg.lgmres`.
+ inner_M : LinearOperator or InverseJacobian
+ Preconditioner for the inner Krylov iteration.
+ Note that you can use also inverse Jacobians as (adaptive)
+ preconditioners. For example,
+
+ >>> jac = BroydenFirst()
+ >>> kjac = KrylovJacobian(inner_M=jac.inverse).
+
+ If the preconditioner has a method named 'update', it will
+ be called as ``update(x, f)`` after each nonlinear step,
+ with ``x`` giving the current point, and ``f`` the current
+ function value.
+ inner_rtol, inner_atol, inner_callback, ...
+ Parameters to pass on to the "inner" Krylov solver.
+
+ For a full list of options, see the documentation for the
+ solver you are using. By default this is `scipy.sparse.linalg.lgmres`.
+ If the solver has been overridden through `method`, see the documentation
+ for that solver instead.
+ To use an option for that solver, prepend ``inner_`` to it.
+ For example, to control the ``rtol`` argument to the solver,
+ set the `inner_rtol` option here.
+
+ outer_k : int, optional
+ Size of the subspace kept across LGMRES nonlinear
+ iterations.
+
+ See `scipy.sparse.linalg.lgmres` for details.
+ """
+ pass
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_root_scalar.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_root_scalar.py
new file mode 100644
index 0000000000000000000000000000000000000000..b19459f7128008910d44e4a0a50b0880121f6edf
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_root_scalar.py
@@ -0,0 +1,538 @@
+"""
+Unified interfaces to root finding algorithms for real or complex
+scalar functions.
+
+Functions
+---------
+- root : find a root of a scalar function.
+"""
+import numpy as np
+
+from . import _zeros_py as optzeros
+from ._numdiff import approx_derivative
+
+__all__ = ['root_scalar']
+
+ROOT_SCALAR_METHODS = ['bisect', 'brentq', 'brenth', 'ridder', 'toms748',
+ 'newton', 'secant', 'halley']
+
+
+class MemoizeDer:
+ """Decorator that caches the value and derivative(s) of function each
+ time it is called.
+
+ This is a simplistic memoizer that calls and caches a single value
+ of ``f(x, *args)``.
+ It assumes that `args` does not change between invocations.
+ It supports the use case of a root-finder where `args` is fixed,
+ `x` changes, and only rarely, if at all, does x assume the same value
+ more than once."""
+ def __init__(self, fun):
+ self.fun = fun
+ self.vals = None
+ self.x = None
+ self.n_calls = 0
+
+ def __call__(self, x, *args):
+ r"""Calculate f or use cached value if available"""
+ # Derivative may be requested before the function itself, always check
+ if self.vals is None or x != self.x:
+ fg = self.fun(x, *args)
+ self.x = x
+ self.n_calls += 1
+ self.vals = fg[:]
+ return self.vals[0]
+
+ def fprime(self, x, *args):
+ r"""Calculate f' or use a cached value if available"""
+ if self.vals is None or x != self.x:
+ self(x, *args)
+ return self.vals[1]
+
+ def fprime2(self, x, *args):
+ r"""Calculate f'' or use a cached value if available"""
+ if self.vals is None or x != self.x:
+ self(x, *args)
+ return self.vals[2]
+
+ def ncalls(self):
+ return self.n_calls
+
+
+def root_scalar(f, args=(), method=None, bracket=None,
+ fprime=None, fprime2=None,
+ x0=None, x1=None,
+ xtol=None, rtol=None, maxiter=None,
+ options=None):
+ """
+ Find a root of a scalar function.
+
+ Parameters
+ ----------
+ f : callable
+ A function to find a root of.
+
+ Suppose the callable has signature ``f0(x, *my_args, **my_kwargs)``, where
+ ``my_args`` and ``my_kwargs`` are required positional and keyword arguments.
+ Rather than passing ``f0`` as the callable, wrap it to accept
+ only ``x``; e.g., pass ``fun=lambda x: f0(x, *my_args, **my_kwargs)`` as the
+ callable, where ``my_args`` (tuple) and ``my_kwargs`` (dict) have been
+ gathered before invoking this function.
+ args : tuple, optional
+ Extra arguments passed to the objective function and its derivative(s).
+ method : str, optional
+ Type of solver. Should be one of
+
+ - 'bisect' :ref:`(see here) `
+ - 'brentq' :ref:`(see here) `
+ - 'brenth' :ref:`(see here) `
+ - 'ridder' :ref:`(see here) `
+ - 'toms748' :ref:`(see here) `
+ - 'newton' :ref:`(see here) `
+ - 'secant' :ref:`(see here) `
+ - 'halley' :ref:`(see here) `
+
+ bracket: A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ x0 : float, optional
+ Initial guess.
+ x1 : float, optional
+ A second guess.
+ fprime : bool or callable, optional
+ If `fprime` is a boolean and is True, `f` is assumed to return the
+ value of the objective function and of the derivative.
+ `fprime` can also be a callable returning the derivative of `f`. In
+ this case, it must accept the same arguments as `f`.
+ fprime2 : bool or callable, optional
+ If `fprime2` is a boolean and is True, `f` is assumed to return the
+ value of the objective function and of the
+ first and second derivatives.
+ `fprime2` can also be a callable returning the second derivative of `f`.
+ In this case, it must accept the same arguments as `f`.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options : dict, optional
+ A dictionary of solver options. E.g., ``k``, see
+ :obj:`show_options()` for details.
+
+ Returns
+ -------
+ sol : RootResults
+ The solution represented as a ``RootResults`` object.
+ Important attributes are: ``root`` the solution , ``converged`` a
+ boolean flag indicating if the algorithm exited successfully and
+ ``flag`` which describes the cause of the termination. See
+ `RootResults` for a description of other attributes.
+
+ See also
+ --------
+ show_options : Additional options accepted by the solvers
+ root : Find a root of a vector function.
+
+ Notes
+ -----
+ This section describes the available solvers that can be selected by the
+ 'method' parameter.
+
+ The default is to use the best method available for the situation
+ presented.
+ If a bracket is provided, it may use one of the bracketing methods.
+ If a derivative and an initial value are specified, it may
+ select one of the derivative-based methods.
+ If no method is judged applicable, it will raise an Exception.
+
+ Arguments for each method are as follows (x=required, o=optional).
+
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | method | f | args | bracket | x0 | x1 | fprime | fprime2 | xtol | rtol | maxiter | options |
+ +===============================================+===+======+=========+====+====+========+=========+======+======+=========+=========+
+ | :ref:`bisect ` | x | o | x | | | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`brentq ` | x | o | x | | | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`brenth ` | x | o | x | | | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`ridder ` | x | o | x | | | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`toms748 ` | x | o | x | | | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`secant ` | x | o | | x | o | | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`newton ` | x | o | | x | | o | | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+ | :ref:`halley ` | x | o | | x | | x | x | o | o | o | o |
+ +-----------------------------------------------+---+------+---------+----+----+--------+---------+------+------+---------+---------+
+
+ Examples
+ --------
+
+ Find the root of a simple cubic
+
+ >>> from scipy import optimize
+ >>> def f(x):
+ ... return (x**3 - 1) # only one real root at x = 1
+
+ >>> def fprime(x):
+ ... return 3*x**2
+
+ The `brentq` method takes as input a bracket
+
+ >>> sol = optimize.root_scalar(f, bracket=[0, 3], method='brentq')
+ >>> sol.root, sol.iterations, sol.function_calls
+ (1.0, 10, 11)
+
+ The `newton` method takes as input a single point and uses the
+ derivative(s).
+
+ >>> sol = optimize.root_scalar(f, x0=0.2, fprime=fprime, method='newton')
+ >>> sol.root, sol.iterations, sol.function_calls
+ (1.0, 11, 22)
+
+ The function can provide the value and derivative(s) in a single call.
+
+ >>> def f_p_pp(x):
+ ... return (x**3 - 1), 3*x**2, 6*x
+
+ >>> sol = optimize.root_scalar(
+ ... f_p_pp, x0=0.2, fprime=True, method='newton'
+ ... )
+ >>> sol.root, sol.iterations, sol.function_calls
+ (1.0, 11, 11)
+
+ >>> sol = optimize.root_scalar(
+ ... f_p_pp, x0=0.2, fprime=True, fprime2=True, method='halley'
+ ... )
+ >>> sol.root, sol.iterations, sol.function_calls
+ (1.0, 7, 8)
+
+
+ """ # noqa: E501
+ if not isinstance(args, tuple):
+ args = (args,)
+
+ if options is None:
+ options = {}
+
+ # fun also returns the derivative(s)
+ is_memoized = False
+ if fprime2 is not None and not callable(fprime2):
+ if bool(fprime2):
+ f = MemoizeDer(f)
+ is_memoized = True
+ fprime2 = f.fprime2
+ fprime = f.fprime
+ else:
+ fprime2 = None
+ if fprime is not None and not callable(fprime):
+ if bool(fprime):
+ f = MemoizeDer(f)
+ is_memoized = True
+ fprime = f.fprime
+ else:
+ fprime = None
+
+ # respect solver-specific default tolerances - only pass in if actually set
+ kwargs = {}
+ for k in ['xtol', 'rtol', 'maxiter']:
+ v = locals().get(k)
+ if v is not None:
+ kwargs[k] = v
+
+ # Set any solver-specific options
+ if options:
+ kwargs.update(options)
+ # Always request full_output from the underlying method as _root_scalar
+ # always returns a RootResults object
+ kwargs.update(full_output=True, disp=False)
+
+ # Pick a method if not specified.
+ # Use the "best" method available for the situation.
+ if not method:
+ if bracket is not None:
+ method = 'brentq'
+ elif x0 is not None:
+ if fprime:
+ if fprime2:
+ method = 'halley'
+ else:
+ method = 'newton'
+ elif x1 is not None:
+ method = 'secant'
+ else:
+ method = 'newton'
+ if not method:
+ raise ValueError('Unable to select a solver as neither bracket '
+ 'nor starting point provided.')
+
+ meth = method.lower()
+ map2underlying = {'halley': 'newton', 'secant': 'newton'}
+
+ try:
+ methodc = getattr(optzeros, map2underlying.get(meth, meth))
+ except AttributeError as e:
+ raise ValueError(f'Unknown solver {meth}') from e
+
+ if meth in ['bisect', 'ridder', 'brentq', 'brenth', 'toms748']:
+ if not isinstance(bracket, list | tuple | np.ndarray):
+ raise ValueError(f'Bracket needed for {method}')
+
+ a, b = bracket[:2]
+ try:
+ r, sol = methodc(f, a, b, args=args, **kwargs)
+ except ValueError as e:
+ # gh-17622 fixed some bugs in low-level solvers by raising an error
+ # (rather than returning incorrect results) when the callable
+ # returns a NaN. It did so by wrapping the callable rather than
+ # modifying compiled code, so the iteration count is not available.
+ if hasattr(e, "_x"):
+ sol = optzeros.RootResults(root=e._x,
+ iterations=np.nan,
+ function_calls=e._function_calls,
+ flag=str(e), method=method)
+ else:
+ raise
+
+ elif meth in ['secant']:
+ if x0 is None:
+ raise ValueError(f'x0 must not be None for {method}')
+ if 'xtol' in kwargs:
+ kwargs['tol'] = kwargs.pop('xtol')
+ r, sol = methodc(f, x0, args=args, fprime=None, fprime2=None,
+ x1=x1, **kwargs)
+ elif meth in ['newton']:
+ if x0 is None:
+ raise ValueError(f'x0 must not be None for {method}')
+ if not fprime:
+ # approximate fprime with finite differences
+
+ def fprime(x, *args):
+ # `root_scalar` doesn't actually seem to support vectorized
+ # use of `newton`. In that case, `approx_derivative` will
+ # always get scalar input. Nonetheless, it always returns an
+ # array, so we extract the element to produce scalar output.
+ # Similarly, `approx_derivative` always passes array input, so
+ # we extract the element to ensure the user's function gets
+ # scalar input.
+ def f_wrapped(x, *args):
+ return f(x[0], *args)
+ return approx_derivative(f_wrapped, x, method='2-point', args=args)[0]
+
+ if 'xtol' in kwargs:
+ kwargs['tol'] = kwargs.pop('xtol')
+ r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=None,
+ **kwargs)
+ elif meth in ['halley']:
+ if x0 is None:
+ raise ValueError(f'x0 must not be None for {method}')
+ if not fprime:
+ raise ValueError(f'fprime must be specified for {method}')
+ if not fprime2:
+ raise ValueError(f'fprime2 must be specified for {method}')
+ if 'xtol' in kwargs:
+ kwargs['tol'] = kwargs.pop('xtol')
+ r, sol = methodc(f, x0, args=args, fprime=fprime, fprime2=fprime2, **kwargs)
+ else:
+ raise ValueError(f'Unknown solver {method}')
+
+ if is_memoized:
+ # Replace the function_calls count with the memoized count.
+ # Avoids double and triple-counting.
+ n_calls = f.n_calls
+ sol.function_calls = n_calls
+
+ return sol
+
+
+def _root_scalar_brentq_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ bracket: A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options: dict, optional
+ Specifies any method-specific options not covered above
+
+ """
+ pass
+
+
+def _root_scalar_brenth_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ bracket: A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+def _root_scalar_toms748_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ bracket: A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+
+def _root_scalar_secant_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ x0 : float, required
+ Initial guess.
+ x1 : float, optional
+ A second guess. Must be different from `x0`. If not specified,
+ a value near `x0` will be chosen.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+
+def _root_scalar_newton_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function and its derivative.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ x0 : float, required
+ Initial guess.
+ fprime : bool or callable, optional
+ If `fprime` is a boolean and is True, `f` is assumed to return the
+ value of derivative along with the objective function.
+ `fprime` can also be a callable returning the derivative of `f`. In
+ this case, it must accept the same arguments as `f`.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+
+def _root_scalar_halley_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function and its derivatives.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ x0 : float, required
+ Initial guess.
+ fprime : bool or callable, required
+ If `fprime` is a boolean and is True, `f` is assumed to return the
+ value of derivative along with the objective function.
+ `fprime` can also be a callable returning the derivative of `f`. In
+ this case, it must accept the same arguments as `f`.
+ fprime2 : bool or callable, required
+ If `fprime2` is a boolean and is True, `f` is assumed to return the
+ value of 1st and 2nd derivatives along with the objective function.
+ `fprime2` can also be a callable returning the 2nd derivative of `f`.
+ In this case, it must accept the same arguments as `f`.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+
+def _root_scalar_ridder_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ bracket: A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
+
+
+def _root_scalar_bisect_doc():
+ r"""
+ Options
+ -------
+ args : tuple, optional
+ Extra arguments passed to the objective function.
+ bracket: A sequence of 2 floats, optional
+ An interval bracketing a root. ``f(x, *args)`` must have different
+ signs at the two endpoints.
+ xtol : float, optional
+ Tolerance (absolute) for termination.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ maxiter : int, optional
+ Maximum number of iterations.
+ options: dict, optional
+ Specifies any method-specific options not covered above.
+
+ """
+ pass
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo.py
new file mode 100644
index 0000000000000000000000000000000000000000..fb8c8e33027491fa95b32243f75248aec2b0bd82
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo.py
@@ -0,0 +1,1626 @@
+"""shgo: The simplicial homology global optimisation algorithm."""
+from collections import namedtuple
+import time
+import logging
+import warnings
+import sys
+
+import numpy as np
+
+from scipy import spatial
+from scipy.optimize import OptimizeResult, minimize, Bounds
+from scipy.optimize._optimize import MemoizeJac
+from scipy.optimize._constraints import new_bounds_to_old
+from scipy.optimize._minimize import standardize_constraints
+from scipy._lib._util import _FunctionWrapper
+
+from scipy.optimize._shgo_lib._complex import Complex
+
+__all__ = ['shgo']
+
+
+def shgo(
+ func, bounds, args=(), constraints=None, n=100, iters=1, callback=None,
+ minimizer_kwargs=None, options=None, sampling_method='simplicial', *,
+ workers=1
+):
+ """
+ Finds the global minimum of a function using SHG optimization.
+
+ SHGO stands for "simplicial homology global optimization".
+
+ Parameters
+ ----------
+ func : callable
+ The objective function to be minimized. Must be in the form
+ ``f(x, *args)``, where ``x`` is the argument in the form of a 1-D array
+ and ``args`` is a tuple of any additional fixed parameters needed to
+ completely specify the function.
+ bounds : sequence or `Bounds`
+ Bounds for variables. There are two ways to specify the bounds:
+
+ 1. Instance of `Bounds` class.
+ 2. Sequence of ``(min, max)`` pairs for each element in `x`.
+
+ args : tuple, optional
+ Any additional fixed parameters needed to completely specify the
+ objective function.
+ constraints : {Constraint, dict} or List of {Constraint, dict}, optional
+ Constraints definition. Only for COBYLA, COBYQA, SLSQP and trust-constr.
+ See the tutorial [5]_ for further details on specifying constraints.
+
+ .. note::
+
+ Only COBYLA, COBYQA, SLSQP, and trust-constr local minimize methods
+ currently support constraint arguments. If the ``constraints``
+ sequence used in the local optimization problem is not defined in
+ ``minimizer_kwargs`` and a constrained method is used then the
+ global ``constraints`` will be used.
+ (Defining a ``constraints`` sequence in ``minimizer_kwargs``
+ means that ``constraints`` will not be added so if equality
+ constraints and so forth need to be added then the inequality
+ functions in ``constraints`` need to be added to
+ ``minimizer_kwargs`` too).
+ COBYLA only supports inequality constraints.
+
+ .. versionchanged:: 1.11.0
+
+ ``constraints`` accepts `NonlinearConstraint`, `LinearConstraint`.
+
+ n : int, optional
+ Number of sampling points used in the construction of the simplicial
+ complex. For the default ``simplicial`` sampling method 2**dim + 1
+ sampling points are generated instead of the default ``n=100``. For all
+ other specified values `n` sampling points are generated. For
+ ``sobol``, ``halton`` and other arbitrary `sampling_methods` ``n=100`` or
+ another specified number of sampling points are generated.
+ iters : int, optional
+ Number of iterations used in the construction of the simplicial
+ complex. Default is 1.
+ callback : callable, optional
+ Called after each iteration, as ``callback(xk)``, where ``xk`` is the
+ current parameter vector.
+ minimizer_kwargs : dict, optional
+ Extra keyword arguments to be passed to the minimizer
+ ``scipy.optimize.minimize``. Some important options could be:
+
+ method : str
+ The minimization method. If not given, chosen to be one of
+ BFGS, L-BFGS-B, SLSQP, depending on whether or not the
+ problem has constraints or bounds.
+ args : tuple
+ Extra arguments passed to the objective function (``func``) and
+ its derivatives (Jacobian, Hessian).
+ options : dict, optional
+ Note that by default the tolerance is specified as
+ ``{ftol: 1e-12}``
+
+ options : dict, optional
+ A dictionary of solver options. Many of the options specified for the
+ global routine are also passed to the ``scipy.optimize.minimize``
+ routine. The options that are also passed to the local routine are
+ marked with "(L)".
+
+ Stopping criteria, the algorithm will terminate if any of the specified
+ criteria are met. However, the default algorithm does not require any
+ to be specified:
+
+ maxfev : int (L)
+ Maximum number of function evaluations in the feasible domain.
+ (Note only methods that support this option will terminate
+ the routine at precisely exact specified value. Otherwise the
+ criterion will only terminate during a global iteration)
+ f_min : float
+ Specify the minimum objective function value, if it is known.
+ f_tol : float
+ Precision goal for the value of f in the stopping
+ criterion. Note that the global routine will also
+ terminate if a sampling point in the global routine is
+ within this tolerance.
+ maxiter : int
+ Maximum number of iterations to perform.
+ maxev : int
+ Maximum number of sampling evaluations to perform (includes
+ searching in infeasible points).
+ maxtime : float
+ Maximum processing runtime allowed
+ minhgrd : int
+ Minimum homology group rank differential. The homology group of the
+ objective function is calculated (approximately) during every
+ iteration. The rank of this group has a one-to-one correspondence
+ with the number of locally convex subdomains in the objective
+ function (after adequate sampling points each of these subdomains
+ contain a unique global minimum). If the difference in the hgr is 0
+ between iterations for ``maxhgrd`` specified iterations the
+ algorithm will terminate.
+
+ Objective function knowledge:
+
+ symmetry : list or bool
+ Specify if the objective function contains symmetric variables.
+ The search space (and therefore performance) is decreased by up to
+ O(n!) times in the fully symmetric case. If `True` is specified
+ then all variables will be set symmetric to the first variable.
+ Default
+ is set to False.
+
+ E.g. f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2
+
+ In this equation x_2 and x_3 are symmetric to x_1, while x_5 and
+ x_6 are symmetric to x_4, this can be specified to the solver as::
+
+ symmetry = [0, # Variable 1
+ 0, # symmetric to variable 1
+ 0, # symmetric to variable 1
+ 3, # Variable 4
+ 3, # symmetric to variable 4
+ 3, # symmetric to variable 4
+ ]
+
+ jac : bool or callable, optional
+ Jacobian (gradient) of objective function. Only for CG, BFGS,
+ Newton-CG, L-BFGS-B, TNC, SLSQP, dogleg, trust-ncg. If ``jac`` is a
+ boolean and is True, ``fun`` is assumed to return the gradient
+ along with the objective function. If False, the gradient will be
+ estimated numerically. ``jac`` can also be a callable returning the
+ gradient of the objective. In this case, it must accept the same
+ arguments as ``fun``. (Passed to `scipy.optimize.minimize`
+ automatically)
+
+ hess, hessp : callable, optional
+ Hessian (matrix of second-order derivatives) of objective function
+ or Hessian of objective function times an arbitrary vector p.
+ Only for Newton-CG, dogleg, trust-ncg. Only one of ``hessp`` or
+ ``hess`` needs to be given. If ``hess`` is provided, then
+ ``hessp`` will be ignored. If neither ``hess`` nor ``hessp`` is
+ provided, then the Hessian product will be approximated using
+ finite differences on ``jac``. ``hessp`` must compute the Hessian
+ times an arbitrary vector. (Passed to `scipy.optimize.minimize`
+ automatically)
+
+ Algorithm settings:
+
+ minimize_every_iter : bool
+ If True then promising global sampling points will be passed to a
+ local minimization routine every iteration. If False then only the
+ final minimizer pool will be run. Defaults to True.
+
+ local_iter : int
+ Only evaluate a few of the best minimizer pool candidates every
+ iteration. If False all potential points are passed to the local
+ minimization routine.
+
+ infty_constraints : bool
+ If True then any sampling points generated which are outside will
+ the feasible domain will be saved and given an objective function
+ value of ``inf``. If False then these points will be discarded.
+ Using this functionality could lead to higher performance with
+ respect to function evaluations before the global minimum is found,
+ specifying False will use less memory at the cost of a slight
+ decrease in performance. Defaults to True.
+
+ Feedback:
+
+ disp : bool (L)
+ Set to True to print convergence messages.
+
+ sampling_method : str or function, optional
+ Current built in sampling method options are ``halton``, ``sobol`` and
+ ``simplicial``. The default ``simplicial`` provides
+ the theoretical guarantee of convergence to the global minimum in
+ finite time. ``halton`` and ``sobol`` method are faster in terms of
+ sampling point generation at the cost of the loss of
+ guaranteed convergence. It is more appropriate for most "easier"
+ problems where the convergence is relatively fast.
+ User defined sampling functions must accept two arguments of ``n``
+ sampling points of dimension ``dim`` per call and output an array of
+ sampling points with shape `n x dim`.
+
+ workers : int or map-like callable, optional
+ Sample and run the local serial minimizations in parallel.
+ Supply -1 to use all available CPU cores, or an int to use
+ that many Processes (uses `multiprocessing.Pool `).
+
+ Alternatively supply a map-like callable, such as
+ `multiprocessing.Pool.map` for parallel evaluation.
+ This evaluation is carried out as ``workers(func, iterable)``.
+ Requires that `func` be pickleable.
+
+ .. versionadded:: 1.11.0
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as a `OptimizeResult` object.
+ Important attributes are:
+ ``x`` the solution array corresponding to the global minimum,
+ ``fun`` the function output at the global solution,
+ ``xl`` an ordered list of local minima solutions,
+ ``funl`` the function output at the corresponding local solutions,
+ ``success`` a Boolean flag indicating if the optimizer exited
+ successfully,
+ ``message`` which describes the cause of the termination,
+ ``nfev`` the total number of objective function evaluations including
+ the sampling calls,
+ ``nlfev`` the total number of objective function evaluations
+ culminating from all local search optimizations,
+ ``nit`` number of iterations performed by the global routine.
+
+ Notes
+ -----
+ Global optimization using simplicial homology global optimization [1]_.
+ Appropriate for solving general purpose NLP and blackbox optimization
+ problems to global optimality (low-dimensional problems).
+
+ In general, the optimization problems are of the form::
+
+ minimize f(x) subject to
+
+ g_i(x) >= 0, i = 1,...,m
+ h_j(x) = 0, j = 1,...,p
+
+ where x is a vector of one or more variables. ``f(x)`` is the objective
+ function ``R^n -> R``, ``g_i(x)`` are the inequality constraints, and
+ ``h_j(x)`` are the equality constraints.
+
+ Optionally, the lower and upper bounds for each element in x can also be
+ specified using the `bounds` argument.
+
+ While most of the theoretical advantages of SHGO are only proven for when
+ ``f(x)`` is a Lipschitz smooth function, the algorithm is also proven to
+ converge to the global optimum for the more general case where ``f(x)`` is
+ non-continuous, non-convex and non-smooth, if the default sampling method
+ is used [1]_.
+
+ The local search method may be specified using the ``minimizer_kwargs``
+ parameter which is passed on to ``scipy.optimize.minimize``. By default,
+ the ``SLSQP`` method is used. In general, it is recommended to use the
+ ``SLSQP``, ``COBYLA``, or ``COBYQA`` local minimization if inequality
+ constraints are defined for the problem since the other methods do not use
+ constraints.
+
+ The ``halton`` and ``sobol`` method points are generated using
+ `scipy.stats.qmc`. Any other QMC method could be used.
+
+ References
+ ----------
+ .. [1] Endres, SC, Sandrock, C, Focke, WW (2018) "A simplicial homology
+ algorithm for lipschitz optimisation", Journal of Global
+ Optimization.
+ .. [2] Joe, SW and Kuo, FY (2008) "Constructing Sobol' sequences with
+ better two-dimensional projections", SIAM J. Sci. Comput. 30,
+ 2635-2654.
+ .. [3] Hock, W and Schittkowski, K (1981) "Test examples for nonlinear
+ programming codes", Lecture Notes in Economics and Mathematical
+ Systems, 187. Springer-Verlag, New York.
+ http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf
+ .. [4] Wales, DJ (2015) "Perspective: Insight into reaction coordinates and
+ dynamics from the potential energy landscape",
+ Journal of Chemical Physics, 142(13), 2015.
+ .. [5] https://docs.scipy.org/doc/scipy/tutorial/optimize.html#constrained-minimization-of-multivariate-scalar-functions-minimize
+
+ Examples
+ --------
+ First consider the problem of minimizing the Rosenbrock function, `rosen`:
+
+ >>> from scipy.optimize import rosen, shgo
+ >>> bounds = [(0,2), (0, 2), (0, 2), (0, 2), (0, 2)]
+ >>> result = shgo(rosen, bounds)
+ >>> result.x, result.fun
+ (array([1., 1., 1., 1., 1.]), 2.920392374190081e-18)
+
+ Note that bounds determine the dimensionality of the objective
+ function and is therefore a required input, however you can specify
+ empty bounds using ``None`` or objects like ``np.inf`` which will be
+ converted to large float numbers.
+
+ >>> bounds = [(None, None), ]*4
+ >>> result = shgo(rosen, bounds)
+ >>> result.x
+ array([0.99999851, 0.99999704, 0.99999411, 0.9999882 ])
+
+ Next, we consider the Eggholder function, a problem with several local
+ minima and one global minimum. We will demonstrate the use of arguments and
+ the capabilities of `shgo`.
+ (https://en.wikipedia.org/wiki/Test_functions_for_optimization)
+
+ >>> import numpy as np
+ >>> def eggholder(x):
+ ... return (-(x[1] + 47.0)
+ ... * np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0))))
+ ... - x[0] * np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0))))
+ ... )
+ ...
+ >>> bounds = [(-512, 512), (-512, 512)]
+
+ `shgo` has built-in low discrepancy sampling sequences. First, we will
+ input 64 initial sampling points of the *Sobol'* sequence:
+
+ >>> result = shgo(eggholder, bounds, n=64, sampling_method='sobol')
+ >>> result.x, result.fun
+ (array([512. , 404.23180824]), -959.6406627208397)
+
+ `shgo` also has a return for any other local minima that was found, these
+ can be called using:
+
+ >>> result.xl
+ array([[ 512. , 404.23180824],
+ [ 283.0759062 , -487.12565635],
+ [-294.66820039, -462.01964031],
+ [-105.87688911, 423.15323845],
+ [-242.97926 , 274.38030925],
+ [-506.25823477, 6.3131022 ],
+ [-408.71980731, -156.10116949],
+ [ 150.23207937, 301.31376595],
+ [ 91.00920901, -391.283763 ],
+ [ 202.89662724, -269.38043241],
+ [ 361.66623976, -106.96493868],
+ [-219.40612786, -244.06020508]])
+
+ >>> result.funl
+ array([-959.64066272, -718.16745962, -704.80659592, -565.99778097,
+ -559.78685655, -557.36868733, -507.87385942, -493.9605115 ,
+ -426.48799655, -421.15571437, -419.31194957, -410.98477763])
+
+ These results are useful in applications where there are many global minima
+ and the values of other global minima are desired or where the local minima
+ can provide insight into the system (for example morphologies
+ in physical chemistry [4]_).
+
+ If we want to find a larger number of local minima, we can increase the
+ number of sampling points or the number of iterations. We'll increase the
+ number of sampling points to 64 and the number of iterations from the
+ default of 1 to 3. Using ``simplicial`` this would have given us
+ 64 x 3 = 192 initial sampling points.
+
+ >>> result_2 = shgo(eggholder,
+ ... bounds, n=64, iters=3, sampling_method='sobol')
+ >>> len(result.xl), len(result_2.xl)
+ (12, 23)
+
+ Note the difference between, e.g., ``n=192, iters=1`` and ``n=64,
+ iters=3``.
+ In the first case the promising points contained in the minimiser pool
+ are processed only once. In the latter case it is processed every 64
+ sampling points for a total of 3 times.
+
+ To demonstrate solving problems with non-linear constraints consider the
+ following example from Hock and Schittkowski problem 73 (cattle-feed)
+ [3]_::
+
+ minimize: f = 24.55 * x_1 + 26.75 * x_2 + 39 * x_3 + 40.50 * x_4
+
+ subject to: 2.3 * x_1 + 5.6 * x_2 + 11.1 * x_3 + 1.3 * x_4 - 5 >= 0,
+
+ 12 * x_1 + 11.9 * x_2 + 41.8 * x_3 + 52.1 * x_4 - 21
+ -1.645 * sqrt(0.28 * x_1**2 + 0.19 * x_2**2 +
+ 20.5 * x_3**2 + 0.62 * x_4**2) >= 0,
+
+ x_1 + x_2 + x_3 + x_4 - 1 == 0,
+
+ 1 >= x_i >= 0 for all i
+
+ The approximate answer given in [3]_ is::
+
+ f([0.6355216, -0.12e-11, 0.3127019, 0.05177655]) = 29.894378
+
+ >>> def f(x): # (cattle-feed)
+ ... return 24.55*x[0] + 26.75*x[1] + 39*x[2] + 40.50*x[3]
+ ...
+ >>> def g1(x):
+ ... return 2.3*x[0] + 5.6*x[1] + 11.1*x[2] + 1.3*x[3] - 5 # >=0
+ ...
+ >>> def g2(x):
+ ... return (12*x[0] + 11.9*x[1] +41.8*x[2] + 52.1*x[3] - 21
+ ... - 1.645 * np.sqrt(0.28*x[0]**2 + 0.19*x[1]**2
+ ... + 20.5*x[2]**2 + 0.62*x[3]**2)
+ ... ) # >=0
+ ...
+ >>> def h1(x):
+ ... return x[0] + x[1] + x[2] + x[3] - 1 # == 0
+ ...
+ >>> cons = ({'type': 'ineq', 'fun': g1},
+ ... {'type': 'ineq', 'fun': g2},
+ ... {'type': 'eq', 'fun': h1})
+ >>> bounds = [(0, 1.0),]*4
+ >>> res = shgo(f, bounds, n=150, constraints=cons)
+ >>> res
+ message: Optimization terminated successfully.
+ success: True
+ fun: 29.894378159142136
+ funl: [ 2.989e+01]
+ x: [ 6.355e-01 1.137e-13 3.127e-01 5.178e-02] # may vary
+ xl: [[ 6.355e-01 1.137e-13 3.127e-01 5.178e-02]] # may vary
+ nit: 1
+ nfev: 142 # may vary
+ nlfev: 35 # may vary
+ nljev: 5
+ nlhev: 0
+
+ >>> g1(res.x), g2(res.x), h1(res.x)
+ (-5.062616992290714e-14, -2.9594104944408173e-12, 0.0)
+
+ """
+ # if necessary, convert bounds class to old bounds
+ if isinstance(bounds, Bounds):
+ bounds = new_bounds_to_old(bounds.lb, bounds.ub, len(bounds.lb))
+
+ # Initiate SHGO class
+ # use in context manager to make sure that any parallelization
+ # resources are freed.
+ with SHGO(func, bounds, args=args, constraints=constraints, n=n,
+ iters=iters, callback=callback,
+ minimizer_kwargs=minimizer_kwargs,
+ options=options, sampling_method=sampling_method,
+ workers=workers) as shc:
+ # Run the algorithm, process results and test success
+ shc.iterate_all()
+
+ if not shc.break_routine:
+ if shc.disp:
+ logging.info("Successfully completed construction of complex.")
+
+ # Test post iterations success
+ if len(shc.LMC.xl_maps) == 0:
+ # If sampling failed to find pool, return lowest sampled point
+ # with a warning
+ shc.find_lowest_vertex()
+ shc.break_routine = True
+ shc.fail_routine(mes="Failed to find a feasible minimizer point. "
+ f"Lowest sampling point = {shc.f_lowest}")
+ shc.res.fun = shc.f_lowest
+ shc.res.x = shc.x_lowest
+ shc.res.nfev = shc.fn
+ shc.res.tnev = shc.n_sampled
+ else:
+ # Test that the optimal solutions do not violate any constraints
+ pass # TODO
+
+ # Confirm the routine ran successfully
+ if not shc.break_routine:
+ shc.res.message = 'Optimization terminated successfully.'
+ shc.res.success = True
+
+ # Return the final results
+ return shc.res
+
+
+class SHGO:
+ def __init__(self, func, bounds, args=(), constraints=None, n=None,
+ iters=None, callback=None, minimizer_kwargs=None,
+ options=None, sampling_method='simplicial', workers=1):
+ from scipy.stats import qmc
+ # Input checks
+ methods = ['halton', 'sobol', 'simplicial']
+ if isinstance(sampling_method, str) and sampling_method not in methods:
+ raise ValueError(("Unknown sampling_method specified."
+ " Valid methods: {}").format(', '.join(methods)))
+
+ # copy the options dictionaries so that the user input is not mutated
+ if minimizer_kwargs is not None and isinstance(minimizer_kwargs, dict):
+ minimizer_kwargs = minimizer_kwargs.copy()
+ if options is not None and isinstance(options, dict):
+ options = options.copy()
+
+ if options is not None and options.get('jac', None) is True:
+ if minimizer_kwargs is None:
+ minimizer_kwargs = {}
+ minimizer_kwargs['jac'] = True
+ options.pop('jac')
+
+ # Split obj func if given with Jac
+ try:
+ if ((minimizer_kwargs['jac'] is True) and
+ (not callable(minimizer_kwargs['jac']))):
+ self.func = MemoizeJac(func)
+ jac = self.func.derivative
+ minimizer_kwargs['jac'] = jac
+ func = self.func # fun
+ else:
+ self.func = func # Normal definition of objective function
+ except (TypeError, KeyError):
+ self.func = func # Normal definition of objective function
+
+ # Initiate class
+ self.func = _FunctionWrapper(func, args)
+ self.bounds = bounds
+ self.args = args
+ self.callback = callback
+
+ # Bounds
+ abound = np.array(bounds, float)
+ self.dim = np.shape(abound)[0] # Dimensionality of problem
+
+ # Set none finite values to large floats
+ infind = ~np.isfinite(abound)
+ abound[infind[:, 0], 0] = -1e50
+ abound[infind[:, 1], 1] = 1e50
+
+ # Check if bounds are correctly specified
+ bnderr = abound[:, 0] > abound[:, 1]
+ if bnderr.any():
+ raise ValueError("Error: lb > ub in bounds "
+ f"{', '.join(str(b) for b in bnderr)}.")
+
+ self.bounds = abound
+
+ # Constraints
+ # Process constraint dict sequence:
+ self.constraints = constraints
+ if constraints is not None:
+ self.min_cons = constraints
+ self.g_cons = []
+ self.g_args = []
+
+ # shgo internals deals with old-style constraints
+ # self.constraints is used to create Complex, so need
+ # to be stored internally in old-style.
+ # `minimize` takes care of normalising these constraints
+ # for slsqp/cobyla/cobyqa/trust-constr.
+ self.constraints = standardize_constraints(
+ constraints,
+ np.empty(self.dim, float),
+ 'old'
+ )
+ for cons in self.constraints:
+ if cons['type'] in ('ineq'):
+ self.g_cons.append(cons['fun'])
+ try:
+ self.g_args.append(cons['args'])
+ except KeyError:
+ self.g_args.append(())
+ self.g_cons = tuple(self.g_cons)
+ self.g_args = tuple(self.g_args)
+ else:
+ self.g_cons = None
+ self.g_args = None
+
+ # Define local minimization keyword arguments
+ # Start with defaults
+ self.minimizer_kwargs = {'method': 'SLSQP',
+ 'bounds': self.bounds,
+ 'options': {},
+ 'callback': self.callback
+ }
+ if minimizer_kwargs is not None:
+ # Overwrite with supplied values
+ self.minimizer_kwargs.update(minimizer_kwargs)
+
+ else:
+ self.minimizer_kwargs['options'] = {'ftol': 1e-12}
+
+ if (
+ self.minimizer_kwargs['method'].lower() in ('slsqp', 'cobyla',
+ 'cobyqa',
+ 'trust-constr')
+ and (
+ minimizer_kwargs is not None and
+ 'constraints' not in minimizer_kwargs and
+ constraints is not None
+ ) or
+ (self.g_cons is not None)
+ ):
+ self.minimizer_kwargs['constraints'] = self.min_cons
+
+ # Process options dict
+ if options is not None:
+ self.init_options(options)
+ else: # Default settings:
+ self.f_min_true = None
+ self.minimize_every_iter = True
+
+ # Algorithm limits
+ self.maxiter = None
+ self.maxfev = None
+ self.maxev = None
+ self.maxtime = None
+ self.f_min_true = None
+ self.minhgrd = None
+
+ # Objective function knowledge
+ self.symmetry = None
+
+ # Algorithm functionality
+ self.infty_cons_sampl = True
+ self.local_iter = False
+
+ # Feedback
+ self.disp = False
+
+ # normalize grad + hess calls for args
+ # this has to be done after minimizer_kwargs has finished having its
+ # jac/hess/args edited.
+ _grad = self.minimizer_kwargs.get('jac', None)
+ if callable(_grad):
+ self.minimizer_kwargs['jac'] = _FunctionWrapper(_grad, self.args)
+ _hess = self.minimizer_kwargs.get('hess', None)
+ if callable(_hess):
+ self.minimizer_kwargs['hess'] = _FunctionWrapper(_hess, self.args)
+
+ # we've already wrapped fun, grad, hess, so no need for args
+ self.minimizer_kwargs.pop("args", None)
+ self.minimizer_kwargs["options"].pop("args", None)
+
+ # Remove unknown arguments in self.minimizer_kwargs
+ # Start with arguments all the solvers have in common
+ self.min_solver_args = ['fun', 'x0', 'args',
+ 'callback', 'options', 'method']
+ # then add the ones unique to specific solvers
+ solver_args = {
+ '_custom': ['jac', 'hess', 'hessp', 'bounds', 'constraints'],
+ 'nelder-mead': [],
+ 'powell': [],
+ 'cg': ['jac'],
+ 'bfgs': ['jac'],
+ 'newton-cg': ['jac', 'hess', 'hessp'],
+ 'l-bfgs-b': ['jac', 'bounds'],
+ 'tnc': ['jac', 'bounds'],
+ 'cobyla': ['constraints', 'catol'],
+ 'cobyqa': ['bounds', 'constraints', 'feasibility_tol'],
+ 'slsqp': ['jac', 'bounds', 'constraints'],
+ 'dogleg': ['jac', 'hess'],
+ 'trust-ncg': ['jac', 'hess', 'hessp'],
+ 'trust-krylov': ['jac', 'hess', 'hessp'],
+ 'trust-exact': ['jac', 'hess'],
+ 'trust-constr': ['jac', 'hess', 'hessp', 'constraints'],
+ }
+ method = self.minimizer_kwargs['method']
+ self.min_solver_args += solver_args[method.lower()]
+
+ # Only retain the known arguments
+ def _restrict_to_keys(dictionary, goodkeys):
+ """Remove keys from dictionary if not in goodkeys - inplace"""
+ existingkeys = set(dictionary)
+ for key in existingkeys - set(goodkeys):
+ dictionary.pop(key, None)
+
+ _restrict_to_keys(self.minimizer_kwargs, self.min_solver_args)
+ _restrict_to_keys(self.minimizer_kwargs['options'],
+ self.min_solver_args + ['ftol'])
+
+ # Algorithm controls
+ # Global controls
+ self.stop_global = False # Used in the stopping_criteria method
+ self.break_routine = False # Break the algorithm globally
+ self.iters = iters # Iterations to be ran
+ self.iters_done = 0 # Iterations completed
+ self.n = n # Sampling points per iteration
+ self.nc = 0 # n # Sampling points to sample in current iteration
+ self.n_prc = 0 # Processed points (used to track Delaunay iters)
+ self.n_sampled = 0 # To track no. of sampling points already generated
+ self.fn = 0 # Number of feasible sampling points evaluations performed
+ self.hgr = 0 # Homology group rank
+ # Initially attempt to build the triangulation incrementally:
+ self.qhull_incremental = True
+
+ # Default settings if no sampling criteria.
+ if (self.n is None) and (self.iters is None) \
+ and (sampling_method == 'simplicial'):
+ self.n = 2 ** self.dim + 1
+ self.nc = 0 # self.n
+ if self.iters is None:
+ self.iters = 1
+ if (self.n is None) and not (sampling_method == 'simplicial'):
+ self.n = self.n = 100
+ self.nc = 0 # self.n
+ if (self.n == 100) and (sampling_method == 'simplicial'):
+ self.n = 2 ** self.dim + 1
+
+ if not ((self.maxiter is None) and (self.maxfev is None) and (
+ self.maxev is None)
+ and (self.minhgrd is None) and (self.f_min_true is None)):
+ self.iters = None
+
+ # Set complex construction mode based on a provided stopping criteria:
+ # Initialise sampling Complex and function cache
+ # Note that sfield_args=() since args are already wrapped in self.func
+ # using the_FunctionWrapper class.
+ self.HC = Complex(dim=self.dim, domain=self.bounds,
+ sfield=self.func, sfield_args=(),
+ symmetry=self.symmetry,
+ constraints=self.constraints,
+ workers=workers)
+
+ # Choose complex constructor
+ if sampling_method == 'simplicial':
+ self.iterate_complex = self.iterate_hypercube
+ self.sampling_method = sampling_method
+
+ elif sampling_method in ['halton', 'sobol'] or \
+ not isinstance(sampling_method, str):
+ self.iterate_complex = self.iterate_delaunay
+ # Sampling method used
+ if sampling_method in ['halton', 'sobol']:
+ if sampling_method == 'sobol':
+ self.n = int(2 ** np.ceil(np.log2(self.n)))
+ # self.n #TODO: Should always be self.n, this is
+ # unacceptable for shgo, check that nfev behaves as
+ # expected.
+ self.nc = 0
+ self.sampling_method = 'sobol'
+ self.qmc_engine = qmc.Sobol(d=self.dim, scramble=False,
+ seed=0)
+ else:
+ self.sampling_method = 'halton'
+ self.qmc_engine = qmc.Halton(d=self.dim, scramble=True,
+ seed=0)
+
+ def sampling_method(n, d):
+ return self.qmc_engine.random(n)
+
+ else:
+ # A user defined sampling method:
+ self.sampling_method = 'custom'
+
+ self.sampling = self.sampling_custom
+ self.sampling_function = sampling_method # F(n, d)
+
+ # Local controls
+ self.stop_l_iter = False # Local minimisation iterations
+ self.stop_complex_iter = False # Sampling iterations
+
+ # Initiate storage objects used in algorithm classes
+ self.minimizer_pool = []
+
+ # Cache of local minimizers mapped
+ self.LMC = LMapCache()
+
+ # Initialize return object
+ self.res = OptimizeResult() # scipy.optimize.OptimizeResult object
+ self.res.nfev = 0 # Includes each sampling point as func evaluation
+ self.res.nlfev = 0 # Local function evals for all minimisers
+ self.res.nljev = 0 # Local Jacobian evals for all minimisers
+ self.res.nlhev = 0 # Local Hessian evals for all minimisers
+
+ # Initiation aids
+ def init_options(self, options):
+ """
+ Initiates the options.
+
+ Can also be useful to change parameters after class initiation.
+
+ Parameters
+ ----------
+ options : dict
+
+ Returns
+ -------
+ None
+
+ """
+ # Update 'options' dict passed to optimize.minimize
+ # Do this first so we don't mutate `options` below.
+ self.minimizer_kwargs['options'].update(options)
+
+ # Ensure that 'jac', 'hess', and 'hessp' are passed directly to
+ # `minimize` as keywords, not as part of its 'options' dictionary.
+ for opt in ['jac', 'hess', 'hessp']:
+ if opt in self.minimizer_kwargs['options']:
+ self.minimizer_kwargs[opt] = (
+ self.minimizer_kwargs['options'].pop(opt))
+
+ # Default settings:
+ self.minimize_every_iter = options.get('minimize_every_iter', True)
+
+ # Algorithm limits
+ # Maximum number of iterations to perform.
+ self.maxiter = options.get('maxiter', None)
+ # Maximum number of function evaluations in the feasible domain
+ self.maxfev = options.get('maxfev', None)
+ # Maximum number of sampling evaluations (includes searching in
+ # infeasible points
+ self.maxev = options.get('maxev', None)
+ # Maximum processing runtime allowed
+ self.init = time.time()
+ self.maxtime = options.get('maxtime', None)
+ if 'f_min' in options:
+ # Specify the minimum objective function value, if it is known.
+ self.f_min_true = options['f_min']
+ self.f_tol = options.get('f_tol', 1e-4)
+ else:
+ self.f_min_true = None
+
+ self.minhgrd = options.get('minhgrd', None)
+
+ # Objective function knowledge
+ self.symmetry = options.get('symmetry', False)
+ if self.symmetry:
+ self.symmetry = [0, ]*len(self.bounds)
+ else:
+ self.symmetry = None
+ # Algorithm functionality
+ # Only evaluate a few of the best candidates
+ self.local_iter = options.get('local_iter', False)
+ self.infty_cons_sampl = options.get('infty_constraints', True)
+
+ # Feedback
+ self.disp = options.get('disp', False)
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return self.HC.V._mapwrapper.__exit__(*args)
+
+ # Iteration properties
+ # Main construction loop:
+ def iterate_all(self):
+ """
+ Construct for `iters` iterations.
+
+ If uniform sampling is used, every iteration adds 'n' sampling points.
+
+ Iterations if a stopping criteria (e.g., sampling points or
+ processing time) has been met.
+
+ """
+ if self.disp:
+ logging.info('Splitting first generation')
+
+ while not self.stop_global:
+ if self.break_routine:
+ break
+ # Iterate complex, process minimisers
+ self.iterate()
+ self.stopping_criteria()
+
+ # Build minimiser pool
+ # Final iteration only needed if pools weren't minimised every
+ # iteration
+ if not self.minimize_every_iter:
+ if not self.break_routine:
+ self.find_minima()
+
+ self.res.nit = self.iters_done # + 1
+ self.fn = self.HC.V.nfev
+
+ def find_minima(self):
+ """
+ Construct the minimizer pool, map the minimizers to local minima
+ and sort the results into a global return object.
+ """
+ if self.disp:
+ logging.info('Searching for minimizer pool...')
+
+ self.minimizers()
+
+ if len(self.X_min) != 0:
+ # Minimize the pool of minimizers with local minimization methods
+ # Note that if Options['local_iter'] is an `int` instead of default
+ # value False then only that number of candidates will be minimized
+ self.minimise_pool(self.local_iter)
+ # Sort results and build the global return object
+ self.sort_result()
+
+ # Lowest values used to report in case of failures
+ self.f_lowest = self.res.fun
+ self.x_lowest = self.res.x
+ else:
+ self.find_lowest_vertex()
+
+ if self.disp:
+ logging.info(f"Minimiser pool = SHGO.X_min = {self.X_min}")
+
+ def find_lowest_vertex(self):
+ # Find the lowest objective function value on one of
+ # the vertices of the simplicial complex
+ self.f_lowest = np.inf
+ for x in self.HC.V.cache:
+ if self.HC.V[x].f < self.f_lowest:
+ if self.disp:
+ logging.info(f'self.HC.V[x].f = {self.HC.V[x].f}')
+ self.f_lowest = self.HC.V[x].f
+ self.x_lowest = self.HC.V[x].x_a
+ for lmc in self.LMC.cache:
+ if self.LMC[lmc].f_min < self.f_lowest:
+ self.f_lowest = self.LMC[lmc].f_min
+ self.x_lowest = self.LMC[lmc].x_l
+
+ if self.f_lowest == np.inf: # no feasible point
+ self.f_lowest = None
+ self.x_lowest = None
+
+ # Stopping criteria functions:
+ def finite_iterations(self):
+ mi = min(x for x in [self.iters, self.maxiter] if x is not None)
+ if self.disp:
+ logging.info(f'Iterations done = {self.iters_done} / {mi}')
+ if self.iters is not None:
+ if self.iters_done >= (self.iters):
+ self.stop_global = True
+
+ if self.maxiter is not None: # Stop for infeasible sampling
+ if self.iters_done >= (self.maxiter):
+ self.stop_global = True
+ return self.stop_global
+
+ def finite_fev(self):
+ # Finite function evals in the feasible domain
+ if self.disp:
+ logging.info(f'Function evaluations done = {self.fn} / {self.maxfev}')
+ if self.fn >= self.maxfev:
+ self.stop_global = True
+ return self.stop_global
+
+ def finite_ev(self):
+ # Finite evaluations including infeasible sampling points
+ if self.disp:
+ logging.info(f'Sampling evaluations done = {self.n_sampled} '
+ f'/ {self.maxev}')
+ if self.n_sampled >= self.maxev:
+ self.stop_global = True
+
+ def finite_time(self):
+ if self.disp:
+ logging.info(f'Time elapsed = {time.time() - self.init} '
+ f'/ {self.maxtime}')
+ if (time.time() - self.init) >= self.maxtime:
+ self.stop_global = True
+
+ def finite_precision(self):
+ """
+ Stop the algorithm if the final function value is known
+
+ Specify in options (with ``self.f_min_true = options['f_min']``)
+ and the tolerance with ``f_tol = options['f_tol']``
+ """
+ # If no minimizer has been found use the lowest sampling value
+ self.find_lowest_vertex()
+ if self.disp:
+ logging.info(f'Lowest function evaluation = {self.f_lowest}')
+ logging.info(f'Specified minimum = {self.f_min_true}')
+ # If no feasible point was return from test
+ if self.f_lowest is None:
+ return self.stop_global
+
+ # Function to stop algorithm at specified percentage error:
+ if self.f_min_true == 0.0:
+ if self.f_lowest <= self.f_tol:
+ self.stop_global = True
+ else:
+ pe = (self.f_lowest - self.f_min_true) / abs(self.f_min_true)
+ if self.f_lowest <= self.f_min_true:
+ self.stop_global = True
+ # 2if (pe - self.f_tol) <= abs(1.0 / abs(self.f_min_true)):
+ if abs(pe) >= 2 * self.f_tol:
+ warnings.warn(
+ f"A much lower value than expected f* = {self.f_min_true} "
+ f"was found f_lowest = {self.f_lowest}",
+ stacklevel=3
+ )
+ if pe <= self.f_tol:
+ self.stop_global = True
+
+ return self.stop_global
+
+ def finite_homology_growth(self):
+ """
+ Stop the algorithm if homology group rank did not grow in iteration.
+ """
+ if self.LMC.size == 0:
+ return # pass on no reason to stop yet.
+ self.hgrd = self.LMC.size - self.hgr
+
+ self.hgr = self.LMC.size
+ if self.hgrd <= self.minhgrd:
+ self.stop_global = True
+ if self.disp:
+ logging.info(f'Current homology growth = {self.hgrd} '
+ f' (minimum growth = {self.minhgrd})')
+ return self.stop_global
+
+ def stopping_criteria(self):
+ """
+ Various stopping criteria ran every iteration
+
+ Returns
+ -------
+ stop : bool
+ """
+ if self.maxiter is not None:
+ self.finite_iterations()
+ if self.iters is not None:
+ self.finite_iterations()
+ if self.maxfev is not None:
+ self.finite_fev()
+ if self.maxev is not None:
+ self.finite_ev()
+ if self.maxtime is not None:
+ self.finite_time()
+ if self.f_min_true is not None:
+ self.finite_precision()
+ if self.minhgrd is not None:
+ self.finite_homology_growth()
+ return self.stop_global
+
+ def iterate(self):
+ self.iterate_complex()
+
+ # Build minimizer pool
+ if self.minimize_every_iter:
+ if not self.break_routine:
+ self.find_minima() # Process minimizer pool
+
+ # Algorithm updates
+ self.iters_done += 1
+
+ def iterate_hypercube(self):
+ """
+ Iterate a subdivision of the complex
+
+ Note: called with ``self.iterate_complex()`` after class initiation
+ """
+ # Iterate the complex
+ if self.disp:
+ logging.info('Constructing and refining simplicial complex graph '
+ 'structure')
+ if self.n is None:
+ self.HC.refine_all()
+ self.n_sampled = self.HC.V.size() # nevs counted
+ else:
+ self.HC.refine(self.n)
+ self.n_sampled += self.n
+
+ if self.disp:
+ logging.info('Triangulation completed, evaluating all constraints '
+ 'and objective function values.')
+
+ # Re-add minimisers to complex
+ if len(self.LMC.xl_maps) > 0:
+ for xl in self.LMC.cache:
+ v = self.HC.V[xl]
+ v_near = v.star()
+ for v in v.nn:
+ v_near = v_near.union(v.nn)
+ # Reconnect vertices to complex
+ # if self.HC.connect_vertex_non_symm(tuple(self.LMC[xl].x_l),
+ # near=v_near):
+ # continue
+ # else:
+ # If failure to find in v_near, then search all vertices
+ # (very expensive operation:
+ # self.HC.connect_vertex_non_symm(tuple(self.LMC[xl].x_l)
+ # )
+
+ # Evaluate all constraints and functions
+ self.HC.V.process_pools()
+ if self.disp:
+ logging.info('Evaluations completed.')
+
+ # feasible sampling points counted by the triangulation.py routines
+ self.fn = self.HC.V.nfev
+ return
+
+ def iterate_delaunay(self):
+ """
+ Build a complex of Delaunay triangulated points
+
+ Note: called with ``self.iterate_complex()`` after class initiation
+ """
+ self.nc += self.n
+ self.sampled_surface(infty_cons_sampl=self.infty_cons_sampl)
+
+ # Add sampled points to a triangulation, construct self.Tri
+ if self.disp:
+ logging.info(f'self.n = {self.n}')
+ logging.info(f'self.nc = {self.nc}')
+ logging.info('Constructing and refining simplicial complex graph '
+ 'structure from sampling points.')
+
+ if self.dim < 2:
+ self.Ind_sorted = np.argsort(self.C, axis=0)
+ self.Ind_sorted = self.Ind_sorted.flatten()
+ tris = []
+ for ind, ind_s in enumerate(self.Ind_sorted):
+ if ind > 0:
+ tris.append(self.Ind_sorted[ind - 1:ind + 1])
+
+ tris = np.array(tris)
+ # Store 1D triangulation:
+ self.Tri = namedtuple('Tri', ['points', 'simplices'])(self.C, tris)
+ self.points = {}
+ else:
+ if self.C.shape[0] > self.dim + 1: # Ensure a simplex can be built
+ self.delaunay_triangulation(n_prc=self.n_prc)
+ self.n_prc = self.C.shape[0]
+
+ if self.disp:
+ logging.info('Triangulation completed, evaluating all '
+ 'constraints and objective function values.')
+
+ if hasattr(self, 'Tri'):
+ self.HC.vf_to_vv(self.Tri.points, self.Tri.simplices)
+
+ # Process all pools
+ # Evaluate all constraints and functions
+ if self.disp:
+ logging.info('Triangulation completed, evaluating all constraints '
+ 'and objective function values.')
+
+ # Evaluate all constraints and functions
+ self.HC.V.process_pools()
+ if self.disp:
+ logging.info('Evaluations completed.')
+
+ # feasible sampling points counted by the triangulation.py routines
+ self.fn = self.HC.V.nfev
+ self.n_sampled = self.nc # nevs counted in triangulation
+ return
+
+ # Hypercube minimizers
+ def minimizers(self):
+ """
+ Returns the indexes of all minimizers
+ """
+ self.minimizer_pool = []
+ # Note: Can implement parallelization here
+ for x in self.HC.V.cache:
+ in_LMC = False
+ if len(self.LMC.xl_maps) > 0:
+ for xlmi in self.LMC.xl_maps:
+ if np.all(np.array(x) == np.array(xlmi)):
+ in_LMC = True
+ if in_LMC:
+ continue
+
+ if self.HC.V[x].minimiser():
+ if self.disp:
+ logging.info('=' * 60)
+ logging.info(f'v.x = {self.HC.V[x].x_a} is minimizer')
+ logging.info(f'v.f = {self.HC.V[x].f} is minimizer')
+ logging.info('=' * 30)
+
+ if self.HC.V[x] not in self.minimizer_pool:
+ self.minimizer_pool.append(self.HC.V[x])
+
+ if self.disp:
+ logging.info('Neighbors:')
+ logging.info('=' * 30)
+ for vn in self.HC.V[x].nn:
+ logging.info(f'x = {vn.x} || f = {vn.f}')
+
+ logging.info('=' * 60)
+ self.minimizer_pool_F = []
+ self.X_min = []
+ # normalized tuple in the Vertex cache
+ self.X_min_cache = {} # Cache used in hypercube sampling
+
+ for v in self.minimizer_pool:
+ self.X_min.append(v.x_a)
+ self.minimizer_pool_F.append(v.f)
+ self.X_min_cache[tuple(v.x_a)] = v.x
+
+ self.minimizer_pool_F = np.array(self.minimizer_pool_F)
+ self.X_min = np.array(self.X_min)
+
+ # TODO: Only do this if global mode
+ self.sort_min_pool()
+
+ return self.X_min
+
+ # Local minimisation
+ # Minimiser pool processing
+ def minimise_pool(self, force_iter=False):
+ """
+ This processing method can optionally minimise only the best candidate
+ solutions in the minimiser pool
+
+ Parameters
+ ----------
+ force_iter : int
+ Number of starting minimizers to process (can be specified
+ globally or locally)
+
+ """
+ # Find first local minimum
+ # NOTE: Since we always minimize this value regardless it is a waste to
+ # build the topograph first before minimizing
+ lres_f_min = self.minimize(self.X_min[0], ind=self.minimizer_pool[0])
+
+ # Trim minimized point from current minimizer set
+ self.trim_min_pool(0)
+
+ while not self.stop_l_iter:
+ # Global stopping criteria:
+ self.stopping_criteria()
+
+ # Note first iteration is outside loop:
+ if force_iter:
+ force_iter -= 1
+ if force_iter == 0:
+ self.stop_l_iter = True
+ break
+
+ if np.shape(self.X_min)[0] == 0:
+ self.stop_l_iter = True
+ break
+
+ # Construct topograph from current minimizer set
+ # (NOTE: This is a very small topograph using only the minizer pool
+ # , it might be worth using some graph theory tools instead.
+ self.g_topograph(lres_f_min.x, self.X_min)
+
+ # Find local minimum at the miniser with the greatest Euclidean
+ # distance from the current solution
+ ind_xmin_l = self.Z[:, -1]
+ lres_f_min = self.minimize(self.Ss[-1, :], self.minimizer_pool[-1])
+
+ # Trim minimised point from current minimizer set
+ self.trim_min_pool(ind_xmin_l)
+
+ # Reset controls
+ self.stop_l_iter = False
+ return
+
+ def sort_min_pool(self):
+ # Sort to find minimum func value in min_pool
+ self.ind_f_min = np.argsort(self.minimizer_pool_F)
+ self.minimizer_pool = np.array(self.minimizer_pool)[self.ind_f_min]
+ self.minimizer_pool_F = np.array(self.minimizer_pool_F)[
+ self.ind_f_min]
+ return
+
+ def trim_min_pool(self, trim_ind):
+ self.X_min = np.delete(self.X_min, trim_ind, axis=0)
+ self.minimizer_pool_F = np.delete(self.minimizer_pool_F, trim_ind)
+ self.minimizer_pool = np.delete(self.minimizer_pool, trim_ind)
+ return
+
+ def g_topograph(self, x_min, X_min):
+ """
+ Returns the topographical vector stemming from the specified value
+ ``x_min`` for the current feasible set ``X_min`` with True boolean
+ values indicating positive entries and False values indicating
+ negative entries.
+
+ """
+ x_min = np.array([x_min])
+ self.Y = spatial.distance.cdist(x_min, X_min, 'euclidean')
+ # Find sorted indexes of spatial distances:
+ self.Z = np.argsort(self.Y, axis=-1)
+
+ self.Ss = X_min[self.Z][0]
+ self.minimizer_pool = self.minimizer_pool[self.Z]
+ self.minimizer_pool = self.minimizer_pool[0]
+ return self.Ss
+
+ # Local bound functions
+ def construct_lcb_simplicial(self, v_min):
+ """
+ Construct locally (approximately) convex bounds
+
+ Parameters
+ ----------
+ v_min : Vertex object
+ The minimizer vertex
+
+ Returns
+ -------
+ cbounds : list of lists
+ List of size dimension with length-2 list of bounds for each
+ dimension.
+
+ """
+ cbounds = [[x_b_i[0], x_b_i[1]] for x_b_i in self.bounds]
+ # Loop over all bounds
+ for vn in v_min.nn:
+ for i, x_i in enumerate(vn.x_a):
+ # Lower bound
+ if (x_i < v_min.x_a[i]) and (x_i > cbounds[i][0]):
+ cbounds[i][0] = x_i
+
+ # Upper bound
+ if (x_i > v_min.x_a[i]) and (x_i < cbounds[i][1]):
+ cbounds[i][1] = x_i
+
+ if self.disp:
+ logging.info(f'cbounds found for v_min.x_a = {v_min.x_a}')
+ logging.info(f'cbounds = {cbounds}')
+
+ return cbounds
+
+ def construct_lcb_delaunay(self, v_min, ind=None):
+ """
+ Construct locally (approximately) convex bounds
+
+ Parameters
+ ----------
+ v_min : Vertex object
+ The minimizer vertex
+
+ Returns
+ -------
+ cbounds : list of lists
+ List of size dimension with length-2 list of bounds for each
+ dimension.
+ """
+ cbounds = [[x_b_i[0], x_b_i[1]] for x_b_i in self.bounds]
+
+ return cbounds
+
+ # Minimize a starting point locally
+ def minimize(self, x_min, ind=None):
+ """
+ This function is used to calculate the local minima using the specified
+ sampling point as a starting value.
+
+ Parameters
+ ----------
+ x_min : vector of floats
+ Current starting point to minimize.
+
+ Returns
+ -------
+ lres : OptimizeResult
+ The local optimization result represented as a `OptimizeResult`
+ object.
+ """
+ # Use minima maps if vertex was already run
+ if self.disp:
+ logging.info(f'Vertex minimiser maps = {self.LMC.v_maps}')
+
+ if self.LMC[x_min].lres is not None:
+ logging.info(f'Found self.LMC[x_min].lres = '
+ f'{self.LMC[x_min].lres}')
+ return self.LMC[x_min].lres
+
+ if self.callback is not None:
+ logging.info(f'Callback for minimizer starting at {x_min}:')
+
+ if self.disp:
+ logging.info(f'Starting minimization at {x_min}...')
+
+ if self.sampling_method == 'simplicial':
+ x_min_t = tuple(x_min)
+ # Find the normalized tuple in the Vertex cache:
+ x_min_t_norm = self.X_min_cache[tuple(x_min_t)]
+ x_min_t_norm = tuple(x_min_t_norm)
+ g_bounds = self.construct_lcb_simplicial(self.HC.V[x_min_t_norm])
+ if 'bounds' in self.min_solver_args:
+ self.minimizer_kwargs['bounds'] = g_bounds
+ logging.info(self.minimizer_kwargs['bounds'])
+
+ else:
+ g_bounds = self.construct_lcb_delaunay(x_min, ind=ind)
+ if 'bounds' in self.min_solver_args:
+ self.minimizer_kwargs['bounds'] = g_bounds
+ logging.info(self.minimizer_kwargs['bounds'])
+
+ if self.disp and 'bounds' in self.minimizer_kwargs:
+ logging.info('bounds in kwarg:')
+ logging.info(self.minimizer_kwargs['bounds'])
+
+ # Local minimization using scipy.optimize.minimize:
+ lres = minimize(self.func, x_min, **self.minimizer_kwargs)
+
+ if self.disp:
+ logging.info(f'lres = {lres}')
+
+ # Local function evals for all minimizers
+ self.res.nlfev += lres.nfev
+ if 'njev' in lres:
+ self.res.nljev += lres.njev
+ if 'nhev' in lres:
+ self.res.nlhev += lres.nhev
+
+ try: # Needed because of the brain dead 1x1 NumPy arrays
+ lres.fun = lres.fun[0]
+ except (IndexError, TypeError):
+ lres.fun
+
+ # Append minima maps
+ self.LMC[x_min]
+ self.LMC.add_res(x_min, lres, bounds=g_bounds)
+
+ return lres
+
+ # Post local minimization processing
+ def sort_result(self):
+ """
+ Sort results and build the global return object
+ """
+ # Sort results in local minima cache
+ results = self.LMC.sort_cache_result()
+ self.res.xl = results['xl']
+ self.res.funl = results['funl']
+ self.res.x = results['x']
+ self.res.fun = results['fun']
+
+ # Add local func evals to sampling func evals
+ # Count the number of feasible vertices and add to local func evals:
+ self.res.nfev = self.fn + self.res.nlfev
+ return self.res
+
+ # Algorithm controls
+ def fail_routine(self, mes=("Failed to converge")):
+ self.break_routine = True
+ self.res.success = False
+ self.X_min = [None]
+ self.res.message = mes
+
+ def sampled_surface(self, infty_cons_sampl=False):
+ """
+ Sample the function surface.
+
+ There are 2 modes, if ``infty_cons_sampl`` is True then the sampled
+ points that are generated outside the feasible domain will be
+ assigned an ``inf`` value in accordance with SHGO rules.
+ This guarantees convergence and usually requires less objective
+ function evaluations at the computational costs of more Delaunay
+ triangulation points.
+
+ If ``infty_cons_sampl`` is False, then the infeasible points are
+ discarded and only a subspace of the sampled points are used. This
+ comes at the cost of the loss of guaranteed convergence and usually
+ requires more objective function evaluations.
+ """
+ # Generate sampling points
+ if self.disp:
+ logging.info('Generating sampling points')
+ self.sampling(self.nc, self.dim)
+ if len(self.LMC.xl_maps) > 0:
+ self.C = np.vstack((self.C, np.array(self.LMC.xl_maps)))
+ if not infty_cons_sampl:
+ # Find subspace of feasible points
+ if self.g_cons is not None:
+ self.sampling_subspace()
+
+ # Sort remaining samples
+ self.sorted_samples()
+
+ # Find objective function references
+ self.n_sampled = self.nc
+
+ def sampling_custom(self, n, dim):
+ """
+ Generates uniform sampling points in a hypercube and scales the points
+ to the bound limits.
+ """
+ # Generate sampling points.
+ # Generate uniform sample points in [0, 1]^m \subset R^m
+ if self.n_sampled == 0:
+ self.C = self.sampling_function(n, dim)
+ else:
+ self.C = self.sampling_function(n, dim)
+ # Distribute over bounds
+ for i in range(len(self.bounds)):
+ self.C[:, i] = (self.C[:, i] *
+ (self.bounds[i][1] - self.bounds[i][0])
+ + self.bounds[i][0])
+ return self.C
+
+ def sampling_subspace(self):
+ """Find subspace of feasible points from g_func definition"""
+ # Subspace of feasible points.
+ for ind, g in enumerate(self.g_cons):
+ # C.shape = (Z, dim) where Z is the number of sampling points to
+ # evaluate and dim is the dimensionality of the problem.
+ # the constraint function may not be vectorised so have to step
+ # through each sampling point sequentially.
+ feasible = np.array(
+ [np.all(g(x_C, *self.g_args[ind]) >= 0.0) for x_C in self.C],
+ dtype=bool
+ )
+ self.C = self.C[feasible]
+
+ if self.C.size == 0:
+ self.res.message = ('No sampling point found within the '
+ + 'feasible set. Increasing sampling '
+ + 'size.')
+ # sampling correctly for both 1-D and >1-D cases
+ if self.disp:
+ logging.info(self.res.message)
+
+ def sorted_samples(self): # Validated
+ """Find indexes of the sorted sampling points"""
+ self.Ind_sorted = np.argsort(self.C, axis=0)
+ self.Xs = self.C[self.Ind_sorted]
+ return self.Ind_sorted, self.Xs
+
+ def delaunay_triangulation(self, n_prc=0):
+ if hasattr(self, 'Tri') and self.qhull_incremental:
+ # TODO: Uncertain if n_prc needs to add len(self.LMC.xl_maps)
+ # in self.sampled_surface
+ self.Tri.add_points(self.C[n_prc:, :])
+ else:
+ try:
+ self.Tri = spatial.Delaunay(self.C,
+ incremental=self.qhull_incremental,
+ )
+ except spatial.QhullError:
+ if str(sys.exc_info()[1])[:6] == 'QH6239':
+ logging.warning('QH6239 Qhull precision error detected, '
+ 'this usually occurs when no bounds are '
+ 'specified, Qhull can only run with '
+ 'handling cocircular/cospherical points'
+ ' and in this case incremental mode is '
+ 'switched off. The performance of shgo '
+ 'will be reduced in this mode.')
+ self.qhull_incremental = False
+ self.Tri = spatial.Delaunay(self.C,
+ incremental=
+ self.qhull_incremental)
+ else:
+ raise
+
+ return self.Tri
+
+
+class LMap:
+ def __init__(self, v):
+ self.v = v
+ self.x_l = None
+ self.lres = None
+ self.f_min = None
+ self.lbounds = []
+
+
+class LMapCache:
+ def __init__(self):
+ self.cache = {}
+
+ # Lists for search queries
+ self.v_maps = []
+ self.xl_maps = []
+ self.xl_maps_set = set()
+ self.f_maps = []
+ self.lbound_maps = []
+ self.size = 0
+
+ def __getitem__(self, v):
+ try:
+ v = np.ndarray.tolist(v)
+ except TypeError:
+ pass
+ v = tuple(v)
+ try:
+ return self.cache[v]
+ except KeyError:
+ xval = LMap(v)
+ self.cache[v] = xval
+
+ return self.cache[v]
+
+ def add_res(self, v, lres, bounds=None):
+ v = np.ndarray.tolist(v)
+ v = tuple(v)
+ self.cache[v].x_l = lres.x
+ self.cache[v].lres = lres
+ self.cache[v].f_min = lres.fun
+ self.cache[v].lbounds = bounds
+
+ # Update cache size
+ self.size += 1
+
+ # Cache lists for search queries
+ self.v_maps.append(v)
+ self.xl_maps.append(lres.x)
+ self.xl_maps_set.add(tuple(lres.x))
+ self.f_maps.append(lres.fun)
+ self.lbound_maps.append(bounds)
+
+ def sort_cache_result(self):
+ """
+ Sort results and build the global return object
+ """
+ results = {}
+ # Sort results and save
+ self.xl_maps = np.array(self.xl_maps)
+ self.f_maps = np.array(self.f_maps)
+
+ # Sorted indexes in Func_min
+ ind_sorted = np.argsort(self.f_maps)
+
+ # Save ordered list of minima
+ results['xl'] = self.xl_maps[ind_sorted] # Ordered x vals
+ self.f_maps = np.array(self.f_maps)
+ results['funl'] = self.f_maps[ind_sorted]
+ results['funl'] = results['funl'].T
+
+ # Find global of all minimizers
+ results['x'] = self.xl_maps[ind_sorted[0]] # Save global minima
+ results['fun'] = self.f_maps[ind_sorted[0]] # Save global fun value
+
+ self.xl_maps = np.ndarray.tolist(self.xl_maps)
+ self.f_maps = np.ndarray.tolist(self.f_maps)
+ return results
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.__complex.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.__complex.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.__complex.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.__vertex.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.__vertex.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/.__vertex.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_complex.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_complex.py
new file mode 100644
index 0000000000000000000000000000000000000000..494d5a5a4dd56dfd0ff8faced6b956b47a965bd8
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_complex.py
@@ -0,0 +1,1225 @@
+"""Base classes for low memory simplicial complex structures."""
+import copy
+import logging
+import itertools
+import decimal
+from functools import cache
+
+import numpy as np
+
+from ._vertex import (VertexCacheField, VertexCacheIndex)
+
+
+class Complex:
+ """
+ Base class for a simplicial complex described as a cache of vertices
+ together with their connections.
+
+ Important methods:
+ Domain triangulation:
+ Complex.triangulate, Complex.split_generation
+ Triangulating arbitrary points (must be traingulable,
+ may exist outside domain):
+ Complex.triangulate(sample_set)
+ Converting another simplicial complex structure data type to the
+ structure used in Complex (ex. OBJ wavefront)
+ Complex.convert(datatype, data)
+
+ Important objects:
+ HC.V: The cache of vertices and their connection
+ HC.H: Storage structure of all vertex groups
+
+ Parameters
+ ----------
+ dim : int
+ Spatial dimensionality of the complex R^dim
+ domain : list of tuples, optional
+ The bounds [x_l, x_u]^dim of the hyperrectangle space
+ ex. The default domain is the hyperrectangle [0, 1]^dim
+ Note: The domain must be convex, non-convex spaces can be cut
+ away from this domain using the non-linear
+ g_cons functions to define any arbitrary domain
+ (these domains may also be disconnected from each other)
+ sfield :
+ A scalar function defined in the associated domain f: R^dim --> R
+ sfield_args : tuple
+ Additional arguments to be passed to `sfield`
+ vfield :
+ A scalar function defined in the associated domain
+ f: R^dim --> R^m
+ (for example a gradient function of the scalar field)
+ vfield_args : tuple
+ Additional arguments to be passed to vfield
+ symmetry : None or list
+ Specify if the objective function contains symmetric variables.
+ The search space (and therefore performance) is decreased by up to
+ O(n!) times in the fully symmetric case.
+
+ E.g. f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2
+
+ In this equation x_2 and x_3 are symmetric to x_1, while x_5 and
+ x_6 are symmetric to x_4, this can be specified to the solver as:
+
+ symmetry = [0, # Variable 1
+ 0, # symmetric to variable 1
+ 0, # symmetric to variable 1
+ 3, # Variable 4
+ 3, # symmetric to variable 4
+ 3, # symmetric to variable 4
+ ]
+
+ constraints : dict or sequence of dict, optional
+ Constraints definition.
+ Function(s) ``R**n`` in the form::
+
+ g(x) <= 0 applied as g : R^n -> R^m
+ h(x) == 0 applied as h : R^n -> R^p
+
+ Each constraint is defined in a dictionary with fields:
+
+ type : str
+ Constraint type: 'eq' for equality, 'ineq' for inequality.
+ fun : callable
+ The function defining the constraint.
+ jac : callable, optional
+ The Jacobian of `fun` (only for SLSQP).
+ args : sequence, optional
+ Extra arguments to be passed to the function and Jacobian.
+
+ Equality constraint means that the constraint function result is to
+ be zero whereas inequality means that it is to be
+ non-negative.constraints : dict or sequence of dict, optional
+ Constraints definition.
+ Function(s) ``R**n`` in the form::
+
+ g(x) <= 0 applied as g : R^n -> R^m
+ h(x) == 0 applied as h : R^n -> R^p
+
+ Each constraint is defined in a dictionary with fields:
+
+ type : str
+ Constraint type: 'eq' for equality, 'ineq' for inequality.
+ fun : callable
+ The function defining the constraint.
+ jac : callable, optional
+ The Jacobian of `fun` (unused).
+ args : sequence, optional
+ Extra arguments to be passed to the function and Jacobian.
+
+ Equality constraint means that the constraint function result is to
+ be zero whereas inequality means that it is to be non-negative.
+
+ workers : int optional
+ Uses `multiprocessing.Pool `) to compute the field
+ functions in parallel.
+ """
+ def __init__(self, dim, domain=None, sfield=None, sfield_args=(),
+ symmetry=None, constraints=None, workers=1):
+ self.dim = dim
+
+ # Domains
+ self.domain = domain
+ if domain is None:
+ self.bounds = [(0.0, 1.0), ] * dim
+ else:
+ self.bounds = domain
+ self.symmetry = symmetry
+ # here in init to avoid if checks
+
+ # Field functions
+ self.sfield = sfield
+ self.sfield_args = sfield_args
+
+ # Process constraints
+ # Constraints
+ # Process constraint dict sequence:
+ if constraints is not None:
+ self.min_cons = constraints
+ self.g_cons = []
+ self.g_args = []
+ if not isinstance(constraints, tuple | list):
+ constraints = (constraints,)
+
+ for cons in constraints:
+ if cons['type'] in ('ineq'):
+ self.g_cons.append(cons['fun'])
+ try:
+ self.g_args.append(cons['args'])
+ except KeyError:
+ self.g_args.append(())
+ self.g_cons = tuple(self.g_cons)
+ self.g_args = tuple(self.g_args)
+ else:
+ self.g_cons = None
+ self.g_args = None
+
+ # Homology properties
+ self.gen = 0
+ self.perm_cycle = 0
+
+ # Every cell is stored in a list of its generation,
+ # ex. the initial cell is stored in self.H[0]
+ # 1st get new cells are stored in self.H[1] etc.
+ # When a cell is sub-generated it is removed from this list
+
+ self.H = [] # Storage structure of vertex groups
+
+ # Cache of all vertices
+ if (sfield is not None) or (self.g_cons is not None):
+ # Initiate a vertex cache and an associated field cache, note that
+ # the field case is always initiated inside the vertex cache if an
+ # associated field scalar field is defined:
+ if sfield is not None:
+ self.V = VertexCacheField(field=sfield, field_args=sfield_args,
+ g_cons=self.g_cons,
+ g_cons_args=self.g_args,
+ workers=workers)
+ elif self.g_cons is not None:
+ self.V = VertexCacheField(field=sfield, field_args=sfield_args,
+ g_cons=self.g_cons,
+ g_cons_args=self.g_args,
+ workers=workers)
+ else:
+ self.V = VertexCacheIndex()
+
+ self.V_non_symm = [] # List of non-symmetric vertices
+ self.split_edge = cache(self._split_edge)
+
+ def __call__(self):
+ return self.H
+
+ # %% Triangulation methods
+ def cyclic_product(self, bounds, origin, supremum, centroid=True):
+ """Generate initial triangulation using cyclic product"""
+ # Define current hyperrectangle
+ vot = tuple(origin)
+ vut = tuple(supremum) # Hyperrectangle supremum
+ self.V[vot]
+ vo = self.V[vot]
+ yield vo.x
+ self.V[vut].connect(self.V[vot])
+ yield vut
+ # Cyclic group approach with second x_l --- x_u operation.
+
+ # These containers store the "lower" and "upper" vertices
+ # corresponding to the origin or supremum of every C2 group.
+ # It has the structure of `dim` times embedded lists each containing
+ # these vertices as the entire complex grows. Bounds[0] has to be done
+ # outside the loops before we have symmetric containers.
+ # NOTE: This means that bounds[0][1] must always exist
+ C0x = [[self.V[vot]]]
+ a_vo = copy.copy(list(origin))
+ a_vo[0] = vut[0] # Update aN Origin
+ a_vo = self.V[tuple(a_vo)]
+ # self.V[vot].connect(self.V[tuple(a_vo)])
+ self.V[vot].connect(a_vo)
+ yield a_vo.x
+ C1x = [[a_vo]]
+ # C1x = [[self.V[tuple(a_vo)]]]
+ ab_C = [] # Container for a + b operations
+
+ # Loop over remaining bounds
+ for i, x in enumerate(bounds[1:]):
+ # Update lower and upper containers
+ C0x.append([])
+ C1x.append([])
+ # try to access a second bound (if not, C1 is symmetric)
+ try:
+ # Early try so that we don't have to copy the cache before
+ # moving on to next C1/C2: Try to add the operation of a new
+ # C2 product by accessing the upper bound
+ x[1]
+ # Copy lists for iteration
+ cC0x = [x[:] for x in C0x[:i + 1]]
+ cC1x = [x[:] for x in C1x[:i + 1]]
+ for j, (VL, VU) in enumerate(zip(cC0x, cC1x)):
+ for k, (vl, vu) in enumerate(zip(VL, VU)):
+ # Build aN vertices for each lower-upper pair in N:
+ a_vl = list(vl.x)
+ a_vu = list(vu.x)
+ a_vl[i + 1] = vut[i + 1]
+ a_vu[i + 1] = vut[i + 1]
+ a_vl = self.V[tuple(a_vl)]
+
+ # Connect vertices in N to corresponding vertices
+ # in aN:
+ vl.connect(a_vl)
+
+ yield a_vl.x
+
+ a_vu = self.V[tuple(a_vu)]
+ # Connect vertices in N to corresponding vertices
+ # in aN:
+ vu.connect(a_vu)
+
+ # Connect new vertex pair in aN:
+ a_vl.connect(a_vu)
+
+ # Connect lower pair to upper (triangulation
+ # operation of a + b (two arbitrary operations):
+ vl.connect(a_vu)
+ ab_C.append((vl, a_vu))
+
+ # Update the containers
+ C0x[i + 1].append(vl)
+ C0x[i + 1].append(vu)
+ C1x[i + 1].append(a_vl)
+ C1x[i + 1].append(a_vu)
+
+ # Update old containers
+ C0x[j].append(a_vl)
+ C1x[j].append(a_vu)
+
+ # Yield new points
+ yield a_vu.x
+
+ # Try to connect aN lower source of previous a + b
+ # operation with a aN vertex
+ ab_Cc = copy.copy(ab_C)
+
+ for vp in ab_Cc:
+ b_v = list(vp[0].x)
+ ab_v = list(vp[1].x)
+ b_v[i + 1] = vut[i + 1]
+ ab_v[i + 1] = vut[i + 1]
+ b_v = self.V[tuple(b_v)] # b + vl
+ ab_v = self.V[tuple(ab_v)] # b + a_vl
+ # Note o---o is already connected
+ vp[0].connect(ab_v) # o-s
+ b_v.connect(ab_v) # s-s
+
+ # Add new list of cross pairs
+ ab_C.append((vp[0], ab_v))
+ ab_C.append((b_v, ab_v))
+
+ except IndexError:
+ cC0x = C0x[i]
+ cC1x = C1x[i]
+ VL, VU = cC0x, cC1x
+ for k, (vl, vu) in enumerate(zip(VL, VU)):
+ # Build aN vertices for each lower-upper pair in N:
+ a_vu = list(vu.x)
+ a_vu[i + 1] = vut[i + 1]
+ # Connect vertices in N to corresponding vertices
+ # in aN:
+ a_vu = self.V[tuple(a_vu)]
+ # Connect vertices in N to corresponding vertices
+ # in aN:
+ vu.connect(a_vu)
+ # Connect new vertex pair in aN:
+ # a_vl.connect(a_vu)
+ # Connect lower pair to upper (triangulation
+ # operation of a + b (two arbitrary operations):
+ vl.connect(a_vu)
+ ab_C.append((vl, a_vu))
+ C0x[i + 1].append(vu)
+ C1x[i + 1].append(a_vu)
+ # Yield new points
+ a_vu.connect(self.V[vut])
+ yield a_vu.x
+ ab_Cc = copy.copy(ab_C)
+ for vp in ab_Cc:
+ if vp[1].x[i] == vut[i]:
+ ab_v = list(vp[1].x)
+ ab_v[i + 1] = vut[i + 1]
+ ab_v = self.V[tuple(ab_v)] # b + a_vl
+ # Note o---o is already connected
+ vp[0].connect(ab_v) # o-s
+
+ # Add new list of cross pairs
+ ab_C.append((vp[0], ab_v))
+
+ # Clean class trash
+ try:
+ del C0x
+ del cC0x
+ del C1x
+ del cC1x
+ del ab_C
+ del ab_Cc
+ except UnboundLocalError:
+ pass
+
+ # Extra yield to ensure that the triangulation is completed
+ if centroid:
+ vo = self.V[vot]
+ vs = self.V[vut]
+ # Disconnect the origin and supremum
+ vo.disconnect(vs)
+ # Build centroid
+ vc = self.split_edge(vot, vut)
+ for v in vo.nn:
+ v.connect(vc)
+ yield vc.x
+ return vc.x
+ else:
+ yield vut
+ return vut
+
+ def triangulate(self, n=None, symmetry=None, centroid=True,
+ printout=False):
+ """
+ Triangulate the initial domain, if n is not None then a limited number
+ of points will be generated
+
+ Parameters
+ ----------
+ n : int, Number of points to be sampled.
+ symmetry :
+
+ Ex. Dictionary/hashtable
+ f(x) = (x_1 + x_2 + x_3) + (x_4)**2 + (x_5)**2 + (x_6)**2
+
+ symmetry = symmetry[0]: 0, # Variable 1
+ symmetry[1]: 0, # symmetric to variable 1
+ symmetry[2]: 0, # symmetric to variable 1
+ symmetry[3]: 3, # Variable 4
+ symmetry[4]: 3, # symmetric to variable 4
+ symmetry[5]: 3, # symmetric to variable 4
+ }
+ centroid : bool, if True add a central point to the hypercube
+ printout : bool, if True print out results
+
+ NOTES:
+ ------
+ Rather than using the combinatorial algorithm to connect vertices we
+ make the following observation:
+
+ The bound pairs are similar a C2 cyclic group and the structure is
+ formed using the cartesian product:
+
+ H = C2 x C2 x C2 ... x C2 (dim times)
+
+ So construct any normal subgroup N and consider H/N first, we connect
+ all vertices within N (ex. N is C2 (the first dimension), then we move
+ to a left coset aN (an operation moving around the defined H/N group by
+ for example moving from the lower bound in C2 (dimension 2) to the
+ higher bound in C2. During this operation connection all the vertices.
+ Now repeat the N connections. Note that these elements can be connected
+ in parallel.
+ """
+ # Inherit class arguments
+ if symmetry is None:
+ symmetry = self.symmetry
+ # Build origin and supremum vectors
+ origin = [i[0] for i in self.bounds]
+ self.origin = origin
+ supremum = [i[1] for i in self.bounds]
+
+ self.supremum = supremum
+
+ if symmetry is None:
+ cbounds = self.bounds
+ else:
+ cbounds = copy.copy(self.bounds)
+ for i, j in enumerate(symmetry):
+ if i is not j:
+ # pop second entry on second symmetry vars
+ cbounds[i] = [self.bounds[symmetry[i]][0]]
+ # Sole (first) entry is the sup value and there is no
+ # origin:
+ cbounds[i] = [self.bounds[symmetry[i]][1]]
+ if (self.bounds[symmetry[i]] is not
+ self.bounds[symmetry[j]]):
+ logging.warning(f"Variable {i} was specified as "
+ f"symmetric to variable {j}, however"
+ f", the bounds {i} ="
+ f" {self.bounds[symmetry[i]]} and {j}"
+ f" ="
+ f" {self.bounds[symmetry[j]]} do not "
+ f"match, the mismatch was ignored in "
+ f"the initial triangulation.")
+ cbounds[i] = self.bounds[symmetry[j]]
+
+ if n is None:
+ # Build generator
+ self.cp = self.cyclic_product(cbounds, origin, supremum, centroid)
+ for i in self.cp:
+ i
+
+ try:
+ self.triangulated_vectors.append((tuple(self.origin),
+ tuple(self.supremum)))
+ except (AttributeError, KeyError):
+ self.triangulated_vectors = [(tuple(self.origin),
+ tuple(self.supremum))]
+
+ else:
+ # Check if generator already exists
+ try:
+ self.cp
+ except (AttributeError, KeyError):
+ self.cp = self.cyclic_product(cbounds, origin, supremum,
+ centroid)
+
+ try:
+ while len(self.V.cache) < n:
+ next(self.cp)
+ except StopIteration:
+ try:
+ self.triangulated_vectors.append((tuple(self.origin),
+ tuple(self.supremum)))
+ except (AttributeError, KeyError):
+ self.triangulated_vectors = [(tuple(self.origin),
+ tuple(self.supremum))]
+
+ if printout:
+ # for v in self.C0():
+ # v.print_out()
+ for v in self.V.cache:
+ self.V[v].print_out()
+
+ return
+
+ def refine(self, n=1):
+ if n is None:
+ try:
+ self.triangulated_vectors
+ self.refine_all()
+ return
+ except AttributeError as ae:
+ if str(ae) == "'Complex' object has no attribute " \
+ "'triangulated_vectors'":
+ self.triangulate(symmetry=self.symmetry)
+ return
+ else:
+ raise
+
+ nt = len(self.V.cache) + n # Target number of total vertices
+ # In the outer while loop we iterate until we have added an extra `n`
+ # vertices to the complex:
+ while len(self.V.cache) < nt: # while loop 1
+ try: # try 1
+ # Try to access triangulated_vectors, this should only be
+ # defined if an initial triangulation has already been
+ # performed:
+ self.triangulated_vectors
+ # Try a usual iteration of the current generator, if it
+ # does not exist or is exhausted then produce a new generator
+ try: # try 2
+ next(self.rls)
+ except (AttributeError, StopIteration, KeyError):
+ vp = self.triangulated_vectors[0]
+ self.rls = self.refine_local_space(*vp, bounds=self.bounds)
+ next(self.rls)
+
+ except (AttributeError, KeyError):
+ # If an initial triangulation has not been completed, then
+ # we start/continue the initial triangulation targeting `nt`
+ # vertices, if nt is greater than the initial number of
+ # vertices then the `refine` routine will move back to try 1.
+ self.triangulate(nt, self.symmetry)
+ return
+
+ def refine_all(self, centroids=True):
+ """Refine the entire domain of the current complex."""
+ try:
+ self.triangulated_vectors
+ tvs = copy.copy(self.triangulated_vectors)
+ for i, vp in enumerate(tvs):
+ self.rls = self.refine_local_space(*vp, bounds=self.bounds)
+ for i in self.rls:
+ i
+ except AttributeError as ae:
+ if str(ae) == "'Complex' object has no attribute " \
+ "'triangulated_vectors'":
+ self.triangulate(symmetry=self.symmetry, centroid=centroids)
+ else:
+ raise
+
+ # This adds a centroid to every new sub-domain generated and defined
+ # by self.triangulated_vectors, in addition the vertices ! to complete
+ # the triangulation
+ return
+
+ def refine_local_space(self, origin, supremum, bounds, centroid=1):
+ # Copy for later removal
+ origin_c = copy.copy(origin)
+ supremum_c = copy.copy(supremum)
+
+ # Initiate local variables redefined in later inner `for` loop:
+ vl, vu, a_vu = None, None, None
+
+ # Change the vector orientation so that it is only increasing
+ s_ov = list(origin)
+ s_origin = list(origin)
+ s_sv = list(supremum)
+ s_supremum = list(supremum)
+ for i, vi in enumerate(s_origin):
+ if s_ov[i] > s_sv[i]:
+ s_origin[i] = s_sv[i]
+ s_supremum[i] = s_ov[i]
+
+ vot = tuple(s_origin)
+ vut = tuple(s_supremum) # Hyperrectangle supremum
+
+ vo = self.V[vot] # initiate if doesn't exist yet
+ vs = self.V[vut]
+ # Start by finding the old centroid of the new space:
+ vco = self.split_edge(vo.x, vs.x) # Split in case not centroid arg
+
+ # Find set of extreme vertices in current local space
+ sup_set = copy.copy(vco.nn)
+ # Cyclic group approach with second x_l --- x_u operation.
+
+ # These containers store the "lower" and "upper" vertices
+ # corresponding to the origin or supremum of every C2 group.
+ # It has the structure of `dim` times embedded lists each containing
+ # these vertices as the entire complex grows. Bounds[0] has to be done
+ # outside the loops before we have symmetric containers.
+ # NOTE: This means that bounds[0][1] must always exist
+
+ a_vl = copy.copy(list(vot))
+ a_vl[0] = vut[0] # Update aN Origin
+ if tuple(a_vl) not in self.V.cache:
+ vo = self.V[vot] # initiate if doesn't exist yet
+ vs = self.V[vut]
+ # Start by finding the old centroid of the new space:
+ vco = self.split_edge(vo.x, vs.x) # Split in case not centroid arg
+
+ # Find set of extreme vertices in current local space
+ sup_set = copy.copy(vco.nn)
+ a_vl = copy.copy(list(vot))
+ a_vl[0] = vut[0] # Update aN Origin
+ a_vl = self.V[tuple(a_vl)]
+ else:
+ a_vl = self.V[tuple(a_vl)]
+
+ c_v = self.split_edge(vo.x, a_vl.x)
+ c_v.connect(vco)
+ yield c_v.x
+ Cox = [[vo]]
+ Ccx = [[c_v]]
+ Cux = [[a_vl]]
+ ab_C = [] # Container for a + b operations
+ s_ab_C = [] # Container for symmetric a + b operations
+
+ # Loop over remaining bounds
+ for i, x in enumerate(bounds[1:]):
+ # Update lower and upper containers
+ Cox.append([])
+ Ccx.append([])
+ Cux.append([])
+ # try to access a second bound (if not, C1 is symmetric)
+ try:
+ t_a_vl = list(vot)
+ t_a_vl[i + 1] = vut[i + 1]
+
+ # New: lists are used anyway, so copy all
+ # %%
+ # Copy lists for iteration
+ cCox = [x[:] for x in Cox[:i + 1]]
+ cCcx = [x[:] for x in Ccx[:i + 1]]
+ cCux = [x[:] for x in Cux[:i + 1]]
+ # Try to connect aN lower source of previous a + b
+ # operation with a aN vertex
+ ab_Cc = copy.copy(ab_C) # NOTE: We append ab_C in the
+ # (VL, VC, VU) for-loop, but we use the copy of the list in the
+ # ab_Cc for-loop.
+ s_ab_Cc = copy.copy(s_ab_C)
+
+ # Early try so that we don't have to copy the cache before
+ # moving on to next C1/C2: Try to add the operation of a new
+ # C2 product by accessing the upper bound
+ if tuple(t_a_vl) not in self.V.cache:
+ # Raise error to continue symmetric refine
+ raise IndexError
+ t_a_vu = list(vut)
+ t_a_vu[i + 1] = vut[i + 1]
+ if tuple(t_a_vu) not in self.V.cache:
+ # Raise error to continue symmetric refine:
+ raise IndexError
+
+ for vectors in s_ab_Cc:
+ # s_ab_C.append([c_vc, vl, vu, a_vu])
+ bc_vc = list(vectors[0].x)
+ b_vl = list(vectors[1].x)
+ b_vu = list(vectors[2].x)
+ ba_vu = list(vectors[3].x)
+
+ bc_vc[i + 1] = vut[i + 1]
+ b_vl[i + 1] = vut[i + 1]
+ b_vu[i + 1] = vut[i + 1]
+ ba_vu[i + 1] = vut[i + 1]
+
+ bc_vc = self.V[tuple(bc_vc)]
+ bc_vc.connect(vco) # NOTE: Unneeded?
+ yield bc_vc
+
+ # Split to centre, call this centre group "d = 0.5*a"
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
+ d_bc_vc.connect(bc_vc)
+ d_bc_vc.connect(vectors[1]) # Connect all to centroid
+ d_bc_vc.connect(vectors[2]) # Connect all to centroid
+ d_bc_vc.connect(vectors[3]) # Connect all to centroid
+ yield d_bc_vc.x
+ b_vl = self.V[tuple(b_vl)]
+ bc_vc.connect(b_vl) # Connect aN cross pairs
+ d_bc_vc.connect(b_vl) # Connect all to centroid
+
+ yield b_vl
+ b_vu = self.V[tuple(b_vu)]
+ bc_vc.connect(b_vu) # Connect aN cross pairs
+ d_bc_vc.connect(b_vu) # Connect all to centroid
+
+ b_vl_c = self.split_edge(b_vu.x, b_vl.x)
+ bc_vc.connect(b_vl_c)
+
+ yield b_vu
+ ba_vu = self.V[tuple(ba_vu)]
+ bc_vc.connect(ba_vu) # Connect aN cross pairs
+ d_bc_vc.connect(ba_vu) # Connect all to centroid
+
+ # Split the a + b edge of the initial triangulation:
+ os_v = self.split_edge(vectors[1].x, ba_vu.x) # o-s
+ ss_v = self.split_edge(b_vl.x, ba_vu.x) # s-s
+ b_vu_c = self.split_edge(b_vu.x, ba_vu.x)
+ bc_vc.connect(b_vu_c)
+ yield os_v.x # often equal to vco, but not always
+ yield ss_v.x # often equal to bc_vu, but not always
+ yield ba_vu
+ # Split remaining to centre, call this centre group
+ # "d = 0.5*a"
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ yield d_bc_vc.x
+ d_b_vl = self.split_edge(vectors[1].x, b_vl.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_b_vl) # Connect dN cross pairs
+ yield d_b_vl.x
+ d_b_vu = self.split_edge(vectors[2].x, b_vu.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_b_vu) # Connect dN cross pairs
+ yield d_b_vu.x
+ d_ba_vu = self.split_edge(vectors[3].x, ba_vu.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_ba_vu) # Connect dN cross pairs
+ yield d_ba_vu
+
+ # comb = [c_vc, vl, vu, a_vl, a_vu,
+ # bc_vc, b_vl, b_vu, ba_vl, ba_vu]
+ comb = [vl, vu, a_vu,
+ b_vl, b_vu, ba_vu]
+ comb_iter = itertools.combinations(comb, 2)
+ for vecs in comb_iter:
+ self.split_edge(vecs[0].x, vecs[1].x)
+ # Add new list of cross pairs
+ ab_C.append((d_bc_vc, vectors[1], b_vl, a_vu, ba_vu))
+ ab_C.append((d_bc_vc, vl, b_vl, a_vu, ba_vu)) # = prev
+
+ for vectors in ab_Cc:
+ bc_vc = list(vectors[0].x)
+ b_vl = list(vectors[1].x)
+ b_vu = list(vectors[2].x)
+ ba_vl = list(vectors[3].x)
+ ba_vu = list(vectors[4].x)
+ bc_vc[i + 1] = vut[i + 1]
+ b_vl[i + 1] = vut[i + 1]
+ b_vu[i + 1] = vut[i + 1]
+ ba_vl[i + 1] = vut[i + 1]
+ ba_vu[i + 1] = vut[i + 1]
+ bc_vc = self.V[tuple(bc_vc)]
+ bc_vc.connect(vco) # NOTE: Unneeded?
+ yield bc_vc
+
+ # Split to centre, call this centre group "d = 0.5*a"
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
+ d_bc_vc.connect(bc_vc)
+ d_bc_vc.connect(vectors[1]) # Connect all to centroid
+ d_bc_vc.connect(vectors[2]) # Connect all to centroid
+ d_bc_vc.connect(vectors[3]) # Connect all to centroid
+ d_bc_vc.connect(vectors[4]) # Connect all to centroid
+ yield d_bc_vc.x
+ b_vl = self.V[tuple(b_vl)]
+ bc_vc.connect(b_vl) # Connect aN cross pairs
+ d_bc_vc.connect(b_vl) # Connect all to centroid
+ yield b_vl
+ b_vu = self.V[tuple(b_vu)]
+ bc_vc.connect(b_vu) # Connect aN cross pairs
+ d_bc_vc.connect(b_vu) # Connect all to centroid
+ yield b_vu
+ ba_vl = self.V[tuple(ba_vl)]
+ bc_vc.connect(ba_vl) # Connect aN cross pairs
+ d_bc_vc.connect(ba_vl) # Connect all to centroid
+ self.split_edge(b_vu.x, ba_vl.x)
+ yield ba_vl
+ ba_vu = self.V[tuple(ba_vu)]
+ bc_vc.connect(ba_vu) # Connect aN cross pairs
+ d_bc_vc.connect(ba_vu) # Connect all to centroid
+ # Split the a + b edge of the initial triangulation:
+ os_v = self.split_edge(vectors[1].x, ba_vu.x) # o-s
+ ss_v = self.split_edge(b_vl.x, ba_vu.x) # s-s
+ yield os_v.x # often equal to vco, but not always
+ yield ss_v.x # often equal to bc_vu, but not always
+ yield ba_vu
+ # Split remaining to centre, call this centre group
+ # "d = 0.5*a"
+ d_bc_vc = self.split_edge(vectors[0].x, bc_vc.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ yield d_bc_vc.x
+ d_b_vl = self.split_edge(vectors[1].x, b_vl.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_b_vl) # Connect dN cross pairs
+ yield d_b_vl.x
+ d_b_vu = self.split_edge(vectors[2].x, b_vu.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_b_vu) # Connect dN cross pairs
+ yield d_b_vu.x
+ d_ba_vl = self.split_edge(vectors[3].x, ba_vl.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_ba_vl) # Connect dN cross pairs
+ yield d_ba_vl
+ d_ba_vu = self.split_edge(vectors[4].x, ba_vu.x)
+ d_bc_vc.connect(vco) # NOTE: Unneeded?
+ d_bc_vc.connect(d_ba_vu) # Connect dN cross pairs
+ yield d_ba_vu
+ c_vc, vl, vu, a_vl, a_vu = vectors
+
+ comb = [vl, vu, a_vl, a_vu,
+ b_vl, b_vu, ba_vl, ba_vu]
+ comb_iter = itertools.combinations(comb, 2)
+ for vecs in comb_iter:
+ self.split_edge(vecs[0].x, vecs[1].x)
+
+ # Add new list of cross pairs
+ ab_C.append((bc_vc, b_vl, b_vu, ba_vl, ba_vu))
+ ab_C.append((d_bc_vc, d_b_vl, d_b_vu, d_ba_vl, d_ba_vu))
+ ab_C.append((d_bc_vc, vectors[1], b_vl, a_vu, ba_vu))
+ ab_C.append((d_bc_vc, vu, b_vu, a_vl, ba_vl))
+
+ for j, (VL, VC, VU) in enumerate(zip(cCox, cCcx, cCux)):
+ for k, (vl, vc, vu) in enumerate(zip(VL, VC, VU)):
+ # Build aN vertices for each lower-upper C3 group in N:
+ a_vl = list(vl.x)
+ a_vu = list(vu.x)
+ a_vl[i + 1] = vut[i + 1]
+ a_vu[i + 1] = vut[i + 1]
+ a_vl = self.V[tuple(a_vl)]
+ a_vu = self.V[tuple(a_vu)]
+ # Note, build (a + vc) later for consistent yields
+ # Split the a + b edge of the initial triangulation:
+ c_vc = self.split_edge(vl.x, a_vu.x)
+ self.split_edge(vl.x, vu.x) # Equal to vc
+ # Build cN vertices for each lower-upper C3 group in N:
+ c_vc.connect(vco)
+ c_vc.connect(vc)
+ c_vc.connect(vl) # Connect c + ac operations
+ c_vc.connect(vu) # Connect c + ac operations
+ c_vc.connect(a_vl) # Connect c + ac operations
+ c_vc.connect(a_vu) # Connect c + ac operations
+ yield c_vc.x
+ c_vl = self.split_edge(vl.x, a_vl.x)
+ c_vl.connect(vco)
+ c_vc.connect(c_vl) # Connect cN group vertices
+ yield c_vl.x
+ # yield at end of loop:
+ c_vu = self.split_edge(vu.x, a_vu.x)
+ c_vu.connect(vco)
+ # Connect remaining cN group vertices
+ c_vc.connect(c_vu) # Connect cN group vertices
+ yield c_vu.x
+
+ a_vc = self.split_edge(a_vl.x, a_vu.x) # is (a + vc) ?
+ a_vc.connect(vco)
+ a_vc.connect(c_vc)
+
+ # Storage for connecting c + ac operations:
+ ab_C.append((c_vc, vl, vu, a_vl, a_vu))
+
+ # Update the containers
+ Cox[i + 1].append(vl)
+ Cox[i + 1].append(vc)
+ Cox[i + 1].append(vu)
+ Ccx[i + 1].append(c_vl)
+ Ccx[i + 1].append(c_vc)
+ Ccx[i + 1].append(c_vu)
+ Cux[i + 1].append(a_vl)
+ Cux[i + 1].append(a_vc)
+ Cux[i + 1].append(a_vu)
+
+ # Update old containers
+ Cox[j].append(c_vl) # !
+ Cox[j].append(a_vl)
+ Ccx[j].append(c_vc) # !
+ Ccx[j].append(a_vc) # !
+ Cux[j].append(c_vu) # !
+ Cux[j].append(a_vu)
+
+ # Yield new points
+ yield a_vc.x
+
+ except IndexError:
+ for vectors in ab_Cc:
+ ba_vl = list(vectors[3].x)
+ ba_vu = list(vectors[4].x)
+ ba_vl[i + 1] = vut[i + 1]
+ ba_vu[i + 1] = vut[i + 1]
+ ba_vu = self.V[tuple(ba_vu)]
+ yield ba_vu
+ d_bc_vc = self.split_edge(vectors[1].x, ba_vu.x) # o-s
+ yield ba_vu
+ d_bc_vc.connect(vectors[1]) # Connect all to centroid
+ d_bc_vc.connect(vectors[2]) # Connect all to centroid
+ d_bc_vc.connect(vectors[3]) # Connect all to centroid
+ d_bc_vc.connect(vectors[4]) # Connect all to centroid
+ yield d_bc_vc.x
+ ba_vl = self.V[tuple(ba_vl)]
+ yield ba_vl
+ d_ba_vl = self.split_edge(vectors[3].x, ba_vl.x)
+ d_ba_vu = self.split_edge(vectors[4].x, ba_vu.x)
+ d_ba_vc = self.split_edge(d_ba_vl.x, d_ba_vu.x)
+ yield d_ba_vl
+ yield d_ba_vu
+ yield d_ba_vc
+ c_vc, vl, vu, a_vl, a_vu = vectors
+ comb = [vl, vu, a_vl, a_vu,
+ ba_vl,
+ ba_vu]
+ comb_iter = itertools.combinations(comb, 2)
+ for vecs in comb_iter:
+ self.split_edge(vecs[0].x, vecs[1].x)
+
+ # Copy lists for iteration
+ cCox = Cox[i]
+ cCcx = Ccx[i]
+ cCux = Cux[i]
+ VL, VC, VU = cCox, cCcx, cCux
+ for k, (vl, vc, vu) in enumerate(zip(VL, VC, VU)):
+ # Build aN vertices for each lower-upper pair in N:
+ a_vu = list(vu.x)
+ a_vu[i + 1] = vut[i + 1]
+
+ # Connect vertices in N to corresponding vertices
+ # in aN:
+ a_vu = self.V[tuple(a_vu)]
+ yield a_vl.x
+ # Split the a + b edge of the initial triangulation:
+ c_vc = self.split_edge(vl.x, a_vu.x)
+ self.split_edge(vl.x, vu.x) # Equal to vc
+ c_vc.connect(vco)
+ c_vc.connect(vc)
+ c_vc.connect(vl) # Connect c + ac operations
+ c_vc.connect(vu) # Connect c + ac operations
+ c_vc.connect(a_vu) # Connect c + ac operations
+ yield (c_vc.x)
+ c_vu = self.split_edge(vu.x,
+ a_vu.x) # yield at end of loop
+ c_vu.connect(vco)
+ # Connect remaining cN group vertices
+ c_vc.connect(c_vu) # Connect cN group vertices
+ yield (c_vu.x)
+
+ # Update the containers
+ Cox[i + 1].append(vu)
+ Ccx[i + 1].append(c_vu)
+ Cux[i + 1].append(a_vu)
+
+ # Update old containers
+ s_ab_C.append([c_vc, vl, vu, a_vu])
+
+ yield a_vu.x
+
+ # Clean class trash
+ try:
+ del Cox
+ del Ccx
+ del Cux
+ del ab_C
+ del ab_Cc
+ except UnboundLocalError:
+ pass
+
+ try:
+ self.triangulated_vectors.remove((tuple(origin_c),
+ tuple(supremum_c)))
+ except ValueError:
+ # Turn this into a logging warning?
+ pass
+ # Add newly triangulated vectors:
+ for vs in sup_set:
+ self.triangulated_vectors.append((tuple(vco.x), tuple(vs.x)))
+
+ # Extra yield to ensure that the triangulation is completed
+ if centroid:
+ vcn_set = set()
+ c_nn_lists = []
+ for vs in sup_set:
+ # Build centroid
+ c_nn = self.vpool(vco.x, vs.x)
+ try:
+ c_nn.remove(vcn_set)
+ except KeyError:
+ pass
+ c_nn_lists.append(c_nn)
+
+ for c_nn in c_nn_lists:
+ try:
+ c_nn.remove(vcn_set)
+ except KeyError:
+ pass
+
+ for vs, c_nn in zip(sup_set, c_nn_lists):
+ # Build centroid
+ vcn = self.split_edge(vco.x, vs.x)
+ vcn_set.add(vcn)
+ try: # Shouldn't be needed?
+ c_nn.remove(vcn_set)
+ except KeyError:
+ pass
+ for vnn in c_nn:
+ vcn.connect(vnn)
+ yield vcn.x
+ else:
+ pass
+
+ yield vut
+ return
+
+ def refine_star(self, v):
+ """Refine the star domain of a vertex `v`."""
+ # Copy lists before iteration
+ vnn = copy.copy(v.nn)
+ v1nn = []
+ d_v0v1_set = set()
+ for v1 in vnn:
+ v1nn.append(copy.copy(v1.nn))
+
+ for v1, v1nn in zip(vnn, v1nn):
+ vnnu = v1nn.intersection(vnn)
+
+ d_v0v1 = self.split_edge(v.x, v1.x)
+ for o_d_v0v1 in d_v0v1_set:
+ d_v0v1.connect(o_d_v0v1)
+ d_v0v1_set.add(d_v0v1)
+ for v2 in vnnu:
+ d_v1v2 = self.split_edge(v1.x, v2.x)
+ d_v0v1.connect(d_v1v2)
+ return
+
+ def _split_edge(self, v1, v2):
+ v1 = self.V[v1]
+ v2 = self.V[v2]
+ # Destroy original edge, if it exists:
+ v1.disconnect(v2)
+ # Compute vertex on centre of edge:
+ try:
+ vct = (v2.x_a - v1.x_a) / 2.0 + v1.x_a
+ except TypeError: # Allow for decimal operations
+ vct = (v2.x_a - v1.x_a) / decimal.Decimal(2.0) + v1.x_a
+
+ vc = self.V[tuple(vct)]
+ # Connect to original 2 vertices to the new centre vertex
+ vc.connect(v1)
+ vc.connect(v2)
+ return vc
+
+ def vpool(self, origin, supremum):
+ vot = tuple(origin)
+ vst = tuple(supremum)
+ # Initiate vertices in case they don't exist
+ vo = self.V[vot]
+ vs = self.V[vst]
+
+ # Remove origin - supremum disconnect
+
+ # Find the lower/upper bounds of the refinement hyperrectangle
+ bl = list(vot)
+ bu = list(vst)
+ for i, (voi, vsi) in enumerate(zip(vot, vst)):
+ if bl[i] > vsi:
+ bl[i] = vsi
+ if bu[i] < voi:
+ bu[i] = voi
+
+ # NOTE: This is mostly done with sets/lists because we aren't sure
+ # how well the numpy arrays will scale to thousands of
+ # dimensions.
+ vn_pool = set()
+ vn_pool.update(vo.nn)
+ vn_pool.update(vs.nn)
+ cvn_pool = copy.copy(vn_pool)
+ for vn in cvn_pool:
+ for i, xi in enumerate(vn.x):
+ if bl[i] <= xi <= bu[i]:
+ pass
+ else:
+ try:
+ vn_pool.remove(vn)
+ except KeyError:
+ pass # NOTE: Not all neighbours are in initial pool
+ return vn_pool
+
+ def vf_to_vv(self, vertices, simplices):
+ """
+ Convert a vertex-face mesh to a vertex-vertex mesh used by this class
+
+ Parameters
+ ----------
+ vertices : list
+ Vertices
+ simplices : list
+ Simplices
+ """
+ if self.dim > 1:
+ for s in simplices:
+ edges = itertools.combinations(s, self.dim)
+ for e in edges:
+ self.V[tuple(vertices[e[0]])].connect(
+ self.V[tuple(vertices[e[1]])])
+ else:
+ for e in simplices:
+ self.V[tuple(vertices[e[0]])].connect(
+ self.V[tuple(vertices[e[1]])])
+ return
+
+ def connect_vertex_non_symm(self, v_x, near=None):
+ """
+ Adds a vertex at coords v_x to the complex that is not symmetric to the
+ initial triangulation and sub-triangulation.
+
+ If near is specified (for example; a star domain or collections of
+ cells known to contain v) then only those simplices containd in near
+ will be searched, this greatly speeds up the process.
+
+ If near is not specified this method will search the entire simplicial
+ complex structure.
+
+ Parameters
+ ----------
+ v_x : tuple
+ Coordinates of non-symmetric vertex
+ near : set or list
+ List of vertices, these are points near v to check for
+ """
+ if near is None:
+ star = self.V
+ else:
+ star = near
+ # Create the vertex origin
+ if tuple(v_x) in self.V.cache:
+ if self.V[v_x] in self.V_non_symm:
+ pass
+ else:
+ return
+
+ self.V[v_x]
+ found_nn = False
+ S_rows = []
+ for v in star:
+ S_rows.append(v.x)
+
+ S_rows = np.array(S_rows)
+ A = np.array(S_rows) - np.array(v_x)
+ # Iterate through all the possible simplices of S_rows
+ for s_i in itertools.combinations(range(S_rows.shape[0]),
+ r=self.dim + 1):
+ # Check if connected, else s_i is not a simplex
+ valid_simplex = True
+ for i in itertools.combinations(s_i, r=2):
+ # Every combination of vertices must be connected, we check of
+ # the current iteration of all combinations of s_i are
+ # connected we break the loop if it is not.
+ if ((self.V[tuple(S_rows[i[1]])] not in
+ self.V[tuple(S_rows[i[0]])].nn)
+ and (self.V[tuple(S_rows[i[0]])] not in
+ self.V[tuple(S_rows[i[1]])].nn)):
+ valid_simplex = False
+ break
+
+ S = S_rows[tuple([s_i])]
+ if valid_simplex:
+ if self.deg_simplex(S, proj=None):
+ valid_simplex = False
+
+ # If s_i is a valid simplex we can test if v_x is inside si
+ if valid_simplex:
+ # Find the A_j0 value from the precalculated values
+ A_j0 = A[tuple([s_i])]
+ if self.in_simplex(S, v_x, A_j0):
+ found_nn = True
+ # breaks the main for loop, s_i is the target simplex:
+ break
+
+ # Connect the simplex to point
+ if found_nn:
+ for i in s_i:
+ self.V[v_x].connect(self.V[tuple(S_rows[i])])
+ # Attached the simplex to storage for all non-symmetric vertices
+ self.V_non_symm.append(self.V[v_x])
+ # this bool value indicates a successful connection if True:
+ return found_nn
+
+ def in_simplex(self, S, v_x, A_j0=None):
+ """Check if a vector v_x is in simplex `S`.
+
+ Parameters
+ ----------
+ S : array_like
+ Array containing simplex entries of vertices as rows
+ v_x :
+ A candidate vertex
+ A_j0 : array, optional,
+ Allows for A_j0 to be pre-calculated
+
+ Returns
+ -------
+ res : boolean
+ True if `v_x` is in `S`
+ """
+ A_11 = np.delete(S, 0, 0) - S[0]
+
+ sign_det_A_11 = np.sign(np.linalg.det(A_11))
+ if sign_det_A_11 == 0:
+ # NOTE: We keep the variable A_11, but we loop through A_jj
+ # ind=
+ # while sign_det_A_11 == 0:
+ # A_11 = np.delete(S, ind, 0) - S[ind]
+ # sign_det_A_11 = np.sign(np.linalg.det(A_11))
+
+ sign_det_A_11 = -1 # TODO: Choose another det of j instead?
+ # TODO: Unlikely to work in many cases
+
+ if A_j0 is None:
+ A_j0 = S - v_x
+
+ for d in range(self.dim + 1):
+ det_A_jj = (-1)**d * sign_det_A_11
+ # TODO: Note that scipy might be faster to add as an optional
+ # dependency
+ sign_det_A_j0 = np.sign(np.linalg.det(np.delete(A_j0, d,
+ 0)))
+ # TODO: Note if sign_det_A_j0 == then the point is coplanar to the
+ # current simplex facet, so perhaps return True and attach?
+ if det_A_jj == sign_det_A_j0:
+ continue
+ else:
+ return False
+
+ return True
+
+ def deg_simplex(self, S, proj=None):
+ """Test a simplex S for degeneracy (linear dependence in R^dim).
+
+ Parameters
+ ----------
+ S : np.array
+ Simplex with rows as vertex vectors
+ proj : array, optional,
+ If the projection S[1:] - S[0] is already
+ computed it can be added as an optional argument.
+ """
+ # Strategy: we test all combination of faces, if any of the
+ # determinants are zero then the vectors lie on the same face and is
+ # therefore linearly dependent in the space of R^dim
+ if proj is None:
+ proj = S[1:] - S[0]
+
+ # TODO: Is checking the projection of one vertex against faces of other
+ # vertices sufficient? Or do we need to check more vertices in
+ # dimensions higher than 2?
+ # TODO: Literature seems to suggest using proj.T, but why is this
+ # needed?
+ if np.linalg.det(proj) == 0.0: # TODO: Replace with tolerance?
+ return True # Simplex is degenerate
+ else:
+ return False # Simplex is not degenerate
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_vertex.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_vertex.py
new file mode 100644
index 0000000000000000000000000000000000000000..e47558ee7b9a181638841c34bb63603b5d37e221
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_shgo_lib/_vertex.py
@@ -0,0 +1,460 @@
+import collections
+from abc import ABC, abstractmethod
+
+import numpy as np
+
+from scipy._lib._util import MapWrapper
+
+
+class VertexBase(ABC):
+ """
+ Base class for a vertex.
+ """
+ def __init__(self, x, nn=None, index=None):
+ """
+ Initiation of a vertex object.
+
+ Parameters
+ ----------
+ x : tuple or vector
+ The geometric location (domain).
+ nn : list, optional
+ Nearest neighbour list.
+ index : int, optional
+ Index of vertex.
+ """
+ self.x = x
+ self.hash = hash(self.x) # Save precomputed hash
+
+ if nn is not None:
+ self.nn = set(nn) # can use .indexupdate to add a new list
+ else:
+ self.nn = set()
+
+ self.index = index
+
+ def __hash__(self):
+ return self.hash
+
+ def __getattr__(self, item):
+ if item not in ['x_a']:
+ raise AttributeError(f"{type(self)} object has no attribute "
+ f"'{item}'")
+ if item == 'x_a':
+ self.x_a = np.array(self.x)
+ return self.x_a
+
+ @abstractmethod
+ def connect(self, v):
+ raise NotImplementedError("This method is only implemented with an "
+ "associated child of the base class.")
+
+ @abstractmethod
+ def disconnect(self, v):
+ raise NotImplementedError("This method is only implemented with an "
+ "associated child of the base class.")
+
+ def star(self):
+ """Returns the star domain ``st(v)`` of the vertex.
+
+ Parameters
+ ----------
+ v :
+ The vertex ``v`` in ``st(v)``
+
+ Returns
+ -------
+ st : set
+ A set containing all the vertices in ``st(v)``
+ """
+ self.st = self.nn
+ self.st.add(self)
+ return self.st
+
+
+class VertexScalarField(VertexBase):
+ """
+ Add homology properties of a scalar field f: R^n --> R associated with
+ the geometry built from the VertexBase class
+ """
+
+ def __init__(self, x, field=None, nn=None, index=None, field_args=(),
+ g_cons=None, g_cons_args=()):
+ """
+ Parameters
+ ----------
+ x : tuple,
+ vector of vertex coordinates
+ field : callable, optional
+ a scalar field f: R^n --> R associated with the geometry
+ nn : list, optional
+ list of nearest neighbours
+ index : int, optional
+ index of the vertex
+ field_args : tuple, optional
+ additional arguments to be passed to field
+ g_cons : callable, optional
+ constraints on the vertex
+ g_cons_args : tuple, optional
+ additional arguments to be passed to g_cons
+
+ """
+ super().__init__(x, nn=nn, index=index)
+
+ # Note Vertex is only initiated once for all x so only
+ # evaluated once
+ # self.feasible = None
+
+ # self.f is externally defined by the cache to allow parallel
+ # processing
+ # None type that will break arithmetic operations unless defined
+ # self.f = None
+
+ self.check_min = True
+ self.check_max = True
+
+ def connect(self, v):
+ """Connects self to another vertex object v.
+
+ Parameters
+ ----------
+ v : VertexBase or VertexScalarField object
+ """
+ if v is not self and v not in self.nn:
+ self.nn.add(v)
+ v.nn.add(self)
+
+ # Flags for checking homology properties:
+ self.check_min = True
+ self.check_max = True
+ v.check_min = True
+ v.check_max = True
+
+ def disconnect(self, v):
+ if v in self.nn:
+ self.nn.remove(v)
+ v.nn.remove(self)
+
+ # Flags for checking homology properties:
+ self.check_min = True
+ self.check_max = True
+ v.check_min = True
+ v.check_max = True
+
+ def minimiser(self):
+ """Check whether this vertex is strictly less than all its
+ neighbours"""
+ if self.check_min:
+ self._min = all(self.f < v.f for v in self.nn)
+ self.check_min = False
+
+ return self._min
+
+ def maximiser(self):
+ """
+ Check whether this vertex is strictly greater than all its
+ neighbours.
+ """
+ if self.check_max:
+ self._max = all(self.f > v.f for v in self.nn)
+ self.check_max = False
+
+ return self._max
+
+
+class VertexVectorField(VertexBase):
+ """
+ Add homology properties of a scalar field f: R^n --> R^m associated with
+ the geometry built from the VertexBase class.
+ """
+
+ def __init__(self, x, sfield=None, vfield=None, field_args=(),
+ vfield_args=(), g_cons=None,
+ g_cons_args=(), nn=None, index=None):
+ super().__init__(x, nn=nn, index=index)
+
+ raise NotImplementedError("This class is still a work in progress")
+
+
+class VertexCacheBase:
+ """Base class for a vertex cache for a simplicial complex."""
+ def __init__(self):
+
+ self.cache = collections.OrderedDict()
+ self.nfev = 0 # Feasible points
+ self.index = -1
+
+ def __iter__(self):
+ for v in self.cache:
+ yield self.cache[v]
+ return
+
+ def size(self):
+ """Returns the size of the vertex cache."""
+ return self.index + 1
+
+ def print_out(self):
+ headlen = len(f"Vertex cache of size: {len(self.cache)}:")
+ print('=' * headlen)
+ print(f"Vertex cache of size: {len(self.cache)}:")
+ print('=' * headlen)
+ for v in self.cache:
+ self.cache[v].print_out()
+
+
+class VertexCube(VertexBase):
+ """Vertex class to be used for a pure simplicial complex with no associated
+ differential geometry (single level domain that exists in R^n)"""
+ def __init__(self, x, nn=None, index=None):
+ super().__init__(x, nn=nn, index=index)
+
+ def connect(self, v):
+ if v is not self and v not in self.nn:
+ self.nn.add(v)
+ v.nn.add(self)
+
+ def disconnect(self, v):
+ if v in self.nn:
+ self.nn.remove(v)
+ v.nn.remove(self)
+
+
+class VertexCacheIndex(VertexCacheBase):
+ def __init__(self):
+ """
+ Class for a vertex cache for a simplicial complex without an associated
+ field. Useful only for building and visualising a domain complex.
+
+ Parameters
+ ----------
+ """
+ super().__init__()
+ self.Vertex = VertexCube
+
+ def __getitem__(self, x, nn=None):
+ try:
+ return self.cache[x]
+ except KeyError:
+ self.index += 1
+ xval = self.Vertex(x, index=self.index)
+ # logging.info("New generated vertex at x = {}".format(x))
+ # NOTE: Surprisingly high performance increase if logging
+ # is commented out
+ self.cache[x] = xval
+ return self.cache[x]
+
+
+class VertexCacheField(VertexCacheBase):
+ def __init__(self, field=None, field_args=(), g_cons=None, g_cons_args=(),
+ workers=1):
+ """
+ Class for a vertex cache for a simplicial complex with an associated
+ field.
+
+ Parameters
+ ----------
+ field : callable
+ Scalar or vector field callable.
+ field_args : tuple, optional
+ Any additional fixed parameters needed to completely specify the
+ field function
+ g_cons : dict or sequence of dict, optional
+ Constraints definition.
+ Function(s) ``R**n`` in the form::
+ g_cons_args : tuple, optional
+ Any additional fixed parameters needed to completely specify the
+ constraint functions
+ workers : int optional
+ Uses `multiprocessing.Pool `) to compute the field
+ functions in parallel.
+
+ """
+ super().__init__()
+ self.index = -1
+ self.Vertex = VertexScalarField
+ self.field = field
+ self.field_args = field_args
+ self.wfield = FieldWrapper(field, field_args) # if workers is not 1
+
+ self.g_cons = g_cons
+ self.g_cons_args = g_cons_args
+ self.wgcons = ConstraintWrapper(g_cons, g_cons_args)
+ self.gpool = set() # A set of tuples to process for feasibility
+
+ # Field processing objects
+ self.fpool = set() # A set of tuples to process for scalar function
+ self.sfc_lock = False # True if self.fpool is non-Empty
+
+ self.workers = workers
+ self._mapwrapper = MapWrapper(workers)
+
+ if workers == 1:
+ self.process_gpool = self.proc_gpool
+ if g_cons is None:
+ self.process_fpool = self.proc_fpool_nog
+ else:
+ self.process_fpool = self.proc_fpool_g
+ else:
+ self.process_gpool = self.pproc_gpool
+ if g_cons is None:
+ self.process_fpool = self.pproc_fpool_nog
+ else:
+ self.process_fpool = self.pproc_fpool_g
+
+ def __getitem__(self, x, nn=None):
+ try:
+ return self.cache[x]
+ except KeyError:
+ self.index += 1
+ xval = self.Vertex(x, field=self.field, nn=nn, index=self.index,
+ field_args=self.field_args,
+ g_cons=self.g_cons,
+ g_cons_args=self.g_cons_args)
+
+ self.cache[x] = xval # Define in cache
+ self.gpool.add(xval) # Add to pool for processing feasibility
+ self.fpool.add(xval) # Add to pool for processing field values
+ return self.cache[x]
+
+ def __getstate__(self):
+ self_dict = self.__dict__.copy()
+ del self_dict['pool']
+ return self_dict
+
+ def process_pools(self):
+ if self.g_cons is not None:
+ self.process_gpool()
+ self.process_fpool()
+ self.proc_minimisers()
+
+ def feasibility_check(self, v):
+ v.feasible = True
+ for g, args in zip(self.g_cons, self.g_cons_args):
+ # constraint may return more than 1 value.
+ if np.any(g(v.x_a, *args) < 0.0):
+ v.f = np.inf
+ v.feasible = False
+ break
+
+ def compute_sfield(self, v):
+ """Compute the scalar field values of a vertex object `v`.
+
+ Parameters
+ ----------
+ v : VertexBase or VertexScalarField object
+ """
+ try:
+ v.f = self.field(v.x_a, *self.field_args)
+ self.nfev += 1
+ except AttributeError:
+ v.f = np.inf
+ # logging.warning(f"Field function not found at x = {self.x_a}")
+ if np.isnan(v.f):
+ v.f = np.inf
+
+ def proc_gpool(self):
+ """Process all constraints."""
+ if self.g_cons is not None:
+ for v in self.gpool:
+ self.feasibility_check(v)
+ # Clean the pool
+ self.gpool = set()
+
+ def pproc_gpool(self):
+ """Process all constraints in parallel."""
+ gpool_l = []
+ for v in self.gpool:
+ gpool_l.append(v.x_a)
+
+ G = self._mapwrapper(self.wgcons.gcons, gpool_l)
+ for v, g in zip(self.gpool, G):
+ v.feasible = g # set vertex object attribute v.feasible = g (bool)
+
+ def proc_fpool_g(self):
+ """Process all field functions with constraints supplied."""
+ for v in self.fpool:
+ if v.feasible:
+ self.compute_sfield(v)
+ # Clean the pool
+ self.fpool = set()
+
+ def proc_fpool_nog(self):
+ """Process all field functions with no constraints supplied."""
+ for v in self.fpool:
+ self.compute_sfield(v)
+ # Clean the pool
+ self.fpool = set()
+
+ def pproc_fpool_g(self):
+ """
+ Process all field functions with constraints supplied in parallel.
+ """
+ self.wfield.func
+ fpool_l = []
+ for v in self.fpool:
+ if v.feasible:
+ fpool_l.append(v.x_a)
+ else:
+ v.f = np.inf
+ F = self._mapwrapper(self.wfield.func, fpool_l)
+ for va, f in zip(fpool_l, F):
+ vt = tuple(va)
+ self[vt].f = f # set vertex object attribute v.f = f
+ self.nfev += 1
+ # Clean the pool
+ self.fpool = set()
+
+ def pproc_fpool_nog(self):
+ """
+ Process all field functions with no constraints supplied in parallel.
+ """
+ self.wfield.func
+ fpool_l = []
+ for v in self.fpool:
+ fpool_l.append(v.x_a)
+ F = self._mapwrapper(self.wfield.func, fpool_l)
+ for va, f in zip(fpool_l, F):
+ vt = tuple(va)
+ self[vt].f = f # set vertex object attribute v.f = f
+ self.nfev += 1
+ # Clean the pool
+ self.fpool = set()
+
+ def proc_minimisers(self):
+ """Check for minimisers."""
+ for v in self:
+ v.minimiser()
+ v.maximiser()
+
+
+class ConstraintWrapper:
+ """Object to wrap constraints to pass to `multiprocessing.Pool`."""
+ def __init__(self, g_cons, g_cons_args):
+ self.g_cons = g_cons
+ self.g_cons_args = g_cons_args
+
+ def gcons(self, v_x_a):
+ vfeasible = True
+ for g, args in zip(self.g_cons, self.g_cons_args):
+ # constraint may return more than 1 value.
+ if np.any(g(v_x_a, *args) < 0.0):
+ vfeasible = False
+ break
+ return vfeasible
+
+
+class FieldWrapper:
+ """Object to wrap field to pass to `multiprocessing.Pool`."""
+ def __init__(self, field, field_args):
+ self.field = field
+ self.field_args = field_args
+
+ def func(self, v_x_a):
+ try:
+ v_f = self.field(v_x_a, *self.field_args)
+ except Exception:
+ v_f = np.inf
+ if np.isnan(v_f):
+ v_f = np.inf
+
+ return v_f
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_slsqp_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_slsqp_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..225c7541aee407674206ccdcda257dd4e06672df
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_slsqp_py.py
@@ -0,0 +1,612 @@
+"""
+This module implements the Sequential Least Squares Programming optimization
+algorithm (SLSQP), originally developed by Dieter Kraft.
+See http://www.netlib.org/toms/733
+
+Functions
+---------
+.. autosummary::
+ :toctree: generated/
+
+ approx_jacobian
+ fmin_slsqp
+
+"""
+
+__all__ = ['approx_jacobian', 'fmin_slsqp']
+
+import numpy as np
+from ._slsqplib import slsqp
+from scipy.linalg import norm as lanorm
+from ._optimize import (OptimizeResult, _check_unknown_options,
+ _prepare_scalar_function, _clip_x_for_func,
+ _check_clip_x, _wrap_callback)
+from ._numdiff import approx_derivative
+from ._constraints import old_bound_to_new, _arr_to_scalar
+from scipy._lib._array_api import array_namespace
+from scipy._lib import array_api_extra as xpx
+from scipy._lib._util import _call_callback_maybe_halt
+from numpy.typing import NDArray
+
+__docformat__ = "restructuredtext en"
+
+_epsilon = np.sqrt(np.finfo(np.float64).eps)
+
+
+def approx_jacobian(x, func, epsilon, *args):
+ """
+ Approximate the Jacobian matrix of a callable function.
+
+ Parameters
+ ----------
+ x : array_like
+ The state vector at which to compute the Jacobian matrix.
+ func : callable f(x,*args)
+ The vector-valued function.
+ epsilon : float
+ The perturbation used to determine the partial derivatives.
+ args : sequence
+ Additional arguments passed to func.
+
+ Returns
+ -------
+ An array of dimensions ``(lenf, lenx)`` where ``lenf`` is the length
+ of the outputs of `func`, and ``lenx`` is the number of elements in
+ `x`.
+
+ Notes
+ -----
+ The approximation is done using forward differences.
+
+ """
+ # approx_derivative returns (m, n) == (lenf, lenx)
+ jac = approx_derivative(func, x, method='2-point', abs_step=epsilon,
+ args=args)
+ # if func returns a scalar jac.shape will be (lenx,). Make sure
+ # it's at least a 2D array.
+ return np.atleast_2d(jac)
+
+
+def fmin_slsqp(func, x0, eqcons=(), f_eqcons=None, ieqcons=(), f_ieqcons=None,
+ bounds=(), fprime=None, fprime_eqcons=None,
+ fprime_ieqcons=None, args=(), iter=100, acc=1.0E-6,
+ iprint=1, disp=None, full_output=0, epsilon=_epsilon,
+ callback=None):
+ """
+ Minimize a function using Sequential Least Squares Programming
+
+ Python interface function for the SLSQP Optimization subroutine
+ originally implemented by Dieter Kraft.
+
+ Parameters
+ ----------
+ func : callable f(x,*args)
+ Objective function. Must return a scalar.
+ x0 : 1-D ndarray of float
+ Initial guess for the independent variable(s).
+ eqcons : list, optional
+ A list of functions of length n such that
+ eqcons[j](x,*args) == 0.0 in a successfully optimized
+ problem.
+ f_eqcons : callable f(x,*args), optional
+ Returns a 1-D array in which each element must equal 0.0 in a
+ successfully optimized problem. If f_eqcons is specified,
+ eqcons is ignored.
+ ieqcons : list, optional
+ A list of functions of length n such that
+ ieqcons[j](x,*args) >= 0.0 in a successfully optimized
+ problem.
+ f_ieqcons : callable f(x,*args), optional
+ Returns a 1-D ndarray in which each element must be greater or
+ equal to 0.0 in a successfully optimized problem. If
+ f_ieqcons is specified, ieqcons is ignored.
+ bounds : list, optional
+ A list of tuples specifying the lower and upper bound
+ for each independent variable [(xl0, xu0),(xl1, xu1),...]
+ Infinite values will be interpreted as large floating values.
+ fprime : callable ``f(x,*args)``, optional
+ A function that evaluates the partial derivatives of func.
+ fprime_eqcons : callable ``f(x,*args)``, optional
+ A function of the form ``f(x, *args)`` that returns the m by n
+ array of equality constraint normals. If not provided,
+ the normals will be approximated. The array returned by
+ fprime_eqcons should be sized as ( len(eqcons), len(x0) ).
+ fprime_ieqcons : callable ``f(x,*args)``, optional
+ A function of the form ``f(x, *args)`` that returns the m by n
+ array of inequality constraint normals. If not provided,
+ the normals will be approximated. The array returned by
+ fprime_ieqcons should be sized as ( len(ieqcons), len(x0) ).
+ args : sequence, optional
+ Additional arguments passed to func and fprime.
+ iter : int, optional
+ The maximum number of iterations.
+ acc : float, optional
+ Requested accuracy.
+ iprint : int, optional
+ The verbosity of fmin_slsqp :
+
+ * iprint <= 0 : Silent operation
+ * iprint == 1 : Print summary upon completion (default)
+ * iprint >= 2 : Print status of each iterate and summary
+ disp : int, optional
+ Overrides the iprint interface (preferred).
+ full_output : bool, optional
+ If False, return only the minimizer of func (default).
+ Otherwise, output final objective function and summary
+ information.
+ epsilon : float, optional
+ The step size for finite-difference derivative estimates.
+ callback : callable, optional
+ Called after each iteration, as ``callback(x)``, where ``x`` is the
+ current parameter vector.
+
+ Returns
+ -------
+ out : ndarray of float
+ The final minimizer of func.
+ fx : ndarray of float, if full_output is true
+ The final value of the objective function.
+ its : int, if full_output is true
+ The number of iterations.
+ imode : int, if full_output is true
+ The exit mode from the optimizer (see below).
+ smode : string, if full_output is true
+ Message describing the exit mode from the optimizer.
+
+ See also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'SLSQP' `method` in particular.
+
+ Notes
+ -----
+ Exit modes are defined as follows:
+
+ - ``-1`` : Gradient evaluation required (g & a)
+ - ``0`` : Optimization terminated successfully
+ - ``1`` : Function evaluation required (f & c)
+ - ``2`` : More equality constraints than independent variables
+ - ``3`` : More than 3*n iterations in LSQ subproblem
+ - ``4`` : Inequality constraints incompatible
+ - ``5`` : Singular matrix E in LSQ subproblem
+ - ``6`` : Singular matrix C in LSQ subproblem
+ - ``7`` : Rank-deficient equality constraint subproblem HFTI
+ - ``8`` : Positive directional derivative for linesearch
+ - ``9`` : Iteration limit reached
+
+ Examples
+ --------
+ Examples are given :ref:`in the tutorial `.
+
+ """
+ if disp is not None:
+ iprint = disp
+
+ # selects whether to use callback(x) or callback(intermediate_result)
+ callback = _wrap_callback(callback, "slsqp")
+
+ opts = {'maxiter': iter,
+ 'ftol': acc,
+ 'iprint': iprint,
+ 'disp': iprint != 0,
+ 'eps': epsilon,
+ 'callback': callback}
+
+ # Build the constraints as a tuple of dictionaries
+ cons = ()
+ # 1. constraints of the 1st kind (eqcons, ieqcons); no Jacobian; take
+ # the same extra arguments as the objective function.
+ cons += tuple({'type': 'eq', 'fun': c, 'args': args} for c in eqcons)
+ cons += tuple({'type': 'ineq', 'fun': c, 'args': args} for c in ieqcons)
+ # 2. constraints of the 2nd kind (f_eqcons, f_ieqcons) and their Jacobian
+ # (fprime_eqcons, fprime_ieqcons); also take the same extra arguments
+ # as the objective function.
+ if f_eqcons:
+ cons += ({'type': 'eq', 'fun': f_eqcons, 'jac': fprime_eqcons,
+ 'args': args}, )
+ if f_ieqcons:
+ cons += ({'type': 'ineq', 'fun': f_ieqcons, 'jac': fprime_ieqcons,
+ 'args': args}, )
+
+ res = _minimize_slsqp(func, x0, args, jac=fprime, bounds=bounds,
+ constraints=cons, **opts)
+ if full_output:
+ return res['x'], res['fun'], res['nit'], res['status'], res['message']
+ else:
+ return res['x']
+
+
+def _minimize_slsqp(func, x0, args=(), jac=None, bounds=None,
+ constraints=(),
+ maxiter=100, ftol=1.0E-6, iprint=1, disp=False,
+ eps=_epsilon, callback=None, finite_diff_rel_step=None,
+ workers=None, **unknown_options):
+ """
+ Minimize a scalar function of one or more variables using Sequential
+ Least Squares Programming (SLSQP).
+
+ Parameters
+ ----------
+ ftol : float
+ Precision target for the value of f in the stopping criterion. This value
+ controls the final accuracy for checking various optimality conditions;
+ gradient of the lagrangian and absolute sum of the constraint violations
+ should be lower than ``ftol``. Similarly, computed step size and the
+ objective function changes are checked against this value. Default is 1e-6.
+ eps : float
+ Step size used for numerical approximation of the Jacobian.
+ disp : bool
+ Set to True to print convergence messages. If False,
+ `verbosity` is ignored and set to 0.
+ maxiter : int, optional
+ Maximum number of iterations. Default value is 100.
+ finite_diff_rel_step : None or array_like, optional
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+ use for numerical approximation of `jac`. The absolute step
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
+ possibly adjusted to fit into the bounds. For ``method='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Returns
+ -------
+ res : OptimizeResult
+ The optimization result represented as an `OptimizeResult` object.
+ In this dict-like object the following fields are of particular importance:
+ ``x`` the solution array, ``success`` a Boolean flag indicating if the
+ optimizer exited successfully, ``message`` which describes the reason for
+ termination, and ``multipliers`` which contains the Karush-Kuhn-Tucker
+ (KKT) multipliers for the QP approximation used in solving the original
+ nonlinear problem. See ``Notes`` below. See also `OptimizeResult` for a
+ description of other attributes.
+
+ Notes
+ -----
+ The KKT multipliers are returned in the ``OptimizeResult.multipliers``
+ attribute as a NumPy array. Denoting the dimension of the equality constraints
+ with ``meq``, and of inequality constraints with ``mineq``, then the returned
+ array slice ``m[:meq]`` contains the multipliers for the equality constraints,
+ and the remaining ``m[meq:meq + mineq]`` contains the multipliers for the
+ inequality constraints. The multipliers corresponding to bound inequalities
+ are not returned. See [1]_ pp. 321 or [2]_ for an explanation of how to interpret
+ these multipliers. The internal QP problem is solved using the methods given
+ in [3]_ Chapter 25.
+
+ Note that if new-style `NonlinearConstraint` or `LinearConstraint` were
+ used, then ``minimize`` converts them first to old-style constraint dicts.
+ It is possible for a single new-style constraint to simultaneously contain
+ both inequality and equality constraints. This means that if there is mixing
+ within a single constraint, then the returned list of multipliers will have
+ a different length than the original new-style constraints.
+
+ References
+ ----------
+ .. [1] Nocedal, J., and S J Wright, 2006, "Numerical Optimization", Springer,
+ New York.
+ .. [2] Kraft, D., "A software package for sequential quadratic programming",
+ 1988, Tech. Rep. DFVLR-FB 88-28, DLR German Aerospace Center, Germany.
+ .. [3] Lawson, C. L., and R. J. Hanson, 1995, "Solving Least Squares Problems",
+ SIAM, Philadelphia, PA.
+
+ """
+ _check_unknown_options(unknown_options)
+ acc = ftol
+ epsilon = eps
+
+ if not disp:
+ iprint = 0
+
+ # Transform x0 into an array.
+ xp = array_namespace(x0)
+ x0 = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ dtype = xp.float64
+ if xp.isdtype(x0.dtype, "real floating"):
+ dtype = x0.dtype
+ x = xp.reshape(xp.astype(x0, dtype), -1)
+
+ # SLSQP is sent 'old-style' bounds, 'new-style' bounds are required by
+ # ScalarFunction
+ if bounds is None or len(bounds) == 0:
+ new_bounds = (-np.inf, np.inf)
+ else:
+ new_bounds = old_bound_to_new(bounds)
+
+ # clip the initial guess to bounds, otherwise ScalarFunction doesn't work
+ x = np.clip(x, new_bounds[0], new_bounds[1])
+
+ # Constraints are triaged per type into a dictionary of tuples
+ if isinstance(constraints, dict):
+ constraints = (constraints, )
+
+ cons = {'eq': (), 'ineq': ()}
+ for ic, con in enumerate(constraints):
+ # check type
+ try:
+ ctype = con['type'].lower()
+ except KeyError as e:
+ raise KeyError(f'Constraint {ic} has no type defined.') from e
+ except TypeError as e:
+ raise TypeError('Constraints must be defined using a '
+ 'dictionary.') from e
+ except AttributeError as e:
+ raise TypeError("Constraint's type must be a string.") from e
+ else:
+ if ctype not in ['eq', 'ineq']:
+ raise ValueError(f"Unknown constraint type '{con['type']}'.")
+
+ # check function
+ if 'fun' not in con:
+ raise ValueError(f'Constraint {ic} has no function defined.')
+
+ # check Jacobian
+ cjac = con.get('jac')
+ if cjac is None:
+ # approximate Jacobian function. The factory function is needed
+ # to keep a reference to `fun`, see gh-4240.
+ def cjac_factory(fun):
+ def cjac(x, *args):
+ x = _check_clip_x(x, new_bounds)
+
+ if jac in ['2-point', '3-point', 'cs']:
+ return approx_derivative(fun, x, method=jac, args=args,
+ rel_step=finite_diff_rel_step,
+ bounds=new_bounds)
+ else:
+ return approx_derivative(fun, x, method='2-point',
+ abs_step=epsilon, args=args,
+ bounds=new_bounds)
+
+ return cjac
+ cjac = cjac_factory(con['fun'])
+
+ # update constraints' dictionary
+ cons[ctype] += ({'fun': con['fun'],
+ 'jac': cjac,
+ 'args': con.get('args', ())}, )
+
+ exit_modes = {-1: "Gradient evaluation required (g & a)",
+ 0: "Optimization terminated successfully",
+ 1: "Function evaluation required (f & c)",
+ 2: "More equality constraints than independent variables",
+ 3: "More than 3*n iterations in LSQ subproblem",
+ 4: "Inequality constraints incompatible",
+ 5: "Singular matrix E in LSQ subproblem",
+ 6: "Singular matrix C in LSQ subproblem",
+ 7: "Rank-deficient equality constraint subproblem HFTI",
+ 8: "Positive directional derivative for linesearch",
+ 9: "Iteration limit reached"}
+
+ # Set the parameters that SLSQP will need
+ # meq, mieq: number of equality and inequality constraints
+ meq = sum(map(len, [np.atleast_1d(c['fun'](x, *c['args']))
+ for c in cons['eq']]))
+ mieq = sum(map(len, [np.atleast_1d(c['fun'](x, *c['args']))
+ for c in cons['ineq']]))
+ # m = The total number of constraints
+ m = meq + mieq
+ # n = The number of independent variables
+ n = len(x)
+
+ # Decompose bounds into xl and xu
+ if bounds is None or len(bounds) == 0:
+ xl = np.empty(n, dtype=float)
+ xu = np.empty(n, dtype=float)
+ xl.fill(np.nan)
+ xu.fill(np.nan)
+ else:
+ bnds = np.array([(_arr_to_scalar(lo), _arr_to_scalar(up))
+ for (lo, up) in bounds], float)
+ if bnds.shape[0] != n:
+ raise IndexError('SLSQP Error: the length of bounds is not '
+ 'compatible with that of x0.')
+
+ with np.errstate(invalid='ignore'):
+ bnderr = bnds[:, 0] > bnds[:, 1]
+
+ if bnderr.any():
+ raise ValueError("SLSQP Error: lb > ub in bounds "
+ f"{', '.join(str(b) for b in bnderr)}.")
+ xl, xu = bnds[:, 0].copy(), bnds[:, 1].copy()
+
+ # Mark infinite bounds with nans; the C code expects this
+ infbnd = ~np.isfinite(bnds)
+ xl[infbnd[:, 0]] = np.nan
+ xu[infbnd[:, 1]] = np.nan
+
+ # ScalarFunction provides function and gradient evaluation
+ sf = _prepare_scalar_function(func, x, jac=jac, args=args, epsilon=eps,
+ finite_diff_rel_step=finite_diff_rel_step,
+ bounds=new_bounds, workers=workers)
+ # gh11403 SLSQP sometimes exceeds bounds by 1 or 2 ULP, make sure this
+ # doesn't get sent to the func/grad evaluator.
+ wrapped_fun = _clip_x_for_func(sf.fun, new_bounds)
+ wrapped_grad = _clip_x_for_func(sf.grad, new_bounds)
+
+ # Initialize internal SLSQP state variables dictionary
+ # This dictionary is passed to the SLSQP matching the C struct defined as
+ #
+ # struct SLSQP_static_vars {
+ # double acc, alpha, f0, gs, h1, h2, h3, h4, t, t0, tol;
+ # int exact, inconsistent, reset, iter, itermax, line, mode, meq;
+ # };
+ #
+ # exact : a dummy variable and should be kept 0 since the underlying code
+ # always uses an inexact search.
+ # inconsistent: a boolean set to 1 if the linearized QP is not well-defined
+ # while the original nonlinear problem is still solvable. Then
+ # the problem is augmented with a regularizing dummy variable.
+ # reset: holds the count of resetting bfgs to identity matrix.
+ # iter : the current and itermax is the maximum number of iterations.
+ # line : the current line search iteration.
+ # mode : the exit mode of the solver.
+ # alpha, f0, gs, h1, h2, h3, h4, t, t0 : internal variables used by the solver.
+ #
+ # The dict holds the intermediate state of the solver. The keys are the same
+ # as the C struct members and will be modified in-place.
+ state_dict = {
+ "acc": acc,
+ "alpha": 0.0,
+ "f0": 0.0,
+ "gs": 0.0,
+ "h1": 0.0,
+ "h2": 0.0,
+ "h3": 0.0,
+ "h4": 0.0,
+ "t": 0.0,
+ "t0": 0.0,
+ "tol": 10.0*acc,
+ "exact": 0,
+ "inconsistent": 0,
+ "reset": 0,
+ "iter": 0,
+ "itermax": int(maxiter),
+ "line": 0,
+ "m": m,
+ "meq": meq,
+ "mode": 0,
+ "n": n
+ }
+
+ # Print the header if iprint >= 2
+ if iprint >= 2:
+ print(f"{'NIT':>5} {'FC':>5} {'OBJFUN':>16} {'GNORM':>16}")
+
+ # Internal buffer and int array
+ indices = np.zeros([max(m + 2*n + 2, 1)], dtype=np.int32)
+
+ # The worst case workspace requirements for the buffer are:
+
+ # n*(n+1)//2 + m + 4*n + 3 # SLSQP
+ # (n+1)*(n+2) + (n+1)*meq + m + (mineq + 2*n + 2)*(n+1) + 3*n + 3 # LSQ
+ # mineq + 2n + 2 + 2*meq + (n+1) + (mineq + 3n + 3)*(n + 1 - meq) # LSEI
+ # (mineq + 2n + 2 + 2)*(n + 2) + mineq + 2n + 2 # LDP
+ # mineq + 2n + 2 # NNLS
+
+ # If we sum all up and simplify by the help of sympy we get the following
+ buffer_size = (
+ n*(n+1)//2 + 3*m*n - (m + 5*n + 7)*meq + 9*m + 8*n*n + 35*n + meq*meq + 28
+ )
+ # If no inequality constraints are given, top up workspace for the missing
+ # terms.
+ if mieq == 0:
+ buffer_size += 2*n*(n + 1)
+ buffer = np.zeros(max(buffer_size, 1), dtype=np.float64)
+
+ # mode is zero on entry, so call objective, constraints and gradients
+ # there should be no func evaluations here because it's cached from
+ # ScalarFunction
+ fx = wrapped_fun(x)
+ g = wrapped_grad(x)
+
+ # Allocate the multiplier array both for constraints and user specified
+ # bounds (extra +2 is for a possible augmented problem).
+ mult = np.zeros([max(1, m + 2*n + 2)], dtype=np.float64)
+
+ # Allocate the constraints and normals once and repopulate as needed
+ C = np.zeros([max(1, m), n], dtype=np.float64, order='F')
+ d = np.zeros([max(1, m)], dtype=np.float64)
+ _eval_con_normals(C, x, cons, m, meq)
+ _eval_constraint(d, x, cons, m, meq)
+
+ iter_prev = 0
+
+ while True:
+ # Call SLSQP
+ slsqp(state_dict, fx, g, C, d, x, mult, xl, xu, buffer, indices)
+
+ if state_dict['mode'] == 1: # objective and constraint evaluation required
+ fx = sf.fun(x)
+ _eval_constraint(d, x, cons, m, meq)
+
+ if state_dict['mode'] == -1: # gradient evaluation required
+ g = sf.grad(x)
+ _eval_con_normals(C, x, cons, m, meq)
+
+ if state_dict['iter'] > iter_prev:
+ # call callback if major iteration has incremented
+ if callback is not None:
+ intermediate_result = OptimizeResult(
+ x=np.copy(x),
+ fun=fx
+ )
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+
+ # Print the status of the current iterate if iprint > 2
+ if iprint >= 2:
+ print(f"{state_dict['iter']:5d} {sf.nfev:5d} "
+ f"{fx:16.6E} {lanorm(g):16.6E}")
+
+ # If exit mode is not -1 or 1, slsqp has completed
+ if abs(state_dict['mode']) != 1:
+ break
+
+ iter_prev = state_dict['iter']
+
+ # Optimization loop complete. Print status if requested
+ if iprint >= 1:
+ print(
+ exit_modes[state_dict['mode']] + f" (Exit mode {state_dict['mode']})"
+ )
+ print(" Current function value:", fx)
+ print(" Iterations:", state_dict['iter'])
+ print(" Function evaluations:", sf.nfev)
+ print(" Gradient evaluations:", sf.ngev)
+
+ return OptimizeResult(
+ x=x, fun=fx, jac=g, nit=state_dict['iter'], nfev=sf.nfev, njev=sf.ngev,
+ status=state_dict['mode'], message=exit_modes[state_dict['mode']],
+ success=(state_dict['mode'] == 0), multipliers=mult[:m]
+ )
+
+# The following functions modify their first input argument in-place.
+def _eval_constraint(d: NDArray, x: NDArray, cons: dict, m: int, meq: int):
+ if m == 0:
+ return
+
+ # The reason why we don't use regular increments with a sane for loop is that
+ # the constraint evaluations do not necessarily return scalars. Their
+ # output length needs to be taken into account while placing them in d.
+
+ if meq > 0:
+ row = 0
+ for con in cons['eq']:
+ temp = np.atleast_1d(con['fun'](x, *con['args'])).ravel()
+ d[row:row + len(temp)] = temp
+ row += len(temp)
+
+ if m > meq:
+ row = meq
+ for con in cons['ineq']:
+ temp = np.atleast_1d(con['fun'](x, *con['args'])).ravel()
+ d[row:row + len(temp)] = temp
+ row += len(temp)
+
+ return
+
+
+def _eval_con_normals(C: NDArray, x: NDArray, cons: dict, m: int, meq: int):
+ if m == 0:
+ return
+
+ if meq > 0:
+ row = 0
+ for con in cons['eq']:
+ temp = np.atleast_2d(con['jac'](x, *con['args']))
+ C[row:row + temp.shape[0], :] = temp
+ row += temp.shape[0]
+
+ if m > meq:
+ row = meq
+ for con in cons['ineq']:
+ temp = np.atleast_2d(con['jac'](x, *con['args']))
+ C[row:row + temp.shape[0], :] = temp
+ row += temp.shape[0]
+
+ return
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_slsqplib.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_slsqplib.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..3f9b485e62e8957588cdb38a239ac80c4260fdde
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_slsqplib.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_spectral.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..42f281944fd746d5892c901ef9a852c40e763775
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_spectral.py
@@ -0,0 +1,260 @@
+"""
+Spectral Algorithm for Nonlinear Equations
+"""
+import collections
+
+import numpy as np
+from scipy.optimize import OptimizeResult
+from scipy.optimize._optimize import _check_unknown_options
+from ._linesearch import _nonmonotone_line_search_cruz, _nonmonotone_line_search_cheng
+
+class _NoConvergence(Exception):
+ pass
+
+
+def _root_df_sane(func, x0, args=(), ftol=1e-8, fatol=1e-300, maxfev=1000,
+ fnorm=None, callback=None, disp=False, M=10, eta_strategy=None,
+ sigma_eps=1e-10, sigma_0=1.0, line_search='cruz', **unknown_options):
+ r"""
+ Solve nonlinear equation with the DF-SANE method
+
+ Options
+ -------
+ ftol : float, optional
+ Relative norm tolerance.
+ fatol : float, optional
+ Absolute norm tolerance.
+ Algorithm terminates when ``||func(x)|| < fatol + ftol ||func(x_0)||``.
+ fnorm : callable, optional
+ Norm to use in the convergence check. If None, 2-norm is used.
+ maxfev : int, optional
+ Maximum number of function evaluations.
+ disp : bool, optional
+ Whether to print convergence process to stdout.
+ eta_strategy : callable, optional
+ Choice of the ``eta_k`` parameter, which gives slack for growth
+ of ``||F||**2``. Called as ``eta_k = eta_strategy(k, x, F)`` with
+ `k` the iteration number, `x` the current iterate and `F` the current
+ residual. Should satisfy ``eta_k > 0`` and ``sum(eta, k=0..inf) < inf``.
+ Default: ``||F||**2 / (1 + k)**2``.
+ sigma_eps : float, optional
+ The spectral coefficient is constrained to ``sigma_eps < sigma < 1/sigma_eps``.
+ Default: 1e-10
+ sigma_0 : float, optional
+ Initial spectral coefficient.
+ Default: 1.0
+ M : int, optional
+ Number of iterates to include in the nonmonotonic line search.
+ Default: 10
+ line_search : {'cruz', 'cheng'}
+ Type of line search to employ. 'cruz' is the original one defined in
+ [Martinez & Raydan. Math. Comp. 75, 1429 (2006)], 'cheng' is
+ a modified search defined in [Cheng & Li. IMA J. Numer. Anal. 29, 814 (2009)].
+ Default: 'cruz'
+
+ References
+ ----------
+ .. [1] "Spectral residual method without gradient information for solving
+ large-scale nonlinear systems of equations." W. La Cruz,
+ J.M. Martinez, M. Raydan. Math. Comp. **75**, 1429 (2006).
+ .. [2] W. La Cruz, Opt. Meth. Software, 29, 24 (2014).
+ .. [3] W. Cheng, D.-H. Li. IMA J. Numer. Anal. **29**, 814 (2009).
+
+ """
+ _check_unknown_options(unknown_options)
+
+ if line_search not in ('cheng', 'cruz'):
+ raise ValueError(f"Invalid value {line_search!r} for 'line_search'")
+
+ nexp = 2
+
+ if eta_strategy is None:
+ # Different choice from [1], as their eta is not invariant
+ # vs. scaling of F.
+ def eta_strategy(k, x, F):
+ # Obtain squared 2-norm of the initial residual from the outer scope
+ return f_0 / (1 + k)**2
+
+ if fnorm is None:
+ def fnorm(F):
+ # Obtain squared 2-norm of the current residual from the outer scope
+ return f_k**(1.0/nexp)
+
+ def fmerit(F):
+ return np.linalg.norm(F)**nexp
+
+ nfev = [0]
+ f, x_k, x_shape, f_k, F_k, is_complex = _wrap_func(func, x0, fmerit,
+ nfev, maxfev, args)
+
+ k = 0
+ f_0 = f_k
+ sigma_k = sigma_0
+
+ F_0_norm = fnorm(F_k)
+
+ # For the 'cruz' line search
+ prev_fs = collections.deque([f_k], M)
+
+ # For the 'cheng' line search
+ Q = 1.0
+ C = f_0
+
+ converged = False
+ message = "too many function evaluations required"
+
+ while True:
+ F_k_norm = fnorm(F_k)
+
+ if disp:
+ print(f"iter {k}: ||F|| = {F_k_norm:g}, sigma = {sigma_k:g}")
+
+ if callback is not None:
+ callback(x_k, F_k)
+
+ if F_k_norm < ftol * F_0_norm + fatol:
+ # Converged!
+ message = "successful convergence"
+ converged = True
+ break
+
+ # Control spectral parameter, from [2]
+ if abs(sigma_k) > 1/sigma_eps:
+ sigma_k = 1/sigma_eps * np.sign(sigma_k)
+ elif abs(sigma_k) < sigma_eps:
+ sigma_k = sigma_eps
+
+ # Line search direction
+ d = -sigma_k * F_k
+
+ # Nonmonotone line search
+ eta = eta_strategy(k, x_k, F_k)
+ try:
+ if line_search == 'cruz':
+ alpha, xp, fp, Fp = _nonmonotone_line_search_cruz(f, x_k, d, prev_fs,
+ eta=eta)
+ elif line_search == 'cheng':
+ alpha, xp, fp, Fp, C, Q = _nonmonotone_line_search_cheng(f, x_k, d, f_k,
+ C, Q, eta=eta)
+ except _NoConvergence:
+ break
+
+ # Update spectral parameter
+ s_k = xp - x_k
+ y_k = Fp - F_k
+ sigma_k = np.vdot(s_k, s_k) / np.vdot(s_k, y_k)
+
+ # Take step
+ x_k = xp
+ F_k = Fp
+ f_k = fp
+
+ # Store function value
+ if line_search == 'cruz':
+ prev_fs.append(fp)
+
+ k += 1
+
+ x = _wrap_result(x_k, is_complex, shape=x_shape)
+ F = _wrap_result(F_k, is_complex)
+
+ result = OptimizeResult(x=x, success=converged,
+ message=message,
+ fun=F, nfev=nfev[0], nit=k, method="df-sane")
+
+ return result
+
+
+def _wrap_func(func, x0, fmerit, nfev_list, maxfev, args=()):
+ """
+ Wrap a function and an initial value so that (i) complex values
+ are wrapped to reals, and (ii) value for a merit function
+ fmerit(x, f) is computed at the same time, (iii) iteration count
+ is maintained and an exception is raised if it is exceeded.
+
+ Parameters
+ ----------
+ func : callable
+ Function to wrap
+ x0 : ndarray
+ Initial value
+ fmerit : callable
+ Merit function fmerit(f) for computing merit value from residual.
+ nfev_list : list
+ List to store number of evaluations in. Should be [0] in the beginning.
+ maxfev : int
+ Maximum number of evaluations before _NoConvergence is raised.
+ args : tuple
+ Extra arguments to func
+
+ Returns
+ -------
+ wrap_func : callable
+ Wrapped function, to be called as
+ ``F, fp = wrap_func(x0)``
+ x0_wrap : ndarray of float
+ Wrapped initial value; raveled to 1-D and complex
+ values mapped to reals.
+ x0_shape : tuple
+ Shape of the initial value array
+ f : float
+ Merit function at F
+ F : ndarray of float
+ Residual at x0_wrap
+ is_complex : bool
+ Whether complex values were mapped to reals
+
+ """
+ x0 = np.asarray(x0)
+ x0_shape = x0.shape
+ F = np.asarray(func(x0, *args)).ravel()
+ is_complex = np.iscomplexobj(x0) or np.iscomplexobj(F)
+ x0 = x0.ravel()
+
+ nfev_list[0] = 1
+
+ if is_complex:
+ def wrap_func(x):
+ if nfev_list[0] >= maxfev:
+ raise _NoConvergence()
+ nfev_list[0] += 1
+ z = _real2complex(x).reshape(x0_shape)
+ v = np.asarray(func(z, *args)).ravel()
+ F = _complex2real(v)
+ f = fmerit(F)
+ return f, F
+
+ x0 = _complex2real(x0)
+ F = _complex2real(F)
+ else:
+ def wrap_func(x):
+ if nfev_list[0] >= maxfev:
+ raise _NoConvergence()
+ nfev_list[0] += 1
+ x = x.reshape(x0_shape)
+ F = np.asarray(func(x, *args)).ravel()
+ f = fmerit(F)
+ return f, F
+
+ return wrap_func, x0, x0_shape, fmerit(F), F, is_complex
+
+
+def _wrap_result(result, is_complex, shape=None):
+ """
+ Convert from real to complex and reshape result arrays.
+ """
+ if is_complex:
+ z = _real2complex(result)
+ else:
+ z = result
+ if shape is not None:
+ z = z.reshape(shape)
+ return z
+
+
+def _real2complex(x):
+ return np.ascontiguousarray(x, dtype=float).view(np.complex128)
+
+
+def _complex2real(z):
+ return np.ascontiguousarray(z, dtype=complex).view(np.float64)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_tnc.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..47141061d6bfeac4d6e281efb39d094b066455fd
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_tnc.py
@@ -0,0 +1,438 @@
+# TNC Python interface
+# @(#) $Jeannot: tnc.py,v 1.11 2005/01/28 18:27:31 js Exp $
+
+# Copyright (c) 2004-2005, Jean-Sebastien Roy (js@jeannot.org)
+
+# Permission is hereby granted, free of charge, to any person obtaining a
+# copy of this software and associated documentation files (the
+# "Software"), to deal in the Software without restriction, including
+# without limitation the rights to use, copy, modify, merge, publish,
+# distribute, sublicense, and/or sell copies of the Software, and to
+# permit persons to whom the Software is furnished to do so, subject to
+# the following conditions:
+
+# The above copyright notice and this permission notice shall be included
+# in all copies or substantial portions of the Software.
+
+# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+# OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+# IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+# CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+# TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+# SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+
+"""
+TNC: A Python interface to the TNC non-linear optimizer
+
+TNC is a non-linear optimizer. To use it, you must provide a function to
+minimize. The function must take one argument: the list of coordinates where to
+evaluate the function; and it must return either a tuple, whose first element is the
+value of the function, and whose second argument is the gradient of the function
+(as a list of values); or None, to abort the minimization.
+"""
+
+from scipy.optimize import _moduleTNC as moduleTNC
+from ._optimize import (MemoizeJac, OptimizeResult, _check_unknown_options,
+ _prepare_scalar_function)
+from ._constraints import old_bound_to_new
+from scipy._lib._array_api import array_namespace
+from scipy._lib import array_api_extra as xpx
+
+from numpy import inf, array, zeros
+
+__all__ = ['fmin_tnc']
+
+
+MSG_NONE = 0 # No messages
+MSG_ITER = 1 # One line per iteration
+MSG_INFO = 2 # Informational messages
+MSG_VERS = 4 # Version info
+MSG_EXIT = 8 # Exit reasons
+MSG_ALL = MSG_ITER + MSG_INFO + MSG_VERS + MSG_EXIT
+
+MSGS = {
+ MSG_NONE: "No messages",
+ MSG_ITER: "One line per iteration",
+ MSG_INFO: "Informational messages",
+ MSG_VERS: "Version info",
+ MSG_EXIT: "Exit reasons",
+ MSG_ALL: "All messages"
+}
+
+INFEASIBLE = -1 # Infeasible (lower bound > upper bound)
+LOCALMINIMUM = 0 # Local minimum reached (|pg| ~= 0)
+FCONVERGED = 1 # Converged (|f_n-f_(n-1)| ~= 0)
+XCONVERGED = 2 # Converged (|x_n-x_(n-1)| ~= 0)
+MAXFUN = 3 # Max. number of function evaluations reached
+LSFAIL = 4 # Linear search failed
+CONSTANT = 5 # All lower bounds are equal to the upper bounds
+NOPROGRESS = 6 # Unable to progress
+USERABORT = 7 # User requested end of minimization
+
+RCSTRINGS = {
+ INFEASIBLE: "Infeasible (lower bound > upper bound)",
+ LOCALMINIMUM: "Local minimum reached (|pg| ~= 0)",
+ FCONVERGED: "Converged (|f_n-f_(n-1)| ~= 0)",
+ XCONVERGED: "Converged (|x_n-x_(n-1)| ~= 0)",
+ MAXFUN: "Max. number of function evaluations reached",
+ LSFAIL: "Linear search failed",
+ CONSTANT: "All lower bounds are equal to the upper bounds",
+ NOPROGRESS: "Unable to progress",
+ USERABORT: "User requested end of minimization"
+}
+
+# Changes to interface made by Travis Oliphant, Apr. 2004 for inclusion in
+# SciPy
+
+
+def fmin_tnc(func, x0, fprime=None, args=(), approx_grad=0,
+ bounds=None, epsilon=1e-8, scale=None, offset=None,
+ messages=MSG_ALL, maxCGit=-1, maxfun=None, eta=-1,
+ stepmx=0, accuracy=0, fmin=0, ftol=-1, xtol=-1, pgtol=-1,
+ rescale=-1, disp=None, callback=None):
+ r"""
+ Minimize a function with variables subject to bounds, using
+ gradient information in a truncated Newton algorithm. This
+ method wraps a C implementation of the algorithm.
+
+ Parameters
+ ----------
+ func : callable ``func(x, *args)``
+ Function to minimize. Must do one of:
+
+ 1. Return f and g, where f is the value of the function and g its
+ gradient (a list of floats).
+
+ 2. Return the function value but supply gradient function
+ separately as `fprime`.
+
+ 3. Return the function value and set ``approx_grad=True``.
+
+ If the function returns None, the minimization
+ is aborted.
+ x0 : array_like
+ Initial estimate of minimum.
+ fprime : callable ``fprime(x, *args)``, optional
+ Gradient of `func`. If None, then either `func` must return the
+ function value and the gradient (``f,g = func(x, *args)``)
+ or `approx_grad` must be True.
+ args : tuple, optional
+ Arguments to pass to function.
+ approx_grad : bool, optional
+ If true, approximate the gradient numerically.
+ bounds : list, optional
+ (min, max) pairs for each element in x0, defining the
+ bounds on that parameter. Use None or +/-inf for one of
+ min or max when there is no bound in that direction.
+ epsilon : float, optional
+ Used if approx_grad is True. The stepsize in a finite
+ difference approximation for fprime.
+ scale : array_like, optional
+ Scaling factors to apply to each variable. If None, the
+ factors are up-low for interval bounded variables and
+ 1+|x| for the others. Defaults to None.
+ offset : array_like, optional
+ Value to subtract from each variable. If None, the
+ offsets are (up+low)/2 for interval bounded variables
+ and x for the others.
+ messages : int, optional
+ Bit mask used to select messages display during
+ minimization values defined in the MSGS dict. Defaults to
+ MGS_ALL.
+ disp : int, optional
+ Integer interface to messages. 0 = no message, 5 = all messages
+ maxCGit : int, optional
+ Maximum number of hessian*vector evaluations per main
+ iteration. If maxCGit == 0, the direction chosen is
+ -gradient if maxCGit < 0, maxCGit is set to
+ max(1,min(50,n/2)). Defaults to -1.
+ maxfun : int, optional
+ Maximum number of function evaluation. If None, maxfun is
+ set to max(100, 10*len(x0)). Defaults to None. Note that this function
+ may violate the limit because of evaluating gradients by numerical
+ differentiation.
+ eta : float, optional
+ Severity of the line search. If < 0 or > 1, set to 0.25.
+ Defaults to -1.
+ stepmx : float, optional
+ Maximum step for the line search. May be increased during
+ call. If too small, it will be set to 10.0. Defaults to 0.
+ accuracy : float, optional
+ Relative precision for finite difference calculations. If
+ <= machine_precision, set to sqrt(machine_precision).
+ Defaults to 0.
+ fmin : float, optional
+ Minimum function value estimate. Defaults to 0.
+ ftol : float, optional
+ Precision goal for the value of f in the stopping criterion.
+ If ftol < 0.0, ftol is set to 0.0 defaults to -1.
+ xtol : float, optional
+ Precision goal for the value of x in the stopping
+ criterion (after applying x scaling factors). If xtol <
+ 0.0, xtol is set to sqrt(machine_precision). Defaults to
+ -1.
+ pgtol : float, optional
+ Precision goal for the value of the projected gradient in
+ the stopping criterion (after applying x scaling factors).
+ If pgtol < 0.0, pgtol is set to 1e-2 * sqrt(accuracy).
+ Setting it to 0.0 is not recommended. Defaults to -1.
+ rescale : float, optional
+ Scaling factor (in log10) used to trigger f value
+ rescaling. If 0, rescale at each iteration. If a large
+ value, never rescale. If < 0, rescale is set to 1.3.
+ callback : callable, optional
+ Called after each iteration, as callback(xk), where xk is the
+ current parameter vector.
+
+ Returns
+ -------
+ x : ndarray
+ The solution.
+ nfeval : int
+ The number of function evaluations.
+ rc : int
+ Return code, see below
+
+ See also
+ --------
+ minimize: Interface to minimization algorithms for multivariate
+ functions. See the 'TNC' `method` in particular.
+
+ Notes
+ -----
+ The underlying algorithm is truncated Newton, also called
+ Newton Conjugate-Gradient. This method differs from
+ scipy.optimize.fmin_ncg in that
+
+ 1. it wraps a C implementation of the algorithm
+ 2. it allows each variable to be given an upper and lower bound.
+
+ The algorithm incorporates the bound constraints by determining
+ the descent direction as in an unconstrained truncated Newton,
+ but never taking a step-size large enough to leave the space
+ of feasible x's. The algorithm keeps track of a set of
+ currently active constraints, and ignores them when computing
+ the minimum allowable step size. (The x's associated with the
+ active constraint are kept fixed.) If the maximum allowable
+ step size is zero then a new constraint is added. At the end
+ of each iteration one of the constraints may be deemed no
+ longer active and removed. A constraint is considered
+ no longer active is if it is currently active
+ but the gradient for that variable points inward from the
+ constraint. The specific constraint removed is the one
+ associated with the variable of largest index whose
+ constraint is no longer active.
+
+ Return codes are defined as follows:
+
+ - ``-1`` : Infeasible (lower bound > upper bound)
+ - ``0`` : Local minimum reached (:math:`|pg| \approx 0`)
+ - ``1`` : Converged (:math:`|f_n-f_(n-1)| \approx 0`)
+ - ``2`` : Converged (:math:`|x_n-x_(n-1)| \approx 0`)
+ - ``3`` : Max. number of function evaluations reached
+ - ``4`` : Linear search failed
+ - ``5`` : All lower bounds are equal to the upper bounds
+ - ``6`` : Unable to progress
+ - ``7`` : User requested end of minimization
+
+ References
+ ----------
+ Wright S., Nocedal J. (2006), 'Numerical Optimization'
+
+ Nash S.G. (1984), "Newton-Type Minimization Via the Lanczos Method",
+ SIAM Journal of Numerical Analysis 21, pp. 770-778
+
+ """
+ # handle fprime/approx_grad
+ if approx_grad:
+ fun = func
+ jac = None
+ elif fprime is None:
+ fun = MemoizeJac(func)
+ jac = fun.derivative
+ else:
+ fun = func
+ jac = fprime
+
+ if disp is not None: # disp takes precedence over messages
+ mesg_num = disp
+ else:
+ mesg_num = {0:MSG_NONE, 1:MSG_ITER, 2:MSG_INFO, 3:MSG_VERS,
+ 4:MSG_EXIT, 5:MSG_ALL}.get(messages, MSG_ALL)
+ # build options
+ opts = {'eps': epsilon,
+ 'scale': scale,
+ 'offset': offset,
+ 'mesg_num': mesg_num,
+ 'maxCGit': maxCGit,
+ 'maxfun': maxfun,
+ 'eta': eta,
+ 'stepmx': stepmx,
+ 'accuracy': accuracy,
+ 'minfev': fmin,
+ 'ftol': ftol,
+ 'xtol': xtol,
+ 'gtol': pgtol,
+ 'rescale': rescale,
+ 'disp': False}
+
+ res = _minimize_tnc(fun, x0, args, jac, bounds, callback=callback, **opts)
+
+ return res['x'], res['nfev'], res['status']
+
+
+def _minimize_tnc(fun, x0, args=(), jac=None, bounds=None,
+ eps=1e-8, scale=None, offset=None, mesg_num=None,
+ maxCGit=-1, eta=-1, stepmx=0, accuracy=0,
+ minfev=0, ftol=-1, xtol=-1, gtol=-1, rescale=-1, disp=False,
+ callback=None, finite_diff_rel_step=None, maxfun=None,
+ workers=None,
+ **unknown_options):
+ """
+ Minimize a scalar function of one or more variables using a truncated
+ Newton (TNC) algorithm.
+
+ Options
+ -------
+ eps : float or ndarray
+ If `jac is None` the absolute step size used for numerical
+ approximation of the jacobian via forward differences.
+ scale : list of floats
+ Scaling factors to apply to each variable. If None, the
+ factors are up-low for interval bounded variables and
+ 1+|x] for the others. Defaults to None.
+ offset : float
+ Value to subtract from each variable. If None, the
+ offsets are (up+low)/2 for interval bounded variables
+ and x for the others.
+ disp : bool
+ Set to True to print convergence messages.
+ maxCGit : int
+ Maximum number of hessian*vector evaluations per main
+ iteration. If maxCGit == 0, the direction chosen is
+ -gradient if maxCGit < 0, maxCGit is set to
+ max(1,min(50,n/2)). Defaults to -1.
+ eta : float
+ Severity of the line search. If < 0 or > 1, set to 0.25.
+ Defaults to -1.
+ stepmx : float
+ Maximum step for the line search. May be increased during
+ call. If too small, it will be set to 10.0. Defaults to 0.
+ accuracy : float
+ Relative precision for finite difference calculations. If
+ <= machine_precision, set to sqrt(machine_precision).
+ Defaults to 0.
+ minfev : float
+ Minimum function value estimate. Defaults to 0.
+ ftol : float
+ Precision goal for the value of f in the stopping criterion.
+ If ftol < 0.0, ftol is set to 0.0 defaults to -1.
+ xtol : float
+ Precision goal for the value of x in the stopping
+ criterion (after applying x scaling factors). If xtol <
+ 0.0, xtol is set to sqrt(machine_precision). Defaults to
+ -1.
+ gtol : float
+ Precision goal for the value of the projected gradient in
+ the stopping criterion (after applying x scaling factors).
+ If gtol < 0.0, gtol is set to 1e-2 * sqrt(accuracy).
+ Setting it to 0.0 is not recommended. Defaults to -1.
+ rescale : float
+ Scaling factor (in log10) used to trigger f value
+ rescaling. If 0, rescale at each iteration. If a large
+ value, never rescale. If < 0, rescale is set to 1.3.
+ finite_diff_rel_step : None or array_like, optional
+ If ``jac in ['2-point', '3-point', 'cs']`` the relative step size to
+ use for numerical approximation of the jacobian. The absolute step
+ size is computed as ``h = rel_step * sign(x) * max(1, abs(x))``,
+ possibly adjusted to fit into the bounds. For ``method='3-point'``
+ the sign of `h` is ignored. If None (default) then step is selected
+ automatically.
+ maxfun : int
+ Maximum number of function evaluations. If None, `maxfun` is
+ set to max(100, 10*len(x0)). Defaults to None.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+ """
+ _check_unknown_options(unknown_options)
+ fmin = minfev
+ pgtol = gtol
+
+ xp = array_namespace(x0)
+ x0 = xpx.atleast_nd(xp.asarray(x0), ndim=1, xp=xp)
+ dtype = xp.float64
+ if xp.isdtype(x0.dtype, "real floating"):
+ dtype = x0.dtype
+ x0 = xp.reshape(xp.astype(x0, dtype), -1)
+
+ n = len(x0)
+
+ if bounds is None:
+ bounds = [(None,None)] * n
+ if len(bounds) != n:
+ raise ValueError('length of x0 != length of bounds')
+ new_bounds = old_bound_to_new(bounds)
+
+ if mesg_num is not None:
+ messages = {0:MSG_NONE, 1:MSG_ITER, 2:MSG_INFO, 3:MSG_VERS,
+ 4:MSG_EXIT, 5:MSG_ALL}.get(mesg_num, MSG_ALL)
+ elif disp:
+ messages = MSG_ALL
+ else:
+ messages = MSG_NONE
+
+ sf = _prepare_scalar_function(fun, x0, jac=jac, args=args, epsilon=eps,
+ finite_diff_rel_step=finite_diff_rel_step,
+ bounds=new_bounds, workers=workers)
+ func_and_grad = sf.fun_and_grad
+
+ """
+ low, up : the bounds (lists of floats)
+ if low is None, the lower bounds are removed.
+ if up is None, the upper bounds are removed.
+ low and up defaults to None
+ """
+ low = zeros(n)
+ up = zeros(n)
+ for i in range(n):
+ if bounds[i] is None:
+ l, u = -inf, inf
+ else:
+ l,u = bounds[i]
+ if l is None:
+ low[i] = -inf
+ else:
+ low[i] = l
+ if u is None:
+ up[i] = inf
+ else:
+ up[i] = u
+
+ if scale is None:
+ scale = array([])
+
+ if offset is None:
+ offset = array([])
+
+ if maxfun is None:
+ maxfun = max(100, 10*len(x0))
+
+ rc, nf, nit, x, funv, jacv = moduleTNC.tnc_minimize(
+ func_and_grad, x0, low, up, scale,
+ offset, messages, maxCGit, maxfun,
+ eta, stepmx, accuracy, fmin, ftol,
+ xtol, pgtol, rescale, callback
+ )
+ # the TNC documentation states: "On output, x, f and g may be very
+ # slightly out of sync because of scaling". Therefore re-evaluate
+ # func_and_grad so they are synced.
+ funv, jacv = func_and_grad(x)
+
+ return OptimizeResult(x=x, fun=funv, jac=jacv, nfev=sf.nfev,
+ nit=nit, status=rc, message=RCSTRINGS[rc],
+ success=(-1 < rc < 3))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/.__trlib.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/.__trlib.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/.__trlib.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..537b73b3aeb36df09863a0cd24957e5612deb030
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/__init__.py
@@ -0,0 +1,12 @@
+from ._trlib import TRLIBQuadraticSubproblem
+
+__all__ = ['TRLIBQuadraticSubproblem', 'get_trlib_quadratic_subproblem']
+
+
+def get_trlib_quadratic_subproblem(tol_rel_i=-2.0, tol_rel_b=-3.0, disp=False):
+ def subproblem_factory(x, fun, jac, hess, hessp):
+ return TRLIBQuadraticSubproblem(x, fun, jac, hess, hessp,
+ tol_rel_i=tol_rel_i,
+ tol_rel_b=tol_rel_b,
+ disp=disp)
+ return subproblem_factory
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..0eabc782ae6d7552fcdffb18a51cb89b96c6e269
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trlib/_trlib.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:9279c8f86d222d1eca88ba513cdd5c6e3d2549cf96f7d153318a8024220a31c1
+size 182816
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2a83e5f76b6cfda9767b68d24b755713ddc3107
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion.py
@@ -0,0 +1,329 @@
+"""Trust-region optimization."""
+import math
+import warnings
+
+import numpy as np
+import scipy.linalg
+from ._optimize import (_check_unknown_options, _status_message,
+ OptimizeResult, _prepare_scalar_function,
+ _call_callback_maybe_halt)
+from scipy.optimize._hessian_update_strategy import HessianUpdateStrategy
+from scipy.optimize._differentiable_functions import FD_METHODS
+__all__ = []
+
+
+def _wrap_function(function, args):
+ # wraps a minimizer function to count number of evaluations
+ # and to easily provide an args kwd.
+ ncalls = [0]
+ if function is None:
+ return ncalls, None
+
+ def function_wrapper(x, *wrapper_args):
+ ncalls[0] += 1
+ # A copy of x is sent to the user function (gh13740)
+ return function(np.copy(x), *(wrapper_args + args))
+
+ return ncalls, function_wrapper
+
+
+class BaseQuadraticSubproblem:
+ """
+ Base/abstract class defining the quadratic model for trust-region
+ minimization. Child classes must implement the ``solve`` method.
+
+ Values of the objective function, Jacobian and Hessian (if provided) at
+ the current iterate ``x`` are evaluated on demand and then stored as
+ attributes ``fun``, ``jac``, ``hess``.
+ """
+
+ def __init__(self, x, fun, jac, hess=None, hessp=None):
+ self._x = x
+ self._f = None
+ self._g = None
+ self._h = None
+ self._g_mag = None
+ self._cauchy_point = None
+ self._newton_point = None
+ self._fun = fun
+ self._jac = jac
+ self._hess = hess
+ self._hessp = hessp
+
+ def __call__(self, p):
+ return self.fun + np.dot(self.jac, p) + 0.5 * np.dot(p, self.hessp(p))
+
+ @property
+ def fun(self):
+ """Value of objective function at current iteration."""
+ if self._f is None:
+ self._f = self._fun(self._x)
+ return self._f
+
+ @property
+ def jac(self):
+ """Value of Jacobian of objective function at current iteration."""
+ if self._g is None:
+ self._g = self._jac(self._x)
+ return self._g
+
+ @property
+ def hess(self):
+ """Value of Hessian of objective function at current iteration."""
+ if self._h is None:
+ self._h = self._hess(self._x)
+ return self._h
+
+ def hessp(self, p):
+ if self._hessp is not None:
+ return self._hessp(self._x, p)
+ else:
+ return np.dot(self.hess, p)
+
+ @property
+ def jac_mag(self):
+ """Magnitude of jacobian of objective function at current iteration."""
+ if self._g_mag is None:
+ self._g_mag = scipy.linalg.norm(self.jac)
+ return self._g_mag
+
+ def get_boundaries_intersections(self, z, d, trust_radius):
+ """
+ Solve the scalar quadratic equation ``||z + t d|| == trust_radius``.
+ This is like a line-sphere intersection.
+ Return the two values of t, sorted from low to high.
+ """
+ a = np.dot(d, d)
+ b = 2 * np.dot(z, d)
+ c = np.dot(z, z) - trust_radius**2
+ sqrt_discriminant = math.sqrt(b*b - 4*a*c)
+
+ # The following calculation is mathematically
+ # equivalent to:
+ # ta = (-b - sqrt_discriminant) / (2*a)
+ # tb = (-b + sqrt_discriminant) / (2*a)
+ # but produce smaller round off errors.
+ # Look at Matrix Computation p.97
+ # for a better justification.
+ aux = b + math.copysign(sqrt_discriminant, b)
+ ta = -aux / (2*a)
+ tb = -2*c / aux
+ return sorted([ta, tb])
+
+ def solve(self, trust_radius):
+ raise NotImplementedError('The solve method should be implemented by '
+ 'the child class')
+
+
+def _minimize_trust_region(fun, x0, args=(), jac=None, hess=None, hessp=None,
+ subproblem=None, initial_trust_radius=1.0,
+ max_trust_radius=1000.0, eta=0.15, gtol=1e-4,
+ maxiter=None, disp=False, return_all=False,
+ callback=None, inexact=True, workers=None,
+ subproblem_maxiter=None, **unknown_options):
+ """
+ Minimization of scalar function of one or more variables using a
+ trust-region algorithm.
+
+ Options for the trust-region algorithm are:
+ initial_trust_radius : float
+ Initial trust radius.
+ max_trust_radius : float
+ Never propose steps that are longer than this value.
+ eta : float
+ Trust region related acceptance stringency for proposed steps.
+ gtol : float
+ Gradient norm must be less than `gtol`
+ before successful termination.
+ maxiter : int
+ Maximum number of iterations to perform.
+ disp : bool
+ If True, print convergence message.
+ inexact : bool
+ Accuracy to solve subproblems. If True requires less nonlinear
+ iterations, but more vector products. Only effective for method
+ trust-krylov.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+ Only for 'trust-krylov', 'trust-ncg'.
+
+ .. versionadded:: 1.16.0
+ subproblem_maxiter : int, optional
+ Maximum number of iterations to perform per subproblem. Only affects
+ trust-exact. Default is 25.
+
+ .. versionadded:: 1.17.0
+
+
+ This function is called by the `minimize` function.
+ It is not supposed to be called directly.
+ """
+ _check_unknown_options(unknown_options)
+
+ if jac is None:
+ raise ValueError('Jacobian is currently required for trust-region '
+ 'methods')
+ if hess is None and hessp is None:
+ raise ValueError('Either the Hessian or the Hessian-vector product '
+ 'is currently required for trust-region methods')
+ if subproblem is None:
+ raise ValueError('A subproblem solving strategy is required for '
+ 'trust-region methods')
+ if not (0 <= eta < 0.25):
+ raise Exception('invalid acceptance stringency')
+ if max_trust_radius <= 0:
+ raise Exception('the max trust radius must be positive')
+ if initial_trust_radius <= 0:
+ raise ValueError('the initial trust radius must be positive')
+ if initial_trust_radius >= max_trust_radius:
+ raise ValueError('the initial trust radius must be less than the '
+ 'max trust radius')
+
+ # force the initial guess into a nice format
+ x0 = np.asarray(x0).flatten()
+
+ # A ScalarFunction representing the problem. This caches calls to fun, jac,
+ # hess.
+ # the workers kwd only has an effect for trust-ncg, trust-krylov when
+ # estimating the Hessian with finite-differences. It's never used
+ # during calculation of jacobian, because callables are required for all
+ # methods.
+ sf = _prepare_scalar_function(
+ fun, x0, jac=jac, hess=hess, args=args, workers=workers
+ )
+ fun = sf.fun
+ jac = sf.grad
+ if callable(hess):
+ hess = sf.hess
+ elif callable(hessp):
+ # this elif statement must come before examining whether hess
+ # is estimated by FD methods or a HessianUpdateStrategy
+ pass
+ elif (hess in FD_METHODS or isinstance(hess, HessianUpdateStrategy)):
+ # If the Hessian is being estimated by finite differences or a
+ # Hessian update strategy then ScalarFunction.hess returns a
+ # LinearOperator or a HessianUpdateStrategy. This enables the
+ # calculation/creation of a hessp. BUT you only want to do this
+ # if the user *hasn't* provided a callable(hessp) function.
+ hess = None
+
+ def hessp(x, p, *args):
+ return sf.hess(x).dot(p)
+ else:
+ raise ValueError('Either the Hessian or the Hessian-vector product '
+ 'is currently required for trust-region methods')
+
+ # ScalarFunction doesn't represent hessp
+ nhessp, hessp = _wrap_function(hessp, args)
+
+ # limit the number of iterations
+ if maxiter is None:
+ maxiter = len(x0)*200
+
+ # init the search status
+ warnflag = 0
+
+ # initialize the search
+ trust_radius = initial_trust_radius
+ x = x0
+ if return_all:
+ allvecs = [x]
+
+ subproblem_init_kw = {}
+ if hasattr(subproblem, 'MAXITER_DEFAULT'):
+ subproblem_init_kw['maxiter'] = subproblem_maxiter
+
+ m = subproblem(x, fun, jac, hess, hessp, **subproblem_init_kw)
+ k = 0
+
+ # search for the function min
+ # do not even start if the gradient is small enough
+ while m.jac_mag >= gtol:
+
+ # Solve the sub-problem.
+ # This gives us the proposed step relative to the current position
+ # and it tells us whether the proposed step
+ # has reached the trust region boundary or not.
+ try:
+ p, hits_boundary = m.solve(trust_radius)
+ except np.linalg.LinAlgError:
+ warnflag = 3
+ break
+
+ # calculate the predicted value at the proposed point
+ predicted_value = m(p)
+
+ # define the local approximation at the proposed point
+ x_proposed = x + p
+ m_proposed = subproblem(x_proposed, fun, jac, hess, hessp, **subproblem_init_kw)
+
+ # evaluate the ratio defined in equation (4.4)
+ actual_reduction = m.fun - m_proposed.fun
+ predicted_reduction = m.fun - predicted_value
+ if predicted_reduction <= 0:
+ warnflag = 2
+ break
+ rho = actual_reduction / predicted_reduction
+
+ # update the trust radius according to the actual/predicted ratio
+ if rho < 0.25:
+ trust_radius *= 0.25
+ elif rho > 0.75 and hits_boundary:
+ trust_radius = min(2*trust_radius, max_trust_radius)
+
+ # if the ratio is high enough then accept the proposed step
+ if rho > eta:
+ x = x_proposed
+ m = m_proposed
+
+ # append the best guess, call back, increment the iteration count
+ if return_all:
+ allvecs.append(np.copy(x))
+ k += 1
+
+ intermediate_result = OptimizeResult(x=x, fun=m.fun)
+ if _call_callback_maybe_halt(callback, intermediate_result):
+ break
+
+ # check if the gradient is small enough to stop
+ if m.jac_mag < gtol:
+ warnflag = 0
+ break
+
+ # check if we have looked at enough iterations
+ if k >= maxiter:
+ warnflag = 1
+ break
+
+ # print some stuff if requested
+ status_messages = (
+ _status_message['success'],
+ _status_message['maxiter'],
+ 'A bad approximation caused failure to predict improvement.',
+ 'A linalg error occurred, such as a non-psd Hessian.',
+ )
+ if disp:
+ if warnflag == 0:
+ print(status_messages[warnflag])
+ else:
+ warnings.warn(status_messages[warnflag], RuntimeWarning, stacklevel=3)
+ print(f" Current function value: {m.fun:f}")
+ print(f" Iterations: {k:d}")
+ print(f" Function evaluations: {sf.nfev:d}")
+ print(f" Gradient evaluations: {sf.ngev:d}")
+ print(f" Hessian evaluations: {sf.nhev + nhessp[0]:d}")
+
+ result = OptimizeResult(x=x, success=(warnflag == 0), status=warnflag,
+ fun=m.fun, jac=m.jac, nfev=sf.nfev, njev=sf.ngev,
+ nhev=sf.nhev + nhessp[0], nit=k,
+ message=status_messages[warnflag])
+
+ if hess is not None:
+ result['hess'] = m.hess
+
+ if return_all:
+ result['allvecs'] = allvecs
+
+ return result
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._canonical_constraint.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._canonical_constraint.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._canonical_constraint.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._equality_constrained_sqp.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._equality_constrained_sqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._equality_constrained_sqp.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._minimize_trustregion_constr.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._minimize_trustregion_constr.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._minimize_trustregion_constr.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._projections.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._projections.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._projections.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._qp_subproblem.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._qp_subproblem.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._qp_subproblem.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._report.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._report.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._report.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._tests b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._tests
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._tests differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._tr_interior_point.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._tr_interior_point.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/._tr_interior_point.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..549cfb9760dda474cb858b7b36d236af48111067
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/__init__.py
@@ -0,0 +1,6 @@
+"""This module contains the equality constrained SQP solver."""
+
+
+from .minimize_trustregion_constr import _minimize_trustregion_constr
+
+__all__ = ['_minimize_trustregion_constr']
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py
new file mode 100644
index 0000000000000000000000000000000000000000..475f7ba970d0952af31e2b30fb03841725397e9c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/canonical_constraint.py
@@ -0,0 +1,390 @@
+import numpy as np
+import scipy.sparse as sps
+
+
+class CanonicalConstraint:
+ """Canonical constraint to use with trust-constr algorithm.
+
+ It represents the set of constraints of the form::
+
+ f_eq(x) = 0
+ f_ineq(x) <= 0
+
+ where ``f_eq`` and ``f_ineq`` are evaluated by a single function, see
+ below.
+
+ The class is supposed to be instantiated by factory methods, which
+ should prepare the parameters listed below.
+
+ Parameters
+ ----------
+ n_eq, n_ineq : int
+ Number of equality and inequality constraints respectively.
+ fun : callable
+ Function defining the constraints. The signature is
+ ``fun(x) -> c_eq, c_ineq``, where ``c_eq`` is ndarray with `n_eq`
+ components and ``c_ineq`` is ndarray with `n_ineq` components.
+ jac : callable
+ Function to evaluate the Jacobian of the constraint. The signature
+ is ``jac(x) -> J_eq, J_ineq``, where ``J_eq`` and ``J_ineq`` are
+ either ndarray of csr_array of shapes (n_eq, n) and (n_ineq, n),
+ respectively.
+ hess : callable
+ Function to evaluate the Hessian of the constraints multiplied
+ by Lagrange multipliers, that is
+ ``dot(f_eq, v_eq) + dot(f_ineq, v_ineq)``. The signature is
+ ``hess(x, v_eq, v_ineq) -> H``, where ``H`` has an implied
+ shape (n, n) and provide a matrix-vector product operation
+ ``H.dot(p)``.
+ keep_feasible : ndarray, shape (n_ineq,)
+ Mask indicating which inequality constraints should be kept feasible.
+ """
+ def __init__(self, n_eq, n_ineq, fun, jac, hess, keep_feasible):
+ self.n_eq = n_eq
+ self.n_ineq = n_ineq
+ self.fun = fun
+ self.jac = jac
+ self.hess = hess
+ self.keep_feasible = keep_feasible
+
+ @classmethod
+ def from_PreparedConstraint(cls, constraint):
+ """Create an instance from `PreparedConstrained` object."""
+ lb, ub = constraint.bounds
+ cfun = constraint.fun
+ keep_feasible = constraint.keep_feasible
+
+ if np.all(lb == -np.inf) and np.all(ub == np.inf):
+ return cls.empty(cfun.n)
+
+ if np.all(lb == -np.inf) and np.all(ub == np.inf):
+ return cls.empty(cfun.n)
+ elif np.all(lb == ub):
+ return cls._equal_to_canonical(cfun, lb)
+ elif np.all(lb == -np.inf):
+ return cls._less_to_canonical(cfun, ub, keep_feasible)
+ elif np.all(ub == np.inf):
+ return cls._greater_to_canonical(cfun, lb, keep_feasible)
+ else:
+ return cls._interval_to_canonical(cfun, lb, ub, keep_feasible)
+
+ @classmethod
+ def empty(cls, n):
+ """Create an "empty" instance.
+
+ This "empty" instance is required to allow working with unconstrained
+ problems as if they have some constraints.
+ """
+ empty_fun = np.empty(0)
+ empty_jac = np.empty((0, n))
+ empty_hess = sps.csr_array((n, n))
+
+ def fun(x):
+ return empty_fun, empty_fun
+
+ def jac(x):
+ return empty_jac, empty_jac
+
+ def hess(x, v_eq, v_ineq):
+ return empty_hess
+
+ return cls(0, 0, fun, jac, hess, np.empty(0, dtype=np.bool_))
+
+ @classmethod
+ def concatenate(cls, canonical_constraints, sparse_jacobian):
+ """Concatenate multiple `CanonicalConstraint` into one.
+
+ `sparse_jacobian` (bool) determines the Jacobian format of the
+ concatenated constraint. Note that items in `canonical_constraints`
+ must have their Jacobians in the same format.
+ """
+ def fun(x):
+ if canonical_constraints:
+ eq_all, ineq_all = zip(
+ *[c.fun(x) for c in canonical_constraints])
+ else:
+ eq_all, ineq_all = [], []
+
+ return np.hstack(eq_all), np.hstack(ineq_all)
+
+ if sparse_jacobian:
+ vstack = sps.vstack
+ else:
+ vstack = np.vstack
+
+ def jac(x):
+ if canonical_constraints:
+ eq_all, ineq_all = zip(
+ *[c.jac(x) for c in canonical_constraints])
+ else:
+ eq_all, ineq_all = [], []
+
+ return vstack(eq_all), vstack(ineq_all)
+
+ def hess(x, v_eq, v_ineq):
+ hess_all = []
+ index_eq = 0
+ index_ineq = 0
+ for c in canonical_constraints:
+ vc_eq = v_eq[index_eq:index_eq + c.n_eq]
+ vc_ineq = v_ineq[index_ineq:index_ineq + c.n_ineq]
+ hess_all.append(c.hess(x, vc_eq, vc_ineq))
+ index_eq += c.n_eq
+ index_ineq += c.n_ineq
+
+ def matvec(p):
+ result = np.zeros_like(p, dtype=float)
+ for h in hess_all:
+ result += h.dot(p)
+ return result
+
+ n = x.shape[0]
+ return sps.linalg.LinearOperator((n, n), matvec, dtype=float)
+
+ n_eq = sum(c.n_eq for c in canonical_constraints)
+ n_ineq = sum(c.n_ineq for c in canonical_constraints)
+ keep_feasible = np.hstack([c.keep_feasible for c in
+ canonical_constraints])
+
+ return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible)
+
+ @classmethod
+ def _equal_to_canonical(cls, cfun, value):
+ empty_fun = np.empty(0)
+ n = cfun.n
+
+ n_eq = value.shape[0]
+ n_ineq = 0
+ keep_feasible = np.empty(0, dtype=bool)
+
+ if cfun.sparse_jacobian:
+ empty_jac = sps.csr_array((0, n))
+ else:
+ empty_jac = np.empty((0, n))
+
+ def fun(x):
+ return cfun.fun(x) - value, empty_fun
+
+ def jac(x):
+ return cfun.jac(x), empty_jac
+
+ def hess(x, v_eq, v_ineq):
+ return cfun.hess(x, v_eq)
+
+ empty_fun = np.empty(0)
+ n = cfun.n
+ if cfun.sparse_jacobian:
+ empty_jac = sps.csr_array((0, n))
+ else:
+ empty_jac = np.empty((0, n))
+
+ return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible)
+
+ @classmethod
+ def _less_to_canonical(cls, cfun, ub, keep_feasible):
+ empty_fun = np.empty(0)
+ n = cfun.n
+ if cfun.sparse_jacobian:
+ empty_jac = sps.csr_array((0, n))
+ else:
+ empty_jac = np.empty((0, n))
+
+ finite_ub = ub < np.inf
+ n_eq = 0
+ n_ineq = np.sum(finite_ub)
+
+ if np.all(finite_ub):
+ def fun(x):
+ return empty_fun, cfun.fun(x) - ub
+
+ def jac(x):
+ return empty_jac, cfun.jac(x)
+
+ def hess(x, v_eq, v_ineq):
+ return cfun.hess(x, v_ineq)
+ else:
+ finite_ub = np.nonzero(finite_ub)[0]
+ keep_feasible = keep_feasible[finite_ub]
+ ub = ub[finite_ub]
+
+ def fun(x):
+ return empty_fun, cfun.fun(x)[finite_ub] - ub
+
+ def jac(x):
+ return empty_jac, cfun.jac(x)[finite_ub]
+
+ def hess(x, v_eq, v_ineq):
+ v = np.zeros(cfun.m)
+ v[finite_ub] = v_ineq
+ return cfun.hess(x, v)
+
+ return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible)
+
+ @classmethod
+ def _greater_to_canonical(cls, cfun, lb, keep_feasible):
+ empty_fun = np.empty(0)
+ n = cfun.n
+ if cfun.sparse_jacobian:
+ empty_jac = sps.csr_array((0, n))
+ else:
+ empty_jac = np.empty((0, n))
+
+ finite_lb = lb > -np.inf
+ n_eq = 0
+ n_ineq = np.sum(finite_lb)
+
+ if np.all(finite_lb):
+ def fun(x):
+ return empty_fun, lb - cfun.fun(x)
+
+ def jac(x):
+ return empty_jac, -cfun.jac(x)
+
+ def hess(x, v_eq, v_ineq):
+ return cfun.hess(x, -v_ineq)
+ else:
+ finite_lb = np.nonzero(finite_lb)[0]
+ keep_feasible = keep_feasible[finite_lb]
+ lb = lb[finite_lb]
+
+ def fun(x):
+ return empty_fun, lb - cfun.fun(x)[finite_lb]
+
+ def jac(x):
+ return empty_jac, -cfun.jac(x)[finite_lb]
+
+ def hess(x, v_eq, v_ineq):
+ v = np.zeros(cfun.m)
+ v[finite_lb] = -v_ineq
+ return cfun.hess(x, v)
+
+ return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible)
+
+ @classmethod
+ def _interval_to_canonical(cls, cfun, lb, ub, keep_feasible):
+ lb_inf = lb == -np.inf
+ ub_inf = ub == np.inf
+ equal = lb == ub
+ less = lb_inf & ~ub_inf
+ greater = ub_inf & ~lb_inf
+ interval = ~equal & ~lb_inf & ~ub_inf
+
+ equal = np.nonzero(equal)[0]
+ less = np.nonzero(less)[0]
+ greater = np.nonzero(greater)[0]
+ interval = np.nonzero(interval)[0]
+ n_less = less.shape[0]
+ n_greater = greater.shape[0]
+ n_interval = interval.shape[0]
+ n_ineq = n_less + n_greater + 2 * n_interval
+ n_eq = equal.shape[0]
+
+ keep_feasible = np.hstack((keep_feasible[less],
+ keep_feasible[greater],
+ keep_feasible[interval],
+ keep_feasible[interval]))
+
+ def fun(x):
+ f = cfun.fun(x)
+ eq = f[equal] - lb[equal]
+ le = f[less] - ub[less]
+ ge = lb[greater] - f[greater]
+ il = f[interval] - ub[interval]
+ ig = lb[interval] - f[interval]
+ return eq, np.hstack((le, ge, il, ig))
+
+ def jac(x):
+ J = cfun.jac(x)
+ eq = J[equal]
+ le = J[less]
+ ge = -J[greater]
+ il = J[interval]
+ ig = -il
+ if sps.issparse(J):
+ ineq = sps.vstack((le, ge, il, ig))
+ else:
+ ineq = np.vstack((le, ge, il, ig))
+ return eq, ineq
+
+ def hess(x, v_eq, v_ineq):
+ n_start = 0
+ v_l = v_ineq[n_start:n_start + n_less]
+ n_start += n_less
+ v_g = v_ineq[n_start:n_start + n_greater]
+ n_start += n_greater
+ v_il = v_ineq[n_start:n_start + n_interval]
+ n_start += n_interval
+ v_ig = v_ineq[n_start:n_start + n_interval]
+
+ v = np.zeros_like(lb)
+ v[equal] = v_eq
+ v[less] = v_l
+ v[greater] = -v_g
+ v[interval] = v_il - v_ig
+
+ return cfun.hess(x, v)
+
+ return cls(n_eq, n_ineq, fun, jac, hess, keep_feasible)
+
+
+def initial_constraints_as_canonical(n, prepared_constraints, sparse_jacobian):
+ """Convert initial values of the constraints to the canonical format.
+
+ The purpose to avoid one additional call to the constraints at the initial
+ point. It takes saved values in `PreparedConstraint`, modifies and
+ concatenates them to the canonical constraint format.
+ """
+ c_eq = []
+ c_ineq = []
+ J_eq = []
+ J_ineq = []
+
+ for c in prepared_constraints:
+ f = c.fun.f
+ J = c.fun.J
+ lb, ub = c.bounds
+ if np.all(lb == ub):
+ c_eq.append(f - lb)
+ J_eq.append(J)
+ elif np.all(lb == -np.inf):
+ finite_ub = ub < np.inf
+ c_ineq.append(f[finite_ub] - ub[finite_ub])
+ J_ineq.append(J[finite_ub])
+ elif np.all(ub == np.inf):
+ finite_lb = lb > -np.inf
+ c_ineq.append(lb[finite_lb] - f[finite_lb])
+ J_ineq.append(-J[finite_lb])
+ else:
+ lb_inf = lb == -np.inf
+ ub_inf = ub == np.inf
+ equal = lb == ub
+ less = lb_inf & ~ub_inf
+ greater = ub_inf & ~lb_inf
+ interval = ~equal & ~lb_inf & ~ub_inf
+
+ c_eq.append(f[equal] - lb[equal])
+ c_ineq.append(f[less] - ub[less])
+ c_ineq.append(lb[greater] - f[greater])
+ c_ineq.append(f[interval] - ub[interval])
+ c_ineq.append(lb[interval] - f[interval])
+
+ J_eq.append(J[equal])
+ J_ineq.append(J[less])
+ J_ineq.append(-J[greater])
+ J_ineq.append(J[interval])
+ J_ineq.append(-J[interval])
+
+ c_eq = np.hstack(c_eq) if c_eq else np.empty(0)
+ c_ineq = np.hstack(c_ineq) if c_ineq else np.empty(0)
+
+ if sparse_jacobian:
+ vstack = sps.vstack
+ empty = sps.csr_array((0, n))
+ else:
+ vstack = np.vstack
+ empty = np.empty((0, n))
+
+ J_eq = vstack(J_eq) if J_eq else empty
+ J_ineq = vstack(J_ineq) if J_ineq else empty
+
+ return c_eq, c_ineq, J_eq, J_ineq
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..20cb069f11be9541ac9fd7dfdd68c0177a0aa685
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/equality_constrained_sqp.py
@@ -0,0 +1,231 @@
+"""Byrd-Omojokun Trust-Region SQP method."""
+
+from scipy.sparse import eye_array as speye
+from .projections import projections
+from .qp_subproblem import modified_dogleg, projected_cg, box_intersections
+import numpy as np
+from numpy.linalg import norm
+
+__all__ = ['equality_constrained_sqp']
+
+
+def default_scaling(x):
+ n, = np.shape(x)
+ return speye(n)
+
+
+def equality_constrained_sqp(fun_and_constr, grad_and_jac, lagr_hess,
+ x0, fun0, grad0, constr0,
+ jac0, stop_criteria,
+ state,
+ initial_penalty,
+ initial_trust_radius,
+ factorization_method,
+ trust_lb=None,
+ trust_ub=None,
+ scaling=default_scaling):
+ """Solve nonlinear equality-constrained problem using trust-region SQP.
+
+ Solve optimization problem:
+
+ minimize fun(x)
+ subject to: constr(x) = 0
+
+ using Byrd-Omojokun Trust-Region SQP method described in [1]_. Several
+ implementation details are based on [2]_ and [3]_, p. 549.
+
+ References
+ ----------
+ .. [1] Lalee, Marucha, Jorge Nocedal, and Todd Plantenga. "On the
+ implementation of an algorithm for large-scale equality
+ constrained optimization." SIAM Journal on
+ Optimization 8.3 (1998): 682-706.
+ .. [2] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal.
+ "An interior point algorithm for large-scale nonlinear
+ programming." SIAM Journal on Optimization 9.4 (1999): 877-900.
+ .. [3] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+ """
+ PENALTY_FACTOR = 0.3 # Rho from formula (3.51), reference [2]_, p.891.
+ LARGE_REDUCTION_RATIO = 0.9
+ INTERMEDIARY_REDUCTION_RATIO = 0.3
+ SUFFICIENT_REDUCTION_RATIO = 1e-8 # Eta from reference [2]_, p.892.
+ TRUST_ENLARGEMENT_FACTOR_L = 7.0
+ TRUST_ENLARGEMENT_FACTOR_S = 2.0
+ MAX_TRUST_REDUCTION = 0.5
+ MIN_TRUST_REDUCTION = 0.1
+ SOC_THRESHOLD = 0.1
+ TR_FACTOR = 0.8 # Zeta from formula (3.21), reference [2]_, p.885.
+ BOX_FACTOR = 0.5
+
+ n, = np.shape(x0) # Number of parameters
+
+ # Set default lower and upper bounds.
+ if trust_lb is None:
+ trust_lb = np.full(n, -np.inf)
+ if trust_ub is None:
+ trust_ub = np.full(n, np.inf)
+
+ # Initial values
+ x = np.copy(x0)
+ trust_radius = initial_trust_radius
+ penalty = initial_penalty
+ # Compute Values
+ f = fun0
+ c = grad0
+ b = constr0
+ A = jac0
+ S = scaling(x)
+ # Get projections
+ try:
+ Z, LS, Y = projections(A, factorization_method)
+ except ValueError as e:
+ if str(e) == "expected square matrix":
+ # can be the case if there are more equality
+ # constraints than independent variables
+ raise ValueError(
+ "The 'expected square matrix' error can occur if there are"
+ " more equality constraints than independent variables."
+ " Consider how your constraints are set up, or use"
+ " factorization_method='SVDFactorization'."
+ ) from e
+ else:
+ raise e
+
+ # Compute least-square lagrange multipliers
+ v = -LS.dot(c)
+ # Compute Hessian
+ H = lagr_hess(x, v)
+
+ # Update state parameters
+ optimality = norm(c + A.T.dot(v), np.inf)
+ constr_violation = norm(b, np.inf) if len(b) > 0 else 0
+ cg_info = {'niter': 0, 'stop_cond': 0,
+ 'hits_boundary': False}
+
+ last_iteration_failed = False
+ while not stop_criteria(state, x, last_iteration_failed,
+ optimality, constr_violation,
+ trust_radius, penalty, cg_info):
+ # Normal Step - `dn`
+ # minimize 1/2*||A dn + b||^2
+ # subject to:
+ # ||dn|| <= TR_FACTOR * trust_radius
+ # BOX_FACTOR * lb <= dn <= BOX_FACTOR * ub.
+ dn = modified_dogleg(A, Y, b,
+ TR_FACTOR*trust_radius,
+ BOX_FACTOR*trust_lb,
+ BOX_FACTOR*trust_ub)
+
+ # Tangential Step - `dt`
+ # Solve the QP problem:
+ # minimize 1/2 dt.T H dt + dt.T (H dn + c)
+ # subject to:
+ # A dt = 0
+ # ||dt|| <= sqrt(trust_radius**2 - ||dn||**2)
+ # lb - dn <= dt <= ub - dn
+ c_t = H.dot(dn) + c
+ b_t = np.zeros_like(b)
+ trust_radius_t = np.sqrt(trust_radius**2 - np.linalg.norm(dn)**2)
+ lb_t = trust_lb - dn
+ ub_t = trust_ub - dn
+ dt, cg_info = projected_cg(H, c_t, Z, Y, b_t,
+ trust_radius_t,
+ lb_t, ub_t)
+
+ # Compute update (normal + tangential steps).
+ d = dn + dt
+
+ # Compute second order model: 1/2 d H d + c.T d + f.
+ quadratic_model = 1/2*(H.dot(d)).dot(d) + c.T.dot(d)
+ # Compute linearized constraint: l = A d + b.
+ linearized_constr = A.dot(d)+b
+ # Compute new penalty parameter according to formula (3.52),
+ # reference [2]_, p.891.
+ vpred = norm(b) - norm(linearized_constr)
+ # Guarantee `vpred` always positive,
+ # regardless of roundoff errors.
+ vpred = max(1e-16, vpred)
+ previous_penalty = penalty
+ if quadratic_model > 0:
+ new_penalty = quadratic_model / ((1-PENALTY_FACTOR)*vpred)
+ penalty = max(penalty, new_penalty)
+ # Compute predicted reduction according to formula (3.52),
+ # reference [2]_, p.891.
+ predicted_reduction = -quadratic_model + penalty*vpred
+
+ # Compute merit function at current point
+ merit_function = f + penalty*norm(b)
+ # Evaluate function and constraints at trial point
+ x_next = x + S.dot(d)
+ f_next, b_next = fun_and_constr(x_next)
+ # Compute merit function at trial point
+ merit_function_next = f_next + penalty*norm(b_next)
+ # Compute actual reduction according to formula (3.54),
+ # reference [2]_, p.892.
+ actual_reduction = merit_function - merit_function_next
+ # Compute reduction ratio
+ reduction_ratio = actual_reduction / predicted_reduction
+
+ # Second order correction (SOC), reference [2]_, p.892.
+ if reduction_ratio < SUFFICIENT_REDUCTION_RATIO and \
+ norm(dn) <= SOC_THRESHOLD * norm(dt):
+ # Compute second order correction
+ y = -Y.dot(b_next)
+ # Make sure increment is inside box constraints
+ _, t, intersect = box_intersections(d, y, trust_lb, trust_ub)
+ # Compute tentative point
+ x_soc = x + S.dot(d + t*y)
+ f_soc, b_soc = fun_and_constr(x_soc)
+ # Recompute actual reduction
+ merit_function_soc = f_soc + penalty*norm(b_soc)
+ actual_reduction_soc = merit_function - merit_function_soc
+ # Recompute reduction ratio
+ reduction_ratio_soc = actual_reduction_soc / predicted_reduction
+ if intersect and reduction_ratio_soc >= SUFFICIENT_REDUCTION_RATIO:
+ x_next = x_soc
+ f_next = f_soc
+ b_next = b_soc
+ reduction_ratio = reduction_ratio_soc
+
+ # Readjust trust region step, formula (3.55), reference [2]_, p.892.
+ if reduction_ratio >= LARGE_REDUCTION_RATIO:
+ trust_radius = max(TRUST_ENLARGEMENT_FACTOR_L * norm(d),
+ trust_radius)
+ elif reduction_ratio >= INTERMEDIARY_REDUCTION_RATIO:
+ trust_radius = max(TRUST_ENLARGEMENT_FACTOR_S * norm(d),
+ trust_radius)
+ # Reduce trust region step, according to reference [3]_, p.696.
+ elif reduction_ratio < SUFFICIENT_REDUCTION_RATIO:
+ trust_reduction = ((1-SUFFICIENT_REDUCTION_RATIO) /
+ (1-reduction_ratio))
+ new_trust_radius = trust_reduction * norm(d)
+ if new_trust_radius >= MAX_TRUST_REDUCTION * trust_radius:
+ trust_radius *= MAX_TRUST_REDUCTION
+ elif new_trust_radius >= MIN_TRUST_REDUCTION * trust_radius:
+ trust_radius = new_trust_radius
+ else:
+ trust_radius *= MIN_TRUST_REDUCTION
+
+ # Update iteration
+ if reduction_ratio >= SUFFICIENT_REDUCTION_RATIO:
+ x = x_next
+ f, b = f_next, b_next
+ c, A = grad_and_jac(x)
+ S = scaling(x)
+ # Get projections
+ Z, LS, Y = projections(A, factorization_method)
+ # Compute least-square lagrange multipliers
+ v = -LS.dot(c)
+ # Compute Hessian
+ H = lagr_hess(x, v)
+ # Set Flag
+ last_iteration_failed = False
+ # Optimality values
+ optimality = norm(c + A.T.dot(v), np.inf)
+ constr_violation = norm(b, np.inf) if len(b) > 0 else 0
+ else:
+ penalty = previous_penalty
+ last_iteration_failed = True
+
+ return x, state
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py
new file mode 100644
index 0000000000000000000000000000000000000000..2978c6fffa80e2988cbb080d3ef074b549b92004
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/minimize_trustregion_constr.py
@@ -0,0 +1,586 @@
+import time
+import numpy as np
+from scipy.sparse.linalg import LinearOperator
+from .._differentiable_functions import VectorFunction
+from .._constraints import (
+ NonlinearConstraint, LinearConstraint, PreparedConstraint, Bounds, strict_bounds)
+from .._hessian_update_strategy import BFGS
+from .._optimize import OptimizeResult
+from .._differentiable_functions import ScalarFunction
+from .equality_constrained_sqp import equality_constrained_sqp
+from .canonical_constraint import (CanonicalConstraint,
+ initial_constraints_as_canonical)
+from .tr_interior_point import tr_interior_point
+from .report import BasicReport, SQPReport, IPReport
+
+
+TERMINATION_MESSAGES = {
+ 0: "The maximum number of function evaluations is exceeded.",
+ 1: "`gtol` termination condition is satisfied.",
+ 2: "`xtol` termination condition is satisfied.",
+ 3: "`callback` raised `StopIteration`.",
+ 4: "Constraint violation exceeds 'gtol'"
+}
+
+
+class HessianLinearOperator:
+ """Build LinearOperator from hessp"""
+ def __init__(self, hessp, n):
+ self.hessp = hessp
+ self.n = n
+
+ def __call__(self, x, *args):
+ def matvec(p):
+ return self.hessp(x, p, *args)
+
+ return LinearOperator((self.n, self.n), matvec=matvec)
+
+
+class LagrangianHessian:
+ """The Hessian of the Lagrangian as LinearOperator.
+
+ The Lagrangian is computed as the objective function plus all the
+ constraints multiplied with some numbers (Lagrange multipliers).
+ """
+ def __init__(self, n, objective_hess, constraints_hess):
+ self.n = n
+ self.objective_hess = objective_hess
+ self.constraints_hess = constraints_hess
+
+ def __call__(self, x, v_eq, v_ineq=None):
+ if v_ineq is None:
+ v_ineq = np.empty(0)
+ H_objective = self.objective_hess(x)
+ H_constraints = self.constraints_hess(x, v_eq, v_ineq)
+
+ def matvec(p):
+ return H_objective.dot(p) + H_constraints.dot(p)
+
+ return LinearOperator((self.n, self.n), matvec)
+
+
+def update_state_sqp(state, x, last_iteration_failed, objective, prepared_constraints,
+ start_time, tr_radius, constr_penalty, cg_info):
+ state.nit += 1
+ state.nfev = objective.nfev
+ state.njev = objective.ngev
+ state.nhev = objective.nhev
+ state.constr_nfev = [c.fun.nfev if isinstance(c.fun, VectorFunction) else 0
+ for c in prepared_constraints]
+ state.constr_njev = [c.fun.njev if isinstance(c.fun, VectorFunction) else 0
+ for c in prepared_constraints]
+ state.constr_nhev = [c.fun.nhev if isinstance(c.fun, VectorFunction) else 0
+ for c in prepared_constraints]
+
+ if not last_iteration_failed:
+ state.x = x
+ state.fun = objective.f
+ state.grad = objective.g
+ state.v = [c.fun.v for c in prepared_constraints]
+ state.constr = [c.fun.f for c in prepared_constraints]
+ state.jac = [c.fun.J for c in prepared_constraints]
+ # Compute Lagrangian Gradient
+ state.lagrangian_grad = np.copy(state.grad)
+ for c in prepared_constraints:
+ state.lagrangian_grad += c.fun.J.T.dot(c.fun.v)
+ state.optimality = np.linalg.norm(state.lagrangian_grad, np.inf)
+ # Compute maximum constraint violation
+ state.constr_violation = 0
+ for i in range(len(prepared_constraints)):
+ lb, ub = prepared_constraints[i].bounds
+ c = state.constr[i]
+ state.constr_violation = np.max([state.constr_violation,
+ np.max(lb - c),
+ np.max(c - ub)])
+
+ state.execution_time = time.time() - start_time
+ state.tr_radius = tr_radius
+ state.constr_penalty = constr_penalty
+ state.cg_niter += cg_info["niter"]
+ state.cg_stop_cond = cg_info["stop_cond"]
+
+ return state
+
+
+def update_state_ip(state, x, last_iteration_failed, objective,
+ prepared_constraints, start_time,
+ tr_radius, constr_penalty, cg_info,
+ barrier_parameter, barrier_tolerance):
+ state = update_state_sqp(state, x, last_iteration_failed, objective,
+ prepared_constraints, start_time, tr_radius,
+ constr_penalty, cg_info)
+ state.barrier_parameter = barrier_parameter
+ state.barrier_tolerance = barrier_tolerance
+ return state
+
+
+def _minimize_trustregion_constr(fun, x0, args, grad,
+ hess, hessp, bounds, constraints,
+ xtol=1e-8, gtol=1e-8,
+ barrier_tol=1e-8,
+ sparse_jacobian=None,
+ callback=None, maxiter=1000,
+ verbose=0, finite_diff_rel_step=None,
+ initial_constr_penalty=1.0, initial_tr_radius=1.0,
+ initial_barrier_parameter=0.1,
+ initial_barrier_tolerance=0.1,
+ factorization_method=None,
+ disp=False,
+ workers=None):
+ """Minimize a scalar function subject to constraints.
+
+ Parameters
+ ----------
+ gtol : float, optional
+ Tolerance for termination by the norm of the Lagrangian gradient.
+ The algorithm will terminate when both the infinity norm (i.e., max
+ abs value) of the Lagrangian gradient and the constraint violation
+ are smaller than ``gtol``. Default is 1e-8.
+ xtol : float, optional
+ Tolerance for termination by the change of the independent variable.
+ The algorithm will terminate when ``tr_radius < xtol``, where
+ ``tr_radius`` is the radius of the trust region used in the algorithm.
+ Default is 1e-8.
+ barrier_tol : float, optional
+ Threshold on the barrier parameter for the algorithm termination.
+ When inequality constraints are present, the algorithm will terminate
+ only when the barrier parameter is less than `barrier_tol`.
+ Default is 1e-8.
+ sparse_jacobian : {bool, None}, optional
+ Determines how to represent Jacobians of the constraints. If bool,
+ then Jacobians of all the constraints will be converted to the
+ corresponding format. If None (default), then Jacobians won't be
+ converted, but the algorithm can proceed only if they all have the
+ same format.
+ initial_tr_radius: float, optional
+ Initial trust radius. The trust radius gives the maximum distance
+ between solution points in consecutive iterations. It reflects the
+ trust the algorithm puts in the local approximation of the optimization
+ problem. For an accurate local approximation the trust-region should be
+ large and for an approximation valid only close to the current point it
+ should be a small one. The trust radius is automatically updated throughout
+ the optimization process, with ``initial_tr_radius`` being its initial value.
+ Default is 1 (recommended in [1]_, p. 19).
+ initial_constr_penalty : float, optional
+ Initial constraints penalty parameter. The penalty parameter is used for
+ balancing the requirements of decreasing the objective function
+ and satisfying the constraints. It is used for defining the merit function:
+ ``merit_function(x) = fun(x) + constr_penalty * constr_norm_l2(x)``,
+ where ``constr_norm_l2(x)`` is the l2 norm of a vector containing all
+ the constraints. The merit function is used for accepting or rejecting
+ trial points and ``constr_penalty`` weights the two conflicting goals
+ of reducing objective function and constraints. The penalty is automatically
+ updated throughout the optimization process, with
+ ``initial_constr_penalty`` being its initial value. Default is 1
+ (recommended in [1]_, p 19).
+ initial_barrier_parameter, initial_barrier_tolerance: float, optional
+ Initial barrier parameter and initial tolerance for the barrier subproblem.
+ Both are used only when inequality constraints are present. For dealing with
+ optimization problems ``min_x f(x)`` subject to inequality constraints
+ ``c(x) <= 0`` the algorithm introduces slack variables, solving the problem
+ ``min_(x,s) f(x) + barrier_parameter*sum(ln(s))`` subject to the equality
+ constraints ``c(x) + s = 0`` instead of the original problem. This subproblem
+ is solved for decreasing values of ``barrier_parameter`` and with decreasing
+ tolerances for the termination, starting with ``initial_barrier_parameter``
+ for the barrier parameter and ``initial_barrier_tolerance`` for the
+ barrier tolerance. Default is 0.1 for both values (recommended in [1]_ p. 19).
+ Also note that ``barrier_parameter`` and ``barrier_tolerance`` are updated
+ with the same prefactor.
+ factorization_method : string or None, optional
+ Method to factorize the Jacobian of the constraints. Use None (default)
+ for the auto selection or one of:
+
+ - 'NormalEquation' (requires scikit-sparse)
+ - 'AugmentedSystem'
+ - 'QRFactorization'
+ - 'SVDFactorization'
+
+ The methods 'NormalEquation' and 'AugmentedSystem' can be used only
+ with sparse constraints. The projections required by the algorithm
+ will be computed using, respectively, the normal equation and the
+ augmented system approaches explained in [1]_. 'NormalEquation'
+ computes the Cholesky factorization of ``A A.T`` and 'AugmentedSystem'
+ performs the LU factorization of an augmented system. They usually
+ provide similar results. 'AugmentedSystem' is used by default for
+ sparse matrices.
+
+ The methods 'QRFactorization' and 'SVDFactorization' can be used
+ only with dense constraints. They compute the required projections
+ using, respectively, QR and SVD factorizations. The 'SVDFactorization'
+ method can cope with Jacobian matrices with deficient row rank and will
+ be used whenever other factorization methods fail (which may imply the
+ conversion of sparse matrices to a dense format when required).
+ By default, 'QRFactorization' is used for dense matrices.
+ finite_diff_rel_step : None or array_like, optional
+ Relative step size for the finite difference approximation.
+ maxiter : int, optional
+ Maximum number of algorithm iterations. Default is 1000.
+ verbose : {0, 1, 2, 3}, optional
+ Level of algorithm's verbosity:
+
+ * 0 (default) : work silently.
+ * 1 : display a termination report.
+ * 2 : display progress during iterations.
+ * 3 : display progress during iterations (more complete report).
+
+ disp : bool, optional
+ If True (default), then `verbose` will be set to 1 if it was 0.
+ workers : int, map-like callable, optional
+ A map-like callable, such as `multiprocessing.Pool.map` for evaluating
+ any numerical differentiation in parallel.
+ This evaluation is carried out as ``workers(fun, iterable)``.
+
+ .. versionadded:: 1.16.0
+
+ Returns
+ -------
+ `OptimizeResult` with the fields documented below. Note the following:
+
+ 1. All values corresponding to the constraints are ordered as they
+ were passed to the solver. And values corresponding to `bounds`
+ constraints are put *after* other constraints.
+ 2. All numbers of function, Jacobian or Hessian evaluations correspond
+ to numbers of actual Python function calls. It means, for example,
+ that if a Jacobian is estimated by finite differences, then the
+ number of Jacobian evaluations will be zero and the number of
+ function evaluations will be incremented by all calls during the
+ finite difference estimation.
+
+ x : ndarray, shape (n,)
+ Solution found.
+ optimality : float
+ Infinity norm of the Lagrangian gradient at the solution.
+ constr_violation : float
+ Maximum constraint violation at the solution.
+ fun : float
+ Objective function at the solution.
+ grad : ndarray, shape (n,)
+ Gradient of the objective function at the solution.
+ lagrangian_grad : ndarray, shape (n,)
+ Gradient of the Lagrangian function at the solution.
+ nit : int
+ Total number of iterations.
+ nfev : integer
+ Number of the objective function evaluations.
+ njev : integer
+ Number of the objective function gradient evaluations.
+ nhev : integer
+ Number of the objective function Hessian evaluations.
+ cg_niter : int
+ Total number of the conjugate gradient method iterations.
+ method : {'equality_constrained_sqp', 'tr_interior_point'}
+ Optimization method used.
+ constr : list of ndarray
+ List of constraint values at the solution.
+ jac : list of {ndarray, sparse array}
+ List of the Jacobian matrices of the constraints at the solution.
+ v : list of ndarray
+ List of the Lagrange multipliers for the constraints at the solution.
+ For an inequality constraint a positive multiplier means that the upper
+ bound is active, a negative multiplier means that the lower bound is
+ active and if a multiplier is zero it means the constraint is not
+ active.
+ constr_nfev : list of int
+ Number of constraint evaluations for each of the constraints.
+ constr_njev : list of int
+ Number of Jacobian matrix evaluations for each of the constraints.
+ constr_nhev : list of int
+ Number of Hessian evaluations for each of the constraints.
+ tr_radius : float
+ Radius of the trust region at the last iteration.
+ constr_penalty : float
+ Penalty parameter at the last iteration, see `initial_constr_penalty`.
+ barrier_tolerance : float
+ Tolerance for the barrier subproblem at the last iteration.
+ Only for problems with inequality constraints.
+ barrier_parameter : float
+ Barrier parameter at the last iteration. Only for problems
+ with inequality constraints.
+ execution_time : float
+ Total execution time.
+ message : str
+ Termination message.
+ status : {0, 1, 2, 3, 4}
+ Termination status:
+
+ * 0 : The maximum number of function evaluations is exceeded.
+ * 1 : `gtol` termination condition is satisfied.
+ * 2 : `xtol` termination condition is satisfied.
+ * 3 : `callback` raised `StopIteration`.
+ * 4 : Constraint violation exceeds 'gtol'.
+
+ .. versionchanged:: 1.15.0
+ If the constraint violation exceeds `gtol`, then ``result.success``
+ will now be False.
+
+ cg_stop_cond : int
+ Reason for CG subproblem termination at the last iteration:
+
+ * 0 : CG subproblem not evaluated.
+ * 1 : Iteration limit was reached.
+ * 2 : Reached the trust-region boundary.
+ * 3 : Negative curvature detected.
+ * 4 : Tolerance was satisfied.
+
+ References
+ ----------
+ .. [1] Conn, A. R., Gould, N. I., & Toint, P. L.
+ Trust region methods. 2000. Siam. pp. 19.
+ """
+ x0 = np.atleast_1d(x0).astype(float)
+ n_vars = np.size(x0)
+ if hess is None:
+ if callable(hessp):
+ hess = HessianLinearOperator(hessp, n_vars)
+ else:
+ hess = BFGS()
+ if disp and verbose == 0:
+ verbose = 1
+
+ if bounds is not None:
+ modified_lb = np.nextafter(bounds.lb, -np.inf, where=bounds.lb > -np.inf,
+ out=None)
+ modified_ub = np.nextafter(bounds.ub, np.inf, where=bounds.ub < np.inf,
+ out=None)
+ modified_lb = np.where(np.isfinite(bounds.lb), modified_lb, bounds.lb)
+ modified_ub = np.where(np.isfinite(bounds.ub), modified_ub, bounds.ub)
+ bounds = Bounds(modified_lb, modified_ub, keep_feasible=bounds.keep_feasible)
+ finite_diff_bounds = strict_bounds(bounds.lb, bounds.ub,
+ bounds.keep_feasible, n_vars)
+ else:
+ finite_diff_bounds = (-np.inf, np.inf)
+
+ # Define Objective Function
+ objective = ScalarFunction(fun, x0, args, grad, hess,
+ finite_diff_rel_step, finite_diff_bounds,
+ workers=workers)
+
+ # Put constraints in list format when needed.
+ if isinstance(constraints, (NonlinearConstraint | LinearConstraint)):
+ constraints = [constraints]
+
+ # Prepare constraints.
+ prepared_constraints = [
+ PreparedConstraint(c, x0, sparse_jacobian, finite_diff_bounds)
+ for c in constraints]
+
+ # Check that all constraints are either sparse or dense.
+ n_sparse = sum(c.fun.sparse_jacobian for c in prepared_constraints)
+ if 0 < n_sparse < len(prepared_constraints):
+ raise ValueError("All constraints must have the same kind of the "
+ "Jacobian --- either all sparse or all dense. "
+ "You can set the sparsity globally by setting "
+ "`sparse_jacobian` to either True of False.")
+ if prepared_constraints:
+ sparse_jacobian = n_sparse > 0
+
+ if bounds is not None:
+ if sparse_jacobian is None:
+ sparse_jacobian = True
+ prepared_constraints.append(PreparedConstraint(bounds, x0,
+ sparse_jacobian))
+
+ # Concatenate initial constraints to the canonical form.
+ c_eq0, c_ineq0, J_eq0, J_ineq0 = initial_constraints_as_canonical(
+ n_vars, prepared_constraints, sparse_jacobian)
+
+ # Prepare all canonical constraints and concatenate it into one.
+ canonical_all = [CanonicalConstraint.from_PreparedConstraint(c)
+ for c in prepared_constraints]
+
+ if len(canonical_all) == 0:
+ canonical = CanonicalConstraint.empty(n_vars)
+ elif len(canonical_all) == 1:
+ canonical = canonical_all[0]
+ else:
+ canonical = CanonicalConstraint.concatenate(canonical_all,
+ sparse_jacobian)
+
+ # Generate the Hessian of the Lagrangian.
+ lagrangian_hess = LagrangianHessian(n_vars, objective.hess, canonical.hess)
+
+ # Choose appropriate method
+ if canonical.n_ineq == 0:
+ method = 'equality_constrained_sqp'
+ else:
+ method = 'tr_interior_point'
+
+ # Construct OptimizeResult
+ state = OptimizeResult(
+ nit=0, nfev=0, njev=0, nhev=0,
+ cg_niter=0, cg_stop_cond=0,
+ fun=objective.f, grad=objective.g,
+ lagrangian_grad=np.copy(objective.g),
+ constr=[c.fun.f for c in prepared_constraints],
+ jac=[c.fun.J for c in prepared_constraints],
+ constr_nfev=[0 for c in prepared_constraints],
+ constr_njev=[0 for c in prepared_constraints],
+ constr_nhev=[0 for c in prepared_constraints],
+ v=[c.fun.v for c in prepared_constraints],
+ method=method)
+
+ # Start counting
+ start_time = time.time()
+
+ # Define stop criteria
+ if method == 'equality_constrained_sqp':
+ def stop_criteria(state, x, last_iteration_failed,
+ optimality, constr_violation,
+ tr_radius, constr_penalty, cg_info):
+ state = update_state_sqp(state, x, last_iteration_failed,
+ objective, prepared_constraints,
+ start_time, tr_radius, constr_penalty,
+ cg_info)
+ if verbose == 2:
+ BasicReport.print_iteration(state.nit,
+ state.nfev,
+ state.cg_niter,
+ state.fun,
+ state.tr_radius,
+ state.optimality,
+ state.constr_violation)
+ elif verbose > 2:
+ SQPReport.print_iteration(state.nit,
+ state.nfev,
+ state.cg_niter,
+ state.fun,
+ state.tr_radius,
+ state.optimality,
+ state.constr_violation,
+ state.constr_penalty,
+ state.cg_stop_cond)
+ state.status = None
+ state.niter = state.nit # Alias for callback (backward-compatibility)
+ if callback is not None:
+ callback_stop = False
+ try:
+ callback_stop = callback(state)
+ except StopIteration:
+ callback_stop = True
+ if callback_stop:
+ state.status = 3
+ return True
+ if state.optimality < gtol and state.constr_violation < gtol:
+ state.status = 1
+ elif state.tr_radius < xtol:
+ state.status = 2
+ elif state.nit >= maxiter:
+ state.status = 0
+ return state.status in (0, 1, 2, 3)
+ elif method == 'tr_interior_point':
+ def stop_criteria(state, x, last_iteration_failed, tr_radius,
+ constr_penalty, cg_info, barrier_parameter,
+ barrier_tolerance):
+ state = update_state_ip(state, x, last_iteration_failed,
+ objective, prepared_constraints,
+ start_time, tr_radius, constr_penalty,
+ cg_info, barrier_parameter, barrier_tolerance)
+ if verbose == 2:
+ BasicReport.print_iteration(state.nit,
+ state.nfev,
+ state.cg_niter,
+ state.fun,
+ state.tr_radius,
+ state.optimality,
+ state.constr_violation)
+ elif verbose > 2:
+ IPReport.print_iteration(state.nit,
+ state.nfev,
+ state.cg_niter,
+ state.fun,
+ state.tr_radius,
+ state.optimality,
+ state.constr_violation,
+ state.constr_penalty,
+ state.barrier_parameter,
+ state.cg_stop_cond)
+ state.status = None
+ state.niter = state.nit # Alias for callback (backward compatibility)
+ if callback is not None:
+ callback_stop = False
+ try:
+ callback_stop = callback(state)
+ except StopIteration:
+ callback_stop = True
+ if callback_stop:
+ state.status = 3
+ return True
+ if state.optimality < gtol and state.constr_violation < gtol:
+ state.status = 1
+ elif (state.tr_radius < xtol
+ and state.barrier_parameter < barrier_tol):
+ state.status = 2
+ elif state.nit >= maxiter:
+ state.status = 0
+ return state.status in (0, 1, 2, 3)
+
+ if verbose == 2:
+ BasicReport.print_header()
+ elif verbose > 2:
+ if method == 'equality_constrained_sqp':
+ SQPReport.print_header()
+ elif method == 'tr_interior_point':
+ IPReport.print_header()
+
+ # Call inferior function to do the optimization
+ if method == 'equality_constrained_sqp':
+ def fun_and_constr(x):
+ f = objective.fun(x)
+ c_eq, _ = canonical.fun(x)
+ return f, c_eq
+
+ def grad_and_jac(x):
+ g = objective.grad(x)
+ J_eq, _ = canonical.jac(x)
+ return g, J_eq
+
+ _, result = equality_constrained_sqp(
+ fun_and_constr, grad_and_jac, lagrangian_hess,
+ x0, objective.f, objective.g,
+ c_eq0, J_eq0,
+ stop_criteria, state,
+ initial_constr_penalty, initial_tr_radius,
+ factorization_method)
+
+ elif method == 'tr_interior_point':
+ _, result = tr_interior_point(
+ objective.fun, objective.grad, lagrangian_hess,
+ n_vars, canonical.n_ineq, canonical.n_eq,
+ canonical.fun, canonical.jac,
+ x0, objective.f, objective.g,
+ c_ineq0, J_ineq0, c_eq0, J_eq0,
+ stop_criteria,
+ canonical.keep_feasible,
+ xtol, state, initial_barrier_parameter,
+ initial_barrier_tolerance,
+ initial_constr_penalty, initial_tr_radius,
+ factorization_method, finite_diff_bounds)
+
+ # Status 4 occurs when minimize is successful but constraints are not satisfied.
+ if result.status in (1, 2) and state.constr_violation > gtol:
+ result.status = 4
+
+ # Status 3 occurs when the callback function requests termination,
+ # this is assumed to not be a success.
+ result.success = True if result.status in (1, 2) else False
+ result.message = TERMINATION_MESSAGES[result.status]
+
+ # Alias (for backward compatibility with 1.1.0)
+ result.niter = result.nit
+
+ if verbose == 2:
+ BasicReport.print_footer()
+ elif verbose > 2:
+ if method == 'equality_constrained_sqp':
+ SQPReport.print_footer()
+ elif method == 'tr_interior_point':
+ IPReport.print_footer()
+ if verbose >= 1:
+ print(result.message)
+ print(f"Number of iterations: {result.nit}, "
+ f"function evaluations: {result.nfev}, "
+ f"CG iterations: {result.cg_niter}, "
+ f"optimality: {result.optimality:.2e}, "
+ f"constraint violation: {result.constr_violation:.2e}, "
+ f"execution time: {result.execution_time:4.2} s.")
+ return result
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/projections.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/projections.py
new file mode 100644
index 0000000000000000000000000000000000000000..09b6cc34bdbc438e3f1fd57c013577ad5a205b32
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/projections.py
@@ -0,0 +1,411 @@
+"""Basic linear factorizations needed by the solver."""
+
+from scipy.sparse import block_array, csc_array, eye_array, issparse
+from scipy.sparse.linalg import LinearOperator
+import scipy.linalg
+import scipy.sparse.linalg
+try:
+ from sksparse.cholmod import cholesky_AAt, CholmodTypeConversionWarning
+ sksparse_available = True
+except ImportError:
+ import warnings
+ sksparse_available = False
+import numpy as np
+from warnings import warn, catch_warnings
+
+__all__ = [
+ 'orthogonality',
+ 'projections',
+]
+
+
+def orthogonality(A, g):
+ """Measure orthogonality between a vector and the null space of a matrix.
+
+ Compute a measure of orthogonality between the null space
+ of the (possibly sparse) matrix ``A`` and a given vector ``g``.
+
+ The formula is a simplified (and cheaper) version of formula (3.13)
+ from [1]_.
+ ``orth = norm(A g, ord=2)/(norm(A, ord='fro')*norm(g, ord=2))``.
+
+ References
+ ----------
+ .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal.
+ "On the solution of equality constrained quadratic
+ programming problems arising in optimization."
+ SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395.
+ """
+ # Compute vector norms
+ norm_g = np.linalg.norm(g)
+ # Compute Froebnius norm of the matrix A
+ if issparse(A):
+ norm_A = scipy.sparse.linalg.norm(A, ord='fro')
+ else:
+ norm_A = np.linalg.norm(A, ord='fro')
+
+ # Check if norms are zero
+ if norm_g == 0 or norm_A == 0:
+ return 0
+
+ norm_A_g = np.linalg.norm(A.dot(g))
+ # Orthogonality measure
+ orth = norm_A_g / (norm_A*norm_g)
+ return orth
+
+
+def normal_equation_projections(A, m, n, orth_tol, max_refin, tol):
+ """Return linear operators for matrix A using ``NormalEquation`` approach.
+ """
+ # Cholesky factorization
+ # TODO: revert this once the warning bug fix in sksparse is merged/released
+ # Add suppression of spurious warning bug from sksparse with csc_array gh-22089
+ # factor = cholesky_AAt(A)
+ with catch_warnings(action='ignore', category=CholmodTypeConversionWarning):
+ factor = cholesky_AAt(A)
+
+ # z = x - A.T inv(A A.T) A x
+ def null_space(x):
+ v = factor(A.dot(x))
+ z = x - A.T.dot(v)
+
+ # Iterative refinement to improve roundoff
+ # errors described in [2]_, algorithm 5.1.
+ k = 0
+ while orthogonality(A, z) > orth_tol:
+ if k >= max_refin:
+ break
+ # z_next = z - A.T inv(A A.T) A z
+ v = factor(A.dot(z))
+ z = z - A.T.dot(v)
+ k += 1
+
+ return z
+
+ # z = inv(A A.T) A x
+ def least_squares(x):
+ return factor(A.dot(x))
+
+ # z = A.T inv(A A.T) x
+ def row_space(x):
+ return A.T.dot(factor(x))
+
+ return null_space, least_squares, row_space
+
+
+def augmented_system_projections(A, m, n, orth_tol, max_refin, tol):
+ """Return linear operators for matrix A - ``AugmentedSystem``."""
+ # Form augmented system
+ K = block_array([[eye_array(n), A.T], [A, None]], format="csc")
+ # LU factorization
+ # TODO: Use a symmetric indefinite factorization
+ # to solve the system twice as fast (because
+ # of the symmetry).
+ try:
+ solve = scipy.sparse.linalg.factorized(K)
+ except RuntimeError:
+ warn("Singular Jacobian matrix. Using dense SVD decomposition to "
+ "perform the factorizations.",
+ stacklevel=3)
+ return svd_factorization_projections(A.toarray(),
+ m, n, orth_tol,
+ max_refin, tol)
+
+ # z = x - A.T inv(A A.T) A x
+ # is computed solving the extended system:
+ # [I A.T] * [ z ] = [x]
+ # [A O ] [aux] [0]
+ def null_space(x):
+ # v = [x]
+ # [0]
+ v = np.hstack([x, np.zeros(m)])
+ # lu_sol = [ z ]
+ # [aux]
+ lu_sol = solve(v)
+ z = lu_sol[:n]
+
+ # Iterative refinement to improve roundoff
+ # errors described in [2]_, algorithm 5.2.
+ k = 0
+ while orthogonality(A, z) > orth_tol:
+ if k >= max_refin:
+ break
+ # new_v = [x] - [I A.T] * [ z ]
+ # [0] [A O ] [aux]
+ new_v = v - K.dot(lu_sol)
+ # [I A.T] * [delta z ] = new_v
+ # [A O ] [delta aux]
+ lu_update = solve(new_v)
+ # [ z ] += [delta z ]
+ # [aux] [delta aux]
+ lu_sol += lu_update
+ z = lu_sol[:n]
+ k += 1
+
+ # return z = x - A.T inv(A A.T) A x
+ return z
+
+ # z = inv(A A.T) A x
+ # is computed solving the extended system:
+ # [I A.T] * [aux] = [x]
+ # [A O ] [ z ] [0]
+ def least_squares(x):
+ # v = [x]
+ # [0]
+ v = np.hstack([x, np.zeros(m)])
+ # lu_sol = [aux]
+ # [ z ]
+ lu_sol = solve(v)
+ # return z = inv(A A.T) A x
+ return lu_sol[n:m+n]
+
+ # z = A.T inv(A A.T) x
+ # is computed solving the extended system:
+ # [I A.T] * [ z ] = [0]
+ # [A O ] [aux] [x]
+ def row_space(x):
+ # v = [0]
+ # [x]
+ v = np.hstack([np.zeros(n), x])
+ # lu_sol = [ z ]
+ # [aux]
+ lu_sol = solve(v)
+ # return z = A.T inv(A A.T) x
+ return lu_sol[:n]
+
+ return null_space, least_squares, row_space
+
+
+def qr_factorization_projections(A, m, n, orth_tol, max_refin, tol):
+ """Return linear operators for matrix A using ``QRFactorization`` approach.
+ """
+ # QRFactorization
+ Q, R, P = scipy.linalg.qr(A.T, pivoting=True, mode='economic')
+
+ if np.linalg.norm(R[-1, :], np.inf) < tol:
+ warn('Singular Jacobian matrix. Using SVD decomposition to ' +
+ 'perform the factorizations.',
+ stacklevel=3)
+ return svd_factorization_projections(A, m, n,
+ orth_tol,
+ max_refin,
+ tol)
+
+ # z = x - A.T inv(A A.T) A x
+ def null_space(x):
+ # v = P inv(R) Q.T x
+ aux1 = Q.T.dot(x)
+ aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False)
+ v = np.zeros(m)
+ v[P] = aux2
+ z = x - A.T.dot(v)
+
+ # Iterative refinement to improve roundoff
+ # errors described in [2]_, algorithm 5.1.
+ k = 0
+ while orthogonality(A, z) > orth_tol:
+ if k >= max_refin:
+ break
+ # v = P inv(R) Q.T x
+ aux1 = Q.T.dot(z)
+ aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False)
+ v[P] = aux2
+ # z_next = z - A.T v
+ z = z - A.T.dot(v)
+ k += 1
+
+ return z
+
+ # z = inv(A A.T) A x
+ def least_squares(x):
+ # z = P inv(R) Q.T x
+ aux1 = Q.T.dot(x)
+ aux2 = scipy.linalg.solve_triangular(R, aux1, lower=False)
+ z = np.zeros(m)
+ z[P] = aux2
+ return z
+
+ # z = A.T inv(A A.T) x
+ def row_space(x):
+ # z = Q inv(R.T) P.T x
+ aux1 = x[P]
+ aux2 = scipy.linalg.solve_triangular(R, aux1,
+ lower=False,
+ trans='T')
+ z = Q.dot(aux2)
+ return z
+
+ return null_space, least_squares, row_space
+
+
+def svd_factorization_projections(A, m, n, orth_tol, max_refin, tol):
+ """Return linear operators for matrix A using ``SVDFactorization`` approach.
+ """
+ # SVD Factorization
+ U, s, Vt = scipy.linalg.svd(A, full_matrices=False)
+
+ # Remove dimensions related with very small singular values
+ U = U[:, s > tol]
+ Vt = Vt[s > tol, :]
+ s = s[s > tol]
+
+ # z = x - A.T inv(A A.T) A x
+ def null_space(x):
+ # v = U 1/s V.T x = inv(A A.T) A x
+ aux1 = Vt.dot(x)
+ aux2 = 1/s*aux1
+ v = U.dot(aux2)
+ z = x - A.T.dot(v)
+
+ # Iterative refinement to improve roundoff
+ # errors described in [2]_, algorithm 5.1.
+ k = 0
+ while orthogonality(A, z) > orth_tol:
+ if k >= max_refin:
+ break
+ # v = U 1/s V.T x = inv(A A.T) A x
+ aux1 = Vt.dot(z)
+ aux2 = 1/s*aux1
+ v = U.dot(aux2)
+ # z_next = z - A.T v
+ z = z - A.T.dot(v)
+ k += 1
+
+ return z
+
+ # z = inv(A A.T) A x
+ def least_squares(x):
+ # z = U 1/s V.T x = inv(A A.T) A x
+ aux1 = Vt.dot(x)
+ aux2 = 1/s*aux1
+ z = U.dot(aux2)
+ return z
+
+ # z = A.T inv(A A.T) x
+ def row_space(x):
+ # z = V 1/s U.T x
+ aux1 = U.T.dot(x)
+ aux2 = 1/s*aux1
+ z = Vt.T.dot(aux2)
+ return z
+
+ return null_space, least_squares, row_space
+
+
+def projections(A, method=None, orth_tol=1e-12, max_refin=3, tol=1e-15):
+ """Return three linear operators related with a given matrix A.
+
+ Parameters
+ ----------
+ A : sparse array (or ndarray), shape (m, n)
+ Matrix ``A`` used in the projection.
+ method : string, optional
+ Method used for compute the given linear
+ operators. Should be one of:
+
+ - 'NormalEquation': The operators
+ will be computed using the
+ so-called normal equation approach
+ explained in [1]_. In order to do
+ so the Cholesky factorization of
+ ``(A A.T)`` is computed. Exclusive
+ for sparse matrices.
+ - 'AugmentedSystem': The operators
+ will be computed using the
+ so-called augmented system approach
+ explained in [1]_. Exclusive
+ for sparse matrices.
+ - 'QRFactorization': Compute projections
+ using QR factorization. Exclusive for
+ dense matrices.
+ - 'SVDFactorization': Compute projections
+ using SVD factorization. Exclusive for
+ dense matrices.
+
+ orth_tol : float, optional
+ Tolerance for iterative refinements.
+ max_refin : int, optional
+ Maximum number of iterative refinements.
+ tol : float, optional
+ Tolerance for singular values.
+
+ Returns
+ -------
+ Z : LinearOperator, shape (n, n)
+ Null-space operator. For a given vector ``x``,
+ the null space operator is equivalent to apply
+ a projection matrix ``P = I - A.T inv(A A.T) A``
+ to the vector. It can be shown that this is
+ equivalent to project ``x`` into the null space
+ of A.
+ LS : LinearOperator, shape (m, n)
+ Least-squares operator. For a given vector ``x``,
+ the least-squares operator is equivalent to apply a
+ pseudoinverse matrix ``pinv(A.T) = inv(A A.T) A``
+ to the vector. It can be shown that this vector
+ ``pinv(A.T) x`` is the least_square solution to
+ ``A.T y = x``.
+ Y : LinearOperator, shape (n, m)
+ Row-space operator. For a given vector ``x``,
+ the row-space operator is equivalent to apply a
+ projection matrix ``Q = A.T inv(A A.T)``
+ to the vector. It can be shown that this
+ vector ``y = Q x`` the minimum norm solution
+ of ``A y = x``.
+
+ Notes
+ -----
+ Uses iterative refinements described in [1]
+ during the computation of ``Z`` in order to
+ cope with the possibility of large roundoff errors.
+
+ References
+ ----------
+ .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal.
+ "On the solution of equality constrained quadratic
+ programming problems arising in optimization."
+ SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395.
+ """
+ m, n = np.shape(A)
+
+ # The factorization of an empty matrix
+ # only works for the sparse representation.
+ if m*n == 0:
+ A = csc_array(A)
+
+ # Check Argument
+ if issparse(A):
+ if method is None:
+ method = "AugmentedSystem"
+ if method not in ("NormalEquation", "AugmentedSystem"):
+ raise ValueError("Method not allowed for sparse array.")
+ if method == "NormalEquation" and not sksparse_available:
+ warnings.warn("Only accepts 'NormalEquation' option when "
+ "scikit-sparse is available. Using "
+ "'AugmentedSystem' option instead.",
+ ImportWarning, stacklevel=3)
+ method = 'AugmentedSystem'
+ else:
+ if method is None:
+ method = "QRFactorization"
+ if method not in ("QRFactorization", "SVDFactorization"):
+ raise ValueError("Method not allowed for dense array.")
+
+ if method == 'NormalEquation':
+ null_space, least_squares, row_space \
+ = normal_equation_projections(A, m, n, orth_tol, max_refin, tol)
+ elif method == 'AugmentedSystem':
+ null_space, least_squares, row_space \
+ = augmented_system_projections(A, m, n, orth_tol, max_refin, tol)
+ elif method == "QRFactorization":
+ null_space, least_squares, row_space \
+ = qr_factorization_projections(A, m, n, orth_tol, max_refin, tol)
+ elif method == "SVDFactorization":
+ null_space, least_squares, row_space \
+ = svd_factorization_projections(A, m, n, orth_tol, max_refin, tol)
+
+ Z = LinearOperator((n, n), null_space)
+ LS = LinearOperator((m, n), least_squares)
+ Y = LinearOperator((n, m), row_space)
+
+ return Z, LS, Y
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py
new file mode 100644
index 0000000000000000000000000000000000000000..e974cbdfa2f182b6186d54505d375d4d8893048e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/qp_subproblem.py
@@ -0,0 +1,637 @@
+"""Equality-constrained quadratic programming solvers."""
+
+from scipy.sparse import linalg, block_array
+from math import copysign
+import numpy as np
+from numpy.linalg import norm
+
+__all__ = [
+ 'eqp_kktfact',
+ 'sphere_intersections',
+ 'box_intersections',
+ 'box_sphere_intersections',
+ 'inside_box_boundaries',
+ 'modified_dogleg',
+ 'projected_cg'
+]
+
+
+# For comparison with the projected CG
+def eqp_kktfact(H, c, A, b):
+ """Solve equality-constrained quadratic programming (EQP) problem.
+
+ Solve ``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0``
+ using direct factorization of the KKT system.
+
+ Parameters
+ ----------
+ H : sparse array, shape (n, n)
+ Hessian matrix of the EQP problem.
+ c : array_like, shape (n,)
+ Gradient of the quadratic objective function.
+ A : sparse array
+ Jacobian matrix of the EQP problem.
+ b : array_like, shape (m,)
+ Right-hand side of the constraint equation.
+
+ Returns
+ -------
+ x : array_like, shape (n,)
+ Solution of the KKT problem.
+ lagrange_multipliers : ndarray, shape (m,)
+ Lagrange multipliers of the KKT problem.
+ """
+ n, = np.shape(c) # Number of parameters
+ m, = np.shape(b) # Number of constraints
+
+ # Karush-Kuhn-Tucker matrix of coefficients.
+ # Defined as in Nocedal/Wright "Numerical
+ # Optimization" p.452 in Eq. (16.4).
+ kkt_matrix = block_array([[H, A.T], [A, None]], format="csc")
+ # Vector of coefficients.
+ kkt_vec = np.hstack([-c, -b])
+
+ # TODO: Use a symmetric indefinite factorization
+ # to solve the system twice as fast (because
+ # of the symmetry).
+ lu = linalg.splu(kkt_matrix)
+ kkt_sol = lu.solve(kkt_vec)
+ x = kkt_sol[:n]
+ lagrange_multipliers = -kkt_sol[n:n+m]
+
+ return x, lagrange_multipliers
+
+
+def sphere_intersections(z, d, trust_radius,
+ entire_line=False):
+ """Find the intersection between segment (or line) and spherical constraints.
+
+ Find the intersection between the segment (or line) defined by the
+ parametric equation ``x(t) = z + t*d`` and the ball
+ ``||x|| <= trust_radius``.
+
+ Parameters
+ ----------
+ z : array_like, shape (n,)
+ Initial point.
+ d : array_like, shape (n,)
+ Direction.
+ trust_radius : float
+ Ball radius.
+ entire_line : bool, optional
+ When ``True``, the function returns the intersection between the line
+ ``x(t) = z + t*d`` (``t`` can assume any value) and the ball
+ ``||x|| <= trust_radius``. When ``False``, the function returns the intersection
+ between the segment ``x(t) = z + t*d``, ``0 <= t <= 1``, and the ball.
+
+ Returns
+ -------
+ ta, tb : float
+ The line/segment ``x(t) = z + t*d`` is inside the ball for
+ for ``ta <= t <= tb``.
+ intersect : bool
+ When ``True``, there is a intersection between the line/segment
+ and the sphere. On the other hand, when ``False``, there is no
+ intersection.
+ """
+ # Special case when d=0
+ if norm(d) == 0:
+ return 0, 0, False
+ # Check for inf trust_radius
+ if np.isinf(trust_radius):
+ if entire_line:
+ ta = -np.inf
+ tb = np.inf
+ else:
+ ta = 0
+ tb = 1
+ intersect = True
+ return ta, tb, intersect
+
+ a = np.dot(d, d)
+ b = 2 * np.dot(z, d)
+ c = np.dot(z, z) - trust_radius**2
+ discriminant = b*b - 4*a*c
+ if discriminant < 0:
+ intersect = False
+ return 0, 0, intersect
+ sqrt_discriminant = np.sqrt(discriminant)
+
+ # The following calculation is mathematically
+ # equivalent to:
+ # ta = (-b - sqrt_discriminant) / (2*a)
+ # tb = (-b + sqrt_discriminant) / (2*a)
+ # but produce smaller round off errors.
+ # Look at Matrix Computation p.97
+ # for a better justification.
+ aux = b + copysign(sqrt_discriminant, b)
+ ta = -aux / (2*a)
+ tb = -2*c / aux
+ ta, tb = sorted([ta, tb])
+
+ if entire_line:
+ intersect = True
+ else:
+ # Checks to see if intersection happens
+ # within vectors length.
+ if tb < 0 or ta > 1:
+ intersect = False
+ ta = 0
+ tb = 0
+ else:
+ intersect = True
+ # Restrict intersection interval
+ # between 0 and 1.
+ ta = max(0, ta)
+ tb = min(1, tb)
+
+ return ta, tb, intersect
+
+
+def box_intersections(z, d, lb, ub,
+ entire_line=False):
+ """Find the intersection between segment (or line) and box constraints.
+
+ Find the intersection between the segment (or line) defined by the
+ parametric equation ``x(t) = z + t*d`` and the rectangular box
+ ``lb <= x <= ub``.
+
+ Parameters
+ ----------
+ z : array_like, shape (n,)
+ Initial point.
+ d : array_like, shape (n,)
+ Direction.
+ lb : array_like, shape (n,)
+ Lower bounds to each one of the components of ``x``. Used
+ to delimit the rectangular box.
+ ub : array_like, shape (n, )
+ Upper bounds to each one of the components of ``x``. Used
+ to delimit the rectangular box.
+ entire_line : bool, optional
+ When ``True``, the function returns the intersection between the line
+ ``x(t) = z + t*d`` (``t`` can assume any value) and the rectangular
+ box. When ``False``, the function returns the intersection between the segment
+ ``x(t) = z + t*d``, ``0 <= t <= 1``, and the rectangular box.
+
+ Returns
+ -------
+ ta, tb : float
+ The line/segment ``x(t) = z + t*d`` is inside the box for
+ for ``ta <= t <= tb``.
+ intersect : bool
+ When ``True``, there is a intersection between the line (or segment)
+ and the rectangular box. On the other hand, when ``False``, there is no
+ intersection.
+ """
+ # Make sure it is a numpy array
+ z = np.asarray(z)
+ d = np.asarray(d)
+ lb = np.asarray(lb)
+ ub = np.asarray(ub)
+ # Special case when d=0
+ if norm(d) == 0:
+ return 0, 0, False
+
+ # Get values for which d==0
+ zero_d = (d == 0)
+ # If the boundaries are not satisfied for some coordinate
+ # for which "d" is zero, there is no box-line intersection.
+ if (z[zero_d] < lb[zero_d]).any() or (z[zero_d] > ub[zero_d]).any():
+ intersect = False
+ return 0, 0, intersect
+ # Remove values for which d is zero
+ not_zero_d = np.logical_not(zero_d)
+ z = z[not_zero_d]
+ d = d[not_zero_d]
+ lb = lb[not_zero_d]
+ ub = ub[not_zero_d]
+
+ # Find a series of intervals (t_lb[i], t_ub[i]).
+ t_lb = (lb-z) / d
+ t_ub = (ub-z) / d
+ # Get the intersection of all those intervals.
+ ta = max(np.minimum(t_lb, t_ub))
+ tb = min(np.maximum(t_lb, t_ub))
+
+ # Check if intersection is feasible
+ if ta <= tb:
+ intersect = True
+ else:
+ intersect = False
+ # Checks to see if intersection happens within vectors length.
+ if not entire_line:
+ if tb < 0 or ta > 1:
+ intersect = False
+ ta = 0
+ tb = 0
+ else:
+ # Restrict intersection interval between 0 and 1.
+ ta = max(0, ta)
+ tb = min(1, tb)
+
+ return ta, tb, intersect
+
+
+def box_sphere_intersections(z, d, lb, ub, trust_radius,
+ entire_line=False,
+ extra_info=False):
+ """Find the intersection between segment (or line) and box/sphere constraints.
+
+ Find the intersection between the segment (or line) defined by the
+ parametric equation ``x(t) = z + t*d``, the rectangular box
+ ``lb <= x <= ub`` and the ball ``||x|| <= trust_radius``.
+
+ Parameters
+ ----------
+ z : array_like, shape (n,)
+ Initial point.
+ d : array_like, shape (n,)
+ Direction.
+ lb : array_like, shape (n,)
+ Lower bounds to each one of the components of ``x``. Used
+ to delimit the rectangular box.
+ ub : array_like, shape (n, )
+ Upper bounds to each one of the components of ``x``. Used
+ to delimit the rectangular box.
+ trust_radius : float
+ Ball radius.
+ entire_line : bool, optional
+ When ``True``, the function returns the intersection between the line
+ ``x(t) = z + t*d`` (``t`` can assume any value) and the constraints.
+ When ``False``, the function returns the intersection between the segment
+ ``x(t) = z + t*d``, ``0 <= t <= 1`` and the constraints.
+ extra_info : bool, optional
+ When ``True``, the function returns ``intersect_sphere`` and ``intersect_box``.
+
+ Returns
+ -------
+ ta, tb : float
+ The line/segment ``x(t) = z + t*d`` is inside the rectangular box and
+ inside the ball for ``ta <= t <= tb``.
+ intersect : bool
+ When ``True``, there is a intersection between the line (or segment)
+ and both constraints. On the other hand, when ``False``, there is no
+ intersection.
+ sphere_info : dict, optional
+ Dictionary ``{ta, tb, intersect}`` containing the interval ``[ta, tb]``
+ for which the line intercepts the ball. And a boolean value indicating
+ whether the sphere is intersected by the line.
+ box_info : dict, optional
+ Dictionary ``{ta, tb, intersect}`` containing the interval ``[ta, tb]``
+ for which the line intercepts the box. And a boolean value indicating
+ whether the box is intersected by the line.
+ """
+ ta_b, tb_b, intersect_b = box_intersections(z, d, lb, ub,
+ entire_line)
+ ta_s, tb_s, intersect_s = sphere_intersections(z, d,
+ trust_radius,
+ entire_line)
+ ta = np.maximum(ta_b, ta_s)
+ tb = np.minimum(tb_b, tb_s)
+ if intersect_b and intersect_s and ta <= tb:
+ intersect = True
+ else:
+ intersect = False
+
+ if extra_info:
+ sphere_info = {'ta': ta_s, 'tb': tb_s, 'intersect': intersect_s}
+ box_info = {'ta': ta_b, 'tb': tb_b, 'intersect': intersect_b}
+ return ta, tb, intersect, sphere_info, box_info
+ else:
+ return ta, tb, intersect
+
+
+def inside_box_boundaries(x, lb, ub):
+ """Check if lb <= x <= ub."""
+ return (lb <= x).all() and (x <= ub).all()
+
+
+def reinforce_box_boundaries(x, lb, ub):
+ """Return clipped value of x"""
+ return np.minimum(np.maximum(x, lb), ub)
+
+
+def modified_dogleg(A, Y, b, trust_radius, lb, ub):
+ """Approximately minimize ``1/2*|| A x + b ||^2`` inside trust-region.
+
+ Approximately solve the problem of minimizing ``1/2*|| A x + b ||^2``
+ subject to ``||x|| < Delta`` and ``lb <= x <= ub`` using a modification
+ of the classical dogleg approach.
+
+ Parameters
+ ----------
+ A : LinearOperator (or sparse array or ndarray), shape (m, n)
+ Matrix ``A`` in the minimization problem. It should have
+ dimension ``(m, n)`` such that ``m < n``.
+ Y : LinearOperator (or sparse array or ndarray), shape (n, m)
+ LinearOperator that apply the projection matrix
+ ``Q = A.T inv(A A.T)`` to the vector. The obtained vector
+ ``y = Q x`` being the minimum norm solution of ``A y = x``.
+ b : array_like, shape (m,)
+ Vector ``b``in the minimization problem.
+ trust_radius: float
+ Trust radius to be considered. Delimits a sphere boundary
+ to the problem.
+ lb : array_like, shape (n,)
+ Lower bounds to each one of the components of ``x``.
+ It is expected that ``lb <= 0``, otherwise the algorithm
+ may fail. If ``lb[i] = -Inf``, the lower
+ bound for the ith component is just ignored.
+ ub : array_like, shape (n, )
+ Upper bounds to each one of the components of ``x``.
+ It is expected that ``ub >= 0``, otherwise the algorithm
+ may fail. If ``ub[i] = Inf``, the upper bound for the ith
+ component is just ignored.
+
+ Returns
+ -------
+ x : array_like, shape (n,)
+ Solution to the problem.
+
+ Notes
+ -----
+ Based on implementations described in pp. 885-886 from [1]_.
+
+ References
+ ----------
+ .. [1] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal.
+ "An interior point algorithm for large-scale nonlinear
+ programming." SIAM Journal on Optimization 9.4 (1999): 877-900.
+ """
+ # Compute minimum norm minimizer of 1/2*|| A x + b ||^2.
+ newton_point = -Y.dot(b)
+ # Check for interior point
+ if inside_box_boundaries(newton_point, lb, ub) \
+ and norm(newton_point) <= trust_radius:
+ x = newton_point
+ return x
+
+ # Compute gradient vector ``g = A.T b``
+ g = A.T.dot(b)
+ # Compute Cauchy point
+ # `cauchy_point = g.T g / (g.T A.T A g)``.
+ A_g = A.dot(g)
+ cauchy_point = -np.dot(g, g) / np.dot(A_g, A_g) * g
+ # Origin
+ origin_point = np.zeros_like(cauchy_point)
+
+ # Check the segment between cauchy_point and newton_point
+ # for a possible solution.
+ z = cauchy_point
+ p = newton_point - cauchy_point
+ _, alpha, intersect = box_sphere_intersections(z, p, lb, ub,
+ trust_radius)
+ if intersect:
+ x1 = z + alpha*p
+ else:
+ # Check the segment between the origin and cauchy_point
+ # for a possible solution.
+ z = origin_point
+ p = cauchy_point
+ _, alpha, _ = box_sphere_intersections(z, p, lb, ub,
+ trust_radius)
+ x1 = z + alpha*p
+
+ # Check the segment between origin and newton_point
+ # for a possible solution.
+ z = origin_point
+ p = newton_point
+ _, alpha, _ = box_sphere_intersections(z, p, lb, ub,
+ trust_radius)
+ x2 = z + alpha*p
+
+ # Return the best solution among x1 and x2.
+ if norm(A.dot(x1) + b) < norm(A.dot(x2) + b):
+ return x1
+ else:
+ return x2
+
+
+def projected_cg(H, c, Z, Y, b, trust_radius=np.inf,
+ lb=None, ub=None, tol=None,
+ max_iter=None, max_infeasible_iter=None,
+ return_all=False):
+ """Solve EQP problem with projected CG method.
+
+ Solve equality-constrained quadratic programming problem
+ ``min 1/2 x.T H x + x.t c`` subject to ``A x + b = 0`` and,
+ possibly, to trust region constraints ``||x|| < trust_radius``
+ and box constraints ``lb <= x <= ub``.
+
+ Parameters
+ ----------
+ H : LinearOperator (or sparse array or ndarray), shape (n, n)
+ Operator for computing ``H v``.
+ c : array_like, shape (n,)
+ Gradient of the quadratic objective function.
+ Z : LinearOperator (or sparse array or ndarray), shape (n, n)
+ Operator for projecting ``x`` into the null space of A.
+ Y : LinearOperator, sparse array, ndarray, shape (n, m)
+ Operator that, for a given a vector ``b``, compute smallest
+ norm solution of ``A x + b = 0``.
+ b : array_like, shape (m,)
+ Right-hand side of the constraint equation.
+ trust_radius : float, optional
+ Trust radius to be considered. By default, uses ``trust_radius=inf``,
+ which means no trust radius at all.
+ lb : array_like, shape (n,), optional
+ Lower bounds to each one of the components of ``x``.
+ If ``lb[i] = -Inf`` the lower bound for the i-th
+ component is just ignored (default).
+ ub : array_like, shape (n, ), optional
+ Upper bounds to each one of the components of ``x``.
+ If ``ub[i] = Inf`` the upper bound for the i-th
+ component is just ignored (default).
+ tol : float, optional
+ Tolerance used to interrupt the algorithm.
+ max_iter : int, optional
+ Maximum algorithm iterations. Where ``max_inter <= n-m``.
+ By default, uses ``max_iter = n-m``.
+ max_infeasible_iter : int, optional
+ Maximum infeasible (regarding box constraints) iterations the
+ algorithm is allowed to take.
+ By default, uses ``max_infeasible_iter = n-m``.
+ return_all : bool, optional
+ When ``true``, return the list of all vectors through the iterations.
+
+ Returns
+ -------
+ x : array_like, shape (n,)
+ Solution of the EQP problem.
+ info : Dict
+ Dictionary containing the following:
+
+ - niter : Number of iterations.
+ - stop_cond : Reason for algorithm termination:
+ 1. Iteration limit was reached;
+ 2. Reached the trust-region boundary;
+ 3. Negative curvature detected;
+ 4. Tolerance was satisfied.
+ - allvecs : List containing all intermediary vectors (optional).
+ - hits_boundary : True if the proposed step is on the boundary
+ of the trust region.
+
+ Notes
+ -----
+ Implementation of Algorithm 6.2 on [1]_.
+
+ In the absence of spherical and box constraints, for sufficient
+ iterations, the method returns a truly optimal result.
+ In the presence of those constraints, the value returned is only
+ a inexpensive approximation of the optimal value.
+
+ References
+ ----------
+ .. [1] Gould, Nicholas IM, Mary E. Hribar, and Jorge Nocedal.
+ "On the solution of equality constrained quadratic
+ programming problems arising in optimization."
+ SIAM Journal on Scientific Computing 23.4 (2001): 1376-1395.
+ """
+ CLOSE_TO_ZERO = 1e-25
+
+ n, = np.shape(c) # Number of parameters
+ m, = np.shape(b) # Number of constraints
+
+ # Initial Values
+ x = Y.dot(-b)
+ r = Z.dot(H.dot(x) + c)
+ g = Z.dot(r)
+ p = -g
+
+ # Store ``x`` value
+ if return_all:
+ allvecs = [x]
+ # Values for the first iteration
+ H_p = H.dot(p)
+ rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389)
+
+ # If x > trust-region the problem does not have a solution.
+ tr_distance = trust_radius - norm(x)
+ if tr_distance < 0:
+ raise ValueError("Trust region problem does not have a solution.")
+ # If x == trust_radius, then x is the solution
+ # to the optimization problem, since x is the
+ # minimum norm solution to Ax=b.
+ elif tr_distance < CLOSE_TO_ZERO:
+ info = {'niter': 0, 'stop_cond': 2, 'hits_boundary': True}
+ if return_all:
+ allvecs.append(x)
+ info['allvecs'] = allvecs
+ return x, info
+
+ # Set default tolerance
+ if tol is None:
+ tol = max(min(0.01 * np.sqrt(rt_g), 0.1 * rt_g), CLOSE_TO_ZERO)
+ # Set default lower and upper bounds
+ if lb is None:
+ lb = np.full(n, -np.inf)
+ if ub is None:
+ ub = np.full(n, np.inf)
+ # Set maximum iterations
+ if max_iter is None:
+ max_iter = n-m
+ max_iter = min(max_iter, n-m)
+ # Set maximum infeasible iterations
+ if max_infeasible_iter is None:
+ max_infeasible_iter = n-m
+
+ hits_boundary = False
+ stop_cond = 1
+ counter = 0
+ last_feasible_x = np.zeros_like(x)
+ k = 0
+ for i in range(max_iter):
+ # Stop criteria - Tolerance : r.T g < tol
+ if rt_g < tol:
+ stop_cond = 4
+ break
+ k += 1
+ # Compute curvature
+ pt_H_p = H_p.dot(p)
+ # Stop criteria - Negative curvature
+ if pt_H_p <= 0:
+ if np.isinf(trust_radius):
+ raise ValueError("Negative curvature not allowed "
+ "for unrestricted problems.")
+ else:
+ # Find intersection with constraints
+ _, alpha, intersect = box_sphere_intersections(
+ x, p, lb, ub, trust_radius, entire_line=True)
+ # Update solution
+ if intersect:
+ x = x + alpha*p
+ # Reinforce variables are inside box constraints.
+ # This is only necessary because of roundoff errors.
+ x = reinforce_box_boundaries(x, lb, ub)
+ # Attribute information
+ stop_cond = 3
+ hits_boundary = True
+ break
+
+ # Get next step
+ alpha = rt_g / pt_H_p
+ x_next = x + alpha*p
+
+ # Stop criteria - Hits boundary
+ if np.linalg.norm(x_next) >= trust_radius:
+ # Find intersection with box constraints
+ _, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub,
+ trust_radius)
+ # Update solution
+ if intersect:
+ x = x + theta*alpha*p
+ # Reinforce variables are inside box constraints.
+ # This is only necessary because of roundoff errors.
+ x = reinforce_box_boundaries(x, lb, ub)
+ # Attribute information
+ stop_cond = 2
+ hits_boundary = True
+ break
+
+ # Check if ``x`` is inside the box and start counter if it is not.
+ if inside_box_boundaries(x_next, lb, ub):
+ counter = 0
+ else:
+ counter += 1
+ # Whenever outside box constraints keep looking for intersections.
+ if counter > 0:
+ _, theta, intersect = box_sphere_intersections(x, alpha*p, lb, ub,
+ trust_radius)
+ if intersect:
+ last_feasible_x = x + theta*alpha*p
+ # Reinforce variables are inside box constraints.
+ # This is only necessary because of roundoff errors.
+ last_feasible_x = reinforce_box_boundaries(last_feasible_x,
+ lb, ub)
+ counter = 0
+ # Stop after too many infeasible (regarding box constraints) iteration.
+ if counter > max_infeasible_iter:
+ break
+ # Store ``x_next`` value
+ if return_all:
+ allvecs.append(x_next)
+
+ # Update residual
+ r_next = r + alpha*H_p
+ # Project residual g+ = Z r+
+ g_next = Z.dot(r_next)
+ # Compute conjugate direction step d
+ rt_g_next = norm(g_next)**2 # g.T g = r.T g (ref [1]_ p.1389)
+ beta = rt_g_next / rt_g
+ p = - g_next + beta*p
+ # Prepare for next iteration
+ x = x_next
+ g = g_next
+ r = g_next
+ rt_g = norm(g)**2 # g.T g = r.T Z g = r.T g (ref [1]_ p.1389)
+ H_p = H.dot(p)
+
+ if not inside_box_boundaries(x, lb, ub):
+ x = last_feasible_x
+ hits_boundary = True
+ info = {'niter': k, 'stop_cond': stop_cond,
+ 'hits_boundary': hits_boundary}
+ if return_all:
+ info['allvecs'] = allvecs
+ return x, info
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/report.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/report.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7f997d663cd5ce6265e77f940622b6105362bf7
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/report.py
@@ -0,0 +1,49 @@
+"""Progress report printers."""
+
+class ReportBase:
+ COLUMN_NAMES: list[str] = NotImplemented
+ COLUMN_WIDTHS: list[int] = NotImplemented
+ ITERATION_FORMATS: list[str] = NotImplemented
+
+ @classmethod
+ def print_header(cls):
+ fmt = ("|"
+ + "|".join([f"{{:^{x}}}" for x in cls.COLUMN_WIDTHS])
+ + "|")
+ separators = ['-' * x for x in cls.COLUMN_WIDTHS]
+ print(fmt.format(*cls.COLUMN_NAMES))
+ print(fmt.format(*separators))
+
+ @classmethod
+ def print_iteration(cls, *args):
+ iteration_format = [f"{{:{x}}}" for x in cls.ITERATION_FORMATS]
+ fmt = "|" + "|".join(iteration_format) + "|"
+ print(fmt.format(*args))
+
+ @classmethod
+ def print_footer(cls):
+ print()
+
+
+class BasicReport(ReportBase):
+ COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius",
+ "opt", "c viol"]
+ COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10]
+ ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e",
+ "^10.2e", "^10.2e", "^10.2e"]
+
+
+class SQPReport(ReportBase):
+ COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius",
+ "opt", "c viol", "penalty", "CG stop"]
+ COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 7]
+ ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e",
+ "^10.2e", "^10.2e", "^7"]
+
+
+class IPReport(ReportBase):
+ COLUMN_NAMES = ["niter", "f evals", "CG iter", "obj func", "tr radius",
+ "opt", "c viol", "penalty", "barrier param", "CG stop"]
+ COLUMN_WIDTHS = [7, 7, 7, 13, 10, 10, 10, 10, 13, 7]
+ ITERATION_FORMATS = ["^7", "^7", "^7", "^+13.4e", "^10.2e", "^10.2e",
+ "^10.2e", "^10.2e", "^13.2e", "^7"]
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_canonical_constraint.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_canonical_constraint.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_canonical_constraint.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_nested_minimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_nested_minimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_nested_minimize.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_projections.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_projections.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_projections.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_qp_subproblem.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_qp_subproblem.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_qp_subproblem.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_report.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_report.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/._test_report.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py
new file mode 100644
index 0000000000000000000000000000000000000000..452b327d02da3b3bd3fab9592bdef4d56d6aff57
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_canonical_constraint.py
@@ -0,0 +1,296 @@
+import numpy as np
+from numpy.testing import assert_array_equal, assert_equal
+from scipy.optimize._constraints import (NonlinearConstraint, Bounds,
+ PreparedConstraint)
+from scipy.optimize._trustregion_constr.canonical_constraint \
+ import CanonicalConstraint, initial_constraints_as_canonical
+
+
+def create_quadratic_function(n, m, rng):
+ a = rng.rand(m)
+ A = rng.rand(m, n)
+ H = rng.rand(m, n, n)
+ HT = np.transpose(H, (1, 2, 0))
+
+ def fun(x):
+ return a + A.dot(x) + 0.5 * H.dot(x).dot(x)
+
+ def jac(x):
+ return A + H.dot(x)
+
+ def hess(x, v):
+ return HT.dot(v)
+
+ return fun, jac, hess
+
+
+def test_bounds_cases():
+ # Test 1: no constraints.
+ user_constraint = Bounds(-np.inf, np.inf)
+ x0 = np.array([-1, 2])
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
+
+ assert_equal(c.n_eq, 0)
+ assert_equal(c.n_ineq, 0)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [])
+ assert_array_equal(c_ineq, [])
+
+ J_eq, J_ineq = c.jac(x0)
+ assert_array_equal(J_eq, np.empty((0, 2)))
+ assert_array_equal(J_ineq, np.empty((0, 2)))
+
+ assert_array_equal(c.keep_feasible, [])
+
+ # Test 2: infinite lower bound.
+ user_constraint = Bounds(-np.inf, [0, np.inf, 1], [False, True, True])
+ x0 = np.array([-1, -2, -3], dtype=float)
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
+
+ assert_equal(c.n_eq, 0)
+ assert_equal(c.n_ineq, 2)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [])
+ assert_array_equal(c_ineq, [-1, -4])
+
+ J_eq, J_ineq = c.jac(x0)
+ assert_array_equal(J_eq, np.empty((0, 3)))
+ assert_array_equal(J_ineq, np.array([[1, 0, 0], [0, 0, 1]]))
+
+ assert_array_equal(c.keep_feasible, [False, True])
+
+ # Test 3: infinite upper bound.
+ user_constraint = Bounds([0, 1, -np.inf], np.inf, [True, False, True])
+ x0 = np.array([1, 2, 3], dtype=float)
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
+
+ assert_equal(c.n_eq, 0)
+ assert_equal(c.n_ineq, 2)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [])
+ assert_array_equal(c_ineq, [-1, -1])
+
+ J_eq, J_ineq = c.jac(x0)
+ assert_array_equal(J_eq, np.empty((0, 3)))
+ assert_array_equal(J_ineq, np.array([[-1, 0, 0], [0, -1, 0]]))
+
+ assert_array_equal(c.keep_feasible, [True, False])
+
+ # Test 4: interval constraint.
+ user_constraint = Bounds([-1, -np.inf, 2, 3], [1, np.inf, 10, 3],
+ [False, True, True, True])
+ x0 = np.array([0, 10, 8, 5])
+ prepared_constraint = PreparedConstraint(user_constraint, x0, False)
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
+
+ assert_equal(c.n_eq, 1)
+ assert_equal(c.n_ineq, 4)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [2])
+ assert_array_equal(c_ineq, [-1, -2, -1, -6])
+
+ J_eq, J_ineq = c.jac(x0)
+ assert_array_equal(J_eq, [[0, 0, 0, 1]])
+ assert_array_equal(J_ineq, [[1, 0, 0, 0],
+ [0, 0, 1, 0],
+ [-1, 0, 0, 0],
+ [0, 0, -1, 0]])
+
+ assert_array_equal(c.keep_feasible, [False, True, False, True])
+
+
+def test_nonlinear_constraint():
+ n = 3
+ m = 5
+ rng = np.random.RandomState(0)
+ x0 = rng.rand(n)
+
+ fun, jac, hess = create_quadratic_function(n, m, rng)
+ f = fun(x0)
+ J = jac(x0)
+
+ lb = [-10, 3, -np.inf, -np.inf, -5]
+ ub = [10, 3, np.inf, 3, np.inf]
+ user_constraint = NonlinearConstraint(
+ fun, lb, ub, jac, hess, [True, False, False, True, False])
+
+ for sparse_jacobian in [False, True]:
+ prepared_constraint = PreparedConstraint(user_constraint, x0,
+ sparse_jacobian)
+ c = CanonicalConstraint.from_PreparedConstraint(prepared_constraint)
+
+ assert_array_equal(c.n_eq, 1)
+ assert_array_equal(c.n_ineq, 4)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [f[1] - lb[1]])
+ assert_array_equal(c_ineq, [f[3] - ub[3], lb[4] - f[4],
+ f[0] - ub[0], lb[0] - f[0]])
+
+ J_eq, J_ineq = c.jac(x0)
+ if sparse_jacobian:
+ J_eq = J_eq.toarray()
+ J_ineq = J_ineq.toarray()
+
+ assert_array_equal(J_eq, J[1, None])
+ assert_array_equal(J_ineq, np.vstack((J[3], -J[4], J[0], -J[0])))
+
+ v_eq = rng.rand(c.n_eq)
+ v_ineq = rng.rand(c.n_ineq)
+ v = np.zeros(m)
+ v[1] = v_eq[0]
+ v[3] = v_ineq[0]
+ v[4] = -v_ineq[1]
+ v[0] = v_ineq[2] - v_ineq[3]
+ assert_array_equal(c.hess(x0, v_eq, v_ineq), hess(x0, v))
+
+ assert_array_equal(c.keep_feasible, [True, False, True, True])
+
+
+def test_concatenation():
+ rng = np.random.RandomState(0)
+ n = 4
+ x0 = rng.rand(n)
+
+ f1 = x0
+ J1 = np.eye(n)
+ lb1 = [-1, -np.inf, -2, 3]
+ ub1 = [1, np.inf, np.inf, 3]
+ bounds = Bounds(lb1, ub1, [False, False, True, False])
+
+ fun, jac, hess = create_quadratic_function(n, 5, rng)
+ f2 = fun(x0)
+ J2 = jac(x0)
+ lb2 = [-10, 3, -np.inf, -np.inf, -5]
+ ub2 = [10, 3, np.inf, 5, np.inf]
+ nonlinear = NonlinearConstraint(
+ fun, lb2, ub2, jac, hess, [True, False, False, True, False])
+
+ for sparse_jacobian in [False, True]:
+ bounds_prepared = PreparedConstraint(bounds, x0, sparse_jacobian)
+ nonlinear_prepared = PreparedConstraint(nonlinear, x0, sparse_jacobian)
+
+ c1 = CanonicalConstraint.from_PreparedConstraint(bounds_prepared)
+ c2 = CanonicalConstraint.from_PreparedConstraint(nonlinear_prepared)
+ c = CanonicalConstraint.concatenate([c1, c2], sparse_jacobian)
+
+ assert_equal(c.n_eq, 2)
+ assert_equal(c.n_ineq, 7)
+
+ c_eq, c_ineq = c.fun(x0)
+ assert_array_equal(c_eq, [f1[3] - lb1[3], f2[1] - lb2[1]])
+ assert_array_equal(c_ineq, [lb1[2] - f1[2], f1[0] - ub1[0],
+ lb1[0] - f1[0], f2[3] - ub2[3],
+ lb2[4] - f2[4], f2[0] - ub2[0],
+ lb2[0] - f2[0]])
+
+ J_eq, J_ineq = c.jac(x0)
+ if sparse_jacobian:
+ J_eq = J_eq.toarray()
+ J_ineq = J_ineq.toarray()
+
+ assert_array_equal(J_eq, np.vstack((J1[3], J2[1])))
+ assert_array_equal(J_ineq, np.vstack((-J1[2], J1[0], -J1[0], J2[3],
+ -J2[4], J2[0], -J2[0])))
+
+ v_eq = rng.rand(c.n_eq)
+ v_ineq = rng.rand(c.n_ineq)
+ v = np.zeros(5)
+ v[1] = v_eq[1]
+ v[3] = v_ineq[3]
+ v[4] = -v_ineq[4]
+ v[0] = v_ineq[5] - v_ineq[6]
+ H = c.hess(x0, v_eq, v_ineq).dot(np.eye(n))
+ assert_array_equal(H, hess(x0, v))
+
+ assert_array_equal(c.keep_feasible,
+ [True, False, False, True, False, True, True])
+
+
+def test_empty():
+ x = np.array([1, 2, 3])
+ c = CanonicalConstraint.empty(3)
+ assert_equal(c.n_eq, 0)
+ assert_equal(c.n_ineq, 0)
+
+ c_eq, c_ineq = c.fun(x)
+ assert_array_equal(c_eq, [])
+ assert_array_equal(c_ineq, [])
+
+ J_eq, J_ineq = c.jac(x)
+ assert_array_equal(J_eq, np.empty((0, 3)))
+ assert_array_equal(J_ineq, np.empty((0, 3)))
+
+ H = c.hess(x, None, None).toarray()
+ assert_array_equal(H, np.zeros((3, 3)))
+
+
+def test_initial_constraints_as_canonical():
+ # rng is only used to generate the coefficients of the quadratic
+ # function that is used by the nonlinear constraint.
+ rng = np.random.RandomState(0)
+
+ x0 = np.array([0.5, 0.4, 0.3, 0.2])
+ n = len(x0)
+
+ lb1 = [-1, -np.inf, -2, 3]
+ ub1 = [1, np.inf, np.inf, 3]
+ bounds = Bounds(lb1, ub1, [False, False, True, False])
+
+ fun, jac, hess = create_quadratic_function(n, 5, rng)
+ lb2 = [-10, 3, -np.inf, -np.inf, -5]
+ ub2 = [10, 3, np.inf, 5, np.inf]
+ nonlinear = NonlinearConstraint(
+ fun, lb2, ub2, jac, hess, [True, False, False, True, False])
+
+ for sparse_jacobian in [False, True]:
+ bounds_prepared = PreparedConstraint(bounds, x0, sparse_jacobian)
+ nonlinear_prepared = PreparedConstraint(nonlinear, x0, sparse_jacobian)
+
+ f1 = bounds_prepared.fun.f
+ J1 = bounds_prepared.fun.J
+ f2 = nonlinear_prepared.fun.f
+ J2 = nonlinear_prepared.fun.J
+
+ c_eq, c_ineq, J_eq, J_ineq = initial_constraints_as_canonical(
+ n, [bounds_prepared, nonlinear_prepared], sparse_jacobian)
+
+ assert_array_equal(c_eq, [f1[3] - lb1[3], f2[1] - lb2[1]])
+ assert_array_equal(c_ineq, [lb1[2] - f1[2], f1[0] - ub1[0],
+ lb1[0] - f1[0], f2[3] - ub2[3],
+ lb2[4] - f2[4], f2[0] - ub2[0],
+ lb2[0] - f2[0]])
+
+ if sparse_jacobian:
+ J1 = J1.toarray()
+ J2 = J2.toarray()
+ J_eq = J_eq.toarray()
+ J_ineq = J_ineq.toarray()
+
+ assert_array_equal(J_eq, np.vstack((J1[3], J2[1])))
+ assert_array_equal(J_ineq, np.vstack((-J1[2], J1[0], -J1[0], J2[3],
+ -J2[4], J2[0], -J2[0])))
+
+
+def test_initial_constraints_as_canonical_empty():
+ n = 3
+ for sparse_jacobian in [False, True]:
+ c_eq, c_ineq, J_eq, J_ineq = initial_constraints_as_canonical(
+ n, [], sparse_jacobian)
+
+ assert_array_equal(c_eq, [])
+ assert_array_equal(c_ineq, [])
+
+ if sparse_jacobian:
+ J_eq = J_eq.toarray()
+ J_ineq = J_ineq.toarray()
+
+ assert_array_equal(J_eq, np.empty((0, n)))
+ assert_array_equal(J_ineq, np.empty((0, n)))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..f9aa57058c6523d4106b26840ef447431d615cd6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_nested_minimize.py
@@ -0,0 +1,39 @@
+import pytest
+import numpy as np
+from scipy.optimize import minimize, NonlinearConstraint, rosen, rosen_der
+
+
+# Ignore this warning about inefficient use of Hessians
+# The bug only shows up with the default HUS
+@pytest.mark.filterwarnings(
+ "ignore:delta_grad == 0.0. Check if the approximated function is linear."
+)
+def test_gh21193():
+ # Test that nested minimization does not share Hessian objects
+ def identity(x):
+ return x[0]
+ def identity_jac(x):
+ a = np.zeros(len(x))
+ a[0] = 1
+ return a
+ constraint1 = NonlinearConstraint(identity, 0, 0, identity_jac)
+ constraint2 = NonlinearConstraint(identity, 0, 0, identity_jac)
+
+ # The default HUS for each should be distinct
+ assert constraint1.hess is not constraint2.hess
+
+ _ = minimize(
+ lambda x: minimize(
+ rosen,
+ x[1:],
+ jac=rosen_der,
+ constraints=constraint1,
+ method="trust-constr",
+ options={'maxiter': 2},
+ ).fun,
+ [1, 0, 0],
+ constraints=constraint2,
+ method="trust-constr",
+ options={'maxiter': 2},
+ )
+ # This test doesn't check that the output is correct, just that it doesn't crash
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py
new file mode 100644
index 0000000000000000000000000000000000000000..f8dd1f61ee0290212ff62d0ba1aca2bd87daf514
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_projections.py
@@ -0,0 +1,214 @@
+import numpy as np
+import scipy.linalg
+from scipy.sparse import csc_array
+from scipy.optimize._trustregion_constr.projections \
+ import projections, orthogonality
+from numpy.testing import (TestCase, assert_array_almost_equal,
+ assert_equal, assert_allclose)
+
+try:
+ from sksparse.cholmod import cholesky_AAt # noqa: F401
+ sksparse_available = True
+ available_sparse_methods = ("NormalEquation", "AugmentedSystem")
+except ImportError:
+ sksparse_available = False
+ available_sparse_methods = ("AugmentedSystem",)
+available_dense_methods = ('QRFactorization', 'SVDFactorization')
+
+
+class TestProjections(TestCase):
+
+ def test_nullspace_and_least_squares_sparse(self):
+ A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ At_dense = A_dense.T
+ A = csc_array(A_dense)
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
+ [1, 10, 3, 0, 1, 6, 7, 8],
+ [1.12, 10, 0, 0, 100000, 6, 0.7, 8])
+
+ for method in available_sparse_methods:
+ Z, LS, _ = projections(A, method)
+ for z in test_points:
+ # Test if x is in the null_space
+ x = Z.matvec(z)
+ assert_array_almost_equal(A.dot(x), 0)
+ # Test orthogonality
+ assert_array_almost_equal(orthogonality(A, x), 0)
+ # Test if x is the least square solution
+ x = LS.matvec(z)
+ x2 = scipy.linalg.lstsq(At_dense, z)[0]
+ assert_array_almost_equal(x, x2)
+
+ def test_iterative_refinements_sparse(self):
+ A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ A = csc_array(A_dense)
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
+ [1, 10, 3, 0, 1, 6, 7, 8],
+ [1.12, 10, 0, 0, 100000, 6, 0.7, 8],
+ [1, 0, 0, 0, 0, 1, 2, 3+1e-10])
+
+ for method in available_sparse_methods:
+ Z, LS, _ = projections(A, method, orth_tol=1e-18, max_refin=100)
+ for z in test_points:
+ # Test if x is in the null_space
+ x = Z.matvec(z)
+ atol = 1e-13 * abs(x).max()
+ assert_allclose(A.dot(x), 0, atol=atol)
+ # Test orthogonality
+ assert_allclose(orthogonality(A, x), 0, atol=1e-13)
+
+ def test_rowspace_sparse(self):
+ A_dense = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ A = csc_array(A_dense)
+ test_points = ([1, 2, 3],
+ [1, 10, 3],
+ [1.12, 10, 0])
+
+ for method in available_sparse_methods:
+ _, _, Y = projections(A, method)
+ for z in test_points:
+ # Test if x is solution of A x = z
+ x = Y.matvec(z)
+ assert_array_almost_equal(A.dot(x), z)
+ # Test if x is in the return row space of A
+ A_ext = np.vstack((A_dense, x))
+ assert_equal(np.linalg.matrix_rank(A_dense),
+ np.linalg.matrix_rank(A_ext))
+
+ def test_nullspace_and_least_squares_dense(self):
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ At = A.T
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
+ [1, 10, 3, 0, 1, 6, 7, 8],
+ [1.12, 10, 0, 0, 100000, 6, 0.7, 8])
+
+ for method in available_dense_methods:
+ Z, LS, _ = projections(A, method)
+ for z in test_points:
+ # Test if x is in the null_space
+ x = Z.matvec(z)
+ assert_array_almost_equal(A.dot(x), 0)
+ # Test orthogonality
+ assert_array_almost_equal(orthogonality(A, x), 0)
+ # Test if x is the least square solution
+ x = LS.matvec(z)
+ x2 = scipy.linalg.lstsq(At, z)[0]
+ assert_array_almost_equal(x, x2)
+
+ def test_compare_dense_and_sparse(self):
+ D = np.diag(range(1, 101))
+ A = np.hstack([D, D, D, D])
+ A_sparse = csc_array(A)
+ rng = np.random.default_rng(123)
+
+ Z, LS, Y = projections(A)
+ Z_sparse, LS_sparse, Y_sparse = projections(A_sparse)
+ for k in range(20):
+ z = rng.standard_normal(size=(400,))
+ assert_array_almost_equal(Z.dot(z), Z_sparse.dot(z))
+ assert_array_almost_equal(LS.dot(z), LS_sparse.dot(z))
+ x = rng.standard_normal(size=(100,))
+ assert_array_almost_equal(Y.dot(x), Y_sparse.dot(x))
+
+ def test_compare_dense_and_sparse2(self):
+ D1 = np.diag([-1.7, 1, 0.5])
+ D2 = np.diag([1, -0.6, -0.3])
+ D3 = np.diag([-0.3, -1.5, 2])
+ A = np.hstack([D1, D2, D3])
+ A_sparse = csc_array(A)
+ rng = np.random.default_rng(123)
+
+ Z, LS, Y = projections(A)
+ Z_sparse, LS_sparse, Y_sparse = projections(A_sparse)
+ for k in range(1):
+ z = rng.standard_normal(size=(9,))
+ assert_array_almost_equal(Z.dot(z), Z_sparse.dot(z))
+ assert_array_almost_equal(LS.dot(z), LS_sparse.dot(z))
+ x = rng.standard_normal(size=(3,))
+ assert_array_almost_equal(Y.dot(x), Y_sparse.dot(x))
+
+ def test_iterative_refinements_dense(self):
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ test_points = ([1, 2, 3, 4, 5, 6, 7, 8],
+ [1, 10, 3, 0, 1, 6, 7, 8],
+ [1, 0, 0, 0, 0, 1, 2, 3+1e-10])
+
+ for method in available_dense_methods:
+ Z, LS, _ = projections(A, method, orth_tol=1e-18, max_refin=10)
+ for z in test_points:
+ # Test if x is in the null_space
+ x = Z.matvec(z)
+ assert_allclose(A.dot(x), 0, rtol=0, atol=2.5e-14)
+ # Test orthogonality
+ assert_allclose(orthogonality(A, x), 0, rtol=0, atol=5e-16)
+
+ def test_rowspace_dense(self):
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ test_points = ([1, 2, 3],
+ [1, 10, 3],
+ [1.12, 10, 0])
+
+ for method in available_dense_methods:
+ _, _, Y = projections(A, method)
+ for z in test_points:
+ # Test if x is solution of A x = z
+ x = Y.matvec(z)
+ assert_array_almost_equal(A.dot(x), z)
+ # Test if x is in the return row space of A
+ A_ext = np.vstack((A, x))
+ assert_equal(np.linalg.matrix_rank(A),
+ np.linalg.matrix_rank(A_ext))
+
+
+class TestOrthogonality(TestCase):
+
+ def test_dense_matrix(self):
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ test_vectors = ([-1.98931144, -1.56363389,
+ -0.84115584, 2.2864762,
+ 5.599141, 0.09286976,
+ 1.37040802, -0.28145812],
+ [697.92794044, -4091.65114008,
+ -3327.42316335, 836.86906951,
+ 99434.98929065, -1285.37653682,
+ -4109.21503806, 2935.29289083])
+ test_expected_orth = (0, 0)
+
+ for i in range(len(test_vectors)):
+ x = test_vectors[i]
+ orth = test_expected_orth[i]
+ assert_array_almost_equal(orthogonality(A, x), orth)
+
+ def test_sparse_matrix(self):
+ A = np.array([[1, 2, 3, 4, 0, 5, 0, 7],
+ [0, 8, 7, 0, 1, 5, 9, 0],
+ [1, 0, 0, 0, 0, 1, 2, 3]])
+ A = csc_array(A)
+ test_vectors = ([-1.98931144, -1.56363389,
+ -0.84115584, 2.2864762,
+ 5.599141, 0.09286976,
+ 1.37040802, -0.28145812],
+ [697.92794044, -4091.65114008,
+ -3327.42316335, 836.86906951,
+ 99434.98929065, -1285.37653682,
+ -4109.21503806, 2935.29289083])
+ test_expected_orth = (0, 0)
+
+ for i in range(len(test_vectors)):
+ x = test_vectors[i]
+ orth = test_expected_orth[i]
+ assert_array_almost_equal(orthogonality(A, x), orth)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py
new file mode 100644
index 0000000000000000000000000000000000000000..9486671520fc6d60e1405fa839b756aa30b524fb
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_qp_subproblem.py
@@ -0,0 +1,645 @@
+import numpy as np
+from scipy.sparse import csc_array
+from scipy.optimize._trustregion_constr.qp_subproblem \
+ import (eqp_kktfact,
+ projected_cg,
+ box_intersections,
+ sphere_intersections,
+ box_sphere_intersections,
+ modified_dogleg)
+from scipy.optimize._trustregion_constr.projections \
+ import projections
+from numpy.testing import TestCase, assert_array_almost_equal, assert_equal
+import pytest
+
+
+class TestEQPDirectFactorization(TestCase):
+
+ # From Example 16.2 Nocedal/Wright "Numerical
+ # Optimization" p.452.
+ def test_nocedal_example(self):
+ H = csc_array([[6, 2, 1],
+ [2, 5, 2],
+ [1, 2, 4]])
+ A = csc_array([[1, 0, 1],
+ [0, 1, 1]])
+ c = np.array([-8, -3, -3])
+ b = -np.array([3, 0])
+ x, lagrange_multipliers = eqp_kktfact(H, c, A, b)
+ assert_array_almost_equal(x, [2, -1, 1])
+ assert_array_almost_equal(lagrange_multipliers, [3, -2])
+
+
+class TestSphericalBoundariesIntersections(TestCase):
+
+ def test_2d_sphere_constraints(self):
+ # Interior initial point
+ ta, tb, intersect = sphere_intersections([0, 0],
+ [1, 0], 0.5)
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # No intersection between line and circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [0, 1], 1)
+ assert_equal(intersect, False)
+
+ # Outside initial point pointing toward outside the circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [1, 0], 1)
+ assert_equal(intersect, False)
+
+ # Outside initial point pointing toward inside the circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [-1, 0], 1.5)
+ assert_array_almost_equal([ta, tb], [0.5, 1])
+ assert_equal(intersect, True)
+
+ # Initial point on the boundary
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [1, 0], 2)
+ assert_array_almost_equal([ta, tb], [0, 0])
+ assert_equal(intersect, True)
+
+ def test_2d_sphere_constraints_line_intersections(self):
+ # Interior initial point
+ ta, tb, intersect = sphere_intersections([0, 0],
+ [1, 0], 0.5,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-0.5, 0.5])
+ assert_equal(intersect, True)
+
+ # No intersection between line and circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [0, 1], 1,
+ entire_line=True)
+ assert_equal(intersect, False)
+
+ # Outside initial point pointing toward outside the circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [1, 0], 1,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-3, -1])
+ assert_equal(intersect, True)
+
+ # Outside initial point pointing toward inside the circle
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [-1, 0], 1.5,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0.5, 3.5])
+ assert_equal(intersect, True)
+
+ # Initial point on the boundary
+ ta, tb, intersect = sphere_intersections([2, 0],
+ [1, 0], 2,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-4, 0])
+ assert_equal(intersect, True)
+
+
+class TestBoxBoundariesIntersections(TestCase):
+
+ def test_2d_box_constraints(self):
+ # Box constraint in the direction of vector d
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [1, 1], [3, 3])
+ assert_array_almost_equal([ta, tb], [0.5, 1])
+ assert_equal(intersect, True)
+
+ # Negative direction
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [1, -3], [3, -1])
+ assert_equal(intersect, False)
+
+ # Some constraints are absent (set to +/- inf)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-np.inf, 1],
+ [np.inf, np.inf])
+ assert_array_almost_equal([ta, tb], [0.5, 1])
+ assert_equal(intersect, True)
+
+ # Intersect on the face of the box
+ ta, tb, intersect = box_intersections([1, 0], [0, 1],
+ [1, 1], [3, 3])
+ assert_array_almost_equal([ta, tb], [1, 1])
+ assert_equal(intersect, True)
+
+ # Interior initial point
+ ta, tb, intersect = box_intersections([0, 0], [4, 4],
+ [-2, -3], [3, 2])
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # No intersection between line and box constraints
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, -3], [-1, -1])
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, 3], [-1, 1])
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, -np.inf],
+ [-1, np.inf])
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([0, 0], [1, 100],
+ [1, 1], [3, 3])
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([0.99, 0], [0, 2],
+ [1, 1], [3, 3])
+ assert_equal(intersect, False)
+
+ # Initial point on the boundary
+ ta, tb, intersect = box_intersections([2, 2], [0, 1],
+ [-2, -2], [2, 2])
+ assert_array_almost_equal([ta, tb], [0, 0])
+ assert_equal(intersect, True)
+
+ def test_2d_box_constraints_entire_line(self):
+ # Box constraint in the direction of vector d
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [1, 1], [3, 3],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0.5, 1.5])
+ assert_equal(intersect, True)
+
+ # Negative direction
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [1, -3], [3, -1],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-1.5, -0.5])
+ assert_equal(intersect, True)
+
+ # Some constraints are absent (set to +/- inf)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-np.inf, 1],
+ [np.inf, np.inf],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0.5, np.inf])
+ assert_equal(intersect, True)
+
+ # Intersect on the face of the box
+ ta, tb, intersect = box_intersections([1, 0], [0, 1],
+ [1, 1], [3, 3],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [1, 3])
+ assert_equal(intersect, True)
+
+ # Interior initial point
+ ta, tb, intersect = box_intersections([0, 0], [4, 4],
+ [-2, -3], [3, 2],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-0.5, 0.5])
+ assert_equal(intersect, True)
+
+ # No intersection between line and box constraints
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, -3], [-1, -1],
+ entire_line=True)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, 3], [-1, 1],
+ entire_line=True)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([2, 0], [0, 2],
+ [-3, -np.inf],
+ [-1, np.inf],
+ entire_line=True)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([0, 0], [1, 100],
+ [1, 1], [3, 3],
+ entire_line=True)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_intersections([0.99, 0], [0, 2],
+ [1, 1], [3, 3],
+ entire_line=True)
+ assert_equal(intersect, False)
+
+ # Initial point on the boundary
+ ta, tb, intersect = box_intersections([2, 2], [0, 1],
+ [-2, -2], [2, 2],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-4, 0])
+ assert_equal(intersect, True)
+
+ def test_3d_box_constraints(self):
+ # Simple case
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1],
+ [1, 1, 1], [3, 3, 3])
+ assert_array_almost_equal([ta, tb], [1, 1])
+ assert_equal(intersect, True)
+
+ # Negative direction
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1],
+ [1, 1, 1], [3, 3, 3])
+ assert_equal(intersect, False)
+
+ # Interior point
+ ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1],
+ [1, 1, 1], [3, 3, 3])
+ assert_array_almost_equal([ta, tb], [0, 1])
+ assert_equal(intersect, True)
+
+ def test_3d_box_constraints_entire_line(self):
+ # Simple case
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, 1],
+ [1, 1, 1], [3, 3, 3],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [1, 3])
+ assert_equal(intersect, True)
+
+ # Negative direction
+ ta, tb, intersect = box_intersections([1, 1, 0], [0, 0, -1],
+ [1, 1, 1], [3, 3, 3],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-3, -1])
+ assert_equal(intersect, True)
+
+ # Interior point
+ ta, tb, intersect = box_intersections([2, 2, 2], [0, -1, 1],
+ [1, 1, 1], [3, 3, 3],
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [-1, 1])
+ assert_equal(intersect, True)
+
+
+class TestBoxSphereBoundariesIntersections(TestCase):
+
+ def test_2d_box_constraints(self):
+ # Both constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-2, 2],
+ [-1, -2], [1, 2], 2,
+ entire_line=False)
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # None of the constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-1, 1],
+ [-1, -3], [1, 3], 10,
+ entire_line=False)
+ assert_array_almost_equal([ta, tb], [0, 1])
+ assert_equal(intersect, True)
+
+ # Box constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [-1, -3], [1, 3], 10,
+ entire_line=False)
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # Spherical constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [-1, -3], [1, 3], 2,
+ entire_line=False)
+ assert_array_almost_equal([ta, tb], [0, 0.25])
+ assert_equal(intersect, True)
+
+ # Infeasible problems
+ ta, tb, intersect = box_sphere_intersections([2, 2], [-4, 4],
+ [-1, -3], [1, 3], 2,
+ entire_line=False)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [2, 4], [2, 4], 2,
+ entire_line=False)
+ assert_equal(intersect, False)
+
+ def test_2d_box_constraints_entire_line(self):
+ # Both constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-2, 2],
+ [-1, -2], [1, 2], 2,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # None of the constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-1, 1],
+ [-1, -3], [1, 3], 10,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0, 2])
+ assert_equal(intersect, True)
+
+ # Box constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [-1, -3], [1, 3], 10,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0, 0.5])
+ assert_equal(intersect, True)
+
+ # Spherical constraints are active
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [-1, -3], [1, 3], 2,
+ entire_line=True)
+ assert_array_almost_equal([ta, tb], [0, 0.25])
+ assert_equal(intersect, True)
+
+ # Infeasible problems
+ ta, tb, intersect = box_sphere_intersections([2, 2], [-4, 4],
+ [-1, -3], [1, 3], 2,
+ entire_line=True)
+ assert_equal(intersect, False)
+ ta, tb, intersect = box_sphere_intersections([1, 1], [-4, 4],
+ [2, 4], [2, 4], 2,
+ entire_line=True)
+ assert_equal(intersect, False)
+
+
+class TestModifiedDogleg(TestCase):
+
+ def test_cauchypoint_equalsto_newtonpoint(self):
+ A = np.array([[1, 8]])
+ b = np.array([-16])
+ _, _, Y = projections(A)
+ newton_point = np.array([0.24615385, 1.96923077])
+
+ # Newton point inside boundaries
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf], [np.inf, np.inf])
+ assert_array_almost_equal(x, newton_point)
+
+ # Spherical constraint active
+ x = modified_dogleg(A, Y, b, 1, [-np.inf, -np.inf], [np.inf, np.inf])
+ assert_array_almost_equal(x, newton_point/np.linalg.norm(newton_point))
+
+ # Box constraints active
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf], [0.1, np.inf])
+ assert_array_almost_equal(x, (newton_point/newton_point[0]) * 0.1)
+
+ def test_3d_example(self):
+ A = np.array([[1, 8, 1],
+ [4, 2, 2]])
+ b = np.array([-16, 2])
+ Z, LS, Y = projections(A)
+
+ newton_point = np.array([-1.37090909, 2.23272727, -0.49090909])
+ cauchy_point = np.array([0.11165723, 1.73068711, 0.16748585])
+ origin = np.zeros_like(newton_point)
+
+ # newton_point inside boundaries
+ x = modified_dogleg(A, Y, b, 3, [-np.inf, -np.inf, -np.inf],
+ [np.inf, np.inf, np.inf])
+ assert_array_almost_equal(x, newton_point)
+
+ # line between cauchy_point and newton_point contains best point
+ # (spherical constraint is active).
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf, -np.inf],
+ [np.inf, np.inf, np.inf])
+ z = cauchy_point
+ d = newton_point-cauchy_point
+ t = ((x-z)/(d))
+ assert_array_almost_equal(t, np.full(3, 0.40807330))
+ assert_array_almost_equal(np.linalg.norm(x), 2)
+
+ # line between cauchy_point and newton_point contains best point
+ # (box constraint is active).
+ x = modified_dogleg(A, Y, b, 5, [-1, -np.inf, -np.inf],
+ [np.inf, np.inf, np.inf])
+ z = cauchy_point
+ d = newton_point-cauchy_point
+ t = ((x-z)/(d))
+ assert_array_almost_equal(t, np.full(3, 0.7498195))
+ assert_array_almost_equal(x[0], -1)
+
+ # line between origin and cauchy_point contains best point
+ # (spherical constraint is active).
+ x = modified_dogleg(A, Y, b, 1, [-np.inf, -np.inf, -np.inf],
+ [np.inf, np.inf, np.inf])
+ z = origin
+ d = cauchy_point
+ t = ((x-z)/(d))
+ assert_array_almost_equal(t, np.full(3, 0.573936265))
+ assert_array_almost_equal(np.linalg.norm(x), 1)
+
+ # line between origin and newton_point contains best point
+ # (box constraint is active).
+ x = modified_dogleg(A, Y, b, 2, [-np.inf, -np.inf, -np.inf],
+ [np.inf, 1, np.inf])
+ z = origin
+ d = newton_point
+ t = ((x-z)/(d))
+ assert_array_almost_equal(t, np.full(3, 0.4478827364))
+ assert_array_almost_equal(x[1], 1)
+
+
+class TestProjectCG(TestCase):
+
+ # From Example 16.2 Nocedal/Wright "Numerical
+ # Optimization" p.452.
+ def test_nocedal_example(self):
+ H = csc_array([[6, 2, 1],
+ [2, 5, 2],
+ [1, 2, 4]])
+ A = csc_array([[1, 0, 1],
+ [0, 1, 1]])
+ c = np.array([-8, -3, -3])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b)
+ assert_equal(info["stop_cond"], 4)
+ assert_equal(info["hits_boundary"], False)
+ assert_array_almost_equal(x, [2, -1, 1])
+
+ def test_compare_with_direct_fact(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b, tol=0)
+ x_kkt, _ = eqp_kktfact(H, c, A, b)
+ assert_equal(info["stop_cond"], 1)
+ assert_equal(info["hits_boundary"], False)
+ assert_array_almost_equal(x, x_kkt)
+
+ def test_trust_region_infeasible(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ trust_radius = 1
+ Z, _, Y = projections(A)
+ with pytest.raises(ValueError):
+ projected_cg(H, c, Z, Y, b, trust_radius=trust_radius)
+
+ def test_trust_region_barely_feasible(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ trust_radius = 2.32379000772445021283
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ trust_radius=trust_radius)
+ assert_equal(info["stop_cond"], 2)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(np.linalg.norm(x), trust_radius)
+ assert_array_almost_equal(x, -Y.dot(b))
+
+ def test_hits_boundary(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ trust_radius = 3
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ trust_radius=trust_radius)
+ assert_equal(info["stop_cond"], 2)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(np.linalg.norm(x), trust_radius)
+
+ def test_negative_curvature_unconstrained(self):
+ H = csc_array([[1, 2, 1, 3],
+ [2, 0, 2, 4],
+ [1, 2, 0, 2],
+ [3, 4, 2, 0]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 0, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ with pytest.raises(ValueError):
+ projected_cg(H, c, Z, Y, b, tol=0)
+
+ def test_negative_curvature(self):
+ H = csc_array([[1, 2, 1, 3],
+ [2, 0, 2, 4],
+ [1, 2, 0, 2],
+ [3, 4, 2, 0]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 0, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ trust_radius = 1000
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ trust_radius=trust_radius)
+ assert_equal(info["stop_cond"], 3)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(np.linalg.norm(x), trust_radius)
+
+ # The box constraints are inactive at the solution but
+ # are active during the iterations.
+ def test_inactive_box_constraints(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ lb=[0.5, -np.inf,
+ -np.inf, -np.inf],
+ return_all=True)
+ x_kkt, _ = eqp_kktfact(H, c, A, b)
+ assert_equal(info["stop_cond"], 1)
+ assert_equal(info["hits_boundary"], False)
+ assert_array_almost_equal(x, x_kkt)
+
+ # The box constraints active and the termination is
+ # by maximum iterations (infeasible interaction).
+ def test_active_box_constraints_maximum_iterations_reached(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ lb=[0.8, -np.inf,
+ -np.inf, -np.inf],
+ return_all=True)
+ assert_equal(info["stop_cond"], 1)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(A.dot(x), -b)
+ assert_array_almost_equal(x[0], 0.8)
+
+ # The box constraints are active and the termination is
+ # because it hits boundary (without infeasible interaction).
+ def test_active_box_constraints_hits_boundaries(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ trust_radius = 3
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ ub=[np.inf, np.inf, 1.6, np.inf],
+ trust_radius=trust_radius,
+ return_all=True)
+ assert_equal(info["stop_cond"], 2)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(x[2], 1.6)
+
+ # The box constraints are active and the termination is
+ # because it hits boundary (infeasible interaction).
+ def test_active_box_constraints_hits_boundaries_infeasible_iter(self):
+ H = csc_array([[6, 2, 1, 3],
+ [2, 5, 2, 4],
+ [1, 2, 4, 5],
+ [3, 4, 5, 7]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 1, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ trust_radius = 4
+ Z, _, Y = projections(A)
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ ub=[np.inf, 0.1, np.inf, np.inf],
+ trust_radius=trust_radius,
+ return_all=True)
+ assert_equal(info["stop_cond"], 2)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(x[1], 0.1)
+
+ # The box constraints are active and the termination is
+ # because it hits boundary (no infeasible interaction).
+ def test_active_box_constraints_negative_curvature(self):
+ H = csc_array([[1, 2, 1, 3],
+ [2, 0, 2, 4],
+ [1, 2, 0, 2],
+ [3, 4, 2, 0]])
+ A = csc_array([[1, 0, 1, 0],
+ [0, 1, 0, 1]])
+ c = np.array([-2, -3, -3, 1])
+ b = -np.array([3, 0])
+ Z, _, Y = projections(A)
+ trust_radius = 1000
+ x, info = projected_cg(H, c, Z, Y, b,
+ tol=0,
+ ub=[np.inf, np.inf, 100, np.inf],
+ trust_radius=trust_radius)
+ assert_equal(info["stop_cond"], 3)
+ assert_equal(info["hits_boundary"], True)
+ assert_array_almost_equal(x[2], 100)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py
new file mode 100644
index 0000000000000000000000000000000000000000..66fa5bd17f80a907db425c927c08e5dc0797028e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tests/test_report.py
@@ -0,0 +1,34 @@
+import pytest
+import numpy as np
+from scipy.optimize import minimize, Bounds
+
+def test_gh10880():
+ # checks that verbose reporting works with trust-constr for
+ # bound-constrained problems
+ bnds = Bounds(1, 2)
+ opts = {'maxiter': 1000, 'verbose': 2}
+ minimize(lambda x: x**2, x0=2., method='trust-constr',
+ bounds=bnds, options=opts)
+
+ opts = {'maxiter': 1000, 'verbose': 3}
+ minimize(lambda x: x**2, x0=2., method='trust-constr',
+ bounds=bnds, options=opts)
+
+@pytest.mark.xslow
+def test_gh12922():
+ # checks that verbose reporting works with trust-constr for
+ # general constraints
+ def objective(x):
+ return np.array([(np.sum((x+1)**4))])
+
+ cons = {'type': 'ineq', 'fun': lambda x: -x[0]**2}
+ n = 25
+ x0 = np.linspace(-5, 5, n)
+
+ opts = {'maxiter': 1000, 'verbose': 2}
+ minimize(objective, x0=x0, method='trust-constr',
+ constraints=cons, options=opts)
+
+ opts = {'maxiter': 1000, 'verbose': 3}
+ minimize(objective, x0=x0, method='trust-constr',
+ constraints=cons, options=opts)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py
new file mode 100644
index 0000000000000000000000000000000000000000..6e985163f97a4dd1f8f25e0bb814aa47c00f56ee
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_constr/tr_interior_point.py
@@ -0,0 +1,361 @@
+"""Trust-region interior point method.
+
+References
+----------
+.. [1] Byrd, Richard H., Mary E. Hribar, and Jorge Nocedal.
+ "An interior point algorithm for large-scale nonlinear
+ programming." SIAM Journal on Optimization 9.4 (1999): 877-900.
+.. [2] Byrd, Richard H., Guanghui Liu, and Jorge Nocedal.
+ "On the local behavior of an interior point method for
+ nonlinear programming." Numerical analysis 1997 (1997): 37-56.
+.. [3] Nocedal, Jorge, and Stephen J. Wright. "Numerical optimization"
+ Second Edition (2006).
+"""
+
+import scipy.sparse as sps
+import numpy as np
+from .equality_constrained_sqp import equality_constrained_sqp
+from scipy.sparse.linalg import LinearOperator
+
+__all__ = ['tr_interior_point']
+
+
+class BarrierSubproblem:
+ """
+ Barrier optimization problem:
+ minimize fun(x) - barrier_parameter*sum(log(s))
+ subject to: constr_eq(x) = 0
+ constr_ineq(x) + s = 0
+ """
+
+ def __init__(self, x0, s0, fun, grad, lagr_hess, n_vars, n_ineq, n_eq,
+ constr, jac, barrier_parameter, tolerance,
+ enforce_feasibility, global_stop_criteria,
+ xtol, fun0, grad0, constr_ineq0, jac_ineq0, constr_eq0,
+ jac_eq0, finite_diff_bounds):
+ # Store parameters
+ self.n_vars = n_vars
+ self.x0 = x0
+ self.s0 = s0
+ self.fun = fun
+ self.grad = grad
+ self.lagr_hess = lagr_hess
+ self.constr = constr
+ self.jac = jac
+ self.barrier_parameter = barrier_parameter
+ self.tolerance = tolerance
+ self.n_eq = n_eq
+ self.n_ineq = n_ineq
+ self.enforce_feasibility = enforce_feasibility
+ self.global_stop_criteria = global_stop_criteria
+ self.xtol = xtol
+ self.fun0 = self._compute_function(fun0, constr_ineq0, s0)
+ self.grad0 = self._compute_gradient(grad0)
+ self.constr0 = self._compute_constr(constr_ineq0, constr_eq0, s0)
+ self.jac0 = self._compute_jacobian(jac_eq0, jac_ineq0, s0)
+ self.terminate = False
+ self.lb = finite_diff_bounds[0]
+ self.ub = finite_diff_bounds[1]
+
+ def update(self, barrier_parameter, tolerance):
+ self.barrier_parameter = barrier_parameter
+ self.tolerance = tolerance
+
+ def get_slack(self, z):
+ return z[self.n_vars:self.n_vars+self.n_ineq]
+
+ def get_variables(self, z):
+ return z[:self.n_vars]
+
+ def function_and_constraints(self, z):
+ """Returns barrier function and constraints at given point.
+
+ For z = [x, s], returns barrier function:
+ function(z) = fun(x) - barrier_parameter*sum(log(s))
+ and barrier constraints:
+ constraints(z) = [ constr_eq(x) ]
+ [ constr_ineq(x) + s ]
+
+ """
+ # Get variables and slack variables
+ x = self.get_variables(z)
+ s = self.get_slack(z)
+
+ # Compute function and constraints,
+ # making sure x is within any strict bounds
+ if np.any((x < self.lb) | (x > self.ub)):
+ # If x is out of the strict bounds, set f = inf,
+ # and just set both equality and inequality
+ # constraints to 0 since we can't evaluate
+ # them separately.
+ f = np.inf
+ c_eq = np.full(self.n_eq, 0.)
+ c_ineq = np.full(self.n_ineq, 0.)
+ else:
+ f = self.fun(x)
+ c_eq, c_ineq = self.constr(x)
+
+ # Return objective function and constraints
+ return (self._compute_function(f, c_ineq, s),
+ self._compute_constr(c_ineq, c_eq, s))
+
+ def _compute_function(self, f, c_ineq, s):
+ # Use technique from Nocedal and Wright book, ref [3]_, p.576,
+ # to guarantee constraints from `enforce_feasibility`
+ # stay feasible along iterations.
+ s[self.enforce_feasibility] = -c_ineq[self.enforce_feasibility]
+ log_s = [np.log(s_i) if s_i > 0 else -np.inf for s_i in s]
+ # Compute barrier objective function
+ return f - self.barrier_parameter*np.sum(log_s)
+
+ def _compute_constr(self, c_ineq, c_eq, s):
+ # Compute barrier constraint
+ return np.hstack((c_eq,
+ c_ineq + s))
+
+ def scaling(self, z):
+ """Returns scaling vector.
+ Given by:
+ scaling = [ones(n_vars), s]
+ """
+ s = self.get_slack(z)
+ diag_elements = np.hstack((np.ones(self.n_vars), s))
+
+ # Diagonal matrix
+ def matvec(vec):
+ return diag_elements*vec
+ return LinearOperator((self.n_vars+self.n_ineq,
+ self.n_vars+self.n_ineq),
+ matvec)
+
+ def gradient_and_jacobian(self, z):
+ """Returns scaled gradient.
+
+ Return scaled gradient:
+ gradient = [ grad(x) ]
+ [ -barrier_parameter*ones(n_ineq) ]
+ and scaled Jacobian matrix:
+ jacobian = [ jac_eq(x) 0 ]
+ [ jac_ineq(x) S ]
+ Both of them scaled by the previously defined scaling factor.
+ """
+ # Get variables and slack variables
+ x = self.get_variables(z)
+ s = self.get_slack(z)
+ # Compute first derivatives
+ g = self.grad(x)
+ J_eq, J_ineq = self.jac(x)
+ # Return gradient and Jacobian
+ return (self._compute_gradient(g),
+ self._compute_jacobian(J_eq, J_ineq, s))
+
+ def _compute_gradient(self, g):
+ return np.hstack((g, -self.barrier_parameter*np.ones(self.n_ineq)))
+
+ def _compute_jacobian(self, J_eq, J_ineq, s):
+ if self.n_ineq == 0:
+ return J_eq
+ else:
+ if sps.issparse(J_eq) or sps.issparse(J_ineq):
+ # It is expected that J_eq and J_ineq
+ # are already `csr_array` because of
+ # the way ``BoxConstraint``, ``NonlinearConstraint``
+ # and ``LinearConstraint`` are defined.
+ J_eq = sps.csr_array(J_eq)
+ J_ineq = sps.csr_array(J_ineq)
+ return self._assemble_sparse_jacobian(J_eq, J_ineq, s)
+ else:
+ S = np.diag(s)
+ zeros = np.zeros((self.n_eq, self.n_ineq))
+ # Convert to matrix
+ if sps.issparse(J_ineq):
+ J_ineq = J_ineq.toarray()
+ if sps.issparse(J_eq):
+ J_eq = J_eq.toarray()
+ # Concatenate matrices
+ return np.block([[J_eq, zeros],
+ [J_ineq, S]])
+
+ def _assemble_sparse_jacobian(self, J_eq, J_ineq, s):
+ """Assemble sparse Jacobian given its components.
+
+ Given ``J_eq``, ``J_ineq`` and ``s`` returns:
+ jacobian = [ J_eq, 0 ]
+ [ J_ineq, diag(s) ]
+
+ It is equivalent to:
+ sps.bmat([[ J_eq, None ],
+ [ J_ineq, diag(s) ]], "csr")
+ but significantly more efficient for this
+ given structure.
+ """
+ n_vars, n_ineq, n_eq = self.n_vars, self.n_ineq, self.n_eq
+ J_aux = sps.vstack([J_eq, J_ineq], "csr")
+ indptr, indices, data = J_aux.indptr, J_aux.indices, J_aux.data
+ new_indptr = indptr + np.hstack((np.zeros(n_eq, dtype=int),
+ np.arange(n_ineq+1, dtype=int)))
+ size = indices.size+n_ineq
+ new_indices = np.empty(size)
+ new_data = np.empty(size)
+ mask = np.full(size, False, bool)
+ mask[new_indptr[-n_ineq:]-1] = True
+ new_indices[mask] = n_vars+np.arange(n_ineq)
+ new_indices[~mask] = indices
+ new_data[mask] = s
+ new_data[~mask] = data
+ J = sps.csr_array((new_data, new_indices, new_indptr),
+ (n_eq + n_ineq, n_vars + n_ineq))
+ return J
+
+ def lagrangian_hessian_x(self, z, v):
+ """Returns Lagrangian Hessian (in relation to `x`) -> Hx"""
+ x = self.get_variables(z)
+ # Get lagrange multipliers related to nonlinear equality constraints
+ v_eq = v[:self.n_eq]
+ # Get lagrange multipliers related to nonlinear ineq. constraints
+ v_ineq = v[self.n_eq:self.n_eq+self.n_ineq]
+ lagr_hess = self.lagr_hess
+ return lagr_hess(x, v_eq, v_ineq)
+
+ def lagrangian_hessian_s(self, z, v):
+ """Returns scaled Lagrangian Hessian (in relation to`s`) -> S Hs S"""
+ s = self.get_slack(z)
+ # Using the primal formulation:
+ # S Hs S = diag(s)*diag(barrier_parameter/s**2)*diag(s).
+ # Reference [1]_ p. 882, formula (3.1)
+ primal = self.barrier_parameter
+ # Using the primal-dual formulation
+ # S Hs S = diag(s)*diag(v/s)*diag(s)
+ # Reference [1]_ p. 883, formula (3.11)
+ primal_dual = v[-self.n_ineq:]*s
+ # Uses the primal-dual formulation for
+ # positives values of v_ineq, and primal
+ # formulation for the remaining ones.
+ return np.where(v[-self.n_ineq:] > 0, primal_dual, primal)
+
+ def lagrangian_hessian(self, z, v):
+ """Returns scaled Lagrangian Hessian"""
+ # Compute Hessian in relation to x and s
+ Hx = self.lagrangian_hessian_x(z, v)
+ if self.n_ineq > 0:
+ S_Hs_S = self.lagrangian_hessian_s(z, v)
+
+ # The scaled Lagragian Hessian is:
+ # [ Hx 0 ]
+ # [ 0 S Hs S ]
+ def matvec(vec):
+ vec_x = self.get_variables(vec)
+ vec_s = self.get_slack(vec)
+ if self.n_ineq > 0:
+ return np.hstack((Hx.dot(vec_x), S_Hs_S*vec_s))
+ else:
+ return Hx.dot(vec_x)
+ return LinearOperator((self.n_vars+self.n_ineq,
+ self.n_vars+self.n_ineq),
+ matvec)
+
+ def stop_criteria(self, state, z, last_iteration_failed,
+ optimality, constr_violation,
+ trust_radius, penalty, cg_info):
+ """Stop criteria to the barrier problem.
+ The criteria here proposed is similar to formula (2.3)
+ from [1]_, p.879.
+ """
+ x = self.get_variables(z)
+ if self.global_stop_criteria(state, x,
+ last_iteration_failed,
+ trust_radius, penalty,
+ cg_info,
+ self.barrier_parameter,
+ self.tolerance):
+ self.terminate = True
+ return True
+ else:
+ g_cond = (optimality < self.tolerance and
+ constr_violation < self.tolerance)
+ x_cond = trust_radius < self.xtol
+ return g_cond or x_cond
+
+
+def tr_interior_point(fun, grad, lagr_hess, n_vars, n_ineq, n_eq,
+ constr, jac, x0, fun0, grad0,
+ constr_ineq0, jac_ineq0, constr_eq0,
+ jac_eq0, stop_criteria,
+ enforce_feasibility, xtol, state,
+ initial_barrier_parameter,
+ initial_tolerance,
+ initial_penalty,
+ initial_trust_radius,
+ factorization_method,
+ finite_diff_bounds):
+ """Trust-region interior points method.
+
+ Solve problem:
+ minimize fun(x)
+ subject to: constr_ineq(x) <= 0
+ constr_eq(x) = 0
+ using trust-region interior point method described in [1]_.
+ """
+ # BOUNDARY_PARAMETER controls the decrease on the slack
+ # variables. Represents ``tau`` from [1]_ p.885, formula (3.18).
+ BOUNDARY_PARAMETER = 0.995
+ # BARRIER_DECAY_RATIO controls the decay of the barrier parameter
+ # and of the subproblem tolerance. Represents ``theta`` from [1]_ p.879.
+ BARRIER_DECAY_RATIO = 0.2
+ # TRUST_ENLARGEMENT controls the enlargement on trust radius
+ # after each iteration
+ TRUST_ENLARGEMENT = 5
+
+ # Default enforce_feasibility
+ if enforce_feasibility is None:
+ enforce_feasibility = np.zeros(n_ineq, bool)
+ # Initial Values
+ barrier_parameter = initial_barrier_parameter
+ tolerance = initial_tolerance
+ trust_radius = initial_trust_radius
+ # Define initial value for the slack variables
+ s0 = np.maximum(-1.5*constr_ineq0, np.ones(n_ineq))
+ # Define barrier subproblem
+ subprob = BarrierSubproblem(
+ x0, s0, fun, grad, lagr_hess, n_vars, n_ineq, n_eq, constr, jac,
+ barrier_parameter, tolerance, enforce_feasibility,
+ stop_criteria, xtol, fun0, grad0, constr_ineq0, jac_ineq0,
+ constr_eq0, jac_eq0, finite_diff_bounds)
+ # Define initial parameter for the first iteration.
+ z = np.hstack((x0, s0))
+ fun0_subprob, constr0_subprob = subprob.fun0, subprob.constr0
+ grad0_subprob, jac0_subprob = subprob.grad0, subprob.jac0
+ # Define trust region bounds
+ trust_lb = np.hstack((np.full(subprob.n_vars, -np.inf),
+ np.full(subprob.n_ineq, -BOUNDARY_PARAMETER)))
+ trust_ub = np.full(subprob.n_vars+subprob.n_ineq, np.inf)
+
+ # Solves a sequence of barrier problems
+ while True:
+ # Solve SQP subproblem
+ z, state = equality_constrained_sqp(
+ subprob.function_and_constraints,
+ subprob.gradient_and_jacobian,
+ subprob.lagrangian_hessian,
+ z, fun0_subprob, grad0_subprob,
+ constr0_subprob, jac0_subprob, subprob.stop_criteria,
+ state, initial_penalty, trust_radius,
+ factorization_method, trust_lb, trust_ub, subprob.scaling)
+ if subprob.terminate:
+ break
+ # Update parameters
+ trust_radius = max(initial_trust_radius,
+ TRUST_ENLARGEMENT*state.tr_radius)
+ # TODO: Use more advanced strategies from [2]_
+ # to update this parameters.
+ barrier_parameter *= BARRIER_DECAY_RATIO
+ tolerance *= BARRIER_DECAY_RATIO
+ # Update Barrier Problem
+ subprob.update(barrier_parameter, tolerance)
+ # Compute initial values for next iteration
+ fun0_subprob, constr0_subprob = subprob.function_and_constraints(z)
+ grad0_subprob, jac0_subprob = subprob.gradient_and_jacobian(z)
+
+ # Get x and s
+ x = subprob.get_variables(z)
+ return x, state
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_dogleg.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_dogleg.py
new file mode 100644
index 0000000000000000000000000000000000000000..a54abd60c703408d6c87cb5020d6781fdf0213c7
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_dogleg.py
@@ -0,0 +1,122 @@
+"""Dog-leg trust-region optimization."""
+import numpy as np
+import scipy.linalg
+from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem)
+
+__all__ = []
+
+
+def _minimize_dogleg(fun, x0, args=(), jac=None, hess=None,
+ **trust_region_options):
+ """
+ Minimization of scalar function of one or more variables using
+ the dog-leg trust-region algorithm.
+
+ Options
+ -------
+ initial_trust_radius : float
+ Initial trust-region radius.
+ max_trust_radius : float
+ Maximum value of the trust-region radius. No steps that are longer
+ than this value will be proposed.
+ eta : float
+ Trust region related acceptance stringency for proposed steps.
+ gtol : float
+ Gradient norm must be less than `gtol` before successful
+ termination.
+
+ """
+ if jac is None:
+ raise ValueError('Jacobian is required for dogleg minimization')
+ if not callable(hess):
+ raise ValueError('Hessian is required for dogleg minimization')
+ return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess,
+ subproblem=DoglegSubproblem,
+ **trust_region_options)
+
+
+class DoglegSubproblem(BaseQuadraticSubproblem):
+ """Quadratic subproblem solved by the dogleg method"""
+
+ def cauchy_point(self):
+ """
+ The Cauchy point is minimal along the direction of steepest descent.
+ """
+ if self._cauchy_point is None:
+ g = self.jac
+ Bg = self.hessp(g)
+ self._cauchy_point = -(np.dot(g, g) / np.dot(g, Bg)) * g
+ return self._cauchy_point
+
+ def newton_point(self):
+ """
+ The Newton point is a global minimum of the approximate function.
+ """
+ if self._newton_point is None:
+ g = self.jac
+ B = self.hess
+ cho_info = scipy.linalg.cho_factor(B)
+ self._newton_point = -scipy.linalg.cho_solve(cho_info, g)
+ return self._newton_point
+
+ def solve(self, trust_radius):
+ """
+ Minimize a function using the dog-leg trust-region algorithm.
+
+ This algorithm requires function values and first and second derivatives.
+ It also performs a costly Hessian decomposition for most iterations,
+ and the Hessian is required to be positive definite.
+
+ Parameters
+ ----------
+ trust_radius : float
+ We are allowed to wander only this far away from the origin.
+
+ Returns
+ -------
+ p : ndarray
+ The proposed step.
+ hits_boundary : bool
+ True if the proposed step is on the boundary of the trust region.
+
+ Notes
+ -----
+ The Hessian is required to be positive definite.
+
+ References
+ ----------
+ .. [1] Jorge Nocedal and Stephen Wright,
+ Numerical Optimization, second edition,
+ Springer-Verlag, 2006, page 73.
+ """
+
+ # Compute the Newton point.
+ # This is the optimum for the quadratic model function.
+ # If it is inside the trust radius then return this point.
+ p_best = self.newton_point()
+ if scipy.linalg.norm(p_best) < trust_radius:
+ hits_boundary = False
+ return p_best, hits_boundary
+
+ # Compute the Cauchy point.
+ # This is the predicted optimum along the direction of steepest descent.
+ p_u = self.cauchy_point()
+
+ # If the Cauchy point is outside the trust region,
+ # then return the point where the path intersects the boundary.
+ p_u_norm = scipy.linalg.norm(p_u)
+ if p_u_norm >= trust_radius:
+ p_boundary = p_u * (trust_radius / p_u_norm)
+ hits_boundary = True
+ return p_boundary, hits_boundary
+
+ # Compute the intersection of the trust region boundary
+ # and the line segment connecting the Cauchy and Newton points.
+ # This requires solving a quadratic equation.
+ # ||p_u + t*(p_best - p_u)||**2 == trust_radius**2
+ # Solve this for positive time t using the quadratic formula.
+ _, tb = self.get_boundaries_intersections(p_u, p_best - p_u,
+ trust_radius)
+ p_boundary = p_u + tb * (p_best - p_u)
+ hits_boundary = True
+ return p_boundary, hits_boundary
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_exact.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_exact.py
new file mode 100644
index 0000000000000000000000000000000000000000..c0d48d41659d0b3f1409bb48e33c7ce51cb6e2e8
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_exact.py
@@ -0,0 +1,458 @@
+"""Nearly exact trust-region optimization subproblem."""
+import numpy as np
+from scipy.linalg import (norm, get_lapack_funcs, solve_triangular,
+ cho_solve)
+from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem)
+
+__all__ = ['_minimize_trustregion_exact',
+ 'estimate_smallest_singular_value',
+ 'singular_leading_submatrix',
+ 'IterativeSubproblem']
+
+
+def _minimize_trustregion_exact(fun, x0, args=(), jac=None, hess=None,
+ **trust_region_options):
+ """
+ Minimization of scalar function of one or more variables using
+ a nearly exact trust-region algorithm.
+
+ Options
+ -------
+ initial_trust_radius : float
+ Initial trust-region radius.
+ max_trust_radius : float
+ Maximum value of the trust-region radius. No steps that are longer
+ than this value will be proposed.
+ eta : float
+ Trust region related acceptance stringency for proposed steps.
+ gtol : float
+ Gradient norm must be less than ``gtol`` before successful
+ termination.
+ subproblem_maxiter : int, optional
+ Maximum number of iterations to perform per subproblem. Only affects
+ trust-exact. Default is 25.
+
+ .. versionadded:: 1.17.0
+ """
+ if jac is None:
+ raise ValueError('Jacobian is required for trust region '
+ 'exact minimization.')
+ if not callable(hess):
+ raise ValueError('Hessian matrix is required for trust region '
+ 'exact minimization.')
+ return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess,
+ subproblem=IterativeSubproblem,
+ **trust_region_options)
+
+
+def estimate_smallest_singular_value(U):
+ """Given upper triangular matrix ``U`` estimate the smallest singular
+ value and the correspondent right singular vector in O(n**2) operations.
+
+ Parameters
+ ----------
+ U : ndarray
+ Square upper triangular matrix.
+
+ Returns
+ -------
+ s_min : float
+ Estimated smallest singular value of the provided matrix.
+ z_min : ndarray
+ Estimated right singular vector.
+
+ Notes
+ -----
+ The procedure is based on [1]_ and is done in two steps. First, it finds
+ a vector ``e`` with components selected from {+1, -1} such that the
+ solution ``w`` from the system ``U.T w = e`` is as large as possible.
+ Next it estimate ``U v = w``. The smallest singular value is close
+ to ``norm(w)/norm(v)`` and the right singular vector is close
+ to ``v/norm(v)``.
+
+ The estimation will be better more ill-conditioned is the matrix.
+
+ References
+ ----------
+ .. [1] Cline, A. K., Moler, C. B., Stewart, G. W., Wilkinson, J. H.
+ An estimate for the condition number of a matrix. 1979.
+ SIAM Journal on Numerical Analysis, 16(2), 368-375.
+ """
+
+ U = np.atleast_2d(U)
+ m, n = U.shape
+
+ if m != n:
+ raise ValueError("A square triangular matrix should be provided.")
+
+ # A vector `e` with components selected from {+1, -1}
+ # is selected so that the solution `w` to the system
+ # `U.T w = e` is as large as possible. Implementation
+ # based on algorithm 3.5.1, p. 142, from reference [2]
+ # adapted for lower triangular matrix.
+
+ p = np.zeros(n)
+ w = np.empty(n)
+
+ # Implemented according to: Golub, G. H., Van Loan, C. F. (2013).
+ # "Matrix computations". Forth Edition. JHU press. pp. 140-142.
+ for k in range(n):
+ wp = (1-p[k]) / U.T[k, k]
+ wm = (-1-p[k]) / U.T[k, k]
+ pp = p[k+1:] + U.T[k+1:, k]*wp
+ pm = p[k+1:] + U.T[k+1:, k]*wm
+
+ if abs(wp) + norm(pp, 1) >= abs(wm) + norm(pm, 1):
+ w[k] = wp
+ p[k+1:] = pp
+ else:
+ w[k] = wm
+ p[k+1:] = pm
+
+ # The system `U v = w` is solved using backward substitution.
+ v = solve_triangular(U, w)
+
+ v_norm = norm(v)
+ w_norm = norm(w)
+
+ # Smallest singular value
+ s_min = w_norm / v_norm
+
+ # Associated vector
+ z_min = v / v_norm
+
+ return s_min, z_min
+
+
+def gershgorin_bounds(H):
+ """
+ Given a square matrix ``H`` compute upper
+ and lower bounds for its eigenvalues (Gregoshgorin Bounds).
+ Defined ref. [1].
+
+ References
+ ----------
+ .. [1] Conn, A. R., Gould, N. I., & Toint, P. L.
+ Trust region methods. 2000. Siam. pp. 19.
+ """
+
+ H_diag = np.diag(H)
+ H_diag_abs = np.abs(H_diag)
+ H_row_sums = np.sum(np.abs(H), axis=1)
+ lb = np.min(H_diag + H_diag_abs - H_row_sums)
+ ub = np.max(H_diag - H_diag_abs + H_row_sums)
+
+ return lb, ub
+
+
+def singular_leading_submatrix(A, U, k):
+ """
+ Compute term that makes the leading ``k`` by ``k``
+ submatrix from ``A`` singular.
+
+ Parameters
+ ----------
+ A : ndarray
+ Symmetric matrix that is not positive definite.
+ U : ndarray
+ Upper triangular matrix resulting of an incomplete
+ Cholesky decomposition of matrix ``A``.
+ k : int
+ Positive integer such that the leading k by k submatrix from
+ `A` is the first non-positive definite leading submatrix.
+
+ Returns
+ -------
+ delta : float
+ Amount that should be added to the element (k, k) of the
+ leading k by k submatrix of ``A`` to make it singular.
+ v : ndarray
+ A vector such that ``v.T B v = 0``. Where B is the matrix A after
+ ``delta`` is added to its element (k, k).
+ """
+
+ # Compute delta
+ delta = np.sum(U[:k-1, k-1]**2) - A[k-1, k-1]
+
+ n = len(A)
+
+ # Initialize v
+ v = np.zeros(n)
+ v[k-1] = 1
+
+ # Compute the remaining values of v by solving a triangular system.
+ if k != 1:
+ v[:k-1] = solve_triangular(U[:k-1, :k-1], -U[:k-1, k-1])
+
+ return delta, v
+
+
+class IterativeSubproblem(BaseQuadraticSubproblem):
+ """Quadratic subproblem solved by nearly exact iterative method.
+
+ Notes
+ -----
+ This subproblem solver was based on [1]_, [2]_ and [3]_,
+ which implement similar algorithms. The algorithm is basically
+ that of [1]_ but ideas from [2]_ and [3]_ were also used.
+
+ References
+ ----------
+ .. [1] A.R. Conn, N.I. Gould, and P.L. Toint, "Trust region methods",
+ Siam, pp. 169-200, 2000.
+ .. [2] J. Nocedal and S. Wright, "Numerical optimization",
+ Springer Science & Business Media. pp. 83-91, 2006.
+ .. [3] J.J. More and D.C. Sorensen, "Computing a trust region step",
+ SIAM Journal on Scientific and Statistical Computing, vol. 4(3),
+ pp. 553-572, 1983.
+ """
+
+ # UPDATE_COEFF appears in reference [1]_
+ # in formula 7.3.14 (p. 190) named as "theta".
+ # As recommended there it value is fixed in 0.01.
+ UPDATE_COEFF = 0.01
+
+ # The subproblem may iterate infinitely for problematic
+ # cases (see https://github.com/scipy/scipy/issues/12513).
+ # When the `maxiter` setting is None, we need to apply a
+ # default. An ad-hoc number (though tested quite extensively)
+ # is 25, which is set below. To restore the old behavior (which
+ # potentially hangs), this parameter may be changed to zero:
+ MAXITER_DEFAULT = 25 # use np.inf for infinite number of iterations
+
+ EPS = np.finfo(float).eps
+
+ def __init__(self, x, fun, jac, hess, hessp=None,
+ k_easy=0.1, k_hard=0.2, maxiter=None):
+
+ super().__init__(x, fun, jac, hess)
+
+ # When the trust-region shrinks in two consecutive
+ # calculations (``tr_radius < previous_tr_radius``)
+ # the lower bound ``lambda_lb`` may be reused,
+ # facilitating the convergence. To indicate no
+ # previous value is known at first ``previous_tr_radius``
+ # is set to -1 and ``lambda_lb`` to None.
+ self.previous_tr_radius = -1
+ self.lambda_lb = None
+
+ self.niter = 0
+
+ # ``k_easy`` and ``k_hard`` are parameters used
+ # to determine the stop criteria to the iterative
+ # subproblem solver. Take a look at pp. 194-197
+ # from reference _[1] for a more detailed description.
+ self.k_easy = k_easy
+ self.k_hard = k_hard
+
+ # ``maxiter`` optionally limits the number of iterations
+ # the solve method may perform. Useful for poorly conditioned
+ # problems which may otherwise hang.
+ self.maxiter = self.MAXITER_DEFAULT if maxiter is None else maxiter
+ if self.maxiter < 0:
+ raise ValueError("maxiter must not be set to a negative number"
+ ", use np.inf to mean infinite.")
+
+ # Get Lapack function for cholesky decomposition.
+ # The implemented SciPy wrapper does not return
+ # the incomplete factorization needed by the method.
+ self.cholesky, = get_lapack_funcs(('potrf',), (self.hess,))
+
+ # Get info about Hessian
+ self.dimension = len(self.hess)
+ self.hess_gershgorin_lb,\
+ self.hess_gershgorin_ub = gershgorin_bounds(self.hess)
+ self.hess_inf = norm(self.hess, np.inf)
+ self.hess_fro = norm(self.hess, 'fro')
+
+ # A constant such that for vectors smaller than that
+ # backward substitution is not reliable. It was established
+ # based on Golub, G. H., Van Loan, C. F. (2013).
+ # "Matrix computations". Forth Edition. JHU press., p.165.
+ self.CLOSE_TO_ZERO = self.dimension * self.EPS * self.hess_inf
+
+ def _initial_values(self, tr_radius):
+ """Given a trust radius, return a good initial guess for
+ the damping factor, the lower bound and the upper bound.
+ The values were chosen accordingly to the guidelines on
+ section 7.3.8 (p. 192) from [1]_.
+ """
+
+ # Upper bound for the damping factor
+ lambda_ub = max(0, self.jac_mag/tr_radius + min(-self.hess_gershgorin_lb,
+ self.hess_fro,
+ self.hess_inf))
+
+ # Lower bound for the damping factor
+ lambda_lb = max(0, -min(self.hess.diagonal()),
+ self.jac_mag/tr_radius - min(self.hess_gershgorin_ub,
+ self.hess_fro,
+ self.hess_inf))
+
+ # Improve bounds with previous info
+ if tr_radius < self.previous_tr_radius:
+ lambda_lb = max(self.lambda_lb, lambda_lb)
+
+ # Initial guess for the damping factor
+ if lambda_lb == 0:
+ lambda_initial = 0
+ else:
+ lambda_initial = max(np.sqrt(lambda_lb * lambda_ub),
+ lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb))
+
+ return lambda_initial, lambda_lb, lambda_ub
+
+ def solve(self, tr_radius):
+ """Solve quadratic subproblem"""
+
+ lambda_current, lambda_lb, lambda_ub = self._initial_values(tr_radius)
+ n = self.dimension
+ hits_boundary = True
+ already_factorized = False
+ self.niter = 0
+
+ while self.niter < self.maxiter:
+
+ # Compute Cholesky factorization
+ if already_factorized:
+ already_factorized = False
+ else:
+ H = self.hess+lambda_current*np.eye(n)
+ U, info = self.cholesky(H, lower=False,
+ overwrite_a=False,
+ clean=True)
+
+ self.niter += 1
+
+ # Check if factorization succeeded
+ if info == 0 and self.jac_mag > self.CLOSE_TO_ZERO:
+ # Successful factorization
+
+ # Solve `U.T U p = s`
+ p = cho_solve((U, False), -self.jac)
+
+ p_norm = norm(p)
+
+ # Check for interior convergence
+ if p_norm <= tr_radius and lambda_current == 0:
+ hits_boundary = False
+ break
+
+ # Solve `U.T w = p`
+ w = solve_triangular(U, p, trans='T')
+
+ w_norm = norm(w)
+
+ # Compute Newton step accordingly to
+ # formula (4.44) p.87 from ref [2]_.
+ delta_lambda = (p_norm/w_norm)**2 * (p_norm-tr_radius)/tr_radius
+ lambda_new = lambda_current + delta_lambda
+
+ if p_norm < tr_radius: # Inside boundary
+ s_min, z_min = estimate_smallest_singular_value(U)
+
+ ta, tb = self.get_boundaries_intersections(p, z_min,
+ tr_radius)
+
+ # Choose `step_len` with the smallest magnitude.
+ # The reason for this choice is explained at
+ # ref [3]_, p. 6 (Immediately before the formula
+ # for `tau`).
+ step_len = min([ta, tb], key=abs)
+
+ # Compute the quadratic term (p.T*H*p)
+ quadratic_term = np.dot(p, np.dot(H, p))
+
+ # Check stop criteria
+ relative_error = ((step_len**2 * s_min**2)
+ / (quadratic_term + lambda_current*tr_radius**2))
+ if relative_error <= self.k_hard:
+ p += step_len * z_min
+ break
+
+ # Update uncertainty bounds
+ lambda_ub = lambda_current
+ lambda_lb = max(lambda_lb, lambda_current - s_min**2)
+
+ # Compute Cholesky factorization
+ H = self.hess + lambda_new*np.eye(n)
+ c, info = self.cholesky(H, lower=False,
+ overwrite_a=False,
+ clean=True)
+
+ # Check if the factorization have succeeded
+ #
+ if info == 0: # Successful factorization
+ # Update damping factor
+ lambda_current = lambda_new
+ already_factorized = True
+ else: # Unsuccessful factorization
+ # Update uncertainty bounds
+ lambda_lb = max(lambda_lb, lambda_new)
+
+ # Update damping factor
+ lambda_current = max(
+ np.sqrt(np.abs(lambda_lb * lambda_ub)),
+ lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb)
+ )
+
+ else: # Outside boundary
+ # Check stop criteria
+ relative_error = abs(p_norm - tr_radius) / tr_radius
+ if relative_error <= self.k_easy:
+ break
+
+ # Update uncertainty bounds
+ lambda_lb = lambda_current
+
+ # Update damping factor
+ lambda_current = lambda_new
+
+ elif info == 0 and self.jac_mag <= self.CLOSE_TO_ZERO:
+ # jac_mag very close to zero
+
+ # Check for interior convergence
+ if lambda_current == 0:
+ p = np.zeros(n)
+ hits_boundary = False
+ break
+
+ s_min, z_min = estimate_smallest_singular_value(U)
+ step_len = tr_radius
+
+ p = step_len * z_min
+ # Check stop criteria
+ if (step_len**2 * s_min**2
+ <= self.k_hard * lambda_current * tr_radius**2):
+ break
+
+ # Update uncertainty bounds
+ lambda_ub = lambda_current
+ lambda_lb = max(lambda_lb, lambda_current - s_min**2)
+
+ # Update damping factor
+ lambda_current = max(
+ np.sqrt(lambda_lb * lambda_ub),
+ lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb)
+ )
+
+ else: # Unsuccessful factorization
+
+ # Compute auxiliary terms
+ delta, v = singular_leading_submatrix(H, U, info)
+ v_norm = norm(v)
+
+ # Update uncertainty interval
+ lambda_lb = max(lambda_lb, lambda_current + delta/v_norm**2)
+
+ # Update damping factor
+ lambda_current = max(
+ np.sqrt(np.abs(lambda_lb * lambda_ub)),
+ lambda_lb + self.UPDATE_COEFF*(lambda_ub-lambda_lb)
+ )
+
+ self.lambda_lb = lambda_lb
+ self.lambda_current = lambda_current
+ self.previous_tr_radius = tr_radius
+
+ return p, hits_boundary
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_krylov.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_krylov.py
new file mode 100644
index 0000000000000000000000000000000000000000..54e861ae2de02164966a33c437e5fdb08ba3006c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_krylov.py
@@ -0,0 +1,65 @@
+from ._trustregion import (_minimize_trust_region)
+from ._trlib import (get_trlib_quadratic_subproblem)
+
+__all__ = ['_minimize_trust_krylov']
+
+def _minimize_trust_krylov(fun, x0, args=(), jac=None, hess=None, hessp=None,
+ inexact=True, **trust_region_options):
+ """
+ Minimization of a scalar function of one or more variables using
+ a nearly exact trust-region algorithm that only requires matrix
+ vector products with the hessian matrix.
+
+ .. versionadded:: 1.0.0
+
+ Options
+ -------
+ inexact : bool, optional
+ Accuracy to solve subproblems. If True requires less nonlinear
+ iterations, but more vector products.
+ """
+
+ if jac is None:
+ raise ValueError('Jacobian is required for trust region ',
+ 'exact minimization.')
+ if hess is None and hessp is None:
+ raise ValueError('Either the Hessian or the Hessian-vector product '
+ 'is required for Krylov trust-region minimization')
+
+ # tol_rel specifies the termination tolerance relative to the initial
+ # gradient norm in the Krylov subspace iteration.
+
+ # - tol_rel_i specifies the tolerance for interior convergence.
+ # - tol_rel_b specifies the tolerance for boundary convergence.
+ # in nonlinear programming applications it is not necessary to solve
+ # the boundary case as exact as the interior case.
+
+ # - setting tol_rel_i=-2 leads to a forcing sequence in the Krylov
+ # subspace iteration leading to quadratic convergence if eventually
+ # the trust region stays inactive.
+ # - setting tol_rel_b=-3 leads to a forcing sequence in the Krylov
+ # subspace iteration leading to superlinear convergence as long
+ # as the iterates hit the trust region boundary.
+
+ # For details consult the documentation of trlib_krylov_min
+ # in _trlib/trlib_krylov.h
+ #
+ # Optimality of this choice of parameters among a range of possibilities
+ # has been tested on the unconstrained subset of the CUTEst library.
+
+ if inexact:
+ return _minimize_trust_region(fun, x0, args=args, jac=jac,
+ hess=hess, hessp=hessp,
+ subproblem=get_trlib_quadratic_subproblem(
+ tol_rel_i=-2.0, tol_rel_b=-3.0,
+ disp=trust_region_options.get('disp', False)
+ ),
+ **trust_region_options)
+ else:
+ return _minimize_trust_region(fun, x0, args=args, jac=jac,
+ hess=hess, hessp=hessp,
+ subproblem=get_trlib_quadratic_subproblem(
+ tol_rel_i=1e-8, tol_rel_b=1e-6,
+ disp=trust_region_options.get('disp', False)
+ ),
+ **trust_region_options)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_ncg.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_ncg.py
new file mode 100644
index 0000000000000000000000000000000000000000..fed17ff8b84eaf019c0ad69a03f260ca674477ad
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_trustregion_ncg.py
@@ -0,0 +1,126 @@
+"""Newton-CG trust-region optimization."""
+import math
+
+import numpy as np
+import scipy.linalg
+from ._trustregion import (_minimize_trust_region, BaseQuadraticSubproblem)
+
+__all__ = []
+
+
+def _minimize_trust_ncg(fun, x0, args=(), jac=None, hess=None, hessp=None,
+ **trust_region_options):
+ """
+ Minimization of scalar function of one or more variables using
+ the Newton conjugate gradient trust-region algorithm.
+
+ Options
+ -------
+ initial_trust_radius : float
+ Initial trust-region radius.
+ max_trust_radius : float
+ Maximum value of the trust-region radius. No steps that are longer
+ than this value will be proposed.
+ eta : float
+ Trust region related acceptance stringency for proposed steps.
+ gtol : float
+ Gradient norm must be less than `gtol` before successful
+ termination.
+
+ """
+ if jac is None:
+ raise ValueError('Jacobian is required for Newton-CG trust-region '
+ 'minimization')
+ if hess is None and hessp is None:
+ raise ValueError('Either the Hessian or the Hessian-vector product '
+ 'is required for Newton-CG trust-region minimization')
+ return _minimize_trust_region(fun, x0, args=args, jac=jac, hess=hess,
+ hessp=hessp, subproblem=CGSteihaugSubproblem,
+ **trust_region_options)
+
+
+class CGSteihaugSubproblem(BaseQuadraticSubproblem):
+ """Quadratic subproblem solved by a conjugate gradient method"""
+ def solve(self, trust_radius):
+ """
+ Solve the subproblem using a conjugate gradient method.
+
+ Parameters
+ ----------
+ trust_radius : float
+ We are allowed to wander only this far away from the origin.
+
+ Returns
+ -------
+ p : ndarray
+ The proposed step.
+ hits_boundary : bool
+ True if the proposed step is on the boundary of the trust region.
+
+ Notes
+ -----
+ This is algorithm (7.2) of Nocedal and Wright 2nd edition.
+ Only the function that computes the Hessian-vector product is required.
+ The Hessian itself is not required, and the Hessian does
+ not need to be positive semidefinite.
+ """
+
+ # get the norm of jacobian and define the origin
+ p_origin = np.zeros_like(self.jac)
+
+ # define a default tolerance
+ tolerance = min(0.5, math.sqrt(self.jac_mag)) * self.jac_mag
+
+ # Stop the method if the search direction
+ # is a direction of nonpositive curvature.
+ if self.jac_mag < tolerance:
+ hits_boundary = False
+ return p_origin, hits_boundary
+
+ # init the state for the first iteration
+ z = p_origin
+ r = self.jac
+ d = -r
+
+ # Search for the min of the approximation of the objective function.
+ while True:
+
+ # do an iteration
+ Bd = self.hessp(d)
+ dBd = np.dot(d, Bd)
+ if dBd <= 0:
+ # Look at the two boundary points.
+ # Find both values of t to get the boundary points such that
+ # ||z + t d|| == trust_radius
+ # and then choose the one with the predicted min value.
+ ta, tb = self.get_boundaries_intersections(z, d, trust_radius)
+ pa = z + ta * d
+ pb = z + tb * d
+ if self(pa) < self(pb):
+ p_boundary = pa
+ else:
+ p_boundary = pb
+ hits_boundary = True
+ return p_boundary, hits_boundary
+ r_squared = np.dot(r, r)
+ alpha = r_squared / dBd
+ z_next = z + alpha * d
+ if scipy.linalg.norm(z_next) >= trust_radius:
+ # Find t >= 0 to get the boundary point such that
+ # ||z + t d|| == trust_radius
+ ta, tb = self.get_boundaries_intersections(z, d, trust_radius)
+ p_boundary = z + tb * d
+ hits_boundary = True
+ return p_boundary, hits_boundary
+ r_next = r + alpha * Bd
+ r_next_squared = np.dot(r_next, r_next)
+ if math.sqrt(r_next_squared) < tolerance:
+ hits_boundary = False
+ return z_next, hits_boundary
+ beta_next = r_next_squared / r_squared
+ d_next = -r_next + beta_next * d
+
+ # update the state for the next iteration
+ z = z_next
+ r = r_next
+ d = d_next
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_tstutils.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_tstutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..f56e835e345d66023efae81114a45ed29269f18d
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_tstutils.py
@@ -0,0 +1,972 @@
+r"""
+Parameters used in test and benchmark methods.
+
+Collections of test cases suitable for testing 1-D root-finders
+ 'original': The original benchmarking functions.
+ Real-valued functions of real-valued inputs on an interval
+ with a zero.
+ f1, .., f3 are continuous and infinitely differentiable
+ f4 has a left- and right- discontinuity at the root
+ f5 has a root at 1 replacing a 1st order pole
+ f6 is randomly positive on one side of the root,
+ randomly negative on the other.
+ f4 - f6 are not continuous at the root.
+
+ 'aps': The test problems in the 1995 paper
+ TOMS "Algorithm 748: Enclosing Zeros of Continuous Functions"
+ by Alefeld, Potra and Shi. Real-valued functions of
+ real-valued inputs on an interval with a zero.
+ Suitable for methods which start with an enclosing interval, and
+ derivatives up to 2nd order.
+
+ 'complex': Some complex-valued functions of complex-valued inputs.
+ No enclosing bracket is provided.
+ Suitable for methods which use one or more starting values, and
+ derivatives up to 2nd order.
+
+ The test cases are provided as a list of dictionaries. The dictionary
+ keys will be a subset of:
+ ["f", "fprime", "fprime2", "args", "bracket", "smoothness",
+ "a", "b", "x0", "x1", "root", "ID"]
+"""
+
+# Sources:
+# [1] Alefeld, G. E. and Potra, F. A. and Shi, Yixun,
+# "Algorithm 748: Enclosing Zeros of Continuous Functions",
+# ACM Trans. Math. Softw. Volume 221(1995)
+# doi = {10.1145/210089.210111},
+# [2] Chandrupatla, Tirupathi R. "A new hybrid quadratic/bisection algorithm
+# for finding the zero of a nonlinear function without using derivatives."
+# Advances in Engineering Software 28.3 (1997): 145-149.
+
+from random import random
+
+import numpy as np
+
+from scipy.optimize import _zeros_py as cc
+from scipy._lib._array_api import array_namespace
+
+# "description" refers to the original functions
+description = """
+f2 is a symmetric parabola, x**2 - 1
+f3 is a quartic polynomial with large hump in interval
+f4 is step function with a discontinuity at 1
+f5 is a hyperbola with vertical asymptote at 1
+f6 has random values positive to left of 1, negative to right
+
+Of course, these are not real problems. They just test how the
+'good' solvers behave in bad circumstances where bisection is
+really the best. A good solver should not be much worse than
+bisection in such circumstance, while being faster for smooth
+monotone sorts of functions.
+"""
+
+
+def f1(x):
+ r"""f1 is a quadratic with roots at 0 and 1"""
+ return x * (x - 1.)
+
+
+def f1_fp(x):
+ return 2 * x - 1
+
+
+def f1_fpp(x):
+ return 2
+
+
+def f2(x):
+ r"""f2 is a symmetric parabola, x**2 - 1"""
+ return x**2 - 1
+
+
+def f2_fp(x):
+ return 2 * x
+
+
+def f2_fpp(x):
+ return 2
+
+
+def f3(x):
+ r"""A quartic with roots at 0, 1, 2 and 3"""
+ return x * (x - 1.) * (x - 2.) * (x - 3.) # x**4 - 6x**3 + 11x**2 - 6x
+
+
+def f3_fp(x):
+ return 4 * x**3 - 18 * x**2 + 22 * x - 6
+
+
+def f3_fpp(x):
+ return 12 * x**2 - 36 * x + 22
+
+
+def f4(x):
+ r"""Piecewise linear, left- and right- discontinuous at x=1, the root."""
+ if x > 1:
+ return 1.0 + .1 * x
+ if x < 1:
+ return -1.0 + .1 * x
+ return 0
+
+
+def f5(x):
+ r"""
+ Hyperbola with a pole at x=1, but pole replaced with 0. Not continuous at root.
+ """
+ if x != 1:
+ return 1.0 / (1. - x)
+ return 0
+
+
+# f6(x) returns random value. Without memoization, calling twice with the
+# same x returns different values, hence a "random value", not a
+# "function with random values"
+_f6_cache = {}
+def f6(x):
+ v = _f6_cache.get(x, None)
+ if v is None:
+ if x > 1:
+ v = random()
+ elif x < 1:
+ v = -random()
+ else:
+ v = 0
+ _f6_cache[x] = v
+ return v
+
+
+# Each Original test case has
+# - a function and its two derivatives,
+# - additional arguments,
+# - a bracket enclosing a root,
+# - the order of differentiability (smoothness) on this interval
+# - a starting value for methods which don't require a bracket
+# - the root (inside the bracket)
+# - an Identifier of the test case
+
+_ORIGINAL_TESTS_KEYS = [
+ "f", "fprime", "fprime2", "args", "bracket", "smoothness", "x0", "root", "ID"
+]
+_ORIGINAL_TESTS = [
+ [f1, f1_fp, f1_fpp, (), [0.5, np.sqrt(3)], np.inf, 0.6, 1.0, "original.01.00"],
+ [f2, f2_fp, f2_fpp, (), [0.5, np.sqrt(3)], np.inf, 0.6, 1.0, "original.02.00"],
+ [f3, f3_fp, f3_fpp, (), [0.5, np.sqrt(3)], np.inf, 0.6, 1.0, "original.03.00"],
+ [f4, None, None, (), [0.5, np.sqrt(3)], -1, 0.6, 1.0, "original.04.00"],
+ [f5, None, None, (), [0.5, np.sqrt(3)], -1, 0.6, 1.0, "original.05.00"],
+ [f6, None, None, (), [0.5, np.sqrt(3)], -np.inf, 0.6, 1.0, "original.05.00"]
+]
+
+_ORIGINAL_TESTS_DICTS = [
+ dict(zip(_ORIGINAL_TESTS_KEYS, testcase)) for testcase in _ORIGINAL_TESTS
+]
+
+# ##################
+# "APS" test cases
+# Functions and test cases that appear in [1]
+
+
+def aps01_f(x):
+ r"""Straightforward sum of trigonometric function and polynomial"""
+ return np.sin(x) - x / 2
+
+
+def aps01_fp(x):
+ return np.cos(x) - 1.0 / 2
+
+
+def aps01_fpp(x):
+ return -np.sin(x)
+
+
+def aps02_f(x):
+ r"""poles at x=n**2, 1st and 2nd derivatives at root are also close to 0"""
+ ii = np.arange(1, 21)
+ return -2 * np.sum((2 * ii - 5)**2 / (x - ii**2)**3)
+
+
+def aps02_fp(x):
+ ii = np.arange(1, 21)
+ return 6 * np.sum((2 * ii - 5)**2 / (x - ii**2)**4)
+
+
+def aps02_fpp(x):
+ ii = np.arange(1, 21)
+ return 24 * np.sum((2 * ii - 5)**2 / (x - ii**2)**5)
+
+
+def aps03_f(x, a, b):
+ r"""Rapidly changing at the root"""
+ return a * x * np.exp(b * x)
+
+
+def aps03_fp(x, a, b):
+ return a * (b * x + 1) * np.exp(b * x)
+
+
+def aps03_fpp(x, a, b):
+ return a * (b * (b * x + 1) + b) * np.exp(b * x)
+
+
+def aps04_f(x, n, a):
+ r"""Medium-degree polynomial"""
+ return x**n - a
+
+
+def aps04_fp(x, n, a):
+ return n * x**(n - 1)
+
+
+def aps04_fpp(x, n, a):
+ return n * (n - 1) * x**(n - 2)
+
+
+def aps05_f(x):
+ r"""Simple Trigonometric function"""
+ return np.sin(x) - 1.0 / 2
+
+
+def aps05_fp(x):
+ return np.cos(x)
+
+
+def aps05_fpp(x):
+ return -np.sin(x)
+
+
+def aps06_f(x, n):
+ r"""Exponential rapidly changing from -1 to 1 at x=0"""
+ return 2 * x * np.exp(-n) - 2 * np.exp(-n * x) + 1
+
+
+def aps06_fp(x, n):
+ return 2 * np.exp(-n) + 2 * n * np.exp(-n * x)
+
+
+def aps06_fpp(x, n):
+ return -2 * n * n * np.exp(-n * x)
+
+
+def aps07_f(x, n):
+ r"""Upside down parabola with parametrizable height"""
+ return (1 + (1 - n)**2) * x - (1 - n * x)**2
+
+
+def aps07_fp(x, n):
+ return (1 + (1 - n)**2) + 2 * n * (1 - n * x)
+
+
+def aps07_fpp(x, n):
+ return -2 * n * n
+
+
+def aps08_f(x, n):
+ r"""Degree n polynomial"""
+ return x * x - (1 - x)**n
+
+
+def aps08_fp(x, n):
+ return 2 * x + n * (1 - x)**(n - 1)
+
+
+def aps08_fpp(x, n):
+ return 2 - n * (n - 1) * (1 - x)**(n - 2)
+
+
+def aps09_f(x, n):
+ r"""Upside down quartic with parametrizable height"""
+ return (1 + (1 - n)**4) * x - (1 - n * x)**4
+
+
+def aps09_fp(x, n):
+ return (1 + (1 - n)**4) + 4 * n * (1 - n * x)**3
+
+
+def aps09_fpp(x, n):
+ return -12 * n * (1 - n * x)**2
+
+
+def aps10_f(x, n):
+ r"""Exponential plus a polynomial"""
+ return np.exp(-n * x) * (x - 1) + x**n
+
+
+def aps10_fp(x, n):
+ return np.exp(-n * x) * (-n * (x - 1) + 1) + n * x**(n - 1)
+
+
+def aps10_fpp(x, n):
+ return (np.exp(-n * x) * (-n * (-n * (x - 1) + 1) + -n * x)
+ + n * (n - 1) * x**(n - 2))
+
+
+def aps11_f(x, n):
+ r"""Rational function with a zero at x=1/n and a pole at x=0"""
+ return (n * x - 1) / ((n - 1) * x)
+
+
+def aps11_fp(x, n):
+ return 1 / (n - 1) / x**2
+
+
+def aps11_fpp(x, n):
+ return -2 / (n - 1) / x**3
+
+
+def aps12_f(x, n):
+ r"""nth root of x, with a zero at x=n"""
+ return np.power(x, 1.0 / n) - np.power(n, 1.0 / n)
+
+
+def aps12_fp(x, n):
+ return np.power(x, (1.0 - n) / n) / n
+
+
+def aps12_fpp(x, n):
+ return np.power(x, (1.0 - 2 * n) / n) * (1.0 / n) * (1.0 - n) / n
+
+
+_MAX_EXPABLE = np.log(np.finfo(float).max)
+
+
+def aps13_f(x):
+ r"""Function with *all* derivatives 0 at the root"""
+ if x == 0:
+ return 0
+ # x2 = 1.0/x**2
+ # if x2 > 708:
+ # return 0
+ y = 1 / x**2
+ if y > _MAX_EXPABLE:
+ return 0
+ return x / np.exp(y)
+
+
+def aps13_fp(x):
+ if x == 0:
+ return 0
+ y = 1 / x**2
+ if y > _MAX_EXPABLE:
+ return 0
+ return (1 + 2 / x**2) / np.exp(y)
+
+
+def aps13_fpp(x):
+ if x == 0:
+ return 0
+ y = 1 / x**2
+ if y > _MAX_EXPABLE:
+ return 0
+ return 2 * (2 - x**2) / x**5 / np.exp(y)
+
+
+def aps14_f(x, n):
+ r"""0 for negative x-values, trigonometric+linear for x positive"""
+ if x <= 0:
+ return -n / 20.0
+ return n / 20.0 * (x / 1.5 + np.sin(x) - 1)
+
+
+def aps14_fp(x, n):
+ if x <= 0:
+ return 0
+ return n / 20.0 * (1.0 / 1.5 + np.cos(x))
+
+
+def aps14_fpp(x, n):
+ if x <= 0:
+ return 0
+ return -n / 20.0 * (np.sin(x))
+
+
+def aps15_f(x, n):
+ r"""piecewise linear, constant outside of [0, 0.002/(1+n)]"""
+ if x < 0:
+ return -0.859
+ if x > 2 * 1e-3 / (1 + n):
+ return np.e - 1.859
+ return np.exp((n + 1) * x / 2 * 1000) - 1.859
+
+
+def aps15_fp(x, n):
+ if not 0 <= x <= 2 * 1e-3 / (1 + n):
+ return np.e - 1.859
+ return np.exp((n + 1) * x / 2 * 1000) * (n + 1) / 2 * 1000
+
+
+def aps15_fpp(x, n):
+ if not 0 <= x <= 2 * 1e-3 / (1 + n):
+ return np.e - 1.859
+ return np.exp((n + 1) * x / 2 * 1000) * (n + 1) / 2 * 1000 * (n + 1) / 2 * 1000
+
+
+# Each APS test case has
+# - a function and its two derivatives,
+# - additional arguments,
+# - a bracket enclosing a root,
+# - the order of differentiability of the function on this interval
+# - a starting value for methods which don't require a bracket
+# - the root (inside the bracket)
+# - an Identifier of the test case
+#
+# Algorithm 748 is a bracketing algorithm so a bracketing interval was provided
+# in [1] for each test case. Newton and Halley methods need a single
+# starting point x0, which was chosen to be near the middle of the interval,
+# unless that would have made the problem too easy.
+
+_APS_TESTS_KEYS = [
+ "f", "fprime", "fprime2", "args", "bracket", "smoothness", "x0", "root", "ID"
+]
+_APS_TESTS = [
+ [aps01_f, aps01_fp, aps01_fpp, (), [np.pi / 2, np.pi], np.inf,
+ 3, 1.89549426703398094e+00, "aps.01.00"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [1 + 1e-9, 4 - 1e-9], np.inf,
+ 2, 3.02291534727305677e+00, "aps.02.00"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [4 + 1e-9, 9 - 1e-9], np.inf,
+ 5, 6.68375356080807848e+00, "aps.02.01"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [9 + 1e-9, 16 - 1e-9], np.inf,
+ 10, 1.12387016550022114e+01, "aps.02.02"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [16 + 1e-9, 25 - 1e-9], np.inf,
+ 17, 1.96760000806234103e+01, "aps.02.03"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [25 + 1e-9, 36 - 1e-9], np.inf,
+ 26, 2.98282273265047557e+01, "aps.02.04"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [36 + 1e-9, 49 - 1e-9], np.inf,
+ 37, 4.19061161952894139e+01, "aps.02.05"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [49 + 1e-9, 64 - 1e-9], np.inf,
+ 50, 5.59535958001430913e+01, "aps.02.06"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [64 + 1e-9, 81 - 1e-9], np.inf,
+ 65, 7.19856655865877997e+01, "aps.02.07"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [81 + 1e-9, 100 - 1e-9], np.inf,
+ 82, 9.00088685391666701e+01, "aps.02.08"],
+ [aps02_f, aps02_fp, aps02_fpp, (), [100 + 1e-9, 121 - 1e-9], np.inf,
+ 101, 1.10026532748330197e+02, "aps.02.09"],
+ [aps03_f, aps03_fp, aps03_fpp, (-40, -1), [-9, 31], np.inf,
+ -2, 0, "aps.03.00"],
+ [aps03_f, aps03_fp, aps03_fpp, (-100, -2), [-9, 31], np.inf,
+ -2, 0, "aps.03.01"],
+ [aps03_f, aps03_fp, aps03_fpp, (-200, -3), [-9, 31], np.inf,
+ -2, 0, "aps.03.02"],
+ [aps04_f, aps04_fp, aps04_fpp, (4, 0.2), [0, 5], np.inf,
+ 2.5, 6.68740304976422006e-01, "aps.04.00"],
+ [aps04_f, aps04_fp, aps04_fpp, (6, 0.2), [0, 5], np.inf,
+ 2.5, 7.64724491331730039e-01, "aps.04.01"],
+ [aps04_f, aps04_fp, aps04_fpp, (8, 0.2), [0, 5], np.inf,
+ 2.5, 8.17765433957942545e-01, "aps.04.02"],
+ [aps04_f, aps04_fp, aps04_fpp, (10, 0.2), [0, 5], np.inf,
+ 2.5, 8.51339922520784609e-01, "aps.04.03"],
+ [aps04_f, aps04_fp, aps04_fpp, (12, 0.2), [0, 5], np.inf,
+ 2.5, 8.74485272221167897e-01, "aps.04.04"],
+ [aps04_f, aps04_fp, aps04_fpp, (4, 1), [0, 5], np.inf,
+ 2.5, 1, "aps.04.05"],
+ [aps04_f, aps04_fp, aps04_fpp, (6, 1), [0, 5], np.inf,
+ 2.5, 1, "aps.04.06"],
+ [aps04_f, aps04_fp, aps04_fpp, (8, 1), [0, 5], np.inf,
+ 2.5, 1, "aps.04.07"],
+ [aps04_f, aps04_fp, aps04_fpp, (10, 1), [0, 5], np.inf,
+ 2.5, 1, "aps.04.08"],
+ [aps04_f, aps04_fp, aps04_fpp, (12, 1), [0, 5], np.inf,
+ 2.5, 1, "aps.04.09"],
+ [aps04_f, aps04_fp, aps04_fpp, (8, 1), [-0.95, 4.05], np.inf,
+ 1.5, 1, "aps.04.10"],
+ [aps04_f, aps04_fp, aps04_fpp, (10, 1), [-0.95, 4.05], np.inf,
+ 1.5, 1, "aps.04.11"],
+ [aps04_f, aps04_fp, aps04_fpp, (12, 1), [-0.95, 4.05], np.inf,
+ 1.5, 1, "aps.04.12"],
+ [aps04_f, aps04_fp, aps04_fpp, (14, 1), [-0.95, 4.05], np.inf,
+ 1.5, 1, "aps.04.13"],
+ [aps05_f, aps05_fp, aps05_fpp, (), [0, 1.5], np.inf,
+ 1.3, np.pi / 6, "aps.05.00"],
+ [aps06_f, aps06_fp, aps06_fpp, (1,), [0, 1], np.inf,
+ 0.5, 4.22477709641236709e-01, "aps.06.00"],
+ [aps06_f, aps06_fp, aps06_fpp, (2,), [0, 1], np.inf,
+ 0.5, 3.06699410483203705e-01, "aps.06.01"],
+ [aps06_f, aps06_fp, aps06_fpp, (3,), [0, 1], np.inf,
+ 0.5, 2.23705457654662959e-01, "aps.06.02"],
+ [aps06_f, aps06_fp, aps06_fpp, (4,), [0, 1], np.inf,
+ 0.5, 1.71719147519508369e-01, "aps.06.03"],
+ [aps06_f, aps06_fp, aps06_fpp, (5,), [0, 1], np.inf,
+ 0.4, 1.38257155056824066e-01, "aps.06.04"],
+ [aps06_f, aps06_fp, aps06_fpp, (20,), [0, 1], np.inf,
+ 0.1, 3.46573590208538521e-02, "aps.06.05"],
+ [aps06_f, aps06_fp, aps06_fpp, (40,), [0, 1], np.inf,
+ 5e-02, 1.73286795139986315e-02, "aps.06.06"],
+ [aps06_f, aps06_fp, aps06_fpp, (60,), [0, 1], np.inf,
+ 1.0 / 30, 1.15524530093324210e-02, "aps.06.07"],
+ [aps06_f, aps06_fp, aps06_fpp, (80,), [0, 1], np.inf,
+ 2.5e-02, 8.66433975699931573e-03, "aps.06.08"],
+ [aps06_f, aps06_fp, aps06_fpp, (100,), [0, 1], np.inf,
+ 2e-02, 6.93147180559945415e-03, "aps.06.09"],
+ [aps07_f, aps07_fp, aps07_fpp, (5,), [0, 1], np.inf,
+ 0.4, 3.84025518406218985e-02, "aps.07.00"],
+ [aps07_f, aps07_fp, aps07_fpp, (10,), [0, 1], np.inf,
+ 0.4, 9.90000999800049949e-03, "aps.07.01"],
+ [aps07_f, aps07_fp, aps07_fpp, (20,), [0, 1], np.inf,
+ 0.4, 2.49375003906201174e-03, "aps.07.02"],
+ [aps08_f, aps08_fp, aps08_fpp, (2,), [0, 1], np.inf,
+ 0.9, 0.5, "aps.08.00"],
+ [aps08_f, aps08_fp, aps08_fpp, (5,), [0, 1], np.inf,
+ 0.9, 3.45954815848242059e-01, "aps.08.01"],
+ [aps08_f, aps08_fp, aps08_fpp, (10,), [0, 1], np.inf,
+ 0.9, 2.45122333753307220e-01, "aps.08.02"],
+ [aps08_f, aps08_fp, aps08_fpp, (15,), [0, 1], np.inf,
+ 0.9, 1.95547623536565629e-01, "aps.08.03"],
+ [aps08_f, aps08_fp, aps08_fpp, (20,), [0, 1], np.inf,
+ 0.9, 1.64920957276440960e-01, "aps.08.04"],
+ [aps09_f, aps09_fp, aps09_fpp, (1,), [0, 1], np.inf,
+ 0.5, 2.75508040999484394e-01, "aps.09.00"],
+ [aps09_f, aps09_fp, aps09_fpp, (2,), [0, 1], np.inf,
+ 0.5, 1.37754020499742197e-01, "aps.09.01"],
+ [aps09_f, aps09_fp, aps09_fpp, (4,), [0, 1], np.inf,
+ 0.5, 1.03052837781564422e-02, "aps.09.02"],
+ [aps09_f, aps09_fp, aps09_fpp, (5,), [0, 1], np.inf,
+ 0.5, 3.61710817890406339e-03, "aps.09.03"],
+ [aps09_f, aps09_fp, aps09_fpp, (8,), [0, 1], np.inf,
+ 0.5, 4.10872918496395375e-04, "aps.09.04"],
+ [aps09_f, aps09_fp, aps09_fpp, (15,), [0, 1], np.inf,
+ 0.5, 2.59895758929076292e-05, "aps.09.05"],
+ [aps09_f, aps09_fp, aps09_fpp, (20,), [0, 1], np.inf,
+ 0.5, 7.66859512218533719e-06, "aps.09.06"],
+ [aps10_f, aps10_fp, aps10_fpp, (1,), [0, 1], np.inf,
+ 0.9, 4.01058137541547011e-01, "aps.10.00"],
+ [aps10_f, aps10_fp, aps10_fpp, (5,), [0, 1], np.inf,
+ 0.9, 5.16153518757933583e-01, "aps.10.01"],
+ [aps10_f, aps10_fp, aps10_fpp, (10,), [0, 1], np.inf,
+ 0.9, 5.39522226908415781e-01, "aps.10.02"],
+ [aps10_f, aps10_fp, aps10_fpp, (15,), [0, 1], np.inf,
+ 0.9, 5.48182294340655241e-01, "aps.10.03"],
+ [aps10_f, aps10_fp, aps10_fpp, (20,), [0, 1], np.inf,
+ 0.9, 5.52704666678487833e-01, "aps.10.04"],
+ [aps11_f, aps11_fp, aps11_fpp, (2,), [0.01, 1], np.inf,
+ 1e-02, 1.0 / 2, "aps.11.00"],
+ [aps11_f, aps11_fp, aps11_fpp, (5,), [0.01, 1], np.inf,
+ 1e-02, 1.0 / 5, "aps.11.01"],
+ [aps11_f, aps11_fp, aps11_fpp, (15,), [0.01, 1], np.inf,
+ 1e-02, 1.0 / 15, "aps.11.02"],
+ [aps11_f, aps11_fp, aps11_fpp, (20,), [0.01, 1], np.inf,
+ 1e-02, 1.0 / 20, "aps.11.03"],
+ [aps12_f, aps12_fp, aps12_fpp, (2,), [1, 100], np.inf,
+ 1.1, 2, "aps.12.00"],
+ [aps12_f, aps12_fp, aps12_fpp, (3,), [1, 100], np.inf,
+ 1.1, 3, "aps.12.01"],
+ [aps12_f, aps12_fp, aps12_fpp, (4,), [1, 100], np.inf,
+ 1.1, 4, "aps.12.02"],
+ [aps12_f, aps12_fp, aps12_fpp, (5,), [1, 100], np.inf,
+ 1.1, 5, "aps.12.03"],
+ [aps12_f, aps12_fp, aps12_fpp, (6,), [1, 100], np.inf,
+ 1.1, 6, "aps.12.04"],
+ [aps12_f, aps12_fp, aps12_fpp, (7,), [1, 100], np.inf,
+ 1.1, 7, "aps.12.05"],
+ [aps12_f, aps12_fp, aps12_fpp, (9,), [1, 100], np.inf,
+ 1.1, 9, "aps.12.06"],
+ [aps12_f, aps12_fp, aps12_fpp, (11,), [1, 100], np.inf,
+ 1.1, 11, "aps.12.07"],
+ [aps12_f, aps12_fp, aps12_fpp, (13,), [1, 100], np.inf,
+ 1.1, 13, "aps.12.08"],
+ [aps12_f, aps12_fp, aps12_fpp, (15,), [1, 100], np.inf,
+ 1.1, 15, "aps.12.09"],
+ [aps12_f, aps12_fp, aps12_fpp, (17,), [1, 100], np.inf,
+ 1.1, 17, "aps.12.10"],
+ [aps12_f, aps12_fp, aps12_fpp, (19,), [1, 100], np.inf,
+ 1.1, 19, "aps.12.11"],
+ [aps12_f, aps12_fp, aps12_fpp, (21,), [1, 100], np.inf,
+ 1.1, 21, "aps.12.12"],
+ [aps12_f, aps12_fp, aps12_fpp, (23,), [1, 100], np.inf,
+ 1.1, 23, "aps.12.13"],
+ [aps12_f, aps12_fp, aps12_fpp, (25,), [1, 100], np.inf,
+ 1.1, 25, "aps.12.14"],
+ [aps12_f, aps12_fp, aps12_fpp, (27,), [1, 100], np.inf,
+ 1.1, 27, "aps.12.15"],
+ [aps12_f, aps12_fp, aps12_fpp, (29,), [1, 100], np.inf,
+ 1.1, 29, "aps.12.16"],
+ [aps12_f, aps12_fp, aps12_fpp, (31,), [1, 100], np.inf,
+ 1.1, 31, "aps.12.17"],
+ [aps12_f, aps12_fp, aps12_fpp, (33,), [1, 100], np.inf,
+ 1.1, 33, "aps.12.18"],
+ [aps13_f, aps13_fp, aps13_fpp, (), [-1, 4], np.inf,
+ 1.5, 0, "aps.13.00"],
+ [aps14_f, aps14_fp, aps14_fpp, (1,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.00"],
+ [aps14_f, aps14_fp, aps14_fpp, (2,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.01"],
+ [aps14_f, aps14_fp, aps14_fpp, (3,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.02"],
+ [aps14_f, aps14_fp, aps14_fpp, (4,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.03"],
+ [aps14_f, aps14_fp, aps14_fpp, (5,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.04"],
+ [aps14_f, aps14_fp, aps14_fpp, (6,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.05"],
+ [aps14_f, aps14_fp, aps14_fpp, (7,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.06"],
+ [aps14_f, aps14_fp, aps14_fpp, (8,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.07"],
+ [aps14_f, aps14_fp, aps14_fpp, (9,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.08"],
+ [aps14_f, aps14_fp, aps14_fpp, (10,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.09"],
+ [aps14_f, aps14_fp, aps14_fpp, (11,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.10"],
+ [aps14_f, aps14_fp, aps14_fpp, (12,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.11"],
+ [aps14_f, aps14_fp, aps14_fpp, (13,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.12"],
+ [aps14_f, aps14_fp, aps14_fpp, (14,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.13"],
+ [aps14_f, aps14_fp, aps14_fpp, (15,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.14"],
+ [aps14_f, aps14_fp, aps14_fpp, (16,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.15"],
+ [aps14_f, aps14_fp, aps14_fpp, (17,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.16"],
+ [aps14_f, aps14_fp, aps14_fpp, (18,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.17"],
+ [aps14_f, aps14_fp, aps14_fpp, (19,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.18"],
+ [aps14_f, aps14_fp, aps14_fpp, (20,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.19"],
+ [aps14_f, aps14_fp, aps14_fpp, (21,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.20"],
+ [aps14_f, aps14_fp, aps14_fpp, (22,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.21"],
+ [aps14_f, aps14_fp, aps14_fpp, (23,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.22"],
+ [aps14_f, aps14_fp, aps14_fpp, (24,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.23"],
+ [aps14_f, aps14_fp, aps14_fpp, (25,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.24"],
+ [aps14_f, aps14_fp, aps14_fpp, (26,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.25"],
+ [aps14_f, aps14_fp, aps14_fpp, (27,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.26"],
+ [aps14_f, aps14_fp, aps14_fpp, (28,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.27"],
+ [aps14_f, aps14_fp, aps14_fpp, (29,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.28"],
+ [aps14_f, aps14_fp, aps14_fpp, (30,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.29"],
+ [aps14_f, aps14_fp, aps14_fpp, (31,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.30"],
+ [aps14_f, aps14_fp, aps14_fpp, (32,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.31"],
+ [aps14_f, aps14_fp, aps14_fpp, (33,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.32"],
+ [aps14_f, aps14_fp, aps14_fpp, (34,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.33"],
+ [aps14_f, aps14_fp, aps14_fpp, (35,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.34"],
+ [aps14_f, aps14_fp, aps14_fpp, (36,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.35"],
+ [aps14_f, aps14_fp, aps14_fpp, (37,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.36"],
+ [aps14_f, aps14_fp, aps14_fpp, (38,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.37"],
+ [aps14_f, aps14_fp, aps14_fpp, (39,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.38"],
+ [aps14_f, aps14_fp, aps14_fpp, (40,), [-1000, np.pi / 2], 0,
+ 1, 6.23806518961612433e-01, "aps.14.39"],
+ [aps15_f, aps15_fp, aps15_fpp, (20,), [-1000, 1e-4], 0,
+ -2, 5.90513055942197166e-05, "aps.15.00"],
+ [aps15_f, aps15_fp, aps15_fpp, (21,), [-1000, 1e-4], 0,
+ -2, 5.63671553399369967e-05, "aps.15.01"],
+ [aps15_f, aps15_fp, aps15_fpp, (22,), [-1000, 1e-4], 0,
+ -2, 5.39164094555919196e-05, "aps.15.02"],
+ [aps15_f, aps15_fp, aps15_fpp, (23,), [-1000, 1e-4], 0,
+ -2, 5.16698923949422470e-05, "aps.15.03"],
+ [aps15_f, aps15_fp, aps15_fpp, (24,), [-1000, 1e-4], 0,
+ -2, 4.96030966991445609e-05, "aps.15.04"],
+ [aps15_f, aps15_fp, aps15_fpp, (25,), [-1000, 1e-4], 0,
+ -2, 4.76952852876389951e-05, "aps.15.05"],
+ [aps15_f, aps15_fp, aps15_fpp, (26,), [-1000, 1e-4], 0,
+ -2, 4.59287932399486662e-05, "aps.15.06"],
+ [aps15_f, aps15_fp, aps15_fpp, (27,), [-1000, 1e-4], 0,
+ -2, 4.42884791956647841e-05, "aps.15.07"],
+ [aps15_f, aps15_fp, aps15_fpp, (28,), [-1000, 1e-4], 0,
+ -2, 4.27612902578832391e-05, "aps.15.08"],
+ [aps15_f, aps15_fp, aps15_fpp, (29,), [-1000, 1e-4], 0,
+ -2, 4.13359139159538030e-05, "aps.15.09"],
+ [aps15_f, aps15_fp, aps15_fpp, (30,), [-1000, 1e-4], 0,
+ -2, 4.00024973380198076e-05, "aps.15.10"],
+ [aps15_f, aps15_fp, aps15_fpp, (31,), [-1000, 1e-4], 0,
+ -2, 3.87524192962066869e-05, "aps.15.11"],
+ [aps15_f, aps15_fp, aps15_fpp, (32,), [-1000, 1e-4], 0,
+ -2, 3.75781035599579910e-05, "aps.15.12"],
+ [aps15_f, aps15_fp, aps15_fpp, (33,), [-1000, 1e-4], 0,
+ -2, 3.64728652199592355e-05, "aps.15.13"],
+ [aps15_f, aps15_fp, aps15_fpp, (34,), [-1000, 1e-4], 0,
+ -2, 3.54307833565318273e-05, "aps.15.14"],
+ [aps15_f, aps15_fp, aps15_fpp, (35,), [-1000, 1e-4], 0,
+ -2, 3.44465949299614980e-05, "aps.15.15"],
+ [aps15_f, aps15_fp, aps15_fpp, (36,), [-1000, 1e-4], 0,
+ -2, 3.35156058778003705e-05, "aps.15.16"],
+ [aps15_f, aps15_fp, aps15_fpp, (37,), [-1000, 1e-4], 0,
+ -2, 3.26336162494372125e-05, "aps.15.17"],
+ [aps15_f, aps15_fp, aps15_fpp, (38,), [-1000, 1e-4], 0,
+ -2, 3.17968568584260013e-05, "aps.15.18"],
+ [aps15_f, aps15_fp, aps15_fpp, (39,), [-1000, 1e-4], 0,
+ -2, 3.10019354369653455e-05, "aps.15.19"],
+ [aps15_f, aps15_fp, aps15_fpp, (40,), [-1000, 1e-4], 0,
+ -2, 3.02457906702100968e-05, "aps.15.20"],
+ [aps15_f, aps15_fp, aps15_fpp, (100,), [-1000, 1e-4], 0,
+ -2, 1.22779942324615231e-05, "aps.15.21"],
+ [aps15_f, aps15_fp, aps15_fpp, (200,), [-1000, 1e-4], 0,
+ -2, 6.16953939044086617e-06, "aps.15.22"],
+ [aps15_f, aps15_fp, aps15_fpp, (300,), [-1000, 1e-4], 0,
+ -2, 4.11985852982928163e-06, "aps.15.23"],
+ [aps15_f, aps15_fp, aps15_fpp, (400,), [-1000, 1e-4], 0,
+ -2, 3.09246238772721682e-06, "aps.15.24"],
+ [aps15_f, aps15_fp, aps15_fpp, (500,), [-1000, 1e-4], 0,
+ -2, 2.47520442610501789e-06, "aps.15.25"],
+ [aps15_f, aps15_fp, aps15_fpp, (600,), [-1000, 1e-4], 0,
+ -2, 2.06335676785127107e-06, "aps.15.26"],
+ [aps15_f, aps15_fp, aps15_fpp, (700,), [-1000, 1e-4], 0,
+ -2, 1.76901200781542651e-06, "aps.15.27"],
+ [aps15_f, aps15_fp, aps15_fpp, (800,), [-1000, 1e-4], 0,
+ -2, 1.54816156988591016e-06, "aps.15.28"],
+ [aps15_f, aps15_fp, aps15_fpp, (900,), [-1000, 1e-4], 0,
+ -2, 1.37633453660223511e-06, "aps.15.29"],
+ [aps15_f, aps15_fp, aps15_fpp, (1000,), [-1000, 1e-4], 0,
+ -2, 1.23883857889971403e-06, "aps.15.30"]
+]
+
+_APS_TESTS_DICTS = [dict(zip(_APS_TESTS_KEYS, testcase)) for testcase in _APS_TESTS]
+
+
+# ##################
+# "complex" test cases
+# A few simple, complex-valued, functions, defined on the complex plane.
+
+
+def cplx01_f(z, n, a):
+ r"""z**n-a: Use to find the nth root of a"""
+ return z**n - a
+
+
+def cplx01_fp(z, n, a):
+ return n * z**(n - 1)
+
+
+def cplx01_fpp(z, n, a):
+ return n * (n - 1) * z**(n - 2)
+
+
+def cplx02_f(z, a):
+ r"""e**z - a: Use to find the log of a"""
+ return np.exp(z) - a
+
+
+def cplx02_fp(z, a):
+ return np.exp(z)
+
+
+def cplx02_fpp(z, a):
+ return np.exp(z)
+
+
+# Each "complex" test case has
+# - a function and its two derivatives,
+# - additional arguments,
+# - the order of differentiability of the function on this interval
+# - two starting values x0 and x1
+# - the root
+# - an Identifier of the test case
+#
+# Algorithm 748 is a bracketing algorithm so a bracketing interval was provided
+# in [1] for each test case. Newton and Halley need a single starting point
+# x0, which was chosen to be near the middle of the interval, unless that
+# would make the problem too easy.
+
+
+_COMPLEX_TESTS_KEYS = [
+ "f", "fprime", "fprime2", "args", "smoothness", "x0", "x1", "root", "ID"
+]
+_COMPLEX_TESTS = [
+ [cplx01_f, cplx01_fp, cplx01_fpp, (2, -1), np.inf,
+ (1 + 1j), (0.5 + 0.5j), 1j, "complex.01.00"],
+ [cplx01_f, cplx01_fp, cplx01_fpp, (3, 1), np.inf,
+ (-1 + 1j), (-0.5 + 2.0j), (-0.5 + np.sqrt(3) / 2 * 1.0j),
+ "complex.01.01"],
+ [cplx01_f, cplx01_fp, cplx01_fpp, (3, -1), np.inf,
+ 1j, (0.5 + 0.5j), (0.5 + np.sqrt(3) / 2 * 1.0j),
+ "complex.01.02"],
+ [cplx01_f, cplx01_fp, cplx01_fpp, (3, 8), np.inf,
+ 5, 4, 2, "complex.01.03"],
+ [cplx02_f, cplx02_fp, cplx02_fpp, (-1,), np.inf,
+ (1 + 2j), (0.5 + 0.5j), np.pi * 1.0j, "complex.02.00"],
+ [cplx02_f, cplx02_fp, cplx02_fpp, (1j,), np.inf,
+ (1 + 2j), (0.5 + 0.5j), np.pi * 0.5j, "complex.02.01"],
+]
+
+_COMPLEX_TESTS_DICTS = [
+ dict(zip(_COMPLEX_TESTS_KEYS, testcase)) for testcase in _COMPLEX_TESTS
+]
+
+
+def _add_a_b(tests):
+ r"""Add "a" and "b" keys to each test from the "bracket" value"""
+ for d in tests:
+ for k, v in zip(['a', 'b'], d.get('bracket', [])):
+ d[k] = v
+
+
+_add_a_b(_ORIGINAL_TESTS_DICTS)
+_add_a_b(_APS_TESTS_DICTS)
+_add_a_b(_COMPLEX_TESTS_DICTS)
+
+
+def get_tests(collection='original', smoothness=None):
+ r"""Return the requested collection of test cases, as an array of dicts with subset-specific keys
+
+ Allowed values of collection:
+ 'original': The original benchmarking functions.
+ Real-valued functions of real-valued inputs on an interval with a zero.
+ f1, .., f3 are continuous and infinitely differentiable
+ f4 has a single discontinuity at the root
+ f5 has a root at 1 replacing a 1st order pole
+ f6 is randomly positive on one side of the root, randomly negative on the other
+ 'aps': The test problems in the TOMS "Algorithm 748: Enclosing Zeros of Continuous Functions"
+ paper by Alefeld, Potra and Shi. Real-valued functions of
+ real-valued inputs on an interval with a zero.
+ Suitable for methods which start with an enclosing interval, and
+ derivatives up to 2nd order.
+ 'complex': Some complex-valued functions of complex-valued inputs.
+ No enclosing bracket is provided.
+ Suitable for methods which use one or more starting values, and
+ derivatives up to 2nd order.
+
+ The dictionary keys will be a subset of
+ ["f", "fprime", "fprime2", "args", "bracket", "a", b", "smoothness", "x0", "x1", "root", "ID"]
+ """ # noqa: E501
+ collection = collection or "original"
+ subsets = {"aps": _APS_TESTS_DICTS,
+ "complex": _COMPLEX_TESTS_DICTS,
+ "original": _ORIGINAL_TESTS_DICTS,
+ "chandrupatla": _CHANDRUPATLA_TESTS_DICTS}
+ tests = subsets.get(collection, [])
+ if smoothness is not None:
+ tests = [tc for tc in tests if tc['smoothness'] >= smoothness]
+ return tests
+
+
+# Backwards compatibility
+methods = [cc.bisect, cc.ridder, cc.brenth, cc.brentq]
+mstrings = ['cc.bisect', 'cc.ridder', 'cc.brenth', 'cc.brentq']
+functions = [f2, f3, f4, f5, f6]
+fstrings = ['f2', 'f3', 'f4', 'f5', 'f6']
+
+# ##################
+# "Chandrupatla" test cases
+# Functions and test cases that appear in [2]
+
+def fun1(x):
+ return x**3 - 2*x - 5
+fun1.root = 2.0945514815423265 # additional precision using mpmath.findroot
+
+
+def fun2(x):
+ return 1 - 1/x**2
+fun2.root = 1
+
+
+def fun3(x):
+ return (x-3)**3
+fun3.root = 3
+
+
+def fun4(x):
+ return 6*(x-2)**5
+fun4.root = 2
+
+
+def fun5(x):
+ return x**9
+fun5.root = 0
+
+
+def fun6(x):
+ return x**19
+fun6.root = 0
+
+
+def fun7(x):
+ xp = array_namespace(x)
+ return 0 if xp.abs(x) < 3.8e-4 else x*xp.exp(-x**(-2))
+fun7.root = 0
+
+
+def fun8(x):
+ xp = array_namespace(x)
+ xi = 0.61489
+ return -(3062*(1-xi)*xp.exp(-x))/(xi + (1-xi)*xp.exp(-x)) - 1013 + 1628/x
+fun8.root = 1.0375360332870405
+
+
+def fun9(x):
+ xp = array_namespace(x)
+ return xp.exp(x) - 2 - 0.01/x**2 + .000002/x**3
+fun9.root = 0.7032048403631358
+
+# Each "chandropatla" test case has
+# - a function,
+# - two starting values x0 and x1
+# - the root
+# - the number of function evaluations required by Chandrupatla's algorithm
+# - an Identifier of the test case
+#
+# Chandrupatla's is a bracketing algorithm, so a bracketing interval was
+# provided in [2] for each test case. No special support for testing with
+# secant/Newton/Halley is provided.
+
+_CHANDRUPATLA_TESTS_KEYS = ["f", "bracket", "root", "nfeval", "ID"]
+_CHANDRUPATLA_TESTS = [
+ [fun1, [2, 3], fun1.root, 7],
+ [fun1, [1, 10], fun1.root, 11],
+ [fun1, [1, 100], fun1.root, 14],
+ [fun1, [-1e4, 1e4], fun1.root, 23],
+ [fun1, [-1e10, 1e10], fun1.root, 43],
+ [fun2, [0.5, 1.51], fun2.root, 8],
+ [fun2, [1e-4, 1e4], fun2.root, 22],
+ [fun2, [1e-6, 1e6], fun2.root, 28],
+ [fun2, [1e-10, 1e10], fun2.root, 41],
+ [fun2, [1e-12, 1e12], fun2.root, 48],
+ [fun3, [0, 5], fun3.root, 21],
+ [fun3, [-10, 10], fun3.root, 23],
+ [fun3, [-1e4, 1e4], fun3.root, 36],
+ [fun3, [-1e6, 1e6], fun3.root, 45],
+ [fun3, [-1e10, 1e10], fun3.root, 55],
+ [fun4, [0, 5], fun4.root, 21],
+ [fun4, [-10, 10], fun4.root, 23],
+ [fun4, [-1e4, 1e4], fun4.root, 33],
+ [fun4, [-1e6, 1e6], fun4.root, 43],
+ [fun4, [-1e10, 1e10], fun4.root, 54],
+ [fun5, [-1, 4], fun5.root, 21],
+ [fun5, [-2, 5], fun5.root, 22],
+ [fun5, [-1, 10], fun5.root, 23],
+ [fun5, [-5, 50], fun5.root, 25],
+ [fun5, [-10, 100], fun5.root, 26],
+ [fun6, [-1., 4.], fun6.root, 21],
+ [fun6, [-2., 5.], fun6.root, 22],
+ [fun6, [-1., 10.], fun6.root, 23],
+ [fun6, [-5., 50.], fun6.root, 25],
+ [fun6, [-10., 100.], fun6.root, 26],
+ [fun7, [-1, 4], fun7.root, 8],
+ [fun7, [-2, 5], fun7.root, 8],
+ [fun7, [-1, 10], fun7.root, 11],
+ [fun7, [-5, 50], fun7.root, 18],
+ [fun7, [-10, 100], fun7.root, 19],
+ [fun8, [2e-4, 2], fun8.root, 9],
+ [fun8, [2e-4, 3], fun8.root, 10],
+ [fun8, [2e-4, 9], fun8.root, 11],
+ [fun8, [2e-4, 27], fun8.root, 12],
+ [fun8, [2e-4, 81], fun8.root, 14],
+ [fun9, [2e-4, 1], fun9.root, 7],
+ [fun9, [2e-4, 3], fun9.root, 8],
+ [fun9, [2e-4, 9], fun9.root, 10],
+ [fun9, [2e-4, 27], fun9.root, 11],
+ [fun9, [2e-4, 81], fun9.root, 13],
+]
+_CHANDRUPATLA_TESTS = [test + [f'{test[0].__name__}.{i%5+1}']
+ for i, test in enumerate(_CHANDRUPATLA_TESTS)]
+
+_CHANDRUPATLA_TESTS_DICTS = [dict(zip(_CHANDRUPATLA_TESTS_KEYS, testcase))
+ for testcase in _CHANDRUPATLA_TESTS]
+_add_a_b(_CHANDRUPATLA_TESTS_DICTS)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_zeros.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_zeros.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..24d08bb798684f4df22b1ade56bd09ea984fc8e5
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_zeros.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_zeros_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_zeros_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..6f2ad0b67887b136341e085fef64296ecbdbcee6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/_zeros_py.py
@@ -0,0 +1,1475 @@
+import warnings
+from collections import namedtuple
+import operator
+from . import _zeros
+from ._optimize import OptimizeResult
+import numpy as np
+
+
+_iter = 100
+_xtol = 2e-12
+_rtol = 4 * np.finfo(float).eps
+
+__all__ = ['newton', 'bisect', 'ridder', 'brentq', 'brenth', 'toms748',
+ 'RootResults']
+
+# Must agree with CONVERGED, SIGNERR, CONVERR, ... in zeros.h
+_ECONVERGED = 0
+_ESIGNERR = -1 # used in _chandrupatla
+_ECONVERR = -2
+_EVALUEERR = -3
+_ECALLBACK = -4
+_EINPROGRESS = 1
+
+CONVERGED = 'converged'
+SIGNERR = 'sign error'
+CONVERR = 'convergence error'
+VALUEERR = 'value error'
+INPROGRESS = 'No error'
+
+
+flag_map = {_ECONVERGED: CONVERGED, _ESIGNERR: SIGNERR, _ECONVERR: CONVERR,
+ _EVALUEERR: VALUEERR, _EINPROGRESS: INPROGRESS}
+
+
+class RootResults(OptimizeResult):
+ """Represents the root finding result.
+
+ Attributes
+ ----------
+ root : float
+ Estimated root location.
+ iterations : int
+ Number of iterations needed to find the root.
+ function_calls : int
+ Number of times the function was called.
+ converged : bool
+ True if the routine converged.
+ flag : str
+ Description of the cause of termination.
+ method : str
+ Root finding method used.
+
+ """
+
+ def __init__(self, root, iterations, function_calls, flag, method):
+ self.root = root
+ self.iterations = iterations
+ self.function_calls = function_calls
+ self.converged = flag == _ECONVERGED
+ if flag in flag_map:
+ self.flag = flag_map[flag]
+ else:
+ self.flag = flag
+ self.method = method
+
+
+def results_c(full_output, r, method):
+ if full_output:
+ x, funcalls, iterations, flag = r
+ results = RootResults(root=x,
+ iterations=iterations,
+ function_calls=funcalls,
+ flag=flag, method=method)
+ return x, results
+ else:
+ return r
+
+
+def _results_select(full_output, r, method):
+ """Select from a tuple of (root, funccalls, iterations, flag)"""
+ x, funcalls, iterations, flag = r
+ if full_output:
+ results = RootResults(root=x,
+ iterations=iterations,
+ function_calls=funcalls,
+ flag=flag, method=method)
+ return x, results
+ return x
+
+
+def _wrap_nan_raise(f):
+
+ def f_raise(x, *args):
+ fx = f(x, *args)
+ f_raise._function_calls += 1
+ if np.isnan(fx):
+ msg = (f'The function value at x={x} is NaN; '
+ 'solver cannot continue.')
+ err = ValueError(msg)
+ err._x = x
+ err._function_calls = f_raise._function_calls
+ raise err
+ return fx
+
+ f_raise._function_calls = 0
+ return f_raise
+
+
+def newton(func, x0, fprime=None, args=(), tol=1.48e-8, maxiter=50,
+ fprime2=None, x1=None, rtol=0.0,
+ full_output=False, disp=True):
+ """
+ Find a root of a real or complex function using the Newton-Raphson
+ (or secant or Halley's) method.
+
+ Find a root of the scalar-valued function `func` given a nearby scalar
+ starting point `x0`.
+ The Newton-Raphson method is used if the derivative `fprime` of `func`
+ is provided, otherwise the secant method is used. If the second order
+ derivative `fprime2` of `func` is also provided, then Halley's method is
+ used.
+
+ If `x0` is a sequence with more than one item, `newton` returns an array:
+ the roots of the function from each (scalar) starting point in `x0`.
+ In this case, `func` must be vectorized to return a sequence or array of
+ the same shape as its first argument. If `fprime` (`fprime2`) is given,
+ then its return must also have the same shape: each element is the first
+ (second) derivative of `func` with respect to its only variable evaluated
+ at each element of its first argument.
+
+ `newton` is for finding roots of a scalar-valued functions of a single
+ variable. For problems involving several variables, see `root`.
+
+ Parameters
+ ----------
+ func : callable
+ The function whose root is wanted. It must be a function of a
+ single variable of the form ``f(x,a,b,c,...)``, where ``a,b,c,...``
+ are extra arguments that can be passed in the `args` parameter.
+ x0 : float, sequence, or ndarray
+ An initial estimate of the root that should be somewhere near the
+ actual root. If not scalar, then `func` must be vectorized and return
+ a sequence or array of the same shape as its first argument.
+ fprime : callable, optional
+ The derivative of the function when available and convenient. If it
+ is None (default), then the secant method is used.
+ args : tuple, optional
+ Extra arguments to be used in the function call.
+ tol : float, optional
+ The allowable error of the root's value. If `func` is complex-valued,
+ a larger `tol` is recommended as both the real and imaginary parts
+ of `x` contribute to ``|x - x0|``.
+ maxiter : int, optional
+ Maximum number of iterations.
+ fprime2 : callable, optional
+ The second order derivative of the function when available and
+ convenient. If it is None (default), then the normal Newton-Raphson
+ or the secant method is used. If it is not None, then Halley's method
+ is used.
+ x1 : float, optional
+ Another estimate of the root that should be somewhere near the
+ actual root. Used if `fprime` is not provided.
+ rtol : float, optional
+ Tolerance (relative) for termination.
+ full_output : bool, optional
+ If `full_output` is False (default), the root is returned.
+ If True and `x0` is scalar, the return value is ``(x, r)``, where ``x``
+ is the root and ``r`` is a `RootResults` object.
+ If True and `x0` is non-scalar, the return value is ``(x, converged,
+ zero_der)`` (see Returns section for details).
+ disp : bool, optional
+ If True, raise a RuntimeError if the algorithm didn't converge, with
+ the error message containing the number of iterations and current
+ function value. Otherwise, the convergence status is recorded in a
+ `RootResults` return object.
+ Ignored if `x0` is not scalar.
+ *Note: this has little to do with displaying, however,
+ the `disp` keyword cannot be renamed for backwards compatibility.*
+
+ Returns
+ -------
+ root : float, sequence, or ndarray
+ Estimated location where function is zero.
+ r : `RootResults`, optional
+ Present if ``full_output=True`` and `x0` is scalar.
+ Object containing information about the convergence. In particular,
+ ``r.converged`` is True if the routine converged.
+ converged : ndarray of bool, optional
+ Present if ``full_output=True`` and `x0` is non-scalar.
+ For vector functions, indicates which elements converged successfully.
+ zero_der : ndarray of bool, optional
+ Present if ``full_output=True`` and `x0` is non-scalar.
+ For vector functions, indicates which elements had a zero derivative.
+
+ See Also
+ --------
+ root_scalar : interface to root solvers for scalar functions
+ root : interface to root solvers for multi-input, multi-output functions
+
+ Notes
+ -----
+ The convergence rate of the Newton-Raphson method is quadratic,
+ the Halley method is cubic, and the secant method is
+ sub-quadratic. This means that if the function is well-behaved
+ the actual error in the estimated root after the nth iteration
+ is approximately the square (cube for Halley) of the error
+ after the (n-1)th step. However, the stopping criterion used
+ here is the step size and there is no guarantee that a root
+ has been found. Consequently, the result should be verified.
+ Safer algorithms are brentq, brenth, ridder, and bisect,
+ but they all require that the root first be bracketed in an
+ interval where the function changes sign. The brentq algorithm
+ is recommended for general use in one dimensional problems
+ when such an interval has been found.
+
+ When `newton` is used with arrays, it is best suited for the following
+ types of problems:
+
+ * The initial guesses, `x0`, are all relatively the same distance from
+ the roots.
+ * Some or all of the extra arguments, `args`, are also arrays so that a
+ class of similar problems can be solved together.
+ * The size of the initial guesses, `x0`, is larger than O(100) elements.
+ Otherwise, a naive loop may perform as well or better than a vector.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy import optimize
+
+ >>> def f(x):
+ ... return (x**3 - 1) # only one real root at x = 1
+
+ ``fprime`` is not provided, use the secant method:
+
+ >>> root = optimize.newton(f, 1.5)
+ >>> root
+ 1.0000000000000016
+ >>> root = optimize.newton(f, 1.5, fprime2=lambda x: 6 * x)
+ >>> root
+ 1.0000000000000016
+
+ Only ``fprime`` is provided, use the Newton-Raphson method:
+
+ >>> root = optimize.newton(f, 1.5, fprime=lambda x: 3 * x**2)
+ >>> root
+ 1.0
+
+ Both ``fprime2`` and ``fprime`` are provided, use Halley's method:
+
+ >>> root = optimize.newton(f, 1.5, fprime=lambda x: 3 * x**2,
+ ... fprime2=lambda x: 6 * x)
+ >>> root
+ 1.0
+
+ When we want to find roots for a set of related starting values and/or
+ function parameters, we can provide both of those as an array of inputs:
+
+ >>> f = lambda x, a: x**3 - a
+ >>> fder = lambda x, a: 3 * x**2
+ >>> rng = np.random.default_rng()
+ >>> x = rng.standard_normal(100)
+ >>> a = np.arange(-50, 50)
+ >>> vec_res = optimize.newton(f, x, fprime=fder, args=(a, ), maxiter=200)
+
+ The above is the equivalent of solving for each value in ``(x, a)``
+ separately in a for-loop, just faster:
+
+ >>> loop_res = [optimize.newton(f, x0, fprime=fder, args=(a0,),
+ ... maxiter=200)
+ ... for x0, a0 in zip(x, a)]
+ >>> np.allclose(vec_res, loop_res)
+ True
+
+ Plot the results found for all values of ``a``:
+
+ >>> analytical_result = np.sign(a) * np.abs(a)**(1/3)
+ >>> fig, ax = plt.subplots()
+ >>> ax.plot(a, analytical_result, 'o')
+ >>> ax.plot(a, vec_res, '.')
+ >>> ax.set_xlabel('$a$')
+ >>> ax.set_ylabel('$x$ where $f(x, a)=0$')
+ >>> plt.show()
+
+ """
+ if tol <= 0:
+ raise ValueError(f"tol too small ({tol:g} <= 0)")
+ maxiter = operator.index(maxiter)
+ if maxiter < 1:
+ raise ValueError("maxiter must be greater than 0")
+ if np.size(x0) > 1:
+ return _array_newton(func, x0, fprime, args, tol, maxiter, fprime2,
+ full_output)
+
+ # Convert to float (don't use float(x0); this works also for complex x0)
+ # Use np.asarray because we want x0 to be a numpy object, not a Python
+ # object. e.g. np.complex(1+1j) > 0 is possible, but (1 + 1j) > 0 raises
+ # a TypeError
+ x0 = np.asarray(x0)[()] * 1.0
+ p0 = x0
+ funcalls = 0
+ if fprime is not None:
+ # Newton-Raphson method
+ method = "newton"
+ for itr in range(maxiter):
+ # first evaluate fval
+ fval = func(p0, *args)
+ funcalls += 1
+ # If fval is 0, a root has been found, then terminate
+ if fval == 0:
+ return _results_select(
+ full_output, (p0, funcalls, itr, _ECONVERGED), method)
+ fder = fprime(p0, *args)
+ funcalls += 1
+ if fder == 0:
+ msg = "Derivative was zero."
+ if disp:
+ msg += (
+ f" Failed to converge after {itr + 1} iterations,"
+ f" value is {p0}."
+ )
+ raise RuntimeError(msg)
+ warnings.warn(msg, RuntimeWarning, stacklevel=2)
+ return _results_select(
+ full_output, (p0, funcalls, itr + 1, _ECONVERR), method)
+ newton_step = fval / fder
+ if fprime2:
+ fder2 = fprime2(p0, *args)
+ funcalls += 1
+ method = "halley"
+ # Halley's method:
+ # newton_step /= (1.0 - 0.5 * newton_step * fder2 / fder)
+ # Only do it if denominator stays close enough to 1
+ # Rationale: If 1-adj < 0, then Halley sends x in the
+ # opposite direction to Newton. Doesn't happen if x is close
+ # enough to root.
+ adj = newton_step * fder2 / fder / 2
+ if np.abs(adj) < 1:
+ newton_step /= 1.0 - adj
+ p = p0 - newton_step
+ if np.isclose(p, p0, rtol=rtol, atol=tol):
+ return _results_select(
+ full_output, (p, funcalls, itr + 1, _ECONVERGED), method)
+ p0 = p
+ else:
+ # Secant method
+ method = "secant"
+ if x1 is not None:
+ if x1 == x0:
+ raise ValueError("x1 and x0 must be different")
+ p1 = x1
+ else:
+ eps = 1e-4
+ p1 = x0 * (1 + eps)
+ p1 += (eps if p1 >= 0 else -eps)
+ q0 = func(p0, *args)
+ funcalls += 1
+ q1 = func(p1, *args)
+ funcalls += 1
+ if abs(q1) < abs(q0):
+ p0, p1, q0, q1 = p1, p0, q1, q0
+ for itr in range(maxiter):
+ if q1 == q0:
+ if p1 != p0:
+ msg = f"Tolerance of {p1 - p0} reached."
+ if disp:
+ msg += (
+ f" Failed to converge after {itr + 1} iterations,"
+ f" value is {p1}."
+ )
+ raise RuntimeError(msg)
+ warnings.warn(msg, RuntimeWarning, stacklevel=2)
+ p = (p1 + p0) / 2.0
+ return _results_select(
+ full_output, (p, funcalls, itr + 1, _ECONVERR), method)
+ else:
+ if abs(q1) > abs(q0):
+ p = (-q0 / q1 * p1 + p0) / (1 - q0 / q1)
+ else:
+ p = (-q1 / q0 * p0 + p1) / (1 - q1 / q0)
+ if np.isclose(p, p1, rtol=rtol, atol=tol):
+ return _results_select(
+ full_output, (p, funcalls, itr + 1, _ECONVERGED), method)
+ p0, q0 = p1, q1
+ p1 = p
+ q1 = func(p1, *args)
+ funcalls += 1
+
+ if disp:
+ msg = f"Failed to converge after {itr + 1} iterations, value is {p}."
+ raise RuntimeError(msg)
+
+ return _results_select(full_output, (p, funcalls, itr + 1, _ECONVERR), method)
+
+
+def _array_newton(func, x0, fprime, args, tol, maxiter, fprime2, full_output):
+ """
+ A vectorized version of Newton, Halley, and secant methods for arrays.
+
+ Do not use this method directly. This method is called from `newton`
+ when ``np.size(x0) > 1`` is ``True``. For docstring, see `newton`.
+ """
+ # Explicitly copy `x0` as `p` will be modified inplace, but the
+ # user's array should not be altered.
+ p = np.array(x0, copy=True)
+
+ failures = np.ones_like(p, dtype=bool)
+ nz_der = np.ones_like(failures)
+ if fprime is not None:
+ # Newton-Raphson method
+ for iteration in range(maxiter):
+ # first evaluate fval
+ fval = np.asarray(func(p, *args))
+ # If all fval are 0, all roots have been found, then terminate
+ if not fval.any():
+ failures = fval.astype(bool)
+ break
+ fder = np.asarray(fprime(p, *args))
+ nz_der = (fder != 0)
+ # stop iterating if all derivatives are zero
+ if not nz_der.any():
+ break
+ # Newton step
+ dp = fval[nz_der] / fder[nz_der]
+ if fprime2 is not None:
+ fder2 = np.asarray(fprime2(p, *args))
+ dp = dp / (1.0 - 0.5 * dp * fder2[nz_der] / fder[nz_der])
+ # only update nonzero derivatives
+ p = np.asarray(p, dtype=np.result_type(p, dp, np.float64))
+ p[nz_der] -= dp
+ failures[nz_der] = np.abs(dp) >= tol # items not yet converged
+ # stop iterating if there aren't any failures, not incl zero der
+ if not failures[nz_der].any():
+ break
+ else:
+ # Secant method
+ dx = np.finfo(float).eps**0.33
+ p1 = p * (1 + dx) + np.where(p >= 0, dx, -dx)
+ q0 = np.asarray(func(p, *args))
+ q1 = np.asarray(func(p1, *args))
+ active = np.ones_like(p, dtype=bool)
+ for iteration in range(maxiter):
+ nz_der = (q1 != q0)
+ # stop iterating if all derivatives are zero
+ if not nz_der.any():
+ p = (p1 + p) / 2.0
+ break
+ # Secant Step
+ dp = (q1 * (p1 - p))[nz_der] / (q1 - q0)[nz_der]
+ # only update nonzero derivatives
+ p = np.asarray(p, dtype=np.result_type(p, p1, dp, np.float64))
+ p[nz_der] = p1[nz_der] - dp
+ active_zero_der = ~nz_der & active
+ p[active_zero_der] = (p1 + p)[active_zero_der] / 2.0
+ active &= nz_der # don't assign zero derivatives again
+ failures[nz_der] = np.abs(dp) >= tol # not yet converged
+ # stop iterating if there aren't any failures, not incl zero der
+ if not failures[nz_der].any():
+ break
+ p1, p = p, p1
+ q0 = q1
+ q1 = np.asarray(func(p1, *args))
+
+ zero_der = ~nz_der & failures # don't include converged with zero-ders
+ if zero_der.any():
+ # Secant warnings
+ if fprime is None:
+ nonzero_dp = (p1 != p)
+ # non-zero dp, but infinite newton step
+ zero_der_nz_dp = (zero_der & nonzero_dp)
+ if zero_der_nz_dp.any():
+ rms = np.sqrt(
+ sum((p1[zero_der_nz_dp] - p[zero_der_nz_dp]) ** 2)
+ )
+ warnings.warn(f'RMS of {rms:g} reached', RuntimeWarning, stacklevel=3)
+ # Newton or Halley warnings
+ else:
+ all_or_some = 'all' if zero_der.all() else 'some'
+ msg = f'{all_or_some:s} derivatives were zero'
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
+ elif failures.any():
+ all_or_some = 'all' if failures.all() else 'some'
+ msg = f'{all_or_some:s} failed to converge after {maxiter:d} iterations'
+ if failures.all():
+ raise RuntimeError(msg)
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
+
+ if full_output:
+ result = namedtuple('result', ('root', 'converged', 'zero_der'))
+ p = result(p, ~failures, zero_der)
+
+ return p
+
+
+def bisect(f, a, b, args=(),
+ xtol=_xtol, rtol=_rtol, maxiter=_iter,
+ full_output=False, disp=True):
+ """
+ Find root of a function within an interval using bisection.
+
+ Basic bisection routine to find a root of the function `f` between the
+ arguments `a` and `b`. `f(a)` and `f(b)` cannot have the same signs.
+ Slow but sure.
+
+ Parameters
+ ----------
+ f : function
+ Python function returning a number. `f` must be continuous, and
+ f(a) and f(b) must have opposite signs.
+ a : scalar
+ One end of the bracketing interval [a,b].
+ b : scalar
+ The other end of the bracketing interval [a,b].
+ xtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter must be positive.
+ rtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter cannot be smaller than its default value of
+ ``4*np.finfo(float).eps``.
+ maxiter : int, optional
+ If convergence is not achieved in `maxiter` iterations, an error is
+ raised. Must be >= 0.
+ args : tuple, optional
+ Containing extra arguments for the function `f`.
+ `f` is called by ``apply(f, (x)+args)``.
+ full_output : bool, optional
+ If `full_output` is False, the root is returned. If `full_output` is
+ True, the return value is ``(x, r)``, where x is the root, and r is
+ a `RootResults` object.
+ disp : bool, optional
+ If True, raise RuntimeError if the algorithm didn't converge.
+ Otherwise, the convergence status is recorded in a `RootResults`
+ return object.
+
+ Returns
+ -------
+ root : float
+ Root of `f` between `a` and `b`.
+ r : `RootResults` (present if ``full_output = True``)
+ Object containing information about the convergence. In particular,
+ ``r.converged`` is True if the routine converged.
+
+ Notes
+ -----
+ As mentioned in the parameter documentation, the computed root ``x0`` will
+ satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the
+ exact root. In equation form, this terminating condition is ``abs(x - x0)
+ <= xtol + rtol * abs(x0)``.
+
+ The default value ``xtol=2e-12`` may lead to surprising behavior if one
+ expects `bisect` to always compute roots with relative error near machine
+ precision. Care should be taken to select `xtol` for the use case at hand.
+ Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the
+ highest level of accuracy. Larger values of `xtol` may be useful for saving
+ function evaluations when a root is at or near zero in applications where
+ the tiny absolute differences available between floating point numbers near
+ zero are not meaningful.
+
+ Examples
+ --------
+
+ >>> def f(x):
+ ... return (x**2 - 1)
+
+ >>> from scipy import optimize
+
+ >>> root = optimize.bisect(f, 0, 2)
+ >>> root
+ 1.0
+
+ >>> root = optimize.bisect(f, -2, 0)
+ >>> root
+ -1.0
+
+ See Also
+ --------
+ brentq, brenth, bisect, newton
+ fixed_point : scalar fixed-point finder
+ fsolve : n-dimensional root-finding
+ elementwise.find_root : efficient elementwise 1-D root-finder
+
+ """
+ if not isinstance(args, tuple):
+ args = (args,)
+ maxiter = operator.index(maxiter)
+ if xtol <= 0:
+ raise ValueError(f"xtol too small ({xtol:g} <= 0)")
+ if rtol < _rtol:
+ raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})")
+ f = _wrap_nan_raise(f)
+ r = _zeros._bisect(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
+ return results_c(full_output, r, "bisect")
+
+
+def ridder(f, a, b, args=(),
+ xtol=_xtol, rtol=_rtol, maxiter=_iter,
+ full_output=False, disp=True):
+ """
+ Find a root of a function in an interval using Ridder's method.
+
+ Parameters
+ ----------
+ f : function
+ Python function returning a number. f must be continuous, and f(a) and
+ f(b) must have opposite signs.
+ a : scalar
+ One end of the bracketing interval [a,b].
+ b : scalar
+ The other end of the bracketing interval [a,b].
+ xtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter must be positive.
+ rtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter cannot be smaller than its default value of
+ ``4*np.finfo(float).eps``.
+ maxiter : int, optional
+ If convergence is not achieved in `maxiter` iterations, an error is
+ raised. Must be >= 0.
+ args : tuple, optional
+ Containing extra arguments for the function `f`.
+ `f` is called by ``apply(f, (x)+args)``.
+ full_output : bool, optional
+ If `full_output` is False, the root is returned. If `full_output` is
+ True, the return value is ``(x, r)``, where `x` is the root, and `r` is
+ a `RootResults` object.
+ disp : bool, optional
+ If True, raise RuntimeError if the algorithm didn't converge.
+ Otherwise, the convergence status is recorded in any `RootResults`
+ return object.
+
+ Returns
+ -------
+ root : float
+ Root of `f` between `a` and `b`.
+ r : `RootResults` (present if ``full_output = True``)
+ Object containing information about the convergence.
+ In particular, ``r.converged`` is True if the routine converged.
+
+ See Also
+ --------
+ brentq, brenth, bisect, newton : 1-D root-finding
+ fixed_point : scalar fixed-point finder
+ elementwise.find_root : efficient elementwise 1-D root-finder
+
+ Notes
+ -----
+ Uses [Ridders1979]_ method to find a root of the function `f` between the
+ arguments `a` and `b`. Ridders' method is faster than bisection, but not
+ generally as fast as the Brent routines. [Ridders1979]_ provides the
+ classic description and source of the algorithm. A description can also be
+ found in any recent edition of Numerical Recipes.
+
+ The routine used here diverges slightly from standard presentations in
+ order to be a bit more careful of tolerance.
+
+ As mentioned in the parameter documentation, the computed root ``x0`` will
+ satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the
+ exact root. In equation form, this terminating condition is ``abs(x - x0)
+ <= xtol + rtol * abs(x0)``.
+
+ The default value ``xtol=2e-12`` may lead to surprising behavior if one
+ expects `ridder` to always compute roots with relative error near machine
+ precision. Care should be taken to select `xtol` for the use case at hand.
+ Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the
+ highest level of accuracy. Larger values of `xtol` may be useful for saving
+ function evaluations when a root is at or near zero in applications where
+ the tiny absolute differences available between floating point numbers near
+ zero are not meaningful.
+
+ References
+ ----------
+ .. [Ridders1979]
+ Ridders, C. F. J. "A New Algorithm for Computing a
+ Single Root of a Real Continuous Function."
+ IEEE Trans. Circuits Systems 26, 979-980, 1979.
+
+ Examples
+ --------
+
+ >>> def f(x):
+ ... return (x**2 - 1)
+
+ >>> from scipy import optimize
+
+ >>> root = optimize.ridder(f, 0, 2)
+ >>> root
+ 1.0
+
+ >>> root = optimize.ridder(f, -2, 0)
+ >>> root
+ -1.0
+ """
+ if not isinstance(args, tuple):
+ args = (args,)
+ maxiter = operator.index(maxiter)
+ if xtol <= 0:
+ raise ValueError(f"xtol too small ({xtol:g} <= 0)")
+ if rtol < _rtol:
+ raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})")
+ f = _wrap_nan_raise(f)
+ r = _zeros._ridder(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
+ return results_c(full_output, r, "ridder")
+
+
+def brentq(f, a, b, args=(),
+ xtol=_xtol, rtol=_rtol, maxiter=_iter,
+ full_output=False, disp=True):
+ """
+ Find a root of a function in a bracketing interval using Brent's method.
+
+ Uses the classic Brent's method to find a root of the function `f` on
+ the sign changing interval [a , b]. Generally considered the best of the
+ rootfinding routines here. It is a safe version of the secant method that
+ uses inverse quadratic extrapolation. Brent's method combines root
+ bracketing, interval bisection, and inverse quadratic interpolation. It is
+ sometimes known as the van Wijngaarden-Dekker-Brent method. Brent (1973)
+ claims convergence is guaranteed for functions computable within [a,b].
+
+ [Brent1973]_ provides the classic description of the algorithm. Another
+ description can be found in a recent edition of Numerical Recipes, including
+ [PressEtal1992]_. A third description is at
+ http://mathworld.wolfram.com/BrentsMethod.html. It should be easy to
+ understand the algorithm just by reading our code. Our code diverges a bit
+ from standard presentations: we choose a different formula for the
+ extrapolation step.
+
+ Parameters
+ ----------
+ f : function
+ Python function returning a number. The function :math:`f`
+ must be continuous, and :math:`f(a)` and :math:`f(b)` must
+ have opposite signs.
+ a : scalar
+ One end of the bracketing interval :math:`[a, b]`.
+ b : scalar
+ The other end of the bracketing interval :math:`[a, b]`.
+ xtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter must be positive. For nice functions, Brent's
+ method will often satisfy the above condition with ``xtol/2``
+ and ``rtol/2``. [Brent1973]_
+ rtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter cannot be smaller than its default value of
+ ``4*np.finfo(float).eps``. For nice functions, Brent's
+ method will often satisfy the above condition with ``xtol/2``
+ and ``rtol/2``. [Brent1973]_
+ maxiter : int, optional
+ If convergence is not achieved in `maxiter` iterations, an error is
+ raised. Must be >= 0.
+ args : tuple, optional
+ Containing extra arguments for the function `f`.
+ `f` is called by ``apply(f, (x)+args)``.
+ full_output : bool, optional
+ If `full_output` is False, the root is returned. If `full_output` is
+ True, the return value is ``(x, r)``, where `x` is the root, and `r` is
+ a `RootResults` object.
+ disp : bool, optional
+ If True, raise RuntimeError if the algorithm didn't converge.
+ Otherwise, the convergence status is recorded in any `RootResults`
+ return object.
+
+ Returns
+ -------
+ root : float
+ Root of `f` between `a` and `b`.
+ r : `RootResults` (present if ``full_output = True``)
+ Object containing information about the convergence. In particular,
+ ``r.converged`` is True if the routine converged.
+
+ See Also
+ --------
+ fmin, fmin_powell, fmin_cg, fmin_bfgs, fmin_ncg : multivariate local optimizers
+ leastsq : nonlinear least squares minimizer
+ fmin_l_bfgs_b, fmin_tnc, fmin_cobyla : constrained multivariate optimizers
+ basinhopping, differential_evolution, brute : global optimizers
+ fminbound, brent, golden, bracket : local scalar minimizers
+ fsolve : N-D root-finding
+ brenth, ridder, bisect, newton : 1-D root-finding
+ fixed_point : scalar fixed-point finder
+ elementwise.find_root : efficient elementwise 1-D root-finder
+
+ Notes
+ -----
+ `f` must be continuous. f(a) and f(b) must have opposite signs.
+
+ As mentioned in the parameter documentation, the computed root ``x0`` will
+ satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the
+ exact root. In equation form, this terminating condition is ``abs(x - x0)
+ <= xtol + rtol * abs(x0)``.
+
+ The default value ``xtol=2e-12`` may lead to surprising behavior if one
+ expects `brentq` to always compute roots with relative error near machine
+ precision. Care should be taken to select `xtol` for the use case at hand.
+ Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the
+ highest level of accuracy. Larger values of `xtol` may be useful for saving
+ function evaluations when a root is at or near zero in applications where
+ the tiny absolute differences available between floating point numbers near
+ zero are not meaningful.
+
+ References
+ ----------
+ .. [Brent1973]
+ Brent, R. P.,
+ *Algorithms for Minimization Without Derivatives*.
+ Englewood Cliffs, NJ: Prentice-Hall, 1973. Ch. 3-4.
+
+ .. [PressEtal1992]
+ Press, W. H.; Flannery, B. P.; Teukolsky, S. A.; and Vetterling, W. T.
+ *Numerical Recipes in FORTRAN: The Art of Scientific Computing*, 2nd ed.
+ Cambridge, England: Cambridge University Press, pp. 352-355, 1992.
+ Section 9.3: "Van Wijngaarden-Dekker-Brent Method."
+
+ Examples
+ --------
+ >>> def f(x):
+ ... return (x**2 - 1)
+
+ >>> from scipy import optimize
+
+ >>> root = optimize.brentq(f, -2, 0)
+ >>> root
+ -1.0
+
+ >>> root = optimize.brentq(f, 0, 2)
+ >>> root
+ 1.0
+ """
+ if not isinstance(args, tuple):
+ args = (args,)
+ maxiter = operator.index(maxiter)
+ if xtol <= 0:
+ raise ValueError(f"xtol too small ({xtol:g} <= 0)")
+ if rtol < _rtol:
+ raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})")
+ f = _wrap_nan_raise(f)
+ r = _zeros._brentq(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
+ return results_c(full_output, r, "brentq")
+
+
+def brenth(f, a, b, args=(),
+ xtol=_xtol, rtol=_rtol, maxiter=_iter,
+ full_output=False, disp=True):
+ """Find a root of a function in a bracketing interval using Brent's
+ method with hyperbolic extrapolation.
+
+ A variation on the classic Brent routine to find a root of the function f
+ between the arguments a and b that uses hyperbolic extrapolation instead of
+ inverse quadratic extrapolation. Bus & Dekker (1975) guarantee convergence
+ for this method, claiming that the upper bound of function evaluations here
+ is 4 or 5 times that of bisection.
+ f(a) and f(b) cannot have the same signs. Generally, on a par with the
+ brent routine, but not as heavily tested. It is a safe version of the
+ secant method that uses hyperbolic extrapolation.
+ The version here is by Chuck Harris, and implements Algorithm M of
+ [BusAndDekker1975]_, where further details (convergence properties,
+ additional remarks and such) can be found
+
+ Parameters
+ ----------
+ f : function
+ Python function returning a number. f must be continuous, and f(a) and
+ f(b) must have opposite signs.
+ a : scalar
+ One end of the bracketing interval [a,b].
+ b : scalar
+ The other end of the bracketing interval [a,b].
+ xtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter must be positive. As with `brentq`, for nice
+ functions the method will often satisfy the above condition
+ with ``xtol/2`` and ``rtol/2``.
+ rtol : number, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter cannot be smaller than its default value of
+ ``4*np.finfo(float).eps``. As with `brentq`, for nice functions
+ the method will often satisfy the above condition with
+ ``xtol/2`` and ``rtol/2``.
+ maxiter : int, optional
+ If convergence is not achieved in `maxiter` iterations, an error is
+ raised. Must be >= 0.
+ args : tuple, optional
+ Containing extra arguments for the function `f`.
+ `f` is called by ``apply(f, (x)+args)``.
+ full_output : bool, optional
+ If `full_output` is False, the root is returned. If `full_output` is
+ True, the return value is ``(x, r)``, where `x` is the root, and `r` is
+ a `RootResults` object.
+ disp : bool, optional
+ If True, raise RuntimeError if the algorithm didn't converge.
+ Otherwise, the convergence status is recorded in any `RootResults`
+ return object.
+
+ Returns
+ -------
+ root : float
+ Root of `f` between `a` and `b`.
+ r : `RootResults` (present if ``full_output = True``)
+ Object containing information about the convergence. In particular,
+ ``r.converged`` is True if the routine converged.
+
+ See Also
+ --------
+ fmin, fmin_powell, fmin_cg, fmin_bfgs, fmin_ncg : multivariate local optimizers
+ leastsq : nonlinear least squares minimizer
+ fmin_l_bfgs_b, fmin_tnc, fmin_cobyla : constrained multivariate optimizers
+ basinhopping, differential_evolution, brute : global optimizers
+ fminbound, brent, golden, bracket : local scalar minimizers
+ fsolve : N-D root-finding
+ brentq, ridder, bisect, newton : 1-D root-finding
+ fixed_point : scalar fixed-point finder
+ elementwise.find_root : efficient elementwise 1-D root-finder
+
+ Notes
+ -----
+ As mentioned in the parameter documentation, the computed root ``x0`` will
+ satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the
+ exact root. In equation form, this terminating condition is ``abs(x - x0)
+ <= xtol + rtol * abs(x0)``.
+
+ The default value ``xtol=2e-12`` may lead to surprising behavior if one
+ expects `brenth` to always compute roots with relative error near machine
+ precision. Care should be taken to select `xtol` for the use case at hand.
+ Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the
+ highest level of accuracy. Larger values of `xtol` may be useful for saving
+ function evaluations when a root is at or near zero in applications where
+ the tiny absolute differences available between floating point numbers near
+ zero are not meaningful.
+
+ References
+ ----------
+ .. [BusAndDekker1975]
+ Bus, J. C. P., Dekker, T. J.,
+ "Two Efficient Algorithms with Guaranteed Convergence for Finding a Zero
+ of a Function", ACM Transactions on Mathematical Software, Vol. 1, Issue
+ 4, Dec. 1975, pp. 330-345. Section 3: "Algorithm M".
+ :doi:`10.1145/355656.355659`
+
+ Examples
+ --------
+ >>> def f(x):
+ ... return (x**2 - 1)
+
+ >>> from scipy import optimize
+
+ >>> root = optimize.brenth(f, -2, 0)
+ >>> root
+ -1.0
+
+ >>> root = optimize.brenth(f, 0, 2)
+ >>> root
+ 1.0
+
+ """
+ if not isinstance(args, tuple):
+ args = (args,)
+ maxiter = operator.index(maxiter)
+ if xtol <= 0:
+ raise ValueError(f"xtol too small ({xtol:g} <= 0)")
+ if rtol < _rtol:
+ raise ValueError(f"rtol too small ({rtol:g} < {_rtol:g})")
+ f = _wrap_nan_raise(f)
+ r = _zeros._brenth(f, a, b, xtol, rtol, maxiter, args, full_output, disp)
+ return results_c(full_output, r, "brenth")
+
+
+################################
+# TOMS "Algorithm 748: Enclosing Zeros of Continuous Functions", by
+# Alefeld, G. E. and Potra, F. A. and Shi, Yixun,
+# See [1]
+
+
+def _notclose(fs, rtol=_rtol, atol=_xtol):
+ # Ensure not None, not 0, all finite, and not very close to each other
+ notclosefvals = (
+ all(fs) and all(np.isfinite(fs)) and
+ not any(any(np.isclose(_f, fs[i + 1:], rtol=rtol, atol=atol))
+ for i, _f in enumerate(fs[:-1])))
+ return notclosefvals
+
+
+def _secant(xvals, fvals):
+ """Perform a secant step, taking a little care"""
+ # Secant has many "mathematically" equivalent formulations
+ # x2 = x0 - (x1 - x0)/(f1 - f0) * f0
+ # = x1 - (x1 - x0)/(f1 - f0) * f1
+ # = (-x1 * f0 + x0 * f1) / (f1 - f0)
+ # = (-f0 / f1 * x1 + x0) / (1 - f0 / f1)
+ # = (-f1 / f0 * x0 + x1) / (1 - f1 / f0)
+ x0, x1 = xvals[:2]
+ f0, f1 = fvals[:2]
+ if f0 == f1:
+ return np.nan
+ if np.abs(f1) > np.abs(f0):
+ x2 = (-f0 / f1 * x1 + x0) / (1 - f0 / f1)
+ else:
+ x2 = (-f1 / f0 * x0 + x1) / (1 - f1 / f0)
+ return x2
+
+
+def _update_bracket(ab, fab, c, fc):
+ """Update a bracket given (c, fc), return the discarded endpoints."""
+ fa, fb = fab
+ idx = (0 if np.sign(fa) * np.sign(fc) > 0 else 1)
+ rx, rfx = ab[idx], fab[idx]
+ fab[idx] = fc
+ ab[idx] = c
+ return rx, rfx
+
+
+def _compute_divided_differences(xvals, fvals, N=None, full=True,
+ forward=True):
+ """Return a matrix of divided differences for the xvals, fvals pairs
+
+ DD[i, j] = f[x_{i-j}, ..., x_i] for 0 <= j <= i
+
+ If full is False, just return the main diagonal(or last row):
+ f[a], f[a, b] and f[a, b, c].
+ If forward is False, return f[c], f[b, c], f[a, b, c]."""
+ if full:
+ if forward:
+ xvals = np.asarray(xvals)
+ else:
+ xvals = np.array(xvals)[::-1]
+ M = len(xvals)
+ N = M if N is None else min(N, M)
+ DD = np.zeros([M, N])
+ DD[:, 0] = fvals[:]
+ for i in range(1, N):
+ DD[i:, i] = (np.diff(DD[i - 1:, i - 1]) /
+ (xvals[i:] - xvals[:M - i]))
+ return DD
+
+ xvals = np.asarray(xvals)
+ dd = np.array(fvals)
+ row = np.array(fvals)
+ idx2Use = (0 if forward else -1)
+ dd[0] = fvals[idx2Use]
+ for i in range(1, len(xvals)):
+ denom = xvals[i:i + len(row) - 1] - xvals[:len(row) - 1]
+ row = np.diff(row)[:] / denom
+ dd[i] = row[idx2Use]
+ return dd
+
+
+def _interpolated_poly(xvals, fvals, x):
+ """Compute p(x) for the polynomial passing through the specified locations.
+
+ Use Neville's algorithm to compute p(x) where p is the minimal degree
+ polynomial passing through the points xvals, fvals"""
+ xvals = np.asarray(xvals)
+ N = len(xvals)
+ Q = np.zeros([N, N])
+ D = np.zeros([N, N])
+ Q[:, 0] = fvals[:]
+ D[:, 0] = fvals[:]
+ for k in range(1, N):
+ alpha = D[k:, k - 1] - Q[k - 1:N - 1, k - 1]
+ diffik = xvals[0:N - k] - xvals[k:N]
+ Q[k:, k] = (xvals[k:] - x) / diffik * alpha
+ D[k:, k] = (xvals[:N - k] - x) / diffik * alpha
+ # Expect Q[-1, 1:] to be small relative to Q[-1, 0] as x approaches a root
+ return np.sum(Q[-1, 1:]) + Q[-1, 0]
+
+
+def _inverse_poly_zero(a, b, c, d, fa, fb, fc, fd):
+ """Inverse cubic interpolation f-values -> x-values
+
+ Given four points (fa, a), (fb, b), (fc, c), (fd, d) with
+ fa, fb, fc, fd all distinct, find poly IP(y) through the 4 points
+ and compute x=IP(0).
+ """
+ return _interpolated_poly([fa, fb, fc, fd], [a, b, c, d], 0)
+
+
+def _newton_quadratic(ab, fab, d, fd, k):
+ """Apply Newton-Raphson like steps, using divided differences to approximate f'
+
+ ab is a real interval [a, b] containing a root,
+ fab holds the real values of f(a), f(b)
+ d is a real number outside [ab, b]
+ k is the number of steps to apply
+ """
+ a, b = ab
+ fa, fb = fab
+ _, B, A = _compute_divided_differences([a, b, d], [fa, fb, fd],
+ forward=True, full=False)
+
+ # _P is the quadratic polynomial through the 3 points
+ def _P(x):
+ # Horner evaluation of fa + B * (x - a) + A * (x - a) * (x - b)
+ return (A * (x - b) + B) * (x - a) + fa
+
+ if A == 0:
+ r = a - fa / B
+ else:
+ r = (a if np.sign(A) * np.sign(fa) > 0 else b)
+ # Apply k Newton-Raphson steps to _P(x), starting from x=r
+ for i in range(k):
+ r1 = r - _P(r) / (B + A * (2 * r - a - b))
+ if not (ab[0] < r1 < ab[1]):
+ if (ab[0] < r < ab[1]):
+ return r
+ r = sum(ab) / 2.0
+ break
+ r = r1
+
+ return r
+
+
+class TOMS748Solver:
+ """Solve f(x, *args) == 0 using Algorithm748 of Alefeld, Potro & Shi.
+ """
+ _MU = 0.5
+ _K_MIN = 1
+ _K_MAX = 100 # A very high value for real usage. Expect 1, 2, maybe 3.
+
+ def __init__(self):
+ self.f = None
+ self.args = None
+ self.function_calls = 0
+ self.iterations = 0
+ self.k = 2
+ # ab=[a,b] is a global interval containing a root
+ self.ab = [np.nan, np.nan]
+ # fab is function values at a, b
+ self.fab = [np.nan, np.nan]
+ self.d = None
+ self.fd = None
+ self.e = None
+ self.fe = None
+ self.disp = False
+ self.xtol = _xtol
+ self.rtol = _rtol
+ self.maxiter = _iter
+
+ def configure(self, xtol, rtol, maxiter, disp, k):
+ self.disp = disp
+ self.xtol = xtol
+ self.rtol = rtol
+ self.maxiter = maxiter
+ # Silently replace a low value of k with 1
+ self.k = max(k, self._K_MIN)
+ # Noisily replace a high value of k with self._K_MAX
+ if self.k > self._K_MAX:
+ msg = f"toms748: Overriding k: ->{self._K_MAX}"
+ warnings.warn(msg, RuntimeWarning, stacklevel=3)
+ self.k = self._K_MAX
+
+ def _callf(self, x, error=True):
+ """Call the user-supplied function, update book-keeping"""
+ fx = self.f(x, *self.args)
+ self.function_calls += 1
+ if not np.isfinite(fx) and error:
+ raise ValueError(f"Invalid function value: f({x:f}) -> {fx} ")
+ return fx
+
+ def get_result(self, x, flag=_ECONVERGED):
+ r"""Package the result and statistics into a tuple."""
+ return (x, self.function_calls, self.iterations, flag)
+
+ def _update_bracket(self, c, fc):
+ return _update_bracket(self.ab, self.fab, c, fc)
+
+ def start(self, f, a, b, args=()):
+ r"""Prepare for the iterations."""
+ self.function_calls = 0
+ self.iterations = 0
+
+ self.f = f
+ self.args = args
+ self.ab[:] = [a, b]
+ if not np.isfinite(a) or np.imag(a) != 0:
+ raise ValueError(f"Invalid x value: {a} ")
+ if not np.isfinite(b) or np.imag(b) != 0:
+ raise ValueError(f"Invalid x value: {b} ")
+
+ fa = self._callf(a)
+ if not np.isfinite(fa) or np.imag(fa) != 0:
+ raise ValueError(f"Invalid function value: f({a:f}) -> {fa} ")
+ if fa == 0:
+ return _ECONVERGED, a
+ fb = self._callf(b)
+ if not np.isfinite(fb) or np.imag(fb) != 0:
+ raise ValueError(f"Invalid function value: f({b:f}) -> {fb} ")
+ if fb == 0:
+ return _ECONVERGED, b
+
+ if np.sign(fb) * np.sign(fa) > 0:
+ raise ValueError("f(a) and f(b) must have different signs, but "
+ f"f({a:e})={fa:e}, f({b:e})={fb:e} ")
+ self.fab[:] = [fa, fb]
+
+ return _EINPROGRESS, sum(self.ab) / 2.0
+
+ def get_status(self):
+ """Determine the current status."""
+ a, b = self.ab[:2]
+ if np.isclose(a, b, rtol=self.rtol, atol=self.xtol):
+ return _ECONVERGED, sum(self.ab) / 2.0
+ if self.iterations >= self.maxiter:
+ return _ECONVERR, sum(self.ab) / 2.0
+ return _EINPROGRESS, sum(self.ab) / 2.0
+
+ def iterate(self):
+ """Perform one step in the algorithm.
+
+ Implements Algorithm 4.1(k=1) or 4.2(k=2) in [APS1995]
+ """
+ self.iterations += 1
+ eps = np.finfo(float).eps
+ d, fd, e, fe = self.d, self.fd, self.e, self.fe
+ ab_width = self.ab[1] - self.ab[0] # Need the start width below
+ c = None
+
+ for nsteps in range(2, self.k+2):
+ # If the f-values are sufficiently separated, perform an inverse
+ # polynomial interpolation step. Otherwise, nsteps repeats of
+ # an approximate Newton-Raphson step.
+ if _notclose(self.fab + [fd, fe], rtol=0, atol=32*eps):
+ c0 = _inverse_poly_zero(self.ab[0], self.ab[1], d, e,
+ self.fab[0], self.fab[1], fd, fe)
+ if self.ab[0] < c0 < self.ab[1]:
+ c = c0
+ if c is None:
+ c = _newton_quadratic(self.ab, self.fab, d, fd, nsteps)
+
+ fc = self._callf(c)
+ if fc == 0:
+ return _ECONVERGED, c
+
+ # re-bracket
+ e, fe = d, fd
+ d, fd = self._update_bracket(c, fc)
+
+ # u is the endpoint with the smallest f-value
+ uix = (0 if np.abs(self.fab[0]) < np.abs(self.fab[1]) else 1)
+ u, fu = self.ab[uix], self.fab[uix]
+
+ _, A = _compute_divided_differences(self.ab, self.fab,
+ forward=(uix == 0), full=False)
+ c = u - 2 * fu / A
+ if np.abs(c - u) > 0.5 * (self.ab[1] - self.ab[0]):
+ c = sum(self.ab) / 2.0
+ else:
+ if np.isclose(c, u, rtol=eps, atol=0):
+ # c didn't change (much).
+ # Either because the f-values at the endpoints have vastly
+ # differing magnitudes, or because the root is very close to
+ # that endpoint
+ frs = np.frexp(self.fab)[1]
+ if frs[uix] < frs[1 - uix] - 50: # Differ by more than 2**50
+ c = (31 * self.ab[uix] + self.ab[1 - uix]) / 32
+ else:
+ # Make a bigger adjustment, about the
+ # size of the requested tolerance.
+ mm = (1 if uix == 0 else -1)
+ adj = mm * np.abs(c) * self.rtol + mm * self.xtol
+ c = u + adj
+ if not self.ab[0] < c < self.ab[1]:
+ c = sum(self.ab) / 2.0
+
+ fc = self._callf(c)
+ if fc == 0:
+ return _ECONVERGED, c
+
+ e, fe = d, fd
+ d, fd = self._update_bracket(c, fc)
+
+ # If the width of the new interval did not decrease enough, bisect
+ if self.ab[1] - self.ab[0] > self._MU * ab_width:
+ e, fe = d, fd
+ z = sum(self.ab) / 2.0
+ fz = self._callf(z)
+ if fz == 0:
+ return _ECONVERGED, z
+ d, fd = self._update_bracket(z, fz)
+
+ # Record d and e for next iteration
+ self.d, self.fd = d, fd
+ self.e, self.fe = e, fe
+
+ status, xn = self.get_status()
+ return status, xn
+
+ def solve(self, f, a, b, args=(),
+ xtol=_xtol, rtol=_rtol, k=2, maxiter=_iter, disp=True):
+ r"""Solve f(x) = 0 given an interval containing a root."""
+ self.configure(xtol=xtol, rtol=rtol, maxiter=maxiter, disp=disp, k=k)
+ status, xn = self.start(f, a, b, args)
+ if status == _ECONVERGED:
+ return self.get_result(xn)
+
+ # The first step only has two x-values.
+ c = _secant(self.ab, self.fab)
+ if not self.ab[0] < c < self.ab[1]:
+ c = sum(self.ab) / 2.0
+ fc = self._callf(c)
+ if fc == 0:
+ return self.get_result(c)
+
+ self.d, self.fd = self._update_bracket(c, fc)
+ self.e, self.fe = None, None
+ self.iterations += 1
+
+ while True:
+ status, xn = self.iterate()
+ if status == _ECONVERGED:
+ return self.get_result(xn)
+ if status == _ECONVERR:
+ fmt = "Failed to converge after %d iterations, bracket is %s"
+ if disp:
+ msg = fmt % (self.iterations + 1, self.ab)
+ raise RuntimeError(msg)
+ return self.get_result(xn, _ECONVERR)
+
+
+def toms748(f, a, b, args=(), k=1,
+ xtol=_xtol, rtol=_rtol, maxiter=_iter,
+ full_output=False, disp=True):
+ """
+ Find a root using TOMS Algorithm 748 method.
+
+ Implements the Algorithm 748 method of Alefeld, Potro and Shi to find a
+ root of the function `f` on the interval ``[a , b]``, where `f(a)` and
+ `f(b)` must have opposite signs.
+
+ It uses a mixture of inverse cubic interpolation and
+ "Newton-quadratic" steps. [APS1995].
+
+ Parameters
+ ----------
+ f : function
+ Python function returning a scalar. The function :math:`f`
+ must be continuous, and :math:`f(a)` and :math:`f(b)`
+ have opposite signs.
+ a : scalar,
+ lower boundary of the search interval
+ b : scalar,
+ upper boundary of the search interval
+ args : tuple, optional
+ containing extra arguments for the function `f`.
+ `f` is called by ``f(x, *args)``.
+ k : int, optional
+ The number of Newton quadratic steps to perform each
+ iteration. ``k>=1``.
+ xtol : scalar, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root. The
+ parameter must be positive.
+ rtol : scalar, optional
+ The computed root ``x0`` will satisfy ``np.isclose(x, x0,
+ atol=xtol, rtol=rtol)``, where ``x`` is the exact root.
+ maxiter : int, optional
+ If convergence is not achieved in `maxiter` iterations, an error is
+ raised. Must be >= 0.
+ full_output : bool, optional
+ If `full_output` is False, the root is returned. If `full_output` is
+ True, the return value is ``(x, r)``, where `x` is the root, and `r` is
+ a `RootResults` object.
+ disp : bool, optional
+ If True, raise RuntimeError if the algorithm didn't converge.
+ Otherwise, the convergence status is recorded in the `RootResults`
+ return object.
+
+ Returns
+ -------
+ root : float
+ Approximate root of `f`
+ r : `RootResults` (present if ``full_output = True``)
+ Object containing information about the convergence. In particular,
+ ``r.converged`` is True if the routine converged.
+
+ See Also
+ --------
+ brentq, brenth, ridder, bisect, newton
+ fsolve : find roots in N dimensions.
+ elementwise.find_root : efficient elementwise 1-D root-finder
+
+ Notes
+ -----
+ `f` must be continuous.
+ Algorithm 748 with ``k=2`` is asymptotically the most efficient
+ algorithm known for finding roots of a four times continuously
+ differentiable function.
+ In contrast with Brent's algorithm, which may only decrease the length of
+ the enclosing bracket on the last step, Algorithm 748 decreases it each
+ iteration with the same asymptotic efficiency as it finds the root.
+
+ For easy statement of efficiency indices, assume that `f` has 4
+ continuous deriviatives.
+ For ``k=1``, the convergence order is at least 2.7, and with about
+ asymptotically 2 function evaluations per iteration, the efficiency
+ index is approximately 1.65.
+ For ``k=2``, the order is about 4.6 with asymptotically 3 function
+ evaluations per iteration, and the efficiency index 1.66.
+ For higher values of `k`, the efficiency index approaches
+ the kth root of ``(3k-2)``, hence ``k=1`` or ``k=2`` are
+ usually appropriate.
+
+ As mentioned in the parameter documentation, the computed root ``x0`` will
+ satisfy ``np.isclose(x, x0, atol=xtol, rtol=rtol)``, where ``x`` is the
+ exact root. In equation form, this terminating condition is ``abs(x - x0)
+ <= xtol + rtol * abs(x0)``.
+
+ The default value ``xtol=2e-12`` may lead to surprising behavior if one
+ expects `toms748` to always compute roots with relative error near machine
+ precision. Care should be taken to select `xtol` for the use case at hand.
+ Setting ``xtol=5e-324``, the smallest subnormal number, will ensure the
+ highest level of accuracy. Larger values of `xtol` may be useful for saving
+ function evaluations when a root is at or near zero in applications where
+ the tiny absolute differences available between floating point numbers near
+ zero are not meaningful.
+
+ References
+ ----------
+ .. [APS1995]
+ Alefeld, G. E. and Potra, F. A. and Shi, Yixun,
+ *Algorithm 748: Enclosing Zeros of Continuous Functions*,
+ ACM Trans. Math. Softw. Volume 221(1995)
+ doi = {10.1145/210089.210111}
+
+ Examples
+ --------
+ >>> def f(x):
+ ... return (x**3 - 1) # only one real root at x = 1
+
+ >>> from scipy import optimize
+ >>> root, results = optimize.toms748(f, 0, 2, full_output=True)
+ >>> root
+ 1.0
+ >>> results
+ converged: True
+ flag: converged
+ function_calls: 11
+ iterations: 5
+ root: 1.0
+ method: toms748
+ """
+ if xtol <= 0:
+ raise ValueError(f"xtol too small ({xtol:g} <= 0)")
+ if rtol < _rtol / 4:
+ raise ValueError(f"rtol too small ({rtol:g} < {_rtol/4:g})")
+ maxiter = operator.index(maxiter)
+ if maxiter < 1:
+ raise ValueError("maxiter must be greater than 0")
+ if not np.isfinite(a):
+ raise ValueError(f"a is not finite {a}")
+ if not np.isfinite(b):
+ raise ValueError(f"b is not finite {b}")
+ if a >= b:
+ raise ValueError(f"a and b are not an interval [{a}, {b}]")
+ if not k >= 1:
+ raise ValueError(f"k too small ({k} < 1)")
+
+ if not isinstance(args, tuple):
+ args = (args,)
+ f = _wrap_nan_raise(f)
+ solver = TOMS748Solver()
+ result = solver.solve(f, a, b, args=args, k=k, xtol=xtol, rtol=rtol,
+ maxiter=maxiter, disp=disp)
+ x, function_calls, iterations, flag = result
+ return _results_select(full_output, (x, function_calls, iterations, flag),
+ "toms748")
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cobyla.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cobyla.py
new file mode 100644
index 0000000000000000000000000000000000000000..87d111d8fc1634e54d3766a3f1c58abd37ac58cb
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cobyla.py
@@ -0,0 +1,19 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'OptimizeResult',
+ 'fmin_cobyla',
+]
+
+def __dir__():
+ return __all__
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="cobyla",
+ private_modules=["_cobyla_py"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize.pxd b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..d35f8da68b34d3a587f3a99326770d8550a2135c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize.pxd
@@ -0,0 +1,11 @@
+# Public Cython API declarations
+#
+# See doc/source/dev/contributor/public_cython_api.rst for guidelines
+
+
+# The following cimport statement provides legacy ABI
+# support. Changing it causes an ABI forward-compatibility break
+# (gh-11793), so we currently leave it as is (no further cimport
+# statements should be used in this file).
+from scipy.optimize.cython_optimize._zeros cimport (
+ brentq, brenth, ridder, bisect, zeros_full_output)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.__zeros.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.__zeros.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.__zeros.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.__zeros.pxd b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.__zeros.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/.__zeros.pxd differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/._c_zeros.pxd b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/._c_zeros.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/._c_zeros.pxd differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..a07250bbeb06542721480c42005307992558fced
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/__init__.py
@@ -0,0 +1,133 @@
+"""
+Cython optimize root finding API
+================================
+The underlying C functions for the following root finders can be accessed
+directly using Cython:
+
+- `~scipy.optimize.bisect`
+- `~scipy.optimize.ridder`
+- `~scipy.optimize.brenth`
+- `~scipy.optimize.brentq`
+
+The Cython API for the root finding functions is similar except there is no
+``disp`` argument. Import the root finding functions using ``cimport`` from
+`scipy.optimize.cython_optimize`. ::
+
+ from scipy.optimize.cython_optimize cimport bisect, ridder, brentq, brenth
+
+
+Callback signature
+------------------
+The zeros functions in `~scipy.optimize.cython_optimize` expect a callback that
+takes a double for the scalar independent variable as the 1st argument and a
+user defined ``struct`` with any extra parameters as the 2nd argument. ::
+
+ double (*callback_type)(double, void*) noexcept
+
+
+Examples
+--------
+Usage of `~scipy.optimize.cython_optimize` requires Cython to write callbacks
+that are compiled into C. For more information on compiling Cython, see the
+`Cython Documentation `_.
+
+These are the basic steps:
+
+1. Create a Cython ``.pyx`` file, for example: ``myexample.pyx``.
+2. Import the desired root finder from `~scipy.optimize.cython_optimize`.
+3. Write the callback function, and call the selected root finding function
+ passing the callback, any extra arguments, and the other solver
+ parameters. ::
+
+ from scipy.optimize.cython_optimize cimport brentq
+
+ # import math from Cython
+ from libc cimport math
+
+ myargs = {'C0': 1.0, 'C1': 0.7} # a dictionary of extra arguments
+ XLO, XHI = 0.5, 1.0 # lower and upper search boundaries
+ XTOL, RTOL, MITR = 1e-3, 1e-3, 10 # other solver parameters
+
+ # user-defined struct for extra parameters
+ ctypedef struct test_params:
+ double C0
+ double C1
+
+
+ # user-defined callback
+ cdef double f(double x, void *args) noexcept:
+ cdef test_params *myargs = args
+ return myargs.C0 - math.exp(-(x - myargs.C1))
+
+
+ # Cython wrapper function
+ cdef double brentq_wrapper_example(dict args, double xa, double xb,
+ double xtol, double rtol, int mitr):
+ # Cython automatically casts dictionary to struct
+ cdef test_params myargs = args
+ return brentq(
+ f, xa, xb, &myargs, xtol, rtol, mitr, NULL)
+
+
+ # Python function
+ def brentq_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL, rtol=RTOL,
+ mitr=MITR):
+ '''Calls Cython wrapper from Python.'''
+ return brentq_wrapper_example(args, xa, xb, xtol, rtol, mitr)
+
+4. If you want to call your function from Python, create a Cython wrapper, and
+ a Python function that calls the wrapper, or use ``cpdef``. Then, in Python,
+ you can import and run the example. ::
+
+ from myexample import brentq_example
+
+ x = brentq_example()
+ # 0.6999942848231314
+
+5. Create a Cython ``.pxd`` file if you need to export any Cython functions.
+
+
+Full output
+-----------
+The functions in `~scipy.optimize.cython_optimize` can also copy the full
+output from the solver to a C ``struct`` that is passed as its last argument.
+If you don't want the full output, just pass ``NULL``. The full output
+``struct`` must be type ``zeros_full_output``, which is defined in
+`scipy.optimize.cython_optimize` with the following fields:
+
+- ``int funcalls``: number of function calls
+- ``int iterations``: number of iterations
+- ``int error_num``: error number
+- ``double root``: root of function
+
+The root is copied by `~scipy.optimize.cython_optimize` to the full output
+``struct``. An error number of -1 means a sign error, -2 means a convergence
+error, and 0 means the solver converged. Continuing from the previous example::
+
+ from scipy.optimize.cython_optimize cimport zeros_full_output
+
+
+ # cython brentq solver with full output
+ cdef zeros_full_output brentq_full_output_wrapper_example(
+ dict args, double xa, double xb, double xtol, double rtol,
+ int mitr):
+ cdef test_params myargs = args
+ cdef zeros_full_output my_full_output
+ # use my_full_output instead of NULL
+ brentq(f, xa, xb, &myargs, xtol, rtol, mitr, &my_full_output)
+ return my_full_output
+
+
+ # Python function
+ def brent_full_output_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL,
+ rtol=RTOL, mitr=MITR):
+ '''Returns full output'''
+ return brentq_full_output_wrapper_example(args, xa, xb, xtol, rtol,
+ mitr)
+
+ result = brent_full_output_example()
+ # {'error_num': 0,
+ # 'funcalls': 6,
+ # 'iterations': 5,
+ # 'root': 0.6999942848231314}
+"""
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..b4a10c9fca019c4c7e4dd1e0c049d0f94518560b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:fc32298585ac397bac8bab07ac8545f4eea3ebb057d956f5ed146dedf965213a
+size 114672
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.pxd b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..d3c9e98f0a24d80d15d1f7052f690d608f66dd80
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/_zeros.pxd
@@ -0,0 +1,33 @@
+# Legacy public Cython API declarations
+#
+# NOTE: due to the way Cython ABI compatibility works, **no changes
+# should be made to this file** --- any API additions/changes should be
+# done in `cython_optimize.pxd` (see gh-11793).
+
+ctypedef double (*callback_type)(double, void*) noexcept
+
+ctypedef struct zeros_parameters:
+ callback_type function
+ void* args
+
+ctypedef struct zeros_full_output:
+ int funcalls
+ int iterations
+ int error_num
+ double root
+
+cdef double bisect(callback_type f, double xa, double xb, void* args,
+ double xtol, double rtol, int iter,
+ zeros_full_output *full_output) noexcept nogil
+
+cdef double ridder(callback_type f, double xa, double xb, void* args,
+ double xtol, double rtol, int iter,
+ zeros_full_output *full_output) noexcept nogil
+
+cdef double brenth(callback_type f, double xa, double xb, void* args,
+ double xtol, double rtol, int iter,
+ zeros_full_output *full_output) noexcept nogil
+
+cdef double brentq(callback_type f, double xa, double xb, void* args,
+ double xtol, double rtol, int iter,
+ zeros_full_output *full_output) noexcept nogil
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/c_zeros.pxd b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/c_zeros.pxd
new file mode 100644
index 0000000000000000000000000000000000000000..0d83c80eb886846ddbbd6927e37e05812911f856
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/cython_optimize/c_zeros.pxd
@@ -0,0 +1,26 @@
+cdef extern from "../Zeros/zeros.h":
+ ctypedef double (*callback_type)(double, void*) noexcept
+ ctypedef struct scipy_zeros_info:
+ int funcalls
+ int iterations
+ int error_num
+
+cdef extern from "../Zeros/bisect.c" nogil:
+ double bisect(callback_type f, double xa, double xb, double xtol,
+ double rtol, int iter, void *func_data_param,
+ scipy_zeros_info *solver_stats)
+
+cdef extern from "../Zeros/ridder.c" nogil:
+ double ridder(callback_type f, double xa, double xb, double xtol,
+ double rtol, int iter, void *func_data_param,
+ scipy_zeros_info *solver_stats)
+
+cdef extern from "../Zeros/brenth.c" nogil:
+ double brenth(callback_type f, double xa, double xb, double xtol,
+ double rtol, int iter, void *func_data_param,
+ scipy_zeros_info *solver_stats)
+
+cdef extern from "../Zeros/brentq.c" nogil:
+ double brentq(callback_type f, double xa, double xb, double xtol,
+ double rtol, int iter, void *func_data_param,
+ scipy_zeros_info *solver_stats)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/elementwise.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/elementwise.py
new file mode 100644
index 0000000000000000000000000000000000000000..f7be4484626880182a17acf883d72388937578d1
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/elementwise.py
@@ -0,0 +1,38 @@
+"""
+===================================================================
+Elementwise Scalar Optimization (:mod:`scipy.optimize.elementwise`)
+===================================================================
+
+.. currentmodule:: scipy.optimize.elementwise
+
+This module provides a collection of functions for root finding and
+minimization of scalar, real-valued functions of one variable. Unlike their
+counterparts in the base :mod:`scipy.optimize` namespace, these functions work
+elementwise, enabling the solution of many related problems in an efficient,
+vectorized call. Furthermore, when environment variable ``SCIPY_ARRAY_API=1``,
+these functions can accept non-NumPy, array API standard compatible arrays and
+perform all calculations using the corresponding array library (e.g. PyTorch,
+JAX, CuPy).
+
+Root finding
+============
+
+.. autosummary::
+ :toctree: generated/
+
+ find_root
+ bracket_root
+
+Minimization
+============
+
+.. autosummary::
+ :toctree: generated/
+
+ find_minimum
+ bracket_minimum
+
+"""
+from ._elementwise import find_root, find_minimum, bracket_root, bracket_minimum # noqa: F401, E501
+
+__all__ = ["find_root", "find_minimum", "bracket_root", "bracket_minimum"]
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/lbfgsb.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/lbfgsb.py
new file mode 100644
index 0000000000000000000000000000000000000000..866407cabb3decf0ff72239e6fd372f69f7550c0
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/lbfgsb.py
@@ -0,0 +1,23 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'LbfgsInvHessProduct',
+ 'OptimizeResult',
+ 'fmin_l_bfgs_b',
+ 'zeros',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="lbfgsb",
+ private_modules=["_lbfgsb_py"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/linesearch.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..cb34b25092da34991c868683da3d6a894d1a7f80
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/linesearch.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ["line_search"] # noqa: F822
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="linesearch",
+ private_modules=["_linesearch"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/minpack.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/minpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..29fddef537361d8508e6343d23b2c3c7d6d12ec6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/minpack.py
@@ -0,0 +1,27 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'OptimizeResult',
+ 'OptimizeWarning',
+ 'curve_fit',
+ 'fixed_point',
+ 'fsolve',
+ 'least_squares',
+ 'leastsq',
+ 'zeros',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="minpack",
+ private_modules=["_minpack_py"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/minpack2.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/minpack2.py
new file mode 100644
index 0000000000000000000000000000000000000000..cdb3503e0e1e4c886c89bfb62e6a2efc3ba54549
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/minpack2.py
@@ -0,0 +1,17 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__: list[str] = []
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="minpack2",
+ private_modules=["_minpack2"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/moduleTNC.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/moduleTNC.py
new file mode 100644
index 0000000000000000000000000000000000000000..3fc5884ed5c39437b7681395419d641443a1fdb8
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/moduleTNC.py
@@ -0,0 +1,19 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = []
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="moduleTNC",
+ private_modules=["_moduleTNC"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/nonlin.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..20b490b40ef790a2943d539790b45fc378df2c76
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/nonlin.py
@@ -0,0 +1,29 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'BroydenFirst',
+ 'InverseJacobian',
+ 'KrylovJacobian',
+ 'anderson',
+ 'broyden1',
+ 'broyden2',
+ 'diagbroyden',
+ 'excitingmixing',
+ 'linearmixing',
+ 'newton_krylov',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="nonlin",
+ private_modules=["_nonlin"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/optimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..4db770e5f6e921906c916f2650003d92f5507791
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/optimize.py
@@ -0,0 +1,40 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'OptimizeResult',
+ 'OptimizeWarning',
+ 'approx_fprime',
+ 'bracket',
+ 'brent',
+ 'brute',
+ 'check_grad',
+ 'fmin',
+ 'fmin_bfgs',
+ 'fmin_cg',
+ 'fmin_ncg',
+ 'fmin_powell',
+ 'fminbound',
+ 'golden',
+ 'line_search',
+ 'rosen',
+ 'rosen_der',
+ 'rosen_hess',
+ 'rosen_hess_prod',
+ 'show_options',
+ 'zeros',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="optimize",
+ private_modules=["_optimize"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/slsqp.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/slsqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..2b79d93a55d363ac4a91154f30919ba5e449b8c7
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/slsqp.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'OptimizeResult',
+ 'fmin_slsqp',
+ 'slsqp',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="slsqp",
+ private_modules=["_slsqp_py"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/.__cython_examples b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/.__cython_examples
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/.__cython_examples differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__basinhopping.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__basinhopping.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__basinhopping.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__differential_evolution.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__differential_evolution.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__differential_evolution.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__dual_annealing.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__dual_annealing.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__dual_annealing.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__linprog_clean_inputs.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__linprog_clean_inputs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__linprog_clean_inputs.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__numdiff.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__numdiff.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__numdiff.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__remove_redundancy.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__remove_redundancy.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__remove_redundancy.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__root.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__root.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__root.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__shgo.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__shgo.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__shgo.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__spectral.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test__spectral.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_bracket.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_bracket.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_bracket.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_chandrupatla.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_chandrupatla.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_chandrupatla.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_cobyla.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_cobyla.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_cobyla.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_cobyqa.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_cobyqa.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_cobyqa.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_constraint_conversion.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_constraint_conversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_constraint_conversion.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_constraints.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_constraints.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_cython_optimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_cython_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_cython_optimize.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_differentiable_functions.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_differentiable_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_differentiable_functions.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_direct.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_direct.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_direct.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_extending.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_extending.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_hessian_update_strategy.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_hessian_update_strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_hessian_update_strategy.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_isotonic_regression.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_isotonic_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_isotonic_regression.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lbfgsb_hessinv.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lbfgsb_hessinv.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lbfgsb_hessinv.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lbfgsb_setulb.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lbfgsb_setulb.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lbfgsb_setulb.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_least_squares.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_least_squares.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_least_squares.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_linear_assignment.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_linear_assignment.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_linear_assignment.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_linesearch.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_linesearch.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_linprog.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_linprog.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_linprog.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lsq_common.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lsq_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lsq_common.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lsq_linear.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lsq_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_lsq_linear.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_milp.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_milp.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_milp.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_minimize_constrained.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_minimize_constrained.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_minimize_constrained.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_minpack.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_minpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_minpack.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_nnls.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_nnls.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_nnls.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_nonlin.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_nonlin.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_optimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_optimize.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_quadratic_assignment.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_quadratic_assignment.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_quadratic_assignment.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_regression.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_regression.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_slsqp.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_slsqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_slsqp.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_tnc.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_tnc.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_trustregion.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_trustregion.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_trustregion.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_trustregion_exact.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_trustregion_exact.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_trustregion_exact.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_trustregion_krylov.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_trustregion_krylov.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_trustregion_krylov.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_zeros.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_zeros.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/._test_zeros.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/._extending.pyx b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/._extending.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/._extending.pyx differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/._meson.build b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/._meson.build
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/._meson.build differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx
new file mode 100644
index 0000000000000000000000000000000000000000..d831b3c7f5dcaee71371027c7ee95aa9ee51d157
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/extending.pyx
@@ -0,0 +1,43 @@
+#!/usr/bin/env python3
+#cython: language_level=3
+#cython: boundscheck=False
+#cython: wraparound=False
+"""
+Taken from docstring for scipy.optimize.cython_optimize module.
+"""
+
+from scipy.optimize.cython_optimize cimport brentq
+
+# import math from Cython
+from libc cimport math
+
+myargs = {'C0': 1.0, 'C1': 0.7} # a dictionary of extra arguments
+XLO, XHI = 0.5, 1.0 # lower and upper search boundaries
+XTOL, RTOL, MITR = 1e-3, 1e-3, 10 # other solver parameters
+
+# user-defined struct for extra parameters
+ctypedef struct test_params:
+ double C0
+ double C1
+
+
+# user-defined callback
+cdef double f(double x, void *args) noexcept:
+ cdef test_params *myargs = args
+ return myargs.C0 - math.exp(-(x - myargs.C1))
+
+
+# Cython wrapper function
+cdef double brentq_wrapper_example(dict args, double xa, double xb,
+ double xtol, double rtol, int mitr):
+ # Cython automatically casts dictionary to struct
+ cdef test_params myargs = args
+ return brentq(
+ f, xa, xb, &myargs, xtol, rtol, mitr, NULL)
+
+
+# Python function
+def brentq_example(args=myargs, xa=XLO, xb=XHI, xtol=XTOL, rtol=RTOL,
+ mitr=MITR):
+ '''Calls Cython wrapper from Python.'''
+ return brentq_wrapper_example(args, xa, xb, xtol, rtol, mitr)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/meson.build b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/meson.build
new file mode 100644
index 0000000000000000000000000000000000000000..1fb210fbecb84a21518ad8828a789376410f02aa
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/_cython_examples/meson.build
@@ -0,0 +1,32 @@
+project('random-build-examples', 'c', 'cpp', 'cython')
+
+fs = import('fs')
+
+py3 = import('python').find_installation(pure: false)
+
+cy = meson.get_compiler('cython')
+
+if not cy.version().version_compare('>=3.0.8')
+ error('tests requires Cython >= 3.0.8')
+endif
+
+cython_args = []
+if cy.version().version_compare('>=3.1.0')
+ cython_args += ['-Xfreethreading_compatible=True']
+endif
+
+py3.extension_module(
+ 'extending',
+ 'extending.pyx',
+ cython_args: cython_args,
+ install: false,
+)
+
+extending_cpp = fs.copyfile('extending.pyx', 'extending_cpp.pyx')
+py3.extension_module(
+ 'extending_cpp',
+ extending_cpp,
+ cython_args: cython_args,
+ install: false,
+ override_options : ['cython_language=cpp']
+)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__basinhopping.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__basinhopping.py
new file mode 100644
index 0000000000000000000000000000000000000000..3f21ae1728a0fa0918b5da6b2292fe88fc695fe5
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__basinhopping.py
@@ -0,0 +1,537 @@
+"""
+Unit tests for the basin hopping global minimization algorithm.
+"""
+import copy
+
+from numpy.testing import (assert_almost_equal, assert_equal, assert_,
+ assert_allclose)
+import pytest
+from pytest import raises as assert_raises
+import numpy as np
+from numpy import cos, sin
+
+from scipy.optimize import basinhopping, OptimizeResult
+from scipy.optimize._basinhopping import (
+ Storage, RandomDisplacement, Metropolis, AdaptiveStepsize)
+
+
+def func1d(x):
+ f = cos(14.5 * x - 0.3) + (x + 0.2) * x
+ df = np.array(-14.5 * sin(14.5 * x - 0.3) + 2. * x + 0.2)
+ return f, df
+
+
+def func2d_nograd(x):
+ f = cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + 0.2) * x[0]
+ return f
+
+
+def func2d(x):
+ f = cos(14.5 * x[0] - 0.3) + (x[1] + 0.2) * x[1] + (x[0] + 0.2) * x[0]
+ df = np.zeros(2)
+ df[0] = -14.5 * sin(14.5 * x[0] - 0.3) + 2. * x[0] + 0.2
+ df[1] = 2. * x[1] + 0.2
+ return f, df
+
+
+def func2d_easyderiv(x):
+ f = 2.0*x[0]**2 + 2.0*x[0]*x[1] + 2.0*x[1]**2 - 6.0*x[0]
+ df = np.zeros(2)
+ df[0] = 4.0*x[0] + 2.0*x[1] - 6.0
+ df[1] = 2.0*x[0] + 4.0*x[1]
+
+ return f, df
+
+
+class MyTakeStep1(RandomDisplacement):
+ """use a copy of displace, but have it set a special parameter to
+ make sure it's actually being used."""
+ def __init__(self):
+ self.been_called = False
+ super().__init__()
+
+ def __call__(self, x):
+ self.been_called = True
+ return super().__call__(x)
+
+
+def myTakeStep2(x):
+ """redo RandomDisplacement in function form without the attribute stepsize
+ to make sure everything still works ok
+ """
+ s = 0.5
+ x += np.random.uniform(-s, s, np.shape(x))
+ return x
+
+
+class MyAcceptTest:
+ """pass a custom accept test
+
+ This does nothing but make sure it's being used and ensure all the
+ possible return values are accepted
+ """
+ def __init__(self):
+ self.been_called = False
+ self.ncalls = 0
+ self.testres = [False, 'force accept', True, np.bool_(True),
+ np.bool_(False), [], {}, 0, 1]
+
+ def __call__(self, **kwargs):
+ self.been_called = True
+ self.ncalls += 1
+ if self.ncalls - 1 < len(self.testres):
+ return self.testres[self.ncalls - 1]
+ else:
+ return True
+
+
+class MyCallBack:
+ """pass a custom callback function
+
+ This makes sure it's being used. It also returns True after 10
+ steps to ensure that it's stopping early.
+
+ """
+ def __init__(self):
+ self.been_called = False
+ self.ncalls = 0
+
+ def __call__(self, x, f, accepted):
+ self.been_called = True
+ self.ncalls += 1
+ if self.ncalls == 10:
+ return True
+
+
+class TestBasinHopping:
+
+ def setup_method(self):
+ """ Tests setup.
+
+ Run tests based on the 1-D and 2-D functions described above.
+ """
+ self.x0 = (1.0, [1.0, 1.0])
+ self.sol = (-0.195, np.array([-0.195, -0.1]))
+
+ self.tol = 3 # number of decimal places
+
+ self.niter = 100
+ self.disp = False
+
+ self.kwargs = {"method": "L-BFGS-B", "jac": True}
+ self.kwargs_nograd = {"method": "L-BFGS-B"}
+
+ def test_TypeError(self):
+ # test the TypeErrors are raised on bad input
+ i = 1
+ # if take_step is passed, it must be callable
+ assert_raises(TypeError, basinhopping, func2d, self.x0[i],
+ take_step=1)
+ # if accept_test is passed, it must be callable
+ assert_raises(TypeError, basinhopping, func2d, self.x0[i],
+ accept_test=1)
+
+ def test_input_validation(self):
+ msg = 'target_accept_rate has to be in range \\(0, 1\\)'
+ with assert_raises(ValueError, match=msg):
+ basinhopping(func1d, self.x0[0], target_accept_rate=0.)
+ with assert_raises(ValueError, match=msg):
+ basinhopping(func1d, self.x0[0], target_accept_rate=1.)
+
+ msg = 'stepwise_factor has to be in range \\(0, 1\\)'
+ with assert_raises(ValueError, match=msg):
+ basinhopping(func1d, self.x0[0], stepwise_factor=0.)
+ with assert_raises(ValueError, match=msg):
+ basinhopping(func1d, self.x0[0], stepwise_factor=1.)
+
+ def test_1d_grad(self):
+ # test 1-D minimizations with gradient
+ i = 0
+ res = basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=self.niter, disp=self.disp)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+
+ def test_2d(self):
+ # test 2d minimizations with gradient
+ i = 1
+ res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=self.niter, disp=self.disp)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+ assert_(res.nfev > 0)
+
+ def test_njev(self):
+ # test njev is returned correctly
+ i = 1
+ minimizer_kwargs = self.kwargs.copy()
+ # L-BFGS-B doesn't use njev, but BFGS does
+ minimizer_kwargs["method"] = "BFGS"
+ res = basinhopping(func2d, self.x0[i],
+ minimizer_kwargs=minimizer_kwargs, niter=self.niter,
+ disp=self.disp)
+ assert_(res.nfev > 0)
+ assert_equal(res.nfev, res.njev)
+
+ def test_jac(self):
+ # test Jacobian returned
+ minimizer_kwargs = self.kwargs.copy()
+ # BFGS returns a Jacobian
+ minimizer_kwargs["method"] = "BFGS"
+
+ res = basinhopping(func2d_easyderiv, [0.0, 0.0],
+ minimizer_kwargs=minimizer_kwargs, niter=self.niter,
+ disp=self.disp)
+
+ assert_(hasattr(res.lowest_optimization_result, "jac"))
+
+ # in this case, the Jacobian is just [df/dx, df/dy]
+ _, jacobian = func2d_easyderiv(res.x)
+ assert_almost_equal(res.lowest_optimization_result.jac, jacobian,
+ self.tol)
+
+ def test_2d_nograd(self):
+ # test 2-D minimizations without gradient
+ i = 1
+ res = basinhopping(func2d_nograd, self.x0[i],
+ minimizer_kwargs=self.kwargs_nograd,
+ niter=self.niter, disp=self.disp)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+
+ @pytest.mark.fail_slow(10)
+ def test_all_minimizers(self):
+ # Test 2-D minimizations with gradient. Nelder-Mead, Powell, COBYLA, and
+ # COBYQA don't accept jac=True, so aren't included here.
+ i = 1
+ methods = ['CG', 'BFGS', 'Newton-CG', 'L-BFGS-B', 'TNC', 'SLSQP']
+ minimizer_kwargs = copy.copy(self.kwargs)
+ for method in methods:
+ minimizer_kwargs["method"] = method
+ res = basinhopping(func2d, self.x0[i],
+ minimizer_kwargs=minimizer_kwargs,
+ niter=self.niter, disp=self.disp)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+
+ @pytest.mark.fail_slow(40)
+ @pytest.mark.parametrize("method", [
+ 'CG', 'BFGS', 'L-BFGS-B', 'TNC', 'SLSQP',
+ 'Nelder-Mead', 'Powell', 'COBYLA', 'COBYQA'])
+ def test_all_nograd_minimizers(self, method):
+ # Test 2-D minimizations without gradient. Newton-CG requires jac=True,
+ # so not included here.
+ i = 1
+ minimizer_kwargs = self.kwargs_nograd.copy()
+ minimizer_kwargs["method"] = method
+ # These methods take extensive amount of time on this problem
+ niter = 10 if method in ('COBYLA', 'COBYQA') else self.niter
+
+ res = basinhopping(func2d_nograd, self.x0[i],
+ minimizer_kwargs=minimizer_kwargs,
+ niter=niter, disp=self.disp, seed=1234)
+
+ tol = 2 if method == 'COBYLA' else self.tol
+ assert_almost_equal(res.x, self.sol[i], decimal=tol)
+
+ def test_pass_takestep(self):
+ # test that passing a custom takestep works
+ # also test that the stepsize is being adjusted
+ takestep = MyTakeStep1()
+ initial_step_size = takestep.stepsize
+ i = 1
+ res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=self.niter, disp=self.disp,
+ take_step=takestep)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+ assert_(takestep.been_called)
+ # make sure that the build in adaptive step size has been used
+ assert_(initial_step_size != takestep.stepsize)
+
+ def test_pass_simple_takestep(self):
+ # test that passing a custom takestep without attribute stepsize
+ takestep = myTakeStep2
+ i = 1
+ res = basinhopping(func2d_nograd, self.x0[i],
+ minimizer_kwargs=self.kwargs_nograd,
+ niter=self.niter, disp=self.disp,
+ take_step=takestep)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+
+ def test_pass_accept_test(self):
+ # test passing a custom accept test
+ # makes sure it's being used and ensures all the possible return values
+ # are accepted.
+ accept_test = MyAcceptTest()
+ i = 1
+ # there's no point in running it more than a few steps.
+ basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=10, disp=self.disp, accept_test=accept_test)
+ assert_(accept_test.been_called)
+
+ def test_pass_callback(self):
+ # test passing a custom callback function
+ # This makes sure it's being used. It also returns True after 10 steps
+ # to ensure that it's stopping early.
+ callback = MyCallBack()
+ i = 1
+ # there's no point in running it more than a few steps.
+ res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=30, disp=self.disp, callback=callback)
+ assert_(callback.been_called)
+ assert_("callback" in res.message[0])
+ # One of the calls of MyCallBack is during BasinHoppingRunner
+ # construction, so there are only 9 remaining before MyCallBack stops
+ # the minimization.
+ assert_equal(res.nit, 9)
+
+ def test_minimizer_fail(self):
+ # test if a minimizer fails
+ i = 1
+ self.kwargs["options"] = dict(maxiter=0)
+ niter = 10
+ res = basinhopping(func2d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=niter, disp=self.disp)
+ # the number of failed minimizations should be the number of
+ # iterations + 1
+ assert_equal(res.nit + 1, res.minimization_failures)
+
+ def test_niter_zero(self):
+ # gh5915, what happens if you call basinhopping with niter=0
+ i = 0
+ basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=0, disp=self.disp)
+
+ def test_rng_reproducibility(self):
+ # rng should ensure reproducibility between runs
+ minimizer_kwargs = {"method": "L-BFGS-B", "jac": True}
+
+ f_1 = []
+
+ def callback(x, f, accepted):
+ f_1.append(f)
+
+ basinhopping(func2d, [1.0, 1.0], minimizer_kwargs=minimizer_kwargs,
+ niter=10, callback=callback, rng=10)
+
+ f_2 = []
+
+ def callback2(x, f, accepted):
+ f_2.append(f)
+
+ basinhopping(func2d, [1.0, 1.0], minimizer_kwargs=minimizer_kwargs,
+ niter=10, callback=callback2, rng=10)
+ assert_equal(np.array(f_1), np.array(f_2))
+
+ def test_random_gen(self):
+ # check that np.random.Generator can be used (numpy >= 1.17)
+ rng = np.random.default_rng(1)
+
+ minimizer_kwargs = {"method": "L-BFGS-B", "jac": True}
+
+ res1 = basinhopping(func2d, [1.0, 1.0],
+ minimizer_kwargs=minimizer_kwargs,
+ niter=10, rng=rng)
+
+ rng = np.random.default_rng(1)
+ res2 = basinhopping(func2d, [1.0, 1.0],
+ minimizer_kwargs=minimizer_kwargs,
+ niter=10, rng=rng)
+ assert_equal(res1.x, res2.x)
+
+ def test_monotonic_basin_hopping(self):
+ # test 1-D minimizations with gradient and T=0
+ i = 0
+
+ res = basinhopping(func1d, self.x0[i], minimizer_kwargs=self.kwargs,
+ niter=self.niter, disp=self.disp, T=0)
+ assert_almost_equal(res.x, self.sol[i], self.tol)
+
+
+class Test_Storage:
+ def create_storage(self):
+ self.x0 = np.array(1)
+ self.f0 = 0
+
+ minres = OptimizeResult(success=True)
+ minres.x = self.x0
+ minres.fun = self.f0
+
+ return Storage(minres)
+
+ def test_higher_f_rejected(self):
+ storage = self.create_storage()
+ new_minres = OptimizeResult(success=True)
+ new_minres.x = self.x0 + 1
+ new_minres.fun = self.f0 + 1
+
+ ret = storage.update(new_minres)
+ minres = storage.get_lowest()
+ assert_equal(self.x0, minres.x)
+ assert_equal(self.f0, minres.fun)
+ assert_(not ret)
+
+ @pytest.mark.parametrize('success', [True, False])
+ def test_lower_f_accepted(self, success):
+ storage = self.create_storage()
+ new_minres = OptimizeResult(success=success)
+ new_minres.x = self.x0 + 1
+ new_minres.fun = self.f0 - 1
+
+ ret = storage.update(new_minres)
+ minres = storage.get_lowest()
+ assert (self.x0 != minres.x) == success # can't use `is`
+ assert (self.f0 != minres.fun) == success # left side is NumPy bool
+ assert ret is success
+
+
+class Test_RandomDisplacement:
+ def setup_method(self):
+ self.stepsize = 1.0
+ self.N = 300000
+
+ def test_random(self):
+ # the mean should be 0
+ # the variance should be (2*stepsize)**2 / 12
+ # note these tests are random, they will fail from time to time
+ rng = np.random.RandomState(0)
+ x0 = np.zeros([self.N])
+ displace = RandomDisplacement(stepsize=self.stepsize, rng=rng)
+ x = displace(x0)
+ v = (2. * self.stepsize) ** 2 / 12
+ assert_almost_equal(np.mean(x), 0., 1)
+ assert_almost_equal(np.var(x), v, 1)
+
+
+class Test_Metropolis:
+ def setup_method(self):
+ self.T = 2.
+ self.met = Metropolis(self.T)
+ self.res_new = OptimizeResult(success=True, fun=0.)
+ self.res_old = OptimizeResult(success=True, fun=1.)
+
+ def test_boolean_return(self):
+ # the return must be a bool, else an error will be raised in
+ # basinhopping
+ ret = self.met(res_new=self.res_new, res_old=self.res_old)
+ assert isinstance(ret, bool)
+
+ def test_lower_f_accepted(self):
+ assert_(self.met(res_new=self.res_new, res_old=self.res_old))
+
+ def test_accept(self):
+ # test that steps are randomly accepted for f_new > f_old
+ one_accept = False
+ one_reject = False
+ for i in range(1000):
+ if one_accept and one_reject:
+ break
+ res_new = OptimizeResult(success=True, fun=1.)
+ res_old = OptimizeResult(success=True, fun=0.5)
+ ret = self.met(res_new=res_new, res_old=res_old)
+ if ret:
+ one_accept = True
+ else:
+ one_reject = True
+ assert_(one_accept)
+ assert_(one_reject)
+
+ def test_GH7495(self):
+ # an overflow in exp was producing a RuntimeWarning
+ # create own object here in case someone changes self.T
+ met = Metropolis(2)
+ res_new = OptimizeResult(success=True, fun=0.)
+ res_old = OptimizeResult(success=True, fun=2000)
+ with np.errstate(over='raise'):
+ met.accept_reject(res_new=res_new, res_old=res_old)
+
+ def test_gh7799(self):
+ # gh-7799 reported a problem in which local search was successful but
+ # basinhopping returned an invalid solution. Show that this is fixed.
+ def func(x):
+ return (x**2-8)**2+(x+2)**2
+
+ x0 = -4
+ limit = 50 # Constrain to func value >= 50
+ con = {'type': 'ineq', 'fun': lambda x: func(x) - limit},
+ res = basinhopping(
+ func,
+ x0,
+ 30,
+ seed=np.random.RandomState(1234),
+ minimizer_kwargs={'constraints': con}
+ )
+ assert res.success
+ assert_allclose(res.fun, limit, rtol=1e-6)
+
+ def test_accept_gh7799(self):
+ # Metropolis should not accept the result of an unsuccessful new local
+ # search if the old local search was successful
+
+ met = Metropolis(0) # monotonic basin hopping
+ res_new = OptimizeResult(success=True, fun=0.)
+ res_old = OptimizeResult(success=True, fun=1.)
+
+ # if new local search was successful and energy is lower, accept
+ assert met(res_new=res_new, res_old=res_old)
+ # if new res is unsuccessful, don't accept - even if energy is lower
+ res_new.success = False
+ assert not met(res_new=res_new, res_old=res_old)
+ # ...unless the old res was unsuccessful, too. In that case, why not?
+ res_old.success = False
+ assert met(res_new=res_new, res_old=res_old)
+
+ def test_reject_all_gh7799(self):
+ # Test the behavior when there is no feasible solution
+ def fun(x):
+ return x@x
+
+ def constraint(x):
+ return x + 1
+
+ kwargs = {'constraints': {'type': 'eq', 'fun': constraint},
+ 'bounds': [(0, 1), (0, 1)], 'method': 'slsqp'}
+ res = basinhopping(fun, x0=[2, 3], niter=10, minimizer_kwargs=kwargs)
+ assert not res.success
+
+
+@pytest.mark.thread_unsafe(reason="shared state")
+class Test_AdaptiveStepsize:
+ def setup_method(self):
+ self.stepsize = 1.
+ self.ts = RandomDisplacement(stepsize=self.stepsize)
+ self.target_accept_rate = 0.5
+ self.takestep = AdaptiveStepsize(takestep=self.ts, verbose=False,
+ accept_rate=self.target_accept_rate)
+
+ def test_adaptive_increase(self):
+ # if few steps are rejected, the stepsize should increase
+ x = 0.
+ self.takestep(x)
+ self.takestep.report(False)
+ for i in range(self.takestep.interval):
+ self.takestep(x)
+ self.takestep.report(True)
+ assert_(self.ts.stepsize > self.stepsize)
+
+ def test_adaptive_decrease(self):
+ # if few steps are rejected, the stepsize should increase
+ x = 0.
+ self.takestep(x)
+ self.takestep.report(True)
+ for i in range(self.takestep.interval):
+ self.takestep(x)
+ self.takestep.report(False)
+ assert_(self.ts.stepsize < self.stepsize)
+
+ def test_all_accepted(self):
+ # test that everything works OK if all steps were accepted
+ x = 0.
+ for i in range(self.takestep.interval + 1):
+ self.takestep(x)
+ self.takestep.report(True)
+ assert_(self.ts.stepsize > self.stepsize)
+
+ def test_all_rejected(self):
+ # test that everything works OK if all steps were rejected
+ x = 0.
+ for i in range(self.takestep.interval + 1):
+ self.takestep(x)
+ self.takestep.report(False)
+ assert_(self.ts.stepsize < self.stepsize)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__differential_evolution.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__differential_evolution.py
new file mode 100644
index 0000000000000000000000000000000000000000..58ca58cdc53746bf5118e21ad98b4a192af3d5c8
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__differential_evolution.py
@@ -0,0 +1,1758 @@
+"""
+Unit tests for the differential global minimization algorithm.
+"""
+from multiprocessing.dummy import Pool as ThreadPool
+import platform
+import warnings
+
+from scipy._lib._gcutils import assert_deallocated
+from scipy.optimize._differentialevolution import (DifferentialEvolutionSolver,
+ _ConstraintWrapper)
+from scipy.optimize import differential_evolution, OptimizeResult
+from scipy.optimize._constraints import (Bounds, NonlinearConstraint,
+ LinearConstraint)
+from scipy.optimize import rosen, minimize, rosen_der
+from scipy.sparse import csr_array
+from scipy import stats
+
+import numpy as np
+from numpy.testing import (assert_equal, assert_allclose, assert_almost_equal,
+ assert_string_equal, assert_)
+from pytest import raises as assert_raises, warns
+import pytest
+
+
+class TestDifferentialEvolutionSolver:
+
+ def setup_method(self):
+ self.old_seterr = np.seterr(invalid='raise')
+ self.limits = np.array([[0., 0.],
+ [2., 2.]])
+ self.bounds = [(0., 2.), (0., 2.)]
+
+ self.dummy_solver = DifferentialEvolutionSolver(self.quadratic,
+ [(0, 100)])
+
+ # dummy_solver2 will be used to test mutation strategies
+ self.dummy_solver2 = DifferentialEvolutionSolver(self.quadratic,
+ [(0, 1)],
+ popsize=7,
+ mutation=0.5)
+ # create a population that's only 7 members long
+ # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
+ population = np.atleast_2d(np.arange(0.1, 0.8, 0.1)).T
+ self.dummy_solver2.population = population
+
+ def teardown_method(self):
+ np.seterr(**self.old_seterr)
+
+ def quadratic(self, x):
+ return x[0]**2
+
+ def test__strategy_resolves(self):
+ # test that the correct mutation function is resolved by
+ # different requested strategy arguments
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='best1exp')
+ assert_equal(solver.strategy, 'best1exp')
+ assert_equal(solver.mutation_func.__name__, '_best1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='best1bin')
+ assert_equal(solver.strategy, 'best1bin')
+ assert_equal(solver.mutation_func.__name__, '_best1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='rand1bin')
+ assert_equal(solver.strategy, 'rand1bin')
+ assert_equal(solver.mutation_func.__name__, '_rand1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='rand1exp')
+ assert_equal(solver.strategy, 'rand1exp')
+ assert_equal(solver.mutation_func.__name__, '_rand1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='rand2exp')
+ assert_equal(solver.strategy, 'rand2exp')
+ assert_equal(solver.mutation_func.__name__, '_rand2')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='best2bin')
+ assert_equal(solver.strategy, 'best2bin')
+ assert_equal(solver.mutation_func.__name__, '_best2')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='rand2bin')
+ assert_equal(solver.strategy, 'rand2bin')
+ assert_equal(solver.mutation_func.__name__, '_rand2')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='rand2exp')
+ assert_equal(solver.strategy, 'rand2exp')
+ assert_equal(solver.mutation_func.__name__, '_rand2')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='randtobest1bin')
+ assert_equal(solver.strategy, 'randtobest1bin')
+ assert_equal(solver.mutation_func.__name__, '_randtobest1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='randtobest1exp')
+ assert_equal(solver.strategy, 'randtobest1exp')
+ assert_equal(solver.mutation_func.__name__, '_randtobest1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='currenttobest1bin')
+ assert_equal(solver.strategy, 'currenttobest1bin')
+ assert_equal(solver.mutation_func.__name__, '_currenttobest1')
+
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='currenttobest1exp')
+ assert_equal(solver.strategy, 'currenttobest1exp')
+ assert_equal(solver.mutation_func.__name__, '_currenttobest1')
+
+ def test__mutate1(self):
+ # strategies */1/*, i.e. rand/1/bin, best/1/exp, etc.
+ result = np.array([0.05])
+ trial = self.dummy_solver2._best1(np.array([2, 3, 4, 5, 6]))
+ assert_allclose(trial, result)
+
+ result = np.array([0.25])
+ trial = self.dummy_solver2._rand1(np.array([2, 3, 4, 5, 6]))
+ assert_allclose(trial, result)
+
+ def test__mutate2(self):
+ # strategies */2/*, i.e. rand/2/bin, best/2/exp, etc.
+ # [0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7]
+
+ result = np.array([-0.1])
+ trial = self.dummy_solver2._best2(np.array([2, 3, 4, 5, 6]))
+ assert_allclose(trial, result)
+
+ result = np.array([0.1])
+ trial = self.dummy_solver2._rand2(np.array([2, 3, 4, 5, 6]))
+ assert_allclose(trial, result)
+
+ def test__randtobest1(self):
+ # strategies randtobest/1/*
+ result = np.array([0.15])
+ trial = self.dummy_solver2._randtobest1(np.array([2, 3, 4, 5, 6]))
+ assert_allclose(trial, result)
+
+ def test__currenttobest1(self):
+ # strategies currenttobest/1/*
+ result = np.array([0.1])
+ trial = self.dummy_solver2._currenttobest1(
+ 1,
+ np.array([2, 3, 4, 5, 6])
+ )
+ assert_allclose(trial, result)
+
+ def test_can_init_with_dithering(self):
+ mutation = (0.5, 1)
+ solver = DifferentialEvolutionSolver(self.quadratic,
+ self.bounds,
+ mutation=mutation)
+
+ assert_equal(solver.dither, list(mutation))
+
+ def test_invalid_mutation_values_arent_accepted(self):
+ func = rosen
+ mutation = (0.5, 3)
+ assert_raises(ValueError,
+ DifferentialEvolutionSolver,
+ func,
+ self.bounds,
+ mutation=mutation)
+
+ mutation = (-1, 1)
+ assert_raises(ValueError,
+ DifferentialEvolutionSolver,
+ func,
+ self.bounds,
+ mutation=mutation)
+
+ mutation = (0.1, np.nan)
+ assert_raises(ValueError,
+ DifferentialEvolutionSolver,
+ func,
+ self.bounds,
+ mutation=mutation)
+
+ mutation = 0.5
+ solver = DifferentialEvolutionSolver(func,
+ self.bounds,
+ mutation=mutation)
+ assert_equal(0.5, solver.scale)
+ assert_equal(None, solver.dither)
+
+ def test_invalid_functional(self):
+ def func(x):
+ return np.array([np.sum(x ** 2), np.sum(x)])
+
+ with assert_raises(
+ RuntimeError,
+ match=r"func\(x, \*args\) must return a scalar value"):
+ differential_evolution(func, [(-2, 2), (-2, 2)])
+
+ def test__scale_parameters(self):
+ trial = np.array([0.3])
+ assert_equal(30, self.dummy_solver._scale_parameters(trial))
+
+ # it should also work with the limits reversed
+ self.dummy_solver.limits = np.array([[100], [0.]])
+ assert_equal(30, self.dummy_solver._scale_parameters(trial))
+
+ def test__unscale_parameters(self):
+ trial = np.array([30])
+ assert_equal(0.3, self.dummy_solver._unscale_parameters(trial))
+
+ # it should also work with the limits reversed
+ self.dummy_solver.limits = np.array([[100], [0.]])
+ assert_equal(0.3, self.dummy_solver._unscale_parameters(trial))
+
+ def test_equal_bounds(self):
+ with np.errstate(invalid='raise'):
+ solver = DifferentialEvolutionSolver(
+ self.quadratic,
+ bounds=[(2.0, 2.0), (1.0, 3.0)]
+ )
+ v = solver._unscale_parameters([2.0, 2.0])
+ assert_allclose(v, 0.5)
+
+ res = differential_evolution(self.quadratic, [(2.0, 2.0), (3.0, 3.0)])
+ assert_equal(res.x, [2.0, 3.0])
+
+ def test__ensure_constraint(self):
+ trial = np.array([1.1, -100, 0.9, 2., 300., -0.00001])
+ self.dummy_solver._ensure_constraint(trial)
+
+ assert_equal(trial[2], 0.9)
+ assert_(np.logical_and(trial >= 0, trial <= 1).all())
+
+ def test_differential_evolution(self):
+ # test that the Jmin of DifferentialEvolutionSolver
+ # is the same as the function evaluation
+ solver = DifferentialEvolutionSolver(
+ self.quadratic, [(-2, 2)], maxiter=1, polish=False
+ )
+ result = solver.solve()
+ assert_equal(result.fun, self.quadratic(result.x))
+
+ solver = DifferentialEvolutionSolver(
+ self.quadratic, [(-2, 2)], maxiter=1, polish=True
+ )
+ result = solver.solve()
+ assert_equal(result.fun, self.quadratic(result.x))
+
+ def test_best_solution_retrieval(self):
+ # test that the getter property method for the best solution works.
+ solver = DifferentialEvolutionSolver(self.quadratic, [(-2, 2)])
+ result = solver.solve()
+ assert_allclose(result.x, solver.x, atol=1e-15, rtol=0)
+
+ def test_intermediate_result(self):
+ # Check that intermediate result object passed into the callback
+ # function contains the expected information and that raising
+ # `StopIteration` causes the expected behavior.
+ maxiter = 10
+
+ def func(x):
+ val = rosen(x)
+ if val < func.val:
+ func.x = x
+ func.val = val
+ return val
+ func.x = None
+ func.val = np.inf
+
+ def callback(intermediate_result):
+ callback.nit += 1
+ callback.intermediate_result = intermediate_result
+ assert intermediate_result.population.ndim == 2
+ assert intermediate_result.population.shape[1] == 2
+ assert intermediate_result.nit == callback.nit
+
+ # Check that `x` and `fun` attributes are the best found so far
+ assert_equal(intermediate_result.x, callback.func.x)
+ assert_equal(intermediate_result.fun, callback.func.val)
+
+ # Check for consistency between `fun`, `population_energies`,
+ # `x`, and `population`
+ assert_equal(intermediate_result.fun, rosen(intermediate_result.x))
+ for i in range(len(intermediate_result.population_energies)):
+ res = intermediate_result.population_energies[i]
+ ref = rosen(intermediate_result.population[i])
+ assert_equal(res, ref)
+ assert_equal(intermediate_result.x,
+ intermediate_result.population[0])
+ assert_equal(intermediate_result.fun,
+ intermediate_result.population_energies[0])
+
+ assert intermediate_result.message == 'in progress'
+ assert intermediate_result.success is True
+ assert isinstance(intermediate_result, OptimizeResult)
+ if callback.nit == maxiter:
+ raise StopIteration
+ callback.nit = 0
+ callback.intermediate_result = None
+ callback.func = func
+
+ bounds = [(0, 2), (0, 2)]
+ kwargs = dict(func=func, bounds=bounds, rng=838245, polish=False)
+ res = differential_evolution(**kwargs, callback=callback)
+ ref = differential_evolution(**kwargs, maxiter=maxiter)
+
+ # Check that final `intermediate_result` is equivalent to returned
+ # result object and that terminating with callback `StopIteration`
+ # after `maxiter` iterations is equivalent to terminating with
+ # `maxiter` parameter.
+ assert res.success is ref.success is False
+ assert callback.nit == res.nit == maxiter
+ assert res.message == 'callback function requested stop early'
+ assert ref.message == 'Maximum number of iterations has been exceeded.'
+ for field, val in ref.items():
+ if field in {'message', 'success'}: # checked separately
+ continue
+ assert_equal(callback.intermediate_result[field], val)
+ assert_equal(res[field], val)
+
+ # Check that polish occurs after `StopIteration` as advertised
+ callback.nit = 0
+ func.val = np.inf
+ kwargs['polish'] = True
+ res = differential_evolution(**kwargs, callback=callback)
+ assert res.fun < ref.fun
+
+ def test_callback_terminates(self):
+ # test that if the callback returns true, then the minimization halts
+ bounds = [(0, 2), (0, 2)]
+ expected_msg = 'callback function requested stop early'
+ def callback_python_true(param, convergence=0.):
+ return True
+
+ result = differential_evolution(
+ rosen, bounds, callback=callback_python_true
+ )
+ assert_string_equal(result.message, expected_msg)
+
+ # if callback raises StopIteration then solve should be interrupted
+ def callback_stop(intermediate_result):
+ raise StopIteration
+
+ result = differential_evolution(rosen, bounds, callback=callback_stop)
+ assert not result.success
+
+ def callback_evaluates_true(param, convergence=0.):
+ # DE should stop if bool(self.callback) is True
+ return [10]
+
+ result = differential_evolution(rosen, bounds, callback=callback_evaluates_true)
+ assert_string_equal(result.message, expected_msg)
+ assert not result.success
+
+ def callback_evaluates_false(param, convergence=0.):
+ return []
+
+ result = differential_evolution(rosen, bounds,
+ callback=callback_evaluates_false)
+ assert result.success
+
+ def test_args_tuple_is_passed(self):
+ # test that the args tuple is passed to the cost function properly.
+ bounds = [(-10, 10)]
+ args = (1., 2., 3.)
+
+ def quadratic(x, *args):
+ if not isinstance(args, tuple):
+ raise ValueError('args should be a tuple')
+ return args[0] + args[1] * x + args[2] * x**2.
+
+ result = differential_evolution(quadratic,
+ bounds,
+ args=args,
+ polish=True)
+ assert_almost_equal(result.fun, 2 / 3.)
+
+ def test_init_with_invalid_strategy(self):
+ # test that passing an invalid strategy raises ValueError
+ func = rosen
+ bounds = [(-3, 3)]
+ assert_raises(ValueError,
+ differential_evolution,
+ func,
+ bounds,
+ strategy='abc')
+
+ def test_bounds_checking(self):
+ # test that the bounds checking works
+ func = rosen
+ bounds = [(-3)]
+ assert_raises(ValueError,
+ differential_evolution,
+ func,
+ bounds)
+ bounds = [(-3, 3), (3, 4, 5)]
+ assert_raises(ValueError,
+ differential_evolution,
+ func,
+ bounds)
+
+ # test that we can use a new-type Bounds object
+ result = differential_evolution(rosen, Bounds([0, 0], [2, 2]))
+ assert_almost_equal(result.x, (1., 1.))
+
+ def test_select_samples(self):
+ # select_samples should return 5 separate random numbers.
+ limits = np.arange(12., dtype='float64').reshape(2, 6)
+ bounds = list(zip(limits[0, :], limits[1, :]))
+ solver = DifferentialEvolutionSolver(None, bounds, popsize=1)
+ candidate = 0
+ r1, r2, r3, r4, r5 = solver._select_samples(candidate, 5)
+ assert_equal(
+ len(np.unique(np.array([candidate, r1, r2, r3, r4, r5]))), 6)
+
+ def test_maxiter_stops_solve(self):
+ # test that if the maximum number of iterations is exceeded
+ # the solver stops.
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, maxiter=1)
+ result = solver.solve()
+ assert_equal(result.success, False)
+ assert_equal(result.message,
+ 'Maximum number of iterations has been exceeded.')
+
+ def test_maxfun_stops_solve(self):
+ # test that if the maximum number of function evaluations is exceeded
+ # during initialisation the solver stops
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, maxfun=1,
+ polish=False)
+ result = solver.solve()
+
+ assert_equal(result.nfev, 2)
+ assert_equal(result.success, False)
+ assert_equal(result.message,
+ 'Maximum number of function evaluations has '
+ 'been exceeded.')
+
+ # test that if the maximum number of function evaluations is exceeded
+ # during the actual minimisation, then the solver stops.
+ # Have to turn polishing off, as this will still occur even if maxfun
+ # is reached. For popsize=5 and len(bounds)=2, then there are only 10
+ # function evaluations during initialisation.
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ popsize=5,
+ polish=False,
+ maxfun=40)
+ result = solver.solve()
+
+ assert_equal(result.nfev, 41)
+ assert_equal(result.success, False)
+ assert_equal(result.message,
+ 'Maximum number of function evaluations has '
+ 'been exceeded.')
+
+ # now repeat for updating='deferred version
+ # 47 function evaluations is not a multiple of the population size,
+ # so maxfun is reached partway through a population evaluation.
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ popsize=5,
+ polish=False,
+ maxfun=47,
+ updating='deferred')
+ result = solver.solve()
+
+ assert_equal(result.nfev, 47)
+ assert_equal(result.success, False)
+ assert_equal(result.message,
+ 'Maximum number of function evaluations has '
+ 'been reached.')
+
+ def test_quadratic(self):
+ # test the quadratic function from object
+ solver = DifferentialEvolutionSolver(self.quadratic,
+ [(-100, 100)],
+ tol=0.02)
+ solver.solve()
+ assert_equal(np.argmin(solver.population_energies), 0)
+
+ def test_quadratic_from_diff_ev(self):
+ # test the quadratic function from differential_evolution function
+ differential_evolution(self.quadratic,
+ [(-100, 100)],
+ tol=0.02,
+ seed=1)
+
+ def test_rng_gives_repeatability(self):
+ result = differential_evolution(self.quadratic,
+ [(-100, 100)],
+ polish=False,
+ rng=1,
+ tol=0.5)
+ result2 = differential_evolution(self.quadratic,
+ [(-100, 100)],
+ polish=False,
+ rng=1,
+ tol=0.5)
+ assert_equal(result.x, result2.x)
+ assert_equal(result.nfev, result2.nfev)
+
+ def test_random_generator(self):
+ # check that np.random.Generator can be used (numpy >= 1.17)
+ # obtain a np.random.Generator object
+ rng = np.random.default_rng()
+
+ inits = ['random', 'latinhypercube', 'sobol', 'halton']
+ for init in inits:
+ differential_evolution(self.quadratic,
+ [(-100, 100)],
+ polish=False,
+ rng=rng,
+ tol=0.5,
+ init=init)
+
+ def test_exp_runs(self):
+ # test whether exponential mutation loop runs
+ solver = DifferentialEvolutionSolver(rosen,
+ self.bounds,
+ strategy='best1exp',
+ maxiter=1)
+
+ solver.solve()
+
+ def test_gh_4511_regression(self):
+ # This modification of the differential evolution docstring example
+ # uses a custom popsize that had triggered an off-by-one error.
+ # Because we do not care about solving the optimization problem in
+ # this test, we use maxiter=1 to reduce the testing time.
+ bounds = [(-5, 5), (-5, 5)]
+ # result = differential_evolution(rosen, bounds, popsize=1815,
+ # maxiter=1)
+
+ # the original issue arose because of rounding error in arange, with
+ # linspace being a much better solution. 1815 is quite a large popsize
+ # to use and results in a long test time (~13s). I used the original
+ # issue to figure out the lowest number of samples that would cause
+ # this rounding error to occur, 49.
+ differential_evolution(rosen, bounds, popsize=49, maxiter=1)
+
+ def test_calculate_population_energies(self):
+ # if popsize is 3, then the overall generation has size (6,)
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=3)
+ solver._calculate_population_energies(solver.population)
+ solver._promote_lowest_energy()
+ assert_equal(np.argmin(solver.population_energies), 0)
+
+ # initial calculation of the energies should require 6 nfev.
+ assert_equal(solver._nfev, 6)
+
+ def test_iteration(self):
+ # test that DifferentialEvolutionSolver is iterable
+ # if popsize is 3, then the overall generation has size (6,)
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, popsize=3,
+ maxfun=12)
+ x, fun = next(solver)
+ assert_equal(np.size(x, 0), 2)
+
+ # 6 nfev are required for initial calculation of energies, 6 nfev are
+ # required for the evolution of the 6 population members.
+ assert_equal(solver._nfev, 12)
+
+ # the next generation should halt because it exceeds maxfun
+ assert_raises(StopIteration, next, solver)
+
+ # check a proper minimisation can be done by an iterable solver
+ solver = DifferentialEvolutionSolver(rosen, self.bounds)
+ _, fun_prev = next(solver)
+ for i, soln in enumerate(solver):
+ x_current, fun_current = soln
+ assert fun_prev >= fun_current
+ _, fun_prev = x_current, fun_current
+ # need to have this otherwise the solver would never stop.
+ if i == 50:
+ break
+
+ def test_convergence(self):
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, tol=0.2,
+ polish=False)
+ solver.solve()
+ assert_(solver.convergence < 0.2)
+
+ def test_maxiter_none_GH5731(self):
+ # Pre 0.17 the previous default for maxiter and maxfun was None.
+ # the numerical defaults are now 1000 and np.inf. However, some scripts
+ # will still supply None for both of those, this will raise a TypeError
+ # in the solve method.
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, maxiter=None,
+ maxfun=None)
+ solver.solve()
+
+ def test_population_initiation(self):
+ # test the different modes of population initiation
+
+ # init must be either 'latinhypercube' or 'random'
+ # raising ValueError is something else is passed in
+ assert_raises(ValueError,
+ DifferentialEvolutionSolver,
+ *(rosen, self.bounds),
+ **{'init': 'rubbish'})
+
+ solver = DifferentialEvolutionSolver(rosen, self.bounds)
+
+ # check that population initiation:
+ # 1) resets _nfev to 0
+ # 2) all population energies are np.inf
+ solver.init_population_random()
+ assert_equal(solver._nfev, 0)
+ assert_(np.all(np.isinf(solver.population_energies)))
+
+ solver.init_population_lhs()
+ assert_equal(solver._nfev, 0)
+ assert_(np.all(np.isinf(solver.population_energies)))
+
+ solver.init_population_qmc(qmc_engine='halton')
+ assert_equal(solver._nfev, 0)
+ assert_(np.all(np.isinf(solver.population_energies)))
+
+ solver = DifferentialEvolutionSolver(rosen, self.bounds, init='sobol')
+ solver.init_population_qmc(qmc_engine='sobol')
+ assert_equal(solver._nfev, 0)
+ assert_(np.all(np.isinf(solver.population_energies)))
+
+ # we should be able to initialize with our own array
+ population = np.linspace(-1, 3, 10).reshape(5, 2)
+ solver = DifferentialEvolutionSolver(rosen, self.bounds,
+ init=population,
+ strategy='best2bin',
+ atol=0.01, rng=1, popsize=5)
+
+ assert_equal(solver._nfev, 0)
+ assert_(np.all(np.isinf(solver.population_energies)))
+ assert_(solver.num_population_members == 5)
+ assert_(solver.population_shape == (5, 2))
+
+ # check that the population was initialized correctly
+ unscaled_population = np.clip(solver._unscale_parameters(population),
+ 0, 1)
+ assert_almost_equal(solver.population[:5], unscaled_population)
+
+ # population values need to be clipped to bounds
+ assert_almost_equal(np.min(solver.population[:5]), 0)
+ assert_almost_equal(np.max(solver.population[:5]), 1)
+
+ # shouldn't be able to initialize with an array if it's the wrong shape
+ # this would have too many parameters
+ population = np.linspace(-1, 3, 15).reshape(5, 3)
+ assert_raises(ValueError,
+ DifferentialEvolutionSolver,
+ *(rosen, self.bounds),
+ **{'init': population})
+
+ # provide an initial solution
+ # bounds are [(0, 2), (0, 2)]
+ x0 = np.random.uniform(low=0.0, high=2.0, size=2)
+ solver = DifferentialEvolutionSolver(
+ rosen, self.bounds, x0=x0
+ )
+ # parameters are scaled to unit interval
+ assert_allclose(solver.population[0], x0 / 2.0)
+
+ def test_x0(self):
+ # smoke test that checks that x0 is usable.
+ res = differential_evolution(rosen, self.bounds, x0=[0.2, 0.8])
+ assert res.success
+
+ # check what happens if some of the x0 lay outside the bounds
+ with assert_raises(ValueError):
+ differential_evolution(rosen, self.bounds, x0=[0.2, 2.1])
+
+ def test_infinite_objective_function(self):
+ # Test that there are no problems if the objective function
+ # returns inf on some runs
+ def sometimes_inf(x):
+ if x[0] < .5:
+ return np.inf
+ return x[1]
+ bounds = [(0, 1), (0, 1)]
+ differential_evolution(sometimes_inf, bounds=bounds, disp=False)
+
+ def test_deferred_updating(self):
+ # check setting of deferred updating, with default workers
+ bounds = [(0., 2.), (0., 2.)]
+ solver = DifferentialEvolutionSolver(rosen, bounds, updating='deferred')
+ assert_(solver._updating == 'deferred')
+ assert_(solver._mapwrapper._mapfunc is map)
+ res = solver.solve()
+ assert res.success
+
+ # check that deferred updating works with an exponential crossover
+ res = differential_evolution(
+ rosen, bounds, updating='deferred', strategy='best1exp'
+ )
+ assert res.success
+
+ def test_immediate_updating(self):
+ # check setting of immediate updating, with default workers
+ bounds = [(0., 2.), (0., 2.)]
+ solver = DifferentialEvolutionSolver(rosen, bounds)
+ assert_(solver._updating == 'immediate')
+
+ # should raise a UserWarning because the updating='immediate'
+ # is being overridden by the workers keyword
+ with warns(UserWarning):
+ with DifferentialEvolutionSolver(rosen, bounds, workers=2) as s:
+ solver.solve()
+ assert s._updating == 'deferred'
+
+ def test_parallel_threads(self):
+ # smoke test for parallelization with deferred updating
+ bounds = [(0., 2.), (0., 2.)]
+ # use threads instead of Process to speed things up for this simple example
+ with ThreadPool(2) as p, DifferentialEvolutionSolver(
+ rosen, bounds, updating='deferred', workers=p.map, tol=0.1, popsize=3
+ ) as solver:
+ assert solver._mapwrapper.pool is not None
+ assert solver._updating == 'deferred'
+ solver.solve()
+
+ @pytest.mark.fail_slow(10)
+ def test_parallel_processes(self):
+ bounds = [(0., 2.), (0., 2.)]
+ with DifferentialEvolutionSolver(
+ rosen, bounds, updating='deferred', workers=2, popsize=3, tol=0.1
+ ) as solver:
+ assert solver._mapwrapper.pool is not None
+ assert solver._updating == 'deferred'
+ solver.solve()
+
+ def test_converged(self):
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)])
+ solver.solve()
+ assert_(solver.converged())
+
+ def test_constraint_violation_fn(self):
+ def constr_f(x):
+ return [x[0] + x[1]]
+
+ def constr_f2(x):
+ return np.array([x[0]**2 + x[1], x[0] - x[1]])
+
+ nlc = NonlinearConstraint(constr_f, -np.inf, 1.9)
+
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc,))
+
+ cv = solver._constraint_violation_fn(np.array([1.0, 1.0]))
+ assert_almost_equal(cv, 0.1)
+
+ nlc2 = NonlinearConstraint(constr_f2, -np.inf, 1.8)
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc, nlc2))
+
+ # for multiple constraints the constraint violations should
+ # be concatenated.
+ xs = [(1.2, 1), (2.0, 2.0), (0.5, 0.5)]
+ vs = [(0.3, 0.64, 0.0), (2.1, 4.2, 0.0), (0, 0, 0)]
+
+ for x, v in zip(xs, vs):
+ cv = solver._constraint_violation_fn(np.array(x))
+ assert_allclose(cv, np.atleast_2d(v))
+
+ # vectorized calculation of a series of solutions
+ assert_allclose(
+ solver._constraint_violation_fn(np.array(xs)), np.array(vs)
+ )
+
+ # the following line is used in _calculate_population_feasibilities.
+ # _constraint_violation_fn returns an (1, M) array when
+ # x.shape == (N,), i.e. a single solution. Therefore this list
+ # comprehension should generate (S, 1, M) array.
+ constraint_violation = np.array([solver._constraint_violation_fn(x)
+ for x in np.array(xs)])
+ assert constraint_violation.shape == (3, 1, 3)
+
+ # we need reasonable error messages if the constraint function doesn't
+ # return the right thing
+ def constr_f3(x):
+ # returns (S, M), rather than (M, S)
+ return constr_f2(x).T
+
+ nlc2 = NonlinearConstraint(constr_f3, -np.inf, 1.8)
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc, nlc2),
+ vectorized=False)
+ solver.vectorized = True
+ with pytest.raises(
+ RuntimeError, match="An array returned from a Constraint"
+ ):
+ solver._constraint_violation_fn(np.array(xs))
+
+ def test_constraint_population_feasibilities(self):
+ def constr_f(x):
+ return [x[0] + x[1]]
+
+ def constr_f2(x):
+ return [x[0]**2 + x[1], x[0] - x[1]]
+
+ nlc = NonlinearConstraint(constr_f, -np.inf, 1.9)
+
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc,))
+
+ # are population feasibilities correct
+ # [0.5, 0.5] corresponds to scaled values of [1., 1.]
+ feas, cv = solver._calculate_population_feasibilities(
+ np.array([[0.5, 0.5], [1., 1.]]))
+ assert_equal(feas, [False, False])
+ assert_almost_equal(cv, np.array([[0.1], [2.1]]))
+ assert cv.shape == (2, 1)
+
+ nlc2 = NonlinearConstraint(constr_f2, -np.inf, 1.8)
+
+ for vectorize in [False, True]:
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc, nlc2),
+ vectorized=vectorize,
+ updating='deferred')
+
+ feas, cv = solver._calculate_population_feasibilities(
+ np.array([[0.5, 0.5], [0.6, 0.5]]))
+ assert_equal(feas, [False, False])
+ assert_almost_equal(cv, np.array([[0.1, 0.2, 0], [0.3, 0.64, 0]]))
+
+ feas, cv = solver._calculate_population_feasibilities(
+ np.array([[0.5, 0.5], [1., 1.]]))
+ assert_equal(feas, [False, False])
+ assert_almost_equal(cv, np.array([[0.1, 0.2, 0], [2.1, 4.2, 0]]))
+ assert cv.shape == (2, 3)
+
+ feas, cv = solver._calculate_population_feasibilities(
+ np.array([[0.25, 0.25], [1., 1.]]))
+ assert_equal(feas, [True, False])
+ assert_almost_equal(cv, np.array([[0.0, 0.0, 0.], [2.1, 4.2, 0]]))
+ assert cv.shape == (2, 3)
+
+ def test_constraint_solve(self):
+ def constr_f(x):
+ return np.array([x[0] + x[1]])
+
+ nlc = NonlinearConstraint(constr_f, -np.inf, 1.9)
+
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc,))
+
+ # trust-constr warns if the constraint function is linear
+ with warns(UserWarning):
+ res = solver.solve()
+
+ assert constr_f(res.x) <= 1.9
+ assert res.success
+
+ @pytest.mark.fail_slow(10)
+ def test_impossible_constraint(self):
+ def constr_f(x):
+ return np.array([x[0] + x[1]])
+
+ nlc = NonlinearConstraint(constr_f, -np.inf, -1)
+
+ solver = DifferentialEvolutionSolver(
+ rosen, [(0, 2), (0, 2)], constraints=(nlc,), popsize=1, rng=1, maxiter=100
+ )
+
+ # a UserWarning is issued because the 'trust-constr' polishing is
+ # attempted on the least infeasible solution found.
+ with warns(UserWarning):
+ res = solver.solve()
+
+ assert res.maxcv > 0
+ assert not res.success
+
+ # test _promote_lowest_energy works when none of the population is
+ # feasible. In this case, the solution with the lowest constraint
+ # violation should be promoted.
+ solver = DifferentialEvolutionSolver(
+ rosen, [(0, 2), (0, 2)], constraints=(nlc,), polish=False)
+ next(solver)
+ assert not solver.feasible.all()
+ assert not np.isfinite(solver.population_energies).all()
+
+ # now swap two of the entries in the population
+ l = 20
+ cv = solver.constraint_violation[0]
+
+ solver.population_energies[[0, l]] = solver.population_energies[[l, 0]]
+ solver.population[[0, l], :] = solver.population[[l, 0], :]
+ solver.constraint_violation[[0, l], :] = (
+ solver.constraint_violation[[l, 0], :])
+
+ solver._promote_lowest_energy()
+ assert_equal(solver.constraint_violation[0], cv)
+
+ def test_accept_trial(self):
+ # _accept_trial(self, energy_trial, feasible_trial, cv_trial,
+ # energy_orig, feasible_orig, cv_orig)
+ def constr_f(x):
+ return [x[0] + x[1]]
+ nlc = NonlinearConstraint(constr_f, -np.inf, 1.9)
+ solver = DifferentialEvolutionSolver(rosen, [(0, 2), (0, 2)],
+ constraints=(nlc,))
+ fn = solver._accept_trial
+ # both solutions are feasible, select lower energy
+ assert fn(0.1, True, np.array([0.]), 1.0, True, np.array([0.]))
+ assert (fn(1.0, True, np.array([0.0]), 0.1, True, np.array([0.0])) is False)
+ assert fn(0.1, True, np.array([0.]), 0.1, True, np.array([0.]))
+
+ # trial is feasible, original is not
+ assert fn(9.9, True, np.array([0.]), 1.0, False, np.array([1.]))
+
+ # trial and original are infeasible
+ # cv_trial have to be <= cv_original to be better
+ assert (fn(0.1, False, np.array([0.5, 0.5]),
+ 1.0, False, np.array([1., 1.0])))
+ assert (fn(0.1, False, np.array([0.5, 0.5]),
+ 1.0, False, np.array([1., 0.50])))
+ assert not (fn(1.0, False, np.array([0.5, 0.5]),
+ 1.0, False, np.array([1.0, 0.4])))
+
+ def test_constraint_wrapper(self):
+ lb = np.array([0, 20, 30])
+ ub = np.array([0.5, np.inf, 70])
+ x0 = np.array([1, 2, 3])
+ pc = _ConstraintWrapper(Bounds(lb, ub), x0)
+ assert (pc.violation(x0) > 0).any()
+ assert (pc.violation([0.25, 21, 31]) == 0).all()
+
+ # check vectorized Bounds constraint
+ xs = np.arange(1, 16).reshape(5, 3)
+ violations = []
+ for x in xs:
+ violations.append(pc.violation(x))
+ np.testing.assert_allclose(pc.violation(xs.T), np.array(violations).T)
+
+ x0 = np.array([1, 2, 3, 4])
+ A = np.array([[1, 2, 3, 4], [5, 0, 0, 6], [7, 0, 8, 0]])
+ pc = _ConstraintWrapper(LinearConstraint(A, -np.inf, 0), x0)
+ assert (pc.violation(x0) > 0).any()
+ assert (pc.violation([-10, 2, -10, 4]) == 0).all()
+
+ # check vectorized LinearConstraint, for 7 lots of parameter vectors
+ # with each parameter vector being 4 long, with 3 constraints
+ # xs is the same shape as stored in the differential evolution
+ # population, but it's sent to the violation function as (len(x), M)
+ xs = np.arange(1, 29).reshape(7, 4)
+ violations = []
+ for x in xs:
+ violations.append(pc.violation(x))
+ np.testing.assert_allclose(pc.violation(xs.T), np.array(violations).T)
+
+ pc = _ConstraintWrapper(LinearConstraint(csr_array(A), -np.inf, 0),
+ x0)
+ assert (pc.violation(x0) > 0).any()
+ assert (pc.violation([-10, 2, -10, 4]) == 0).all()
+
+ def fun(x):
+ return A.dot(x)
+
+ nonlinear = NonlinearConstraint(fun, -np.inf, 0)
+ pc = _ConstraintWrapper(nonlinear, [-10, 2, -10, 4])
+ assert (pc.violation(x0) > 0).any()
+ assert (pc.violation([-10, 2, -10, 4]) == 0).all()
+
+ def test_constraint_wrapper_violation(self):
+ def cons_f(x):
+ # written in vectorised form to accept an array of (N, S)
+ # returning (M, S)
+ # where N is the number of parameters,
+ # S is the number of solution vectors to be examined,
+ # and M is the number of constraint components
+ return np.array([x[0] ** 2 + x[1],
+ x[0] ** 2 - x[1]])
+
+ nlc = NonlinearConstraint(cons_f, [-1, -0.8500], [2, 2])
+ pc = _ConstraintWrapper(nlc, [0.5, 1])
+ assert np.size(pc.bounds[0]) == 2
+
+ xs = [(0.5, 1), (0.5, 1.2), (1.2, 1.2), (0.1, -1.2), (0.1, 2.0)]
+ vs = [(0, 0), (0, 0.1), (0.64, 0), (0.19, 0), (0.01, 1.14)]
+
+ for x, v in zip(xs, vs):
+ assert_allclose(pc.violation(x), v)
+
+ # now check that we can vectorize the constraint wrapper
+ assert_allclose(pc.violation(np.array(xs).T),
+ np.array(vs).T)
+ assert pc.fun(np.array(xs).T).shape == (2, len(xs))
+ assert pc.violation(np.array(xs).T).shape == (2, len(xs))
+ assert pc.num_constr == 2
+ assert pc.parameter_count == 2
+
+ def test_matrix_linear_constraint(self):
+ # gh20041 supplying an np.matrix to construct a LinearConstraint caused
+ # _ConstraintWrapper to start returning constraint violations of the
+ # wrong shape.
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", PendingDeprecationWarning)
+ matrix = np.matrix([[1, 1, 1, 1.],
+ [2, 2, 2, 2.]])
+ lc = LinearConstraint(matrix, 0, 1)
+ x0 = np.ones(4)
+ cw = _ConstraintWrapper(lc, x0)
+ # the shape of the constraint violation should be the same as the number
+ # of constraints applied.
+ assert cw.violation(x0).shape == (2,)
+
+ # let's try a vectorised violation call.
+ xtrial = np.arange(4 * 5).reshape(4, 5)
+ assert cw.violation(xtrial).shape == (2, 5)
+
+ @pytest.mark.fail_slow(20)
+ def test_L1(self):
+ # Lampinen ([5]) test problem 1
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = np.sum(5*x[1:5]) - 5*x[1:5]@x[1:5] - np.sum(x[5:])
+ return fun
+
+ A = np.zeros((10, 14)) # 1-indexed to match reference
+ A[1, [1, 2, 10, 11]] = 2, 2, 1, 1
+ A[2, [1, 10]] = -8, 1
+ A[3, [4, 5, 10]] = -2, -1, 1
+ A[4, [1, 3, 10, 11]] = 2, 2, 1, 1
+ A[5, [2, 11]] = -8, 1
+ A[6, [6, 7, 11]] = -2, -1, 1
+ A[7, [2, 3, 11, 12]] = 2, 2, 1, 1
+ A[8, [3, 12]] = -8, 1
+ A[9, [8, 9, 12]] = -2, -1, 1
+ A = A[1:, 1:]
+
+ b = np.array([10, 0, 0, 10, 0, 0, 10, 0, 0])
+
+ L = LinearConstraint(A, -np.inf, b)
+
+ bounds = [(0, 1)]*9 + [(0, 100)]*3 + [(0, 1)]
+
+ # using a lower popsize to speed the test up
+ res = differential_evolution(
+ f, bounds, strategy='best1bin', rng=12345, constraints=(L,),
+ popsize=5, tol=0.01
+ )
+
+ x_opt = (1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 3, 1)
+ f_opt = -15
+
+ assert_allclose(f(x_opt), f_opt, atol=6e-4)
+ assert res.success
+ assert_allclose(res.x, x_opt, atol=6e-4)
+ assert_allclose(res.fun, f_opt, atol=5e-3)
+ assert_(np.all(A@res.x <= b))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ # now repeat the same solve, using the same overall constraints,
+ # but using a sparse array for the LinearConstraint instead of an
+ # array
+
+ L = LinearConstraint(csr_array(A), -np.inf, b)
+
+ # using a lower popsize to speed the test up
+ res = differential_evolution(
+ f, bounds, strategy='best1bin', rng=1211134, constraints=(L,),
+ popsize=2, tol=0.05
+ )
+
+ assert_allclose(f(x_opt), f_opt)
+ assert res.success
+ assert_allclose(res.x, x_opt, atol=5e-4)
+ assert_allclose(res.fun, f_opt, atol=5e-3)
+ assert_(np.all(A@res.x <= b))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ # now repeat the same solve, using the same overall constraints,
+ # but specify half the constraints in terms of LinearConstraint,
+ # and the other half by NonlinearConstraint
+ def c1(x):
+ x = np.hstack(([0], x))
+ return [2*x[2] + 2*x[3] + x[11] + x[12],
+ -8*x[3] + x[12]]
+
+ def c2(x):
+ x = np.hstack(([0], x))
+ return -2*x[8] - x[9] + x[12]
+
+ L = LinearConstraint(A[:5, :], -np.inf, b[:5])
+ L2 = LinearConstraint(A[5:6, :], -np.inf, b[5:6])
+ N = NonlinearConstraint(c1, -np.inf, b[6:8])
+ N2 = NonlinearConstraint(c2, -np.inf, b[8:9])
+ constraints = (L, N, L2, N2)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ res = differential_evolution(
+ f, bounds, strategy='best1bin', rng=1211134,
+ constraints=constraints, popsize=2, tol=0.05
+ )
+
+ assert_allclose(res.x, x_opt, atol=6e-4)
+ assert_allclose(res.fun, f_opt, atol=5e-3)
+ assert_(np.all(A@res.x <= b))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(10)
+ def test_L2(self):
+ # Lampinen ([5]) test problem 2
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = ((x[1]-10)**2 + 5*(x[2]-12)**2 + x[3]**4 + 3*(x[4]-11)**2 +
+ 10*x[5]**6 + 7*x[6]**2 + x[7]**4 - 4*x[6]*x[7] - 10*x[6] -
+ 8*x[7])
+ return fun
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [127 - 2*x[1]**2 - 3*x[2]**4 - x[3] - 4*x[4]**2 - 5*x[5],
+ 196 - 23*x[1] - x[2]**2 - 6*x[6]**2 + 8*x[7],
+ 282 - 7*x[1] - 3*x[2] - 10*x[3]**2 - x[4] + x[5],
+ -4*x[1]**2 - x[2]**2 + 3*x[1]*x[2] - 2*x[3]**2 -
+ 5*x[6] + 11*x[7]]
+
+ N = NonlinearConstraint(c1, 0, np.inf)
+ bounds = [(-10, 10)]*7
+ constraints = (N)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ res = differential_evolution(f, bounds, strategy='best1bin',
+ rng=1234, constraints=constraints)
+
+ f_opt = 680.6300599487869
+ x_opt = (2.330499, 1.951372, -0.4775414, 4.365726,
+ -0.6244870, 1.038131, 1.594227)
+
+ assert_allclose(f(x_opt), f_opt)
+ assert_allclose(res.fun, f_opt)
+ assert_allclose(res.x, x_opt, atol=1e-5)
+ assert res.success
+ assert_(np.all(np.array(c1(res.x)) >= 0))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(10)
+ def test_L3(self):
+ # Lampinen ([5]) test problem 3
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = (x[1]**2 + x[2]**2 + x[1]*x[2] - 14*x[1] - 16*x[2] +
+ (x[3]-10)**2 + 4*(x[4]-5)**2 + (x[5]-3)**2 + 2*(x[6]-1)**2 +
+ 5*x[7]**2 + 7*(x[8]-11)**2 + 2*(x[9]-10)**2 +
+ (x[10] - 7)**2 + 45
+ )
+ return fun # maximize
+
+ A = np.zeros((4, 11))
+ A[1, [1, 2, 7, 8]] = -4, -5, 3, -9
+ A[2, [1, 2, 7, 8]] = -10, 8, 17, -2
+ A[3, [1, 2, 9, 10]] = 8, -2, -5, 2
+ A = A[1:, 1:]
+ b = np.array([-105, 0, -12])
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [3*x[1] - 6*x[2] - 12*(x[9]-8)**2 + 7*x[10],
+ -3*(x[1]-2)**2 - 4*(x[2]-3)**2 - 2*x[3]**2 + 7*x[4] + 120,
+ -x[1]**2 - 2*(x[2]-2)**2 + 2*x[1]*x[2] - 14*x[5] + 6*x[6],
+ -5*x[1]**2 - 8*x[2] - (x[3]-6)**2 + 2*x[4] + 40,
+ -0.5*(x[1]-8)**2 - 2*(x[2]-4)**2 - 3*x[5]**2 + x[6] + 30]
+
+ L = LinearConstraint(A, b, np.inf)
+ N = NonlinearConstraint(c1, 0, np.inf)
+ bounds = [(-10, 10)]*10
+ constraints = (L, N)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ res = differential_evolution(f, bounds, rng=1234,
+ constraints=constraints, popsize=3)
+
+ x_opt = (2.171996, 2.363683, 8.773926, 5.095984, 0.9906548,
+ 1.430574, 1.321644, 9.828726, 8.280092, 8.375927)
+ f_opt = 24.3062091
+
+ assert_allclose(f(x_opt), f_opt, atol=1e-5)
+ assert_allclose(res.x, x_opt, atol=1e-6)
+ assert_allclose(res.fun, f_opt, atol=1e-5)
+ assert res.success
+ assert_(np.all(A @ res.x >= b))
+ assert_(np.all(np.array(c1(res.x)) >= 0))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(10)
+ def test_L4(self):
+ # Lampinen ([5]) test problem 4
+ def f(x):
+ return np.sum(x[:3])
+
+ A = np.zeros((4, 9))
+ A[1, [4, 6]] = 0.0025, 0.0025
+ A[2, [5, 7, 4]] = 0.0025, 0.0025, -0.0025
+ A[3, [8, 5]] = 0.01, -0.01
+ A = A[1:, 1:]
+ b = np.array([1, 1, 1])
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [x[1]*x[6] - 833.33252*x[4] - 100*x[1] + 83333.333,
+ x[2]*x[7] - 1250*x[5] - x[2]*x[4] + 1250*x[4],
+ x[3]*x[8] - 1250000 - x[3]*x[5] + 2500*x[5]]
+
+ L = LinearConstraint(A, -np.inf, 1)
+ N = NonlinearConstraint(c1, 0, np.inf)
+
+ bounds = [(100, 10000)] + [(1000, 10000)]*2 + [(10, 1000)]*5
+ constraints = (L, N)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ res = differential_evolution(
+ f, bounds, strategy='best1bin', rng=1234,
+ constraints=constraints, popsize=3, tol=0.05
+ )
+
+ f_opt = 7049.248
+
+ x_opt = [579.306692, 1359.97063, 5109.9707, 182.0177, 295.601172,
+ 217.9823, 286.416528, 395.601172]
+
+ assert_allclose(f(x_opt), f_opt, atol=0.001)
+ assert_allclose(res.fun, f_opt, atol=0.001)
+
+ # use higher tol here for 32-bit Windows, see gh-11693
+ if (platform.system() == 'Windows' and np.dtype(np.intp).itemsize < 8):
+ assert_allclose(res.x, x_opt, rtol=2.4e-6, atol=0.0035)
+ else:
+ # tolerance determined from macOS + MKL failure, see gh-12701
+ assert_allclose(res.x, x_opt, rtol=5e-6, atol=0.0024)
+
+ assert res.success
+ assert_(np.all(A @ res.x <= b))
+ assert_(np.all(np.array(c1(res.x)) >= 0))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(10)
+ def test_L5(self):
+ # Lampinen ([5]) test problem 5
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = (np.sin(2*np.pi*x[1])**3*np.sin(2*np.pi*x[2]) /
+ (x[1]**3*(x[1]+x[2])))
+ return -fun # maximize
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [x[1]**2 - x[2] + 1,
+ 1 - x[1] + (x[2]-4)**2]
+
+ N = NonlinearConstraint(c1, -np.inf, 0)
+ bounds = [(0, 10)]*2
+ constraints = (N)
+
+ res = differential_evolution(f, bounds, strategy='rand1bin', rng=1234,
+ constraints=constraints)
+
+ x_opt = (1.22797135, 4.24537337)
+ f_opt = -0.095825
+ assert_allclose(f(x_opt), f_opt, atol=2e-5)
+ assert_allclose(res.fun, f_opt, atol=1e-4)
+ assert res.success
+ assert_(np.all(np.array(c1(res.x)) <= 0))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(10)
+ def test_L6(self):
+ # Lampinen ([5]) test problem 6
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = (x[1]-10)**3 + (x[2] - 20)**3
+ return fun
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [(x[1]-5)**2 + (x[2] - 5)**2 - 100,
+ -(x[1]-6)**2 - (x[2] - 5)**2 + 82.81]
+
+ N = NonlinearConstraint(c1, 0, np.inf)
+ bounds = [(13, 100), (0, 100)]
+ constraints = (N)
+ res = differential_evolution(f, bounds, strategy='rand1bin', rng=1234,
+ constraints=constraints, tol=1e-7)
+ x_opt = (14.095, 0.84296)
+ f_opt = -6961.814744
+
+ assert_allclose(f(x_opt), f_opt, atol=1e-6)
+ assert_allclose(res.fun, f_opt, atol=0.001)
+ assert_allclose(res.x, x_opt, atol=1e-4)
+ assert res.success
+ assert_(np.all(np.array(c1(res.x)) >= 0))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ def test_L7(self):
+ # Lampinen ([5]) test problem 7
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = (5.3578547*x[3]**2 + 0.8356891*x[1]*x[5] +
+ 37.293239*x[1] - 40792.141)
+ return fun
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [
+ 85.334407 + 0.0056858*x[2]*x[5] + 0.0006262*x[1]*x[4] -
+ 0.0022053*x[3]*x[5],
+
+ 80.51249 + 0.0071317*x[2]*x[5] + 0.0029955*x[1]*x[2] +
+ 0.0021813*x[3]**2,
+
+ 9.300961 + 0.0047026*x[3]*x[5] + 0.0012547*x[1]*x[3] +
+ 0.0019085*x[3]*x[4]
+ ]
+
+ N = NonlinearConstraint(c1, [0, 90, 20], [92, 110, 25])
+
+ bounds = [(78, 102), (33, 45)] + [(27, 45)]*3
+ constraints = (N)
+
+ res = differential_evolution(f, bounds, strategy='rand1bin', rng=1234,
+ constraints=constraints)
+
+ # using our best solution, rather than Lampinen/Koziel. Koziel solution
+ # doesn't satisfy constraints, Lampinen f_opt just plain wrong.
+ x_opt = [78.00000686, 33.00000362, 29.99526064, 44.99999971,
+ 36.77579979]
+
+ f_opt = -30665.537578
+
+ assert_allclose(f(x_opt), f_opt)
+ assert_allclose(res.x, x_opt, atol=1e-3)
+ assert_allclose(res.fun, f_opt, atol=1e-3)
+
+ assert res.success
+ assert_(np.all(np.array(c1(res.x)) >= np.array([0, 90, 20])))
+ assert_(np.all(np.array(c1(res.x)) <= np.array([92, 110, 25])))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.xslow
+ @pytest.mark.xfail(platform.machine() == 'ppc64le',
+ reason="fails on ppc64le")
+ def test_L8(self):
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ fun = 3*x[1] + 0.000001*x[1]**3 + 2*x[2] + 0.000002/3*x[2]**3
+ return fun
+
+ A = np.zeros((3, 5))
+ A[1, [4, 3]] = 1, -1
+ A[2, [3, 4]] = 1, -1
+ A = A[1:, 1:]
+ b = np.array([-.55, -.55])
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [
+ 1000*np.sin(-x[3]-0.25) + 1000*np.sin(-x[4]-0.25) +
+ 894.8 - x[1],
+ 1000*np.sin(x[3]-0.25) + 1000*np.sin(x[3]-x[4]-0.25) +
+ 894.8 - x[2],
+ 1000*np.sin(x[4]-0.25) + 1000*np.sin(x[4]-x[3]-0.25) +
+ 1294.8
+ ]
+ L = LinearConstraint(A, b, np.inf)
+ N = NonlinearConstraint(c1, np.full(3, -0.001), np.full(3, 0.001))
+
+ bounds = [(0, 1200)]*2+[(-.55, .55)]*2
+ constraints = (L, N)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ # original Lampinen test was with rand1bin, but that takes a
+ # huge amount of CPU time. Changing strategy to best1bin speeds
+ # things up a lot
+ res = differential_evolution(f, bounds, strategy='best1bin',
+ rng=1234, constraints=constraints,
+ maxiter=5000)
+
+ x_opt = (679.9453, 1026.067, 0.1188764, -0.3962336)
+ f_opt = 5126.4981
+
+ assert_allclose(f(x_opt), f_opt, atol=1e-3)
+ assert_allclose(res.x[:2], x_opt[:2], atol=2e-3)
+ assert_allclose(res.x[2:], x_opt[2:], atol=2e-3)
+ assert_allclose(res.fun, f_opt, atol=2e-2)
+ assert res.success
+ assert_(np.all(A@res.x >= b))
+ assert_(np.all(np.array(c1(res.x)) >= -0.001))
+ assert_(np.all(np.array(c1(res.x)) <= 0.001))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(5)
+ def test_L9(self):
+ # Lampinen ([5]) test problem 9
+
+ def f(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return x[1]**2 + (x[2]-1)**2
+
+ def c1(x):
+ x = np.hstack(([0], x)) # 1-indexed to match reference
+ return [x[2] - x[1]**2]
+
+ N = NonlinearConstraint(c1, [-.001], [0.001])
+
+ bounds = [(-1, 1)]*2
+ constraints = (N)
+ res = differential_evolution(f, bounds, strategy='rand1bin', rng=1234,
+ constraints=constraints)
+
+ x_opt = [np.sqrt(2)/2, 0.5]
+ f_opt = 0.75
+
+ assert_allclose(f(x_opt), f_opt)
+ assert_allclose(np.abs(res.x), x_opt, atol=1e-3)
+ assert_allclose(res.fun, f_opt, atol=1e-3)
+ assert res.success
+ assert_(np.all(np.array(c1(res.x)) >= -0.001))
+ assert_(np.all(np.array(c1(res.x)) <= 0.001))
+ assert_(np.all(res.x >= np.array(bounds)[:, 0]))
+ assert_(np.all(res.x <= np.array(bounds)[:, 1]))
+
+ @pytest.mark.fail_slow(10)
+ def test_integrality(self):
+ # test fitting discrete distribution to data
+ rng = np.random.default_rng(6519843218105)
+ dist = stats.nbinom
+ shapes = (5, 0.5)
+ x = dist.rvs(*shapes, size=10000, random_state=rng)
+
+ def func(p, *args):
+ dist, x = args
+ # negative log-likelihood function
+ ll = -np.log(dist.pmf(x, *p)).sum(axis=-1)
+ if np.isnan(ll): # occurs when x is outside of support
+ ll = np.inf # we don't want that
+ return ll
+
+ integrality = [True, False]
+ bounds = [(1, 18), (0, 0.95)]
+
+ res = differential_evolution(func, bounds, args=(dist, x),
+ integrality=integrality, polish=False,
+ rng=rng)
+ # tolerance has to be fairly relaxed for the second parameter
+ # because we're fitting a distribution to random variates.
+ assert res.x[0] == 5
+ assert_allclose(res.x, shapes, rtol=0.025)
+
+ # check that we can still use integrality constraints with polishing
+ res2 = differential_evolution(func, bounds, args=(dist, x),
+ integrality=integrality, polish=True,
+ rng=rng)
+
+ def func2(p, *args):
+ n, dist, x = args
+ return func(np.array([n, p[0]]), dist, x)
+
+ # compare the DE derived solution to an LBFGSB solution (that doesn't
+ # have to find the integral values). Note we're setting x0 to be the
+ # output from the first DE result, thereby making the polishing step
+ # and this minimisation pretty much equivalent.
+ LBFGSB = minimize(func2, res2.x[1], args=(5, dist, x),
+ bounds=[(0, 0.95)])
+ assert_allclose(res2.x[1], LBFGSB.x)
+ assert res2.fun <= res.fun
+
+ def test_integrality_limits(self):
+ def f(x):
+ return x
+
+ integrality = [True, False, True]
+ bounds = [(0.2, 1.1), (0.9, 2.2), (3.3, 4.9)]
+
+ # no integrality constraints
+ solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False,
+ integrality=False)
+ assert_allclose(solver.limits[0], [0.2, 0.9, 3.3])
+ assert_allclose(solver.limits[1], [1.1, 2.2, 4.9])
+
+ # with integrality constraints
+ solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False,
+ integrality=integrality)
+ assert_allclose(solver.limits[0], [0.5, 0.9, 3.5])
+ assert_allclose(solver.limits[1], [1.5, 2.2, 4.5])
+ assert_equal(solver.integrality, [True, False, True])
+ assert solver.polish is False
+
+ bounds = [(-1.2, -0.9), (0.9, 2.2), (-10.3, 4.1)]
+ solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False,
+ integrality=integrality)
+ assert_allclose(solver.limits[0], [-1.5, 0.9, -10.5])
+ assert_allclose(solver.limits[1], [-0.5, 2.2, 4.5])
+
+ # A lower bound of -1.2 is converted to
+ # np.nextafter(np.ceil(-1.2) - 0.5, np.inf)
+ # with a similar process to the upper bound. Check that the
+ # conversions work
+ assert_allclose(np.round(solver.limits[0]), [-1.0, 1.0, -10.0])
+ assert_allclose(np.round(solver.limits[1]), [-1.0, 2.0, 4.0])
+
+ bounds = [(-10.2, -8.1), (0.9, 2.2), (-10.9, -9.9999)]
+ solver = DifferentialEvolutionSolver(f, bounds=bounds, polish=False,
+ integrality=integrality)
+ assert_allclose(solver.limits[0], [-10.5, 0.9, -10.5])
+ assert_allclose(solver.limits[1], [-8.5, 2.2, -9.5])
+
+ bounds = [(-10.2, -10.1), (0.9, 2.2), (-10.9, -9.9999)]
+ with pytest.raises(ValueError, match='One of the integrality'):
+ DifferentialEvolutionSolver(f, bounds=bounds, polish=False,
+ integrality=integrality)
+
+ @pytest.mark.fail_slow(10)
+ def test_vectorized(self):
+ def quadratic(x):
+ return np.sum(x**2)
+
+ def quadratic_vec(x):
+ return np.sum(x**2, axis=0)
+
+ # A vectorized function needs to accept (len(x), S) and return (S,)
+ with pytest.raises(RuntimeError, match='The vectorized function'):
+ differential_evolution(quadratic, self.bounds,
+ vectorized=True, updating='deferred')
+
+ # vectorized overrides the updating keyword, check for warning
+ with warns(UserWarning, match="differential_evolution: the 'vector"):
+ differential_evolution(quadratic_vec, self.bounds,
+ vectorized=True)
+
+ # vectorized defers to the workers keyword, check for warning
+ with warns(UserWarning, match="differential_evolution: the 'workers"):
+ differential_evolution(quadratic_vec, self.bounds,
+ vectorized=True, workers=map,
+ updating='deferred')
+
+ ncalls = [0]
+
+ def rosen_vec(x):
+ ncalls[0] += 1
+ return rosen(x)
+
+ bounds = [(0, 10), (0, 10)]
+ res1 = differential_evolution(rosen, bounds, updating='deferred',
+ rng=1)
+ res2 = differential_evolution(rosen_vec, bounds, vectorized=True,
+ updating='deferred', rng=1)
+
+ # the two minimisation runs should be functionally equivalent
+ assert_allclose(res1.x, res2.x)
+ assert ncalls[0] == res2.nfev
+ assert res1.nit == res2.nit
+
+ def test_vectorized_constraints(self):
+ def constr_f(x):
+ return np.array([x[0] + x[1]])
+
+ def constr_f2(x):
+ return np.array([x[0]**2 + x[1], x[0] - x[1]])
+
+ nlc1 = NonlinearConstraint(constr_f, -np.inf, 1.9)
+ nlc2 = NonlinearConstraint(constr_f2, (0.9, 0.5), (2.0, 2.0))
+
+ def rosen_vec(x):
+ # accept an (len(x0), S) array, returning a (S,) array
+ v = 100 * (x[1:] - x[:-1]**2.0)**2.0
+ v += (1 - x[:-1])**2.0
+ return np.squeeze(v)
+
+ bounds = [(0, 10), (0, 10)]
+
+ res1 = differential_evolution(rosen, bounds, updating='deferred',
+ rng=1, constraints=[nlc1, nlc2],
+ polish=False)
+ res2 = differential_evolution(rosen_vec, bounds, vectorized=True,
+ updating='deferred', rng=1,
+ constraints=[nlc1, nlc2],
+ polish=False)
+ # the two minimisation runs should be functionally equivalent
+ assert_allclose(res1.x, res2.x)
+
+ def test_polish_function(self):
+ # the polishing may be done by a callable
+ N = len(self.bounds)
+
+ def pf(fun, x, **kwds):
+ pf.res = minimize(fun, x, jac=rosen_der, method='trust-constr', **kwds)
+ return pf.res
+ pf.res = None
+
+ res = differential_evolution(rosen, self.bounds, polish=pf, maxiter=1, rng=0)
+ ref = differential_evolution(rosen, self.bounds, polish=True, maxiter=1, rng=0)
+
+ # res.success will be False because of the small number of iterations
+ # The solution produced by DE would be bad after only one iteration.
+ # However, we still expect a good answer if the polishing worked
+ assert res.jac is not None
+ assert_allclose(res.x, np.ones(N), atol=1e-6)
+ # test that the `pf` callable is really used; it's not just truthy
+ assert res.fun == pf.res.fun
+ assert ref.fun != res.fun
+
+ def dummy_pf(func, x, **kwds):
+ assert "bounds" in kwds
+ assert isinstance(kwds["bounds"], Bounds)
+ assert "constraints" in kwds
+ return np.ones(N)
+
+ with assert_raises(
+ ValueError,
+ match="The result from a user defined polishing"
+ ):
+ differential_evolution(
+ rosen,
+ self.bounds,
+ polish=dummy_pf,
+ maxiter=1
+ )
+
+ # check that output of polish==False followed by a manual polish
+ # is the same as a callable(polish). Limit maxiter on DE so polisher
+ # has to do all the work.
+ def pf(func, x, **kwds):
+ return minimize(func, x, method='L-BFGS-B', **kwds)
+
+ rng = np.random.default_rng(110980928209)
+ res = differential_evolution(
+ rosen, self.bounds, polish=False, rng=rng, maxiter=1
+ )
+ res = minimize(rosen, res.x, bounds=self.bounds, method='L-BFGS-B')
+ rng = np.random.default_rng(110980928209)
+ res2 = differential_evolution(
+ rosen, self.bounds, polish=pf, rng=rng, maxiter=1
+ )
+ # could possibly do assert_allequal, but not sure about bitwise exactness
+ # for repeated runs from same starting point
+ assert_allclose(res.x, res2.x)
+ assert_allclose(res.fun, res2.fun)
+
+ def test_constraint_violation_error_message(self):
+
+ def func(x):
+ return np.cos(x[0]) + np.sin(x[1])
+
+ # Intentionally infeasible constraints.
+ c0 = NonlinearConstraint(lambda x: x[1] - (x[0]-1)**2, 0, np.inf)
+ c1 = NonlinearConstraint(lambda x: x[1] + x[0]**2, -np.inf, 0)
+
+ result = differential_evolution(func,
+ bounds=[(-1, 2), (-1, 1)],
+ constraints=[c0, c1],
+ maxiter=10,
+ polish=False,
+ rng=864197532)
+ assert result.success is False
+ # The numerical value in the error message might be sensitive to
+ # changes in the implementation. It can be updated if the code is
+ # changed. The essential part of the test is that there is a number
+ # after the '=', so if necessary, the text could be reduced to, say,
+ # "MAXCV = 0.".
+ assert "MAXCV = 0." in result.message
+
+ @pytest.mark.fail_slow(20) # fail-slow exception by request - see gh-20806
+ def test_strategy_fn(self):
+ # examines ability to customize strategy by mimicking one of the
+ # in-built strategies
+ parameter_count = 4
+ popsize = 10
+ bounds = [(0, 10.)] * parameter_count
+ total_popsize = parameter_count * popsize
+ mutation = 0.8
+ recombination = 0.7
+
+ calls = [0]
+ def custom_strategy_fn(candidate, population, rng=None):
+ calls[0] += 1
+ trial = np.copy(population[candidate])
+ fill_point = rng.choice(parameter_count)
+
+ pool = np.arange(total_popsize)
+ rng.shuffle(pool)
+ idxs = pool[:2 + 1]
+ idxs = idxs[idxs != candidate][:2]
+
+ r0, r1 = idxs[:2]
+
+ bprime = (population[0] + mutation *
+ (population[r0] - population[r1]))
+
+ crossovers = rng.uniform(size=parameter_count)
+ crossovers = crossovers < recombination
+ crossovers[fill_point] = True
+ trial = np.where(crossovers, bprime, trial)
+ return trial
+
+ solver = DifferentialEvolutionSolver(
+ rosen,
+ bounds,
+ popsize=popsize,
+ recombination=recombination,
+ mutation=mutation,
+ maxiter=2,
+ strategy=custom_strategy_fn,
+ rng=10,
+ polish=False
+ )
+ assert solver.strategy is custom_strategy_fn
+ solver.solve()
+ assert calls[0] > 0
+
+ # check custom strategy works with updating='deferred'
+ res = differential_evolution(
+ rosen, bounds, strategy=custom_strategy_fn, updating='deferred'
+ )
+ assert res.success
+
+ def custom_strategy_fn(candidate, population, rng=None):
+ return np.array([1.0, 2.0])
+
+ with pytest.raises(RuntimeError, match="strategy*"):
+ differential_evolution(
+ rosen,
+ bounds,
+ strategy=custom_strategy_fn
+ )
+
+ def test_reference_cycles(self):
+ with assert_deallocated(DifferentialEvolutionSolver, rosen, [(0, 10)]*2):
+ pass
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__dual_annealing.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__dual_annealing.py
new file mode 100644
index 0000000000000000000000000000000000000000..931f497361edd6bd5edc2914a05ccc5da468f40b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__dual_annealing.py
@@ -0,0 +1,415 @@
+# Dual annealing unit tests implementation.
+# Copyright (c) 2018 Sylvain Gubian ,
+# Yang Xiang
+# Author: Sylvain Gubian, PMP S.A.
+"""
+Unit tests for the dual annealing global optimizer
+"""
+from scipy.optimize import dual_annealing, Bounds
+
+from scipy.optimize._dual_annealing import EnergyState
+from scipy.optimize._dual_annealing import LocalSearchWrapper
+from scipy.optimize._dual_annealing import ObjectiveFunWrapper
+from scipy.optimize._dual_annealing import StrategyChain
+from scipy.optimize._dual_annealing import VisitingDistribution
+from scipy.optimize import rosen, rosen_der
+import pytest
+import numpy as np
+from numpy.testing import assert_equal, assert_allclose, assert_array_less
+from pytest import raises as assert_raises
+from scipy._lib._util import check_random_state
+
+import threading
+
+
+class TestDualAnnealing:
+
+ def setup_method(self):
+ # A function that returns always infinity for initialization tests
+ self.weirdfunc = lambda x: np.inf
+ # 2-D bounds for testing function
+ self.ld_bounds = [(-5.12, 5.12)] * 2
+ # 4-D bounds for testing function
+ self.hd_bounds = self.ld_bounds * 4
+ # Number of values to be generated for testing visit function
+ self.nbtestvalues = 5000
+ self.high_temperature = 5230
+ self.low_temperature = 0.1
+ self.qv = 2.62
+ self.seed = 1234
+ self.nb_fun_call = threading.local()
+ self.ngev = threading.local()
+
+ def callback(self, x, f, context):
+ # For testing callback mechanism. Should stop for e <= 1 as
+ # the callback function returns True
+ if f <= 1.0:
+ return True
+
+ def func(self, x, args=()):
+ # Using Rastrigin function for performing tests
+ if args:
+ shift = args
+ else:
+ shift = 0
+ y = np.sum((x - shift) ** 2 - 10 * np.cos(2 * np.pi * (
+ x - shift))) + 10 * np.size(x) + shift
+ if not hasattr(self.nb_fun_call, 'c'):
+ self.nb_fun_call.c = 0
+ self.nb_fun_call.c += 1
+ return y
+
+ def rosen_der_wrapper(self, x, args=()):
+ if not hasattr(self.ngev, 'c'):
+ self.ngev.c = 0
+ self.ngev.c += 1
+ return rosen_der(x, *args)
+
+ # FIXME: there are some discontinuities in behaviour as a function of `qv`,
+ # this needs investigating - see gh-12384
+ @pytest.mark.parametrize('qv', [1.1, 1.41, 2, 2.62, 2.9])
+ def test_visiting_stepping(self, qv):
+ rng = np.random.default_rng(1234)
+ lu = list(zip(*self.ld_bounds))
+ lower = np.array(lu[0])
+ upper = np.array(lu[1])
+ dim = lower.size
+ vd = VisitingDistribution(lower, upper, qv, rng)
+ values = np.zeros(dim)
+ x_step_low = vd.visiting(values, 0, self.high_temperature)
+ # Make sure that only the first component is changed
+ assert_equal(np.not_equal(x_step_low, 0), True)
+ values = np.zeros(dim)
+ x_step_high = vd.visiting(values, dim, self.high_temperature)
+ # Make sure that component other than at dim has changed
+ assert_equal(np.not_equal(x_step_high[0], 0), True)
+
+ @pytest.mark.parametrize('qv', [2.25, 2.62, 2.9])
+ def test_visiting_dist_high_temperature(self, qv):
+ rng = np.random.default_rng(1234)
+ lu = list(zip(*self.ld_bounds))
+ lower = np.array(lu[0])
+ upper = np.array(lu[1])
+ vd = VisitingDistribution(lower, upper, qv, rng)
+ # values = np.zeros(self.nbtestvalues)
+ # for i in np.arange(self.nbtestvalues):
+ # values[i] = vd.visit_fn(self.high_temperature)
+ values = vd.visit_fn(self.high_temperature, self.nbtestvalues)
+
+ # Visiting distribution is a distorted version of Cauchy-Lorentz
+ # distribution, and as no 1st and higher moments (no mean defined,
+ # no variance defined).
+ # Check that big tails values are generated
+ assert_array_less(np.min(values), 1e-10)
+ assert_array_less(1e+10, np.max(values))
+
+ def test_reset(self):
+ owf = ObjectiveFunWrapper(self.weirdfunc)
+ lu = list(zip(*self.ld_bounds))
+ lower = np.array(lu[0])
+ upper = np.array(lu[1])
+ es = EnergyState(lower, upper)
+ assert_raises(ValueError, es.reset, owf, check_random_state(None))
+
+ def test_low_dim(self):
+ ret = dual_annealing(
+ self.func, self.ld_bounds, rng=self.seed)
+ assert_allclose(ret.fun, 0., atol=1e-12)
+ assert ret.success
+
+ @pytest.mark.fail_slow(10)
+ def test_high_dim(self):
+ ret = dual_annealing(self.func, self.hd_bounds, rng=self.seed)
+ assert_allclose(ret.fun, 0., atol=1e-12)
+ assert ret.success
+
+ def test_low_dim_no_ls(self):
+ ret = dual_annealing(self.func, self.ld_bounds,
+ no_local_search=True, seed=self.seed)
+ assert_allclose(ret.fun, 0., atol=1e-4)
+
+ @pytest.mark.fail_slow(10)
+ def test_high_dim_no_ls(self):
+ ret = dual_annealing(self.func, self.hd_bounds,
+ no_local_search=True, rng=self.seed)
+ assert_allclose(ret.fun, 0., atol=1.2e-4)
+
+ def test_nb_fun_call(self):
+ self.nb_fun_call.c = 0
+ ret = dual_annealing(self.func, self.ld_bounds, rng=self.seed)
+ assert_equal(self.nb_fun_call.c, ret.nfev)
+
+ def test_nb_fun_call_no_ls(self):
+ self.nb_fun_call.c = 0
+ ret = dual_annealing(self.func, self.ld_bounds,
+ no_local_search=True, rng=self.seed)
+ assert_equal(self.nb_fun_call.c, ret.nfev)
+
+ def test_max_reinit(self):
+ assert_raises(ValueError, dual_annealing, self.weirdfunc,
+ self.ld_bounds)
+
+ @pytest.mark.fail_slow(10)
+ def test_reproduce(self):
+ res1 = dual_annealing(self.func, self.ld_bounds, rng=self.seed)
+ res2 = dual_annealing(self.func, self.ld_bounds, rng=self.seed)
+ res3 = dual_annealing(self.func, self.ld_bounds, rng=self.seed)
+ # If we have reproducible results, x components found has to
+ # be exactly the same, which is not the case with no seeding
+ assert_equal(res1.x, res2.x)
+ assert_equal(res1.x, res3.x)
+
+ def test_rand_gen(self):
+ # check that np.random.Generator can be used (numpy >= 1.17)
+ # obtain a np.random.Generator object
+ rng = np.random.default_rng(1)
+
+ res1 = dual_annealing(self.func, self.ld_bounds, rng=rng)
+ # seed again
+ rng = np.random.default_rng(1)
+ res2 = dual_annealing(self.func, self.ld_bounds, rng=rng)
+ # If we have reproducible results, x components found has to
+ # be exactly the same, which is not the case with no seeding
+ assert_equal(res1.x, res2.x)
+
+ def test_bounds_integrity(self):
+ wrong_bounds = [(-5.12, 5.12), (1, 0), (5.12, 5.12)]
+ assert_raises(ValueError, dual_annealing, self.func,
+ wrong_bounds)
+
+ def test_bound_validity(self):
+ invalid_bounds = [(-5, 5), (-np.inf, 0), (-5, 5)]
+ assert_raises(ValueError, dual_annealing, self.func,
+ invalid_bounds)
+ invalid_bounds = [(-5, 5), (0, np.inf), (-5, 5)]
+ assert_raises(ValueError, dual_annealing, self.func,
+ invalid_bounds)
+ invalid_bounds = [(-5, 5), (0, np.nan), (-5, 5)]
+ assert_raises(ValueError, dual_annealing, self.func,
+ invalid_bounds)
+
+ def test_deprecated_local_search_options_bounds(self):
+ def func(x):
+ return np.sum((x - 5) * (x - 1))
+ bounds = list(zip([-6, -5], [6, 5]))
+ # Test bounds can be passed (see gh-10831)
+
+ with pytest.warns(RuntimeWarning, match=r"Method CG cannot handle "):
+ dual_annealing(
+ func,
+ bounds=bounds,
+ minimizer_kwargs={"method": "CG", "bounds": bounds})
+
+ def test_minimizer_kwargs_bounds(self):
+ def func(x):
+ return np.sum((x - 5) * (x - 1))
+ bounds = list(zip([-6, -5], [6, 5]))
+ # Test bounds can be passed (see gh-10831)
+ dual_annealing(
+ func,
+ bounds=bounds,
+ minimizer_kwargs={"method": "SLSQP", "bounds": bounds})
+
+ with pytest.warns(RuntimeWarning, match=r"Method CG cannot handle "):
+ dual_annealing(
+ func,
+ bounds=bounds,
+ minimizer_kwargs={"method": "CG", "bounds": bounds})
+
+ def test_max_fun_ls(self):
+ ret = dual_annealing(self.func, self.ld_bounds, maxfun=100,
+ rng=self.seed)
+
+ ls_max_iter = min(max(
+ len(self.ld_bounds) * LocalSearchWrapper.LS_MAXITER_RATIO,
+ LocalSearchWrapper.LS_MAXITER_MIN),
+ LocalSearchWrapper.LS_MAXITER_MAX)
+ assert ret.nfev <= 100 + ls_max_iter
+ assert not ret.success
+
+ def test_max_fun_no_ls(self):
+ ret = dual_annealing(self.func, self.ld_bounds,
+ no_local_search=True, maxfun=500, rng=self.seed)
+ assert ret.nfev <= 500
+ assert not ret.success
+
+ def test_maxiter(self):
+ ret = dual_annealing(self.func, self.ld_bounds, maxiter=700,
+ rng=self.seed)
+ assert ret.nit <= 700
+
+ # Testing that args are passed correctly for dual_annealing
+ def test_fun_args_ls(self):
+ ret = dual_annealing(self.func, self.ld_bounds,
+ args=((3.14159,)), rng=self.seed)
+ assert_allclose(ret.fun, 3.14159, atol=1e-6)
+
+ # Testing that args are passed correctly for pure simulated annealing
+ def test_fun_args_no_ls(self):
+ ret = dual_annealing(self.func, self.ld_bounds,
+ args=((3.14159, )), no_local_search=True,
+ rng=self.seed)
+ assert_allclose(ret.fun, 3.14159, atol=1e-4)
+
+ def test_callback_stop(self):
+ # Testing that callback make the algorithm stop for
+ # fun value <= 1.0 (see callback method)
+ ret = dual_annealing(self.func, self.ld_bounds,
+ callback=self.callback, rng=self.seed)
+ assert ret.fun <= 1.0
+ assert 'stop early' in ret.message[0]
+ assert not ret.success
+
+ @pytest.mark.parametrize('method, atol', [
+ ('Nelder-Mead', 2e-5),
+ ('COBYLA', 1e-5),
+ ('COBYQA', 1e-8),
+ ('Powell', 1e-8),
+ ('CG', 1e-8),
+ ('BFGS', 1e-8),
+ ('TNC', 1e-8),
+ ('SLSQP', 2e-7),
+ ])
+ def test_multi_ls_minimizer(self, method, atol):
+ ret = dual_annealing(self.func, self.ld_bounds,
+ minimizer_kwargs=dict(method=method),
+ rng=self.seed)
+ assert_allclose(ret.fun, 0., atol=atol)
+
+ def test_wrong_restart_temp(self):
+ assert_raises(ValueError, dual_annealing, self.func,
+ self.ld_bounds, restart_temp_ratio=1)
+ assert_raises(ValueError, dual_annealing, self.func,
+ self.ld_bounds, restart_temp_ratio=0)
+
+ def test_gradient_gnev(self):
+ minimizer_opts = {
+ 'jac': self.rosen_der_wrapper,
+ }
+ ret = dual_annealing(rosen, self.ld_bounds,
+ minimizer_kwargs=minimizer_opts,
+ rng=self.seed)
+ assert ret.njev == self.ngev.c
+
+ @pytest.mark.fail_slow(10)
+ def test_from_docstring(self):
+ def func(x):
+ return np.sum(x * x - 10 * np.cos(2 * np.pi * x)) + 10 * np.size(x)
+ lw = [-5.12] * 10
+ up = [5.12] * 10
+ ret = dual_annealing(func, bounds=list(zip(lw, up)), rng=1234)
+ assert_allclose(ret.x,
+ [-4.26437714e-09, -3.91699361e-09, -1.86149218e-09,
+ -3.97165720e-09, -6.29151648e-09, -6.53145322e-09,
+ -3.93616815e-09, -6.55623025e-09, -6.05775280e-09,
+ -5.00668935e-09], atol=4e-8)
+ assert_allclose(ret.fun, 0.000000, atol=5e-13)
+
+ @pytest.mark.parametrize('new_e, temp_step, accepted, accept_rate', [
+ (0, 100, 1000, 1.0097587941791923),
+ (0, 2, 1000, 1.2599210498948732),
+ (10, 100, 878, 0.8786035869128718),
+ (10, 60, 695, 0.6812920690579612),
+ (2, 100, 990, 0.9897404249173424),
+ ])
+ def test_accept_reject_probabilistic(
+ self, new_e, temp_step, accepted, accept_rate):
+ # Test accepts unconditionally with e < current_energy and
+ # probabilistically with e > current_energy
+
+ rs = check_random_state(123)
+
+ count_accepted = 0
+ iterations = 1000
+
+ accept_param = -5
+ current_energy = 1
+ for _ in range(iterations):
+ energy_state = EnergyState(lower=None, upper=None)
+ # Set energy state with current_energy, any location.
+ energy_state.update_current(current_energy, [0])
+
+ chain = StrategyChain(
+ accept_param, None, None, None, rs, energy_state)
+ # Normally this is set in run()
+ chain.temperature_step = temp_step
+
+ # Check if update is accepted.
+ chain.accept_reject(j=1, e=new_e, x_visit=[2])
+ if energy_state.current_energy == new_e:
+ count_accepted += 1
+
+ assert count_accepted == accepted
+
+ # Check accept rate
+ pqv = 1 - (1 - accept_param) * (new_e - current_energy) / temp_step
+ rate = 0 if pqv <= 0 else np.exp(np.log(pqv) / (1 - accept_param))
+
+ assert_allclose(rate, accept_rate)
+
+ @pytest.mark.fail_slow(10)
+ def test_bounds_class(self):
+ # test that result does not depend on the bounds type
+ def func(x):
+ f = np.sum(x * x - 10 * np.cos(2 * np.pi * x)) + 10 * np.size(x)
+ return f
+ lw = [-5.12] * 5
+ up = [5.12] * 5
+
+ # Unbounded global minimum is all zeros. Most bounds below will force
+ # a DV away from unbounded minimum and be active at solution.
+ up[0] = -2.0
+ up[1] = -1.0
+ lw[3] = 1.0
+ lw[4] = 2.0
+
+ # run optimizations
+ bounds = Bounds(lw, up)
+ ret_bounds_class = dual_annealing(func, bounds=bounds, rng=1234)
+
+ bounds_old = list(zip(lw, up))
+ ret_bounds_list = dual_annealing(func, bounds=bounds_old, rng=1234)
+
+ # test that found minima, function evaluations and iterations match
+ assert_allclose(ret_bounds_class.x, ret_bounds_list.x, atol=1e-8)
+ assert_allclose(ret_bounds_class.x, np.arange(-2, 3), atol=1e-7)
+ assert_allclose(ret_bounds_list.fun, ret_bounds_class.fun, atol=1e-9)
+ assert ret_bounds_list.nfev == ret_bounds_class.nfev
+
+ @pytest.mark.fail_slow(10)
+ def test_callable_jac_hess_with_args_gh11052(self):
+ # dual_annealing used to fail when `jac` was callable and `args` were
+ # used; check that this is resolved. Example is from gh-11052.
+
+ # extended to hess as part of closing gh20614
+ rng = np.random.default_rng(94253637693657847462)
+ def f(x, power):
+ return np.sum(np.exp(x ** power))
+
+ def jac(x, power):
+ return np.exp(x ** power) * power * x ** (power - 1)
+
+ def hess(x, power):
+ # calculated using WolframAlpha as d^2/dx^2 e^(x^p)
+ return np.diag(
+ power * np.exp(x ** power) * x ** (power - 2) *
+ (power * x ** power + power - 1)
+ )
+
+ def hessp(x, p, power):
+ return hess(x, power) @ p
+
+ res1 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng,
+ minimizer_kwargs=dict(method='L-BFGS-B'))
+ res2 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng,
+ minimizer_kwargs=dict(method='L-BFGS-B',
+ jac=jac))
+ res3 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng,
+ minimizer_kwargs=dict(method='newton-cg',
+ jac=jac, hess=hess))
+ res4 = dual_annealing(f, args=(2, ), bounds=[[0, 1], [0, 1]], rng=rng,
+ minimizer_kwargs=dict(method='newton-cg',
+ jac=jac, hessp=hessp))
+ assert_allclose(res1.fun, res2.fun, rtol=1e-6)
+ assert_allclose(res3.fun, res2.fun, rtol=1e-6)
+ assert_allclose(res4.fun, res2.fun, rtol=1e-6)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py
new file mode 100644
index 0000000000000000000000000000000000000000..c1affff822e8abdb50ba1483b0f3f85eb1becdd6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__linprog_clean_inputs.py
@@ -0,0 +1,320 @@
+"""
+Unit test for Linear Programming via Simplex Algorithm.
+"""
+import warnings
+
+from copy import deepcopy
+from datetime import date
+
+import numpy as np
+from numpy.testing import assert_, assert_allclose, assert_equal
+from numpy.exceptions import VisibleDeprecationWarning
+from pytest import raises as assert_raises
+
+from scipy.optimize._linprog_util import _clean_inputs, _LPProblem
+
+
+def test_aliasing():
+ """
+ Test for ensuring that no objects referred to by `lp` attributes,
+ `c`, `A_ub`, `b_ub`, `A_eq`, `b_eq`, `bounds`, have been modified
+ by `_clean_inputs` as a side effect.
+ """
+ lp = _LPProblem(
+ c=1,
+ A_ub=[[1]],
+ b_ub=[1],
+ A_eq=[[1]],
+ b_eq=[1],
+ bounds=(-np.inf, np.inf)
+ )
+ lp_copy = deepcopy(lp)
+
+ _clean_inputs(lp)
+
+ assert_(lp.c == lp_copy.c, "c modified by _clean_inputs")
+ assert_(lp.A_ub == lp_copy.A_ub, "A_ub modified by _clean_inputs")
+ assert_(lp.b_ub == lp_copy.b_ub, "b_ub modified by _clean_inputs")
+ assert_(lp.A_eq == lp_copy.A_eq, "A_eq modified by _clean_inputs")
+ assert_(lp.b_eq == lp_copy.b_eq, "b_eq modified by _clean_inputs")
+ assert_(lp.bounds == lp_copy.bounds, "bounds modified by _clean_inputs")
+
+
+def test_aliasing2():
+ """
+ Similar purpose as `test_aliasing` above.
+ """
+ lp = _LPProblem(
+ c=np.array([1, 1]),
+ A_ub=np.array([[1, 1], [2, 2]]),
+ b_ub=np.array([[1], [1]]),
+ A_eq=np.array([[1, 1]]),
+ b_eq=np.array([1]),
+ bounds=[(-np.inf, np.inf), (None, 1)]
+ )
+ lp_copy = deepcopy(lp)
+
+ _clean_inputs(lp)
+
+ assert_allclose(lp.c, lp_copy.c, err_msg="c modified by _clean_inputs")
+ assert_allclose(lp.A_ub, lp_copy.A_ub, err_msg="A_ub modified by _clean_inputs")
+ assert_allclose(lp.b_ub, lp_copy.b_ub, err_msg="b_ub modified by _clean_inputs")
+ assert_allclose(lp.A_eq, lp_copy.A_eq, err_msg="A_eq modified by _clean_inputs")
+ assert_allclose(lp.b_eq, lp_copy.b_eq, err_msg="b_eq modified by _clean_inputs")
+ assert_(lp.bounds == lp_copy.bounds, "bounds modified by _clean_inputs")
+
+
+def test_missing_inputs():
+ c = [1, 2]
+ A_ub = np.array([[1, 1], [2, 2]])
+ b_ub = np.array([1, 1])
+ A_eq = np.array([[1, 1], [2, 2]])
+ b_eq = np.array([1, 1])
+
+ assert_raises(TypeError, _clean_inputs)
+ assert_raises(TypeError, _clean_inputs, _LPProblem(c=None))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=A_ub))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=A_ub, b_ub=None))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, b_ub=b_ub))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=None, b_ub=b_ub))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=A_eq))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=A_eq, b_eq=None))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, b_eq=b_eq))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=None, b_eq=b_eq))
+
+
+def test_too_many_dimensions():
+ cb = [1, 2, 3, 4]
+ rng = np.random.default_rng(1234)
+ A = rng.random((4, 4))
+ bad2D = [[1, 2], [3, 4]]
+ bad3D = rng.random((4, 4, 4))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=bad2D, A_ub=A, b_ub=cb))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=bad3D, b_ub=cb))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=A, b_ub=bad2D))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=bad3D, b_eq=cb))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=A, b_eq=bad2D))
+
+
+def test_too_few_dimensions():
+ rng = np.random.default_rng(1234)
+ bad = rng.random((4, 4)).ravel()
+ cb = rng.random(4)
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_ub=bad, b_ub=cb))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=cb, A_eq=bad, b_eq=cb))
+
+
+def test_inconsistent_dimensions():
+ m = 2
+ n = 4
+ c = [1, 2, 3, 4]
+
+ rng = np.random.default_rng(122390)
+ Agood = rng.random((m, n))
+ Abad = rng.random((m, n + 1))
+ bgood = rng.random(m)
+ bbad = rng.random(m + 1)
+ boundsbad = [(0, 1)] * (n + 1)
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=Abad, b_ub=bgood))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_ub=Agood, b_ub=bbad))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=Abad, b_eq=bgood))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, A_eq=Agood, b_eq=bbad))
+ assert_raises(ValueError, _clean_inputs, _LPProblem(c=c, bounds=boundsbad))
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Creating an ndarray from ragged", VisibleDeprecationWarning)
+ assert_raises(ValueError, _clean_inputs,
+ _LPProblem(c=c, bounds=[[1, 2], [2, 3], [3, 4], [4, 5, 6]]))
+
+
+def test_type_errors():
+ lp = _LPProblem(
+ c=[1, 2],
+ A_ub=np.array([[1, 1], [2, 2]]),
+ b_ub=np.array([1, 1]),
+ A_eq=np.array([[1, 1], [2, 2]]),
+ b_eq=np.array([1, 1]),
+ bounds=[(0, 1)]
+ )
+ bad = "hello"
+
+ assert_raises(TypeError, _clean_inputs, lp._replace(c=bad))
+ assert_raises(TypeError, _clean_inputs, lp._replace(A_ub=bad))
+ assert_raises(TypeError, _clean_inputs, lp._replace(b_ub=bad))
+ assert_raises(TypeError, _clean_inputs, lp._replace(A_eq=bad))
+ assert_raises(TypeError, _clean_inputs, lp._replace(b_eq=bad))
+
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=bad))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds="hi"))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=["hi"]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[("hi")]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, "")]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, 2), (1, "")]))
+ assert_raises(TypeError, _clean_inputs,
+ lp._replace(bounds=[(1, date(2020, 2, 29))]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[[[1, 2]]]))
+
+
+def test_non_finite_errors():
+ lp = _LPProblem(
+ c=[1, 2],
+ A_ub=np.array([[1, 1], [2, 2]]),
+ b_ub=np.array([1, 1]),
+ A_eq=np.array([[1, 1], [2, 2]]),
+ b_eq=np.array([1, 1]),
+ bounds=[(0, 1)]
+ )
+ assert_raises(ValueError, _clean_inputs, lp._replace(c=[0, None]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(c=[np.inf, 0]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(c=[0, -np.inf]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(c=[np.nan, 0]))
+
+ assert_raises(ValueError, _clean_inputs, lp._replace(A_ub=[[1, 2], [None, 1]]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(b_ub=[np.inf, 1]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(A_eq=[[1, 2], [1, -np.inf]]))
+ assert_raises(ValueError, _clean_inputs, lp._replace(b_eq=[1, np.nan]))
+
+
+def test__clean_inputs1():
+ lp = _LPProblem(
+ c=[1, 2],
+ A_ub=[[1, 1], [2, 2]],
+ b_ub=[1, 1],
+ A_eq=[[1, 1], [2, 2]],
+ b_eq=[1, 1],
+ bounds=None
+ )
+
+ lp_cleaned = _clean_inputs(lp)
+
+ assert_allclose(lp_cleaned.c, np.array(lp.c))
+ assert_allclose(lp_cleaned.A_ub, np.array(lp.A_ub))
+ assert_allclose(lp_cleaned.b_ub, np.array(lp.b_ub))
+ assert_allclose(lp_cleaned.A_eq, np.array(lp.A_eq))
+ assert_allclose(lp_cleaned.b_eq, np.array(lp.b_eq))
+ assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
+
+ assert_(lp_cleaned.c.shape == (2,), "")
+ assert_(lp_cleaned.A_ub.shape == (2, 2), "")
+ assert_(lp_cleaned.b_ub.shape == (2,), "")
+ assert_(lp_cleaned.A_eq.shape == (2, 2), "")
+ assert_(lp_cleaned.b_eq.shape == (2,), "")
+
+
+def test__clean_inputs2():
+ lp = _LPProblem(
+ c=1,
+ A_ub=[[1]],
+ b_ub=1,
+ A_eq=[[1]],
+ b_eq=1,
+ bounds=(0, 1)
+ )
+
+ lp_cleaned = _clean_inputs(lp)
+
+ assert_allclose(lp_cleaned.c, np.array(lp.c))
+ assert_allclose(lp_cleaned.A_ub, np.array(lp.A_ub))
+ assert_allclose(lp_cleaned.b_ub, np.array(lp.b_ub))
+ assert_allclose(lp_cleaned.A_eq, np.array(lp.A_eq))
+ assert_allclose(lp_cleaned.b_eq, np.array(lp.b_eq))
+ assert_equal(lp_cleaned.bounds, [(0, 1)])
+
+ assert_(lp_cleaned.c.shape == (1,), "")
+ assert_(lp_cleaned.A_ub.shape == (1, 1), "")
+ assert_(lp_cleaned.b_ub.shape == (1,), "")
+ assert_(lp_cleaned.A_eq.shape == (1, 1), "")
+ assert_(lp_cleaned.b_eq.shape == (1,), "")
+
+
+def test__clean_inputs3():
+ rng = np.random.default_rng(1890908)
+ lp = _LPProblem(
+ c=[[1, 2]],
+ A_ub=rng.random((2, 2)),
+ b_ub=[[1], [2]],
+ A_eq=rng.random((2, 2)),
+ b_eq=[[1], [2]],
+ bounds=[(0, 1)]
+ )
+
+ lp_cleaned = _clean_inputs(lp)
+
+ assert_allclose(lp_cleaned.c, np.array([1, 2]))
+ assert_allclose(lp_cleaned.b_ub, np.array([1, 2]))
+ assert_allclose(lp_cleaned.b_eq, np.array([1, 2]))
+ assert_equal(lp_cleaned.bounds, [(0, 1)] * 2)
+
+ assert_(lp_cleaned.c.shape == (2,), "")
+ assert_(lp_cleaned.b_ub.shape == (2,), "")
+ assert_(lp_cleaned.b_eq.shape == (2,), "")
+
+
+def test_bad_bounds():
+ lp = _LPProblem(c=[1, 2])
+
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=(1, 2, 2)))
+ assert_raises(ValueError, _clean_inputs, lp._replace(bounds=[(1, 2, 2)]))
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Creating an ndarray from ragged", VisibleDeprecationWarning)
+ assert_raises(ValueError, _clean_inputs,
+ lp._replace(bounds=[(1, 2), (1, 2, 2)]))
+ assert_raises(ValueError, _clean_inputs,
+ lp._replace(bounds=[(1, 2), (1, 2), (1, 2)]))
+
+ lp = _LPProblem(c=[1, 2, 3, 4])
+
+ assert_raises(ValueError, _clean_inputs,
+ lp._replace(bounds=[(1, 2, 3, 4), (1, 2, 3, 4)]))
+
+
+def test_good_bounds():
+ lp = _LPProblem(c=[1, 2])
+
+ lp_cleaned = _clean_inputs(lp) # lp.bounds is None by default
+ assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[]))
+ assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[[]]))
+ assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=(1, 2)))
+ assert_equal(lp_cleaned.bounds, [(1, 2)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, 2)]))
+ assert_equal(lp_cleaned.bounds, [(1, 2)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, None)]))
+ assert_equal(lp_cleaned.bounds, [(1, np.inf)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, 1)]))
+ assert_equal(lp_cleaned.bounds, [(-np.inf, 1)] * 2)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, None), (-np.inf, None)]))
+ assert_equal(lp_cleaned.bounds, [(-np.inf, np.inf)] * 2)
+
+ lp = _LPProblem(c=[1, 2, 3, 4])
+
+ lp_cleaned = _clean_inputs(lp) # lp.bounds is None by default
+ assert_equal(lp_cleaned.bounds, [(0, np.inf)] * 4)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=(1, 2)))
+ assert_equal(lp_cleaned.bounds, [(1, 2)] * 4)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, 2)]))
+ assert_equal(lp_cleaned.bounds, [(1, 2)] * 4)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(1, None)]))
+ assert_equal(lp_cleaned.bounds, [(1, np.inf)] * 4)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, 1)]))
+ assert_equal(lp_cleaned.bounds, [(-np.inf, 1)] * 4)
+
+ lp_cleaned = _clean_inputs(lp._replace(bounds=[(None, None),
+ (-np.inf, None),
+ (None, np.inf),
+ (-np.inf, np.inf)]))
+ assert_equal(lp_cleaned.bounds, [(-np.inf, np.inf)] * 4)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__numdiff.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__numdiff.py
new file mode 100644
index 0000000000000000000000000000000000000000..aedd84d62791e8f094a918c9980d6ab87b3fda47
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__numdiff.py
@@ -0,0 +1,885 @@
+import math
+from itertools import product
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal, assert_
+import pytest
+from pytest import raises as assert_raises
+
+from scipy._lib._util import MapWrapper, _ScalarFunctionWrapper
+from scipy.sparse import csr_array, csc_array, lil_array
+
+from scipy.optimize._numdiff import (
+ _adjust_scheme_to_bounds, approx_derivative, check_derivative,
+ group_columns, _eps_for_method, _compute_absolute_step)
+from scipy.optimize import rosen
+
+
+def test_group_columns():
+ structure = [
+ [1, 1, 0, 0, 0, 0],
+ [1, 1, 1, 0, 0, 0],
+ [0, 1, 1, 1, 0, 0],
+ [0, 0, 1, 1, 1, 0],
+ [0, 0, 0, 1, 1, 1],
+ [0, 0, 0, 0, 1, 1],
+ [0, 0, 0, 0, 0, 0]
+ ]
+ for transform in [np.asarray, csr_array, csc_array, lil_array]:
+ A = transform(structure)
+ order = np.arange(6)
+ groups_true = np.array([0, 1, 2, 0, 1, 2])
+ groups = group_columns(A, order)
+ assert_equal(groups, groups_true)
+
+ order = [1, 2, 4, 3, 5, 0]
+ groups_true = np.array([2, 0, 1, 2, 0, 1])
+ groups = group_columns(A, order)
+ assert_equal(groups, groups_true)
+
+ # Test repeatability.
+ groups_1 = group_columns(A)
+ groups_2 = group_columns(A)
+ assert_equal(groups_1, groups_2)
+
+
+def test_correct_fp_eps():
+ # check that relative step size is correct for FP size
+ EPS = np.finfo(np.float64).eps
+ relative_step = {"2-point": EPS**0.5,
+ "3-point": EPS**(1/3),
+ "cs": EPS**0.5}
+ for method in ['2-point', '3-point', 'cs']:
+ assert_allclose(
+ _eps_for_method(np.float64, np.float64, method),
+ relative_step[method])
+ assert_allclose(
+ _eps_for_method(np.complex128, np.complex128, method),
+ relative_step[method]
+ )
+
+ # check another FP size
+ EPS = np.finfo(np.float32).eps
+ relative_step = {"2-point": EPS**0.5,
+ "3-point": EPS**(1/3),
+ "cs": EPS**0.5}
+
+ for method in ['2-point', '3-point', 'cs']:
+ assert_allclose(
+ _eps_for_method(np.float64, np.float32, method),
+ relative_step[method]
+ )
+ assert_allclose(
+ _eps_for_method(np.float32, np.float64, method),
+ relative_step[method]
+ )
+ assert_allclose(
+ _eps_for_method(np.float32, np.float32, method),
+ relative_step[method]
+ )
+
+
+class TestAdjustSchemeToBounds:
+ def test_no_bounds(self):
+ x0 = np.zeros(3)
+ h = np.full(3, 1e-2)
+ inf_lower = np.empty_like(x0)
+ inf_upper = np.empty_like(x0)
+ inf_lower.fill(-np.inf)
+ inf_upper.fill(np.inf)
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '1-sided', inf_lower, inf_upper)
+ assert_allclose(h_adjusted, h)
+ assert_(np.all(one_sided))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 2, '1-sided', inf_lower, inf_upper)
+ assert_allclose(h_adjusted, h)
+ assert_(np.all(one_sided))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '2-sided', inf_lower, inf_upper)
+ assert_allclose(h_adjusted, h)
+ assert_(np.all(~one_sided))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 2, '2-sided', inf_lower, inf_upper)
+ assert_allclose(h_adjusted, h)
+ assert_(np.all(~one_sided))
+
+ def test_with_bound(self):
+ x0 = np.array([0.0, 0.85, -0.85])
+ lb = -np.ones(3)
+ ub = np.ones(3)
+ h = np.array([1, 1, -1]) * 1e-1
+
+ h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 1, '1-sided', lb, ub)
+ assert_allclose(h_adjusted, h)
+
+ h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 2, '1-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([1, -1, 1]) * 1e-1)
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '2-sided', lb, ub)
+ assert_allclose(h_adjusted, np.abs(h))
+ assert_(np.all(~one_sided))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 2, '2-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([1, -1, 1]) * 1e-1)
+ assert_equal(one_sided, np.array([False, True, True]))
+
+ def test_tight_bounds(self):
+ lb = np.array([-0.03, -0.03])
+ ub = np.array([0.05, 0.05])
+ x0 = np.array([0.0, 0.03])
+ h = np.array([-0.1, -0.1])
+
+ h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 1, '1-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([0.05, -0.06]))
+
+ h_adjusted, _ = _adjust_scheme_to_bounds(x0, h, 2, '1-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([0.025, -0.03]))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 1, '2-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([0.03, -0.03]))
+ assert_equal(one_sided, np.array([False, True]))
+
+ h_adjusted, one_sided = _adjust_scheme_to_bounds(
+ x0, h, 2, '2-sided', lb, ub)
+ assert_allclose(h_adjusted, np.array([0.015, -0.015]))
+ assert_equal(one_sided, np.array([False, True]))
+
+
+class TestApproxDerivativesDense:
+ def fun_scalar_scalar(self, x):
+ return np.sinh(x)
+
+ def jac_scalar_scalar(self, x):
+ return np.cosh(x)
+
+ def fun_scalar_vector(self, x):
+ return np.array([x[0]**2, np.tan(x[0]), np.exp(x[0])])
+
+ def jac_scalar_vector(self, x):
+ return np.array(
+ [2 * x[0], np.cos(x[0]) ** -2, np.exp(x[0])]).reshape(-1, 1)
+
+ def fun_vector_scalar(self, x):
+ return np.sin(x[0] * x[1]) * np.log(x[0])
+
+ def wrong_dimensions_fun(self, x):
+ return np.array([x**2, np.tan(x), np.exp(x)])
+
+ def jac_vector_scalar(self, x):
+ return np.array([
+ x[1] * np.cos(x[0] * x[1]) * np.log(x[0]) +
+ np.sin(x[0] * x[1]) / x[0],
+ x[0] * np.cos(x[0] * x[1]) * np.log(x[0])
+ ])
+
+ def fun_vector_vector(self, x):
+ return np.array([
+ x[0] * np.sin(x[1]),
+ x[1] * np.cos(x[0]),
+ x[0] ** 3 * x[1] ** -0.5
+ ])
+
+ def fun_vector_vector_with_arg(self, x, arg):
+ """Used to test passing custom arguments with check_derivative()"""
+ assert arg == 42
+ return np.array([
+ x[0] * np.sin(x[1]),
+ x[1] * np.cos(x[0]),
+ x[0] ** 3 * x[1] ** -0.5
+ ])
+
+ def jac_vector_vector(self, x):
+ return np.array([
+ [np.sin(x[1]), x[0] * np.cos(x[1])],
+ [-x[1] * np.sin(x[0]), np.cos(x[0])],
+ [3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5]
+ ])
+
+ def jac_vector_vector_with_arg(self, x, arg):
+ """Used to test passing custom arguments with check_derivative()"""
+ assert arg == 42
+ return np.array([
+ [np.sin(x[1]), x[0] * np.cos(x[1])],
+ [-x[1] * np.sin(x[0]), np.cos(x[0])],
+ [3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5]
+ ])
+
+ def fun_parametrized(self, x, c0, c1=1.0):
+ return np.array([np.exp(c0 * x[0]), np.exp(c1 * x[1])])
+
+ def jac_parametrized(self, x, c0, c1=0.1):
+ return np.array([
+ [c0 * np.exp(c0 * x[0]), 0],
+ [0, c1 * np.exp(c1 * x[1])]
+ ])
+
+ def fun_with_nan(self, x):
+ return x if np.abs(x) <= 1e-8 else np.nan
+
+ def jac_with_nan(self, x):
+ return 1.0 if np.abs(x) <= 1e-8 else np.nan
+
+ def fun_zero_jacobian(self, x):
+ return np.array([x[0] * x[1], np.cos(x[0] * x[1])])
+
+ def jac_zero_jacobian(self, x):
+ return np.array([
+ [x[1], x[0]],
+ [-x[1] * np.sin(x[0] * x[1]), -x[0] * np.sin(x[0] * x[1])]
+ ])
+
+ def jac_non_numpy(self, x):
+ # x can be a scalar or an array [val].
+ # Cast to true scalar before handing over to math.exp
+ xp = np.asarray(x).item()
+ return math.exp(xp)
+
+ def test_scalar_scalar(self):
+ x0 = 1.0
+ jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='2-point')
+ jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0)
+ jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='cs')
+ jac_true = self.jac_scalar_scalar(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ def test_scalar_scalar_abs_step(self):
+ # can approx_derivative use abs_step?
+ x0 = 1.0
+ jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='2-point', abs_step=1.49e-8)
+ jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0,
+ abs_step=1.49e-8)
+ jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='cs', abs_step=1.49e-8)
+ jac_true = self.jac_scalar_scalar(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ def test_scalar_vector(self):
+ x0 = 0.5
+ with MapWrapper(2) as mapper:
+ jac_diff_2 = approx_derivative(self.fun_scalar_vector, x0,
+ method='2-point', workers=mapper)
+ jac_diff_3 = approx_derivative(self.fun_scalar_vector, x0, workers=map)
+ jac_diff_4 = approx_derivative(self.fun_scalar_vector, x0,
+ method='cs', workers=None)
+ jac_true = self.jac_scalar_vector(np.atleast_1d(x0))
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ @pytest.mark.fail_slow(5.0)
+ def test_workers_evaluations_and_nfev(self):
+ # check that nfev consumed by approx_derivative is tracked properly
+ # and that parallel evaluation is same as series
+ x0 = [0.5, 1.5, 2.0]
+ with MapWrapper(2) as mapper:
+ md2, mdct2 = approx_derivative(rosen, x0,
+ method='2-point', workers=mapper,
+ full_output=True)
+ md3, mdct3 = approx_derivative(rosen, x0,
+ workers=mapper, full_output=True)
+ # supply a number for workers. This is not normally recommended
+ # for upstream workers as setting up processes incurs a large overhead
+ md4, mdct4 = approx_derivative(rosen, x0,
+ method='cs', workers=2,
+ full_output=True)
+
+ sfr = _ScalarFunctionWrapper(rosen)
+ d2, dct2 = approx_derivative(sfr, x0, method='2-point', full_output=True)
+ assert_equal(dct2['nfev'], sfr.nfev)
+ sfr.nfev = 0
+ d3, dct3 = approx_derivative(sfr, x0, full_output=True)
+ assert_equal(dct3['nfev'], sfr.nfev)
+ sfr.nfev = 0
+ d4, dct4 = approx_derivative(sfr, x0, method='cs', full_output=True)
+ assert_equal(dct4['nfev'], sfr.nfev)
+
+ assert_equal(mdct2['nfev'], dct2['nfev'])
+ assert_equal(mdct3['nfev'], dct3['nfev'])
+ assert_equal(mdct4['nfev'], dct4['nfev'])
+ # also check that gradients are equivalent
+ assert_equal(md2, d2)
+ assert_equal(md3, d3)
+ assert_equal(md4, d4)
+
+ def test_vector_scalar(self):
+ x0 = np.array([100.0, -0.5])
+ jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0,
+ method='2-point')
+ jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0)
+ jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0,
+ method='cs')
+ jac_true = self.jac_vector_scalar(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-7)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ def test_vector_scalar_abs_step(self):
+ # can approx_derivative use abs_step?
+ x0 = np.array([100.0, -0.5])
+ jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0,
+ method='2-point', abs_step=1.49e-8)
+ jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0,
+ abs_step=1.49e-8, rel_step=np.inf)
+ jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0,
+ method='cs', abs_step=1.49e-8)
+ jac_true = self.jac_vector_scalar(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=3e-9)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ def test_vector_vector(self):
+ x0 = np.array([-100.0, 0.2])
+ jac_diff_2 = approx_derivative(self.fun_vector_vector, x0,
+ method='2-point')
+ jac_diff_3 = approx_derivative(self.fun_vector_vector, x0)
+ with MapWrapper(2) as mapper:
+ jac_diff_4 = approx_derivative(self.fun_vector_vector, x0,
+ method='cs', workers=mapper)
+ jac_true = self.jac_vector_vector(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-5)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_4, jac_true, rtol=1e-12)
+
+ def test_wrong_dimensions(self):
+ x0 = 1.0
+ assert_raises(RuntimeError, approx_derivative,
+ self.wrong_dimensions_fun, x0)
+ f0 = self.wrong_dimensions_fun(np.atleast_1d(x0))
+ assert_raises(ValueError, approx_derivative,
+ self.wrong_dimensions_fun, x0, f0=f0)
+
+ def test_custom_rel_step(self):
+ x0 = np.array([-0.1, 0.1])
+ jac_diff_2 = approx_derivative(self.fun_vector_vector, x0,
+ method='2-point', rel_step=1e-4)
+ jac_diff_3 = approx_derivative(self.fun_vector_vector, x0,
+ rel_step=1e-4)
+ jac_true = self.jac_vector_vector(x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-2)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-4)
+
+ def test_options(self):
+ x0 = np.array([1.0, 1.0])
+ c0 = -1.0
+ c1 = 1.0
+ lb = 0.0
+ ub = 2.0
+ f0 = self.fun_parametrized(x0, c0, c1=c1)
+ rel_step = np.array([-1e-6, 1e-7])
+ jac_true = self.jac_parametrized(x0, c0, c1)
+ jac_diff_2 = approx_derivative(
+ self.fun_parametrized, x0, method='2-point', rel_step=rel_step,
+ f0=f0, args=(c0,), kwargs=dict(c1=c1), bounds=(lb, ub))
+ jac_diff_3 = approx_derivative(
+ self.fun_parametrized, x0, rel_step=rel_step,
+ f0=f0, args=(c0,), kwargs=dict(c1=c1), bounds=(lb, ub))
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+
+ def test_with_bounds_2_point(self):
+ lb = -np.ones(2)
+ ub = np.ones(2)
+
+ x0 = np.array([-2.0, 0.2])
+ assert_raises(ValueError, approx_derivative,
+ self.fun_vector_vector, x0, bounds=(lb, ub))
+
+ x0 = np.array([-1.0, 1.0])
+ jac_diff = approx_derivative(self.fun_vector_vector, x0,
+ method='2-point', bounds=(lb, ub))
+ jac_true = self.jac_vector_vector(x0)
+ assert_allclose(jac_diff, jac_true, rtol=1e-6)
+
+ def test_with_bounds_3_point(self):
+ lb = np.array([1.0, 1.0])
+ ub = np.array([2.0, 2.0])
+
+ x0 = np.array([1.0, 2.0])
+ jac_true = self.jac_vector_vector(x0)
+
+ jac_diff = approx_derivative(self.fun_vector_vector, x0)
+ assert_allclose(jac_diff, jac_true, rtol=1e-9)
+
+ jac_diff = approx_derivative(self.fun_vector_vector, x0,
+ bounds=(lb, np.inf))
+ assert_allclose(jac_diff, jac_true, rtol=1e-9)
+
+ jac_diff = approx_derivative(self.fun_vector_vector, x0,
+ bounds=(-np.inf, ub))
+ assert_allclose(jac_diff, jac_true, rtol=1e-9)
+
+ jac_diff = approx_derivative(self.fun_vector_vector, x0,
+ bounds=(lb, ub))
+ assert_allclose(jac_diff, jac_true, rtol=1e-9)
+
+ def test_tight_bounds(self):
+ x0 = np.array([10.0, 10.0])
+ lb = x0 - 3e-9
+ ub = x0 + 2e-9
+ jac_true = self.jac_vector_vector(x0)
+ jac_diff = approx_derivative(
+ self.fun_vector_vector, x0, method='2-point', bounds=(lb, ub))
+ assert_allclose(jac_diff, jac_true, rtol=1e-6)
+ jac_diff = approx_derivative(
+ self.fun_vector_vector, x0, method='2-point',
+ rel_step=1e-6, bounds=(lb, ub))
+ assert_allclose(jac_diff, jac_true, rtol=1e-6)
+
+ jac_diff = approx_derivative(
+ self.fun_vector_vector, x0, bounds=(lb, ub))
+ assert_allclose(jac_diff, jac_true, rtol=1e-6)
+ jac_diff = approx_derivative(
+ self.fun_vector_vector, x0, rel_step=1e-6, bounds=(lb, ub))
+ assert_allclose(jac_true, jac_diff, rtol=1e-6)
+
+ def test_bound_switches(self):
+ lb = -1e-8
+ ub = 1e-8
+ x0 = 0.0
+ jac_true = self.jac_with_nan(x0)
+ jac_diff_2 = approx_derivative(
+ self.fun_with_nan, x0, method='2-point', rel_step=1e-6,
+ bounds=(lb, ub))
+ jac_diff_3 = approx_derivative(
+ self.fun_with_nan, x0, rel_step=1e-6, bounds=(lb, ub))
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+
+ x0 = 1e-8
+ jac_true = self.jac_with_nan(x0)
+ jac_diff_2 = approx_derivative(
+ self.fun_with_nan, x0, method='2-point', rel_step=1e-6,
+ bounds=(lb, ub))
+ jac_diff_3 = approx_derivative(
+ self.fun_with_nan, x0, rel_step=1e-6, bounds=(lb, ub))
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-9)
+
+ def test_non_numpy(self):
+ x0 = 1.0
+ jac_true = self.jac_non_numpy(x0)
+ jac_diff_2 = approx_derivative(self.jac_non_numpy, x0,
+ method='2-point')
+ jac_diff_3 = approx_derivative(self.jac_non_numpy, x0)
+ assert_allclose(jac_diff_2, jac_true, rtol=1e-6)
+ assert_allclose(jac_diff_3, jac_true, rtol=1e-8)
+
+ # math.exp cannot handle complex arguments, hence this raises
+ assert_raises(TypeError, approx_derivative, self.jac_non_numpy, x0,
+ **dict(method='cs'))
+
+ def test_fp(self):
+ # checks that approx_derivative works for FP size other than 64.
+ # Example is derived from the minimal working example in gh12991.
+ rng = np.random.default_rng(1)
+
+ def func(p, x):
+ return p[0] + p[1] * x
+
+ def err(p, x, y):
+ return func(p, x) - y
+
+ x = np.linspace(0, 1, 100, dtype=np.float64)
+ y = rng.random(size=100, dtype=np.float64)
+ p0 = np.array([-1.0, -1.0])
+
+ jac_fp64 = approx_derivative(err, p0, method='2-point', args=(x, y))
+
+ # parameter vector is float32, func output is float64
+ jac_fp = approx_derivative(err, p0.astype(np.float32),
+ method='2-point', args=(x, y))
+ assert err(p0, x, y).dtype == np.float64
+ assert_allclose(jac_fp, jac_fp64, atol=1e-3)
+
+ # parameter vector is float64, func output is float32
+ def err_fp32(p):
+ assert p.dtype == np.float32
+ return err(p, x, y).astype(np.float32)
+
+ jac_fp = approx_derivative(err_fp32, p0.astype(np.float32),
+ method='2-point')
+ assert_allclose(jac_fp, jac_fp64, atol=1e-3)
+
+ # check upper bound of error on the derivative for 2-point
+ def f(x):
+ return np.sin(x)
+ def g(x):
+ return np.cos(x)
+ def hess(x):
+ return -np.sin(x)
+
+ def calc_atol(h, x0, f, hess, EPS):
+ # truncation error
+ t0 = h / 2 * max(np.abs(hess(x0)), np.abs(hess(x0 + h)))
+ # roundoff error. There may be a divisor (>1) missing from
+ # the following line, so this contribution is possibly
+ # overestimated
+ t1 = EPS / h * max(np.abs(f(x0)), np.abs(f(x0 + h)))
+ return t0 + t1
+
+ for dtype in [np.float16, np.float32, np.float64]:
+ EPS = np.finfo(dtype).eps
+ x0 = np.array(1.0).astype(dtype)
+ h = _compute_absolute_step(None, x0, f(x0), '2-point')
+ atol = calc_atol(h, x0, f, hess, EPS)
+ err = approx_derivative(f, x0, method='2-point',
+ abs_step=h) - g(x0)
+ assert abs(err) < atol
+
+ def test_check_derivative(self):
+ x0 = np.array([-10.0, 10])
+ accuracy = check_derivative(self.fun_vector_vector,
+ self.jac_vector_vector, x0)
+ assert_(accuracy < 1e-9)
+ accuracy = check_derivative(self.fun_vector_vector,
+ self.jac_vector_vector, x0)
+ assert_(accuracy < 1e-6)
+
+ x0 = np.array([0.0, 0.0])
+ accuracy = check_derivative(self.fun_zero_jacobian,
+ self.jac_zero_jacobian, x0)
+ assert_(accuracy == 0)
+ accuracy = check_derivative(self.fun_zero_jacobian,
+ self.jac_zero_jacobian, x0)
+ assert_(accuracy == 0)
+
+ def test_check_derivative_with_kwargs(self):
+ x0 = np.array([-10.0, 10])
+ accuracy = check_derivative(self.fun_vector_vector_with_arg,
+ self.jac_vector_vector_with_arg,
+ x0,
+ kwargs={'arg': 42})
+ assert_(accuracy < 1e-9)
+
+
+class TestApproxDerivativeSparse:
+ # Example from Numerical Optimization 2nd edition, p. 198.
+ def setup_method(self):
+ self.rng = np.random.default_rng(121091202)
+ self.n = 50
+ self.lb = -0.1 * (1 + np.arange(self.n))
+ self.ub = 0.1 * (1 + np.arange(self.n))
+ self.x0 = np.empty(self.n)
+ self.x0[::2] = (1 - 1e-7) * self.lb[::2]
+ self.x0[1::2] = (1 - 1e-7) * self.ub[1::2]
+
+ self.J_true = self.jac(self.x0)
+
+ def fun(self, x):
+ e = x[1:]**3 - x[:-1]**2
+ return np.hstack((0, 3 * e)) + np.hstack((2 * e, 0))
+
+ def jac(self, x):
+ n = x.size
+ J = np.zeros((n, n))
+ J[0, 0] = -4 * x[0]
+ J[0, 1] = 6 * x[1]**2
+ for i in range(1, n - 1):
+ J[i, i - 1] = -6 * x[i-1]
+ J[i, i] = 9 * x[i]**2 - 4 * x[i]
+ J[i, i + 1] = 6 * x[i+1]**2
+ J[-1, -1] = 9 * x[-1]**2
+ J[-1, -2] = -6 * x[-2]
+
+ return J
+
+ def structure(self, n):
+ A = np.zeros((n, n), dtype=int)
+ A[0, 0] = 1
+ A[0, 1] = 1
+ for i in range(1, n - 1):
+ A[i, i - 1: i + 2] = 1
+ A[-1, -1] = 1
+ A[-1, -2] = 1
+
+ return A
+
+ @pytest.mark.fail_slow(5)
+ def test_all(self):
+ A = self.structure(self.n)
+ order = np.arange(self.n)
+ groups_1 = group_columns(A, order)
+ self.rng.shuffle(order)
+ groups_2 = group_columns(A, order)
+
+ with MapWrapper(2) as mapper:
+ for method, groups, l, u, mf in product(
+ ['2-point', '3-point', 'cs'], [groups_1, groups_2],
+ [-np.inf, self.lb], [np.inf, self.ub], [map, mapper]):
+ J = approx_derivative(self.fun, self.x0, method=method,
+ bounds=(l, u), sparsity=(A, groups),
+ workers=mf)
+ assert_(isinstance(J, csr_array))
+ assert_allclose(J.toarray(), self.J_true, rtol=1e-6)
+
+ rel_step = np.full_like(self.x0, 1e-8)
+ rel_step[::2] *= -1
+ J = approx_derivative(self.fun, self.x0, method=method,
+ rel_step=rel_step, sparsity=(A, groups),
+ workers=mf)
+ assert_allclose(J.toarray(), self.J_true, rtol=1e-5)
+
+ def test_no_precomputed_groups(self):
+ A = self.structure(self.n)
+ J = approx_derivative(self.fun, self.x0, sparsity=A)
+ assert_allclose(J.toarray(), self.J_true, rtol=1e-6)
+
+ def test_equivalence(self):
+ structure = np.ones((self.n, self.n), dtype=int)
+ groups = np.arange(self.n)
+ for method in ['2-point', '3-point', 'cs']:
+ J_dense = approx_derivative(self.fun, self.x0, method=method)
+ J_sparse = approx_derivative(
+ self.fun, self.x0, sparsity=(structure, groups), method=method)
+ assert_allclose(J_dense, J_sparse.toarray(),
+ rtol=5e-16, atol=7e-15)
+
+ def test_check_derivative(self):
+ def jac(x):
+ return csr_array(self.jac(x))
+
+ accuracy = check_derivative(self.fun, jac, self.x0,
+ bounds=(self.lb, self.ub))
+ assert_(accuracy < 1e-9)
+
+ accuracy = check_derivative(self.fun, jac, self.x0,
+ bounds=(self.lb, self.ub))
+ assert_(accuracy < 1e-9)
+
+
+class TestApproxDerivativeLinearOperator:
+
+ def fun_scalar_scalar(self, x):
+ return np.sinh(x)
+
+ def jac_scalar_scalar(self, x):
+ return np.cosh(x)
+
+ def fun_scalar_vector(self, x):
+ return np.array([x[0]**2, np.tan(x[0]), np.exp(x[0])])
+
+ def jac_scalar_vector(self, x):
+ return np.array(
+ [2 * x[0], np.cos(x[0]) ** -2, np.exp(x[0])]).reshape(-1, 1)
+
+ def fun_vector_scalar(self, x):
+ return np.sin(x[0] * x[1]) * np.log(x[0])
+
+ def jac_vector_scalar(self, x):
+ return np.array([
+ x[1] * np.cos(x[0] * x[1]) * np.log(x[0]) +
+ np.sin(x[0] * x[1]) / x[0],
+ x[0] * np.cos(x[0] * x[1]) * np.log(x[0])
+ ])
+
+ def fun_vector_vector(self, x):
+ return np.array([
+ x[0] * np.sin(x[1]),
+ x[1] * np.cos(x[0]),
+ x[0] ** 3 * x[1] ** -0.5
+ ])
+
+ def jac_vector_vector(self, x):
+ return np.array([
+ [np.sin(x[1]), x[0] * np.cos(x[1])],
+ [-x[1] * np.sin(x[0]), np.cos(x[0])],
+ [3 * x[0] ** 2 * x[1] ** -0.5, -0.5 * x[0] ** 3 * x[1] ** -1.5]
+ ])
+
+ def test_scalar_scalar(self):
+ x0 = 1.0
+ jac_diff_2 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='2-point',
+ as_linear_operator=True)
+ jac_diff_3 = approx_derivative(self.fun_scalar_scalar, x0,
+ as_linear_operator=True)
+ jac_diff_4 = approx_derivative(self.fun_scalar_scalar, x0,
+ method='cs',
+ as_linear_operator=True)
+ jac_true = self.jac_scalar_scalar(x0)
+ rng = np.random.default_rng(11290049580398)
+ for i in range(10):
+ p = rng.uniform(-10, 10, size=(1,))
+ assert_allclose(jac_diff_2.dot(p), jac_true*p,
+ rtol=1e-5)
+ assert_allclose(jac_diff_3.dot(p), jac_true*p,
+ rtol=5e-6)
+ assert_allclose(jac_diff_4.dot(p), jac_true*p,
+ rtol=5e-6)
+
+ def test_scalar_vector(self):
+ x0 = 0.5
+ jac_diff_2 = approx_derivative(self.fun_scalar_vector, x0,
+ method='2-point',
+ as_linear_operator=True)
+ jac_diff_3 = approx_derivative(self.fun_scalar_vector, x0,
+ as_linear_operator=True)
+ jac_diff_4 = approx_derivative(self.fun_scalar_vector, x0,
+ method='cs',
+ as_linear_operator=True)
+ jac_true = self.jac_scalar_vector(np.atleast_1d(x0))
+ rng = np.random.default_rng(11290049580398)
+ for i in range(10):
+ p = rng.uniform(-10, 10, size=(1,))
+ assert_allclose(jac_diff_2.dot(p), jac_true.dot(p),
+ rtol=1e-5)
+ assert_allclose(jac_diff_3.dot(p), jac_true.dot(p),
+ rtol=5e-6)
+ assert_allclose(jac_diff_4.dot(p), jac_true.dot(p),
+ rtol=5e-6)
+
+ def test_vector_scalar(self):
+ x0 = np.array([100.0, -0.5])
+ jac_diff_2 = approx_derivative(self.fun_vector_scalar, x0,
+ method='2-point',
+ as_linear_operator=True)
+ jac_diff_3 = approx_derivative(self.fun_vector_scalar, x0,
+ as_linear_operator=True)
+ jac_diff_4 = approx_derivative(self.fun_vector_scalar, x0,
+ method='cs',
+ as_linear_operator=True)
+ jac_true = self.jac_vector_scalar(x0)
+ rng = np.random.default_rng(11290049580398)
+ for i in range(10):
+ p = rng.uniform(-10, 10, size=x0.shape)
+ assert_allclose(jac_diff_2.dot(p), np.atleast_1d(jac_true.dot(p)),
+ rtol=1e-5)
+ assert_allclose(jac_diff_3.dot(p), np.atleast_1d(jac_true.dot(p)),
+ rtol=5e-6)
+ assert_allclose(jac_diff_4.dot(p), np.atleast_1d(jac_true.dot(p)),
+ rtol=1e-7)
+
+ def test_vector_vector(self):
+ x0 = np.array([-100.0, 0.2])
+ jac_diff_2 = approx_derivative(self.fun_vector_vector, x0,
+ method='2-point',
+ as_linear_operator=True)
+ jac_diff_3 = approx_derivative(self.fun_vector_vector, x0,
+ as_linear_operator=True)
+ jac_diff_4 = approx_derivative(self.fun_vector_vector, x0,
+ method='cs',
+ as_linear_operator=True)
+ jac_true = self.jac_vector_vector(x0)
+ rng = np.random.default_rng(11290049580398)
+ for i in range(10):
+ p = rng.uniform(-10, 10, size=x0.shape)
+ assert_allclose(jac_diff_2.dot(p), jac_true.dot(p), rtol=1e-5)
+ assert_allclose(jac_diff_3.dot(p), jac_true.dot(p), rtol=1e-6)
+ assert_allclose(jac_diff_4.dot(p), jac_true.dot(p), rtol=1e-7)
+
+ def test_exception(self):
+ x0 = np.array([-100.0, 0.2])
+ assert_raises(ValueError, approx_derivative,
+ self.fun_vector_vector, x0,
+ method='2-point', bounds=(1, np.inf))
+
+
+def test_absolute_step_sign():
+ # test for gh12487
+ # if an absolute step is specified for 2-point differences make sure that
+ # the side corresponds to the step. i.e. if step is positive then forward
+ # differences should be used, if step is negative then backwards
+ # differences should be used.
+
+ # function has double discontinuity at x = [-1, -1]
+ # first component is \/, second component is /\
+ def f(x):
+ return -np.abs(x[0] + 1) + np.abs(x[1] + 1)
+
+ # check that the forward difference is used
+ grad = approx_derivative(f, [-1, -1], method='2-point', abs_step=1e-8)
+ assert_allclose(grad, [-1.0, 1.0])
+
+ # check that the backwards difference is used
+ grad = approx_derivative(f, [-1, -1], method='2-point', abs_step=-1e-8)
+ assert_allclose(grad, [1.0, -1.0])
+
+ # check that the forwards difference is used with a step for both
+ # parameters
+ grad = approx_derivative(
+ f, [-1, -1], method='2-point', abs_step=[1e-8, 1e-8]
+ )
+ assert_allclose(grad, [-1.0, 1.0])
+
+ # check that we can mix forward/backwards steps.
+ grad = approx_derivative(
+ f, [-1, -1], method='2-point', abs_step=[1e-8, -1e-8]
+ )
+ assert_allclose(grad, [-1.0, -1.0])
+ grad = approx_derivative(
+ f, [-1, -1], method='2-point', abs_step=[-1e-8, 1e-8]
+ )
+ assert_allclose(grad, [1.0, 1.0])
+
+ # the forward step should reverse to a backwards step if it runs into a
+ # bound
+ # This is kind of tested in TestAdjustSchemeToBounds, but only for a lower level
+ # function.
+ grad = approx_derivative(
+ f, [-1, -1], method='2-point', abs_step=1e-8,
+ bounds=(-np.inf, -1)
+ )
+ assert_allclose(grad, [1.0, -1.0])
+
+ grad = approx_derivative(
+ f, [-1, -1], method='2-point', abs_step=-1e-8, bounds=(-1, np.inf)
+ )
+ assert_allclose(grad, [-1.0, 1.0])
+
+
+def test__compute_absolute_step():
+ # tests calculation of absolute step from rel_step
+ methods = ['2-point', '3-point', 'cs']
+
+ x0 = np.array([1e-5, 0, 1, 1e5])
+
+ EPS = np.finfo(np.float64).eps
+ relative_step = {
+ "2-point": EPS**0.5,
+ "3-point": EPS**(1/3),
+ "cs": EPS**0.5
+ }
+ f0 = np.array(1.0)
+
+ for method in methods:
+ rel_step = relative_step[method]
+ correct_step = np.array([rel_step,
+ rel_step * 1.,
+ rel_step * 1.,
+ rel_step * np.abs(x0[3])])
+
+ abs_step = _compute_absolute_step(None, x0, f0, method)
+ assert_allclose(abs_step, correct_step)
+
+ sign_x0 = (-x0 >= 0).astype(float) * 2 - 1
+ abs_step = _compute_absolute_step(None, -x0, f0, method)
+ assert_allclose(abs_step, sign_x0 * correct_step)
+
+ # if a relative step is provided it should be used
+ rel_step = np.array([0.1, 1, 10, 100])
+ correct_step = np.array([rel_step[0] * x0[0],
+ relative_step['2-point'],
+ rel_step[2] * 1.,
+ rel_step[3] * np.abs(x0[3])])
+
+ abs_step = _compute_absolute_step(rel_step, x0, f0, '2-point')
+ assert_allclose(abs_step, correct_step)
+
+ sign_x0 = (-x0 >= 0).astype(float) * 2 - 1
+ abs_step = _compute_absolute_step(rel_step, -x0, f0, '2-point')
+ assert_allclose(abs_step, sign_x0 * correct_step)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__remove_redundancy.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__remove_redundancy.py
new file mode 100644
index 0000000000000000000000000000000000000000..d583bcb97049861ba842632419b54ade4cd0caab
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__remove_redundancy.py
@@ -0,0 +1,227 @@
+"""
+Unit test for Linear Programming via Simplex Algorithm.
+"""
+
+# TODO: add tests for:
+# https://github.com/scipy/scipy/issues/5400
+# https://github.com/scipy/scipy/issues/6690
+
+import numpy as np
+from numpy.testing import (
+ assert_,
+ assert_allclose,
+ assert_equal)
+
+from .test_linprog import magic_square
+from scipy.optimize._remove_redundancy import _remove_redundancy_svd
+from scipy.optimize._remove_redundancy import _remove_redundancy_pivot_dense
+from scipy.optimize._remove_redundancy import _remove_redundancy_pivot_sparse
+from scipy.optimize._remove_redundancy import _remove_redundancy_id
+
+from scipy.sparse import csc_array
+
+
+def redundancy_removed(A, B):
+ """Checks whether a matrix contains only independent rows of another"""
+ for rowA in A:
+ # `rowA in B` is not a reliable check
+ for rowB in B:
+ if np.all(rowA == rowB):
+ break
+ else:
+ return False
+ return A.shape[0] == np.linalg.matrix_rank(A) == np.linalg.matrix_rank(B)
+
+
+class RRCommonTests:
+ def setup_method(self):
+ self.rng = np.random.default_rng(2017)
+
+ def test_no_redundancy(self):
+ m, n = 10, 10
+ A0 = self.rng.random((m, n))
+ b0 = self.rng.random(m)
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_allclose(A0, A1)
+ assert_allclose(b0, b1)
+ assert_equal(status, 0)
+
+ def test_infeasible_zero_row(self):
+ A = np.eye(3)
+ A[1, :] = 0
+ b = self.rng.random(3)
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 2)
+
+ def test_remove_zero_row(self):
+ A = np.eye(3)
+ A[1, :] = 0
+ b = self.rng.random(3)
+ b[1] = 0
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_allclose(A1, A[[0, 2], :])
+ assert_allclose(b1, b[[0, 2]])
+
+ def test_infeasible_m_gt_n(self):
+ m, n = 20, 10
+ A0 = self.rng.random((m, n))
+ b0 = self.rng.random(m)
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 2)
+
+ def test_infeasible_m_eq_n(self):
+ m, n = 10, 10
+ A0 = self.rng.random((m, n))
+ b0 = self.rng.random(m)
+ A0[-1, :] = 2 * A0[-2, :]
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 2)
+
+ def test_infeasible_m_lt_n(self):
+ m, n = 9, 10
+ A0 = self.rng.random((m, n))
+ b0 = self.rng.random(m)
+ A0[-1, :] = np.arange(m - 1).dot(A0[:-1])
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 2)
+
+ def test_m_gt_n(self):
+ rng = np.random.default_rng(2032)
+ m, n = 20, 10
+ A0 = rng.random((m, n))
+ b0 = rng.random(m)
+ x = np.linalg.solve(A0[:n, :], b0[:n])
+ b0[n:] = A0[n:, :].dot(x)
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], n)
+ assert_equal(np.linalg.matrix_rank(A1), n)
+
+ def test_m_gt_n_rank_deficient(self):
+ m, n = 20, 10
+ A0 = np.zeros((m, n))
+ A0[:, 0] = 1
+ b0 = np.ones(m)
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 0)
+ assert_allclose(A1, A0[0:1, :])
+ assert_allclose(b1, b0[0])
+
+ def test_m_lt_n_rank_deficient(self):
+ m, n = 9, 10
+ A0 = self.rng.random((m, n))
+ b0 = self.rng.random(m)
+ A0[-1, :] = np.arange(m - 1).dot(A0[:-1])
+ b0[-1] = np.arange(m - 1).dot(b0[:-1])
+ A1, b1, status, message = self.rr(A0, b0)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], 8)
+ assert_equal(np.linalg.matrix_rank(A1), 8)
+
+ def test_dense1(self):
+ A = np.ones((6, 6))
+ A[0, :3] = 0
+ A[1, 3:] = 0
+ A[3:, ::2] = -1
+ A[3, :2] = 0
+ A[4, 2:] = 0
+ b = np.zeros(A.shape[0])
+
+ A1, b1, status, message = self.rr(A, b)
+ assert_(redundancy_removed(A1, A))
+ assert_equal(status, 0)
+
+ def test_dense2(self):
+ A = np.eye(6)
+ A[-2, -1] = 1
+ A[-1, :] = 1
+ b = np.zeros(A.shape[0])
+ A1, b1, status, message = self.rr(A, b)
+ assert_(redundancy_removed(A1, A))
+ assert_equal(status, 0)
+
+ def test_dense3(self):
+ A = np.eye(6)
+ A[-2, -1] = 1
+ A[-1, :] = 1
+ b = self.rng.random(A.shape[0])
+ b[-1] = np.sum(b[:-1])
+ A1, b1, status, message = self.rr(A, b)
+ assert_(redundancy_removed(A1, A))
+ assert_equal(status, 0)
+
+ def test_m_gt_n_sparse(self):
+ rng = np.random.default_rng(2013)
+ m, n = 20, 5
+ p = 0.1
+ A = rng.random((m, n))
+ A[rng.random((m, n)) > p] = 0
+ rank = np.linalg.matrix_rank(A)
+ b = np.zeros(A.shape[0])
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], rank)
+ assert_equal(np.linalg.matrix_rank(A1), rank)
+
+ def test_m_lt_n_sparse(self):
+ rng = np.random.default_rng(2017)
+ m, n = 20, 50
+ p = 0.05
+ A = rng.random((m, n))
+ A[rng.random((m, n)) > p] = 0
+ rank = np.linalg.matrix_rank(A)
+ b = np.zeros(A.shape[0])
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], rank)
+ assert_equal(np.linalg.matrix_rank(A1), rank)
+
+ def test_m_eq_n_sparse(self):
+ rng = np.random.default_rng(2017)
+ m, n = 100, 100
+ p = 0.01
+ A = rng.random((m, n))
+ A[rng.random((m, n)) > p] = 0
+ rank = np.linalg.matrix_rank(A)
+ b = np.zeros(A.shape[0])
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], rank)
+ assert_equal(np.linalg.matrix_rank(A1), rank)
+
+ def test_magic_square(self):
+ A, b, c, numbers, _ = magic_square(3)
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], 23)
+ assert_equal(np.linalg.matrix_rank(A1), 23)
+
+ def test_magic_square2(self):
+ A, b, c, numbers, _ = magic_square(4)
+ A1, b1, status, message = self.rr(A, b)
+ assert_equal(status, 0)
+ assert_equal(A1.shape[0], 39)
+ assert_equal(np.linalg.matrix_rank(A1), 39)
+
+
+class TestRRSVD(RRCommonTests):
+ def rr(self, A, b):
+ return _remove_redundancy_svd(A, b)
+
+
+class TestRRPivotDense(RRCommonTests):
+ def rr(self, A, b):
+ return _remove_redundancy_pivot_dense(A, b)
+
+
+class TestRRID(RRCommonTests):
+ def rr(self, A, b):
+ return _remove_redundancy_id(A, b)
+
+
+class TestRRPivotSparse(RRCommonTests):
+ def rr(self, A, b):
+ rr_res = _remove_redundancy_pivot_sparse(csc_array(A), b)
+ A1, b1, status, message = rr_res
+ return A1.toarray(), b1, status, message
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__root.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__root.py
new file mode 100644
index 0000000000000000000000000000000000000000..271123240cabbe93d976c8edfbd745ecf596b5a9
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__root.py
@@ -0,0 +1,123 @@
+"""
+Unit tests for optimization routines from _root.py.
+"""
+from numpy.testing import assert_, assert_equal
+import pytest
+from pytest import raises as assert_raises, warns as assert_warns
+import numpy as np
+
+from scipy.optimize import root
+
+
+class TestRoot:
+ def test_tol_parameter(self):
+ # Check that the minimize() tol= argument does something
+ def func(z):
+ x, y = z
+ return np.array([x**3 - 1, y**3 - 1])
+
+ def dfunc(z):
+ x, y = z
+ return np.array([[3*x**2, 0], [0, 3*y**2]])
+
+ for method in ['hybr', 'lm', 'broyden1', 'broyden2', 'anderson',
+ 'diagbroyden', 'krylov']:
+ if method in ('linearmixing', 'excitingmixing'):
+ # doesn't converge
+ continue
+
+ if method in ('hybr', 'lm'):
+ jac = dfunc
+ else:
+ jac = None
+
+ sol1 = root(func, [1.1,1.1], jac=jac, tol=1e-4, method=method)
+ sol2 = root(func, [1.1,1.1], jac=jac, tol=0.5, method=method)
+ msg = f"{method}: {func(sol1.x)} vs. {func(sol2.x)}"
+ assert_(sol1.success, msg)
+ assert_(sol2.success, msg)
+ assert_(abs(func(sol1.x)).max() < abs(func(sol2.x)).max(),
+ msg)
+
+ def test_tol_norm(self):
+
+ def norm(x):
+ return abs(x[0])
+
+ for method in ['excitingmixing',
+ 'diagbroyden',
+ 'linearmixing',
+ 'anderson',
+ 'broyden1',
+ 'broyden2',
+ 'krylov']:
+
+ root(np.zeros_like, np.zeros(2), method=method,
+ options={"tol_norm": norm})
+
+ def test_minimize_scalar_coerce_args_param(self):
+ # GitHub issue #3503
+ def func(z, f=1):
+ x, y = z
+ return np.array([x**3 - 1, y**3 - f])
+ root(func, [1.1, 1.1], args=1.5)
+
+ def test_f_size(self):
+ # gh8320
+ # check that decreasing the size of the returned array raises an error
+ # and doesn't segfault
+ class fun:
+ def __init__(self):
+ self.count = 0
+
+ def __call__(self, x):
+ self.count += 1
+
+ if not (self.count % 5):
+ ret = x[0] + 0.5 * (x[0] - x[1]) ** 3 - 1.0
+ else:
+ ret = ([x[0] + 0.5 * (x[0] - x[1]) ** 3 - 1.0,
+ 0.5 * (x[1] - x[0]) ** 3 + x[1]])
+
+ return ret
+
+ F = fun()
+ with assert_raises(ValueError):
+ root(F, [0.1, 0.0], method='lm')
+
+ def test_gh_10370(self):
+ # gh-10370 reported that passing both `args` and `jac` to `root` with
+ # `method='krylov'` caused a failure. Ensure that this is fixed whether
+ # the gradient is passed via `jac` or as a second output of `fun`.
+ def fun(x, ignored):
+ return [3*x[0] - 0.25*x[1]**2 + 10, 0.1*x[0]**2 + 5*x[1] - 2]
+
+ def grad(x, ignored):
+ return [[3, 0.5 * x[1]], [0.2 * x[0], 5]]
+
+ def fun_grad(x, ignored):
+ return fun(x, ignored), grad(x, ignored)
+
+ x0 = np.zeros(2)
+
+ ref = root(fun, x0, args=(1,), method='krylov')
+ message = 'Method krylov does not use the jacobian'
+ with assert_warns(RuntimeWarning, match=message):
+ res1 = root(fun, x0, args=(1,), method='krylov', jac=grad)
+ with assert_warns(RuntimeWarning, match=message):
+ res2 = root(fun_grad, x0, args=(1,), method='krylov', jac=True)
+
+ assert_equal(res1.x, ref.x)
+ assert_equal(res2.x, ref.x)
+ assert res1.success is res2.success is ref.success is True
+
+ @pytest.mark.parametrize("method", ["hybr", "lm", "broyden1", "broyden2",
+ "anderson", "linearmixing",
+ "diagbroyden", "excitingmixing",
+ "krylov", "df-sane"])
+ def test_method_in_result(self, method):
+ def func(x):
+ return x - 1
+
+ res = root(func, x0=[1], method=method)
+ assert res.method == method
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__shgo.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__shgo.py
new file mode 100644
index 0000000000000000000000000000000000000000..103075edc287ecc35e631150942e4a52b6423aab
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__shgo.py
@@ -0,0 +1,1228 @@
+import logging
+import sys
+import warnings
+
+import numpy as np
+import time
+from multiprocessing import Pool
+from numpy.testing import assert_allclose, IS_PYPY
+import pytest
+from pytest import raises as assert_raises, warns
+from scipy.optimize import (shgo, Bounds, minimize_scalar, minimize, rosen,
+ rosen_der, rosen_hess, NonlinearConstraint, OptimizeWarning)
+from scipy.optimize._constraints import new_constraint_to_old
+from scipy.optimize._shgo import SHGO
+from scipy.optimize.tests.test_minimize_constrained import MaratosTestArgs
+
+
+class StructTestFunction:
+ def __init__(self, bounds, expected_x, expected_fun=None,
+ expected_xl=None, expected_funl=None):
+ self.bounds = bounds
+ self.expected_x = expected_x
+ self.expected_fun = expected_fun
+ self.expected_xl = expected_xl
+ self.expected_funl = expected_funl
+
+
+def wrap_constraints(g):
+ cons = []
+ if g is not None:
+ if not isinstance(g, tuple | list):
+ g = (g,)
+ else:
+ pass
+ for g in g:
+ cons.append({'type': 'ineq',
+ 'fun': g})
+ cons = tuple(cons)
+ else:
+ cons = None
+ return cons
+
+
+class StructTest1(StructTestFunction):
+ def f(self, x):
+ return x[0] ** 2 + x[1] ** 2
+
+ def g(x):
+ return -(np.sum(x, axis=0) - 6.0)
+
+ cons = wrap_constraints(g)
+
+
+test1_1 = StructTest1(bounds=[(-1, 6), (-1, 6)],
+ expected_x=[0, 0])
+test1_2 = StructTest1(bounds=[(0, 1), (0, 1)],
+ expected_x=[0, 0])
+test1_3 = StructTest1(bounds=[(None, None), (None, None)],
+ expected_x=[0, 0])
+
+
+class StructTest2(StructTestFunction):
+ """
+ Scalar function with several minima to test all minimiser retrievals
+ """
+
+ def f(self, x):
+ return (x - 30) * np.sin(x)
+
+ def g(x):
+ return 58 - np.sum(x, axis=0)
+
+ cons = wrap_constraints(g)
+
+
+test2_1 = StructTest2(bounds=[(0, 60)],
+ expected_x=[1.53567906],
+ expected_fun=-28.44677132,
+ # Important: test that funl return is in the correct
+ # order
+ expected_xl=np.array([[1.53567906],
+ [55.01782167],
+ [7.80894889],
+ [48.74797493],
+ [14.07445705],
+ [42.4913859],
+ [20.31743841],
+ [36.28607535],
+ [26.43039605],
+ [30.76371366]]),
+
+ expected_funl=np.array([-28.44677132, -24.99785984,
+ -22.16855376, -18.72136195,
+ -15.89423937, -12.45154942,
+ -9.63133158, -6.20801301,
+ -3.43727232, -0.46353338])
+ )
+
+test2_2 = StructTest2(bounds=[(0, 4.5)],
+ expected_x=[1.53567906],
+ expected_fun=[-28.44677132],
+ expected_xl=np.array([[1.53567906]]),
+ expected_funl=np.array([-28.44677132])
+ )
+
+
+class StructTest3(StructTestFunction):
+ """
+ Hock and Schittkowski 18 problem (HS18). Hoch and Schittkowski (1981)
+ http://www.ai7.uni-bayreuth.de/test_problem_coll.pdf
+ Minimize: f = 0.01 * (x_1)**2 + (x_2)**2
+
+ Subject to: x_1 * x_2 - 25.0 >= 0,
+ (x_1)**2 + (x_2)**2 - 25.0 >= 0,
+ 2 <= x_1 <= 50,
+ 0 <= x_2 <= 50.
+
+ Approx. Answer:
+ f([(250)**0.5 , (2.5)**0.5]) = 5.0
+
+
+ """
+
+ # amended to test vectorisation of constraints
+ def f(self, x):
+ return 0.01 * (x[0]) ** 2 + (x[1]) ** 2
+
+ def g1(x):
+ return x[0] * x[1] - 25.0
+
+ def g2(x):
+ return x[0] ** 2 + x[1] ** 2 - 25.0
+
+ # g = (g1, g2)
+ # cons = wrap_constraints(g)
+
+ def g(x):
+ return x[0] * x[1] - 25.0, x[0] ** 2 + x[1] ** 2 - 25.0
+
+ # this checks that shgo can be sent new-style constraints
+ __nlc = NonlinearConstraint(g, 0, np.inf)
+ cons = (__nlc,)
+
+test3_1 = StructTest3(bounds=[(2, 50), (0, 50)],
+ expected_x=[250 ** 0.5, 2.5 ** 0.5],
+ expected_fun=5.0
+ )
+
+
+class StructTest4(StructTestFunction):
+ """
+ Hock and Schittkowski 11 problem (HS11). Hoch and Schittkowski (1981)
+
+ NOTE: Did not find in original reference to HS collection, refer to
+ Henderson (2015) problem 7 instead. 02.03.2016
+ """
+
+ def f(self, x):
+ return ((x[0] - 10) ** 2 + 5 * (x[1] - 12) ** 2 + x[2] ** 4
+ + 3 * (x[3] - 11) ** 2 + 10 * x[4] ** 6 + 7 * x[5] ** 2 + x[
+ 6] ** 4
+ - 4 * x[5] * x[6] - 10 * x[5] - 8 * x[6]
+ )
+
+ def g1(x):
+ return -(2 * x[0] ** 2 + 3 * x[1] ** 4 + x[2] + 4 * x[3] ** 2
+ + 5 * x[4] - 127)
+
+ def g2(x):
+ return -(7 * x[0] + 3 * x[1] + 10 * x[2] ** 2 + x[3] - x[4] - 282.0)
+
+ def g3(x):
+ return -(23 * x[0] + x[1] ** 2 + 6 * x[5] ** 2 - 8 * x[6] - 196)
+
+ def g4(x):
+ return -(4 * x[0] ** 2 + x[1] ** 2 - 3 * x[0] * x[1] + 2 * x[2] ** 2
+ + 5 * x[5] - 11 * x[6])
+
+ g = (g1, g2, g3, g4)
+
+ cons = wrap_constraints(g)
+
+
+test4_1 = StructTest4(bounds=[(-10, 10), ] * 7,
+ expected_x=[2.330499, 1.951372, -0.4775414,
+ 4.365726, -0.6244870, 1.038131, 1.594227],
+ expected_fun=680.6300573
+ )
+
+
+class StructTest5(StructTestFunction):
+ def f(self, x):
+ return (
+ -(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0]/2.0 + (x[1] + 47.0))))
+ - x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0))))
+ )
+
+ g = None
+ cons = wrap_constraints(g)
+
+
+test5_1 = StructTest5(bounds=[(-512, 512), (-512, 512)],
+ expected_fun=[-959.64066272085051],
+ expected_x=[512., 404.23180542])
+
+
+class StructTestLJ(StructTestFunction):
+ """
+ LennardJones objective function. Used to test symmetry constraints
+ settings.
+ """
+
+ def f(self, x, *args):
+ print(f'x = {x}')
+ self.N = args[0]
+ k = int(self.N / 3)
+ s = 0.0
+
+ for i in range(k - 1):
+ for j in range(i + 1, k):
+ a = 3 * i
+ b = 3 * j
+ xd = x[a] - x[b]
+ yd = x[a + 1] - x[b + 1]
+ zd = x[a + 2] - x[b + 2]
+ ed = xd * xd + yd * yd + zd * zd
+ ud = ed * ed * ed
+ if ed > 0.0:
+ s += (1.0 / ud - 2.0) / ud
+
+ return s
+
+ g = None
+ cons = wrap_constraints(g)
+
+
+N = 6
+boundsLJ = list(zip([-4.0] * 6, [4.0] * 6))
+
+testLJ = StructTestLJ(bounds=boundsLJ,
+ expected_fun=[-1.0],
+ expected_x=None,
+ # expected_x=[-2.71247337e-08,
+ # -2.71247337e-08,
+ # -2.50000222e+00,
+ # -2.71247337e-08,
+ # -2.71247337e-08,
+ # -1.50000222e+00]
+ )
+
+
+class StructTestS(StructTestFunction):
+ def f(self, x):
+ return ((x[0] - 0.5) ** 2 + (x[1] - 0.5) ** 2
+ + (x[2] - 0.5) ** 2 + (x[3] - 0.5) ** 2)
+
+ g = None
+ cons = wrap_constraints(g)
+
+
+test_s = StructTestS(bounds=[(0, 2.0), ] * 4,
+ expected_fun=0.0,
+ expected_x=np.ones(4) - 0.5
+ )
+
+
+class StructTestTable(StructTestFunction):
+ def f(self, x):
+ if x[0] == 3.0 and x[1] == 3.0:
+ return 50
+ else:
+ return 100
+
+ g = None
+ cons = wrap_constraints(g)
+
+
+test_table = StructTestTable(bounds=[(-10, 10), (-10, 10)],
+ expected_fun=[50],
+ expected_x=[3.0, 3.0])
+
+
+class StructTestInfeasible(StructTestFunction):
+ """
+ Test function with no feasible domain.
+ """
+
+ def f(self, x, *args):
+ return x[0] ** 2 + x[1] ** 2
+
+ def g1(x):
+ return x[0] + x[1] - 1
+
+ def g2(x):
+ return -(x[0] + x[1] - 1)
+
+ def g3(x):
+ return -x[0] + x[1] - 1
+
+ def g4(x):
+ return -(-x[0] + x[1] - 1)
+
+ g = (g1, g2, g3, g4)
+ cons = wrap_constraints(g)
+
+
+test_infeasible = StructTestInfeasible(bounds=[(2, 50), (-1, 1)],
+ expected_fun=None,
+ expected_x=None
+ )
+
+
+@pytest.mark.skip("Not a test")
+def run_test(test, args=(), test_atol=1e-5, n=100, iters=None,
+ callback=None, minimizer_kwargs=None, options=None,
+ sampling_method='sobol', workers=1):
+ res = shgo(test.f, test.bounds, args=args, constraints=test.cons,
+ n=n, iters=iters, callback=callback,
+ minimizer_kwargs=minimizer_kwargs, options=options,
+ sampling_method=sampling_method, workers=workers)
+
+ print(f'res = {res}')
+ logging.info(f'res = {res}')
+ if test.expected_x is not None:
+ np.testing.assert_allclose(res.x, test.expected_x,
+ rtol=test_atol,
+ atol=test_atol)
+
+ # (Optional tests)
+ if test.expected_fun is not None:
+ np.testing.assert_allclose(res.fun,
+ test.expected_fun,
+ atol=test_atol)
+
+ if test.expected_xl is not None:
+ np.testing.assert_allclose(res.xl,
+ test.expected_xl,
+ atol=test_atol)
+
+ if test.expected_funl is not None:
+ np.testing.assert_allclose(res.funl,
+ test.expected_funl,
+ atol=test_atol)
+ return
+
+
+# Base test functions:
+class TestShgoSobolTestFunctions:
+ """
+ Global optimisation tests with Sobol sampling:
+ """
+
+ # Sobol algorithm
+ def test_f1_1_sobol(self):
+ """Multivariate test function 1:
+ x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]"""
+ run_test(test1_1)
+
+ def test_f1_2_sobol(self):
+ """Multivariate test function 1:
+ x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]"""
+ run_test(test1_2)
+
+ def test_f1_3_sobol(self):
+ """Multivariate test function 1:
+ x[0]**2 + x[1]**2 with bounds=[(None, None),(None, None)]"""
+ options = {'disp': True}
+ run_test(test1_3, options=options)
+
+ def test_f2_1_sobol(self):
+ """Univariate test function on
+ f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]"""
+ run_test(test2_1)
+
+ def test_f2_2_sobol(self):
+ """Univariate test function on
+ f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]"""
+ run_test(test2_2)
+
+ def test_f3_sobol(self):
+ """NLP: Hock and Schittkowski problem 18"""
+ run_test(test3_1)
+
+ @pytest.mark.slow
+ def test_f4_sobol(self):
+ """NLP: (High dimensional) Hock and Schittkowski 11 problem (HS11)"""
+ options = {'infty_constraints': False}
+ # run_test(test4_1, n=990, options=options)
+ run_test(test4_1, n=990 * 2, options=options)
+
+ def test_f5_1_sobol(self):
+ """NLP: Eggholder, multimodal"""
+ # run_test(test5_1, n=30)
+ run_test(test5_1, n=60)
+
+ def test_f5_2_sobol(self):
+ """NLP: Eggholder, multimodal"""
+ # run_test(test5_1, n=60, iters=5)
+ run_test(test5_1, n=60, iters=5)
+
+ # def test_t911(self):
+ # """1D tabletop function"""
+ # run_test(test11_1)
+
+
+class TestShgoSimplicialTestFunctions:
+ """
+ Global optimisation tests with Simplicial sampling:
+ """
+
+ def test_f1_1_simplicial(self):
+ """Multivariate test function 1:
+ x[0]**2 + x[1]**2 with bounds=[(-1, 6), (-1, 6)]"""
+ run_test(test1_1, n=1, sampling_method='simplicial')
+
+ def test_f1_2_simplicial(self):
+ """Multivariate test function 1:
+ x[0]**2 + x[1]**2 with bounds=[(0, 1), (0, 1)]"""
+ run_test(test1_2, n=1, sampling_method='simplicial')
+
+ def test_f1_3_simplicial(self):
+ """Multivariate test function 1: x[0]**2 + x[1]**2
+ with bounds=[(None, None),(None, None)]"""
+ run_test(test1_3, n=5, sampling_method='simplicial')
+
+ def test_f2_1_simplicial(self):
+ """Univariate test function on
+ f(x) = (x - 30) * sin(x) with bounds=[(0, 60)]"""
+ options = {'minimize_every_iter': False}
+ run_test(test2_1, n=200, iters=7, options=options,
+ sampling_method='simplicial')
+
+ def test_f2_2_simplicial(self):
+ """Univariate test function on
+ f(x) = (x - 30) * sin(x) bounds=[(0, 4.5)]"""
+ run_test(test2_2, n=1, sampling_method='simplicial')
+
+ def test_f3_simplicial(self):
+ """NLP: Hock and Schittkowski problem 18"""
+ run_test(test3_1, n=1, sampling_method='simplicial')
+
+ @pytest.mark.slow
+ def test_f4_simplicial(self):
+ """NLP: (High dimensional) Hock and Schittkowski 11 problem (HS11)"""
+ run_test(test4_1, n=1, sampling_method='simplicial')
+
+ def test_lj_symmetry_old(self):
+ """LJ: Symmetry-constrained test function"""
+ options = {'symmetry': True,
+ 'disp': True}
+ args = (6,) # Number of atoms
+ run_test(testLJ, args=args, n=300,
+ options=options, iters=1,
+ sampling_method='simplicial')
+
+ def test_f5_1_lj_symmetry(self):
+ """LJ: Symmetry constrained test function"""
+ options = {'symmetry': [0, ] * 6,
+ 'disp': True}
+ args = (6,) # No. of atoms
+
+ run_test(testLJ, args=args, n=300,
+ options=options, iters=1,
+ sampling_method='simplicial')
+
+ def test_f5_2_cons_symmetry(self):
+ """Symmetry constrained test function"""
+ options = {'symmetry': [0, 0],
+ 'disp': True}
+
+ run_test(test1_1, n=200,
+ options=options, iters=1,
+ sampling_method='simplicial')
+
+ @pytest.mark.fail_slow(10)
+ def test_f5_3_cons_symmetry(self):
+ """Asymmetrically constrained test function"""
+ options = {'symmetry': [0, 0, 0, 3],
+ 'disp': True}
+
+ run_test(test_s, n=10000,
+ options=options,
+ iters=1,
+ sampling_method='simplicial')
+
+ @pytest.mark.skip("Not a test")
+ def test_f0_min_variance(self):
+ """Return a minimum on a perfectly symmetric problem, based on
+ gh10429"""
+ avg = 0.5 # Given average value of x
+ cons = {'type': 'eq', 'fun': lambda x: np.mean(x) - avg}
+
+ # Minimize the variance of x under the given constraint
+ res = shgo(np.var, bounds=6 * [(0, 1)], constraints=cons)
+ assert res.success
+ assert_allclose(res.fun, 0, atol=1e-15)
+ assert_allclose(res.x, 0.5)
+
+ @pytest.mark.skip("Not a test")
+ def test_f0_min_variance_1D(self):
+ """Return a minimum on a perfectly symmetric 1D problem, based on
+ gh10538"""
+
+ def fun(x):
+ return x * (x - 1.0) * (x - 0.5)
+
+ bounds = [(0, 1)]
+ res = shgo(fun, bounds=bounds)
+ ref = minimize_scalar(fun, bounds=bounds[0])
+ assert res.success
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x, rtol=1e-6)
+
+# Argument test functions
+class TestShgoArguments:
+ def test_1_1_simpl_iter(self):
+ """Iterative simplicial sampling on TestFunction 1 (multivariate)"""
+ run_test(test1_2, n=None, iters=2, sampling_method='simplicial')
+
+ def test_1_2_simpl_iter(self):
+ """Iterative simplicial on TestFunction 2 (univariate)"""
+ options = {'minimize_every_iter': False}
+ run_test(test2_1, n=None, iters=9, options=options,
+ sampling_method='simplicial')
+
+ def test_2_1_sobol_iter(self):
+ """Iterative Sobol sampling on TestFunction 1 (multivariate)"""
+ run_test(test1_2, n=None, iters=1, sampling_method='sobol')
+
+ def test_2_2_sobol_iter(self):
+ """Iterative Sobol sampling on TestFunction 2 (univariate)"""
+ res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons,
+ n=None, iters=1, sampling_method='sobol')
+
+ np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5)
+ np.testing.assert_allclose(res.fun, test2_1.expected_fun, atol=1e-5)
+
+ def test_3_1_disp_simplicial(self):
+ """Iterative sampling on TestFunction 1 and 2 (multi and univariate)
+ """
+
+ def callback_func(x):
+ print("Local minimization callback test")
+
+ for test in [test1_1, test2_1]:
+ shgo(test.f, test.bounds, iters=1,
+ sampling_method='simplicial',
+ callback=callback_func, options={'disp': True})
+ shgo(test.f, test.bounds, n=1, sampling_method='simplicial',
+ callback=callback_func, options={'disp': True})
+
+ def test_3_2_disp_sobol(self):
+ """Iterative sampling on TestFunction 1 and 2 (multi and univariate)"""
+
+ def callback_func(x):
+ print("Local minimization callback test")
+
+ for test in [test1_1, test2_1]:
+ shgo(test.f, test.bounds, iters=1, sampling_method='sobol',
+ callback=callback_func, options={'disp': True})
+
+ shgo(test.f, test.bounds, n=1, sampling_method='simplicial',
+ callback=callback_func, options={'disp': True})
+
+ def test_args_gh14589(self):
+ """Using `args` used to cause `shgo` to fail; see #14589, #15986,
+ #16506"""
+ res = shgo(func=lambda x, y, z: x * z + y, bounds=[(0, 3)], args=(1, 2)
+ )
+ ref = shgo(func=lambda x: 2 * x + 1, bounds=[(0, 3)])
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x)
+
+ def test_args_gh23517(self):
+ """
+ Checks that using `args` for func, jac and hess works
+ """
+ obj = MaratosTestArgs("a", 234)
+ obj.bounds = Bounds([-5, -5], [5, 5])
+ res2 = minimize(
+ obj.fun,
+ [4.0, 4.0],
+ constraints=obj.constr,
+ bounds=obj.bounds,
+ method='trust-constr',
+ args=("a", 234),
+ jac=obj.grad
+ )
+ assert_allclose(res2.x, obj.x_opt, atol=1e-6)
+
+ obj = MaratosTestArgs("a", 234)
+ obj.bounds = Bounds([-10., -10.], [10., 10.])
+ with warnings.catch_warnings():
+ # warnings are from initialization of NonlinearConstraint and
+ # poor initialization of the constraint by shgo
+ warnings.simplefilter(
+ "ignore",
+ (OptimizeWarning, RuntimeWarning)
+ )
+ res = shgo(
+ func=obj.fun,
+ bounds=obj.bounds,
+ args=("a", 234),
+ minimizer_kwargs={
+ "method": 'trust-constr',
+ "constraints": obj.constr,
+ "bounds": obj.bounds,
+ "jac": obj.grad,
+ "args": ("a", 234),
+ },
+ constraints=obj.constr,
+ sampling_method='sobol',
+ )
+ assert_allclose(res.x, obj.x_opt, atol=1e-6)
+
+ res = shgo(
+ func=obj.fun,
+ bounds=obj.bounds,
+ args=("a", 234),
+ minimizer_kwargs={
+ "method": 'trust-constr',
+ "constraints": obj.constr,
+ "bounds": obj.bounds,
+ "jac": obj.grad,
+ "hess": obj.hess,
+ },
+ constraints=obj.constr,
+ sampling_method='sobol',
+ )
+ assert_allclose(res.x, obj.x_opt, atol=1e-6)
+
+ @pytest.mark.slow
+ def test_4_1_known_f_min(self):
+ """Test known function minima stopping criteria"""
+ # Specify known function value
+ options = {'f_min': test4_1.expected_fun,
+ 'f_tol': 1e-6,
+ 'minimize_every_iter': True}
+ # TODO: Make default n higher for faster tests
+ run_test(test4_1, n=None, test_atol=1e-5, options=options,
+ sampling_method='simplicial')
+
+ @pytest.mark.slow
+ def test_4_2_known_f_min(self):
+ """Test Global mode limiting local evaluations"""
+ options = { # Specify known function value
+ 'f_min': test4_1.expected_fun,
+ 'f_tol': 1e-6,
+ # Specify number of local iterations to perform
+ 'minimize_every_iter': True,
+ 'local_iter': 1}
+
+ run_test(test4_1, n=None, test_atol=1e-5, options=options,
+ sampling_method='simplicial')
+
+ def test_4_4_known_f_min(self):
+ """Test Global mode limiting local evaluations for 1D funcs"""
+ options = { # Specify known function value
+ 'f_min': test2_1.expected_fun,
+ 'f_tol': 1e-6,
+ # Specify number of local iterations to perform+
+ 'minimize_every_iter': True,
+ 'local_iter': 1,
+ 'infty_constraints': False}
+
+ res = shgo(test2_1.f, test2_1.bounds, constraints=test2_1.cons,
+ n=None, iters=None, options=options,
+ sampling_method='sobol')
+ np.testing.assert_allclose(res.x, test2_1.expected_x, rtol=1e-5, atol=1e-5)
+
+ def test_5_1_simplicial_argless(self):
+ """Test Default simplicial sampling settings on TestFunction 1"""
+ res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons)
+ np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5)
+
+ def test_5_2_sobol_argless(self):
+ """Test Default sobol sampling settings on TestFunction 1"""
+ res = shgo(test1_1.f, test1_1.bounds, constraints=test1_1.cons,
+ sampling_method='sobol')
+ np.testing.assert_allclose(res.x, test1_1.expected_x, rtol=1e-5, atol=1e-5)
+
+ def test_6_1_simplicial_max_iter(self):
+ """Test that maximum iteration option works on TestFunction 3"""
+ options = {'max_iter': 2}
+ res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons,
+ options=options, sampling_method='simplicial')
+ np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5)
+ np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5)
+
+ def test_6_2_simplicial_min_iter(self):
+ """Test that maximum iteration option works on TestFunction 3"""
+ options = {'min_iter': 2}
+ res = shgo(test3_1.f, test3_1.bounds, constraints=test3_1.cons,
+ options=options, sampling_method='simplicial')
+ np.testing.assert_allclose(res.x, test3_1.expected_x, rtol=1e-5, atol=1e-5)
+ np.testing.assert_allclose(res.fun, test3_1.expected_fun, atol=1e-5)
+
+ def test_7_1_minkwargs(self):
+ """Test the minimizer_kwargs arguments for solvers with constraints"""
+ # Test solvers
+ for solver in ['COBYLA', 'COBYQA', 'SLSQP']:
+ # Note that passing global constraints to SLSQP is tested in other
+ # unittests which run test4_1 normally
+ minimizer_kwargs = {'method': solver,
+ 'constraints': test3_1.cons}
+ run_test(test3_1, n=100, test_atol=1e-3,
+ minimizer_kwargs=minimizer_kwargs,
+ sampling_method='sobol')
+
+ def test_7_2_minkwargs(self):
+ """Test the minimizer_kwargs default inits"""
+ minimizer_kwargs = {'ftol': 1e-5}
+ options = {'disp': True} # For coverage purposes
+ SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0],
+ minimizer_kwargs=minimizer_kwargs, options=options)
+
+ def test_7_3_minkwargs(self):
+ """Test minimizer_kwargs arguments for solvers without constraints"""
+ for solver in ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'Newton-CG',
+ 'L-BFGS-B', 'TNC', 'dogleg', 'trust-ncg', 'trust-exact',
+ 'trust-krylov']:
+ def jac(x):
+ return np.array([2 * x[0], 2 * x[1]]).T
+
+ def hess(x):
+ return np.array([[2, 0], [0, 2]])
+
+ minimizer_kwargs = {'method': solver,
+ 'jac': jac,
+ 'hess': hess}
+ logging.info(f"Solver = {solver}")
+ logging.info("=" * 100)
+ run_test(test1_1, n=100, test_atol=1e-3,
+ minimizer_kwargs=minimizer_kwargs,
+ sampling_method='sobol')
+
+ def test_8_homology_group_diff(self):
+ options = {'minhgrd': 1,
+ 'minimize_every_iter': True}
+
+ run_test(test1_1, n=None, iters=None, options=options,
+ sampling_method='simplicial')
+
+ def test_9_cons_g(self):
+ """Test single function constraint passing"""
+ SHGO(test3_1.f, test3_1.bounds, constraints=test3_1.cons[0])
+
+ @pytest.mark.xfail(IS_PYPY and sys.platform == 'win32',
+ reason="Failing and fix in PyPy not planned (see gh-18632)")
+ def test_10_finite_time(self):
+ """Test single function constraint passing"""
+ options = {'maxtime': 1e-15}
+
+ def f(x):
+ time.sleep(1e-14)
+ return 0.0
+
+ res = shgo(f, test1_1.bounds, iters=5, options=options)
+ # Assert that only 1 rather than 5 requested iterations ran:
+ assert res.nit == 1
+
+ def test_11_f_min_0(self):
+ """Test to cover the case where f_lowest == 0"""
+ options = {'f_min': 0.0,
+ 'disp': True}
+ res = shgo(test1_2.f, test1_2.bounds, n=10, iters=None,
+ options=options, sampling_method='sobol')
+ np.testing.assert_equal(0, res.x[0])
+ np.testing.assert_equal(0, res.x[1])
+
+ # @nottest
+ @pytest.mark.skip(reason="no way of currently testing this")
+ def test_12_sobol_inf_cons(self):
+ """Test to cover the case where f_lowest == 0"""
+ # TODO: This test doesn't cover anything new, it is unknown what the
+ # original test was intended for as it was never complete. Delete or
+ # replace in the future.
+ options = {'maxtime': 1e-15,
+ 'f_min': 0.0}
+ res = shgo(test1_2.f, test1_2.bounds, n=1, iters=None,
+ options=options, sampling_method='sobol')
+ np.testing.assert_equal(0.0, res.fun)
+
+ def test_13_high_sobol(self):
+ """Test init of high-dimensional sobol sequences"""
+
+ def f(x):
+ return 0
+
+ bounds = [(None, None), ] * 41
+ SHGOc = SHGO(f, bounds, sampling_method='sobol')
+ # SHGOc.sobol_points(2, 50)
+ SHGOc.sampling_function(2, 50)
+
+ def test_14_local_iter(self):
+ """Test limited local iterations for a pseudo-global mode"""
+ options = {'local_iter': 4}
+ run_test(test5_1, n=60, options=options)
+
+ def test_15_min_every_iter(self):
+ """Test minimize every iter options and cover function cache"""
+ options = {'minimize_every_iter': True}
+ run_test(test1_1, n=1, iters=7, options=options,
+ sampling_method='sobol')
+
+ def test_16_disp_bounds_minimizer(self, capsys):
+ """Test disp=True with minimizers that do not support bounds """
+ options = {'disp': True}
+ minimizer_kwargs = {'method': 'nelder-mead'}
+ run_test(test1_2, sampling_method='simplicial',
+ options=options, minimizer_kwargs=minimizer_kwargs)
+
+ def test_17_custom_sampling(self):
+ """Test the functionality to add custom sampling methods to shgo"""
+
+ def sample(n, d):
+ return np.random.uniform(size=(n, d))
+
+ run_test(test1_1, n=30, sampling_method=sample)
+
+ def test_18_bounds_class(self):
+ # test that new and old bounds yield same result
+ def f(x):
+ return np.square(x).sum()
+
+ lb = [-6., 1., -5.]
+ ub = [-1., 3., 5.]
+ bounds_old = list(zip(lb, ub))
+ bounds_new = Bounds(lb, ub)
+
+ res_old_bounds = shgo(f, bounds_old)
+ res_new_bounds = shgo(f, bounds_new)
+
+ assert res_new_bounds.nfev == res_old_bounds.nfev
+ assert res_new_bounds.message == res_old_bounds.message
+ assert res_new_bounds.success == res_old_bounds.success
+ x_opt = np.array([-1., 1., 0.])
+ np.testing.assert_allclose(res_new_bounds.x, x_opt)
+ np.testing.assert_allclose(res_new_bounds.x, res_old_bounds.x)
+
+ @pytest.mark.fail_slow(10)
+ def test_19_parallelization(self):
+ """Test the functionality to add custom sampling methods to shgo"""
+
+ with Pool(2) as p:
+ run_test(test1_1, n=30, workers=p.map) # Constrained
+ run_test(test1_1, n=30, workers=map) # Constrained
+ with Pool(2) as p:
+ run_test(test_s, n=30, workers=p.map) # Unconstrained
+ run_test(test_s, n=30, workers=map) # Unconstrained
+
+ def test_20_constrained_args(self):
+ """Test that constraints can be passed to arguments"""
+
+ def eggholder(x):
+ return (
+ -(x[1] + 47.0)*np.sin(np.sqrt(abs(x[0] / 2.0 + (x[1] + 47.0))))
+ - x[0]*np.sin(np.sqrt(abs(x[0] - (x[1] + 47.0))))
+ )
+
+ def f(x): # (cattle-feed)
+ return 24.55 * x[0] + 26.75 * x[1] + 39 * x[2] + 40.50 * x[3]
+
+ bounds = [(0, 1.0), ] * 4
+
+ def g1_modified(x, i):
+ return i * 2.3 * x[0] + i * 5.6 * x[1] + 11.1 * x[2] + 1.3 * x[
+ 3] - 5 # >=0
+
+ def g2(x):
+ return (
+ 12*x[0] + 11.9*x[1] + 41.8*x[2] + 52.1*x[3] - 21
+ - 1.645*np.sqrt(
+ 0.28*x[0]**2 + 0.19*x[1]**2 + 20.5*x[2]**2 + 0.62*x[3]**2
+ )
+ ) # >=0
+
+ def h1(x):
+ return x[0] + x[1] + x[2] + x[3] - 1 # == 0
+
+ cons = ({'type': 'ineq', 'fun': g1_modified, "args": (0,)},
+ {'type': 'ineq', 'fun': g2},
+ {'type': 'eq', 'fun': h1})
+
+ shgo(f, bounds, n=300, iters=1, constraints=cons)
+ # using constrain with arguments AND sampling method sobol
+ shgo(f, bounds, n=300, iters=1, constraints=cons,
+ sampling_method='sobol')
+
+ def test_21_1_jac_true(self):
+ """Test that shgo can handle objective functions that return the
+ gradient alongside the objective value. Fixes gh-13547"""
+ # previous
+ def func(x):
+ return np.sum(np.power(x, 2)), 2 * x
+
+ min_kwds = {"method": "SLSQP", "jac": True}
+ opt_kwds = {"jac": True}
+ shgo(
+ func,
+ bounds=[[-1, 1], [1, 2]],
+ n=100, iters=5,
+ sampling_method="sobol",
+ minimizer_kwargs=min_kwds,
+ options=opt_kwds
+ )
+ assert min_kwds['jac'] is True
+ assert "jac" in opt_kwds
+
+ # new
+ def func(x):
+ return np.sum(x ** 2), 2 * x
+
+ bounds = [[-1, 1], [1, 2], [-1, 1], [1, 2], [0, 3]]
+
+ res = shgo(func, bounds=bounds, sampling_method="sobol",
+ minimizer_kwargs={'method': 'SLSQP', 'jac': True})
+ ref = minimize(func, x0=[1, 1, 1, 1, 1], bounds=bounds,
+ jac=True)
+ assert res.success
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x, atol=1e-15)
+
+ # Testing the passing of jac via options dict
+ res = shgo(func, bounds=bounds, sampling_method="sobol",
+ minimizer_kwargs={'method': 'SLSQP'},
+ options={'jac': True})
+ assert res.success
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x, atol=1e-15)
+
+ @pytest.mark.parametrize('derivative', ['jac', 'hess', 'hessp'])
+ def test_21_2_derivative_options(self, derivative):
+ """shgo used to raise an error when passing `options` with 'jac'
+ # see gh-12963. check that this is resolved
+ """
+
+ def objective(x):
+ return 3 * x[0] * x[0] + 2 * x[0] + 5
+
+ def gradient(x):
+ return 6 * x[0] + 2
+
+ def hess(x):
+ return 6
+
+ def hessp(x, p):
+ return 6 * p
+
+ derivative_funcs = {'jac': gradient, 'hess': hess, 'hessp': hessp}
+ options = {derivative: derivative_funcs[derivative]}
+ minimizer_kwargs = {'method': 'trust-constr'}
+
+ bounds = [(-100, 100)]
+ res = shgo(objective, bounds, minimizer_kwargs=minimizer_kwargs,
+ options=options)
+ ref = minimize(objective, x0=[0], bounds=bounds, **minimizer_kwargs,
+ **options)
+
+ assert res.success
+ np.testing.assert_allclose(res.fun, ref.fun)
+ np.testing.assert_allclose(res.x, ref.x)
+
+ def test_21_3_hess_options_rosen(self):
+ """Ensure the Hessian gets passed correctly to the local minimizer
+ routine. Previous report gh-14533.
+ """
+ bounds = [(0, 1.6), (0, 1.6), (0, 1.4), (0, 1.4), (0, 1.4)]
+ options = {'jac': rosen_der, 'hess': rosen_hess}
+ minimizer_kwargs = {'method': 'Newton-CG'}
+ res = shgo(rosen, bounds, minimizer_kwargs=minimizer_kwargs,
+ options=options)
+ ref = minimize(rosen, np.zeros(5), method='Newton-CG',
+ **options)
+ assert res.success
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x, atol=1e-15)
+
+ def test_21_arg_tuple_sobol(self):
+ """shgo used to raise an error when passing `args` with Sobol sampling
+ # see gh-12114. check that this is resolved"""
+
+ def fun(x, k):
+ return x[0] ** k
+
+ constraints = ({'type': 'ineq', 'fun': lambda x: x[0] - 1})
+
+ bounds = [(0, 10)]
+ res = shgo(fun, bounds, args=(1,), constraints=constraints,
+ sampling_method='sobol')
+ ref = minimize(fun, np.zeros(1), bounds=bounds, args=(1,),
+ constraints=constraints)
+ assert res.success
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x)
+
+
+# Failure test functions
+class TestShgoFailures:
+ def test_1_maxiter(self):
+ """Test failure on insufficient iterations"""
+ options = {'maxiter': 2}
+ res = shgo(test4_1.f, test4_1.bounds, n=2, iters=None,
+ options=options, sampling_method='sobol')
+
+ np.testing.assert_equal(False, res.success)
+ # np.testing.assert_equal(4, res.nfev)
+ np.testing.assert_equal(4, res.tnev)
+
+ def test_2_sampling(self):
+ """Rejection of unknown sampling method"""
+ assert_raises(ValueError, shgo, test1_1.f, test1_1.bounds,
+ sampling_method='not_Sobol')
+
+ def test_3_1_no_min_pool_sobol(self):
+ """Check that the routine stops when no minimiser is found
+ after maximum specified function evaluations"""
+ options = {'maxfev': 10,
+ # 'maxev': 10,
+ 'disp': True}
+ res = shgo(test_table.f, test_table.bounds, n=3, options=options,
+ sampling_method='sobol')
+ np.testing.assert_equal(False, res.success)
+ # np.testing.assert_equal(9, res.nfev)
+ np.testing.assert_equal(12, res.nfev)
+
+ def test_3_2_no_min_pool_simplicial(self):
+ """Check that the routine stops when no minimiser is found
+ after maximum specified sampling evaluations"""
+ options = {'maxev': 10,
+ 'disp': True}
+ res = shgo(test_table.f, test_table.bounds, n=3, options=options,
+ sampling_method='simplicial')
+ np.testing.assert_equal(False, res.success)
+
+ def test_4_1_bound_err(self):
+ """Specified bounds ub > lb"""
+ bounds = [(6, 3), (3, 5)]
+ assert_raises(ValueError, shgo, test1_1.f, bounds)
+
+ def test_4_2_bound_err(self):
+ """Specified bounds are of the form (lb, ub)"""
+ bounds = [(3, 5, 5), (3, 5)]
+ assert_raises(ValueError, shgo, test1_1.f, bounds)
+
+ def test_5_1_1_infeasible_sobol(self):
+ """Ensures the algorithm terminates on infeasible problems
+ after maxev is exceeded. Use infty constraints option"""
+ options = {'maxev': 100,
+ 'disp': True}
+
+ res = shgo(test_infeasible.f, test_infeasible.bounds,
+ constraints=test_infeasible.cons, n=100, options=options,
+ sampling_method='sobol')
+
+ np.testing.assert_equal(False, res.success)
+
+ def test_5_1_2_infeasible_sobol(self):
+ """Ensures the algorithm terminates on infeasible problems
+ after maxev is exceeded. Do not use infty constraints option"""
+ options = {'maxev': 100,
+ 'disp': True,
+ 'infty_constraints': False}
+
+ res = shgo(test_infeasible.f, test_infeasible.bounds,
+ constraints=test_infeasible.cons, n=100, options=options,
+ sampling_method='sobol')
+
+ np.testing.assert_equal(False, res.success)
+
+ def test_5_2_infeasible_simplicial(self):
+ """Ensures the algorithm terminates on infeasible problems
+ after maxev is exceeded."""
+ options = {'maxev': 1000,
+ 'disp': False}
+
+ res = shgo(test_infeasible.f, test_infeasible.bounds,
+ constraints=test_infeasible.cons, n=100, options=options,
+ sampling_method='simplicial')
+
+ np.testing.assert_equal(False, res.success)
+
+ def test_6_1_lower_known_f_min(self):
+ """Test Global mode limiting local evaluations with f* too high"""
+ options = { # Specify known function value
+ 'f_min': test2_1.expected_fun + 2.0,
+ 'f_tol': 1e-6,
+ # Specify number of local iterations to perform+
+ 'minimize_every_iter': True,
+ 'local_iter': 1,
+ 'infty_constraints': False}
+ args = (test2_1.f, test2_1.bounds)
+ kwargs = {'constraints': test2_1.cons,
+ 'n': None,
+ 'iters': None,
+ 'options': options,
+ 'sampling_method': 'sobol'
+ }
+ warns(UserWarning, shgo, *args, **kwargs)
+
+ def test(self):
+ from scipy.optimize import rosen, shgo
+ bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)]
+
+ def fun(x):
+ fun.nfev += 1
+ return rosen(x)
+
+ fun.nfev = 0
+
+ result = shgo(fun, bounds)
+ print(result.x, result.fun, fun.nfev) # 50
+
+
+# Returns
+class TestShgoReturns:
+ def test_1_nfev_simplicial(self):
+ bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)]
+
+ def fun(x):
+ fun.nfev += 1
+ return rosen(x)
+
+ fun.nfev = 0
+
+ result = shgo(fun, bounds)
+ np.testing.assert_equal(fun.nfev, result.nfev)
+
+ def test_1_nfev_sobol(self):
+ bounds = [(0, 2), (0, 2), (0, 2), (0, 2), (0, 2)]
+
+ def fun(x):
+ fun.nfev += 1
+ return rosen(x)
+
+ fun.nfev = 0
+
+ result = shgo(fun, bounds, sampling_method='sobol')
+ np.testing.assert_equal(fun.nfev, result.nfev)
+
+
+def test_vector_constraint():
+ # gh15514
+ def quad(x):
+ x = np.asarray(x)
+ return [np.sum(x ** 2)]
+
+ nlc = NonlinearConstraint(quad, [2.2], [3])
+ oldc = new_constraint_to_old(nlc, np.array([1.0, 1.0]))
+
+ res = shgo(rosen, [(0, 10), (0, 10)], constraints=oldc, sampling_method='sobol')
+ assert np.all(np.sum((res.x)**2) >= 2.2)
+ assert np.all(np.sum((res.x) ** 2) <= 3.0)
+ assert res.success
+
+
+@pytest.mark.filterwarnings("ignore:delta_grad")
+def test_trust_constr():
+ def quad(x):
+ x = np.asarray(x)
+ return [np.sum(x ** 2)]
+
+ nlc = NonlinearConstraint(quad, [2.6], [3])
+ minimizer_kwargs = {'method': 'trust-constr'}
+ # note that we don't supply the constraints in minimizer_kwargs,
+ # so if the final result obeys the constraints we know that shgo
+ # passed them on to 'trust-constr'
+ res = shgo(
+ rosen,
+ [(0, 10), (0, 10)],
+ constraints=nlc,
+ sampling_method='sobol',
+ minimizer_kwargs=minimizer_kwargs
+ )
+ assert np.all(np.sum((res.x)**2) >= 2.6)
+ assert np.all(np.sum((res.x) ** 2) <= 3.0)
+ assert res.success
+
+
+def test_equality_constraints():
+ # gh16260
+ bounds = [(0.9, 4.0)] * 2 # Constrain probabilities to 0 and 1.
+
+ def faulty(x):
+ return x[0] + x[1]
+
+ nlc = NonlinearConstraint(faulty, 3.9, 3.9)
+ res = shgo(rosen, bounds=bounds, constraints=nlc)
+ assert_allclose(np.sum(res.x), 3.9)
+
+ def faulty(x):
+ return x[0] + x[1] - 3.9
+
+ constraints = {'type': 'eq', 'fun': faulty}
+ res = shgo(rosen, bounds=bounds, constraints=constraints)
+ assert_allclose(np.sum(res.x), 3.9)
+
+ bounds = [(0, 1.0)] * 4
+ # sum of variable should equal 1.
+ def faulty(x):
+ return x[0] + x[1] + x[2] + x[3] - 1
+
+ # options = {'minimize_every_iter': True, 'local_iter':10}
+ constraints = {'type': 'eq', 'fun': faulty}
+ res = shgo(
+ lambda x: - np.prod(x),
+ bounds=bounds,
+ constraints=constraints,
+ sampling_method='sobol'
+ )
+ assert_allclose(np.sum(res.x), 1.0)
+
+def test_gh16971():
+ def cons(x):
+ return np.sum(x**2) - 0
+
+ c = {'fun': cons, 'type': 'ineq'}
+ minimizer_kwargs = {
+ 'method': 'COBYLA',
+ 'options': {'rhobeg': 5, 'tol': 5e-1, 'catol': 0.05}
+ }
+
+ s = SHGO(
+ rosen, [(0, 10)]*2, constraints=c, minimizer_kwargs=minimizer_kwargs
+ )
+
+ assert s.minimizer_kwargs['method'].lower() == 'cobyla'
+ assert s.minimizer_kwargs['options']['catol'] == 0.05
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__spectral.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..00f233671133b1ce5a3f7cc25673569fb003326c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test__spectral.py
@@ -0,0 +1,225 @@
+import itertools
+
+import numpy as np
+from numpy import exp
+from numpy.testing import assert_, assert_equal
+
+from scipy.optimize import root
+
+
+def test_performance():
+ # Compare performance results to those listed in
+ # [Cheng & Li, IMA J. Num. An. 29, 814 (2008)]
+ # and
+ # [W. La Cruz, J.M. Martinez, M. Raydan, Math. Comp. 75, 1429 (2006)].
+ # and those produced by dfsane.f from M. Raydan's website.
+ #
+ # Where the results disagree, the largest limits are taken.
+
+ e_a = 1e-5
+ e_r = 1e-4
+
+ table_1 = [
+ dict(F=F_1, x0=x0_1, n=1000, nit=5, nfev=5),
+ dict(F=F_1, x0=x0_1, n=10000, nit=2, nfev=2),
+ dict(F=F_2, x0=x0_2, n=500, nit=11, nfev=11),
+ dict(F=F_2, x0=x0_2, n=2000, nit=11, nfev=11),
+ # dict(F=F_4, x0=x0_4, n=999, nit=243, nfev=1188) removed:
+ # too sensitive to rounding errors
+ # Results from dfsane.f; papers list nit=3, nfev=3
+ dict(F=F_6, x0=x0_6, n=100, nit=6, nfev=6),
+ # Must have n%3==0, typo in papers?
+ dict(F=F_7, x0=x0_7, n=99, nit=23, nfev=29),
+ # Must have n%3==0, typo in papers?
+ dict(F=F_7, x0=x0_7, n=999, nit=23, nfev=29),
+ # Results from dfsane.f; papers list nit=nfev=6?
+ dict(F=F_9, x0=x0_9, n=100, nit=12, nfev=18),
+ dict(F=F_9, x0=x0_9, n=1000, nit=12, nfev=18),
+ # Results from dfsane.f; papers list nit=2, nfev=12
+ dict(F=F_10, x0=x0_10, n=1000, nit=5, nfev=5),
+ ]
+
+ # Check also scaling invariance
+ for xscale, yscale, line_search in itertools.product(
+ [1.0, 1e-10, 1e10], [1.0, 1e-10, 1e10], ['cruz', 'cheng']
+ ):
+ for problem in table_1:
+ n = problem['n']
+ def func(x, n):
+ return yscale * problem['F'](x / xscale, n)
+ args = (n,)
+ x0 = problem['x0'](n) * xscale
+
+ fatol = np.sqrt(n) * e_a * yscale + e_r * np.linalg.norm(func(x0, n))
+
+ sigma_eps = 1e-10 * min(yscale/xscale, xscale/yscale)
+ sigma_0 = xscale/yscale
+
+ with np.errstate(over='ignore'):
+ sol = root(func, x0, args=args,
+ options=dict(ftol=0, fatol=fatol, maxfev=problem['nfev'] + 1,
+ sigma_0=sigma_0, sigma_eps=sigma_eps,
+ line_search=line_search),
+ method='DF-SANE')
+
+ err_msg = repr(
+ [xscale, yscale, line_search, problem, np.linalg.norm(func(sol.x, n)),
+ fatol, sol.success, sol.nit, sol.nfev]
+ )
+ assert sol.success, err_msg
+ # nfev+1: dfsane.f doesn't count first eval
+ assert sol.nfev <= problem['nfev'] + 1, err_msg
+ assert sol.nit <= problem['nit'], err_msg
+ assert np.linalg.norm(func(sol.x, n)) <= fatol, err_msg
+
+
+def test_complex():
+ def func(z):
+ return z**2 - 1 + 2j
+ x0 = 2.0j
+
+ ftol = 1e-4
+ sol = root(func, x0, tol=ftol, method='DF-SANE')
+
+ assert_(sol.success)
+
+ f0 = np.linalg.norm(func(x0))
+ fx = np.linalg.norm(func(sol.x))
+ assert_(fx <= ftol*f0)
+
+
+def test_linear_definite():
+ # The DF-SANE paper proves convergence for "strongly isolated"
+ # solutions.
+ #
+ # For linear systems F(x) = A x - b = 0, with A positive or
+ # negative definite, the solution is strongly isolated.
+
+ def check_solvability(A, b, line_search='cruz'):
+ def func(x):
+ return A.dot(x) - b
+ xp = np.linalg.solve(A, b)
+ eps = np.linalg.norm(func(xp)) * 1e3
+ sol = root(
+ func, b,
+ options=dict(fatol=eps, ftol=0, maxfev=17523, line_search=line_search),
+ method='DF-SANE',
+ )
+ assert_(sol.success)
+ assert_(np.linalg.norm(func(sol.x)) <= eps)
+
+ n = 90
+
+ # Test linear pos.def. system
+ A = np.arange(n*n).reshape(n, n)
+ A = A + n*n * np.diag(1 + np.arange(n))
+ assert_(np.linalg.eigvals(A).min() > 0)
+ b = np.arange(n) * 1.0
+ check_solvability(A, b, 'cruz')
+ check_solvability(A, b, 'cheng')
+
+ # Test linear neg.def. system
+ check_solvability(-A, b, 'cruz')
+ check_solvability(-A, b, 'cheng')
+
+
+def test_shape():
+ def f(x, arg):
+ return x - arg
+
+ for dt in [float, complex]:
+ x = np.zeros([2,2])
+ arg = np.ones([2,2], dtype=dt)
+
+ sol = root(f, x, args=(arg,), method='DF-SANE')
+ assert_(sol.success)
+ assert_equal(sol.x.shape, x.shape)
+
+
+# Some of the test functions and initial guesses listed in
+# [W. La Cruz, M. Raydan. Optimization Methods and Software, 18, 583 (2003)]
+
+def F_1(x, n):
+ g = np.zeros([n])
+ i = np.arange(2, n+1)
+ g[0] = exp(x[0] - 1) - 1
+ g[1:] = i*(exp(x[1:] - 1) - x[1:])
+ return g
+
+def x0_1(n):
+ x0 = np.empty([n])
+ x0.fill(n/(n-1))
+ return x0
+
+def F_2(x, n):
+ g = np.zeros([n])
+ i = np.arange(2, n+1)
+ g[0] = exp(x[0]) - 1
+ g[1:] = 0.1*i*(exp(x[1:]) + x[:-1] - 1)
+ return g
+
+def x0_2(n):
+ x0 = np.empty([n])
+ x0.fill(1/n**2)
+ return x0
+
+
+def F_4(x, n): # skip name check
+ assert_equal(n % 3, 0)
+ g = np.zeros([n])
+ # Note: the first line is typoed in some of the references;
+ # correct in original [Gasparo, Optimization Meth. 13, 79 (2000)]
+ g[::3] = 0.6 * x[::3] + 1.6 * x[1::3]**3 - 7.2 * x[1::3]**2 + 9.6 * x[1::3] - 4.8
+ g[1::3] = (0.48 * x[::3] - 0.72 * x[1::3]**3 + 3.24 * x[1::3]**2 - 4.32 * x[1::3]
+ - x[2::3] + 0.2 * x[2::3]**3 + 2.16)
+ g[2::3] = 1.25 * x[2::3] - 0.25*x[2::3]**3
+ return g
+
+
+def x0_4(n): # skip name check
+ assert_equal(n % 3, 0)
+ x0 = np.array([-1, 1/2, -1] * (n//3))
+ return x0
+
+def F_6(x, n):
+ c = 0.9
+ mu = (np.arange(1, n+1) - 0.5)/n
+ return x - 1/(1 - c/(2*n) * (mu[:,None]*x / (mu[:,None] + mu)).sum(axis=1))
+
+def x0_6(n):
+ return np.ones([n])
+
+def F_7(x, n):
+ assert_equal(n % 3, 0)
+
+ def phi(t):
+ v = 0.5*t - 2
+ v[t > -1] = ((-592*t**3 + 888*t**2 + 4551*t - 1924)/1998)[t > -1]
+ v[t >= 2] = (0.5*t + 2)[t >= 2]
+ return v
+ g = np.zeros([n])
+ g[::3] = 1e4 * x[1::3]**2 - 1
+ g[1::3] = exp(-x[::3]) + exp(-x[1::3]) - 1.0001
+ g[2::3] = phi(x[2::3])
+ return g
+
+def x0_7(n):
+ assert_equal(n % 3, 0)
+ return np.array([1e-3, 18, 1] * (n//3))
+
+def F_9(x, n):
+ g = np.zeros([n])
+ i = np.arange(2, n)
+ g[0] = x[0]**3/3 + x[1]**2/2
+ g[1:-1] = -x[1:-1]**2/2 + i*x[1:-1]**3/3 + x[2:]**2/2
+ g[-1] = -x[-1]**2/2 + n*x[-1]**3/3
+ return g
+
+def x0_9(n):
+ return np.ones([n])
+
+def F_10(x, n):
+ return np.log(1 + x) - x/n
+
+def x0_10(n):
+ return np.ones([n])
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_bracket.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_bracket.py
new file mode 100644
index 0000000000000000000000000000000000000000..46e6b616ba0c63ba2dc70281afbdbdf3cd22577d
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_bracket.py
@@ -0,0 +1,888 @@
+import pytest
+
+import numpy as np
+
+from scipy.optimize._bracket import _ELIMITS
+from scipy.optimize.elementwise import bracket_root, bracket_minimum
+import scipy._lib._elementwise_iterative_method as eim
+from scipy import stats
+from scipy._lib._array_api_no_0d import (xp_assert_close, xp_assert_equal,
+ xp_assert_less)
+from scipy._lib._array_api import xp_ravel, make_xp_test_case
+
+
+# These tests were originally written for the private `optimize._bracket`
+# interfaces, but now we want the tests to check the behavior of the public
+# `optimize.elementwise` interfaces. Therefore, rather than importing
+# `_bracket_root`/`_bracket_minimum` from `_bracket.py`, we import
+# `bracket_root`/`bracket_minimum` from `optimize.elementwise` and wrap those
+# functions to conform to the private interface. This may look a little strange,
+# since it effectively just inverts the interface transformation done within the
+# `bracket_root`/`bracket_minimum` functions, but it allows us to run the original,
+# unmodified tests on the public interfaces, simplifying the PR that adds
+# the public interfaces. We'll refactor this when we want to @parametrize the
+# tests over multiple `method`s.
+def _bracket_root(*args, **kwargs):
+ res = bracket_root(*args, **kwargs)
+ res.xl, res.xr = res.bracket
+ res.fl, res.fr = res.f_bracket
+ del res.bracket
+ del res.f_bracket
+ return res
+
+
+def _bracket_minimum(*args, **kwargs):
+ res = bracket_minimum(*args, **kwargs)
+ res.xl, res.xm, res.xr = res.bracket
+ res.fl, res.fm, res.fr = res.f_bracket
+ del res.bracket
+ del res.f_bracket
+ return res
+
+
+@make_xp_test_case(bracket_root)
+class TestBracketRoot:
+ @pytest.mark.parametrize("seed", (615655101, 3141866013, 238075752))
+ @pytest.mark.parametrize("use_xmin", (False, True))
+ @pytest.mark.parametrize("other_side", (False, True))
+ @pytest.mark.parametrize("fix_one_side", (False, True))
+ def test_nfev_expected(self, seed, use_xmin, other_side, fix_one_side, xp):
+ # Property-based test to confirm that _bracket_root is behaving as
+ # expected. The basic case is when root < a < b.
+ # The number of times bracket expands (per side) can be found by
+ # setting the expression for the left endpoint of the bracket to the
+ # root of f (x=0), solving for i, and rounding up. The corresponding
+ # lower and upper ends of the bracket are found by plugging this back
+ # into the expression for the ends of the bracket.
+ # `other_side=True` is the case that a < b < root
+ # Special cases like a < root < b are tested separately
+ rng = np.random.default_rng(seed)
+ xl0, d, factor = xp.asarray(rng.random(size=3) * [1e5, 10, 5])
+ factor = 1 + factor # factor must be greater than 1
+ xr0 = xl0 + d # xr0 must be greater than a in basic case
+
+ def f(x):
+ f.count += 1
+ return x # root is 0
+
+ if use_xmin:
+ xmin = xp.asarray(-rng.random())
+ n = xp.ceil(xp.log(-(xl0 - xmin) / xmin) / xp.log(factor))
+ l, u = xmin + (xl0 - xmin)*factor**-n, xmin + (xl0 - xmin)*factor**-(n - 1)
+ kwargs = dict(xl0=xl0, xr0=xr0, factor=factor, xmin=xmin)
+ else:
+ n = xp.ceil(xp.log(xr0/d) / xp.log(factor))
+ l, u = xr0 - d*factor**n, xr0 - d*factor**(n-1)
+ kwargs = dict(xl0=xl0, xr0=xr0, factor=factor)
+
+ if other_side:
+ kwargs['xl0'], kwargs['xr0'] = -kwargs['xr0'], -kwargs['xl0']
+ l, u = -u, -l
+ if 'xmin' in kwargs:
+ kwargs['xmax'] = -kwargs.pop('xmin')
+
+ if fix_one_side:
+ if other_side:
+ kwargs['xmin'] = -xr0
+ else:
+ kwargs['xmax'] = xr0
+
+ f.count = 0
+ res = _bracket_root(f, **kwargs)
+
+ # Compare reported number of function evaluations `nfev` against
+ # reported `nit`, actual function call count `f.count`, and theoretical
+ # number of expansions `n`.
+ # When both sides are free, these get multiplied by 2 because function
+ # is evaluated on the left and the right each iteration.
+ # When one side is fixed, however, we add one: on the right side, the
+ # function gets evaluated once at b.
+ # Add 1 to `n` and `res.nit` because function evaluations occur at
+ # iterations *0*, 1, ..., `n`. Subtract 1 from `f.count` because
+ # function is called separately for left and right in iteration 0.
+ if not fix_one_side:
+ assert res.nfev == 2*(res.nit+1) == 2*(f.count-1) == 2*(n + 1)
+ else:
+ assert res.nfev == (res.nit+1)+1 == (f.count-1)+1 == (n+1)+1
+
+ # Compare reported bracket to theoretical bracket and reported function
+ # values to function evaluated at bracket.
+ bracket = xp.asarray([res.xl, res.xr])
+ xp_assert_close(bracket, xp.asarray([l, u]))
+ f_bracket = xp.asarray([res.fl, res.fr])
+ xp_assert_close(f_bracket, f(bracket))
+
+ # Check that bracket is valid and that status and success are correct
+ assert res.xr > res.xl
+ signs = xp.sign(f_bracket)
+ assert signs[0] == -signs[1]
+ assert res.status == 0
+ assert res.success
+
+ def f(self, q, p):
+ return stats._stats_py._SimpleNormal().cdf(q) - p
+
+ @pytest.mark.parametrize('p', [0.6, np.linspace(0.05, 0.95, 10)])
+ @pytest.mark.parametrize('xmin', [-5, None])
+ @pytest.mark.parametrize('xmax', [5, None])
+ @pytest.mark.parametrize('factor', [1.2, 2])
+ def test_basic(self, p, xmin, xmax, factor, xp):
+ # Test basic functionality to bracket root (distribution PPF)
+ res = _bracket_root(self.f, xp.asarray(-0.01), 0.01, xmin=xmin, xmax=xmax,
+ factor=factor, args=(xp.asarray(p),))
+ xp_assert_equal(-xp.sign(res.fl), xp.sign(res.fr))
+
+ @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+ def test_vectorization(self, shape, xp):
+ # Test for correct functionality, output shapes, and dtypes for various
+ # input shapes.
+ p = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else np.float64(0.6)
+ args = (p,)
+ maxiter = 10
+
+ @np.vectorize
+ def bracket_root_single(xl0, xr0, xmin, xmax, factor, p):
+ return _bracket_root(self.f, xl0, xr0, xmin=xmin, xmax=xmax,
+ factor=factor, args=(p,),
+ maxiter=maxiter)
+
+ def f(*args, **kwargs):
+ f.f_evals += 1
+ return self.f(*args, **kwargs)
+ f.f_evals = 0
+
+ rng = np.random.default_rng(2348234)
+ xl0 = -rng.random(size=shape)
+ xr0 = rng.random(size=shape)
+ xmin, xmax = 1e3*xl0, 1e3*xr0
+ if shape: # make some elements un
+ i = rng.random(size=shape) > 0.5
+ xmin[i], xmax[i] = -np.inf, np.inf
+ factor = rng.random(size=shape) + 1.5
+ refs = bracket_root_single(xl0, xr0, xmin, xmax, factor, p).ravel()
+ xl0, xr0, xmin, xmax, factor = (xp.asarray(xl0), xp.asarray(xr0),
+ xp.asarray(xmin), xp.asarray(xmax),
+ xp.asarray(factor))
+ args = tuple(map(xp.asarray, args))
+ res = _bracket_root(f, xl0, xr0, xmin=xmin, xmax=xmax, factor=factor,
+ args=args, maxiter=maxiter)
+
+ attrs = ['xl', 'xr', 'fl', 'fr', 'success', 'nfev', 'nit']
+ for attr in attrs:
+ ref_attr = [xp.asarray(getattr(ref, attr)) for ref in refs]
+ res_attr = getattr(res, attr)
+ xp_assert_close(xp_ravel(res_attr, xp=xp), xp.stack(ref_attr))
+ assert res_attr.shape == shape
+
+ assert res.success.dtype == xp.bool
+ if shape:
+ assert xp.all(res.success[1:-1])
+ assert res.status.dtype == xp.int32
+ assert res.nfev.dtype == xp.int32
+ assert res.nit.dtype == xp.int32
+ assert xp.max(res.nit) == f.f_evals - 2
+ xp_assert_less(res.xl, res.xr)
+ xp_assert_close(res.fl, xp.asarray(self.f(res.xl, *args)))
+ xp_assert_close(res.fr, xp.asarray(self.f(res.xr, *args)))
+
+ def test_flags(self, xp):
+ # Test cases that should produce different status flags; show that all
+ # can be produced simultaneously.
+ def f(xs, js):
+ funcs = [lambda x: x - 1.5,
+ lambda x: x - 1000,
+ lambda x: x - 1000,
+ lambda x: x * xp.nan,
+ lambda x: x]
+
+ return [funcs[int(j)](x) for x, j in zip(xs, js)]
+
+ args = (xp.arange(5, dtype=xp.int64),)
+ res = _bracket_root(f,
+ xl0=xp.asarray([-1., -1., -1., -1., 4.]),
+ xr0=xp.asarray([1, 1, 1, 1, -4]),
+ xmin=xp.asarray([-xp.inf, -1, -xp.inf, -xp.inf, 6]),
+ xmax=xp.asarray([xp.inf, 1, xp.inf, xp.inf, 2]),
+ args=args, maxiter=3)
+
+ ref_flags = xp.asarray([eim._ECONVERGED,
+ _ELIMITS,
+ eim._ECONVERR,
+ eim._EVALUEERR,
+ eim._EINPUTERR],
+ dtype=xp.int32)
+
+ xp_assert_equal(res.status, ref_flags)
+
+ @pytest.mark.parametrize("root", (0.622, [0.622, 0.623]))
+ @pytest.mark.parametrize('xmin', [-5, None])
+ @pytest.mark.parametrize('xmax', [5, None])
+ @pytest.mark.parametrize("dtype", ("float16", "float32", "float64"))
+ def test_dtype(self, root, xmin, xmax, dtype, xp):
+ # Test that dtypes are preserved
+ dtype = getattr(xp, dtype)
+ xmin = xmin if xmin is None else xp.asarray(xmin, dtype=dtype)
+ xmax = xmax if xmax is None else xp.asarray(xmax, dtype=dtype)
+ root = xp.asarray(root, dtype=dtype)
+ def f(x, root):
+ return xp.astype((x - root) ** 3, dtype)
+
+ bracket = xp.asarray([-0.01, 0.01], dtype=dtype)
+ res = _bracket_root(f, *bracket, xmin=xmin, xmax=xmax, args=(root,))
+ assert xp.all(res.success)
+ assert res.xl.dtype == res.xr.dtype == dtype
+ assert res.fl.dtype == res.fr.dtype == dtype
+
+ def test_input_validation(self, xp):
+ # Test input validation for appropriate error messages
+
+ message = '`func` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(None, -4, 4)
+
+ message = '...must be numeric and real.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4+1j, 4)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, xmin=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, xmax=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, factor=4+1j)
+
+ message = "All elements of `factor` must be greater than 1."
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, factor=0.5)
+
+ message = "broadcast"
+ # raised by `xp.broadcast, but the traceback is readable IMO
+ with pytest.raises(Exception, match=message):
+ _bracket_root(lambda x: x, xp.asarray([-2, -3]), xp.asarray([3, 4, 5]))
+ # Consider making this give a more readable error message
+ # with pytest.raises(ValueError, match=message):
+ # _bracket_root(lambda x: [x[0], x[1], x[1]], [-3, -3], [5, 5])
+
+ message = '`maxiter` must be a non-negative integer.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, maxiter=1.5)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, maxiter=-1)
+ with pytest.raises(ValueError, match=message):
+ _bracket_root(lambda x: x, -4, 4, maxiter="shrubbery")
+
+ def test_special_cases(self, xp):
+ # Test edge cases and other special cases
+ # Test that integers are not passed to `f`
+ # (otherwise this would overflow)
+ def f(x):
+ assert xp.isdtype(x.dtype, "real floating")
+ return x ** 99 - 1
+
+ res = _bracket_root(f, xp.asarray(-7.), xp.asarray(5.))
+ assert res.success
+
+ # Test maxiter = 0. Should do nothing to bracket.
+ def f(x):
+ return x - 10
+
+ bracket = (xp.asarray(-3.), xp.asarray(5.))
+ res = _bracket_root(f, *bracket, maxiter=0)
+ assert res.xl, res.xr == bracket
+ assert res.nit == 0
+ assert res.nfev == 2
+ assert res.status == -2
+
+ # Test scalar `args` (not in tuple)
+ def f(x, c):
+ return c*x - 1
+
+ res = _bracket_root(f, xp.asarray(-1.), xp.asarray(1.),
+ args=xp.asarray(3.))
+ assert res.success
+ xp_assert_close(res.fl, f(res.xl, 3))
+
+ # Test other edge cases
+
+ def f(x):
+ f.count += 1
+ return x
+
+ # 1. root lies within guess of bracket
+ f.count = 0
+ _bracket_root(f, xp.asarray(-10), xp.asarray(20))
+ assert f.count == 2
+
+ # 2. bracket endpoint hits root exactly
+ f.count = 0
+ res = _bracket_root(f, xp.asarray(5.), xp.asarray(10.),
+ factor=2)
+
+ assert res.nfev == 4
+ xp_assert_close(res.xl, xp.asarray(0.), atol=1e-15)
+ xp_assert_close(res.xr, xp.asarray(5.), atol=1e-15)
+
+ # 3. bracket limit hits root exactly
+ with np.errstate(over='ignore'):
+ res = _bracket_root(f, xp.asarray(5.), xp.asarray(10.),
+ xmin=0)
+ xp_assert_close(res.xl, xp.asarray(0.), atol=1e-15)
+
+ with np.errstate(over='ignore'):
+ res = _bracket_root(f, xp.asarray(-10.), xp.asarray(-5.),
+ xmax=0)
+ xp_assert_close(res.xr, xp.asarray(0.), atol=1e-15)
+
+ # 4. bracket not within min, max
+ with np.errstate(over='ignore'):
+ res = _bracket_root(f, xp.asarray(5.), xp.asarray(10.),
+ xmin=1)
+ assert not res.success
+
+ def test_bug_fixes(self):
+ # 1. Bug in double sided bracket search.
+ # Happened in some cases where there are terminations on one side
+ # after corresponding searches on other side failed due to reaching the
+ # boundary.
+
+ # https://github.com/scipy/scipy/pull/22560#discussion_r1962853839
+ def f(x, p):
+ return np.exp(x) - p
+
+ p = np.asarray([0.29, 0.35])
+ res = _bracket_root(f, xl0=-1, xmin=-np.inf, xmax=0, args=(p, ))
+
+ # https://github.com/scipy/scipy/pull/22560/files#r1962952517
+ def f(x, p, c):
+ return np.exp(x*c) - p
+
+ p = [0.32061201, 0.39175242, 0.40047535, 0.50527218, 0.55654373,
+ 0.11911647, 0.37507896, 0.66554191]
+ c = [1., -1., 1., 1., -1., 1., 1., 1.]
+ xl0 = [-7.63108551, 3.27840947, -8.36968526, -1.78124372,
+ 0.92201295, -2.48930123, -0.66733533, -0.44606749]
+ xr0 = [-6.63108551, 4.27840947, -7.36968526, -0.78124372,
+ 1.92201295, -1.48930123, 0., 0.]
+ xmin = [-np.inf, 0., -np.inf, -np.inf, 0., -np.inf, -np.inf,
+ -np.inf]
+ xmax = [0., np.inf, 0., 0., np.inf, 0., 0., 0.]
+
+ res = _bracket_root(f, xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, args=(p, c))
+
+ # 2. Default xl0 + 1 for xr0 exceeds xmax.
+ # https://github.com/scipy/scipy/pull/22560#discussion_r1962947434
+ res = _bracket_root(lambda x: x + 0.25, xl0=-0.5, xmin=-np.inf, xmax=0)
+ assert res.success
+
+
+@make_xp_test_case(bracket_minimum)
+class TestBracketMinimum:
+ def init_f(self):
+ def f(x, a, b):
+ f.count += 1
+ return (x - a)**2 + b
+ f.count = 0
+ return f
+
+ def assert_valid_bracket(self, result, xp):
+ assert xp.all(
+ (result.xl < result.xm) & (result.xm < result.xr)
+ )
+ assert xp.all(
+ (result.fl >= result.fm) & (result.fr > result.fm)
+ | (result.fl > result.fm) & (result.fr > result.fm)
+ )
+
+ def get_kwargs(
+ self, *, xl0=None, xr0=None, factor=None, xmin=None, xmax=None, args=None
+ ):
+ names = ("xl0", "xr0", "xmin", "xmax", "factor", "args")
+ return {
+ name: val for name, val in zip(names, (xl0, xr0, xmin, xmax, factor, args))
+ if val is not None
+ }
+
+ @pytest.mark.parametrize(
+ "seed",
+ (
+ 307448016549685229886351382450158984917,
+ 11650702770735516532954347931959000479,
+ 113767103358505514764278732330028568336,
+ )
+ )
+ @pytest.mark.parametrize("use_xmin", (False, True))
+ @pytest.mark.parametrize("other_side", (False, True))
+ def test_nfev_expected(self, seed, use_xmin, other_side, xp):
+ rng = np.random.default_rng(seed)
+ args = (xp.asarray(0.), xp.asarray(0.)) # f(x) = x^2 with minimum at 0
+ # xl0, xm0, xr0 are chosen such that the initial bracket is to
+ # the right of the minimum, and the bracket will expand
+ # downhill towards zero.
+ xl0, d1, d2, factor = xp.asarray(rng.random(size=4) * [1e5, 10, 10, 5])
+ xm0 = xl0 + d1
+ xr0 = xm0 + d2
+ # Factor should be greater than one.
+ factor += 1
+
+ if use_xmin:
+ xmin = xp.asarray(-rng.random() * 5, dtype=xp.float64)
+ n = int(xp.ceil(xp.log(-(xl0 - xmin) / xmin) / xp.log(factor)))
+ lower = xmin + (xl0 - xmin)*factor**-n
+ middle = xmin + (xl0 - xmin)*factor**-(n-1)
+ upper = xmin + (xl0 - xmin)*factor**-(n-2) if n > 1 else xm0
+ # It may be the case the lower is below the minimum, but we still
+ # don't have a valid bracket.
+ if middle**2 > lower**2:
+ n += 1
+ lower, middle, upper = (
+ xmin + (xl0 - xmin)*factor**-n, lower, middle
+ )
+ else:
+ xmin = None
+ n = int(xp.ceil(xp.log(xl0 / d1) / xp.log(factor)))
+ lower = xl0 - d1*factor**n
+ middle = xl0 - d1*factor**(n-1) if n > 1 else xl0
+ upper = xl0 - d1*factor**(n-2) if n > 1 else xm0
+ # It may be the case the lower is below the minimum, but we still
+ # don't have a valid bracket.
+ if middle**2 > lower**2:
+ n += 1
+ lower, middle, upper = (
+ xl0 - d1*factor**n, lower, middle
+ )
+ f = self.init_f()
+
+ xmax = None
+ if other_side:
+ xl0, xm0, xr0 = -xr0, -xm0, -xl0
+ xmin, xmax = None, -xmin if xmin is not None else None
+ lower, middle, upper = -upper, -middle, -lower
+
+ kwargs = self.get_kwargs(
+ xl0=xl0, xr0=xr0, xmin=xmin, xmax=xmax, factor=factor, args=args
+ )
+ result = _bracket_minimum(f, xp.asarray(xm0), **kwargs)
+
+ # Check that `nfev` and `nit` have the correct relationship
+ assert result.nfev == result.nit + 3
+ # Check that `nfev` reports the correct number of function evaluations.
+ assert result.nfev == f.count
+ # Check that the number of iterations matches the theoretical value.
+ assert result.nit == n
+
+ # Compare reported bracket to theoretical bracket and reported function
+ # values to function evaluated at bracket.
+ xp_assert_close(result.xl, lower)
+ xp_assert_close(result.xm, middle)
+ xp_assert_close(result.xr, upper)
+ xp_assert_close(result.fl, f(lower, *args))
+ xp_assert_close(result.fm, f(middle, *args))
+ xp_assert_close(result.fr, f(upper, *args))
+
+ self.assert_valid_bracket(result, xp)
+ assert result.status == 0
+ assert result.success
+
+ def test_flags(self, xp):
+ # Test cases that should produce different status flags; show that all
+ # can be produced simultaneously
+ def f(xs, js):
+ funcs = [lambda x: (x - 1.5)**2,
+ lambda x: x,
+ lambda x: x,
+ lambda x: xp.asarray(xp.nan),
+ lambda x: x**2]
+
+ return [funcs[int(j)](x) for x, j in zip(xs, js)]
+
+ args = (xp.arange(5, dtype=xp.int64),)
+ xl0 = xp.asarray([-1.0, -1.0, -1.0, -1.0, 6.0])
+ xm0 = xp.asarray([0.0, 0.0, 0.0, 0.0, 4.0])
+ xr0 = xp.asarray([1.0, 1.0, 1.0, 1.0, 2.0])
+ xmin = xp.asarray([-xp.inf, -1.0, -xp.inf, -xp.inf, 8.0])
+
+ result = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, xmin=xmin,
+ args=args, maxiter=3)
+
+ reference_flags = xp.asarray([eim._ECONVERGED, _ELIMITS,
+ eim._ECONVERR, eim._EVALUEERR,
+ eim._EINPUTERR], dtype=xp.int32)
+ xp_assert_equal(result.status, reference_flags)
+
+ @pytest.mark.parametrize("minimum", (0.622, [0.622, 0.623]))
+ @pytest.mark.parametrize("dtype", ("float16", "float32", "float64"))
+ @pytest.mark.parametrize("xmin", [-5, None])
+ @pytest.mark.parametrize("xmax", [5, None])
+ def test_dtypes(self, minimum, xmin, xmax, dtype, xp):
+ dtype = getattr(xp, dtype)
+ xmin = xmin if xmin is None else xp.asarray(xmin, dtype=dtype)
+ xmax = xmax if xmax is None else xp.asarray(xmax, dtype=dtype)
+ minimum = xp.asarray(minimum, dtype=dtype)
+
+ def f(x, minimum):
+ return xp.astype((x - minimum)**2, dtype)
+
+ xl0, xm0, xr0 = [-0.01, 0.0, 0.01]
+ result = _bracket_minimum(
+ f, xp.asarray(xm0, dtype=dtype), xl0=xp.asarray(xl0, dtype=dtype),
+ xr0=xp.asarray(xr0, dtype=dtype), xmin=xmin, xmax=xmax, args=(minimum, )
+ )
+ assert xp.all(result.success)
+ assert result.xl.dtype == result.xm.dtype == result.xr.dtype == dtype
+ assert result.fl.dtype == result.fm.dtype == result.fr.dtype == dtype
+
+ @pytest.mark.skip_xp_backends(np_only=True, reason="str/object arrays")
+ def test_input_validation(self, xp):
+ # Test input validation for appropriate error messages
+
+ message = '`func` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(None, -4, xl0=4)
+
+ message = '...must be numeric and real.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(4+1j))
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xl0=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xr0=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xmin=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xmax=4+1j)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), factor=4+1j)
+
+ message = "All elements of `factor` must be greater than 1."
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x, xp.asarray(-4), factor=0.5)
+
+ message = "Array shapes are incompatible for broadcasting."
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray([-2, -3]), xl0=[-3, -4, -5])
+
+ message = '`maxiter` must be a non-negative integer.'
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xr0=4, maxiter=1.5)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xr0=4, maxiter=-1)
+ with pytest.raises(ValueError, match=message):
+ _bracket_minimum(lambda x: x**2, xp.asarray(-4), xr0=4, maxiter="ekki")
+
+ @pytest.mark.parametrize("xl0", [0.0, None])
+ @pytest.mark.parametrize("xm0", (0.05, 0.1, 0.15))
+ @pytest.mark.parametrize("xr0", (0.2, 0.4, 0.6, None))
+ # Minimum is ``a`` for each tuple ``(a, b)`` below. Tests cases where minimum
+ # is within, or at varying distances to the left or right of the initial
+ # bracket.
+ @pytest.mark.parametrize(
+ "args",
+ (
+ (1.2, 0), (-0.5, 0), (0.1, 0), (0.2, 0), (3.6, 0), (21.4, 0),
+ (121.6, 0), (5764.1, 0), (-6.4, 0), (-12.9, 0), (-146.2, 0)
+ )
+ )
+ def test_scalar_no_limits(self, xl0, xm0, xr0, args, xp):
+ f = self.init_f()
+ kwargs = self.get_kwargs(xl0=xl0, xr0=xr0, args=tuple(map(xp.asarray, args)))
+ result = _bracket_minimum(f, xp.asarray(xm0, dtype=xp.float64), **kwargs)
+ self.assert_valid_bracket(result, xp)
+ assert result.status == 0
+ assert result.success
+ assert result.nfev == f.count
+
+ @pytest.mark.parametrize(
+ # xmin is set at 0.0 in all cases.
+ "xl0,xm0,xr0,xmin",
+ (
+ # Initial bracket at varying distances from the xmin.
+ (0.5, 0.75, 1.0, 0.0),
+ (1.0, 2.5, 4.0, 0.0),
+ (2.0, 4.0, 6.0, 0.0),
+ (12.0, 16.0, 20.0, 0.0),
+ # Test default initial left endpoint selection. It should not
+ # be below xmin.
+ (None, 0.75, 1.0, 0.0),
+ (None, 2.5, 4.0, 0.0),
+ (None, 4.0, 6.0, 0.0),
+ (None, 16.0, 20.0, 0.0),
+ )
+ )
+ @pytest.mark.parametrize(
+ "args", (
+ (0.0, 0.0), # Minimum is directly at xmin.
+ (1e-300, 0.0), # Minimum is extremely close to xmin.
+ (1e-20, 0.0), # Minimum is very close to xmin.
+ # Minimum at varying distances from xmin.
+ (0.1, 0.0),
+ (0.2, 0.0),
+ (0.4, 0.0)
+ )
+ )
+ def test_scalar_with_limit_left(self, xl0, xm0, xr0, xmin, args, xp):
+ f = self.init_f()
+ kwargs = self.get_kwargs(xl0=xl0, xr0=xr0, xmin=xmin,
+ args=tuple(map(xp.asarray, args)))
+ result = _bracket_minimum(f, xp.asarray(xm0), **kwargs)
+ self.assert_valid_bracket(result, xp)
+ assert result.status == 0
+ assert result.success
+ assert result.nfev == f.count
+
+ @pytest.mark.parametrize(
+ #xmax is set to 1.0 in all cases.
+ "xl0,xm0,xr0,xmax",
+ (
+ # Bracket at varying distances from xmax.
+ (0.2, 0.3, 0.4, 1.0),
+ (0.05, 0.075, 0.1, 1.0),
+ (-0.2, -0.1, 0.0, 1.0),
+ (-21.2, -17.7, -14.2, 1.0),
+ # Test default right endpoint selection. It should not exceed xmax.
+ (0.2, 0.3, None, 1.0),
+ (0.05, 0.075, None, 1.0),
+ (-0.2, -0.1, None, 1.0),
+ (-21.2, -17.7, None, 1.0),
+ )
+ )
+ @pytest.mark.parametrize(
+ "args", (
+ (0.9999999999999999, 0.0), # Minimum very close to xmax.
+ # Minimum at varying distances from xmax.
+ (0.9, 0.0),
+ (0.7, 0.0),
+ (0.5, 0.0)
+ )
+ )
+ def test_scalar_with_limit_right(self, xl0, xm0, xr0, xmax, args, xp):
+ f = self.init_f()
+ args = tuple(xp.asarray(arg, dtype=xp.float64) for arg in args)
+ kwargs = self.get_kwargs(xl0=xl0, xr0=xr0, xmax=xmax, args=args)
+ result = _bracket_minimum(f, xp.asarray(xm0, dtype=xp.float64), **kwargs)
+ self.assert_valid_bracket(result, xp)
+ assert result.status == 0
+ assert result.success
+ assert result.nfev == f.count
+
+ @pytest.mark.parametrize(
+ "xl0,xm0,xr0,xmin,xmax,args",
+ (
+ ( # Case 1:
+ # Initial bracket.
+ 0.2,
+ 0.3,
+ 0.4,
+ # Function slopes down to the right from the bracket to a minimum
+ # at 1.0. xmax is also at 1.0
+ None,
+ 1.0,
+ (1.0, 0.0)
+ ),
+ ( # Case 2:
+ # Initial bracket.
+ 1.4,
+ 1.95,
+ 2.5,
+ # Function slopes down to the left from the bracket to a minimum at
+ # 0.3 with xmin set to 0.3.
+ 0.3,
+ None,
+ (0.3, 0.0)
+ ),
+ (
+ # Case 3:
+ # Initial bracket.
+ 2.6,
+ 3.25,
+ 3.9,
+ # Function slopes down and to the right to a minimum at 99.4 with xmax
+ # at 99.4. Tests case where minimum is at xmax relatively further from
+ # the bracket.
+ None,
+ 99.4,
+ (99.4, 0)
+ ),
+ (
+ # Case 4:
+ # Initial bracket.
+ 4,
+ 4.5,
+ 5,
+ # Function slopes down and to the left away from the bracket with a
+ # minimum at -26.3 with xmin set to -26.3. Tests case where minimum is
+ # at xmin relatively far from the bracket.
+ -26.3,
+ None,
+ (-26.3, 0)
+ ),
+ (
+ # Case 5:
+ # Similar to Case 1 above, but tests default values of xl0 and xr0.
+ None,
+ 0.3,
+ None,
+ None,
+ 1.0,
+ (1.0, 0.0)
+ ),
+ ( # Case 6:
+ # Similar to Case 2 above, but tests default values of xl0 and xr0.
+ None,
+ 1.95,
+ None,
+ 0.3,
+ None,
+ (0.3, 0.0)
+ ),
+ (
+ # Case 7:
+ # Similar to Case 3 above, but tests default values of xl0 and xr0.
+ None,
+ 3.25,
+ None,
+ None,
+ 99.4,
+ (99.4, 0)
+ ),
+ (
+ # Case 8:
+ # Similar to Case 4 above, but tests default values of xl0 and xr0.
+ None,
+ 4.5,
+ None,
+ -26.3,
+ None,
+ (-26.3, 0)
+ ),
+ )
+ )
+ def test_minimum_at_boundary_point(self, xl0, xm0, xr0, xmin, xmax, args, xp):
+ f = self.init_f()
+ kwargs = self.get_kwargs(xr0=xr0, xmin=xmin, xmax=xmax,
+ args=tuple(map(xp.asarray, args)))
+ result = _bracket_minimum(f, xp.asarray(xm0), **kwargs)
+ assert result.status == -1
+ assert args[0] in (result.xl, result.xr)
+ assert result.nfev == f.count
+
+ @pytest.mark.parametrize('shape', [tuple(), (12, ), (3, 4), (3, 2, 2)])
+ def test_vectorization(self, shape, xp):
+ # Test for correct functionality, output shapes, and dtypes for
+ # various input shapes.
+ a = np.linspace(-0.05, 1.05, 12).reshape(shape) if shape else 0.6
+ args = (a, 0.)
+ maxiter = 10
+
+ @np.vectorize
+ def bracket_minimum_single(xm0, xl0, xr0, xmin, xmax, factor, a):
+ return _bracket_minimum(self.init_f(), xm0, xl0=xl0, xr0=xr0, xmin=xmin,
+ xmax=xmax, factor=factor, maxiter=maxiter,
+ args=(a, 0.0))
+
+ f = self.init_f()
+
+ rng = np.random.default_rng(2348234)
+ xl0 = -rng.random(size=shape)
+ xr0 = rng.random(size=shape)
+ xm0 = xl0 + rng.random(size=shape) * (xr0 - xl0)
+ xmin, xmax = 1e3*xl0, 1e3*xr0
+ if shape: # make some elements un
+ i = rng.random(size=shape) > 0.5
+ xmin[i], xmax[i] = -np.inf, np.inf
+ factor = rng.random(size=shape) + 1.5
+ refs = bracket_minimum_single(xm0, xl0, xr0, xmin, xmax, factor, a).ravel()
+ args = tuple(xp.asarray(arg, dtype=xp.float64) for arg in args)
+ res = _bracket_minimum(f, xp.asarray(xm0), xl0=xp.asarray(xl0),
+ xr0=xp.asarray(xr0), xmin=xp.asarray(xmin),
+ xmax=xp.asarray(xmax), factor=xp.asarray(factor),
+ args=args, maxiter=maxiter)
+
+ attrs = ['xl', 'xm', 'xr', 'fl', 'fm', 'fr', 'success', 'nfev', 'nit']
+ for attr in attrs:
+ ref_attr = [xp.asarray(getattr(ref, attr)) for ref in refs]
+ res_attr = getattr(res, attr)
+ xp_assert_close(xp_ravel(res_attr, xp=xp), xp.stack(ref_attr))
+ assert res_attr.shape == shape
+
+ assert res.success.dtype == xp.bool
+ if shape:
+ assert xp.all(res.success[1:-1])
+ assert res.status.dtype == xp.int32
+ assert res.nfev.dtype == xp.int32
+ assert res.nit.dtype == xp.int32
+ assert xp.max(res.nit) == f.count - 3
+ self.assert_valid_bracket(res, xp)
+ xp_assert_close(res.fl, f(res.xl, *args))
+ xp_assert_close(res.fm, f(res.xm, *args))
+ xp_assert_close(res.fr, f(res.xr, *args))
+
+ def test_special_cases(self, xp):
+ # Test edge cases and other special cases.
+
+ # Test that integers are not passed to `f`
+ # (otherwise this would overflow)
+ def f(x):
+ assert xp.isdtype(x.dtype, "numeric")
+ return x ** 98 - 1
+
+ result = _bracket_minimum(f, xp.asarray(-7., dtype=xp.float64), xr0=5)
+ assert result.success
+
+ # Test maxiter = 0. Should do nothing to bracket.
+ def f(x):
+ return x**2 - 10
+
+ xl0, xm0, xr0 = xp.asarray(-3.), xp.asarray(-1.), xp.asarray(2.)
+ result = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, maxiter=0)
+ xp_assert_equal(result.xl, xl0)
+ xp_assert_equal(result.xm, xm0)
+ xp_assert_equal(result.xr, xr0)
+
+ # Test scalar `args` (not in tuple)
+ def f(x, c):
+ return c*x**2 - 1
+
+ result = _bracket_minimum(f, xp.asarray(-1.), args=xp.asarray(3.))
+ assert result.success
+ xp_assert_close(result.fl, f(result.xl, 3))
+
+ # Initial bracket is valid.
+ f = self.init_f()
+ xl0, xm0, xr0 = xp.asarray(-1.0), xp.asarray(-0.2), xp.asarray(1.0)
+ args = (xp.asarray(0.), xp.asarray(0.))
+ result = _bracket_minimum(f, xm0, xl0=xl0, xr0=xr0, args=args)
+ assert f.count == 3
+
+ xp_assert_equal(result.xl, xl0)
+ xp_assert_equal(result.xm , xm0)
+ xp_assert_equal(result.xr, xr0)
+ xp_assert_equal(result.fl, f(xl0, *args))
+ xp_assert_equal(result.fm, f(xm0, *args))
+ xp_assert_equal(result.fr, f(xr0, *args))
+
+ def test_gh_20562_left(self, xp):
+ # Regression test for https://github.com/scipy/scipy/issues/20562
+ # minimum of f in [xmin, xmax] is at xmin.
+ xmin, xmax = xp.asarray(0.21933608), xp.asarray(1.39713606)
+
+ def f(x):
+ log_a, log_b = xp.log(xmin), xp.log(xmax)
+ return -((log_b - log_a)*x)**-1
+
+ result = _bracket_minimum(f, xp.asarray(0.5535723499480897), xmin=xmin,
+ xmax=xmax)
+ xp_assert_close(result.xl, xmin)
+
+ def test_gh_20562_right(self, xp):
+ # Regression test for https://github.com/scipy/scipy/issues/20562
+ # minimum of f in [xmin, xmax] is at xmax.
+ xmin, xmax = xp.asarray(-1.39713606), xp.asarray(-0.21933608)
+
+ def f(x):
+ log_a, log_b = xp.log(-xmax), xp.log(-xmin)
+ return ((log_b - log_a)*x)**-1
+
+ result = _bracket_minimum(f, xp.asarray(-0.5535723499480897),
+ xmin=xmin, xmax=xmax)
+ xp_assert_close(result.xr, xmax)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_chandrupatla.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_chandrupatla.py
new file mode 100644
index 0000000000000000000000000000000000000000..232a826ef4236c46c69b5fb2bc676484278fec18
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_chandrupatla.py
@@ -0,0 +1,976 @@
+import math
+import pytest
+import numpy as np
+from copy import deepcopy
+
+from scipy import stats, special
+import scipy._lib._elementwise_iterative_method as eim
+import scipy._lib.array_api_extra as xpx
+from scipy._lib._array_api import (array_namespace, is_cupy, is_numpy, xp_ravel,
+ xp_size, make_xp_test_case)
+from scipy._lib._array_api_no_0d import (xp_assert_close, xp_assert_equal,
+ xp_assert_less)
+
+from scipy.optimize.elementwise import find_minimum, find_root
+from scipy.optimize._tstutils import _CHANDRUPATLA_TESTS
+
+from itertools import permutations
+
+
+def _vectorize(xp):
+ # xp-compatible version of np.vectorize
+ # assumes arguments are all arrays of the same shape
+ def decorator(f):
+ def wrapped(*arg_arrays):
+ shape = arg_arrays[0].shape
+ arg_arrays = [xp_ravel(arg_array, xp=xp) for arg_array in arg_arrays]
+ res = []
+ for i in range(math.prod(shape)):
+ arg_scalars = [arg_array[i] for arg_array in arg_arrays]
+ res.append(f(*arg_scalars))
+ return res
+
+ return wrapped
+
+ return decorator
+
+
+# These tests were originally written for the private `optimize._chandrupatla`
+# interfaces, but now we want the tests to check the behavior of the public
+# `optimize.elementwise` interfaces. Therefore, rather than importing
+# `_chandrupatla`/`_chandrupatla_minimize` from `_chandrupatla.py`, we import
+# `find_root`/`find_minimum` from `optimize.elementwise` and wrap those
+# functions to conform to the private interface. This may look a little strange,
+# since it effectively just inverts the interface transformation done within the
+# `find_root`/`find_minimum` functions, but it allows us to run the original,
+# unmodified tests on the public interfaces, simplifying the PR that adds
+# the public interfaces. We'll refactor this when we want to @parametrize the
+# tests over multiple `method`s.
+def _wrap_chandrupatla(func):
+ def _chandrupatla_wrapper(f, *bracket, **kwargs):
+ # avoid passing arguments to `find_minimum` to this function
+ tol_keys = {'xatol', 'xrtol', 'fatol', 'frtol'}
+ tolerances = {key: kwargs.pop(key) for key in tol_keys if key in kwargs}
+ _callback = kwargs.pop('callback', None)
+ if callable(_callback):
+ def callback(res):
+ if func == find_root:
+ res.xl, res.xr = res.bracket
+ res.fl, res.fr = res.f_bracket
+ else:
+ res.xl, res.xm, res.xr = res.bracket
+ res.fl, res.fm, res.fr = res.f_bracket
+ res.fun = res.f_x
+ del res.bracket
+ del res.f_bracket
+ del res.f_x
+ return _callback(res)
+ else:
+ callback = _callback
+
+ res = func(f, bracket, tolerances=tolerances, callback=callback, **kwargs)
+ if func == find_root:
+ res.xl, res.xr = res.bracket
+ res.fl, res.fr = res.f_bracket
+ else:
+ res.xl, res.xm, res.xr = res.bracket
+ res.fl, res.fm, res.fr = res.f_bracket
+ res.fun = res.f_x
+ del res.bracket
+ del res.f_bracket
+ del res.f_x
+ return res
+ return _chandrupatla_wrapper
+
+
+_chandrupatla_minimize = _wrap_chandrupatla(find_minimum)
+
+
+def f1(x):
+ return 100*(1 - x**3.)**2 + (1-x**2.) + 2*(1-x)**2.
+
+
+def f2(x):
+ return 5 + (x - 2.)**6
+
+
+def f3(x):
+ xp = array_namespace(x)
+ return xp.exp(x) - 5*x
+
+
+def f4(x):
+ return x**5. - 5*x**3. - 20.*x + 5.
+
+
+def f5(x):
+ return 8*x**3 - 2*x**2 - 7*x + 3
+
+
+def _bracket_minimum(func, x1, x2):
+ phi = 1.61803398875
+ maxiter = 100
+ f1 = func(x1)
+ f2 = func(x2)
+ step = x2 - x1
+ x1, x2, f1, f2, step = ((x2, x1, f2, f1, -step) if f2 > f1
+ else (x1, x2, f1, f2, step))
+
+ for i in range(maxiter):
+ step *= phi
+ x3 = x2 + step
+ f3 = func(x3)
+ if f3 < f2:
+ x1, x2, f1, f2 = x2, x3, f2, f3
+ else:
+ break
+ return x1, x2, x3, f1, f2, f3
+
+
+cases = [
+ (f1, -1, 11),
+ (f1, -2, 13),
+ (f1, -4, 13),
+ (f1, -8, 15),
+ (f1, -16, 16),
+ (f1, -32, 19),
+ (f1, -64, 20),
+ (f1, -128, 21),
+ (f1, -256, 21),
+ (f1, -512, 19),
+ (f1, -1024, 24),
+ (f2, -1, 8),
+ (f2, -2, 6),
+ (f2, -4, 6),
+ (f2, -8, 7),
+ (f2, -16, 8),
+ (f2, -32, 8),
+ (f2, -64, 9),
+ (f2, -128, 11),
+ (f2, -256, 13),
+ (f2, -512, 12),
+ (f2, -1024, 13),
+ (f3, -1, 11),
+ (f3, -2, 11),
+ (f3, -4, 11),
+ (f3, -8, 10),
+ (f3, -16, 14),
+ (f3, -32, 12),
+ (f3, -64, 15),
+ (f3, -128, 18),
+ (f3, -256, 18),
+ (f3, -512, 19),
+ (f3, -1024, 19),
+ (f4, -0.05, 9),
+ (f4, -0.10, 11),
+ (f4, -0.15, 11),
+ (f4, -0.20, 11),
+ (f4, -0.25, 11),
+ (f4, -0.30, 9),
+ (f4, -0.35, 9),
+ (f4, -0.40, 9),
+ (f4, -0.45, 10),
+ (f4, -0.50, 10),
+ (f4, -0.55, 10),
+ (f5, -0.05, 6),
+ (f5, -0.10, 7),
+ (f5, -0.15, 8),
+ (f5, -0.20, 10),
+ (f5, -0.25, 9),
+ (f5, -0.30, 8),
+ (f5, -0.35, 7),
+ (f5, -0.40, 7),
+ (f5, -0.45, 9),
+ (f5, -0.50, 9),
+ (f5, -0.55, 8)
+]
+
+
+@make_xp_test_case(find_minimum)
+class TestChandrupatlaMinimize:
+
+ def f(self, x, loc):
+ xp = array_namespace(x, loc)
+ res = -xp.exp(-1/2 * (x-loc)**2) / (2*xp.pi)**0.5
+ return xp.asarray(res, dtype=x.dtype)[()]
+
+ @pytest.mark.parametrize('dtype', ('float32', 'float64'))
+ @pytest.mark.parametrize('loc', [0.6, np.linspace(-1.05, 1.05, 10)])
+ def test_basic(self, loc, xp, dtype):
+ # Find mode of normal distribution. Compare mode against location
+ # parameter and value of pdf at mode against expected pdf.
+ rtol = {'float32': 5e-3, 'float64': 5e-7}[dtype]
+ dtype = getattr(xp, dtype)
+ bracket = (xp.asarray(xi, dtype=dtype) for xi in (-5, 0, 5))
+ loc = xp.asarray(loc, dtype=dtype)
+ fun = xp.broadcast_to(xp.asarray(-stats.norm.pdf(0), dtype=dtype), loc.shape)
+
+ res = _chandrupatla_minimize(self.f, *bracket, args=(loc,))
+ xp_assert_close(res.x, loc, rtol=rtol)
+ xp_assert_equal(res.fun, fun)
+
+ @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+ def test_vectorization(self, shape, xp):
+ # Test for correct functionality, output shapes, and dtypes for various
+ # input shapes.
+ loc = xp.linspace(-0.05, 1.05, 12).reshape(shape) if shape else xp.asarray(0.6)
+ args = (loc,)
+ bracket = xp.asarray(-5.), xp.asarray(0.), xp.asarray(5.)
+
+ @_vectorize(xp)
+ def chandrupatla_single(loc_single):
+ return _chandrupatla_minimize(self.f, *bracket, args=(loc_single,))
+
+ def f(*args, **kwargs):
+ f.f_evals += 1
+ return self.f(*args, **kwargs)
+ f.f_evals = 0
+
+ res = _chandrupatla_minimize(f, *bracket, args=args)
+ refs = chandrupatla_single(loc)
+
+ attrs = ['x', 'fun', 'success', 'status', 'nfev', 'nit',
+ 'xl', 'xm', 'xr', 'fl', 'fm', 'fr']
+ for attr in attrs:
+ ref_attr = xp.stack([getattr(ref, attr) for ref in refs])
+ res_attr = xp_ravel(getattr(res, attr))
+ xp_assert_equal(res_attr, ref_attr)
+ assert getattr(res, attr).shape == shape
+
+ xp_assert_equal(res.fun, self.f(res.x, *args))
+ xp_assert_equal(res.fl, self.f(res.xl, *args))
+ xp_assert_equal(res.fm, self.f(res.xm, *args))
+ xp_assert_equal(res.fr, self.f(res.xr, *args))
+ assert xp.max(res.nfev) == f.f_evals
+ assert xp.max(res.nit) == f.f_evals - 3
+
+ assert xp.isdtype(res.success.dtype, 'bool')
+ assert xp.isdtype(res.status.dtype, 'integral')
+ assert xp.isdtype(res.nfev.dtype, 'integral')
+ assert xp.isdtype(res.nit.dtype, 'integral')
+
+
+ def test_flags(self, xp):
+ # Test cases that should produce different status flags; show that all
+ # can be produced simultaneously.
+ def f(xs, js):
+ funcs = [lambda x: (x - 2.5) ** 2,
+ lambda x: x - 10,
+ lambda x: (x - 2.5) ** 4,
+ lambda x: xp.full_like(x, xp.asarray(xp.nan))]
+ res = []
+ for i in range(xp_size(js)):
+ x = xs[i, ...]
+ j = int(xp_ravel(js)[i])
+ res.append(funcs[j](x))
+ return xp.stack(res)
+
+ args = (xp.arange(4, dtype=xp.int64),)
+ bracket = (xp.asarray([0]*4, dtype=xp.float64),
+ xp.asarray([2]*4, dtype=xp.float64),
+ xp.asarray([np.pi]*4, dtype=xp.float64))
+ res = _chandrupatla_minimize(f, *bracket, args=args, maxiter=10)
+
+ ref_flags = xp.asarray([eim._ECONVERGED, eim._ESIGNERR, eim._ECONVERR,
+ eim._EVALUEERR], dtype=xp.int32)
+ xp_assert_equal(res.status, ref_flags)
+
+ def test_convergence(self, xp):
+ # Test that the convergence tolerances behave as expected
+ rng = np.random.default_rng(2585255913088665241)
+ p = xp.asarray(rng.random(size=3))
+ bracket = (xp.asarray(-5, dtype=xp.float64), xp.asarray(0), xp.asarray(5))
+ args = (p,)
+ kwargs0 = dict(args=args, xatol=0, xrtol=0, fatol=0, frtol=0)
+
+ kwargs = kwargs0.copy()
+ kwargs['xatol'] = 1e-3
+ res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ j1 = xp.abs(res1.xr - res1.xl)
+ tol = xp.asarray(4*kwargs['xatol'], dtype=p.dtype)
+ xp_assert_less(j1, xp.full((3,), tol, dtype=p.dtype))
+ kwargs['xatol'] = 1e-6
+ res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ j2 = xp.abs(res2.xr - res2.xl)
+ tol = xp.asarray(4*kwargs['xatol'], dtype=p.dtype)
+ xp_assert_less(j2, xp.full((3,), tol, dtype=p.dtype))
+ xp_assert_less(j2, j1)
+
+ kwargs = kwargs0.copy()
+ kwargs['xrtol'] = 1e-3
+ res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ j1 = xp.abs(res1.xr - res1.xl)
+ tol = xp.asarray(4*kwargs['xrtol']*xp.abs(res1.x), dtype=p.dtype)
+ xp_assert_less(j1, tol)
+ kwargs['xrtol'] = 1e-6
+ res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ j2 = xp.abs(res2.xr - res2.xl)
+ tol = xp.asarray(4*kwargs['xrtol']*xp.abs(res2.x), dtype=p.dtype)
+ xp_assert_less(j2, tol)
+ xp_assert_less(j2, j1)
+
+ kwargs = kwargs0.copy()
+ kwargs['fatol'] = 1e-3
+ res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ h1 = xp.abs(res1.fl - 2 * res1.fm + res1.fr)
+ tol = xp.asarray(2*kwargs['fatol'], dtype=p.dtype)
+ xp_assert_less(h1, xp.full((3,), tol, dtype=p.dtype))
+ kwargs['fatol'] = 1e-6
+ res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ h2 = xp.abs(res2.fl - 2 * res2.fm + res2.fr)
+ tol = xp.asarray(2*kwargs['fatol'], dtype=p.dtype)
+ xp_assert_less(h2, xp.full((3,), tol, dtype=p.dtype))
+ xp_assert_less(h2, h1)
+
+ kwargs = kwargs0.copy()
+ kwargs['frtol'] = 1e-3
+ res1 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ h1 = xp.abs(res1.fl - 2 * res1.fm + res1.fr)
+ tol = xp.asarray(2*kwargs['frtol']*xp.abs(res1.fun), dtype=p.dtype)
+ xp_assert_less(h1, tol)
+ kwargs['frtol'] = 1e-6
+ res2 = _chandrupatla_minimize(self.f, *bracket, **kwargs)
+ h2 = xp.abs(res2.fl - 2 * res2.fm + res2.fr)
+ tol = xp.asarray(2*kwargs['frtol']*abs(res2.fun), dtype=p.dtype)
+ xp_assert_less(h2, tol)
+ xp_assert_less(h2, h1)
+
+ def test_maxiter_callback(self, xp):
+ # Test behavior of `maxiter` parameter and `callback` interface
+ loc = xp.asarray(0.612814)
+ bracket = (xp.asarray(-5), xp.asarray(0), xp.asarray(5))
+ maxiter = 5
+
+ res = _chandrupatla_minimize(self.f, *bracket, args=(loc,),
+ maxiter=maxiter)
+ assert not xp.any(res.success)
+ assert xp.all(res.nfev == maxiter+3)
+ assert xp.all(res.nit == maxiter)
+
+ def callback(res):
+ callback.iter += 1
+ callback.res = res
+ assert hasattr(res, 'x')
+ if callback.iter == 0:
+ # callback is called once with initial bracket
+ assert (res.xl, res.xm, res.xr) == bracket
+ else:
+ changed_xr = (res.xl == callback.xl) & (res.xr != callback.xr)
+ changed_xl = (res.xl != callback.xl) & (res.xr == callback.xr)
+ assert xp.all(changed_xr | changed_xl)
+
+ callback.xl = res.xl
+ callback.xr = res.xr
+ assert res.status == eim._EINPROGRESS
+ xp_assert_equal(self.f(res.xl, loc), res.fl)
+ xp_assert_equal(self.f(res.xm, loc), res.fm)
+ xp_assert_equal(self.f(res.xr, loc), res.fr)
+ xp_assert_equal(self.f(res.x, loc), res.fun)
+ if callback.iter == maxiter:
+ raise StopIteration
+
+ callback.xl = xp.nan
+ callback.xr = xp.nan
+ callback.iter = -1 # callback called once before first iteration
+ callback.res = None
+
+ res2 = _chandrupatla_minimize(self.f, *bracket, args=(loc,),
+ callback=callback)
+
+ # terminating with callback is identical to terminating due to maxiter
+ # (except for `status`)
+ for key in res.keys():
+ if key == 'status':
+ assert res[key] == eim._ECONVERR
+ # assert callback.res[key] == eim._EINPROGRESS
+ assert res2[key] == eim._ECALLBACK
+ else:
+ assert res2[key] == callback.res[key] == res[key]
+
+ @pytest.mark.parametrize('case', cases)
+ def test_nit_expected(self, case, xp):
+ # Test that `_chandrupatla` implements Chandrupatla's algorithm:
+ # in all 55 test cases, the number of iterations performed
+ # matches the number reported in the original paper.
+ func, x1, nit = case
+
+ # Find bracket using the algorithm in the paper
+ step = 0.2
+ x2 = x1 + step
+ x1, x2, x3, f1, f2, f3 = _bracket_minimum(func, x1, x2)
+
+ # Use tolerances from original paper
+ xatol = 0.0001
+ fatol = 0.000001
+ xrtol = 1e-16
+ frtol = 1e-16
+
+ bracket = xp.asarray(x1), xp.asarray(x2), xp.asarray(x3, dtype=xp.float64)
+ res = _chandrupatla_minimize(func, *bracket, xatol=xatol,
+ fatol=fatol, xrtol=xrtol, frtol=frtol)
+ xp_assert_equal(res.nit, xp.asarray(nit, dtype=xp.int32))
+
+ @pytest.mark.parametrize("loc", (0.65, [0.65, 0.7]))
+ @pytest.mark.parametrize("dtype", ('float16', 'float32', 'float64'))
+ def test_dtype(self, loc, dtype, xp):
+ # Test that dtypes are preserved
+ dtype = getattr(xp, dtype)
+
+ loc = xp.asarray(loc, dtype=dtype)
+ bracket = (xp.asarray(-3, dtype=dtype),
+ xp.asarray(1, dtype=dtype),
+ xp.asarray(5, dtype=dtype))
+
+ def f(x, loc):
+ assert x.dtype == dtype
+ return xp.astype((x - loc)**2, dtype)
+
+ res = _chandrupatla_minimize(f, *bracket, args=(loc,))
+ assert res.x.dtype == dtype
+ xp_assert_close(res.x, loc, rtol=math.sqrt(xp.finfo(dtype).eps))
+
+ def test_input_validation(self, xp):
+ # Test input validation for appropriate error messages
+
+ message = '`func` must be callable.'
+ bracket = xp.asarray(-4), xp.asarray(0), xp.asarray(4)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(None, *bracket)
+
+ message = 'Abscissae and function output must be real numbers.'
+ bracket = xp.asarray(-4 + 1j), xp.asarray(0), xp.asarray(4)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket)
+
+ message = "...be broadcast..."
+ bracket = xp.asarray([-2, -3]), xp.asarray([0, 0]), xp.asarray([3, 4, 5])
+ # raised by `np.broadcast, but the traceback is readable IMO
+ with pytest.raises((ValueError, RuntimeError), match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket)
+
+ message = "The shape of the array returned by `func` must be the same"
+ bracket = xp.asarray([-3, -3]), xp.asarray([0, 0]), xp.asarray([5, 5])
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: [x[0, ...], x[1, ...], x[1, ...]],
+ *bracket)
+
+ message = 'Tolerances must be non-negative scalars.'
+ bracket = xp.asarray(-4), xp.asarray(0), xp.asarray(4)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, xatol=-1)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, xrtol=xp.nan)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, fatol='ekki')
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, frtol=xp.nan)
+
+ message = '`maxiter` must be a non-negative integer.'
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, maxiter=1.5)
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, maxiter=-1)
+
+ message = '`callback` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ _chandrupatla_minimize(lambda x: x, *bracket, callback='shrubbery')
+
+ def test_bracket_order(self, xp):
+ # Confirm that order of points in bracket doesn't
+ loc = xp.linspace(-1, 1, 6)[:, xp.newaxis]
+ brackets = xp.asarray(list(permutations([-5, 0, 5]))).T
+ res = _chandrupatla_minimize(self.f, *brackets, args=(loc,))
+ assert xp.all(xpx.isclose(res.x, loc) | (res.fun == self.f(loc, loc)))
+ ref = res.x[:, 0] # all columns should be the same
+ xp_assert_close(*xp.broadcast_arrays(res.x.T, ref), rtol=1e-15)
+
+ def test_special_cases(self, xp):
+ # Test edge cases and other special cases
+
+ # Test that integers are not passed to `f`
+ def f(x):
+ assert xp.isdtype(x.dtype, "real floating")
+ return (x - 1)**2
+
+ bracket = xp.asarray(-7), xp.asarray(0), xp.asarray(8)
+ with np.errstate(invalid='ignore'):
+ res = _chandrupatla_minimize(f, *bracket, fatol=0, frtol=0)
+ assert res.success
+ xp_assert_close(res.x, xp.asarray(1.), rtol=1e-3)
+ xp_assert_close(res.fun, xp.asarray(0.), atol=1e-200)
+
+ # Test that if all elements of bracket equal minimizer, algorithm
+ # reports convergence
+ def f(x):
+ return (x-1)**2
+
+ bracket = xp.asarray(1), xp.asarray(1), xp.asarray(1)
+ res = _chandrupatla_minimize(f, *bracket)
+ assert res.success
+ xp_assert_equal(res.x, xp.asarray(1.))
+
+ # Test maxiter = 0. Should do nothing to bracket.
+ def f(x):
+ return (x-1)**2
+
+ bracket = xp.asarray(-3), xp.asarray(1.1), xp.asarray(5)
+ res = _chandrupatla_minimize(f, *bracket, maxiter=0)
+ assert res.xl, res.xr == bracket
+ assert res.nit == 0
+ assert res.nfev == 3
+ assert res.status == -2
+ assert res.x == 1.1 # best so far
+
+ # Test scalar `args` (not in tuple)
+ def f(x, c):
+ return (x-c)**2 - 1
+
+ bracket = xp.asarray(-1), xp.asarray(0), xp.asarray(1)
+ c = xp.asarray(1/3)
+ res = _chandrupatla_minimize(f, *bracket, args=(c,))
+ xp_assert_close(res.x, c)
+
+ # Test zero tolerances
+ def f(x):
+ return -xp.sin(x)
+
+ bracket = xp.asarray(0), xp.asarray(1), xp.asarray(xp.pi)
+ res = _chandrupatla_minimize(f, *bracket, xatol=0, xrtol=0, fatol=0, frtol=0)
+ assert res.success
+ # found a minimum exactly (according to floating point arithmetic)
+ assert res.xl < res.xm < res.xr
+ assert f(res.xl) == f(res.xm) == f(res.xr)
+
+
+@make_xp_test_case(find_root)
+class TestFindRoot:
+
+ def f(self, q, p):
+ return special.ndtr(q) - p
+
+ @pytest.mark.parametrize('p', [0.6, np.linspace(-0.05, 1.05, 10)])
+ def test_basic(self, p, xp):
+ # Invert distribution CDF and compare against distribution `ppf`
+ a, b = xp.asarray(-5.), xp.asarray(5.)
+ res = find_root(self.f, (a, b), args=(xp.asarray(p),))
+ ref = xp.asarray(stats.norm().ppf(p), dtype=xp.asarray(p).dtype)
+ xp_assert_close(res.x, ref)
+
+ @pytest.mark.parametrize('shape', [tuple(), (12,), (3, 4), (3, 2, 2)])
+ def test_vectorization(self, shape, xp):
+ # Test for correct functionality, output shapes, and dtypes for various
+ # input shapes.
+ p = (np.linspace(-0.05, 1.05, 12).reshape(shape) if shape
+ else np.float64(0.6))
+ p_xp = xp.asarray(p)
+ args_xp = (p_xp,)
+ dtype = p_xp.dtype
+
+ @np.vectorize
+ def find_root_single(p):
+ return find_root(self.f, (-5, 5), args=(p,))
+
+ def f(*args, **kwargs):
+ f.f_evals += 1
+ return self.f(*args, **kwargs)
+ f.f_evals = 0
+
+ bracket = xp.asarray(-5., dtype=xp.float64), xp.asarray(5., dtype=xp.float64)
+ res = find_root(f, bracket, args=args_xp)
+ refs = find_root_single(p).ravel()
+
+ ref_x = [ref.x for ref in refs]
+ ref_x = xp.reshape(xp.asarray(ref_x, dtype=dtype), shape)
+ xp_assert_close(res.x, ref_x)
+
+ ref_f = [ref.f_x for ref in refs]
+ ref_f = xp.reshape(xp.asarray(ref_f, dtype=dtype), shape)
+ xp_assert_close(res.f_x, ref_f, atol=1e-15)
+ xp_assert_equal(res.f_x, self.f(res.x, *args_xp))
+
+ ref_success = [bool(ref.success) for ref in refs]
+ ref_success = xp.reshape(xp.asarray(ref_success, dtype=xp.bool), shape)
+ xp_assert_equal(res.success, ref_success)
+
+ ref_status = [ref.status for ref in refs]
+ ref_status = xp.reshape(xp.asarray(ref_status, dtype=xp.int32), shape)
+ xp_assert_equal(res.status, ref_status)
+
+ ref_nfev = [ref.nfev for ref in refs]
+ ref_nfev = xp.reshape(xp.asarray(ref_nfev, dtype=xp.int32), shape)
+ if is_numpy(xp):
+ xp_assert_equal(res.nfev, ref_nfev)
+ assert xp.max(res.nfev) == f.f_evals
+ else: # different backend may lead to different nfev
+ assert res.nfev.shape == shape
+ assert res.nfev.dtype == xp.int32
+
+ ref_nit = [ref.nit for ref in refs]
+ ref_nit = xp.reshape(xp.asarray(ref_nit, dtype=xp.int32), shape)
+ if is_numpy(xp):
+ xp_assert_equal(res.nit, ref_nit)
+ assert xp.max(res.nit) == f.f_evals-2
+ else:
+ assert res.nit.shape == shape
+ assert res.nit.dtype == xp.int32
+
+ ref_xl = [ref.bracket[0] for ref in refs]
+ ref_xl = xp.reshape(xp.asarray(ref_xl, dtype=dtype), shape)
+ xp_assert_close(res.bracket[0], ref_xl)
+
+ ref_xr = [ref.bracket[1] for ref in refs]
+ ref_xr = xp.reshape(xp.asarray(ref_xr, dtype=dtype), shape)
+ xp_assert_close(res.bracket[1], ref_xr)
+
+ xp_assert_less(res.bracket[0], res.bracket[1])
+ finite = xp.isfinite(res.x)
+ assert xp.all((res.x[finite] == res.bracket[0][finite])
+ | (res.x[finite] == res.bracket[1][finite]))
+
+ # PyTorch and CuPy don't solve to the same accuracy as NumPy - that's OK.
+ atol = 1e-15 if is_numpy(xp) else 1e-9
+
+ ref_fl = [ref.f_bracket[0] for ref in refs]
+ ref_fl = xp.reshape(xp.asarray(ref_fl, dtype=dtype), shape)
+ xp_assert_close(res.f_bracket[0], ref_fl, atol=atol)
+ xp_assert_equal(res.f_bracket[0], self.f(res.bracket[0], *args_xp))
+
+ ref_fr = [ref.f_bracket[1] for ref in refs]
+ ref_fr = xp.reshape(xp.asarray(ref_fr, dtype=dtype), shape)
+ xp_assert_close(res.f_bracket[1], ref_fr, atol=atol)
+ xp_assert_equal(res.f_bracket[1], self.f(res.bracket[1], *args_xp))
+
+ assert xp.all(xp.abs(res.f_x[finite]) ==
+ xp.minimum(xp.abs(res.f_bracket[0][finite]),
+ xp.abs(res.f_bracket[1][finite])))
+
+ def test_flags(self, xp):
+ # Test cases that should produce different status flags; show that all
+ # can be produced simultaneously.
+ def f(xs, js):
+ # Note that full_like and int(j) shouldn't really be required. CuPy
+ # is just really picky here, so I'm making it a special case to
+ # make sure the other backends work when the user is less careful.
+ assert js.dtype == xp.int64
+ if is_cupy(xp):
+ funcs = [lambda x: x - 2.5,
+ lambda x: x - 10,
+ lambda x: (x - 0.1)**3,
+ lambda x: xp.full_like(x, xp.asarray(xp.nan))]
+ return [funcs[int(j)](x) for x, j in zip(xs, js)]
+
+ funcs = [lambda x: x - 2.5,
+ lambda x: x - 10,
+ lambda x: (x - 0.1) ** 3,
+ lambda x: xp.nan]
+ return [funcs[j](x) for x, j in zip(xs, js)]
+
+ args = (xp.arange(4, dtype=xp.int64),)
+ a, b = xp.asarray([0.]*4), xp.asarray([xp.pi]*4)
+ res = find_root(f, (a, b), args=args, maxiter=2)
+
+ ref_flags = xp.asarray([eim._ECONVERGED,
+ eim._ESIGNERR,
+ eim._ECONVERR,
+ eim._EVALUEERR], dtype=xp.int32)
+ xp_assert_equal(res.status, ref_flags)
+
+ def test_convergence(self, xp):
+ # Test that the convergence tolerances behave as expected
+ rng = np.random.default_rng(2585255913088665241)
+ p = xp.asarray(rng.random(size=3))
+ bracket = (-xp.asarray(5.), xp.asarray(5.))
+ args = (p,)
+ kwargs0 = dict(args=args, tolerances=dict(xatol=0, xrtol=0, fatol=0, frtol=0))
+
+ kwargs = deepcopy(kwargs0)
+ kwargs['tolerances']['xatol'] = 1e-3
+ res1 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(res1.bracket[1] - res1.bracket[0],
+ xp.full_like(p, xp.asarray(1e-3)))
+ kwargs['tolerances']['xatol'] = 1e-6
+ res2 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(res2.bracket[1] - res2.bracket[0],
+ xp.full_like(p, xp.asarray(1e-6)))
+ xp_assert_less(res2.bracket[1] - res2.bracket[0],
+ res1.bracket[1] - res1.bracket[0])
+
+ kwargs = deepcopy(kwargs0)
+ kwargs['tolerances']['xrtol'] = 1e-3
+ res1 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(res1.bracket[1] - res1.bracket[0], 1e-3 * xp.abs(res1.x))
+ kwargs['tolerances']['xrtol'] = 1e-6
+ res2 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(res2.bracket[1] - res2.bracket[0],
+ 1e-6 * xp.abs(res2.x))
+ xp_assert_less(res2.bracket[1] - res2.bracket[0],
+ res1.bracket[1] - res1.bracket[0])
+
+ kwargs = deepcopy(kwargs0)
+ kwargs['tolerances']['fatol'] = 1e-3
+ res1 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(xp.abs(res1.f_x), xp.full_like(p, xp.asarray(1e-3)))
+ kwargs['tolerances']['fatol'] = 1e-6
+ res2 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(xp.abs(res2.f_x), xp.full_like(p, xp.asarray(1e-6)))
+ xp_assert_less(xp.abs(res2.f_x), xp.abs(res1.f_x))
+
+ kwargs = deepcopy(kwargs0)
+ kwargs['tolerances']['frtol'] = 1e-3
+ x1, x2 = bracket
+ f0 = xp.minimum(xp.abs(self.f(x1, *args)), xp.abs(self.f(x2, *args)))
+ res1 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(xp.abs(res1.f_x), 1e-3*f0)
+ kwargs['tolerances']['frtol'] = 1e-6
+ res2 = find_root(self.f, bracket, **kwargs)
+ xp_assert_less(xp.abs(res2.f_x), 1e-6*f0)
+ xp_assert_less(xp.abs(res2.f_x), xp.abs(res1.f_x))
+
+ def test_maxiter_callback(self, xp):
+ # Test behavior of `maxiter` parameter and `callback` interface
+ p = xp.asarray(0.612814)
+ bracket = (xp.asarray(-5.), xp.asarray(5.))
+ maxiter = 5
+
+ def f(q, p):
+ res = special.ndtr(q) - p
+ f.x = q
+ f.f_x = res
+ return res
+ f.x = None
+ f.f_x = None
+
+ res = find_root(f, bracket, args=(p,), maxiter=maxiter)
+ assert not xp.any(res.success)
+ assert xp.all(res.nfev == maxiter+2)
+ assert xp.all(res.nit == maxiter)
+
+ def callback(res):
+ callback.iter += 1
+ callback.res = res
+ assert hasattr(res, 'x')
+ if callback.iter == 0:
+ # callback is called once with initial bracket
+ assert (res.bracket[0], res.bracket[1]) == bracket
+ else:
+ changed = (((res.bracket[0] == callback.bracket[0])
+ & (res.bracket[1] != callback.bracket[1]))
+ | ((res.bracket[0] != callback.bracket[0])
+ & (res.bracket[1] == callback.bracket[1])))
+ assert xp.all(changed)
+
+ callback.bracket[0] = res.bracket[0]
+ callback.bracket[1] = res.bracket[1]
+ assert res.status == eim._EINPROGRESS
+ xp_assert_equal(self.f(res.bracket[0], p), res.f_bracket[0])
+ xp_assert_equal(self.f(res.bracket[1], p), res.f_bracket[1])
+ xp_assert_equal(self.f(res.x, p), res.f_x)
+ if callback.iter == maxiter:
+ raise StopIteration
+ callback.iter = -1 # callback called once before first iteration
+ callback.res = None
+ callback.bracket = [None, None]
+
+ res2 = find_root(f, bracket, args=(p,), callback=callback)
+
+ # terminating with callback is identical to terminating due to maxiter
+ # (except for `status`)
+ for key in res.keys():
+ if key == 'status':
+ xp_assert_equal(res[key], xp.asarray(eim._ECONVERR, dtype=xp.int32))
+ xp_assert_equal(res2[key], xp.asarray(eim._ECALLBACK, dtype=xp.int32))
+ elif key in {'bracket', 'f_bracket'}:
+ xp_assert_equal(res2[key][0], res[key][0])
+ xp_assert_equal(res2[key][1], res[key][1])
+ elif key.startswith('_'):
+ continue
+ else:
+ xp_assert_equal(res2[key], res[key])
+
+ @pytest.mark.parametrize('case', _CHANDRUPATLA_TESTS)
+ def test_nit_expected(self, case, xp):
+ # Test that `_chandrupatla` implements Chandrupatla's algorithm:
+ # in all 40 test cases, the number of iterations performed
+ # matches the number reported in the original paper.
+ f, bracket, root, nfeval, id = case
+ # Chandrupatla's criterion is equivalent to
+ # abs(x2-x1) < 4*abs(xmin)*xrtol + xatol, but we use the more standard
+ # abs(x2-x1) < abs(xmin)*xrtol + xatol. Therefore, set xrtol to 4x
+ # that used by Chandrupatla in tests.
+ bracket = (xp.asarray(bracket[0], dtype=xp.float64),
+ xp.asarray(bracket[1], dtype=xp.float64))
+ root = xp.asarray(root, dtype=xp.float64)
+
+ res = find_root(f, bracket, tolerances=dict(xrtol=4e-10, xatol=1e-5))
+ xp_assert_close(res.f_x, xp.asarray(f(root), dtype=xp.float64),
+ rtol=1e-8, atol=2e-3)
+ xp_assert_equal(res.nfev, xp.asarray(nfeval, dtype=xp.int32))
+
+ @pytest.mark.parametrize("root", (0.622, [0.622, 0.623]))
+ @pytest.mark.parametrize("dtype", ('float16', 'float32', 'float64'))
+ def test_dtype(self, root, dtype, xp):
+ # Test that dtypes are preserved
+ not_numpy = not is_numpy(xp)
+ if not_numpy and dtype == 'float16':
+ pytest.skip("`float16` dtype only supported for NumPy arrays.")
+
+ dtype = getattr(xp, dtype, None)
+ if dtype is None:
+ pytest.skip(f"{xp} does not support {dtype}")
+
+ def f(x, root):
+ res = (x - root) ** 3.
+ if is_numpy(xp): # NumPy does not preserve dtype
+ return xp.asarray(res, dtype=dtype)
+ return res
+
+ a, b = xp.asarray(-3, dtype=dtype), xp.asarray(3, dtype=dtype)
+ root = xp.asarray(root, dtype=dtype)
+ res = find_root(f, (a, b), args=(root,), tolerances={'xatol': 1e-3})
+ try:
+ xp_assert_close(res.x, root, atol=1e-3)
+ except AssertionError:
+ assert res.x.dtype == dtype
+ xp.all(res.f_x == 0)
+
+ def test_input_validation(self, xp):
+ # Test input validation for appropriate error messages
+
+ def func(x):
+ return x
+
+ message = '`func` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ bracket = xp.asarray(-4), xp.asarray(4)
+ find_root(None, bracket)
+
+ message = 'Abscissae and function output must be real numbers.'
+ with pytest.raises(ValueError, match=message):
+ bracket = xp.asarray(-4+1j), xp.asarray(4)
+ find_root(func, bracket)
+
+ # raised by `np.broadcast, but the traceback is readable IMO
+ # all messages include this part
+ message = "(not be broadcast|Attempting to broadcast a dimension of length)"
+ with pytest.raises((ValueError, RuntimeError), match=message):
+ bracket = xp.asarray([-2, -3]), xp.asarray([3, 4, 5])
+ find_root(func, bracket)
+
+ message = "The shape of the array returned by `func`..."
+ with pytest.raises(ValueError, match=message):
+ bracket = xp.asarray([-3, -3]), xp.asarray([5, 5])
+ find_root(lambda x: [x[0], x[1], x[1]], bracket)
+
+ message = 'Tolerances must be non-negative scalars.'
+ bracket = xp.asarray(-4), xp.asarray(4)
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, tolerances=dict(xatol=-1))
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, tolerances=dict(xrtol=xp.nan))
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, tolerances=dict(fatol='ekki'))
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, tolerances=dict(frtol=xp.nan))
+
+ message = '`maxiter` must be a non-negative integer.'
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, maxiter=1.5)
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, maxiter=-1)
+
+ message = '`callback` must be callable.'
+ with pytest.raises(ValueError, match=message):
+ find_root(func, bracket, callback='shrubbery')
+
+ def test_special_cases(self, xp):
+ # Test edge cases and other special cases
+
+ # Test infinite function values
+ def f(x):
+ return 1 / x + 1 - 1 / (-x + 1)
+
+ a, b = xp.asarray([0.1, 0., 0., 0.1]), xp.asarray([0.9, 1.0, 0.9, 1.0])
+
+ with np.errstate(divide='ignore', invalid='ignore'):
+ res = find_root(f, (a, b))
+
+ assert xp.all(res.success)
+ xp_assert_close(res.x[1:], xp.full((3,), res.x[0]))
+
+ # Test that integers are not passed to `f`
+ # (otherwise this would overflow)
+ def f(x):
+ assert xp.isdtype(x.dtype, "real floating")
+ # this would overflow if x were an xp integer dtype
+ return x ** 31 - 1
+
+ # note that all inputs are integer type; result is automatically default float
+ res = find_root(f, (xp.asarray(-7), xp.asarray(5)))
+ assert res.success
+ xp_assert_close(res.x, xp.asarray(1.))
+
+ # Test that if both ends of bracket equal root, algorithm reports
+ # convergence.
+ def f(x, root):
+ return x**2 - root
+
+ root = xp.asarray([0, 1])
+ res = find_root(f, (xp.asarray(1), xp.asarray(1)), args=(root,))
+ xp_assert_equal(res.success, xp.asarray([False, True]))
+ xp_assert_equal(res.x, xp.asarray([xp.nan, 1.]))
+
+ def f(x):
+ return 1/x
+
+ with np.errstate(invalid='ignore'):
+ inf = xp.asarray(xp.inf)
+ res = find_root(f, (inf, inf))
+ assert res.success
+ xp_assert_equal(res.x, xp.asarray(xp.inf))
+
+ # Test maxiter = 0. Should do nothing to bracket.
+ def f(x):
+ return x**3 - 1
+
+ a, b = xp.asarray(-3.), xp.asarray(5.)
+ res = find_root(f, (a, b), maxiter=0)
+ xp_assert_equal(res.success, xp.asarray(False))
+ xp_assert_equal(res.status, xp.asarray(-2, dtype=xp.int32))
+ xp_assert_equal(res.nit, xp.asarray(0, dtype=xp.int32))
+ xp_assert_equal(res.nfev, xp.asarray(2, dtype=xp.int32))
+ xp_assert_equal(res.bracket[0], a)
+ xp_assert_equal(res.bracket[1], b)
+ # The `x` attribute is the one with the smaller function value
+ xp_assert_equal(res.x, a)
+ # Reverse bracket; check that this is still true
+ res = find_root(f, (-b, -a), maxiter=0)
+ xp_assert_equal(res.x, -a)
+
+ # Test maxiter = 1
+ res = find_root(f, (a, b), maxiter=1)
+ xp_assert_equal(res.success, xp.asarray(True))
+ xp_assert_equal(res.status, xp.asarray(0, dtype=xp.int32))
+ xp_assert_equal(res.nit, xp.asarray(1, dtype=xp.int32))
+ xp_assert_equal(res.nfev, xp.asarray(3, dtype=xp.int32))
+ xp_assert_close(res.x, xp.asarray(1.))
+
+ # Test scalar `args` (not in tuple)
+ def f(x, c):
+ return c*x - 1
+
+ res = find_root(f, (xp.asarray(-1), xp.asarray(1)), args=xp.asarray(3))
+ xp_assert_close(res.x, xp.asarray(1/3))
+
+ # # TODO: Test zero tolerance
+ # # ~~What's going on here - why are iterations repeated?~~
+ # # tl goes to zero when xatol=xrtol=0. When function is nearly linear,
+ # # this causes convergence issues.
+ # def f(x):
+ # return np.cos(x)
+ #
+ # res = _chandrupatla_root(f, 0, np.pi, xatol=0, xrtol=0)
+ # assert res.nit < 100
+ # xp = np.nextafter(res.x, np.inf)
+ # xm = np.nextafter(res.x, -np.inf)
+ # assert np.abs(res.fun) < np.abs(f(xp))
+ # assert np.abs(res.fun) < np.abs(f(xm))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyla.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyla.py
new file mode 100644
index 0000000000000000000000000000000000000000..0c4c4de8f37367da8c00043cb5f929f368ef6ace
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyla.py
@@ -0,0 +1,195 @@
+import math
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_array_almost_equal
+
+from scipy.optimize import (
+ fmin_cobyla, minimize, Bounds, NonlinearConstraint, LinearConstraint,
+ OptimizeResult
+)
+
+
+class TestCobyla:
+ def setup_method(self):
+ # The algorithm is very fragile on 32 bit, so unfortunately we need to start
+ # very near the solution in order for the test to pass.
+ self.x0 = [np.sqrt(25 - (2.0/3)**2), 2.0/3 + 1e-4]
+ self.solution = [math.sqrt(25 - (2.0/3)**2), 2.0/3]
+ self.opts = {'disp': 0, 'rhobeg': 1, 'tol': 1e-6,
+ 'maxiter': 100}
+
+ def fun(self, x):
+ return x[0]**2 + abs(x[1])**3
+
+ def con1(self, x):
+ return x[0]**2 + x[1]**2 - 25
+
+ def con2(self, x):
+ return -self.con1(x)
+
+ def test_simple(self):
+ # use disp=True as smoke test for gh-8118
+ x = fmin_cobyla(self.fun, self.x0, [self.con1, self.con2], rhobeg=1,
+ rhoend=1e-5, maxfun=100, disp=1)
+ assert_allclose(x, self.solution, atol=1e-4)
+
+ def test_minimize_simple(self):
+ class Callback:
+ def __init__(self):
+ self.n_calls = 0
+ self.last_x = None
+
+ def __call__(self, x):
+ self.n_calls += 1
+ self.last_x = x
+
+ class CallbackNewSyntax:
+ def __init__(self):
+ self.n_calls = 0
+
+ def __call__(self, intermediate_result):
+ assert isinstance(intermediate_result, OptimizeResult)
+ self.n_calls += 1
+
+ callback = Callback()
+ callback_new_syntax = CallbackNewSyntax()
+
+ # Minimize with method='COBYLA'
+ cons = (NonlinearConstraint(self.con1, 0, np.inf),
+ {'type': 'ineq', 'fun': self.con2})
+ sol = minimize(self.fun, self.x0, method='cobyla', constraints=cons,
+ callback=callback, options=self.opts)
+ sol_new = minimize(self.fun, self.x0, method='cobyla', constraints=cons,
+ callback=callback_new_syntax, options=self.opts)
+ assert_allclose(sol.x, self.solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-5, sol
+ assert sol.nfev < 70, sol
+ assert sol.fun < self.fun(self.solution) + 1e-3, sol
+ assert_array_almost_equal(
+ sol.x,
+ callback.last_x,
+ decimal=5,
+ err_msg="Last design vector sent to the callback is not equal to"
+ " returned value.",
+ )
+ assert sol_new.success, sol_new.message
+ assert sol.fun == sol_new.fun
+ assert sol.maxcv == sol_new.maxcv
+ assert sol.nfev == sol_new.nfev
+ assert callback.n_calls == callback_new_syntax.n_calls, \
+ "Callback is not called the same amount of times for old and new syntax."
+
+ def test_minimize_constraint_violation(self):
+ # We set up conflicting constraints so that the algorithm will be
+ # guaranteed to end up with maxcv > 0.
+ cons = ({'type': 'ineq', 'fun': lambda x: 4 - x},
+ {'type': 'ineq', 'fun': lambda x: x - 5})
+ sol = minimize(lambda x: x, [0], method='cobyla', constraints=cons,
+ options={'catol': 0.6})
+ assert sol.maxcv > 0.1
+ assert sol.success
+ sol = minimize(lambda x: x, [0], method='cobyla', constraints=cons,
+ options={'catol': 0.4})
+ assert sol.maxcv > 0.1
+ assert not sol.success
+
+ def test_f_target(self):
+ f_target = 250
+ sol = minimize(lambda x: x**2, [500], method='cobyla',
+ options={'f_target': f_target})
+ assert sol.status == 1
+ assert sol.success
+ assert sol.fun <= f_target
+
+ def test_minimize_linear_constraints(self):
+ constraints = LinearConstraint([1.0, 1.0], 1.0, 1.0)
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyla',
+ constraints=constraints,
+ options=self.opts,
+ )
+ solution = [(4 - np.sqrt(7)) / 3, (np.sqrt(7) - 1) / 3]
+ assert_allclose(sol.x, solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert sol.nfev <= 100, sol
+ assert sol.fun < self.fun(solution) + 1e-3, sol
+
+
+def test_vector_constraints():
+ # test that fmin_cobyla and minimize can take a combination
+ # of constraints, some returning a number and others an array
+ def fun(x):
+ return (x[0] - 1)**2 + (x[1] - 2.5)**2
+
+ def fmin(x):
+ return fun(x) - 1
+
+ def cons1(x):
+ a = np.array([[1, -2, 2], [-1, -2, 6], [-1, 2, 2]])
+ return np.array([a[i, 0] * x[0] + a[i, 1] * x[1] +
+ a[i, 2] for i in range(len(a))])
+
+ def cons2(x):
+ return x # identity, acts as bounds x > 0
+
+ x0 = np.array([2, 0])
+ cons_list = [fun, cons1, cons2]
+
+ xsol = [1.4, 1.7]
+ fsol = 0.8
+
+ # testing fmin_cobyla
+ sol = fmin_cobyla(fun, x0, cons_list, rhoend=1e-5)
+ assert_allclose(sol, xsol, atol=1e-4)
+
+ sol = fmin_cobyla(fun, x0, fmin, rhoend=1e-5)
+ assert_allclose(fun(sol), 1, atol=1e-4)
+
+ # testing minimize
+ constraints = [{'type': 'ineq', 'fun': cons} for cons in cons_list]
+ sol = minimize(fun, x0, constraints=constraints, tol=1e-5)
+ assert_allclose(sol.x, xsol, atol=1e-4)
+ assert sol.success, sol.message
+ assert_allclose(sol.fun, fsol, atol=1e-4)
+
+ constraints = {'type': 'ineq', 'fun': fmin}
+ sol = minimize(fun, x0, constraints=constraints, tol=1e-5)
+ assert_allclose(sol.fun, 1, atol=1e-4)
+
+
+class TestBounds:
+ # Test cobyla support for bounds (only when used via `minimize`)
+ # Invalid bounds is tested in
+ # test_optimize.TestOptimizeSimple.test_minimize_invalid_bounds
+
+ def test_basic(self):
+ def f(x):
+ return np.sum(x**2)
+
+ lb = [-1, None, 1, None, -0.5]
+ ub = [-0.5, -0.5, None, None, -0.5]
+ bounds = [(a, b) for a, b in zip(lb, ub)]
+ # these are converted to Bounds internally
+
+ res = minimize(f, x0=[1, 2, 3, 4, 5], method='cobyla', bounds=bounds)
+ ref = [-0.5, -0.5, 1, 0, -0.5]
+ assert res.success
+ assert_allclose(res.x, ref, atol=1e-3)
+
+ def test_unbounded(self):
+ def f(x):
+ return np.sum(x**2)
+
+ bounds = Bounds([-np.inf, -np.inf], [np.inf, np.inf])
+ res = minimize(f, x0=[1, 2], method='cobyla', bounds=bounds)
+ assert res.success
+ assert_allclose(res.x, 0, atol=1e-3)
+
+ bounds = Bounds([1, -np.inf], [np.inf, np.inf])
+ res = minimize(f, x0=[1, 2], method='cobyla', bounds=bounds)
+ assert res.success
+ assert_allclose(res.x, [1, 0], atol=1e-3)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyqa.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyqa.py
new file mode 100644
index 0000000000000000000000000000000000000000..bf16af71625c4d476353407f9708c981915b098a
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_cobyqa.py
@@ -0,0 +1,252 @@
+import numpy as np
+import pytest
+import threading
+from numpy.testing import assert_allclose, assert_equal
+
+from scipy.optimize import (
+ Bounds,
+ LinearConstraint,
+ NonlinearConstraint,
+ OptimizeResult,
+ minimize,
+)
+
+
+class TestCOBYQA:
+
+ def setup_method(self):
+ self.x0 = [4.95, 0.66]
+ self.options = {'maxfev': 100}
+
+ @staticmethod
+ def fun(x, c=1.0):
+ return x[0]**2 + c * abs(x[1])**3
+
+ @staticmethod
+ def con(x):
+ return x[0]**2 + x[1]**2 - 25.0
+
+ def test_minimize_simple(self):
+ class Callback:
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.n_calls = 0
+
+ def __call__(self, x):
+ assert isinstance(x, np.ndarray)
+ with self.lock:
+ self.n_calls += 1
+
+ class CallbackNewSyntax:
+ def __init__(self):
+ self.lock = threading.Lock()
+ self.n_calls = 0
+
+ def __call__(self, intermediate_result):
+ assert isinstance(intermediate_result, OptimizeResult)
+ with self.lock:
+ self.n_calls += 1
+
+ x0 = [4.95, 0.66]
+ callback = Callback()
+ callback_new_syntax = CallbackNewSyntax()
+
+ # Minimize with method='cobyqa'.
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ sol = minimize(
+ self.fun,
+ x0,
+ method='cobyqa',
+ constraints=constraints,
+ callback=callback,
+ options=self.options,
+ )
+ sol_new = minimize(
+ self.fun,
+ x0,
+ method='cobyqa',
+ constraints=constraints,
+ callback=callback_new_syntax,
+ options=self.options,
+ )
+ solution = [np.sqrt(25.0 - 4.0 / 9.0), 2.0 / 3.0]
+ assert_allclose(sol.x, solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert sol.nfev <= 100, sol
+ assert sol.fun < self.fun(solution) + 1e-3, sol
+ assert sol.nfev == callback.n_calls, \
+ "Callback is not called exactly once for every function eval."
+ assert_equal(sol.x, sol_new.x)
+ assert sol_new.success, sol_new.message
+ assert sol.fun == sol_new.fun
+ assert sol.maxcv == sol_new.maxcv
+ assert sol.nfev == sol_new.nfev
+ assert sol.nit == sol_new.nit
+ assert sol_new.nfev == callback_new_syntax.n_calls, \
+ "Callback is not called exactly once for every function eval."
+
+ def test_minimize_bounds(self):
+ def fun_check_bounds(x):
+ assert np.all(bounds.lb <= x) and np.all(x <= bounds.ub)
+ return self.fun(x)
+
+ # Case where the bounds are not active at the solution.
+ bounds = Bounds([4.5, 0.6], [5.0, 0.7])
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ sol = minimize(
+ fun_check_bounds,
+ self.x0,
+ method='cobyqa',
+ bounds=bounds,
+ constraints=constraints,
+ options=self.options,
+ )
+ solution = [np.sqrt(25.0 - 4.0 / 9.0), 2.0 / 3.0]
+ assert_allclose(sol.x, solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert np.all(bounds.lb <= sol.x) and np.all(sol.x <= bounds.ub), sol
+ assert sol.nfev <= 100, sol
+ assert sol.fun < self.fun(solution) + 1e-3, sol
+
+ # Case where the bounds are active at the solution.
+ bounds = Bounds([5.0, 0.6], [5.5, 0.65])
+ sol = minimize(
+ fun_check_bounds,
+ self.x0,
+ method='cobyqa',
+ bounds=bounds,
+ constraints=constraints,
+ options=self.options,
+ )
+ assert not sol.success, sol.message
+ assert sol.maxcv > 0.35, sol
+ assert np.all(bounds.lb <= sol.x) and np.all(sol.x <= bounds.ub), sol
+ assert sol.nfev <= 100, sol
+
+ def test_minimize_linear_constraints(self):
+ constraints = LinearConstraint([1.0, 1.0], 1.0, 1.0)
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ constraints=constraints,
+ options=self.options,
+ )
+ solution = [(4 - np.sqrt(7)) / 3, (np.sqrt(7) - 1) / 3]
+ assert_allclose(sol.x, solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert sol.nfev <= 100, sol
+ assert sol.fun < self.fun(solution) + 1e-3, sol
+
+ def test_minimize_args(self):
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ sol = minimize(
+ self.fun,
+ self.x0,
+ args=(2.0,),
+ method='cobyqa',
+ constraints=constraints,
+ options=self.options,
+ )
+ solution = [np.sqrt(25.0 - 4.0 / 36.0), 2.0 / 6.0]
+ assert_allclose(sol.x, solution, atol=1e-4)
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert sol.nfev <= 100, sol
+ assert sol.fun < self.fun(solution, 2.0) + 1e-3, sol
+
+ def test_minimize_array(self):
+ def fun_array(x, dim):
+ f = np.array(self.fun(x))
+ return np.reshape(f, (1,) * dim)
+
+ # The argument fun can return an array with a single element.
+ bounds = Bounds([4.5, 0.6], [5.0, 0.7])
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ bounds=bounds,
+ constraints=constraints,
+ options=self.options,
+ )
+ for dim in [0, 1, 2]:
+ sol_array = minimize(
+ fun_array,
+ self.x0,
+ args=(dim,),
+ method='cobyqa',
+ bounds=bounds,
+ constraints=constraints,
+ options=self.options,
+ )
+ assert_equal(sol.x, sol_array.x)
+ assert sol_array.success, sol_array.message
+ assert sol.fun == sol_array.fun
+ assert sol.maxcv == sol_array.maxcv
+ assert sol.nfev == sol_array.nfev
+ assert sol.nit == sol_array.nit
+
+ # The argument fun cannot return an array with more than one element.
+ with pytest.raises(TypeError):
+ minimize(
+ lambda x: np.array([self.fun(x), self.fun(x)]),
+ self.x0,
+ method='cobyqa',
+ bounds=bounds,
+ constraints=constraints,
+ options=self.options,
+ )
+
+ def test_minimize_maxfev(self):
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ options = {'maxfev': 2}
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ constraints=constraints,
+ options=options,
+ )
+ assert not sol.success, sol.message
+ assert sol.nfev <= 2, sol
+
+ def test_minimize_maxiter(self):
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ options = {'maxiter': 2}
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ constraints=constraints,
+ options=options,
+ )
+ assert not sol.success, sol.message
+ assert sol.nit <= 2, sol
+
+ def test_minimize_f_target(self):
+ constraints = NonlinearConstraint(self.con, 0.0, 0.0)
+ sol_ref = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ constraints=constraints,
+ options=self.options,
+ )
+ options = dict(self.options)
+ options['f_target'] = sol_ref.fun
+ sol = minimize(
+ self.fun,
+ self.x0,
+ method='cobyqa',
+ constraints=constraints,
+ options=options,
+ )
+ assert sol.success, sol.message
+ assert sol.maxcv < 1e-8, sol
+ assert sol.nfev <= sol_ref.nfev, sol
+ assert sol.fun <= sol_ref.fun, sol
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_constraint_conversion.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_constraint_conversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..80453fe497968db39031695462b9ee3301da7e2e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_constraint_conversion.py
@@ -0,0 +1,284 @@
+"""
+Unit test for constraint conversion
+"""
+import warnings
+
+import numpy as np
+from numpy.testing import (assert_array_almost_equal,
+ assert_allclose)
+import pytest
+from scipy.optimize import (NonlinearConstraint, LinearConstraint,
+ OptimizeWarning, minimize, BFGS)
+from .test_minimize_constrained import (Maratos, HyperbolicIneq, Rosenbrock,
+ IneqRosenbrock, EqIneqRosenbrock,
+ BoundedRosenbrock, Elec)
+
+
+class TestOldToNew:
+ x0 = (2, 0)
+ bnds = ((0, None), (0, None))
+ method = "trust-constr"
+
+ def test_constraint_dictionary_1(self):
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2
+ cons = ({'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},
+ {'type': 'ineq', 'fun': lambda x: -x[0] - 2 * x[1] + 6},
+ {'type': 'ineq', 'fun': lambda x: -x[0] + 2 * x[1] + 2})
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ res = minimize(fun, self.x0, method=self.method,
+ bounds=self.bnds, constraints=cons)
+ assert_allclose(res.x, [1.4, 1.7], rtol=1e-4)
+ assert_allclose(res.fun, 0.8, rtol=1e-4)
+
+ def test_constraint_dictionary_2(self):
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2
+ cons = {'type': 'eq',
+ 'fun': lambda x, p1, p2: p1*x[0] - p2*x[1],
+ 'args': (1, 1.1),
+ 'jac': lambda x, p1, p2: np.array([[p1, -p2]])}
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ res = minimize(fun, self.x0, method=self.method,
+ bounds=self.bnds, constraints=cons)
+ assert_allclose(res.x, [1.7918552, 1.62895927])
+ assert_allclose(res.fun, 1.3857466063348418)
+
+ def test_constraint_dictionary_3(self):
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2
+ cons = [{'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},
+ NonlinearConstraint(lambda x: x[0] - x[1], 0, 0)]
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ res = minimize(fun, self.x0, method=self.method,
+ bounds=self.bnds, constraints=cons)
+ assert_allclose(res.x, [1.75, 1.75], rtol=1e-4)
+ assert_allclose(res.fun, 1.125, rtol=1e-4)
+
+
+class TestNewToOld:
+ @pytest.mark.fail_slow(2)
+ def test_multiple_constraint_objects(self):
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2
+ x0 = [2, 0, 1]
+ coni = [] # only inequality constraints (can use cobyla)
+ methods = ["slsqp", "cobyla", "cobyqa", "trust-constr"]
+
+ # mixed old and new
+ coni.append([{'type': 'ineq', 'fun': lambda x: x[0] - 2 * x[1] + 2},
+ NonlinearConstraint(lambda x: x[0] - x[1], -1, 1)])
+
+ coni.append([LinearConstraint([1, -2, 0], -2, np.inf),
+ NonlinearConstraint(lambda x: x[0] - x[1], -1, 1)])
+
+ coni.append([NonlinearConstraint(lambda x: x[0] - 2 * x[1] + 2, 0, np.inf),
+ NonlinearConstraint(lambda x: x[0] - x[1], -1, 1)])
+
+ for con in coni:
+ funs = {}
+ for method in methods:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ result = minimize(fun, x0, method=method, constraints=con)
+ funs[method] = result.fun
+ assert_allclose(funs['slsqp'], funs['trust-constr'], rtol=1e-4)
+ assert_allclose(funs['cobyla'], funs['trust-constr'], rtol=1e-4)
+ assert_allclose(funs['cobyqa'], funs['trust-constr'],
+ rtol=1e-4)
+
+ @pytest.mark.fail_slow(20)
+ def test_individual_constraint_objects(self):
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2
+ x0 = [2, 0, 1]
+
+ cone = [] # with equality constraints (can't use cobyla)
+ coni = [] # only inequality constraints (can use cobyla)
+ methods = ["slsqp", "cobyla", "cobyqa", "trust-constr"]
+
+ # nonstandard data types for constraint equality bounds
+ cone.append(NonlinearConstraint(lambda x: x[0] - x[1], 1, 1))
+ cone.append(NonlinearConstraint(lambda x: x[0] - x[1], [1.21], [1.21]))
+ cone.append(NonlinearConstraint(lambda x: x[0] - x[1],
+ 1.21, np.array([1.21])))
+
+ # multiple equalities
+ cone.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ 1.21, 1.21)) # two same equalities
+ cone.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [1.21, 1.4], [1.21, 1.4])) # two different equalities
+ cone.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [1.21, 1.21], 1.21)) # equality specified two ways
+ cone.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [1.21, -np.inf], [1.21, np.inf])) # equality + unbounded
+
+ # nonstandard data types for constraint inequality bounds
+ coni.append(NonlinearConstraint(lambda x: x[0] - x[1], 1.21, np.inf))
+ coni.append(NonlinearConstraint(lambda x: x[0] - x[1], [1.21], np.inf))
+ coni.append(NonlinearConstraint(lambda x: x[0] - x[1],
+ 1.21, np.array([np.inf])))
+ coni.append(NonlinearConstraint(lambda x: x[0] - x[1], -np.inf, -3))
+ coni.append(NonlinearConstraint(lambda x: x[0] - x[1],
+ np.array(-np.inf), -3))
+
+ # multiple inequalities/equalities
+ coni.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ 1.21, np.inf)) # two same inequalities
+ cone.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [1.21, -np.inf], [1.21, 1.4])) # mixed equality/inequality
+ coni.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [1.1, .8], [1.2, 1.4])) # bounded above and below
+ coni.append(NonlinearConstraint(
+ lambda x: [x[0] - x[1], x[1] - x[2]],
+ [-1.2, -1.4], [-1.1, -.8])) # - bounded above and below
+
+ # quick check of LinearConstraint class (very little new code to test)
+ cone.append(LinearConstraint([1, -1, 0], 1.21, 1.21))
+ cone.append(LinearConstraint([[1, -1, 0], [0, 1, -1]], 1.21, 1.21))
+ cone.append(LinearConstraint([[1, -1, 0], [0, 1, -1]],
+ [1.21, -np.inf], [1.21, 1.4]))
+
+ for con in coni:
+ funs = {}
+ for method in methods:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ result = minimize(fun, x0, method=method, constraints=con)
+ funs[method] = result.fun
+ assert_allclose(funs['slsqp'], funs['trust-constr'], rtol=1e-3)
+ assert_allclose(funs['cobyla'], funs['trust-constr'], rtol=1e-3)
+ assert_allclose(funs['cobyqa'], funs['trust-constr'],
+ rtol=1e-3)
+
+ for con in cone:
+ funs = {}
+ for method in [method for method in methods if method != 'cobyla']:
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ result = minimize(fun, x0, method=method, constraints=con)
+ funs[method] = result.fun
+ assert_allclose(funs['slsqp'], funs['trust-constr'], rtol=1e-3)
+ assert_allclose(funs['cobyqa'], funs['trust-constr'],
+ rtol=1e-3)
+
+
+class TestNewToOldSLSQP:
+ method = 'slsqp'
+ elec = Elec(n_electrons=2)
+ elec.x_opt = np.array([-0.58438468, 0.58438466, 0.73597047,
+ -0.73597044, 0.34180668, -0.34180667])
+ brock = BoundedRosenbrock()
+ brock.x_opt = [0, 0]
+ list_of_problems = [Maratos(),
+ HyperbolicIneq(),
+ Rosenbrock(),
+ IneqRosenbrock(),
+ EqIneqRosenbrock(),
+ elec,
+ brock
+ ]
+
+ def test_list_of_problems(self):
+
+ for prob in self.list_of_problems:
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ result = minimize(prob.fun, prob.x0,
+ method=self.method,
+ bounds=prob.bounds,
+ constraints=prob.constr)
+
+ assert_array_almost_equal(result.x, prob.x_opt, decimal=3)
+
+ def test_warn_mixed_constraints(self):
+ # warns about inefficiency of mixed equality/inequality constraints
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2
+ cons = NonlinearConstraint(lambda x: [x[0]**2 - x[1], x[1] - x[2]],
+ [1.1, .8], [1.1, 1.4])
+ bnds = ((0, None), (0, None), (0, None))
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ with pytest.warns(OptimizeWarning):
+ minimize(fun, (2, 0, 1),
+ method=self.method, bounds=bnds, constraints=cons)
+
+ def test_warn_ignored_options(self):
+ # warns about constraint options being ignored
+ def fun(x):
+ return (x[0] - 1) ** 2 + (x[1] - 2.5) ** 2 + (x[2] - 0.75) ** 2
+ x0 = (2, 0, 1)
+
+ if self.method == "slsqp":
+ bnds = ((0, None), (0, None), (0, None))
+ else:
+ bnds = None
+
+ cons = NonlinearConstraint(lambda x: x[0], 2, np.inf)
+ res = minimize(fun, x0, method=self.method,
+ bounds=bnds, constraints=cons)
+ # no warnings without constraint options
+ assert_allclose(res.fun, 1)
+
+ cons = LinearConstraint([1, 0, 0], 2, np.inf)
+ res = minimize(fun, x0, method=self.method,
+ bounds=bnds, constraints=cons)
+ # no warnings without constraint options
+ assert_allclose(res.fun, 1)
+
+ cons = []
+ cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf,
+ keep_feasible=True))
+ cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf,
+ hess=BFGS()))
+ cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf,
+ finite_diff_jac_sparsity=42))
+ cons.append(NonlinearConstraint(lambda x: x[0]**2, 2, np.inf,
+ finite_diff_rel_step=42))
+ cons.append(LinearConstraint([1, 0, 0], 2, np.inf,
+ keep_feasible=True))
+ for con in cons:
+ with pytest.warns(OptimizeWarning):
+ minimize(fun, x0,
+ method=self.method, bounds=bnds, constraints=cons)
+
+
+class TestNewToOldCobyla:
+ method = 'cobyla'
+
+ list_of_problems = [
+ Elec(n_electrons=2),
+ Elec(n_electrons=4),
+ ]
+
+ @pytest.mark.slow
+ def test_list_of_problems(self):
+
+ for prob in self.list_of_problems:
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ truth = minimize(prob.fun, prob.x0,
+ method='trust-constr',
+ bounds=prob.bounds,
+ constraints=prob.constr)
+ result = minimize(prob.fun, prob.x0,
+ method=self.method,
+ bounds=prob.bounds,
+ constraints=prob.constr)
+
+ assert_allclose(result.fun, truth.fun, rtol=1e-3)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_constraints.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_constraints.py
new file mode 100644
index 0000000000000000000000000000000000000000..1bc986e0ea2bf2154204de06594e67539fe0cdb6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_constraints.py
@@ -0,0 +1,255 @@
+import pytest
+import numpy as np
+from numpy.testing import TestCase, assert_array_equal
+import scipy.sparse as sps
+from scipy.optimize._constraints import (
+ Bounds, LinearConstraint, NonlinearConstraint, PreparedConstraint,
+ new_bounds_to_old, old_bound_to_new, strict_bounds)
+
+
+class TestStrictBounds(TestCase):
+ def test_scalarvalue_unique_enforce_feasibility(self):
+ m = 3
+ lb = 2
+ ub = 4
+ enforce_feasibility = False
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [-np.inf, -np.inf, -np.inf])
+ assert_array_equal(strict_ub, [np.inf, np.inf, np.inf])
+
+ enforce_feasibility = True
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [2, 2, 2])
+ assert_array_equal(strict_ub, [4, 4, 4])
+
+ def test_vectorvalue_unique_enforce_feasibility(self):
+ m = 3
+ lb = [1, 2, 3]
+ ub = [4, 5, 6]
+ enforce_feasibility = False
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [-np.inf, -np.inf, -np.inf])
+ assert_array_equal(strict_ub, [np.inf, np.inf, np.inf])
+
+ enforce_feasibility = True
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [1, 2, 3])
+ assert_array_equal(strict_ub, [4, 5, 6])
+
+ def test_scalarvalue_vector_enforce_feasibility(self):
+ m = 3
+ lb = 2
+ ub = 4
+ enforce_feasibility = [False, True, False]
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [-np.inf, 2, -np.inf])
+ assert_array_equal(strict_ub, [np.inf, 4, np.inf])
+
+ def test_vectorvalue_vector_enforce_feasibility(self):
+ m = 3
+ lb = [1, 2, 3]
+ ub = [4, 6, np.inf]
+ enforce_feasibility = [True, False, True]
+ strict_lb, strict_ub = strict_bounds(lb, ub,
+ enforce_feasibility,
+ m)
+ assert_array_equal(strict_lb, [1, -np.inf, 3])
+ assert_array_equal(strict_ub, [4, np.inf, np.inf])
+
+
+def test_prepare_constraint_infeasible_x0():
+ lb = np.array([0, 20, 30])
+ ub = np.array([0.5, np.inf, 70])
+ x0 = np.array([1, 2, 3])
+ enforce_feasibility = np.array([False, True, True], dtype=bool)
+ bounds = Bounds(lb, ub, enforce_feasibility)
+ pytest.raises(ValueError, PreparedConstraint, bounds, x0)
+
+ pc = PreparedConstraint(Bounds(lb, ub), [1, 2, 3])
+ assert (pc.violation([1, 2, 3]) > 0).any()
+ assert (pc.violation([0.25, 21, 31]) == 0).all()
+
+ x0 = np.array([1, 2, 3, 4])
+ A = np.array([[1, 2, 3, 4], [5, 0, 0, 6], [7, 0, 8, 0]])
+ enforce_feasibility = np.array([True, True, True], dtype=bool)
+ linear = LinearConstraint(A, -np.inf, 0, enforce_feasibility)
+ pytest.raises(ValueError, PreparedConstraint, linear, x0)
+
+ pc = PreparedConstraint(LinearConstraint(A, -np.inf, 0),
+ [1, 2, 3, 4])
+ assert (pc.violation([1, 2, 3, 4]) > 0).any()
+ assert (pc.violation([-10, 2, -10, 4]) == 0).all()
+
+ def fun(x):
+ return A.dot(x)
+
+ def jac(x):
+ return A
+
+ def hess(x, v):
+ return sps.csr_array((4, 4))
+
+ nonlinear = NonlinearConstraint(fun, -np.inf, 0, jac, hess,
+ enforce_feasibility)
+ pytest.raises(ValueError, PreparedConstraint, nonlinear, x0)
+
+ pc = PreparedConstraint(nonlinear, [-10, 2, -10, 4])
+ assert (pc.violation([1, 2, 3, 4]) > 0).any()
+ assert (pc.violation([-10, 2, -10, 4]) == 0).all()
+
+
+def test_violation():
+ def cons_f(x):
+ return np.array([x[0] ** 2 + x[1], x[0] ** 2 - x[1]])
+
+ nlc = NonlinearConstraint(cons_f, [-1, -0.8500], [2, 2])
+ pc = PreparedConstraint(nlc, [0.5, 1])
+
+ assert_array_equal(pc.violation([0.5, 1]), [0., 0.])
+
+ np.testing.assert_almost_equal(pc.violation([0.5, 1.2]), [0., 0.1])
+
+ np.testing.assert_almost_equal(pc.violation([1.2, 1.2]), [0.64, 0])
+
+ np.testing.assert_almost_equal(pc.violation([0.1, -1.2]), [0.19, 0])
+
+ np.testing.assert_almost_equal(pc.violation([0.1, 2]), [0.01, 1.14])
+
+
+def test_new_bounds_to_old():
+ lb = np.array([-np.inf, 2, 3])
+ ub = np.array([3, np.inf, 10])
+
+ bounds = [(None, 3), (2, None), (3, 10)]
+ assert_array_equal(new_bounds_to_old(lb, ub, 3), bounds)
+
+ bounds_single_lb = [(-1, 3), (-1, None), (-1, 10)]
+ assert_array_equal(new_bounds_to_old(-1, ub, 3), bounds_single_lb)
+
+ bounds_no_lb = [(None, 3), (None, None), (None, 10)]
+ assert_array_equal(new_bounds_to_old(-np.inf, ub, 3), bounds_no_lb)
+
+ bounds_single_ub = [(None, 20), (2, 20), (3, 20)]
+ assert_array_equal(new_bounds_to_old(lb, 20, 3), bounds_single_ub)
+
+ bounds_no_ub = [(None, None), (2, None), (3, None)]
+ assert_array_equal(new_bounds_to_old(lb, np.inf, 3), bounds_no_ub)
+
+ bounds_single_both = [(1, 2), (1, 2), (1, 2)]
+ assert_array_equal(new_bounds_to_old(1, 2, 3), bounds_single_both)
+
+ bounds_no_both = [(None, None), (None, None), (None, None)]
+ assert_array_equal(new_bounds_to_old(-np.inf, np.inf, 3), bounds_no_both)
+
+
+def test_old_bounds_to_new():
+ bounds = ([1, 2], (None, 3), (-1, None))
+ lb_true = np.array([1, -np.inf, -1])
+ ub_true = np.array([2, 3, np.inf])
+
+ lb, ub = old_bound_to_new(bounds)
+ assert_array_equal(lb, lb_true)
+ assert_array_equal(ub, ub_true)
+
+ bounds = [(-np.inf, np.inf), (np.array([1]), np.array([1]))]
+ lb, ub = old_bound_to_new(bounds)
+
+ assert_array_equal(lb, [-np.inf, 1])
+ assert_array_equal(ub, [np.inf, 1])
+
+
+class TestBounds:
+ def test_repr(self):
+ # so that eval works
+ from numpy import array, inf # noqa: F401
+ for args in (
+ (-1.0, 5.0),
+ (-1.0, np.inf, True),
+ (np.array([1.0, -np.inf]), np.array([2.0, np.inf])),
+ (np.array([1.0, -np.inf]), np.array([2.0, np.inf]),
+ np.array([True, False])),
+ ):
+ bounds = Bounds(*args)
+ bounds2 = eval(repr(Bounds(*args)))
+ assert_array_equal(bounds.lb, bounds2.lb)
+ assert_array_equal(bounds.ub, bounds2.ub)
+ assert_array_equal(bounds.keep_feasible, bounds2.keep_feasible)
+
+ def test_array(self):
+ # gh13501
+ b = Bounds(lb=[0.0, 0.0], ub=[1.0, 1.0])
+ assert isinstance(b.lb, np.ndarray)
+ assert isinstance(b.ub, np.ndarray)
+
+ def test_defaults(self):
+ b1 = Bounds()
+ b2 = Bounds(np.asarray(-np.inf), np.asarray(np.inf))
+ assert b1.lb == b2.lb
+ assert b1.ub == b2.ub
+
+ def test_input_validation(self):
+ message = "Lower and upper bounds must be dense arrays."
+ with pytest.raises(ValueError, match=message):
+ Bounds(sps.coo_array([1, 2]), [1, 2])
+ with pytest.raises(ValueError, match=message):
+ Bounds([1, 2], sps.coo_array([1, 2]))
+
+ message = "`keep_feasible` must be a dense array."
+ with pytest.raises(ValueError, match=message):
+ Bounds([1, 2], [1, 2], keep_feasible=sps.coo_array([True, True]))
+
+ message = "`lb`, `ub`, and `keep_feasible` must be broadcastable."
+ with pytest.raises(ValueError, match=message):
+ Bounds([1, 2], [1, 2, 3])
+
+ def test_residual(self):
+ bounds = Bounds(-2, 4)
+ x0 = [-1, 2]
+ np.testing.assert_allclose(bounds.residual(x0), ([1, 4], [5, 2]))
+
+
+class TestLinearConstraint:
+ def test_defaults(self):
+ A = np.eye(4)
+ lc = LinearConstraint(A)
+ lc2 = LinearConstraint(A, -np.inf, np.inf)
+ assert_array_equal(lc.lb, lc2.lb)
+ assert_array_equal(lc.ub, lc2.ub)
+
+ def test_input_validation(self):
+ A = np.eye(4)
+ message = "`lb`, `ub`, and `keep_feasible` must be broadcastable"
+ with pytest.raises(ValueError, match=message):
+ LinearConstraint(A, [1, 2], [1, 2, 3])
+
+ message = "Constraint limits must be dense arrays"
+ with pytest.raises(ValueError, match=message):
+ LinearConstraint(A, sps.coo_array([1, 2]), [2, 3])
+ with pytest.raises(ValueError, match=message):
+ LinearConstraint(A, [1, 2], sps.coo_array([2, 3]))
+
+ message = "`keep_feasible` must be a dense array"
+ with pytest.raises(ValueError, match=message):
+ keep_feasible = sps.coo_array([True, True])
+ LinearConstraint(A, [1, 2], [2, 3], keep_feasible=keep_feasible)
+
+ A = np.empty((4, 3, 5))
+ message = "`A` must have exactly two dimensions."
+ with pytest.raises(ValueError, match=message):
+ LinearConstraint(A)
+
+ def test_residual(self):
+ A = np.eye(2)
+ lc = LinearConstraint(A, -2, 4)
+ x0 = [-1, 2]
+ np.testing.assert_allclose(lc.residual(x0), ([1, 4], [5, 2]))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_cython_optimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_cython_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..2f859c1143eb6b63c439fe278bfdd4fdaa15410f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_cython_optimize.py
@@ -0,0 +1,92 @@
+"""
+Test Cython optimize zeros API functions: ``bisect``, ``ridder``, ``brenth``,
+and ``brentq`` in `scipy.optimize.cython_optimize`, by finding the roots of a
+3rd order polynomial given a sequence of constant terms, ``a0``, and fixed 1st,
+2nd, and 3rd order terms in ``args``.
+
+.. math::
+
+ f(x, a0, args) = ((args[2]*x + args[1])*x + args[0])*x + a0
+
+The 3rd order polynomial function is written in Cython and called in a Python
+wrapper named after the zero function. See the private ``_zeros`` Cython module
+in `scipy.optimize.cython_optimze` for more information.
+"""
+
+import numpy.testing as npt
+from scipy.optimize.cython_optimize import _zeros
+
+# CONSTANTS
+# Solve x**3 - A0 = 0 for A0 = [2.0, 2.1, ..., 2.9].
+# The ARGS have 3 elements just to show how this could be done for any cubic
+# polynomial.
+A0 = tuple(-2.0 - x/10.0 for x in range(10)) # constant term
+ARGS = (0.0, 0.0, 1.0) # 1st, 2nd, and 3rd order terms
+XLO, XHI = 0.0, 2.0 # first and second bounds of zeros functions
+# absolute and relative tolerances and max iterations for zeros functions
+XTOL, RTOL, MITR = 0.001, 0.001, 10
+EXPECTED = [(-a0) ** (1.0/3.0) for a0 in A0]
+# = [1.2599210498948732,
+# 1.2805791649874942,
+# 1.300591446851387,
+# 1.3200061217959123,
+# 1.338865900164339,
+# 1.3572088082974532,
+# 1.375068867074141,
+# 1.3924766500838337,
+# 1.4094597464129783,
+# 1.4260431471424087]
+
+
+# test bisect
+def test_bisect():
+ npt.assert_allclose(
+ EXPECTED,
+ list(
+ _zeros.loop_example('bisect', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR)
+ ),
+ rtol=RTOL, atol=XTOL
+ )
+
+
+# test ridder
+def test_ridder():
+ npt.assert_allclose(
+ EXPECTED,
+ list(
+ _zeros.loop_example('ridder', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR)
+ ),
+ rtol=RTOL, atol=XTOL
+ )
+
+
+# test brenth
+def test_brenth():
+ npt.assert_allclose(
+ EXPECTED,
+ list(
+ _zeros.loop_example('brenth', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR)
+ ),
+ rtol=RTOL, atol=XTOL
+ )
+
+
+# test brentq
+def test_brentq():
+ npt.assert_allclose(
+ EXPECTED,
+ list(
+ _zeros.loop_example('brentq', A0, ARGS, XLO, XHI, XTOL, RTOL, MITR)
+ ),
+ rtol=RTOL, atol=XTOL
+ )
+
+
+# test brentq with full output
+def test_brentq_full_output():
+ output = _zeros.full_output_example(
+ (A0[0],) + ARGS, XLO, XHI, XTOL, RTOL, MITR)
+ npt.assert_allclose(EXPECTED[0], output['root'], rtol=RTOL, atol=XTOL)
+ npt.assert_equal(6, output['iterations'])
+ npt.assert_equal(7, output['funcalls'])
+ npt.assert_equal(0, output['error_num'])
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_differentiable_functions.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_differentiable_functions.py
new file mode 100644
index 0000000000000000000000000000000000000000..45ea942e3ab2aa6ec4580125543e45c315db8336
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_differentiable_functions.py
@@ -0,0 +1,1023 @@
+import pytest
+import platform
+import numpy as np
+from numpy.testing import (TestCase, assert_array_almost_equal,
+ assert_array_equal, assert_, assert_allclose,
+ assert_equal)
+from scipy._lib._gcutils import assert_deallocated
+from scipy._lib._util import MapWrapper
+from scipy.sparse import csr_array
+from scipy.sparse.linalg import LinearOperator
+from scipy.optimize._differentiable_functions import (ScalarFunction,
+ VectorFunction,
+ LinearVectorFunction,
+ IdentityVectorFunction)
+from scipy.optimize import rosen, rosen_der, rosen_hess
+from scipy.optimize._hessian_update_strategy import BFGS
+
+
+class ExScalarFunction:
+
+ def __init__(self):
+ self.nfev = 0
+ self.ngev = 0
+ self.nhev = 0
+
+ def fun(self, x):
+ self.nfev += 1
+ return 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+
+ def grad(self, x):
+ self.ngev += 1
+ return np.array([4*x[0]-1, 4*x[1]])
+
+ def hess(self, x):
+ self.nhev += 1
+ return 4*np.eye(2)
+
+
+class TestScalarFunction(TestCase):
+
+ def test_finite_difference_grad(self):
+ ex = ExScalarFunction()
+ nfev = 0
+ ngev = 0
+
+ x0 = [1.0, 0.0]
+ analit = ScalarFunction(ex.fun, x0, (), ex.grad,
+ ex.hess, None, (-np.inf, np.inf))
+ nfev += 1
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev, nfev)
+ approx = ScalarFunction(ex.fun, x0, (), '2-point',
+ ex.hess, None, (-np.inf, np.inf))
+ nfev += 3
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(analit.f, approx.f)
+ assert_array_almost_equal(analit.g, approx.g)
+
+ x = [10, 0.3]
+ f_analit = analit.fun(x)
+ g_analit = analit.grad(x)
+ nfev += 1
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ f_approx = approx.fun(x)
+ g_approx = approx.grad(x)
+ nfev += 3
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(g_analit, g_approx)
+
+ x = [2.0, 1.0]
+ g_analit = analit.grad(x)
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+
+ g_approx = approx.grad(x)
+ nfev += 3
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_almost_equal(g_analit, g_approx)
+
+ x = [2.5, 0.3]
+ f_analit = analit.fun(x)
+ g_analit = analit.grad(x)
+ nfev += 1
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ f_approx = approx.fun(x)
+ g_approx = approx.grad(x)
+ nfev += 3
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(g_analit, g_approx)
+
+ x = [2, 0.3]
+ f_analit = analit.fun(x)
+ g_analit = analit.grad(x)
+ nfev += 1
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ f_approx = approx.fun(x)
+ g_approx = approx.grad(x)
+ nfev += 3
+ ngev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(g_analit, g_approx)
+
+ @pytest.mark.fail_slow(5.0)
+ def test_workers(self):
+ x0 = np.array([2.0, 0.3])
+ ex = ExScalarFunction()
+ ex2 = ExScalarFunction()
+ with MapWrapper(2) as mapper:
+ approx = ScalarFunction(ex.fun, x0, (), '2-point',
+ ex.hess, None, (-np.inf, np.inf),
+ workers=mapper)
+ approx_series = ScalarFunction(ex2.fun, x0, (), '2-point',
+ ex2.hess, None, (-np.inf, np.inf),
+ )
+ assert_allclose(approx.grad(x0), ex.grad(x0))
+ assert_allclose(approx_series.grad(x0), ex.grad(x0))
+ assert_allclose(approx_series.hess(x0), ex.hess(x0))
+ assert_allclose(approx.hess(x0), ex.hess(x0))
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.ngev, approx_series.ngev)
+ assert_equal(approx.nhev, approx_series.nhev)
+ assert_equal(approx_series.nhev, ex2.nhev)
+
+ ex = ExScalarFunction()
+ ex2 = ExScalarFunction()
+ approx = ScalarFunction(ex.fun, x0, (), '3-point',
+ ex.hess, None, (-np.inf, np.inf),
+ workers=mapper)
+ approx_series = ScalarFunction(ex2.fun, x0, (), '3-point',
+ ex2.hess, None, (-np.inf, np.inf),
+ )
+ assert_allclose(approx.grad(x0), ex.grad(x0))
+ assert_allclose(approx_series.grad(x0), ex.grad(x0))
+ assert_allclose(approx_series.hess(x0), ex.hess(x0))
+ assert_allclose(approx.hess(x0), ex.hess(x0))
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.ngev, approx_series.ngev)
+ assert_equal(approx.nhev, approx_series.nhev)
+ assert_equal(approx_series.nhev, ex2.nhev)
+
+ ex = ExScalarFunction()
+ ex2 = ExScalarFunction()
+ x1 = np.array([3.0, 4.0])
+
+ approx = ScalarFunction(ex.fun, x0, (), ex.grad,
+ '3-point', None, (-np.inf, np.inf),
+ workers=mapper)
+ approx_series = ScalarFunction(ex2.fun, x0, (), ex2.grad,
+ '3-point', None, (-np.inf, np.inf),
+ )
+ assert_allclose(approx.grad(x1), ex.grad(x1))
+ assert_allclose(approx_series.grad(x1), ex.grad(x1))
+ approx_series.hess(x1)
+ approx.hess(x1)
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.ngev, approx_series.ngev)
+ assert_equal(approx_series.ngev, ex2.ngev)
+ assert_equal(approx.nhev, approx_series.nhev)
+ assert_equal(approx_series.nhev, ex2.nhev)
+
+ def test_fun_and_grad(self):
+ ex = ExScalarFunction()
+
+ def fg_allclose(x, y):
+ assert_allclose(x[0], y[0])
+ assert_allclose(x[1], y[1])
+
+ # with analytic gradient
+ x0 = [2.0, 0.3]
+ analit = ScalarFunction(ex.fun, x0, (), ex.grad,
+ ex.hess, None, (-np.inf, np.inf))
+
+ fg = ex.fun(x0), ex.grad(x0)
+ fg_allclose(analit.fun_and_grad(x0), fg)
+ assert analit.ngev == 1
+
+ x0[1] = 1.
+ fg = ex.fun(x0), ex.grad(x0)
+ fg_allclose(analit.fun_and_grad(x0), fg)
+
+ # with finite difference gradient
+ x0 = [2.0, 0.3]
+ sf = ScalarFunction(ex.fun, x0, (), '3-point',
+ ex.hess, None, (-np.inf, np.inf))
+ assert sf.ngev == 1
+ fg = ex.fun(x0), ex.grad(x0)
+ fg_allclose(sf.fun_and_grad(x0), fg)
+ assert sf.ngev == 1
+
+ x0[1] = 1.
+ fg = ex.fun(x0), ex.grad(x0)
+ fg_allclose(sf.fun_and_grad(x0), fg)
+
+ def test_finite_difference_hess_linear_operator(self):
+ ex = ExScalarFunction()
+ nfev = 0
+ ngev = 0
+ nhev = 0
+
+ x0 = [1.0, 0.0]
+ analit = ScalarFunction(ex.fun, x0, (), ex.grad,
+ ex.hess, None, (-np.inf, np.inf))
+ nfev += 1
+ ngev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev, nhev)
+ approx = ScalarFunction(ex.fun, x0, (), ex.grad,
+ '2-point', None, (-np.inf, np.inf))
+ assert_(isinstance(approx.H, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_equal(analit.f, approx.f)
+ assert_array_almost_equal(analit.g, approx.g)
+ assert_array_almost_equal(analit.H.dot(v), approx.H.dot(v))
+ nfev += 1
+ ngev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.0, 1.0]
+ H_analit = analit.hess(x)
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ H_approx = approx.hess(x)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v))
+ ngev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.1, 1.2]
+ H_analit = analit.hess(x)
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ H_approx = approx.hess(x)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v))
+ ngev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.5, 0.3]
+ _ = analit.grad(x)
+ H_analit = analit.hess(x)
+ ngev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ _ = approx.grad(x)
+ H_approx = approx.hess(x)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v))
+ ngev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [5.2, 2.3]
+ _ = analit.grad(x)
+ H_analit = analit.hess(x)
+ ngev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ _ = approx.grad(x)
+ H_approx = approx.hess(x)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v))
+ ngev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.ngev, ngev)
+ assert_array_equal(analit.ngev+approx.ngev, ngev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ def test_x_storage_overlap(self):
+ # Scalar_Function should not store references to arrays, it should
+ # store copies - this checks that updating an array in-place causes
+ # Scalar_Function.x to be updated.
+
+ def f(x):
+ return np.sum(np.asarray(x) ** 2)
+
+ x = np.array([1., 2., 3.])
+ sf = ScalarFunction(f, x, (), '3-point', lambda x: x, None, (-np.inf, np.inf))
+
+ assert x is not sf.x
+ assert_equal(sf.fun(x), 14.0)
+ assert x is not sf.x
+
+ x[0] = 0.
+ f1 = sf.fun(x)
+ assert_equal(f1, 13.0)
+
+ x[0] = 1
+ f2 = sf.fun(x)
+ assert_equal(f2, 14.0)
+ assert x is not sf.x
+
+ # now test with a HessianUpdate strategy specified
+ hess = BFGS()
+ x = np.array([1., 2., 3.])
+ sf = ScalarFunction(f, x, (), '3-point', hess, None, (-np.inf, np.inf))
+
+ assert x is not sf.x
+ assert_equal(sf.fun(x), 14.0)
+ assert x is not sf.x
+
+ x[0] = 0.
+ f1 = sf.fun(x)
+ assert_equal(f1, 13.0)
+
+ x[0] = 1
+ f2 = sf.fun(x)
+ assert_equal(f2, 14.0)
+ assert x is not sf.x
+
+ # gh13740 x is changed in user function
+ def ff(x):
+ x *= x # overwrite x
+ return np.sum(x)
+
+ x = np.array([1., 2., 3.])
+ sf = ScalarFunction(
+ ff, x, (), '3-point', lambda x: x, None, (-np.inf, np.inf)
+ )
+ assert x is not sf.x
+ assert_equal(sf.fun(x), 14.0)
+ assert_equal(sf.x, np.array([1., 2., 3.]))
+ assert x is not sf.x
+
+ def test_lowest_x(self):
+ # ScalarFunction should remember the lowest func(x) visited.
+ x0 = np.array([2, 3, 4])
+ sf = ScalarFunction(rosen, x0, (), rosen_der, rosen_hess,
+ None, None)
+ sf.fun([1, 1, 1])
+ sf.fun(x0)
+ sf.fun([1.01, 1, 1.0])
+ sf.grad([1.01, 1, 1.0])
+ assert_equal(sf._lowest_f, 0.0)
+ assert_equal(sf._lowest_x, [1.0, 1.0, 1.0])
+
+ sf = ScalarFunction(rosen, x0, (), '2-point', rosen_hess,
+ None, (-np.inf, np.inf))
+ sf.fun([1, 1, 1])
+ sf.fun(x0)
+ sf.fun([1.01, 1, 1.0])
+ sf.grad([1.01, 1, 1.0])
+ assert_equal(sf._lowest_f, 0.0)
+ assert_equal(sf._lowest_x, [1.0, 1.0, 1.0])
+
+ def test_float_size(self):
+ x0 = np.array([2, 3, 4]).astype(np.float32)
+
+ # check that ScalarFunction/approx_derivative always send the correct
+ # float width
+ def rosen_(x):
+ assert x.dtype == np.float32
+ return rosen(x)
+
+ sf = ScalarFunction(rosen_, x0, (), '2-point', rosen_hess,
+ None, (-np.inf, np.inf))
+ res = sf.fun(x0)
+ assert res.dtype == np.float32
+
+
+class ExVectorialFunction:
+
+ def __init__(self):
+ self.nfev = 0
+ self.njev = 0
+ self.nhev = 0
+
+ def fun(self, x):
+ self.nfev += 1
+ return np.array([2*(x[0]**2 + x[1]**2 - 1) - x[0],
+ 4*(x[0]**3 + x[1]**2 - 4) - 3*x[0]], dtype=x.dtype)
+
+ def jac(self, x):
+ self.njev += 1
+ return np.array([[4*x[0]-1, 4*x[1]],
+ [12*x[0]**2-3, 8*x[1]]], dtype=x.dtype)
+
+ def hess(self, x, v):
+ self.nhev += 1
+ return v[0]*4*np.eye(2) + v[1]*np.array([[24*x[0], 0],
+ [0, 8]])
+
+
+class TestVectorialFunction(TestCase):
+
+ def test_finite_difference_jac(self):
+ ex = ExVectorialFunction()
+ nfev = 0
+ njev = 0
+
+ x0 = [1.0, 0.0]
+ analit = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None,
+ (-np.inf, np.inf), None)
+ nfev += 1
+ njev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev, njev)
+ # create with defaults for the keyword arguments, to
+ # ensure that the defaults work
+ approx = VectorFunction(ex.fun, x0, '2-point', ex.hess)
+ nfev += 3
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(analit.f, approx.f)
+ assert_array_almost_equal(analit.J, approx.J)
+
+ x = [10, 0.3]
+ f_analit = analit.fun(x)
+ J_analit = analit.jac(x)
+ nfev += 1
+ njev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ f_approx = approx.fun(x)
+ J_approx = approx.jac(x)
+ nfev += 3
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(J_analit, J_approx, decimal=4)
+
+ x = [2.0, 1.0]
+ J_analit = analit.jac(x)
+ njev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ J_approx = approx.jac(x)
+ nfev += 3
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_almost_equal(J_analit, J_approx)
+
+ x = [2.5, 0.3]
+ f_analit = analit.fun(x)
+ J_analit = analit.jac(x)
+ nfev += 1
+ njev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ f_approx = approx.fun(x)
+ J_approx = approx.jac(x)
+ nfev += 3
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(J_analit, J_approx)
+
+ x = [2, 0.3]
+ f_analit = analit.fun(x)
+ J_analit = analit.jac(x)
+ nfev += 1
+ njev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ f_approx = approx.fun(x)
+ J_approx = approx.jac(x)
+ nfev += 3
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_almost_equal(f_analit, f_approx)
+ assert_array_almost_equal(J_analit, J_approx)
+
+ def test_updating_on_initial_setup(self):
+ # Check that memoisation works with the freshly created VectorFunction
+ # On initialization vf.f_updated attribute wasn't being set correctly.
+ x0 = np.array([2.5, 3.0])
+ ex = ExVectorialFunction()
+ vf = VectorFunction(ex.fun, x0, ex.jac, ex.hess)
+ assert vf.f_updated
+ assert vf.nfev == 1
+ assert vf.njev == 1
+ assert ex.nfev == 1
+ assert ex.njev == 1
+ vf.fun(x0)
+ vf.jac(x0)
+ assert vf.nfev == 1
+ assert vf.njev == 1
+ assert ex.nfev == 1
+ assert ex.njev == 1
+
+ @pytest.mark.fail_slow(5.0)
+ def test_workers(self):
+ x0 = np.array([2.5, 3.0])
+ ex = ExVectorialFunction()
+ ex2 = ExVectorialFunction()
+ v = np.array([1.0, 2.0])
+
+ with MapWrapper(2) as mapper:
+ approx = VectorFunction(ex.fun, x0, '2-point',
+ ex.hess, None, None, (-np.inf, np.inf),
+ False, workers=mapper)
+ approx_series = VectorFunction(ex2.fun, x0, '2-point',
+ ex2.hess, None, None, (-np.inf, np.inf),
+ False)
+
+ assert_allclose(approx.jac(x0), ex.jac(x0))
+ assert_allclose(approx_series.jac(x0), ex.jac(x0))
+ assert_allclose(approx_series.hess(x0, v), ex.hess(x0, v))
+ assert_allclose(approx.hess(x0, v), ex.hess(x0, v))
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.njev, approx_series.njev)
+ assert_equal(approx.nhev, approx_series.nhev)
+ assert_equal(approx_series.nhev, ex2.nhev)
+
+ ex.nfev = ex.njev = ex.nhev = 0
+ ex2.nfev = ex2.njev = ex2.nhev = 0
+ approx = VectorFunction(ex.fun, x0, '3-point',
+ ex.hess, None, None, (-np.inf, np.inf),
+ False, workers=mapper)
+ approx_series = VectorFunction(ex2.fun, x0, '3-point',
+ ex2.hess, None, None, (-np.inf, np.inf),
+ False)
+ assert_allclose(approx.jac(x0), ex.jac(x0))
+ assert_allclose(approx_series.jac(x0), ex.jac(x0))
+ assert_allclose(approx_series.hess(x0, v), ex.hess(x0, v))
+ assert_allclose(approx.hess(x0, v), ex.hess(x0, v))
+
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.njev, approx_series.njev)
+ assert_equal(approx.nhev, approx_series.nhev)
+ assert_equal(approx_series.nhev, ex2.nhev)
+
+ # The following tests are somewhat redundant because the LinearOperator
+ # produced by VectorFunction.hess does not use any parallelisation.
+ # The tests are left for completeness, in case that situation changes.
+ ex.nfev = ex.njev = ex.nhev = 0
+ ex2.nfev = ex2.njev = ex2.nhev = 0
+ approx = VectorFunction(ex.fun, x0, ex.jac,
+ '2-point', None, None, (-np.inf, np.inf),
+ False, workers=mapper)
+ approx_series = VectorFunction(ex2.fun, x0, ex2.jac,
+ '2-point', None, None, (-np.inf, np.inf),
+ False)
+ assert_allclose(approx.jac(x0), ex.jac(x0))
+ assert_allclose(approx_series.jac(x0), ex.jac(x0))
+
+ H_analit = ex2.hess(x0, v)
+ H_approx_series = approx_series.hess(x0, v)
+ H_approx = approx.hess(x0, v)
+ x = [5, 2.0]
+ assert_allclose(H_approx.dot(x), H_analit.dot(x))
+ assert_allclose(H_approx_series.dot(x), H_analit.dot(x))
+
+ assert_equal(approx.nfev, approx_series.nfev)
+ assert_equal(approx_series.nfev, ex2.nfev)
+ assert_equal(approx.njev, approx_series.njev)
+ assert_equal(approx.nhev, approx_series.nhev)
+
+ def test_finite_difference_hess_linear_operator(self):
+ ex = ExVectorialFunction()
+ nfev = 0
+ njev = 0
+ nhev = 0
+
+ x0 = [1.0, 0.0]
+ v0 = [1.0, 2.0]
+ analit = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None,
+ (-np.inf, np.inf), None)
+ nfev += 1
+ njev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev, nhev)
+ approx = VectorFunction(ex.fun, x0, ex.jac, '2-point', None, None,
+ (-np.inf, np.inf), None)
+ assert_(isinstance(approx.H, LinearOperator))
+ for p in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_equal(analit.f, approx.f)
+ assert_array_almost_equal(analit.J, approx.J)
+ assert_array_almost_equal(analit.H.dot(p), approx.H.dot(p))
+ nfev += 1
+ njev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.0, 1.0]
+ H_analit = analit.hess(x, v0)
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ H_approx = approx.hess(x, v0)
+ assert_(isinstance(H_approx, LinearOperator))
+ for p in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(p), H_approx.dot(p),
+ decimal=5)
+ njev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.1, 1.2]
+ v = [1.0, 1.0]
+ H_analit = analit.hess(x, v)
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ H_approx = approx.hess(x, v)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v))
+ njev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [2.5, 0.3]
+ _ = analit.jac(x)
+ H_analit = analit.hess(x, v0)
+ njev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ _ = approx.jac(x)
+ H_approx = approx.hess(x, v0)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v), decimal=4)
+ njev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ x = [5.2, 2.3]
+ v = [2.3, 5.2]
+ _ = analit.jac(x)
+ H_analit = analit.hess(x, v)
+ njev += 1
+ nhev += 1
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+ _ = approx.jac(x)
+ H_approx = approx.hess(x, v)
+ assert_(isinstance(H_approx, LinearOperator))
+ for v in ([1.0, 2.0], [3.0, 4.0], [5.0, 2.0]):
+ assert_array_almost_equal(H_analit.dot(v), H_approx.dot(v), decimal=4)
+ njev += 4
+ assert_array_equal(ex.nfev, nfev)
+ assert_array_equal(analit.nfev+approx.nfev, nfev)
+ assert_array_equal(ex.njev, njev)
+ assert_array_equal(analit.njev+approx.njev, njev)
+ assert_array_equal(ex.nhev, nhev)
+ assert_array_equal(analit.nhev+approx.nhev, nhev)
+
+ # Test VectorFunction.hess_wrapped with J0=None
+ x = np.array([1.5, 0.5])
+ v = np.array([1.0, 2.0])
+ njev_before = approx.hess_wrapped.njev
+ H = approx.hess_wrapped(x, v, J0=None)
+ assert isinstance(H, LinearOperator)
+ # The njev counter should be incremented by exactly 1
+ assert approx.hess_wrapped.njev == njev_before + 1
+
+ def test_fgh_overlap(self):
+ # VectorFunction.fun/jac should return copies to internal attributes
+ ex = ExVectorialFunction()
+ x0 = np.array([1.0, 0.0])
+
+ vf = VectorFunction(ex.fun, x0, '3-point', ex.hess, None, None,
+ (-np.inf, np.inf), None)
+ f = vf.fun(np.array([1.1, 0.1]))
+ J = vf.jac([1.1, 0.1])
+ assert vf.f is not f
+ assert vf.J is not J
+ assert_equal(f, vf.f)
+ assert_equal(J, vf.J)
+
+ vf = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None,
+ (-np.inf, np.inf), None)
+ f = vf.fun(np.array([1.1, 0.1]))
+ J = vf.jac([1.1, 0.1])
+ assert vf.f is not f
+ assert vf.J is not J
+ assert_equal(f, vf.f)
+ assert_equal(J, vf.J)
+
+ def test_x_storage_overlap(self):
+ # VectorFunction should not store references to arrays, it should
+ # store copies - this checks that updating an array in-place causes
+ # Scalar_Function.x to be updated.
+ ex = ExVectorialFunction()
+ x0 = np.array([1.0, 0.0])
+
+ vf = VectorFunction(ex.fun, x0, '3-point', ex.hess, None, None,
+ (-np.inf, np.inf), None)
+
+ assert x0 is not vf.x
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ x0[0] = 2.
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ x0[0] = 1.
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ # now test with a HessianUpdate strategy specified
+ hess = BFGS()
+ x0 = np.array([1.0, 0.0])
+ vf = VectorFunction(ex.fun, x0, '3-point', hess, None, None,
+ (-np.inf, np.inf), None)
+
+ with pytest.warns(UserWarning):
+ # filter UserWarning because ExVectorialFunction is linear and
+ # a quasi-Newton approximation is used for the Hessian.
+ assert x0 is not vf.x
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ x0[0] = 2.
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ x0[0] = 1.
+ assert_equal(vf.fun(x0), ex.fun(x0))
+ assert x0 is not vf.x
+
+ def test_float_size(self):
+ ex = ExVectorialFunction()
+ x0 = np.array([1.0, 0.0]).astype(np.float32)
+
+ vf = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None,
+ (-np.inf, np.inf), None)
+
+ res = vf.fun(x0)
+ assert res.dtype == np.float32
+
+ res = vf.jac(x0)
+ assert res.dtype == np.float32
+
+ def test_sparse_analytic_jac(self):
+ ex = ExVectorialFunction()
+ x0 = np.array([1.0, 0.0])
+ def sparse_adapter(func):
+ def inner(x):
+ f_x = func(x)
+ return csr_array(f_x)
+ return inner
+
+ # jac(x) returns dense jacobian
+ vf1 = VectorFunction(ex.fun, x0, ex.jac, ex.hess, None, None,
+ (-np.inf, np.inf), sparse_jacobian=None)
+ # jac(x) returns sparse jacobian, but sparse_jacobian=False requests dense
+ vf2 = VectorFunction(ex.fun, x0, sparse_adapter(ex.jac), ex.hess, None, None,
+ (-np.inf, np.inf), sparse_jacobian=False)
+
+ res1 = vf1.jac(x0 + 1)
+ res2 = vf2.jac(x0 + 1)
+ assert_equal(res1, res2)
+
+ def test_sparse_numerical_jac(self):
+ ex = ExVectorialFunction()
+ x0 = np.array([1.0, 0.0])
+ N = len(x0)
+
+ # normal dense numerical difference
+ vf1 = VectorFunction(ex.fun, x0, '2-point', ex.hess, None, None,
+ (-np.inf, np.inf), sparse_jacobian=None)
+ # use sparse numerical difference, but ask it to be converted to dense
+ finite_diff_jac_sparsity = csr_array(np.ones((N, N)))
+ vf2 = VectorFunction(ex.fun, x0, '2-point', ex.hess, None,
+ finite_diff_jac_sparsity, (-np.inf, np.inf),
+ sparse_jacobian=False)
+
+ res1 = vf1.jac(x0 + 1)
+ res2 = vf2.jac(x0 + 1)
+ assert_equal(res1, res2)
+
+
+def test_LinearVectorFunction():
+ A_dense = np.array([
+ [-1, 2, 0],
+ [0, 4, 2]
+ ])
+ x0 = np.zeros(3)
+ A_sparse = csr_array(A_dense)
+ x = np.array([1, -1, 0])
+ v = np.array([-1, 1])
+ Ax = np.array([-3, -4])
+
+ f1 = LinearVectorFunction(A_dense, x0, None)
+ assert_(not f1.sparse_jacobian)
+
+ f2 = LinearVectorFunction(A_dense, x0, True)
+ assert_(f2.sparse_jacobian)
+
+ f3 = LinearVectorFunction(A_dense, x0, False)
+ assert_(not f3.sparse_jacobian)
+
+ f4 = LinearVectorFunction(A_sparse, x0, None)
+ assert_(f4.sparse_jacobian)
+
+ f5 = LinearVectorFunction(A_sparse, x0, True)
+ assert_(f5.sparse_jacobian)
+
+ f6 = LinearVectorFunction(A_sparse, x0, False)
+ assert_(not f6.sparse_jacobian)
+
+ assert_array_equal(f1.fun(x), Ax)
+ assert_array_equal(f2.fun(x), Ax)
+ assert_array_equal(f1.jac(x), A_dense)
+ assert_array_equal(f2.jac(x).toarray(), A_sparse.toarray())
+ assert_array_equal(f1.hess(x, v).toarray(), np.zeros((3, 3)))
+
+
+def test_LinearVectorFunction_memoization():
+ A = np.array([[-1, 2, 0], [0, 4, 2]])
+ x0 = np.array([1, 2, -1])
+ fun = LinearVectorFunction(A, x0, False)
+
+ assert_array_equal(x0, fun.x)
+ assert_array_equal(A.dot(x0), fun.f)
+
+ x1 = np.array([-1, 3, 10])
+ assert_array_equal(A, fun.jac(x1))
+ assert_array_equal(x1, fun.x)
+ assert_array_equal(A.dot(x0), fun.f)
+ assert_array_equal(A.dot(x1), fun.fun(x1))
+ assert_array_equal(A.dot(x1), fun.f)
+
+
+def test_IdentityVectorFunction():
+ x0 = np.zeros(3)
+
+ f1 = IdentityVectorFunction(x0, None)
+ f2 = IdentityVectorFunction(x0, False)
+ f3 = IdentityVectorFunction(x0, True)
+
+ assert_(f1.sparse_jacobian)
+ assert_(not f2.sparse_jacobian)
+ assert_(f3.sparse_jacobian)
+
+ x = np.array([-1, 2, 1])
+ v = np.array([-2, 3, 0])
+
+ assert_array_equal(f1.fun(x), x)
+ assert_array_equal(f2.fun(x), x)
+
+ assert_array_equal(f1.jac(x).toarray(), np.eye(3))
+ assert_array_equal(f2.jac(x), np.eye(3))
+
+ assert_array_equal(f1.hess(x, v).toarray(), np.zeros((3, 3)))
+
+
+@pytest.mark.skipif(
+ platform.python_implementation() == "PyPy",
+ reason="assert_deallocate not available on PyPy"
+)
+def test_ScalarFunctionNoReferenceCycle():
+ """Regression test for gh-20768."""
+ ex = ExScalarFunction()
+ x0 = np.zeros(3)
+ with assert_deallocated(lambda: ScalarFunction(ex.fun, x0, (), ex.grad,
+ ex.hess, None, (-np.inf, np.inf))):
+ pass
+
+
+@pytest.mark.skipif(
+ platform.python_implementation() == "PyPy",
+ reason="assert_deallocate not available on PyPy"
+)
+def test_VectorFunctionNoReferenceCycle():
+ """Regression test for gh-20768."""
+ ex = ExVectorialFunction()
+ x0 = [1.0, 0.0]
+ with assert_deallocated(lambda: VectorFunction(ex.fun, x0, ex.jac,
+ ex.hess, None, None, (-np.inf, np.inf), None)):
+ pass
+
+
+@pytest.mark.skipif(
+ platform.python_implementation() == "PyPy",
+ reason="assert_deallocate not available on PyPy"
+)
+def test_LinearVectorFunctionNoReferenceCycle():
+ """Regression test for gh-20768."""
+ A_dense = np.array([
+ [-1, 2, 0],
+ [0, 4, 2]
+ ])
+ x0 = np.zeros(3)
+ A_sparse = csr_array(A_dense)
+ with assert_deallocated(lambda: LinearVectorFunction(A_sparse, x0, None)):
+ pass
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_direct.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_direct.py
new file mode 100644
index 0000000000000000000000000000000000000000..835d3164c8d547599a507550dcc7629e7d327394
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_direct.py
@@ -0,0 +1,321 @@
+"""
+Unit test for DIRECT optimization algorithm.
+"""
+from numpy.testing import (assert_allclose,
+ assert_array_less)
+import pytest
+import numpy as np
+from scipy.optimize import direct, Bounds
+import threading
+
+
+class TestDIRECT:
+
+ def setup_method(self):
+ self.fun_calls = threading.local()
+ self.bounds_sphere = 4*[(-2, 3)]
+ self.optimum_sphere_pos = np.zeros((4, ))
+ self.optimum_sphere = 0.0
+ self.bounds_stylinski_tang = Bounds([-4., -4.], [4., 4.])
+ self.maxiter = 1000
+
+ # test functions
+ def sphere(self, x):
+ if not hasattr(self.fun_calls, 'c'):
+ self.fun_calls.c = 0
+ self.fun_calls.c += 1
+ return np.square(x).sum()
+
+ def inv(self, x):
+ if np.sum(x) == 0:
+ raise ZeroDivisionError()
+ return 1/np.sum(x)
+
+ def nan_fun(self, x):
+ return np.nan
+
+ def inf_fun(self, x):
+ return np.inf
+
+ def styblinski_tang(self, pos):
+ x, y = pos
+ return 0.5 * (x**4 - 16 * x**2 + 5 * x + y**4 - 16 * y**2 + 5 * y)
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_direct(self, locally_biased):
+ res = direct(self.sphere, self.bounds_sphere,
+ locally_biased=locally_biased)
+
+ # test accuracy
+ assert_allclose(res.x, self.optimum_sphere_pos,
+ rtol=1e-3, atol=1e-3)
+ assert_allclose(res.fun, self.optimum_sphere, atol=1e-5, rtol=1e-5)
+
+ # test that result lies within bounds
+ _bounds = np.asarray(self.bounds_sphere)
+ assert_array_less(_bounds[:, 0], res.x)
+ assert_array_less(res.x, _bounds[:, 1])
+
+ # test number of function evaluations. Original DIRECT overshoots by
+ # up to 500 evaluations in last iteration
+ assert res.nfev <= 1000 * (len(self.bounds_sphere) + 1)
+ # test that number of function evaluations is correct
+ assert res.nfev == self.fun_calls.c
+
+ # test that number of iterations is below supplied maximum
+ assert res.nit <= self.maxiter
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_direct_callback(self, locally_biased):
+ # test that callback does not change the result
+ res = direct(self.sphere, self.bounds_sphere,
+ locally_biased=locally_biased)
+
+ def callback(x):
+ x = 2*x
+ dummy = np.square(x)
+ print("DIRECT minimization algorithm callback test")
+ return dummy
+
+ res_callback = direct(self.sphere, self.bounds_sphere,
+ locally_biased=locally_biased,
+ callback=callback)
+
+ assert_allclose(res.x, res_callback.x)
+
+ assert res.nit == res_callback.nit
+ assert res.nfev == res_callback.nfev
+ assert res.status == res_callback.status
+ assert res.success == res_callback.success
+ assert res.fun == res_callback.fun
+ assert_allclose(res.x, res_callback.x)
+ assert res.message == res_callback.message
+
+ # test accuracy
+ assert_allclose(res_callback.x, self.optimum_sphere_pos,
+ rtol=1e-3, atol=1e-3)
+ assert_allclose(res_callback.fun, self.optimum_sphere,
+ atol=1e-5, rtol=1e-5)
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_exception(self, locally_biased):
+ bounds = 4*[(-10, 10)]
+ with pytest.raises(ZeroDivisionError):
+ direct(self.inv, bounds=bounds,
+ locally_biased=locally_biased)
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_nan(self, locally_biased):
+ bounds = 4*[(-10, 10)]
+ direct(self.nan_fun, bounds=bounds,
+ locally_biased=locally_biased)
+
+ @pytest.mark.parametrize("len_tol", [1e-3, 1e-4])
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_len_tol(self, len_tol, locally_biased):
+ bounds = 4*[(-10., 10.)]
+ res = direct(self.sphere, bounds=bounds, len_tol=len_tol,
+ vol_tol=1e-30, locally_biased=locally_biased)
+ assert res.status == 5
+ assert res.success
+ assert_allclose(res.x, np.zeros((4, )))
+ message = ("The side length measure of the hyperrectangle containing "
+ "the lowest function value found is below "
+ f"len_tol={len_tol}")
+ assert res.message == message
+
+ @pytest.mark.parametrize("vol_tol", [1e-6, 1e-8])
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_vol_tol(self, vol_tol, locally_biased):
+ bounds = 4*[(-10., 10.)]
+ res = direct(self.sphere, bounds=bounds, vol_tol=vol_tol,
+ len_tol=0., locally_biased=locally_biased)
+ assert res.status == 4
+ assert res.success
+ assert_allclose(res.x, np.zeros((4, )))
+ message = ("The volume of the hyperrectangle containing the lowest "
+ f"function value found is below vol_tol={vol_tol}")
+ assert res.message == message
+
+ @pytest.mark.parametrize("f_min_rtol", [1e-3, 1e-5, 1e-7])
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_f_min(self, f_min_rtol, locally_biased):
+ # test that desired function value is reached within
+ # relative tolerance of f_min_rtol
+ f_min = 1.
+ bounds = 4*[(-2., 10.)]
+ res = direct(self.sphere, bounds=bounds, f_min=f_min,
+ f_min_rtol=f_min_rtol,
+ locally_biased=locally_biased)
+ assert res.status == 3
+ assert res.success
+ assert res.fun < f_min * (1. + f_min_rtol)
+ message = ("The best function value found is within a relative "
+ f"error={f_min_rtol} of the (known) global optimum f_min")
+ assert res.message == message
+
+ def circle_with_args(self, x, a, b):
+ return np.square(x[0] - a) + np.square(x[1] - b).sum()
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_f_circle_with_args(self, locally_biased):
+ bounds = 2*[(-2.0, 2.0)]
+
+ res = direct(self.circle_with_args, bounds, args=(1, 1), maxfun=1250,
+ locally_biased=locally_biased)
+ assert_allclose(res.x, np.array([1., 1.]), rtol=1e-5)
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_failure_maxfun(self, locally_biased):
+ # test that if optimization runs for the maximal number of
+ # evaluations, success = False is returned
+
+ maxfun = 100
+ result = direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxfun=maxfun, locally_biased=locally_biased)
+ assert result.success is False
+ assert result.status == 1
+ assert result.nfev >= maxfun
+ message = ("Number of function evaluations done is "
+ f"larger than maxfun={maxfun}")
+ assert result.message == message
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_failure_maxiter(self, locally_biased):
+ # test that if optimization runs for the maximal number of
+ # iterations, success = False is returned
+
+ maxiter = 10
+ result = direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxiter=maxiter, locally_biased=locally_biased)
+ assert result.success is False
+ assert result.status == 2
+ assert result.nit >= maxiter
+ message = f"Number of iterations is larger than maxiter={maxiter}"
+ assert result.message == message
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_bounds_variants(self, locally_biased):
+ # test that new and old bounds yield same result
+
+ lb = [-6., 1., -5.]
+ ub = [-1., 3., 5.]
+ x_opt = np.array([-1., 1., 0.])
+ bounds_old = list(zip(lb, ub))
+ bounds_new = Bounds(lb, ub)
+
+ res_old_bounds = direct(self.sphere, bounds_old,
+ locally_biased=locally_biased)
+ res_new_bounds = direct(self.sphere, bounds_new,
+ locally_biased=locally_biased)
+
+ assert res_new_bounds.nfev == res_old_bounds.nfev
+ assert res_new_bounds.message == res_old_bounds.message
+ assert res_new_bounds.success == res_old_bounds.success
+ assert res_new_bounds.nit == res_old_bounds.nit
+ assert_allclose(res_new_bounds.x, res_old_bounds.x)
+ assert_allclose(res_new_bounds.x, x_opt, rtol=1e-2)
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ @pytest.mark.parametrize("eps", [1e-5, 1e-4, 1e-3])
+ def test_epsilon(self, eps, locally_biased):
+ result = direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ eps=eps, vol_tol=1e-6,
+ locally_biased=locally_biased)
+ assert result.status == 4
+ assert result.success
+
+ @pytest.mark.xslow
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_no_segmentation_fault(self, locally_biased):
+ # test that an excessive number of function evaluations
+ # does not result in segmentation fault
+ bounds = [(-5., 20.)] * 100
+ result = direct(self.sphere, bounds, maxfun=10000000,
+ maxiter=1000000, locally_biased=locally_biased)
+ assert result is not None
+
+ @pytest.mark.parametrize("locally_biased", [True, False])
+ def test_inf_fun(self, locally_biased):
+ # test that an objective value of infinity does not crash DIRECT
+ bounds = [(-5., 5.)] * 2
+ result = direct(self.inf_fun, bounds,
+ locally_biased=locally_biased)
+ assert result is not None
+
+ @pytest.mark.parametrize("len_tol", [-1, 2])
+ def test_len_tol_validation(self, len_tol):
+ error_msg = "len_tol must be between 0 and 1."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ len_tol=len_tol)
+
+ @pytest.mark.parametrize("vol_tol", [-1, 2])
+ def test_vol_tol_validation(self, vol_tol):
+ error_msg = "vol_tol must be between 0 and 1."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ vol_tol=vol_tol)
+
+ @pytest.mark.parametrize("f_min_rtol", [-1, 2])
+ def test_fmin_rtol_validation(self, f_min_rtol):
+ error_msg = "f_min_rtol must be between 0 and 1."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ f_min_rtol=f_min_rtol, f_min=0.)
+
+ @pytest.mark.parametrize("maxfun", [1.5, "string", (1, 2)])
+ def test_maxfun_wrong_type(self, maxfun):
+ error_msg = "maxfun must be of type int."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxfun=maxfun)
+
+ @pytest.mark.parametrize("maxiter", [1.5, "string", (1, 2)])
+ def test_maxiter_wrong_type(self, maxiter):
+ error_msg = "maxiter must be of type int."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxiter=maxiter)
+
+ def test_negative_maxiter(self):
+ error_msg = "maxiter must be > 0."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxiter=-1)
+
+ def test_negative_maxfun(self):
+ error_msg = "maxfun must be > 0."
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ maxfun=-1)
+
+ @pytest.mark.parametrize("bounds", ["bounds", 2., 0])
+ def test_invalid_bounds_type(self, bounds):
+ error_msg = ("bounds must be a sequence or "
+ "instance of Bounds class")
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, bounds)
+
+ @pytest.mark.parametrize("bounds",
+ [Bounds([-1., -1], [-2, 1]),
+ Bounds([-np.nan, -1], [-2, np.nan]),
+ ]
+ )
+ def test_incorrect_bounds(self, bounds):
+ error_msg = 'Bounds are not consistent min < max'
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, bounds)
+
+ def test_inf_bounds(self):
+ error_msg = 'Bounds must not be inf.'
+ bounds = Bounds([-np.inf, -1], [-2, np.inf])
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, bounds)
+
+ @pytest.mark.parametrize("locally_biased", ["bias", [0, 0], 2.])
+ def test_locally_biased_validation(self, locally_biased):
+ error_msg = 'locally_biased must be True or False.'
+ with pytest.raises(ValueError, match=error_msg):
+ direct(self.styblinski_tang, self.bounds_stylinski_tang,
+ locally_biased=locally_biased)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_extending.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_extending.py
new file mode 100644
index 0000000000000000000000000000000000000000..279cac794e5f453fee52f19026f96eb530259485
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_extending.py
@@ -0,0 +1,28 @@
+import os
+import platform
+import sysconfig
+
+import pytest
+
+from scipy._lib._testutils import IS_EDITABLE, _test_cython_extension, cython
+
+
+@pytest.mark.fail_slow(40)
+# essential per https://github.com/scipy/scipy/pull/20487#discussion_r1567057247
+@pytest.mark.skipif(IS_EDITABLE,
+ reason='Editable install cannot find .pxd headers.')
+@pytest.mark.skipif((platform.system() == 'Windows' and
+ sysconfig.get_config_var('Py_GIL_DISABLED')),
+ reason='gh-22039')
+@pytest.mark.skipif(platform.machine() in ["wasm32", "wasm64"],
+ reason="Can't start subprocess")
+@pytest.mark.skipif(cython is None, reason="requires cython")
+def test_cython(tmp_path):
+ srcdir = os.path.dirname(os.path.dirname(__file__))
+ extensions, extensions_cpp = _test_cython_extension(tmp_path, srcdir)
+ # actually test the cython c-extensions
+ # From docstring for scipy.optimize.cython_optimize module
+ x = extensions.brentq_example()
+ assert x == 0.6999942848231314
+ x = extensions_cpp.brentq_example()
+ assert x == 0.6999942848231314
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_hessian_update_strategy.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_hessian_update_strategy.py
new file mode 100644
index 0000000000000000000000000000000000000000..2434e92434ff2ecc74ce2e8b8119632207fd0853
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_hessian_update_strategy.py
@@ -0,0 +1,300 @@
+import re
+from copy import deepcopy
+
+import numpy as np
+import pytest
+from numpy.linalg import norm
+from numpy.testing import (TestCase, assert_array_almost_equal,
+ assert_array_equal, assert_array_less)
+from scipy.optimize import (BFGS, SR1)
+
+
+class Rosenbrock:
+ """Rosenbrock function.
+
+ The following optimization problem:
+ minimize sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
+ """
+
+ def __init__(self, n=2, random_state=0):
+ rng = np.random.RandomState(random_state)
+ self.x0 = rng.uniform(-1, 1, n)
+ self.x_opt = np.ones(n)
+
+ def fun(self, x):
+ x = np.asarray(x)
+ r = np.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0,
+ axis=0)
+ return r
+
+ def grad(self, x):
+ x = np.asarray(x)
+ xm = x[1:-1]
+ xm_m1 = x[:-2]
+ xm_p1 = x[2:]
+ der = np.zeros_like(x)
+ der[1:-1] = (200 * (xm - xm_m1**2) -
+ 400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm))
+ der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0])
+ der[-1] = 200 * (x[-1] - x[-2]**2)
+ return der
+
+ def hess(self, x):
+ x = np.atleast_1d(x)
+ H = np.diag(-400 * x[:-1], 1) - np.diag(400 * x[:-1], -1)
+ diagonal = np.zeros(len(x), dtype=x.dtype)
+ diagonal[0] = 1200 * x[0]**2 - 400 * x[1] + 2
+ diagonal[-1] = 200
+ diagonal[1:-1] = 202 + 1200 * x[1:-1]**2 - 400 * x[2:]
+ H = H + np.diag(diagonal)
+ return H
+
+
+class TestHessianUpdateStrategy(TestCase):
+
+
+ def test_hessian_initialization(self):
+
+ ndims = 5
+ symmetric_matrix = np.array([[43, 24, 33, 34, 49],
+ [24, 36, 44, 15, 44],
+ [33, 44, 37, 1, 30],
+ [34, 15, 1, 5, 46],
+ [49, 44, 30, 46, 22]])
+ init_scales = (
+ ('auto', np.eye(ndims)),
+ (2, np.eye(ndims) * 2),
+ (np.arange(1, ndims + 1) * np.eye(ndims),
+ np.arange(1, ndims + 1) * np.eye(ndims)),
+ (symmetric_matrix, symmetric_matrix),)
+ for approx_type in ['hess', 'inv_hess']:
+ for init_scale, true_matrix in init_scales:
+ # large min_{denominator,curvatur} makes them skip an update,
+ # so we can have our initial matrix
+ quasi_newton = (BFGS(init_scale=init_scale,
+ min_curvature=1e50,
+ exception_strategy='skip_update'),
+ SR1(init_scale=init_scale,
+ min_denominator=1e50))
+
+ for qn in quasi_newton:
+ qn.initialize(ndims, approx_type)
+ B = qn.get_matrix()
+
+ assert_array_equal(B, np.eye(ndims))
+ # don't test the auto init scale
+ if isinstance(init_scale, str) and init_scale == 'auto':
+ continue
+
+ qn.update(np.ones(ndims) * 1e-5, np.arange(ndims) + 0.2)
+ B = qn.get_matrix()
+ assert_array_equal(B, true_matrix)
+
+ # For this list of points, it is known
+ # that no exception occur during the
+ # Hessian update. Hence no update is
+ # skiped or damped.
+
+
+ def test_initialize_catch_illegal(self):
+ ndims = 3
+ # no complex allowed
+ inits_msg_errtype = ((complex(3.14),
+ r"float\(\) argument must be a string or a "
+ r"(real )?number, not 'complex'",
+ TypeError),
+
+ (np.array([3.2, 2.3, 1.2]).astype(np.complex128),
+ "init_scale contains complex elements, "
+ "must be real.",
+ TypeError),
+
+ (np.array([[43, 24, 33],
+ [24, 36, 44, ],
+ [33, 44, 37, ]]).astype(np.complex128),
+ "init_scale contains complex elements, "
+ "must be real.",
+ TypeError),
+
+ # not square
+ (np.array([[43, 55, 66]]),
+ re.escape(
+ "If init_scale is an array, it must have the "
+ "dimensions of the hess/inv_hess: (3, 3)."
+ " Got (1, 3)."),
+ ValueError),
+
+ # not symmetric
+ (np.array([[43, 24, 33],
+ [24.1, 36, 44, ],
+ [33, 44, 37, ]]),
+ re.escape("If init_scale is an array, it must be"
+ " symmetric (passing scipy.linalg.issymmetric)"
+ " to be an approximation of a hess/inv_hess."),
+ ValueError),
+ )
+ for approx_type in ['hess', 'inv_hess']:
+ for init_scale, message, errortype in inits_msg_errtype:
+ # large min_{denominator,curvatur} makes it skip an update,
+ # so we can retrieve our initial matrix
+ quasi_newton = (BFGS(init_scale=init_scale),
+ SR1(init_scale=init_scale))
+
+ for qn in quasi_newton:
+ qn.initialize(ndims, approx_type)
+ with pytest.raises(errortype, match=message):
+ qn.update(np.ones(ndims), np.arange(ndims))
+
+ def test_rosenbrock_with_no_exception(self):
+ # Define auxiliary problem
+ prob = Rosenbrock(n=5)
+ # Define iteration points
+ x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040],
+ [0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286],
+ [0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606],
+ [0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750],
+ [0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699],
+ [0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610],
+ [0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184],
+ [0.2354930, 0.0443711, 0.0173959, 0.0041872, 0.00794563],
+ [0.4168118, 0.1433867, 0.0111714, 0.0126265, -0.00658537],
+ [0.4681972, 0.2153273, 0.0225249, 0.0152704, -0.00463809],
+ [0.6023068, 0.3346815, 0.0731108, 0.0186618, -0.00371541],
+ [0.6415743, 0.3985468, 0.1324422, 0.0214160, -0.00062401],
+ [0.7503690, 0.5447616, 0.2804541, 0.0539851, 0.00242230],
+ [0.7452626, 0.5644594, 0.3324679, 0.0865153, 0.00454960],
+ [0.8059782, 0.6586838, 0.4229577, 0.1452990, 0.00976702],
+ [0.8549542, 0.7226562, 0.4991309, 0.2420093, 0.02772661],
+ [0.8571332, 0.7285741, 0.5279076, 0.2824549, 0.06030276],
+ [0.8835633, 0.7727077, 0.5957984, 0.3411303, 0.09652185],
+ [0.9071558, 0.8299587, 0.6771400, 0.4402896, 0.17469338],
+ [0.9190793, 0.8486480, 0.7163332, 0.5083780, 0.26107691],
+ [0.9371223, 0.8762177, 0.7653702, 0.5773109, 0.32181041],
+ [0.9554613, 0.9119893, 0.8282687, 0.6776178, 0.43162744],
+ [0.9545744, 0.9099264, 0.8270244, 0.6822220, 0.45237623],
+ [0.9688112, 0.9351710, 0.8730961, 0.7546601, 0.56622448],
+ [0.9743227, 0.9491953, 0.9005150, 0.8086497, 0.64505437],
+ [0.9807345, 0.9638853, 0.9283012, 0.8631675, 0.73812581],
+ [0.9886746, 0.9777760, 0.9558950, 0.9123417, 0.82726553],
+ [0.9899096, 0.9803828, 0.9615592, 0.9255600, 0.85822149],
+ [0.9969510, 0.9935441, 0.9864657, 0.9726775, 0.94358663],
+ [0.9979533, 0.9960274, 0.9921724, 0.9837415, 0.96626288],
+ [0.9995981, 0.9989171, 0.9974178, 0.9949954, 0.99023356],
+ [1.0002640, 1.0005088, 1.0010594, 1.0021161, 1.00386912],
+ [0.9998903, 0.9998459, 0.9997795, 0.9995484, 0.99916305],
+ [1.0000008, 0.9999905, 0.9999481, 0.9998903, 0.99978047],
+ [1.0000004, 0.9999983, 1.0000001, 1.0000031, 1.00000297],
+ [0.9999995, 1.0000003, 1.0000005, 1.0000001, 1.00000032],
+ [0.9999999, 0.9999997, 0.9999994, 0.9999989, 0.99999786],
+ [0.9999999, 0.9999999, 0.9999999, 0.9999999, 0.99999991]]
+ # Get iteration points
+ grad_list = [prob.grad(x) for x in x_list]
+ delta_x = [np.array(x_list[i+1])-np.array(x_list[i])
+ for i in range(len(x_list)-1)]
+ delta_grad = [grad_list[i+1]-grad_list[i]
+ for i in range(len(grad_list)-1)]
+ # Check curvature condition
+ for s, y in zip(delta_x, delta_grad):
+ if np.dot(s, y) <= 0:
+ raise ArithmeticError()
+ # Define QuasiNewton update
+ for quasi_newton in (BFGS(init_scale=1, min_curvature=1e-4),
+ SR1(init_scale=1)):
+ hess = deepcopy(quasi_newton)
+ inv_hess = deepcopy(quasi_newton)
+ hess.initialize(len(x_list[0]), 'hess')
+ inv_hess.initialize(len(x_list[0]), 'inv_hess')
+ # Compare the hessian and its inverse
+ for s, y in zip(delta_x, delta_grad):
+ hess.update(s, y)
+ inv_hess.update(s, y)
+ B = hess.get_matrix()
+ H = inv_hess.get_matrix()
+ assert_array_almost_equal(np.linalg.inv(B), H, decimal=10)
+ B_true = prob.hess(x_list[len(delta_x)])
+ assert_array_less(norm(B - B_true)/norm(B_true), 0.1)
+
+ def test_SR1_skip_update(self):
+ # Define auxiliary problem
+ prob = Rosenbrock(n=5)
+ # Define iteration points
+ x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040],
+ [0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286],
+ [0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606],
+ [0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750],
+ [0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699],
+ [0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610],
+ [0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184],
+ [0.2354930, 0.0443711, 0.0173959, 0.0041872, 0.00794563],
+ [0.4168118, 0.1433867, 0.0111714, 0.0126265, -0.00658537],
+ [0.4681972, 0.2153273, 0.0225249, 0.0152704, -0.00463809],
+ [0.6023068, 0.3346815, 0.0731108, 0.0186618, -0.00371541],
+ [0.6415743, 0.3985468, 0.1324422, 0.0214160, -0.00062401],
+ [0.7503690, 0.5447616, 0.2804541, 0.0539851, 0.00242230],
+ [0.7452626, 0.5644594, 0.3324679, 0.0865153, 0.00454960],
+ [0.8059782, 0.6586838, 0.4229577, 0.1452990, 0.00976702],
+ [0.8549542, 0.7226562, 0.4991309, 0.2420093, 0.02772661],
+ [0.8571332, 0.7285741, 0.5279076, 0.2824549, 0.06030276],
+ [0.8835633, 0.7727077, 0.5957984, 0.3411303, 0.09652185],
+ [0.9071558, 0.8299587, 0.6771400, 0.4402896, 0.17469338]]
+ # Get iteration points
+ grad_list = [prob.grad(x) for x in x_list]
+ delta_x = [np.array(x_list[i+1])-np.array(x_list[i])
+ for i in range(len(x_list)-1)]
+ delta_grad = [grad_list[i+1]-grad_list[i]
+ for i in range(len(grad_list)-1)]
+ hess = SR1(init_scale=1, min_denominator=1e-2)
+ hess.initialize(len(x_list[0]), 'hess')
+ # Compare the Hessian and its inverse
+ for i in range(len(delta_x)-1):
+ s = delta_x[i]
+ y = delta_grad[i]
+ hess.update(s, y)
+ # Test skip update
+ B = np.copy(hess.get_matrix())
+ s = delta_x[17]
+ y = delta_grad[17]
+ hess.update(s, y)
+ B_updated = np.copy(hess.get_matrix())
+ assert_array_equal(B, B_updated)
+
+ def test_BFGS_skip_update(self):
+ # Define auxiliary problem
+ prob = Rosenbrock(n=5)
+ # Define iteration points
+ x_list = [[0.0976270, 0.4303787, 0.2055267, 0.0897663, -0.15269040],
+ [0.1847239, 0.0505757, 0.2123832, 0.0255081, 0.00083286],
+ [0.2142498, -0.0188480, 0.0503822, 0.0347033, 0.03323606],
+ [0.2071680, -0.0185071, 0.0341337, -0.0139298, 0.02881750],
+ [0.1533055, -0.0322935, 0.0280418, -0.0083592, 0.01503699],
+ [0.1382378, -0.0276671, 0.0266161, -0.0074060, 0.02801610],
+ [0.1651957, -0.0049124, 0.0269665, -0.0040025, 0.02138184]]
+ # Get iteration points
+ grad_list = [prob.grad(x) for x in x_list]
+ delta_x = [np.array(x_list[i+1])-np.array(x_list[i])
+ for i in range(len(x_list)-1)]
+ delta_grad = [grad_list[i+1]-grad_list[i]
+ for i in range(len(grad_list)-1)]
+ hess = BFGS(init_scale=1, min_curvature=10)
+ hess.initialize(len(x_list[0]), 'hess')
+ # Compare the Hessian and its inverse
+ for i in range(len(delta_x)-1):
+ s = delta_x[i]
+ y = delta_grad[i]
+ hess.update(s, y)
+ # Test skip update
+ B = np.copy(hess.get_matrix())
+ s = delta_x[5]
+ y = delta_grad[5]
+ hess.update(s, y)
+ B_updated = np.copy(hess.get_matrix())
+ assert_array_equal(B, B_updated)
+
+
+@pytest.mark.parametrize('strategy', [BFGS, SR1])
+@pytest.mark.parametrize('approx_type', ['hess', 'inv_hess'])
+def test_matmul_equals_dot(strategy, approx_type):
+ H = strategy(init_scale=1)
+ H.initialize(2, approx_type)
+ v = np.array([1, 2])
+ assert_array_equal(H @ v, H.dot(v))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_isotonic_regression.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_isotonic_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..b49c56db5b4470c1e4e0f787df52c80eb055c120
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_isotonic_regression.py
@@ -0,0 +1,167 @@
+import numpy as np
+from numpy.testing import assert_allclose, assert_equal
+import pytest
+
+from scipy.optimize._pava_pybind import pava
+from scipy.optimize import isotonic_regression
+
+
+class TestIsotonicRegression:
+ @pytest.mark.parametrize(
+ ("y", "w", "msg"),
+ [
+ ([[0, 1]], None,
+ "array has incorrect number of dimensions: 2; expected 1"),
+ ([0, 1], [[1, 2]],
+ "Input arrays y and w must have one dimension of equal length"),
+ ([0, 1], [1],
+ "Input arrays y and w must have one dimension of equal length"),
+ (1, [1, 2],
+ "Input arrays y and w must have one dimension of equal length"),
+ ([1, 2], 1,
+ "Input arrays y and w must have one dimension of equal length"),
+ ([0, 1], [0, 1],
+ "Weights w must be strictly positive"),
+ ]
+ )
+ def test_raise_error(self, y, w, msg):
+ with pytest.raises(ValueError, match=msg):
+ isotonic_regression(y=y, weights=w)
+
+ def test_simple_pava(self):
+ # Test case of Busing 2020
+ # https://doi.org/10.18637/jss.v102.c01
+ y = np.array([8, 4, 8, 2, 2, 0, 8], dtype=np.float64)
+ w = np.ones_like(y)
+ r = np.full(shape=y.shape[0] + 1, fill_value=-1, dtype=np.intp)
+ pava(y, w, r)
+ assert_allclose(y, [4, 4, 4, 4, 4, 4, 8])
+ # Only first 2 elements of w are changed.
+ assert_allclose(w, [6, 1, 1, 1, 1, 1, 1])
+ # Only first 3 elements of r are changed.
+ assert_allclose(r, [0, 6, 7, -1, -1, -1, -1, -1])
+
+ @pytest.mark.parametrize("y_dtype", [np.float64, np.float32, np.int64, np.int32])
+ @pytest.mark.parametrize("w_dtype", [np.float64, np.float32, np.int64, np.int32])
+ @pytest.mark.parametrize("w", [None, "ones"])
+ def test_simple_isotonic_regression(self, w, w_dtype, y_dtype):
+ # Test case of Busing 2020
+ # https://doi.org/10.18637/jss.v102.c01
+ y = np.array([8, 4, 8, 2, 2, 0, 8], dtype=y_dtype)
+ if w is not None:
+ w = np.ones_like(y, dtype=w_dtype)
+ res = isotonic_regression(y, weights=w)
+ assert res.x.dtype == np.float64
+ assert res.weights.dtype == np.float64
+ assert_allclose(res.x, [4, 4, 4, 4, 4, 4, 8])
+ assert_allclose(res.weights, [6, 1])
+ assert_allclose(res.blocks, [0, 6, 7])
+ # Assert that y was not overwritten
+ assert_equal(y, np.array([8, 4, 8, 2, 2, 0, 8], dtype=np.float64))
+
+ @pytest.mark.parametrize("increasing", [True, False])
+ def test_linspace(self, increasing):
+ n = 10
+ y = np.linspace(0, 1, n) if increasing else np.linspace(1, 0, n)
+ res = isotonic_regression(y, increasing=increasing)
+ assert_allclose(res.x, y)
+ assert_allclose(res.blocks, np.arange(n + 1))
+
+ def test_weights(self):
+ w = np.array([1, 2, 5, 0.5, 0.5, 0.5, 1, 3])
+ y = np.array([3, 2, 1, 10, 9, 8, 20, 10])
+ res = isotonic_regression(y, weights=w)
+ assert_allclose(res.x, [12/8, 12/8, 12/8, 9, 9, 9, 50/4, 50/4])
+ assert_allclose(res.weights, [8, 1.5, 4])
+ assert_allclose(res.blocks, [0, 3, 6, 8])
+
+ # weights are like repeated observations, we repeat the 3rd element 5
+ # times.
+ w2 = np.array([1, 2, 1, 1, 1, 1, 1, 0.5, 0.5, 0.5, 1, 3])
+ y2 = np.array([3, 2, 1, 1, 1, 1, 1, 10, 9, 8, 20, 10])
+ res2 = isotonic_regression(y2, weights=w2)
+ assert_allclose(np.diff(res2.x[0:7]), 0)
+ assert_allclose(res2.x[4:], res.x)
+ assert_allclose(res2.weights, res.weights)
+ assert_allclose(res2.blocks[1:] - 4, res.blocks[1:])
+
+ def test_against_R_monotone(self):
+ y = [0, 6, 8, 3, 5, 2, 1, 7, 9, 4]
+ res = isotonic_regression(y)
+ # R code
+ # library(monotone)
+ # options(digits=8)
+ # monotone(c(0, 6, 8, 3, 5, 2, 1, 7, 9, 4))
+ x_R = [
+ 0, 4.1666667, 4.1666667, 4.1666667, 4.1666667, 4.1666667,
+ 4.1666667, 6.6666667, 6.6666667, 6.6666667,
+ ]
+ assert_allclose(res.x, x_R)
+ assert_equal(res.blocks, [0, 1, 7, 10])
+
+ n = 100
+ y = np.linspace(0, 1, num=n, endpoint=False)
+ y = 5 * y + np.sin(10 * y)
+ res = isotonic_regression(y)
+ # R code
+ # library(monotone)
+ # n <- 100
+ # y <- 5 * ((1:n)-1)/n + sin(10 * ((1:n)-1)/n)
+ # options(digits=8)
+ # monotone(y)
+ x_R = [
+ 0.00000000, 0.14983342, 0.29866933, 0.44552021, 0.58941834, 0.72942554,
+ 0.86464247, 0.99421769, 1.11735609, 1.23332691, 1.34147098, 1.44120736,
+ 1.53203909, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100, 1.57081100,
+ 1.57081100, 1.57081100, 1.57081100, 1.62418532, 1.71654534, 1.81773256,
+ 1.92723551, 2.04445967, 2.16873336, 2.29931446, 2.43539782, 2.57612334,
+ 2.72058450, 2.86783750, 3.01691060, 3.16681390, 3.31654920, 3.46511999,
+ 3.61154136, 3.75484992, 3.89411335, 4.02843976, 4.15698660, 4.27896904,
+ 4.39366786, 4.50043662, 4.59870810, 4.68799998, 4.76791967, 4.83816823,
+ 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130,
+ 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130,
+ 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130, 4.86564130,
+ 4.86564130, 4.86564130, 4.86564130, 4.86564130,
+ ]
+ assert_allclose(res.x, x_R)
+
+ # Test increasing
+ assert np.all(np.diff(res.x) >= 0)
+
+ # Test balance property: sum(y) == sum(x)
+ assert_allclose(np.sum(res.x), np.sum(y))
+
+ # Reverse order
+ res_inv = isotonic_regression(-y, increasing=False)
+ assert_allclose(-res_inv.x, res.x)
+ assert_equal(res_inv.blocks, res.blocks)
+
+ def test_readonly(self):
+ x = np.arange(3, dtype=float)
+ w = np.ones(3, dtype=float)
+
+ x.flags.writeable = False
+ w.flags.writeable = False
+
+ res = isotonic_regression(x, weights=w)
+ assert np.all(np.isfinite(res.x))
+ assert np.all(np.isfinite(res.weights))
+ assert np.all(np.isfinite(res.blocks))
+
+ def test_non_contiguous_arrays(self):
+ x = np.arange(10, dtype=float)[::3]
+ w = np.ones(10, dtype=float)[::3]
+ assert not x.flags.c_contiguous
+ assert not x.flags.f_contiguous
+ assert not w.flags.c_contiguous
+ assert not w.flags.f_contiguous
+
+ res = isotonic_regression(x, weights=w)
+ assert np.all(np.isfinite(res.x))
+ assert np.all(np.isfinite(res.weights))
+ assert np.all(np.isfinite(res.blocks))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py
new file mode 100644
index 0000000000000000000000000000000000000000..8740b94e99929b23ad1aa55bc26829b472691d24
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_hessinv.py
@@ -0,0 +1,65 @@
+import numpy as np
+from numpy.testing import assert_allclose
+import scipy.linalg
+from scipy.optimize import minimize
+
+
+def test_1():
+ def f(x):
+ return x**4, 4*x**3
+
+ for gtol in [1e-8, 1e-12, 1e-20]:
+ for maxcor in range(20, 35):
+ result = minimize(fun=f, jac=True, method='L-BFGS-B', x0=20,
+ options={'gtol': gtol, 'maxcor': maxcor})
+
+ H1 = result.hess_inv(np.array([1])).reshape(1,1)
+ H2 = result.hess_inv.todense()
+
+ assert_allclose(H1, H2)
+
+
+def test_2():
+ H0 = [[3, 0], [1, 2]]
+
+ def f(x):
+ return np.dot(x, np.dot(scipy.linalg.inv(H0), x))
+
+ result1 = minimize(fun=f, method='L-BFGS-B', x0=[10, 20])
+ result2 = minimize(fun=f, method='BFGS', x0=[10, 20])
+
+ H1 = result1.hess_inv.todense()
+
+ H2 = np.vstack((
+ result1.hess_inv(np.array([1, 0])),
+ result1.hess_inv(np.array([0, 1]))))
+
+ assert_allclose(
+ result1.hess_inv(np.array([1, 0]).reshape(2,1)).reshape(-1),
+ result1.hess_inv(np.array([1, 0])))
+ assert_allclose(H1, H2)
+ assert_allclose(H1, result2.hess_inv, rtol=1e-2, atol=0.03)
+
+
+def test_3():
+
+ def todense_old_impl(self):
+ s, y, n_corrs, rho = self.sk, self.yk, self.n_corrs, self.rho
+ I_arr = np.eye(*self.shape, dtype=self.dtype)
+ Hk = I_arr
+
+ for i in range(n_corrs):
+ A1 = I_arr - s[i][:, np.newaxis] * y[i][np.newaxis, :] * rho[i]
+ A2 = I_arr - y[i][:, np.newaxis] * s[i][np.newaxis, :] * rho[i]
+
+ Hk = np.dot(A1, np.dot(Hk, A2)) + (rho[i] * s[i][:, np.newaxis] *
+ s[i][np.newaxis, :])
+ return Hk
+
+ H0 = [[3, 0], [1, 2]]
+
+ def f(x):
+ return np.dot(x, np.dot(scipy.linalg.inv(H0), x))
+
+ result1 = minimize(fun=f, method='L-BFGS-B', x0=[10, 20])
+ assert_allclose(result1.hess_inv.todense(), todense_old_impl(result1.hess_inv))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee47f45509c86968b9b551eb8740ad301fd37958
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lbfgsb_setulb.py
@@ -0,0 +1,122 @@
+import numpy as np
+from scipy.optimize import _lbfgsb, minimize
+
+
+def objfun(x):
+ """simplified objective func to test lbfgsb bound violation"""
+ x0 = [0.8750000000000278,
+ 0.7500000000000153,
+ 0.9499999999999722,
+ 0.8214285714285992,
+ 0.6363636363636085]
+ x1 = [1.0, 0.0, 1.0, 0.0, 0.0]
+ x2 = [1.0,
+ 0.0,
+ 0.9889733043149325,
+ 0.0,
+ 0.026353554421041155]
+ x3 = [1.0,
+ 0.0,
+ 0.9889917442915558,
+ 0.0,
+ 0.020341986743231205]
+
+ f0 = 5163.647901211178
+ f1 = 5149.8181642072905
+ f2 = 5149.379332309634
+ f3 = 5149.374490771297
+
+ g0 = np.array([-0.5934820547965749,
+ 1.6251549718258351,
+ -71.99168459202559,
+ 5.346636965797545,
+ 37.10732723092604])
+ g1 = np.array([-0.43295349282641515,
+ 1.008607936794592,
+ 18.223666726602975,
+ 31.927010036981997,
+ -19.667512518739386])
+ g2 = np.array([-0.4699874455100256,
+ 0.9466285353668347,
+ -0.016874360242016825,
+ 48.44999161133457,
+ 5.819631620590712])
+ g3 = np.array([-0.46970678696829116,
+ 0.9612719312174818,
+ 0.006129809488833699,
+ 48.43557729419473,
+ 6.005481418498221])
+
+ if np.allclose(x, x0):
+ f = f0
+ g = g0
+ elif np.allclose(x, x1):
+ f = f1
+ g = g1
+ elif np.allclose(x, x2):
+ f = f2
+ g = g2
+ elif np.allclose(x, x3):
+ f = f3
+ g = g3
+ else:
+ raise ValueError(
+ 'Simplified objective function not defined '
+ 'at requested point')
+ return (np.copy(f), np.copy(g))
+
+
+def test_setulb_floatround():
+ """test if setulb() violates bounds
+
+ checks for violation due to floating point rounding error
+ """
+
+ n = 5
+ m = 10
+ factr = 1e7
+ pgtol = 1e-5
+ maxls = 20
+ nbd = np.full(shape=(n,), fill_value=2, dtype=np.int32)
+ low_bnd = np.zeros(n, dtype=np.float64)
+ upper_bnd = np.ones(n, dtype=np.float64)
+
+ x0 = np.array(
+ [0.8750000000000278,
+ 0.7500000000000153,
+ 0.9499999999999722,
+ 0.8214285714285992,
+ 0.6363636363636085])
+ x = np.copy(x0)
+
+ f = np.array(0.0, dtype=np.float64)
+ g = np.zeros(n, dtype=np.float64)
+
+ wa = np.zeros(2*m*n + 5*n + 11*m*m + 8*m, dtype=np.float64)
+ iwa = np.zeros(3*n, dtype=np.int32)
+ task = np.zeros(2, dtype=np.int32)
+ ln_task = np.zeros(2, dtype=np.int32)
+ lsave = np.zeros(4, dtype=np.int32)
+ isave = np.zeros(44, dtype=np.int32)
+ dsave = np.zeros(29, dtype=np.float64)
+
+ for n_iter in range(7): # 7 steps required to reproduce error
+ f, g = objfun(x)
+
+ _lbfgsb.setulb(m, x, low_bnd, upper_bnd, nbd, f, g, factr, pgtol, wa,
+ iwa, task, lsave, isave, dsave, maxls, ln_task)
+
+ assert (x <= upper_bnd).all() and (x >= low_bnd).all(), (
+ "_lbfgsb.setulb() stepped to a point outside of the bounds")
+
+
+def test_gh_issue18730():
+ # issue 18730 reported that l-bfgs-b did not work with objectives
+ # returning single precision gradient arrays
+ def fun_single_precision(x):
+ x = x.astype(np.float32)
+ return np.sum(x**2), (2*x)
+
+ res = minimize(fun_single_precision, x0=np.array([1., 1.]), jac=True,
+ method="l-bfgs-b")
+ np.testing.assert_allclose(res.fun, 0., atol=1e-15)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_least_squares.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_least_squares.py
new file mode 100644
index 0000000000000000000000000000000000000000..07587acc4f972e009bb2e72d5b95531140ccd3eb
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_least_squares.py
@@ -0,0 +1,999 @@
+import warnings
+
+from itertools import product
+from multiprocessing import Pool
+
+import numpy as np
+from numpy.linalg import norm
+from numpy.testing import (assert_, assert_allclose,
+ assert_equal)
+import pytest
+from pytest import raises as assert_raises
+from scipy.sparse import issparse, lil_array
+from scipy.sparse.linalg import aslinearoperator
+
+from scipy.optimize import least_squares, Bounds, minimize
+from scipy.optimize._lsq.least_squares import IMPLEMENTED_LOSSES
+from scipy.optimize._lsq.common import EPS, make_strictly_feasible, CL_scaling_vector
+
+from scipy.optimize import OptimizeResult
+
+def fun_trivial(x, a=0):
+ return (x - a)**2 + 5.0
+
+
+def jac_trivial(x, a=0.0):
+ return 2 * (x - a)
+
+
+def fun_2d_trivial(x):
+ return np.array([x[0], x[1]])
+
+
+def jac_2d_trivial(x):
+ return np.identity(2)
+
+
+def fun_rosenbrock(x):
+ return np.array([10 * (x[1] - x[0]**2), (1 - x[0])])
+
+
+class Fun_Rosenbrock:
+ def __init__(self):
+ self.nfev = 0
+
+ def __call__(self, x, a=0):
+ self.nfev += 1
+ return fun_rosenbrock(x)
+
+
+def jac_rosenbrock(x):
+ return np.array([
+ [-20 * x[0], 10],
+ [-1, 0]
+ ])
+
+
+def jac_rosenbrock_bad_dim(x):
+ return np.array([
+ [-20 * x[0], 10],
+ [-1, 0],
+ [0.0, 0.0]
+ ])
+
+
+def fun_rosenbrock_cropped(x):
+ return fun_rosenbrock(x)[0]
+
+
+def jac_rosenbrock_cropped(x):
+ return jac_rosenbrock(x)[0]
+
+
+# When x is 1-D array, return is 2-D array.
+def fun_wrong_dimensions(x):
+ return np.array([x, x**2, x**3])
+
+
+def jac_wrong_dimensions(x, a=0.0):
+ return np.atleast_3d(jac_trivial(x, a=a))
+
+
+def fun_bvp(x):
+ n = int(np.sqrt(x.shape[0]))
+ u = np.zeros((n + 2, n + 2))
+ x = x.reshape((n, n))
+ u[1:-1, 1:-1] = x
+ y = u[:-2, 1:-1] + u[2:, 1:-1] + u[1:-1, :-2] + u[1:-1, 2:] - 4 * x + x**3
+ return y.ravel()
+
+
+class BroydenTridiagonal:
+ def __init__(self, n=100, mode='sparse'):
+ rng = np.random.default_rng(123440)
+
+ self.n = n
+
+ self.x0 = -np.ones(n)
+ self.lb = np.linspace(-2, -1.5, n)
+ self.ub = np.linspace(-0.8, 0.0, n)
+
+ self.lb += 0.1 * rng.standard_normal(n)
+ self.ub += 0.1 * rng.standard_normal(n)
+
+ self.x0 += 0.1 * rng.standard_normal(n)
+ self.x0 = make_strictly_feasible(self.x0, self.lb, self.ub)
+
+ if mode == 'sparse':
+ self.sparsity = lil_array((n, n), dtype=int)
+ i = np.arange(n)
+ self.sparsity[i, i] = 1
+ i = np.arange(1, n)
+ self.sparsity[i, i - 1] = 1
+ i = np.arange(n - 1)
+ self.sparsity[i, i + 1] = 1
+
+ self.jac = self._jac
+ elif mode == 'operator':
+ self.jac = lambda x: aslinearoperator(self._jac(x))
+ elif mode == 'dense':
+ self.sparsity = None
+ self.jac = lambda x: self._jac(x).toarray()
+ else:
+ assert_(False)
+
+ def fun(self, x):
+ f = (3 - x) * x + 1
+ f[1:] -= x[:-1]
+ f[:-1] -= 2 * x[1:]
+ return f
+
+ def _jac(self, x):
+ J = lil_array((self.n, self.n))
+ i = np.arange(self.n)
+ J[i, i] = 3 - 2 * x
+ i = np.arange(1, self.n)
+ J[i, i - 1] = -1
+ i = np.arange(self.n - 1)
+ J[i, i + 1] = -2
+ return J
+
+
+class ExponentialFittingProblem:
+ """Provide data and function for exponential fitting in the form
+ y = a + exp(b * x) + noise."""
+
+ def __init__(self, a, b, noise, n_outliers=1, x_range=(-1, 1),
+ n_points=11, rng=None):
+ rng = np.random.default_rng(rng)
+ self.m = n_points
+ self.n = 2
+
+ self.p0 = np.zeros(2)
+ self.x = np.linspace(x_range[0], x_range[1], n_points)
+
+ self.y = a + np.exp(b * self.x)
+ self.y += noise * rng.standard_normal(self.m)
+
+ outliers = rng.integers(0, self.m, n_outliers)
+ self.y[outliers] += 50 * noise * rng.random(n_outliers)
+
+ self.p_opt = np.array([a, b])
+
+ def fun(self, p):
+ return p[0] + np.exp(p[1] * self.x) - self.y
+
+ def jac(self, p):
+ J = np.empty((self.m, self.n))
+ J[:, 0] = 1
+ J[:, 1] = self.x * np.exp(p[1] * self.x)
+ return J
+
+
+def cubic_soft_l1(z):
+ rho = np.empty((3, z.size))
+
+ t = 1 + z
+ rho[0] = 3 * (t**(1/3) - 1)
+ rho[1] = t ** (-2/3)
+ rho[2] = -2/3 * t**(-5/3)
+
+ return rho
+
+
+LOSSES = list(IMPLEMENTED_LOSSES.keys()) + [cubic_soft_l1]
+
+
+class BaseMixin:
+ msg = "jac='(3-point|cs)' works equivalently to '2-point' for method='lm'"
+ def test_basic(self):
+ # Test that the basic calling sequence works.
+ res = least_squares(fun_trivial, 2., method=self.method)
+ assert_allclose(res.x, 0, atol=1e-4)
+ assert_allclose(res.fun, fun_trivial(res.x))
+
+ def test_args_kwargs(self):
+ # Test that args and kwargs are passed correctly to the functions.
+ a = 3.0
+ for jac in ['2-point', '3-point', 'cs', jac_trivial]:
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", self.msg, UserWarning)
+ res = least_squares(fun_trivial, 2.0, jac, args=(a,),
+ method=self.method)
+ res1 = least_squares(fun_trivial, 2.0, jac, kwargs={'a': a},
+ method=self.method)
+
+ assert_allclose(res.x, a, rtol=1e-4)
+ assert_allclose(res1.x, a, rtol=1e-4)
+
+ assert_raises(TypeError, least_squares, fun_trivial, 2.0,
+ args=(3, 4,), method=self.method)
+ assert_raises(TypeError, least_squares, fun_trivial, 2.0,
+ kwargs={'kaboom': 3}, method=self.method)
+
+ def test_jac_options(self):
+ for jac in ['2-point', '3-point', 'cs', jac_trivial]:
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", self.msg, UserWarning)
+ res = least_squares(fun_trivial, 2.0, jac, method=self.method)
+ assert_allclose(res.x, 0, atol=1e-4)
+
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0, jac='oops',
+ method=self.method)
+
+ def test_nfev_options(self):
+ for max_nfev in [None, 20]:
+ res = least_squares(fun_trivial, 2.0, max_nfev=max_nfev,
+ method=self.method)
+ assert_allclose(res.x, 0, atol=1e-4)
+
+ def test_x_scale_options(self):
+ for x_scale in [1.0, np.array([0.5]), 'jac']:
+ res = least_squares(fun_trivial, 2.0, x_scale=x_scale)
+ assert_allclose(res.x, 0)
+ assert_raises(ValueError, least_squares, fun_trivial,
+ 2.0, x_scale='auto', method=self.method)
+ assert_raises(ValueError, least_squares, fun_trivial,
+ 2.0, x_scale=-1.0, method=self.method)
+ assert_raises(ValueError, least_squares, fun_trivial,
+ 2.0, x_scale=1.0+2.0j, method=self.method)
+
+ def test_diff_step(self):
+ res1 = least_squares(fun_trivial, 2.0, diff_step=1e-1,
+ method=self.method)
+ res3 = least_squares(fun_trivial, 2.0,
+ diff_step=None, method=self.method)
+ assert_allclose(res1.x, 0, atol=1e-4)
+ assert_allclose(res3.x, 0, atol=1e-4)
+
+
+ def test_incorrect_options_usage(self):
+ assert_raises(TypeError, least_squares, fun_trivial, 2.0,
+ method=self.method, options={'no_such_option': 100})
+ assert_raises(TypeError, least_squares, fun_trivial, 2.0,
+ method=self.method, options={'max_nfev': 100})
+
+ def test_full_result(self):
+ # MINPACK doesn't work very well with factor=100 on this problem,
+ # thus using low 'atol'.
+ res = least_squares(fun_trivial, 2.0, method=self.method)
+ assert_allclose(res.x, 0, atol=1e-4)
+ assert_allclose(res.cost, 12.5)
+ assert_allclose(res.fun, 5)
+ assert_allclose(res.jac, 0, atol=1e-4)
+ assert_allclose(res.grad, 0, atol=1e-2)
+ assert_allclose(res.optimality, 0, atol=1e-2)
+ assert_equal(res.active_mask, 0)
+ if self.method == 'lm':
+ assert_(res.njev is None)
+ else:
+ assert_(res.nfev < 10)
+ assert_(res.njev < 10)
+ assert_(res.status > 0)
+ assert_(res.success)
+
+ def test_full_result_single_fev(self):
+ # MINPACK checks the number of nfev after the iteration,
+ # so it's hard to tell what he is going to compute.
+ if self.method == 'lm':
+ return
+
+ res = least_squares(fun_trivial, 2.0, method=self.method,
+ max_nfev=1)
+ assert_equal(res.x, np.array([2]))
+ assert_equal(res.cost, 40.5)
+ assert_equal(res.fun, np.array([9]))
+ assert_equal(res.jac, np.array([[4]]))
+ assert_equal(res.grad, np.array([36]))
+ assert_equal(res.optimality, 36)
+ assert_equal(res.active_mask, np.array([0]))
+ assert_equal(res.nfev, 1)
+ assert_equal(res.njev, 1)
+ assert_equal(res.status, 0)
+ assert_equal(res.success, 0)
+
+ def test_nfev(self):
+ # checks that the true number of nfev are being consumed
+ for i in range(1, 3):
+ rng = np.random.default_rng(128908)
+ x0 = rng.uniform(size=2) * 10
+ ftrivial = Fun_Rosenbrock()
+ res = least_squares(
+ ftrivial, x0, jac=jac_rosenbrock, method=self.method, max_nfev=i
+ )
+ assert res.nfev == ftrivial.nfev
+
+ def test_rosenbrock(self):
+ x0 = [-2, 1]
+ x_opt = [1, 1]
+ for jac, x_scale, tr_solver in product(
+ ['2-point', '3-point', 'cs', jac_rosenbrock],
+ [1.0, np.array([1.0, 0.2]), 'jac'],
+ ['exact', 'lsmr']):
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", self.msg, UserWarning)
+ res = least_squares(fun_rosenbrock, x0, jac, x_scale=x_scale,
+ tr_solver=tr_solver, method=self.method)
+ assert_allclose(res.x, x_opt)
+
+ def test_rosenbrock_cropped(self):
+ x0 = [-2, 1]
+ if self.method == 'lm':
+ assert_raises(ValueError, least_squares, fun_rosenbrock_cropped,
+ x0, method='lm')
+ else:
+ for jac, x_scale, tr_solver in product(
+ ['2-point', '3-point', 'cs', jac_rosenbrock_cropped],
+ [1.0, np.array([1.0, 0.2]), 'jac'],
+ ['exact', 'lsmr']):
+ res = least_squares(
+ fun_rosenbrock_cropped, x0, jac, x_scale=x_scale,
+ tr_solver=tr_solver, method=self.method)
+ assert_allclose(res.cost, 0, atol=1e-14)
+
+ def test_fun_wrong_dimensions(self):
+ assert_raises(ValueError, least_squares, fun_wrong_dimensions,
+ 2.0, method=self.method)
+
+ def test_jac_wrong_dimensions(self):
+ assert_raises(ValueError, least_squares, fun_trivial,
+ 2.0, jac_wrong_dimensions, method=self.method)
+
+ def test_fun_and_jac_inconsistent_dimensions(self):
+ x0 = [1, 2]
+ assert_raises(ValueError, least_squares, fun_rosenbrock, x0,
+ jac_rosenbrock_bad_dim, method=self.method)
+
+ def test_x0_multidimensional(self):
+ x0 = np.ones(4).reshape(2, 2)
+ assert_raises(ValueError, least_squares, fun_trivial, x0,
+ method=self.method)
+
+ def test_x0_complex_scalar(self):
+ x0 = 2.0 + 0.0*1j
+ assert_raises(ValueError, least_squares, fun_trivial, x0,
+ method=self.method)
+
+ def test_x0_complex_array(self):
+ x0 = [1.0, 2.0 + 0.0*1j]
+ assert_raises(ValueError, least_squares, fun_trivial, x0,
+ method=self.method)
+
+ def test_bvp(self):
+ # This test was introduced with fix #5556. It turned out that
+ # dogbox solver had a bug with trust-region radius update, which
+ # could block its progress and create an infinite loop. And this
+ # discrete boundary value problem is the one which triggers it.
+ n = 10
+ x0 = np.ones(n**2)
+ if self.method == 'lm':
+ max_nfev = 5000 # To account for Jacobian estimation.
+ else:
+ max_nfev = 100
+ res = least_squares(fun_bvp, x0, ftol=1e-2, method=self.method,
+ max_nfev=max_nfev)
+
+ assert_(res.nfev < max_nfev)
+ assert_(res.cost < 0.5)
+
+ def test_error_raised_when_all_tolerances_below_eps(self):
+ # Test that all 0 tolerances are not allowed.
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ method=self.method, ftol=None, xtol=None, gtol=None)
+
+ def test_convergence_with_only_one_tolerance_enabled(self):
+ if self.method == 'lm':
+ return # should not do test
+ x0 = [-2, 1]
+ x_opt = [1, 1]
+ for ftol, xtol, gtol in [(1e-8, None, None),
+ (None, 1e-8, None),
+ (None, None, 1e-8)]:
+ res = least_squares(fun_rosenbrock, x0, jac=jac_rosenbrock,
+ ftol=ftol, gtol=gtol, xtol=xtol,
+ method=self.method)
+ assert_allclose(res.x, x_opt)
+
+ # This test is thread safe, but it is too slow and opens
+ # too many file descriptors to run it in parallel.
+ @pytest.mark.parallel_threads_limit(1)
+ @pytest.mark.fail_slow(5.0)
+ def test_workers(self):
+ serial = least_squares(fun_trivial, 2.0, method=self.method)
+
+ reses = []
+ for workers in [None, 2]:
+ res = least_squares(
+ fun_trivial, 2.0, method=self.method, workers=workers
+ )
+ reses.append(res)
+ with Pool(2) as workers:
+ res = least_squares(
+ fun_trivial, 2.0, method=self.method, workers=workers.map
+ )
+ reses.append(res)
+ for res in reses:
+ assert res.success
+ assert_equal(res.x, serial.x)
+ assert_equal(res.nfev, serial.nfev)
+ assert_equal(res.njev, serial.njev)
+
+
+class BoundsMixin:
+ def test_inconsistent(self):
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ bounds=(10.0, 0.0), method=self.method)
+
+ def test_infeasible(self):
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ bounds=(3., 4), method=self.method)
+
+ def test_wrong_number(self):
+ assert_raises(ValueError, least_squares, fun_trivial, 2.,
+ bounds=(1., 2, 3), method=self.method)
+
+ def test_inconsistent_shape(self):
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ bounds=(1.0, [2.0, 3.0]), method=self.method)
+ # 1-D array won't be broadcast
+ assert_raises(ValueError, least_squares, fun_rosenbrock, [1.0, 2.0],
+ bounds=([0.0], [3.0, 4.0]), method=self.method)
+
+ def test_in_bounds(self):
+ for jac in ['2-point', '3-point', 'cs', jac_trivial]:
+ res = least_squares(fun_trivial, 2.0, jac=jac,
+ bounds=(-1.0, 3.0), method=self.method)
+ assert_allclose(res.x, 0.0, atol=1e-4)
+ assert_equal(res.active_mask, [0])
+ assert_(-1 <= res.x <= 3)
+ res = least_squares(fun_trivial, 2.0, jac=jac,
+ bounds=(0.5, 3.0), method=self.method)
+ assert_allclose(res.x, 0.5, atol=1e-4)
+ assert_equal(res.active_mask, [-1])
+ assert_(0.5 <= res.x <= 3)
+
+ def test_bounds_shape(self):
+ def get_bounds_direct(lb, ub):
+ return lb, ub
+
+ def get_bounds_instances(lb, ub):
+ return Bounds(lb, ub)
+
+ for jac in ['2-point', '3-point', 'cs', jac_2d_trivial]:
+ for bounds_func in [get_bounds_direct, get_bounds_instances]:
+ x0 = [1.0, 1.0]
+ res = least_squares(fun_2d_trivial, x0, jac=jac)
+ assert_allclose(res.x, [0.0, 0.0])
+ res = least_squares(fun_2d_trivial, x0, jac=jac,
+ bounds=bounds_func(0.5, [2.0, 2.0]),
+ method=self.method)
+ assert_allclose(res.x, [0.5, 0.5])
+ res = least_squares(fun_2d_trivial, x0, jac=jac,
+ bounds=bounds_func([0.3, 0.2], 3.0),
+ method=self.method)
+ assert_allclose(res.x, [0.3, 0.2])
+ res = least_squares(
+ fun_2d_trivial, x0, jac=jac,
+ bounds=bounds_func([-1, 0.5], [1.0, 3.0]),
+ method=self.method)
+ assert_allclose(res.x, [0.0, 0.5], atol=1e-5)
+
+ def test_bounds_instances(self):
+ res = least_squares(fun_trivial, 0.5, bounds=Bounds())
+ assert_allclose(res.x, 0.0, atol=1e-4)
+
+ res = least_squares(fun_trivial, 3.0, bounds=Bounds(lb=1.0))
+ assert_allclose(res.x, 1.0, atol=1e-4)
+
+ res = least_squares(fun_trivial, 0.5, bounds=Bounds(lb=-1.0, ub=1.0))
+ assert_allclose(res.x, 0.0, atol=1e-4)
+
+ res = least_squares(fun_trivial, -3.0, bounds=Bounds(ub=-1.0))
+ assert_allclose(res.x, -1.0, atol=1e-4)
+
+ res = least_squares(fun_2d_trivial, [0.5, 0.5],
+ bounds=Bounds(lb=[-1.0, -1.0], ub=1.0))
+ assert_allclose(res.x, [0.0, 0.0], atol=1e-5)
+
+ res = least_squares(fun_2d_trivial, [0.5, 0.5],
+ bounds=Bounds(lb=[0.1, 0.1]))
+ assert_allclose(res.x, [0.1, 0.1], atol=1e-5)
+
+ @pytest.mark.fail_slow(10)
+ def test_rosenbrock_bounds(self):
+ x0_1 = np.array([-2.0, 1.0])
+ x0_2 = np.array([2.0, 2.0])
+ x0_3 = np.array([-2.0, 2.0])
+ x0_4 = np.array([0.0, 2.0])
+ x0_5 = np.array([-1.2, 1.0])
+ problems = [
+ (x0_1, ([-np.inf, -1.5], np.inf)),
+ (x0_2, ([-np.inf, 1.5], np.inf)),
+ (x0_3, ([-np.inf, 1.5], np.inf)),
+ (x0_4, ([-np.inf, 1.5], [1.0, np.inf])),
+ (x0_2, ([1.0, 1.5], [3.0, 3.0])),
+ (x0_5, ([-50.0, 0.0], [0.5, 100]))
+ ]
+ for x0, bounds in problems:
+ for jac, x_scale, tr_solver in product(
+ ['2-point', '3-point', 'cs', jac_rosenbrock],
+ [1.0, [1.0, 0.5], 'jac'],
+ ['exact', 'lsmr']):
+ res = least_squares(fun_rosenbrock, x0, jac, bounds,
+ x_scale=x_scale, tr_solver=tr_solver,
+ method=self.method)
+ assert_allclose(res.optimality, 0.0, atol=1e-5)
+
+
+class SparseMixin:
+ def test_exact_tr_solver(self):
+ p = BroydenTridiagonal()
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ tr_solver='exact', method=self.method)
+ assert_raises(ValueError, least_squares, p.fun, p.x0,
+ tr_solver='exact', jac_sparsity=p.sparsity,
+ method=self.method)
+
+ def test_equivalence(self):
+ sparse = BroydenTridiagonal(mode='sparse')
+ dense = BroydenTridiagonal(mode='dense')
+ res_sparse = least_squares(
+ sparse.fun, sparse.x0, jac=sparse.jac,
+ method=self.method)
+ res_dense = least_squares(
+ dense.fun, dense.x0, jac=sparse.jac,
+ method=self.method)
+ assert_equal(res_sparse.nfev, res_dense.nfev)
+ assert_allclose(res_sparse.x, res_dense.x, atol=1e-20)
+ assert_allclose(res_sparse.cost, 0, atol=1e-20)
+ assert_allclose(res_dense.cost, 0, atol=1e-20)
+
+ def test_tr_options(self):
+ p = BroydenTridiagonal()
+ res = least_squares(p.fun, p.x0, p.jac, method=self.method,
+ tr_options={'btol': 1e-10})
+ assert_allclose(res.cost, 0, atol=1e-20)
+
+ def test_wrong_parameters(self):
+ p = BroydenTridiagonal()
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ tr_solver='best', method=self.method)
+ assert_raises(TypeError, least_squares, p.fun, p.x0, p.jac,
+ tr_solver='lsmr', tr_options={'tol': 1e-10})
+
+ def test_solver_selection(self):
+ sparse = BroydenTridiagonal(mode='sparse')
+ dense = BroydenTridiagonal(mode='dense')
+ res_sparse = least_squares(sparse.fun, sparse.x0, jac=sparse.jac,
+ method=self.method)
+ res_dense = least_squares(dense.fun, dense.x0, jac=dense.jac,
+ method=self.method)
+ assert_allclose(res_sparse.cost, 0, atol=1e-20)
+ assert_allclose(res_dense.cost, 0, atol=1e-20)
+ assert_(issparse(res_sparse.jac))
+ assert_(isinstance(res_dense.jac, np.ndarray))
+
+ def test_numerical_jac(self):
+ p = BroydenTridiagonal()
+ for jac in ['2-point', '3-point', 'cs']:
+ res_dense = least_squares(p.fun, p.x0, jac, method=self.method)
+ res_sparse = least_squares(
+ p.fun, p.x0, jac,method=self.method,
+ jac_sparsity=p.sparsity)
+ assert_equal(res_dense.nfev, res_sparse.nfev)
+ assert_allclose(res_dense.x, res_sparse.x, atol=1e-20)
+ assert_allclose(res_dense.cost, 0, atol=1e-20)
+ assert_allclose(res_sparse.cost, 0, atol=1e-20)
+
+ @pytest.mark.fail_slow(10)
+ def test_with_bounds(self):
+ p = BroydenTridiagonal()
+ for jac, jac_sparsity in product(
+ [p.jac, '2-point', '3-point', 'cs'], [None, p.sparsity]):
+ res_1 = least_squares(
+ p.fun, p.x0, jac, bounds=(p.lb, np.inf),
+ method=self.method,jac_sparsity=jac_sparsity)
+ res_2 = least_squares(
+ p.fun, p.x0, jac, bounds=(-np.inf, p.ub),
+ method=self.method, jac_sparsity=jac_sparsity)
+ res_3 = least_squares(
+ p.fun, p.x0, jac, bounds=(p.lb, p.ub),
+ method=self.method, jac_sparsity=jac_sparsity)
+ assert_allclose(res_1.optimality, 0, atol=1e-10)
+ assert_allclose(res_2.optimality, 0, atol=1e-10)
+ assert_allclose(res_3.optimality, 0, atol=1e-10)
+
+ def test_wrong_jac_sparsity(self):
+ p = BroydenTridiagonal()
+ sparsity = p.sparsity[:-1]
+ assert_raises(ValueError, least_squares, p.fun, p.x0,
+ jac_sparsity=sparsity, method=self.method)
+
+ def test_linear_operator(self):
+ p = BroydenTridiagonal(mode='operator')
+ res = least_squares(p.fun, p.x0, p.jac, method=self.method)
+ assert_allclose(res.cost, 0.0, atol=1e-20)
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ method=self.method, tr_solver='exact')
+
+ def test_x_scale_jac_scale(self):
+ p = BroydenTridiagonal()
+ res = least_squares(p.fun, p.x0, p.jac, method=self.method,
+ x_scale='jac')
+ assert_allclose(res.cost, 0.0, atol=1e-20)
+
+ p = BroydenTridiagonal(mode='operator')
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ method=self.method, x_scale='jac')
+
+
+class LossFunctionMixin:
+ def test_options(self):
+ for loss in LOSSES:
+ res = least_squares(fun_trivial, 2.0, loss=loss,
+ method=self.method)
+ assert_allclose(res.x, 0, atol=1e-15)
+
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ loss='hinge', method=self.method)
+
+ def test_fun(self):
+ # Test that res.fun is actual residuals, and not modified by loss
+ # function stuff.
+ for loss in LOSSES:
+ res = least_squares(fun_trivial, 2.0, loss=loss,
+ method=self.method)
+ assert_equal(res.fun, fun_trivial(res.x))
+
+ def test_grad(self):
+ # Test that res.grad is true gradient of loss function at the
+ # solution. Use max_nfev = 1, to avoid reaching minimum.
+ x = np.array([2.0]) # res.x will be this.
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='linear',
+ max_nfev=1, method=self.method)
+ assert_equal(res.grad, 2 * x * (x**2 + 5))
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='huber',
+ max_nfev=1, method=self.method)
+ assert_equal(res.grad, 2 * x)
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='soft_l1',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.grad,
+ 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**2)**0.5)
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='cauchy',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.grad, 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**2))
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='arctan',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.grad, 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**4))
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss=cubic_soft_l1,
+ max_nfev=1, method=self.method)
+ assert_allclose(res.grad,
+ 2 * x * (x**2 + 5) / (1 + (x**2 + 5)**2)**(2/3))
+
+ def test_jac(self):
+ # Test that res.jac.T.dot(res.jac) gives Gauss-Newton approximation
+ # of Hessian. This approximation is computed by doubly differentiating
+ # the cost function and dropping the part containing second derivative
+ # of f. For a scalar function it is computed as
+ # H = (rho' + 2 * rho'' * f**2) * f'**2, if the expression inside the
+ # brackets is less than EPS it is replaced by EPS. Here, we check
+ # against the root of H.
+
+ x = 2.0 # res.x will be this.
+ f = x**2 + 5 # res.fun will be this.
+
+ res = least_squares(fun_trivial, x, jac_trivial, loss='linear',
+ max_nfev=1, method=self.method)
+ assert_equal(res.jac, 2 * x)
+
+ # For `huber` loss the Jacobian correction is identically zero
+ # in outlier region, in such cases it is modified to be equal EPS**0.5.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='huber',
+ max_nfev=1, method=self.method)
+ assert_equal(res.jac, 2 * x * EPS**0.5)
+
+ # Now, let's apply `loss_scale` to turn the residual into an inlier.
+ # The loss function becomes linear.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='huber',
+ f_scale=10, max_nfev=1)
+ assert_equal(res.jac, 2 * x)
+
+ # 'soft_l1' always gives a positive scaling.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='soft_l1',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.jac, 2 * x * (1 + f**2)**-0.75)
+
+ # For 'cauchy' the correction term turns out to be negative, and it
+ # replaced by EPS**0.5.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='cauchy',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.jac, 2 * x * EPS**0.5)
+
+ # Now use scaling to turn the residual to inlier.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='cauchy',
+ f_scale=10, max_nfev=1, method=self.method)
+ fs = f / 10
+ assert_allclose(res.jac, 2 * x * (1 - fs**2)**0.5 / (1 + fs**2))
+
+ # 'arctan' gives an outlier.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='arctan',
+ max_nfev=1, method=self.method)
+ assert_allclose(res.jac, 2 * x * EPS**0.5)
+
+ # Turn to inlier.
+ res = least_squares(fun_trivial, x, jac_trivial, loss='arctan',
+ f_scale=20.0, max_nfev=1, method=self.method)
+ fs = f / 20
+ assert_allclose(res.jac, 2 * x * (1 - 3 * fs**4)**0.5 / (1 + fs**4))
+
+ # cubic_soft_l1 will give an outlier.
+ res = least_squares(fun_trivial, x, jac_trivial, loss=cubic_soft_l1,
+ max_nfev=1)
+ assert_allclose(res.jac, 2 * x * EPS**0.5)
+
+ # Turn to inlier.
+ res = least_squares(fun_trivial, x, jac_trivial,
+ loss=cubic_soft_l1, f_scale=6, max_nfev=1)
+ fs = f / 6
+ assert_allclose(res.jac,
+ 2 * x * (1 - fs**2 / 3)**0.5 * (1 + fs**2)**(-5/6))
+
+ def test_robustness(self):
+ for noise in [0.1, 1.0]:
+ p = ExponentialFittingProblem(1, 0.1, noise, rng=12220903)
+
+ for jac in ['2-point', '3-point', 'cs', p.jac]:
+ res_lsq = least_squares(p.fun, p.p0, jac=jac,
+ method=self.method)
+ assert_allclose(res_lsq.optimality, 0, atol=1e-2)
+ for loss in LOSSES:
+ if loss == 'linear':
+ continue
+ res_robust = least_squares(
+ p.fun, p.p0, jac=jac, loss=loss, f_scale=noise,
+ method=self.method)
+ assert_allclose(res_robust.optimality, 0, atol=1e-2)
+ assert_(norm(res_robust.x - p.p_opt) <
+ norm(res_lsq.x - p.p_opt))
+
+
+class TestDogbox(BaseMixin, BoundsMixin, SparseMixin, LossFunctionMixin):
+ method = 'dogbox'
+
+
+class TestTRF(BaseMixin, BoundsMixin, SparseMixin, LossFunctionMixin):
+ method = 'trf'
+
+ def test_lsmr_regularization(self):
+ p = BroydenTridiagonal()
+ for regularize in [True, False]:
+ res = least_squares(p.fun, p.x0, p.jac, method='trf',
+ tr_options={'regularize': regularize})
+ assert_allclose(res.cost, 0, atol=1e-20)
+
+
+class TestLM(BaseMixin):
+ method = 'lm'
+
+ def test_bounds_not_supported(self):
+ assert_raises(ValueError, least_squares, fun_trivial,
+ 2.0, bounds=(-3.0, 3.0), method='lm')
+
+ def test_m_less_n_not_supported(self):
+ x0 = [-2, 1]
+ assert_raises(ValueError, least_squares, fun_rosenbrock_cropped, x0,
+ method='lm')
+
+ def test_sparse_not_supported(self):
+ p = BroydenTridiagonal()
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ method='lm')
+
+ def test_jac_sparsity_not_supported(self):
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ jac_sparsity=[1], method='lm')
+
+ def test_LinearOperator_not_supported(self):
+ p = BroydenTridiagonal(mode="operator")
+ assert_raises(ValueError, least_squares, p.fun, p.x0, p.jac,
+ method='lm')
+
+ def test_loss(self):
+ res = least_squares(fun_trivial, 2.0, loss='linear', method='lm')
+ assert_allclose(res.x, 0.0, atol=1e-4)
+
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0,
+ method='lm', loss='huber')
+
+ def test_callback_with_lm_method(self):
+ def callback(x):
+ assert(False) # Dummy callback function
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "Callback function specified, but not supported with `lm` method.",
+ UserWarning,
+ )
+ least_squares(fun_trivial, x0=[0], method='lm', callback=callback)
+
+
+def test_basic():
+ # test that 'method' arg is really optional
+ res = least_squares(fun_trivial, 2.0)
+ assert_allclose(res.x, 0, atol=1e-10)
+
+
+def test_callback():
+ # test that callback function works as expected
+
+ results = []
+
+ def my_callback_optimresult(intermediate_result: OptimizeResult):
+ results.append(intermediate_result)
+
+ def my_callback_x(x):
+ r = OptimizeResult()
+ r.nit = 1
+ r.x = x
+ results.append(r)
+ return False
+
+ def my_callback_optimresult_stop_exception(
+ intermediate_result: OptimizeResult):
+ results.append(intermediate_result)
+ raise StopIteration
+
+ def my_callback_x_stop_exception(x):
+ r = OptimizeResult()
+ r.nit = 1
+ r.x = x
+ results.append(r)
+ raise StopIteration
+
+ # Try for different function signatures and stop methods
+ callbacks_nostop = [my_callback_optimresult, my_callback_x]
+ callbacks_stop = [my_callback_optimresult_stop_exception,
+ my_callback_x_stop_exception]
+
+ # Try for all the implemented methods: trf, trf_bounds and dogbox
+ calls = [
+ lambda callback: least_squares(fun_trivial, 5.0, method='trf',
+ callback=callback),
+ lambda callback: least_squares(fun_trivial, 5.0, method='trf',
+ bounds=(-8.0, 8.0), callback=callback),
+ lambda callback: least_squares(fun_trivial, 5.0, method='dogbox',
+ callback=callback)
+ ]
+
+ for mycallback, call in product(callbacks_nostop, calls):
+ results.clear()
+ # Call the different implemented methods
+ res = call(mycallback)
+ # Check that callback was called
+ assert len(results) > 0
+ # Check that results data makes sense
+ assert results[-1].nit > 0
+ # Check that it didn't stop because of the callback
+ assert res.status != -2
+ # final callback x should be same as final result
+ assert_allclose(results[-1].x, res.x)
+
+ for mycallback, call in product(callbacks_stop, calls):
+ results.clear()
+ # Call the different implemented methods
+ res = call(mycallback)
+ # Check that callback was called
+ assert len(results) > 0
+ # Check that only one iteration was run
+ assert results[-1].nit == 1
+ # Check that it stopped because of the callback
+ assert res.status == -2
+
+
+def test_small_tolerances_for_lm():
+ for ftol, xtol, gtol in [(None, 1e-13, 1e-13),
+ (1e-13, None, 1e-13),
+ (1e-13, 1e-13, None)]:
+ assert_raises(ValueError, least_squares, fun_trivial, 2.0, xtol=xtol,
+ ftol=ftol, gtol=gtol, method='lm')
+
+
+def test_fp32_gh12991():
+ # checks that smaller FP sizes can be used in least_squares
+ # this is the minimum working example reported for gh12991
+ rng = np.random.default_rng(1978)
+
+ x = np.linspace(0, 1, 100, dtype=np.float32)
+ y = rng.random(size=100, dtype=np.float32)
+
+ # changed in gh21872. These functions should've been working in fp32 to force
+ # approx_derivative to work in fp32. One of the initial steps in least_squares
+ # is to force x0 (p) to be a float, meaning that the output of func and err would
+ # be in float64, unless forced to be in float32
+ def func(p, x):
+ return (p[0] + p[1] * x).astype(np.float32)
+
+ def err(p, x, y):
+ return (func(p, x) - y).astype(np.float32)
+
+ def mse(p, x, y):
+ return np.sum(err(p, x, y)**2)
+
+ res = least_squares(err, [-1.0, -1.0], args=(x, y))
+ # previously the initial jacobian calculated for this would be all 0
+ # and the minimize would terminate immediately, with nfev=1, would
+ # report a successful minimization (it shouldn't have done), but be
+ # unchanged from the initial solution.
+ # It was terminating early because the underlying approx_derivative
+ # used a step size for FP64 when the working space was FP32.
+ assert res.nfev > 2
+ # compare output to solver that doesn't use derivatives
+ res2 = minimize(
+ mse,
+ [-1.0, 1.0],
+ method='cobyqa',
+ args=(x, y),
+ options={'final_tr_radius': 1e-6}
+ )
+ assert_allclose(res.x, res2.x, atol=9e-5)
+
+
+def test_gh_18793_and_19351():
+ answer = 1e-12
+ initial_guess = 1.1e-12
+
+ def chi2(x):
+ return (x-answer)**2
+
+ gtol = 1e-15
+ res = least_squares(chi2, x0=initial_guess, gtol=1e-15, bounds=(0, np.inf))
+ # Original motivation: gh-18793
+ # if we choose an initial condition that is close to the solution
+ # we shouldn't return an answer that is further away from the solution
+
+ # Update: gh-19351
+ # However this requirement does not go well with 'trf' algorithm logic.
+ # Some regressions were reported after the presumed fix.
+ # The returned solution is good as long as it satisfies the convergence
+ # conditions.
+ # Specifically in this case the scaled gradient will be sufficiently low.
+
+ scaling, _ = CL_scaling_vector(res.x, res.grad,
+ np.atleast_1d(0), np.atleast_1d(np.inf))
+ assert res.status == 1 # Converged by gradient
+ assert np.linalg.norm(res.grad * scaling, ord=np.inf) < gtol
+
+
+def test_gh_19103():
+ # Checks that least_squares trf method selects a strictly feasible point,
+ # and thus succeeds instead of failing,
+ # when the initial guess is reported exactly at a boundary point.
+ # This is a reduced example from gh191303
+
+ ydata = np.array([0.] * 66 + [
+ 1., 0., 0., 0., 0., 0., 1., 1., 0., 0., 1.,
+ 1., 1., 1., 0., 0., 0., 1., 0., 0., 2., 1.,
+ 0., 3., 1., 6., 5., 0., 0., 2., 8., 4., 4.,
+ 6., 9., 7., 2., 7., 8., 2., 13., 9., 8., 11.,
+ 10., 13., 14., 19., 11., 15., 18., 26., 19., 32., 29.,
+ 28., 36., 32., 35., 36., 43., 52., 32., 58., 56., 52.,
+ 67., 53., 72., 88., 77., 95., 94., 84., 86., 101., 107.,
+ 108., 118., 96., 115., 138., 137.,
+ ])
+ xdata = np.arange(0, ydata.size) * 0.1
+
+ def exponential_wrapped(params):
+ A, B, x0 = params
+ return A * np.exp(B * (xdata - x0)) - ydata
+
+ x0 = [0.01, 1., 5.]
+ bounds = ((0.01, 0, 0), (np.inf, 10, 20.9))
+ res = least_squares(exponential_wrapped, x0, method='trf', bounds=bounds)
+ assert res.success
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_linear_assignment.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_linear_assignment.py
new file mode 100644
index 0000000000000000000000000000000000000000..523ed78f5115b02349c35eb94e601fd31f03936d
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_linear_assignment.py
@@ -0,0 +1,116 @@
+# Author: Brian M. Clapper, G. Varoquaux, Lars Buitinck
+# License: BSD
+
+from numpy.testing import assert_array_equal
+import pytest
+
+import numpy as np
+
+from scipy.optimize import linear_sum_assignment
+from scipy.sparse import random_array
+from scipy.sparse._sputils import matrix
+from scipy.sparse.csgraph import min_weight_full_bipartite_matching
+from scipy.sparse.csgraph.tests.test_matching import (
+ linear_sum_assignment_assertions, linear_sum_assignment_test_cases
+)
+
+
+def test_linear_sum_assignment_input_shape():
+ with pytest.raises(ValueError, match="expected a matrix"):
+ linear_sum_assignment([1, 2, 3])
+
+
+def test_linear_sum_assignment_input_object():
+ C = [[1, 2, 3], [4, 5, 6]]
+ assert_array_equal(linear_sum_assignment(C),
+ linear_sum_assignment(np.asarray(C)))
+ assert_array_equal(linear_sum_assignment(C),
+ linear_sum_assignment(matrix(C)))
+
+
+def test_linear_sum_assignment_input_bool():
+ I = np.identity(3)
+ assert_array_equal(linear_sum_assignment(I.astype(np.bool_)),
+ linear_sum_assignment(I))
+
+
+def test_linear_sum_assignment_input_string():
+ I = np.identity(3)
+ with pytest.raises(TypeError, match="Cannot cast array data"):
+ linear_sum_assignment(I.astype(str))
+
+
+def test_linear_sum_assignment_input_nan():
+ I = np.diag([np.nan, 1, 1])
+ with pytest.raises(ValueError, match="contains invalid numeric entries"):
+ linear_sum_assignment(I)
+
+
+def test_linear_sum_assignment_input_neginf():
+ I = np.diag([1, -np.inf, 1])
+ with pytest.raises(ValueError, match="contains invalid numeric entries"):
+ linear_sum_assignment(I)
+
+
+def test_linear_sum_assignment_input_inf():
+ I = np.identity(3)
+ I[:, 0] = np.inf
+ with pytest.raises(ValueError, match="cost matrix is infeasible"):
+ linear_sum_assignment(I)
+
+
+def test_constant_cost_matrix():
+ # Fixes #11602
+ n = 8
+ C = np.ones((n, n))
+ row_ind, col_ind = linear_sum_assignment(C)
+ assert_array_equal(row_ind, np.arange(n))
+ assert_array_equal(col_ind, np.arange(n))
+
+
+@pytest.mark.parametrize('num_rows,num_cols', [(0, 0), (2, 0), (0, 3)])
+def test_linear_sum_assignment_trivial_cost(num_rows, num_cols):
+ C = np.empty(shape=(num_cols, num_rows))
+ row_ind, col_ind = linear_sum_assignment(C)
+ assert len(row_ind) == 0
+ assert len(col_ind) == 0
+
+
+@pytest.mark.parametrize('sign,test_case', linear_sum_assignment_test_cases)
+def test_linear_sum_assignment_small_inputs(sign, test_case):
+ linear_sum_assignment_assertions(
+ linear_sum_assignment, np.array, sign, test_case)
+
+
+# Tests that combine scipy.optimize.linear_sum_assignment and
+# scipy.sparse.csgraph.min_weight_full_bipartite_matching
+def test_two_methods_give_same_result_on_many_sparse_inputs():
+ # As opposed to the test above, here we do not spell out the expected
+ # output; only assert that the two methods give the same result.
+ # Concretely, the below tests 100 cases of size 100x100, out of which
+ # 36 are infeasible.
+ rng = np.random.default_rng(12342309)
+ for _ in range(100):
+ lsa_raises = False
+ mwfbm_raises = False
+ sparse = random_array((100, 100), density=0.06,
+ data_sampler=lambda size: rng.integers(1, 100, size))
+ # In csgraph, zeros correspond to missing edges, so we explicitly
+ # replace those with infinities
+ dense = np.full(sparse.shape, np.inf)
+ dense[sparse.row, sparse.col] = sparse.data
+ sparse = sparse.tocsr()
+ try:
+ row_ind, col_ind = linear_sum_assignment(dense)
+ lsa_cost = dense[row_ind, col_ind].sum()
+ except ValueError:
+ lsa_raises = True
+ try:
+ row_ind, col_ind = min_weight_full_bipartite_matching(sparse)
+ mwfbm_cost = sparse[row_ind, col_ind].sum()
+ except ValueError:
+ mwfbm_raises = True
+ # Ensure that if one method raises, so does the other one.
+ assert lsa_raises == mwfbm_raises
+ if not lsa_raises:
+ assert lsa_cost == mwfbm_cost
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_linesearch.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_linesearch.py
new file mode 100644
index 0000000000000000000000000000000000000000..4a76b9248b2dd3e257196877261d1ab7bedd2532
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_linesearch.py
@@ -0,0 +1,334 @@
+"""
+Tests for line search routines
+"""
+import warnings
+
+from numpy.testing import (assert_equal, assert_array_almost_equal,
+ assert_array_almost_equal_nulp)
+import scipy.optimize._linesearch as ls
+from scipy.optimize._linesearch import LineSearchWarning
+import numpy as np
+import pytest
+import threading
+
+
+def assert_wolfe(s, phi, derphi, c1=1e-4, c2=0.9, err_msg=""):
+ """
+ Check that strong Wolfe conditions apply
+ """
+ phi1 = phi(s)
+ phi0 = phi(0)
+ derphi0 = derphi(0)
+ derphi1 = derphi(s)
+ msg = (f"s = {s}; phi(0) = {phi0}; phi(s) = {phi1}; phi'(0) = {derphi0};"
+ f" phi'(s) = {derphi1}; {err_msg}")
+
+ assert phi1 <= phi0 + c1*s*derphi0, "Wolfe 1 failed: " + msg
+ assert abs(derphi1) <= abs(c2*derphi0), "Wolfe 2 failed: " + msg
+
+
+def assert_armijo(s, phi, c1=1e-4, err_msg=""):
+ """
+ Check that Armijo condition applies
+ """
+ phi1 = phi(s)
+ phi0 = phi(0)
+ msg = f"s = {s}; phi(0) = {phi0}; phi(s) = {phi1}; {err_msg}"
+ assert phi1 <= (1 - c1*s)*phi0, msg
+
+
+def assert_line_wolfe(x, p, s, f, fprime, **kw):
+ assert_wolfe(s, phi=lambda sp: f(x + p*sp),
+ derphi=lambda sp: np.dot(fprime(x + p*sp), p), **kw)
+
+
+def assert_line_armijo(x, p, s, f, **kw):
+ assert_armijo(s, phi=lambda sp: f(x + p*sp), **kw)
+
+
+def assert_fp_equal(x, y, err_msg="", nulp=50):
+ """Assert two arrays are equal, up to some floating-point rounding error"""
+ try:
+ assert_array_almost_equal_nulp(x, y, nulp)
+ except AssertionError as e:
+ raise AssertionError(f"{e}\n{err_msg}") from e
+
+
+class TestLineSearch:
+ # -- scalar functions; must have dphi(0.) < 0
+ def _scalar_func_1(self, s): # skip name check
+ if not hasattr(self.fcount, 'c'):
+ self.fcount.c = 0
+ self.fcount.c += 1
+ p = -s - s**3 + s**4
+ dp = -1 - 3*s**2 + 4*s**3
+ return p, dp
+
+ def _scalar_func_2(self, s): # skip name check
+ if not hasattr(self.fcount, 'c'):
+ self.fcount.c = 0
+ self.fcount.c += 1
+ p = np.exp(-4*s) + s**2
+ dp = -4*np.exp(-4*s) + 2*s
+ return p, dp
+
+ def _scalar_func_3(self, s): # skip name check
+ if not hasattr(self.fcount, 'c'):
+ self.fcount.c = 0
+ self.fcount.c += 1
+ p = -np.sin(10*s)
+ dp = -10*np.cos(10*s)
+ return p, dp
+
+ # -- n-d functions
+
+ def _line_func_1(self, x): # skip name check
+ if not hasattr(self.fcount, 'c'):
+ self.fcount.c = 0
+ self.fcount.c += 1
+ f = np.dot(x, x)
+ df = 2*x
+ return f, df
+
+ def _line_func_2(self, x): # skip name check
+ if not hasattr(self.fcount, 'c'):
+ self.fcount.c = 0
+ self.fcount.c += 1
+ f = np.dot(x, np.dot(self.A, x)) + 1
+ df = np.dot(self.A + self.A.T, x)
+ return f, df
+
+ # --
+
+ def setup_method(self):
+ self.scalar_funcs = []
+ self.line_funcs = []
+ self.N = 20
+ self.fcount = threading.local()
+
+ def bind_index(func, idx):
+ # Remember Python's closure semantics!
+ return lambda *a, **kw: func(*a, **kw)[idx]
+
+ for name in sorted(dir(self)):
+ if name.startswith('_scalar_func_'):
+ value = getattr(self, name)
+ self.scalar_funcs.append(
+ (name, bind_index(value, 0), bind_index(value, 1)))
+ elif name.startswith('_line_func_'):
+ value = getattr(self, name)
+ self.line_funcs.append(
+ (name, bind_index(value, 0), bind_index(value, 1)))
+
+ # the choice of seed affects whether the tests pass
+ rng = np.random.default_rng(1231892908)
+ self.A = rng.standard_normal((self.N, self.N))
+
+ def scalar_iter(self):
+ rng = np.random.default_rng(2231892908)
+ for name, phi, derphi in self.scalar_funcs:
+ for old_phi0 in rng.standard_normal(3):
+ yield name, phi, derphi, old_phi0
+
+ def line_iter(self):
+ rng = np.random.default_rng(2231892908)
+ for name, f, fprime in self.line_funcs:
+ k = 0
+ while k < 9:
+ x = rng.standard_normal(self.N)
+ p = rng.standard_normal(self.N)
+ if np.dot(p, fprime(x)) >= 0:
+ # always pick a descent direction
+ continue
+ k += 1
+ old_fv = float(rng.standard_normal())
+ yield name, f, fprime, x, p, old_fv
+
+ # -- Generic scalar searches
+
+ def test_scalar_search_wolfe1(self):
+ c = 0
+ for name, phi, derphi, old_phi0 in self.scalar_iter():
+ c += 1
+ s, phi1, phi0 = ls.scalar_search_wolfe1(phi, derphi, phi(0),
+ old_phi0, derphi(0))
+ assert_fp_equal(phi0, phi(0), name)
+ assert_fp_equal(phi1, phi(s), name)
+ assert_wolfe(s, phi, derphi, err_msg=name)
+
+ assert c > 3 # check that the iterator really works...
+
+ def test_scalar_search_wolfe2(self):
+ for name, phi, derphi, old_phi0 in self.scalar_iter():
+ s, phi1, phi0, derphi1 = ls.scalar_search_wolfe2(
+ phi, derphi, phi(0), old_phi0, derphi(0))
+ assert_fp_equal(phi0, phi(0), name)
+ assert_fp_equal(phi1, phi(s), name)
+ if derphi1 is not None:
+ assert_fp_equal(derphi1, derphi(s), name)
+ assert_wolfe(s, phi, derphi, err_msg=f"{name} {old_phi0:g}")
+
+ def test_scalar_search_wolfe2_with_low_amax(self):
+ def phi(alpha):
+ return (alpha - 5) ** 2
+
+ def derphi(alpha):
+ return 2 * (alpha - 5)
+
+ alpha_star, _, _, derphi_star = ls.scalar_search_wolfe2(phi, derphi, amax=0.001)
+ assert alpha_star is None # Not converged
+ assert derphi_star is None # Not converged
+
+ def test_scalar_search_wolfe2_regression(self):
+ # Regression test for gh-12157
+ # This phi has its minimum at alpha=4/3 ~ 1.333.
+ def phi(alpha):
+ if alpha < 1:
+ return - 3*np.pi/2 * (alpha - 1)
+ else:
+ return np.cos(3*np.pi/2 * alpha - np.pi)
+
+ def derphi(alpha):
+ if alpha < 1:
+ return - 3*np.pi/2
+ else:
+ return - 3*np.pi/2 * np.sin(3*np.pi/2 * alpha - np.pi)
+
+ s, _, _, _ = ls.scalar_search_wolfe2(phi, derphi)
+ # Without the fix in gh-13073, the scalar_search_wolfe2
+ # returned s=2.0 instead.
+ assert s < 1.5
+
+ def test_scalar_search_armijo(self):
+ for name, phi, derphi, old_phi0 in self.scalar_iter():
+ s, phi1 = ls.scalar_search_armijo(phi, phi(0), derphi(0))
+ assert_fp_equal(phi1, phi(s), name)
+ assert_armijo(s, phi, err_msg=f"{name} {old_phi0:g}")
+
+ # -- Generic line searches
+
+ def test_line_search_wolfe1(self):
+ c = 0
+ smax = 100
+ for name, f, fprime, x, p, old_f in self.line_iter():
+ f0 = f(x)
+ g0 = fprime(x)
+ self.fcount.c = 0
+ s, fc, gc, fv, ofv, gv = ls.line_search_wolfe1(f, fprime, x, p,
+ g0, f0, old_f,
+ amax=smax)
+ assert_equal(self.fcount.c, fc+gc)
+ assert_fp_equal(ofv, f(x))
+ if s is None:
+ continue
+ assert_fp_equal(fv, f(x + s*p))
+ assert_array_almost_equal(gv, fprime(x + s*p), decimal=14)
+ if s < smax:
+ c += 1
+ assert_line_wolfe(x, p, s, f, fprime, err_msg=name)
+
+ assert c > 3 # check that the iterator really works...
+
+ def test_line_search_wolfe2(self):
+ c = 0
+ smax = 512
+ for name, f, fprime, x, p, old_f in self.line_iter():
+ f0 = f(x)
+ g0 = fprime(x)
+ self.fcount.c = 0
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "The line search algorithm could not find a solution",
+ LineSearchWarning)
+ warnings.filterwarnings(
+ "ignore",
+ "The line search algorithm did not converge",
+ LineSearchWarning)
+ s, fc, gc, fv, ofv, gv = ls.line_search_wolfe2(f, fprime, x, p,
+ g0, f0, old_f,
+ amax=smax)
+ assert_equal(self.fcount.c, fc+gc)
+ assert_fp_equal(ofv, f(x))
+ assert_fp_equal(fv, f(x + s*p))
+ if gv is not None:
+ assert_array_almost_equal(gv, fprime(x + s*p), decimal=14)
+ if s < smax:
+ c += 1
+ assert_line_wolfe(x, p, s, f, fprime, err_msg=name)
+ assert c > 3 # check that the iterator really works...
+
+ def test_line_search_wolfe2_bounds(self):
+ # See gh-7475
+
+ # For this f and p, starting at a point on axis 0, the strong Wolfe
+ # condition 2 is met if and only if the step length s satisfies
+ # |x + s| <= c2 * |x|
+ def f(x):
+ return np.dot(x, x)
+ def fp(x):
+ return 2 * x
+ p = np.array([1, 0])
+
+ # Smallest s satisfying strong Wolfe conditions for these arguments is 30
+ x = -60 * p
+ c2 = 0.5
+
+ s, _, _, _, _, _ = ls.line_search_wolfe2(f, fp, x, p, amax=30, c2=c2)
+ assert_line_wolfe(x, p, s, f, fp)
+
+ with pytest.warns(LineSearchWarning):
+ s, _, _, _, _, _ = ls.line_search_wolfe2(f, fp, x, p,
+ amax=29, c2=c2)
+ assert s is None
+
+ # s=30 will only be tried on the 6th iteration, so this won't converge
+ with pytest.warns(LineSearchWarning):
+ ls.line_search_wolfe2(f, fp, x, p, c2=c2, maxiter=5)
+
+ def test_line_search_armijo(self):
+ c = 0
+ for name, f, fprime, x, p, old_f in self.line_iter():
+ f0 = f(x)
+ g0 = fprime(x)
+ self.fcount.c = 0
+ s, fc, fv = ls.line_search_armijo(f, x, p, g0, f0)
+ c += 1
+ assert_equal(self.fcount.c, fc)
+ assert_fp_equal(fv, f(x + s*p))
+ assert_line_armijo(x, p, s, f, err_msg=name)
+ assert c >= 9
+
+ # -- More specific tests
+
+ def test_armijo_terminate_1(self):
+ # Armijo should evaluate the function only once if the trial step
+ # is already suitable
+ count = [0]
+
+ def phi(s):
+ count[0] += 1
+ return -s + 0.01*s**2
+ s, phi1 = ls.scalar_search_armijo(phi, phi(0), -1, alpha0=1)
+ assert_equal(s, 1)
+ assert_equal(count[0], 2)
+ assert_armijo(s, phi)
+
+ def test_wolfe_terminate(self):
+ # wolfe1 and wolfe2 should also evaluate the function only a few
+ # times if the trial step is already suitable
+
+ def phi(s):
+ count[0] += 1
+ return -s + 0.05*s**2
+
+ def derphi(s):
+ count[0] += 1
+ return -1 + 0.05*2*s
+
+ for func in [ls.scalar_search_wolfe1, ls.scalar_search_wolfe2]:
+ count = [0]
+ r = func(phi, derphi, phi(0), None, derphi(0))
+ assert r[0] is not None, (r, func)
+ assert count[0] <= 2 + 2, (count, func)
+ assert_wolfe(r[0], phi, derphi, err_msg=str(func))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_linprog.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_linprog.py
new file mode 100644
index 0000000000000000000000000000000000000000..a36694c60f0c0d3db42deebdaac7ccc9e4e966ca
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_linprog.py
@@ -0,0 +1,2614 @@
+"""
+Unit test for Linear Programming
+"""
+import sys
+import platform
+import warnings
+
+import numpy as np
+from numpy.exceptions import VisibleDeprecationWarning
+from numpy.testing import (assert_, assert_allclose, assert_equal,
+ assert_array_less)
+from pytest import raises as assert_raises
+from scipy.optimize import linprog, OptimizeWarning
+from scipy.optimize._numdiff import approx_derivative
+from scipy.sparse.linalg import MatrixRankWarning
+from scipy.linalg import LinAlgWarning
+import scipy.sparse
+import pytest
+
+has_umfpack = True
+try:
+ from scikits.umfpack import UmfpackWarning
+except ImportError:
+ has_umfpack = False
+
+has_cholmod = True
+try:
+ import sksparse # noqa: F401
+ from sksparse.cholmod import cholesky as cholmod # noqa: F401
+except ImportError:
+ has_cholmod = False
+
+
+def _assert_iteration_limit_reached(res, maxiter):
+ assert_(not res.success, "Incorrectly reported success")
+ assert_(res.success < maxiter, "Incorrectly reported number of iterations")
+ assert_equal(res.status, 1, "Failed to report iteration limit reached")
+
+
+def _assert_infeasible(res):
+ # res: linprog result object
+ assert_(not res.success, "incorrectly reported success")
+ assert_equal(res.status, 2, "failed to report infeasible status")
+
+
+def _assert_unbounded(res):
+ # res: linprog result object
+ assert_(not res.success, "incorrectly reported success")
+ assert_equal(res.status, 3, "failed to report unbounded status")
+
+
+def _assert_unable_to_find_basic_feasible_sol(res):
+ # res: linprog result object
+
+ # The status may be either 2 or 4 depending on why the feasible solution
+ # could not be found. If the underlying problem is expected to not have a
+ # feasible solution, _assert_infeasible should be used.
+ assert_(not res.success, "incorrectly reported success")
+ assert_(res.status in (2, 4), "failed to report optimization failure")
+
+
+def _assert_success(res, desired_fun=None, desired_x=None,
+ rtol=1e-8, atol=1e-8):
+ # res: linprog result object
+ # desired_fun: desired objective function value or None
+ # desired_x: desired solution or None
+ if not res.success:
+ msg = f"linprog status {res.status}, message: {res.message}"
+ raise AssertionError(msg)
+
+ assert_equal(res.status, 0)
+ if desired_fun is not None:
+ assert_allclose(res.fun, desired_fun,
+ err_msg="converged to an unexpected objective value",
+ rtol=rtol, atol=atol)
+ if desired_x is not None:
+ assert_allclose(res.x, desired_x,
+ err_msg="converged to an unexpected solution",
+ rtol=rtol, atol=atol)
+
+
+def magic_square(n, rng=None):
+ """
+ Generates a linear program for which integer solutions represent an
+ n x n magic square; binary decision variables represent the presence
+ (or absence) of an integer 1 to n^2 in each position of the square.
+ """
+
+ rng = np.random.default_rng(92350948245690509234) if rng is None else rng
+ M = n * (n**2 + 1) / 2
+
+ numbers = np.arange(n**4) // n**2 + 1
+
+ numbers = numbers.reshape(n**2, n, n)
+
+ zeros = np.zeros((n**2, n, n))
+
+ A_list = []
+ b_list = []
+
+ # Rule 1: use every number exactly once
+ for i in range(n**2):
+ A_row = zeros.copy()
+ A_row[i, :, :] = 1
+ A_list.append(A_row.flatten())
+ b_list.append(1)
+
+ # Rule 2: Only one number per square
+ for i in range(n):
+ for j in range(n):
+ A_row = zeros.copy()
+ A_row[:, i, j] = 1
+ A_list.append(A_row.flatten())
+ b_list.append(1)
+
+ # Rule 3: sum of rows is M
+ for i in range(n):
+ A_row = zeros.copy()
+ A_row[:, i, :] = numbers[:, i, :]
+ A_list.append(A_row.flatten())
+ b_list.append(M)
+
+ # Rule 4: sum of columns is M
+ for i in range(n):
+ A_row = zeros.copy()
+ A_row[:, :, i] = numbers[:, :, i]
+ A_list.append(A_row.flatten())
+ b_list.append(M)
+
+ # Rule 5: sum of diagonals is M
+ A_row = zeros.copy()
+ A_row[:, range(n), range(n)] = numbers[:, range(n), range(n)]
+ A_list.append(A_row.flatten())
+ b_list.append(M)
+ A_row = zeros.copy()
+ A_row[:, range(n), range(-1, -n - 1, -1)] = \
+ numbers[:, range(n), range(-1, -n - 1, -1)]
+ A_list.append(A_row.flatten())
+ b_list.append(M)
+
+ A = np.array(np.vstack(A_list), dtype=float)
+ b = np.array(b_list, dtype=float)
+ c = rng.random(A.shape[1])
+
+ return A, b, c, numbers, M
+
+
+def lpgen_2d(m, n):
+ """ -> A b c LP test: m*n vars, m+n constraints
+ row sums == n/m, col sums == 1
+ https://gist.github.com/denis-bz/8647461
+ """
+ rng = np.random.default_rng(35892345982340246935)
+ c = - rng.exponential(size=(m, n))
+ Arow = np.zeros((m, m * n))
+ brow = np.zeros(m)
+ for j in range(m):
+ j1 = j + 1
+ Arow[j, j * n:j1 * n] = 1
+ brow[j] = n / m
+
+ Acol = np.zeros((n, m * n))
+ bcol = np.zeros(n)
+ for j in range(n):
+ j1 = j + 1
+ Acol[j, j::n] = 1
+ bcol[j] = 1
+
+ A = np.vstack((Arow, Acol))
+ b = np.hstack((brow, bcol))
+
+ return A, b, c.ravel()
+
+
+def very_random_gen(seed=0):
+ rng = np.random.default_rng(389234982354865)
+ m_eq, m_ub, n = 10, 20, 50
+ c = rng.random(n)-0.5
+ A_ub = rng.random((m_ub, n))-0.5
+ b_ub = rng.random(m_ub)-0.5
+ A_eq = rng.random((m_eq, n))-0.5
+ b_eq = rng.random(m_eq)-0.5
+ lb = -rng.random(n)
+ ub = rng.random(n)
+ lb[lb < -rng.random()] = -np.inf
+ ub[ub > rng.random()] = np.inf
+ bounds = np.vstack((lb, ub)).T
+ return c, A_ub, b_ub, A_eq, b_eq, bounds
+
+
+def nontrivial_problem():
+ c = [-1, 8, 4, -6]
+ A_ub = [[-7, -7, 6, 9],
+ [1, -1, -3, 0],
+ [10, -10, -7, 7],
+ [6, -1, 3, 4]]
+ b_ub = [-3, 6, -6, 6]
+ A_eq = [[-10, 1, 1, -8]]
+ b_eq = [-4]
+ x_star = [101 / 1391, 1462 / 1391, 0, 752 / 1391]
+ f_star = 7083 / 1391
+ return c, A_ub, b_ub, A_eq, b_eq, x_star, f_star
+
+
+def l1_regression_prob(seed=0, m=8, d=9, n=100):
+ '''
+ Training data is {(x0, y0), (x1, y2), ..., (xn-1, yn-1)}
+ x in R^d
+ y in R
+ n: number of training samples
+ d: dimension of x, i.e. x in R^d
+ phi: feature map R^d -> R^m
+ m: dimension of feature space
+ '''
+ rng = np.random.default_rng(72847583923592458453)
+ phi = rng.normal(0, 1, size=(m, d)) # random feature mapping
+ w_true = rng.standard_normal(m)
+ x = rng.normal(0, 1, size=(d, n)) # features
+ y = w_true @ (phi @ x) + rng.normal(0, 1e-5, size=n) # measurements
+
+ # construct the problem
+ c = np.ones(m+n)
+ c[:m] = 0
+ A_ub = scipy.sparse.lil_array((2*n, n+m))
+ idx = 0
+ for ii in range(n):
+ A_ub[idx, :m] = phi @ x[:, ii]
+ A_ub[idx, m+ii] = -1
+ A_ub[idx+1, :m] = -1*phi @ x[:, ii]
+ A_ub[idx+1, m+ii] = -1
+ idx += 2
+ A_ub = A_ub.tocsc()
+ b_ub = np.zeros(2*n)
+ b_ub[0::2] = y
+ b_ub[1::2] = -y
+ bnds = [(None, None)]*m + [(0, None)]*n
+ return c, A_ub, b_ub, bnds
+
+
+def generic_callback_test(self):
+ # Check that callback is as advertised
+ last_cb = {}
+
+ def cb(res):
+ message = res.pop('message')
+ complete = res.pop('complete')
+
+ assert_(res.pop('phase') in (1, 2))
+ assert_(res.pop('status') in range(4))
+ assert_(isinstance(res.pop('nit'), int))
+ assert_(isinstance(complete, bool))
+ assert_(isinstance(message, str))
+
+ last_cb['x'] = res['x']
+ last_cb['fun'] = res['fun']
+ last_cb['slack'] = res['slack']
+ last_cb['con'] = res['con']
+
+ c = np.array([-3, -2])
+ A_ub = [[2, 1], [1, 1], [1, 0]]
+ b_ub = [10, 8, 4]
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, callback=cb, method=self.method)
+
+ _assert_success(res, desired_fun=-18.0, desired_x=[2, 6])
+ assert_allclose(last_cb['fun'], res['fun'])
+ assert_allclose(last_cb['x'], res['x'])
+ assert_allclose(last_cb['con'], res['con'])
+ assert_allclose(last_cb['slack'], res['slack'])
+
+
+def test_unknown_solvers_and_options():
+ c = np.array([-3, -2])
+ A_ub = [[2, 1], [1, 1], [1, 0]]
+ b_ub = [10, 8, 4]
+
+ assert_raises(ValueError, linprog,
+ c, A_ub=A_ub, b_ub=b_ub, method='ekki-ekki-ekki')
+ assert_raises(ValueError, linprog,
+ c, A_ub=A_ub, b_ub=b_ub, method='highs-ekki')
+ message = "Unrecognized options detected: {'rr_method': 'ekki-ekki-ekki'}"
+ with pytest.warns(OptimizeWarning, match=message):
+ linprog(c, A_ub=A_ub, b_ub=b_ub,
+ options={"rr_method": 'ekki-ekki-ekki'})
+
+
+def test_choose_solver():
+ # 'highs' chooses 'dual'
+ c = np.array([-3, -2])
+ A_ub = [[2, 1], [1, 1], [1, 0]]
+ b_ub = [10, 8, 4]
+
+ res = linprog(c, A_ub, b_ub, method='highs')
+ _assert_success(res, desired_fun=-18.0, desired_x=[2, 6])
+
+
+def test_deprecation():
+ with pytest.warns(DeprecationWarning):
+ linprog(1, method='interior-point')
+ with pytest.warns(DeprecationWarning):
+ linprog(1, method='revised simplex')
+ with pytest.warns(DeprecationWarning):
+ linprog(1, method='simplex')
+
+
+def test_highs_status_message():
+ res = linprog(1, method='highs')
+ msg = "Optimization terminated successfully. (HiGHS Status 7:"
+ assert res.status == 0
+ assert res.message.startswith(msg)
+
+ A, b, c, numbers, M = magic_square(6)
+ bounds = [(0, 1)] * len(c)
+ integrality = [1] * len(c)
+ options = {"time_limit": 0.1}
+ res = linprog(c=c, A_eq=A, b_eq=b, bounds=bounds, method='highs',
+ options=options, integrality=integrality)
+ msg = "Time limit reached. (HiGHS Status 13:"
+ assert res.status == 1
+ assert res.message.startswith(msg)
+
+ options = {"maxiter": 10}
+ res = linprog(c=c, A_eq=A, b_eq=b, bounds=bounds, method='highs-ds',
+ options=options)
+ msg = "Iteration limit reached. (HiGHS Status 14:"
+ assert res.status == 1
+ assert res.message.startswith(msg)
+
+ res = linprog(1, bounds=(1, -1), method='highs')
+ msg = "The problem is infeasible. (HiGHS Status 8:"
+ assert res.status == 2
+ assert res.message.startswith(msg)
+
+ res = linprog(-1, method='highs')
+ msg = "The problem is unbounded. (HiGHS Status 10:"
+ assert res.status == 3
+ assert res.message.startswith(msg)
+
+ from scipy.optimize._linprog_highs import _highs_to_scipy_status_message
+ status, message = _highs_to_scipy_status_message(58, "Hello!")
+ msg = "The HiGHS status code was not recognized. (HiGHS Status 58:"
+ assert status == 4
+ assert message.startswith(msg)
+
+ status, message = _highs_to_scipy_status_message(None, None)
+ msg = "HiGHS did not provide a status code. (HiGHS Status None: None)"
+ assert status == 4
+ assert message.startswith(msg)
+
+
+def test_bug_17380():
+ linprog([1, 1], A_ub=[[-1, 0]], b_ub=[-2.5], integrality=[1, 1])
+
+
+A_ub = None
+b_ub = None
+A_eq = None
+b_eq = None
+bounds = None
+
+################
+# Common Tests #
+################
+
+
+class LinprogCommonTests:
+ """
+ Base class for `linprog` tests. Generally, each test will be performed
+ once for every derived class of LinprogCommonTests, each of which will
+ typically change self.options and/or self.method. Effectively, these tests
+ are run for many combination of method (simplex, revised simplex, and
+ interior point) and options (such as pivoting rule or sparse treatment).
+ """
+
+ ##################
+ # Targeted Tests #
+ ##################
+
+ def test_callback(self):
+ generic_callback_test(self)
+
+ def test_disp(self):
+ # test that display option does not break anything.
+ A, b, c = lpgen_2d(20, 20)
+ res = linprog(c, A_ub=A, b_ub=b, method=self.method,
+ options={"disp": True})
+ _assert_success(res, desired_fun=-63.47967608020187) # method='highs' solution
+
+ def test_docstring_example(self):
+ # Example from linprog docstring.
+ c = [-1, 4]
+ A = [[-3, 1], [1, 2]]
+ b = [6, 4]
+ x0_bounds = (None, None)
+ x1_bounds = (-3, None)
+ res = linprog(c, A_ub=A, b_ub=b, bounds=(x0_bounds, x1_bounds),
+ options=self.options, method=self.method)
+ _assert_success(res, desired_fun=-22)
+
+ def test_type_error(self):
+ # (presumably) checks that linprog recognizes type errors
+ # This is tested more carefully in test__linprog_clean_inputs.py
+ c = [1]
+ A_eq = [[1]]
+ b_eq = "hello"
+ assert_raises(TypeError, linprog,
+ c, A_eq=A_eq, b_eq=b_eq,
+ method=self.method, options=self.options)
+
+ def test_aliasing_b_ub(self):
+ # (presumably) checks that linprog does not modify b_ub
+ # This is tested more carefully in test__linprog_clean_inputs.py
+ c = np.array([1.0])
+ A_ub = np.array([[1.0]])
+ b_ub_orig = np.array([3.0])
+ b_ub = b_ub_orig.copy()
+ bounds = (-4.0, np.inf)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-4, desired_x=[-4])
+ assert_allclose(b_ub_orig, b_ub)
+
+ def test_aliasing_b_eq(self):
+ # (presumably) checks that linprog does not modify b_eq
+ # This is tested more carefully in test__linprog_clean_inputs.py
+ c = np.array([1.0])
+ A_eq = np.array([[1.0]])
+ b_eq_orig = np.array([3.0])
+ b_eq = b_eq_orig.copy()
+ bounds = (-4.0, np.inf)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=3, desired_x=[3])
+ assert_allclose(b_eq_orig, b_eq)
+
+ def test_non_ndarray_args(self):
+ # (presumably) checks that linprog accepts list in place of arrays
+ # This is tested more carefully in test__linprog_clean_inputs.py
+ c = [1.0]
+ A_ub = [[1.0]]
+ b_ub = [3.0]
+ A_eq = [[1.0]]
+ b_eq = [2.0]
+ bounds = (-1.0, 10.0)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=2, desired_x=[2])
+
+ def test_unknown_options(self):
+ c = np.array([-3, -2])
+ A_ub = [[2, 1], [1, 1], [1, 0]]
+ b_ub = [10, 8, 4]
+
+ def f(c, A_ub=None, b_ub=None, A_eq=None,
+ b_eq=None, bounds=None, options=None):
+ linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=options)
+
+ o = {key: self.options[key] for key in self.options}
+ o['spam'] = 42
+
+ with pytest.warns(OptimizeWarning):
+ f(c, A_ub=A_ub, b_ub=b_ub, options=o)
+
+ def test_integrality_without_highs(self):
+ # ensure that using `integrality` parameter without `method='highs'`
+ # raises warning and produces correct solution to relaxed problem
+ # source: https://en.wikipedia.org/wiki/Integer_programming#Example
+ A_ub = np.array([[-1, 1], [3, 2], [2, 3]])
+ b_ub = np.array([1, 12, 12])
+ c = -np.array([0, 1])
+
+ bounds = [(0, np.inf)] * len(c)
+ integrality = [1] * len(c)
+
+ with pytest.warns(OptimizeWarning):
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ np.testing.assert_allclose(res.x, [1.8, 2.8])
+ np.testing.assert_allclose(res.fun, -2.8)
+
+ def test_invalid_inputs(self):
+
+ def f(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None):
+ linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ # Test ill-formatted bounds
+ assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, 2), (3, 4)])
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Creating an ndarray from ragged", VisibleDeprecationWarning)
+ assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, 2), (3, 4), (3, 4, 5)])
+ assert_raises(ValueError, f, [1, 2, 3], bounds=[(1, -2), (1, 2)])
+
+ # Test other invalid inputs
+ assert_raises(ValueError, f, [1, 2], A_ub=[[1, 2]], b_ub=[1, 2])
+ assert_raises(ValueError, f, [1, 2], A_ub=[[1]], b_ub=[1])
+ assert_raises(ValueError, f, [1, 2], A_eq=[[1, 2]], b_eq=[1, 2])
+ assert_raises(ValueError, f, [1, 2], A_eq=[[1]], b_eq=[1])
+ assert_raises(ValueError, f, [1, 2], A_eq=[1], b_eq=1)
+
+ # this last check doesn't make sense for sparse presolve
+ if ("_sparse_presolve" in self.options and
+ self.options["_sparse_presolve"]):
+ return
+ # there aren't 3-D sparse matrices
+
+ assert_raises(ValueError, f, [1, 2], A_ub=np.zeros((1, 1, 3)), b_eq=1)
+
+ def test_sparse_constraints(self):
+ # gh-13559: improve error message for sparse inputs when unsupported
+ def f(c, A_ub=None, b_ub=None, A_eq=None, b_eq=None, bounds=None):
+ linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ rng = np.random.default_rng(9938284754882992)
+ m = 100
+ n = 150
+ A_eq = scipy.sparse.random_array((m, n), density=0.5, rng=rng)
+ x_valid = rng.standard_normal(n)
+ c = rng.standard_normal(n)
+ ub = x_valid + rng.random(n)
+ lb = x_valid - rng.random(n)
+ bounds = np.column_stack((lb, ub))
+ b_eq = A_eq @ x_valid
+
+ if self.method in {'simplex', 'revised simplex'}:
+ # simplex and revised simplex should raise error
+ with assert_raises(ValueError, match=f"Method '{self.method}' "
+ "does not support sparse constraint matrices."):
+ linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds,
+ method=self.method, options=self.options)
+ else:
+ # other methods should succeed
+ options = {**self.options}
+ if self.method in {'interior-point'}:
+ options['sparse'] = True
+
+ res = linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds,
+ method=self.method, options=options)
+ assert res.success
+
+ def test_maxiter(self):
+ # test iteration limit w/ Enzo example
+ c = [4, 8, 3, 0, 0, 0]
+ A = [
+ [2, 5, 3, -1, 0, 0],
+ [3, 2.5, 8, 0, -1, 0],
+ [8, 10, 4, 0, 0, -1]]
+ b = [185, 155, 600]
+ maxiter = 3
+ res = linprog(c, A_eq=A, b_eq=b, method=self.method,
+ options={"maxiter": maxiter})
+ _assert_iteration_limit_reached(res, maxiter)
+ assert_equal(res.nit, maxiter)
+
+ def test_bounds_fixed(self):
+
+ # Test fixed bounds (upper equal to lower)
+ # If presolve option True, test if solution found in presolve (i.e.
+ # number of iterations is 0).
+ do_presolve = self.options.get('presolve', True)
+
+ res = linprog([1], bounds=(1, 1),
+ method=self.method, options=self.options)
+ _assert_success(res, 1, 1)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ res = linprog([1, 2, 3], bounds=[(5, 5), (-1, -1), (3, 3)],
+ method=self.method, options=self.options)
+ _assert_success(res, 12, [5, -1, 3])
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ res = linprog([1, 1], bounds=[(1, 1), (1, 3)],
+ method=self.method, options=self.options)
+ _assert_success(res, 2, [1, 1])
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ res = linprog([1, 1, 2], A_eq=[[1, 0, 0], [0, 1, 0]], b_eq=[1, 7],
+ bounds=[(-5, 5), (0, 10), (3.5, 3.5)],
+ method=self.method, options=self.options)
+ _assert_success(res, 15, [1, 7, 3.5])
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ def test_bounds_infeasible(self):
+
+ # Test ill-valued bounds (upper less than lower)
+ # If presolve option True, test if solution found in presolve (i.e.
+ # number of iterations is 0).
+ do_presolve = self.options.get('presolve', True)
+
+ res = linprog([1], bounds=(1, -2), method=self.method, options=self.options)
+ _assert_infeasible(res)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ res = linprog([1], bounds=[(1, -2)], method=self.method, options=self.options)
+ _assert_infeasible(res)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ res = linprog([1, 2, 3], bounds=[(5, 0), (1, 2), (3, 4)],
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ def test_bounds_infeasible_2(self):
+
+ # Test ill-valued bounds (lower inf, upper -inf)
+ # If presolve option True, test if solution found in presolve (i.e.
+ # number of iterations is 0).
+ # For the simplex method, the cases do not result in an
+ # infeasible status, but in a RuntimeWarning. This is a
+ # consequence of having _presolve() take care of feasibility
+ # checks. See issue gh-11618.
+ do_presolve = self.options.get('presolve', True)
+ simplex_without_presolve = not do_presolve and self.method == 'simplex'
+
+ c = [1, 2, 3]
+ bounds_1 = [(1, 2), (np.inf, np.inf), (3, 4)]
+ bounds_2 = [(1, 2), (-np.inf, -np.inf), (3, 4)]
+
+ if simplex_without_presolve:
+ def g(c, bounds):
+ res = linprog(c, bounds=bounds,
+ method=self.method, options=self.options)
+ return res
+
+ with pytest.warns(RuntimeWarning):
+ with pytest.raises(IndexError):
+ g(c, bounds=bounds_1)
+
+ with pytest.warns(RuntimeWarning):
+ with pytest.raises(IndexError):
+ g(c, bounds=bounds_2)
+ else:
+ res = linprog(c=c, bounds=bounds_1,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+ res = linprog(c=c, bounds=bounds_2,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+ if do_presolve:
+ assert_equal(res.nit, 0)
+
+ def test_empty_constraint_1(self):
+ c = [-1, -2]
+ res = linprog(c, method=self.method, options=self.options)
+ _assert_unbounded(res)
+
+ def test_empty_constraint_2(self):
+ c = [-1, 1, -1, 1]
+ bounds = [(0, np.inf), (-np.inf, 0), (-1, 1), (-1, 1)]
+ res = linprog(c, bounds=bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+ # Unboundedness detected in presolve requires no iterations
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_empty_constraint_3(self):
+ c = [1, -1, 1, -1]
+ bounds = [(0, np.inf), (-np.inf, 0), (-1, 1), (-1, 1)]
+ res = linprog(c, bounds=bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[0, 0, -1, 1], desired_fun=-2)
+
+ def test_inequality_constraints(self):
+ # Minimize linear function subject to linear inequality constraints.
+ # http://www.dam.brown.edu/people/huiwang/classes/am121/Archive/simplex_121_c.pdf
+ c = np.array([3, 2]) * -1 # maximize
+ A_ub = [[2, 1],
+ [1, 1],
+ [1, 0]]
+ b_ub = [10, 8, 4]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-18, desired_x=[2, 6])
+
+ def test_inequality_constraints2(self):
+ # Minimize linear function subject to linear inequality constraints.
+ # http://www.statslab.cam.ac.uk/~ff271/teaching/opt/notes/notes8.pdf
+ # (dead link)
+ c = [6, 3]
+ A_ub = [[0, 3],
+ [-1, -1],
+ [-2, 1]]
+ b_ub = [2, -1, -1]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=5, desired_x=[2 / 3, 1 / 3])
+
+ def test_bounds_simple(self):
+ c = [1, 2]
+ bounds = (1, 2)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[1, 1])
+
+ bounds = [(1, 2), (1, 2)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[1, 1])
+
+ def test_bounded_below_only_1(self):
+ c = np.array([1.0])
+ A_eq = np.array([[1.0]])
+ b_eq = np.array([3.0])
+ bounds = (1.0, None)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=3, desired_x=[3])
+
+ def test_bounded_below_only_2(self):
+ c = np.ones(3)
+ A_eq = np.eye(3)
+ b_eq = np.array([1, 2, 3])
+ bounds = (0.5, np.inf)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq))
+
+ def test_bounded_above_only_1(self):
+ c = np.array([1.0])
+ A_eq = np.array([[1.0]])
+ b_eq = np.array([3.0])
+ bounds = (None, 10.0)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=3, desired_x=[3])
+
+ def test_bounded_above_only_2(self):
+ c = np.ones(3)
+ A_eq = np.eye(3)
+ b_eq = np.array([1, 2, 3])
+ bounds = (-np.inf, 4)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq))
+
+ def test_bounds_infinity(self):
+ c = np.ones(3)
+ A_eq = np.eye(3)
+ b_eq = np.array([1, 2, 3])
+ bounds = (-np.inf, np.inf)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=b_eq, desired_fun=np.sum(b_eq))
+
+ def test_bounds_mixed(self):
+ # Problem has one unbounded variable and
+ # another with a negative lower bound.
+ c = np.array([-1, 4]) * -1 # maximize
+ A_ub = np.array([[-3, 1],
+ [1, 2]], dtype=np.float64)
+ b_ub = [6, 4]
+ x0_bounds = (-np.inf, np.inf)
+ x1_bounds = (-3, np.inf)
+ bounds = (x0_bounds, x1_bounds)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-80 / 7, desired_x=[-8 / 7, 18 / 7])
+
+ def test_bounds_equal_but_infeasible(self):
+ c = [-4, 1]
+ A_ub = [[7, -2], [0, 1], [2, -2]]
+ b_ub = [14, 0, 3]
+ bounds = [(2, 2), (0, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ def test_bounds_equal_but_infeasible2(self):
+ c = [-4, 1]
+ A_eq = [[7, -2], [0, 1], [2, -2]]
+ b_eq = [14, 0, 3]
+ bounds = [(2, 2), (0, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ def test_bounds_equal_no_presolve(self):
+ # There was a bug when a lower and upper bound were equal but
+ # presolve was not on to eliminate the variable. The bound
+ # was being converted to an equality constraint, but the bound
+ # was not eliminated, leading to issues in postprocessing.
+ c = [1, 2]
+ A_ub = [[1, 2], [1.1, 2.2]]
+ b_ub = [4, 8]
+ bounds = [(1, 2), (2, 2)]
+
+ o = {key: self.options[key] for key in self.options}
+ o["presolve"] = False
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ _assert_infeasible(res)
+
+ def test_zero_column_1(self):
+ m, n = 3, 4
+ rng = np.random.default_rng(558329500002933)
+ c = rng.random(n)
+ c[1] = 1
+ A_eq = rng.random((m, n))
+ A_eq[:, 1] = 0
+ b_eq = rng.random(m)
+ A_ub = [[1, 0, 1, 1]]
+ b_ub = 3
+ bounds = [(-10, 10), (-10, 10), (-10, None), (None, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-9.485758655190649) # method='highs' solution
+
+ def test_zero_column_2(self):
+ if self.method in {'highs-ds', 'highs-ipm'}:
+ # See upstream issue https://github.com/ERGO-Code/HiGHS/issues/648
+ pytest.xfail()
+
+ rng = np.random.default_rng(4492835845925983465)
+ m, n = 2, 4
+ c = rng.random(n)
+ c[1] = -1
+ A_eq = rng.random((m, n))
+ A_eq[:, 1] = 0
+ b_eq = rng.random(m)
+
+ A_ub = rng.random((m, n))
+ A_ub[:, 1] = 0
+ b_ub = rng.random(m)
+ bounds = (None, None)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+ # Unboundedness detected in presolve
+ if self.options.get('presolve', True) and "highs" not in self.method:
+ # HiGHS detects unboundedness or infeasibility in presolve
+ # It needs an iteration of simplex to be sure of unboundedness
+ # Other solvers report that the problem is unbounded if feasible
+ assert_equal(res.nit, 0)
+
+ def test_zero_row_1(self):
+ c = [1, 2, 3]
+ A_eq = [[0, 0, 0], [1, 1, 1], [0, 0, 0]]
+ b_eq = [0, 3, 0]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=3)
+
+ def test_zero_row_2(self):
+ A_ub = [[0, 0, 0], [1, 1, 1], [0, 0, 0]]
+ b_ub = [0, 3, 0]
+ c = [1, 2, 3]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=0)
+
+ def test_zero_row_3(self):
+ m, n = 2, 4
+ rng = np.random.default_rng(49949482723982545)
+ c = rng.random(n)
+ A_eq = rng.random((m, n))
+ A_eq[0, :] = 0
+ b_eq = rng.random(m)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ # Infeasibility detected in presolve
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_zero_row_4(self):
+ m, n = 2, 4
+ rng = np.random.default_rng(1032934859282349)
+ c = rng.random(n)
+ A_ub = rng.random((m, n))
+ A_ub[0, :] = 0
+ b_ub = -rng.random(m)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ # Infeasibility detected in presolve
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_singleton_row_eq_1(self):
+ c = [1, 1, 1, 2]
+ A_eq = [[1, 0, 0, 0], [0, 2, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1]]
+ b_eq = [1, 2, 2, 4]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ # Infeasibility detected in presolve
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_singleton_row_eq_2(self):
+ c = [1, 1, 1, 2]
+ A_eq = [[1, 0, 0, 0], [0, 2, 0, 0], [1, 0, 0, 0], [1, 1, 1, 1]]
+ b_eq = [1, 2, 1, 4]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=4)
+
+ def test_singleton_row_ub_1(self):
+ c = [1, 1, 1, 2]
+ A_ub = [[1, 0, 0, 0], [0, 2, 0, 0], [-1, 0, 0, 0], [1, 1, 1, 1]]
+ b_ub = [1, 2, -2, 4]
+ bounds = [(None, None), (0, None), (0, None), (0, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ # Infeasibility detected in presolve
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_singleton_row_ub_2(self):
+ c = [1, 1, 1, 2]
+ A_ub = [[1, 0, 0, 0], [0, 2, 0, 0], [-1, 0, 0, 0], [1, 1, 1, 1]]
+ b_ub = [1, 2, -0.5, 4]
+ bounds = [(None, None), (0, None), (0, None), (0, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=0.5)
+
+ def test_infeasible(self):
+ # Test linprog response to an infeasible problem
+ c = [-1, -1]
+ A_ub = [[1, 0],
+ [0, 1],
+ [-1, -1]]
+ b_ub = [2, 2, -5]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ def test_infeasible_inequality_bounds(self):
+ c = [1]
+ A_ub = [[2]]
+ b_ub = 4
+ bounds = (5, 6)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ # Infeasibility detected in presolve
+ if self.options.get('presolve', True):
+ assert_equal(res.nit, 0)
+
+ def test_unbounded(self):
+ # Test linprog response to an unbounded problem
+ c = np.array([1, 1]) * -1 # maximize
+ A_ub = [[-1, 1],
+ [-1, -1]]
+ b_ub = [-1, -2]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+
+ def test_unbounded_below_no_presolve_corrected(self):
+ c = [1]
+ bounds = [(None, 1)]
+
+ o = {key: self.options[key] for key in self.options}
+ o["presolve"] = False
+
+ res = linprog(c=c, bounds=bounds,
+ method=self.method,
+ options=o)
+ if self.method == "revised simplex":
+ # Revised simplex has a special pathway for no constraints.
+ assert_equal(res.status, 5)
+ else:
+ _assert_unbounded(res)
+
+ def test_unbounded_no_nontrivial_constraints_1(self):
+ """
+ Test whether presolve pathway for detecting unboundedness after
+ constraint elimination is working.
+ """
+ c = np.array([0, 0, 0, 1, -1, -1])
+ A_ub = np.array([[1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, -1]])
+ b_ub = np.array([2, -2, 0])
+ bounds = [(None, None), (None, None), (None, None),
+ (-1, 1), (-1, 1), (0, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+ if not self.method.lower().startswith("highs"):
+ assert_equal(res.x[-1], np.inf)
+ assert_equal(res.message[:36],
+ "The problem is (trivially) unbounded")
+
+ def test_unbounded_no_nontrivial_constraints_2(self):
+ """
+ Test whether presolve pathway for detecting unboundedness after
+ constraint elimination is working.
+ """
+ c = np.array([0, 0, 0, 1, -1, 1])
+ A_ub = np.array([[1, 0, 0, 0, 0, 0],
+ [0, 1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1]])
+ b_ub = np.array([2, -2, 0])
+ bounds = [(None, None), (None, None), (None, None),
+ (-1, 1), (-1, 1), (None, 0)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+ if not self.method.lower().startswith("highs"):
+ assert_equal(res.x[-1], -np.inf)
+ assert_equal(res.message[:36],
+ "The problem is (trivially) unbounded")
+
+ def test_cyclic_recovery(self):
+ # Test linprogs recovery from cycling using the Klee-Minty problem
+ # Klee-Minty https://www.math.ubc.ca/~israel/m340/kleemin3.pdf
+ c = np.array([100, 10, 1]) * -1 # maximize
+ A_ub = [[1, 0, 0],
+ [20, 1, 0],
+ [200, 20, 1]]
+ b_ub = [1, 100, 10000]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[0, 0, 10000], atol=5e-6, rtol=1e-7)
+
+ def test_cyclic_bland(self):
+ # Test the effect of Bland's rule on a cycling problem
+ c = np.array([-10, 57, 9, 24.])
+ A_ub = np.array([[0.5, -5.5, -2.5, 9],
+ [0.5, -1.5, -0.5, 1],
+ [1, 0, 0, 0]])
+ b_ub = [0, 0, 1]
+
+ # copy the existing options dictionary but change maxiter
+ maxiter = 100
+ o = {key: val for key, val in self.options.items()}
+ o['maxiter'] = maxiter
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+
+ if self.method == 'simplex' and not self.options.get('bland'):
+ # simplex cycles without Bland's rule
+ _assert_iteration_limit_reached(res, o['maxiter'])
+ else:
+ # other methods, including simplex with Bland's rule, succeed
+ _assert_success(res, desired_x=[1, 0, 1, 0])
+ # note that revised simplex skips this test because it may or may not
+ # cycle depending on the initial basis
+
+ def test_remove_redundancy_infeasibility(self):
+ # mostly a test of redundancy removal, which is carefully tested in
+ # test__remove_redundancy.py
+ m, n = 10, 10
+ rng = np.random.default_rng(253985716283940)
+ c = rng.random(n)
+ A_eq = rng.random((m, n))
+ b_eq = rng.random(m)
+ A_eq[-1, :] = 2 * A_eq[-2, :]
+ b_eq[-1] *= -1
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ #################
+ # General Tests #
+ #################
+
+ def test_nontrivial_problem(self):
+ # Problem involves all constraint types,
+ # negative resource limits, and rounding issues.
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+
+ def test_lpgen_problem(self):
+ # Test linprog with a rather large problem (400 variables,
+ # 40 constraints) generated by https://gist.github.com/denis-bz/8647461
+ A_ub, b_ub, c = lpgen_2d(20, 20)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Solving system with option 'sym_pos'", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ _assert_success(res, desired_fun=-63.47967608020187) # method='highs' solution
+
+ def test_network_flow(self):
+ # A network flow problem with supply and demand at nodes
+ # and with costs along directed edges.
+ # https://www.princeton.edu/~rvdb/542/lectures/lec10.pdf
+ c = [2, 4, 9, 11, 4, 3, 8, 7, 0, 15, 16, 18]
+ n, p = -1, 1
+ A_eq = [
+ [n, n, p, 0, p, 0, 0, 0, 0, p, 0, 0],
+ [p, 0, 0, p, 0, p, 0, 0, 0, 0, 0, 0],
+ [0, 0, n, n, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, p, p, 0, 0, p, 0],
+ [0, 0, 0, 0, n, n, n, 0, p, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, n, n, 0, 0, p],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, n, n, n]]
+ b_eq = [0, 19, -16, 33, 0, 0, -36]
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=755, atol=1e-6, rtol=1e-7)
+
+ def test_network_flow_limited_capacity(self):
+ # A network flow problem with supply and demand at nodes
+ # and with costs and capacities along directed edges.
+ # http://blog.sommer-forst.de/2013/04/10/
+ c = [2, 2, 1, 3, 1]
+ bounds = [
+ [0, 4],
+ [0, 2],
+ [0, 2],
+ [0, 3],
+ [0, 5]]
+ n, p = -1, 1
+ A_eq = [
+ [n, n, 0, 0, 0],
+ [p, 0, n, n, 0],
+ [0, p, p, 0, n],
+ [0, 0, 0, p, p]]
+ b_eq = [-4, 0, 0, 4]
+
+ with warnings.catch_warnings():
+ # this is an UmfpackWarning but I had trouble importing it
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "scipy.linalg.solve\nIll...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=14)
+
+ def test_simplex_algorithm_wikipedia_example(self):
+ # https://en.wikipedia.org/wiki/Simplex_algorithm#Example
+ c = [-2, -3, -4]
+ A_ub = [
+ [3, 2, 1],
+ [2, 5, 3]]
+ b_ub = [10, 15]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-20)
+
+ def test_enzo_example(self):
+ # https://github.com/scipy/scipy/issues/1779 lp2.py
+ #
+ # Translated from Octave code at:
+ # http://www.ecs.shimane-u.ac.jp/~kyoshida/lpeng.htm
+ # and placed under MIT licence by Enzo Michelangeli
+ # with permission explicitly granted by the original author,
+ # Prof. Kazunobu Yoshida
+ c = [4, 8, 3, 0, 0, 0]
+ A_eq = [
+ [2, 5, 3, -1, 0, 0],
+ [3, 2.5, 8, 0, -1, 0],
+ [8, 10, 4, 0, 0, -1]]
+ b_eq = [185, 155, 600]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=317.5,
+ desired_x=[66.25, 0, 17.5, 0, 183.75, 0],
+ atol=6e-6, rtol=1e-7)
+
+ def test_enzo_example_b(self):
+ # rescued from https://github.com/scipy/scipy/pull/218
+ c = [2.8, 6.3, 10.8, -2.8, -6.3, -10.8]
+ A_eq = [[-1, -1, -1, 0, 0, 0],
+ [0, 0, 0, 1, 1, 1],
+ [1, 0, 0, 1, 0, 0],
+ [0, 1, 0, 0, 1, 0],
+ [0, 0, 1, 0, 0, 1]]
+ b_eq = [-0.5, 0.4, 0.3, 0.3, 0.3]
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-1.77,
+ desired_x=[0.3, 0.2, 0.0, 0.0, 0.1, 0.3])
+
+ def test_enzo_example_c_with_degeneracy(self):
+ # rescued from https://github.com/scipy/scipy/pull/218
+ m = 20
+ c = -np.ones(m)
+ tmp = 2 * np.pi * np.arange(1, m + 1) / (m + 1)
+ A_eq = np.vstack((np.cos(tmp) - 1, np.sin(tmp)))
+ b_eq = [0, 0]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=0, desired_x=np.zeros(m))
+
+ def test_enzo_example_c_with_unboundedness(self):
+ # rescued from https://github.com/scipy/scipy/pull/218
+ m = 50
+ c = -np.ones(m)
+ tmp = 2 * np.pi * np.arange(m) / (m + 1)
+ # This test relies on `cos(0) -1 == sin(0)`, so ensure that's true
+ # (SIMD code or -ffast-math may cause spurious failures otherwise)
+ row0 = np.cos(tmp) - 1
+ row0[0] = 0.0
+ row1 = np.sin(tmp)
+ row1[0] = 0.0
+ A_eq = np.vstack((row0, row1))
+ b_eq = [0, 0]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_unbounded(res)
+
+ def test_enzo_example_c_with_infeasibility(self):
+ # rescued from https://github.com/scipy/scipy/pull/218
+ m = 50
+ c = -np.ones(m)
+ tmp = 2 * np.pi * np.arange(m) / (m + 1)
+ A_eq = np.vstack((np.cos(tmp) - 1, np.sin(tmp)))
+ b_eq = [1, 1]
+
+ o = {key: self.options[key] for key in self.options}
+ o["presolve"] = False
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ _assert_infeasible(res)
+
+ def test_basic_artificial_vars(self):
+ # Problem is chosen to test two phase simplex methods when at the end
+ # of phase 1 some artificial variables remain in the basis.
+ # Also, for `method='simplex'`, the row in the tableau corresponding
+ # with the artificial variables is not all zero.
+ c = np.array([-0.1, -0.07, 0.004, 0.004, 0.004, 0.004])
+ A_ub = np.array([[1.0, 0, 0, 0, 0, 0], [-1.0, 0, 0, 0, 0, 0],
+ [0, -1.0, 0, 0, 0, 0], [0, 1.0, 0, 0, 0, 0],
+ [1.0, 1.0, 0, 0, 0, 0]])
+ b_ub = np.array([3.0, 3.0, 3.0, 3.0, 20.0])
+ A_eq = np.array([[1.0, 0, -1, 1, -1, 1], [0, -1.0, -1, 1, -1, 1]])
+ b_eq = np.array([0, 0])
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=0, desired_x=np.zeros_like(c),
+ atol=2e-6)
+
+ def test_optimize_result(self):
+ # check all fields in OptimizeResult
+ c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(0)
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method, options=self.options)
+ assert_(res.success)
+ assert_(res.nit)
+ assert_(not res.status)
+ if 'highs' not in self.method:
+ # HiGHS status/message tested separately
+ assert_(res.message == "Optimization terminated successfully.")
+ assert_allclose(c @ res.x, res.fun)
+ assert_allclose(b_eq - A_eq @ res.x, res.con, atol=1e-11)
+ assert_allclose(b_ub - A_ub @ res.x, res.slack, atol=1e-11)
+ for key in ['eqlin', 'ineqlin', 'lower', 'upper']:
+ if key in res.keys():
+ assert isinstance(res[key]['marginals'], np.ndarray)
+ assert isinstance(res[key]['residual'], np.ndarray)
+
+ #################
+ # Bug Fix Tests #
+ #################
+
+ def test_bug_5400(self):
+ # https://github.com/scipy/scipy/issues/5400
+ bounds = [
+ (0, None),
+ (0, 100), (0, 100), (0, 100), (0, 100), (0, 100), (0, 100),
+ (0, 900), (0, 900), (0, 900), (0, 900), (0, 900), (0, 900),
+ (0, None), (0, None), (0, None), (0, None), (0, None), (0, None)]
+
+ f = 1 / 9
+ g = -1e4
+ h = -3.1
+ A_ub = np.array([
+ [1, -2.99, 0, 0, -3, 0, 0, 0, -1, -1, 0, -1, -1, 1, 1, 0, 0, 0, 0],
+ [1, 0, -2.9, h, 0, -3, 0, -1, 0, 0, -1, 0, -1, 0, 0, 1, 1, 0, 0],
+ [1, 0, 0, h, 0, 0, -3, -1, -1, 0, -1, -1, 0, 0, 0, 0, 0, 1, 1],
+ [0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -1],
+ [0, 1.99, -1, -1, 0, 0, 0, -1, f, f, 0, 0, 0, g, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0, 2, -1, -1, 0, 0, 0, -1, f, f, 0, g, 0, 0, 0, 0],
+ [0, -1, 1.9, 2.1, 0, 0, 0, f, -1, -1, 0, 0, 0, 0, 0, g, 0, 0, 0],
+ [0, 0, 0, 0, -1, 2, -1, 0, 0, 0, f, -1, f, 0, 0, 0, g, 0, 0],
+ [0, -1, -1, 2.1, 0, 0, 0, f, f, -1, 0, 0, 0, 0, 0, 0, 0, g, 0],
+ [0, 0, 0, 0, -1, -1, 2, 0, 0, 0, f, f, -1, 0, 0, 0, 0, 0, g]])
+
+ b_ub = np.array([
+ 0.0, 0, 0, 100, 100, 100, 100, 100, 100, 900, 900, 900, 900, 900,
+ 900, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0])
+
+ c = np.array([-1.0, 1, 1, 1, 1, 1, 1, 1, 1,
+ 1, 1, 1, 1, 0, 0, 0, 0, 0, 0])
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Solving system with option 'sym_pos'", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=-106.63507541835018)
+
+ def test_bug_6139(self):
+ # linprog(method='simplex') fails to find a basic feasible solution
+ # if phase 1 pseudo-objective function is outside the provided tol.
+ # https://github.com/scipy/scipy/issues/6139
+
+ # Note: This is not strictly a bug as the default tolerance determines
+ # if a result is "close enough" to zero and should not be expected
+ # to work for all cases.
+
+ c = np.array([1, 1, 1])
+ A_eq = np.array([[1., 0., 0.], [-1000., 0., - 1000.]])
+ b_eq = np.array([5.00000000e+00, -1.00000000e+04])
+ A_ub = -np.array([[0., 1000000., 1010000.]])
+ b_ub = -np.array([10000000.])
+ bounds = (None, None)
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ _assert_success(res, desired_fun=14.95,
+ desired_x=np.array([5, 4.95, 5]))
+
+ def test_bug_6690(self):
+ # linprog simplex used to violate bound constraint despite reporting
+ # success.
+ # https://github.com/scipy/scipy/issues/6690
+
+ A_eq = np.array([[0, 0, 0, 0.93, 0, 0.65, 0, 0, 0.83, 0]])
+ b_eq = np.array([0.9626])
+ A_ub = np.array([
+ [0, 0, 0, 1.18, 0, 0, 0, -0.2, 0, -0.22],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [0, 0, 0, 0.43, 0, 0, 0, 0, 0, 0],
+ [0, -1.22, -0.25, 0, 0, 0, -2.06, 0, 0, 1.37],
+ [0, 0, 0, 0, 0, 0, 0, -0.25, 0, 0]
+ ])
+ b_ub = np.array([0.615, 0, 0.172, -0.869, -0.022])
+ bounds = np.array([
+ [-0.84, -0.97, 0.34, 0.4, -0.33, -0.74, 0.47, 0.09, -1.45, -0.73],
+ [0.37, 0.02, 2.86, 0.86, 1.18, 0.5, 1.76, 0.17, 0.32, -0.15]
+ ]).T
+ c = np.array([
+ -1.64, 0.7, 1.8, -1.06, -1.16, 0.26, 2.13, 1.53, 0.66, 0.28
+ ])
+
+ with warnings.catch_warnings():
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option 'cholesky'", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option 'sym_pos'", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ desired_fun = -1.19099999999
+ desired_x = np.array([0.3700, -0.9700, 0.3400, 0.4000, 1.1800,
+ 0.5000, 0.4700, 0.0900, 0.3200, -0.7300])
+ _assert_success(res, desired_fun=desired_fun, desired_x=desired_x)
+
+ # Add small tol value to ensure arrays are less than or equal.
+ atol = 1e-6
+ assert_array_less(bounds[:, 0] - atol, res.x)
+ assert_array_less(res.x, bounds[:, 1] + atol)
+
+ def test_bug_7044(self):
+ # linprog simplex failed to "identify correct constraints" (?)
+ # leading to a non-optimal solution if A is rank-deficient.
+ # https://github.com/scipy/scipy/issues/7044
+
+ A_eq, b_eq, c, _, _ = magic_square(3)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ desired_fun = 1.7002011030086288 # `method='highs' solution
+ _assert_success(res, desired_fun=desired_fun)
+ assert_allclose(A_eq.dot(res.x), b_eq)
+ assert_array_less(np.zeros(res.x.size) - 1e-5, res.x)
+
+ def test_bug_7237(self):
+ # https://github.com/scipy/scipy/issues/7237
+ # linprog simplex "explodes" when the pivot value is very
+ # close to zero.
+
+ c = np.array([-1, 0, 0, 0, 0, 0, 0, 0, 0])
+ A_ub = np.array([
+ [1., -724., 911., -551., -555., -896., 478., -80., -293.],
+ [1., 566., 42., 937., 233., 883., 392., -909., 57.],
+ [1., -208., -894., 539., 321., 532., -924., 942., 55.],
+ [1., 857., -859., 83., 462., -265., -971., 826., 482.],
+ [1., 314., -424., 245., -424., 194., -443., -104., -429.],
+ [1., 540., 679., 361., 149., -827., 876., 633., 302.],
+ [0., -1., -0., -0., -0., -0., -0., -0., -0.],
+ [0., -0., -1., -0., -0., -0., -0., -0., -0.],
+ [0., -0., -0., -1., -0., -0., -0., -0., -0.],
+ [0., -0., -0., -0., -1., -0., -0., -0., -0.],
+ [0., -0., -0., -0., -0., -1., -0., -0., -0.],
+ [0., -0., -0., -0., -0., -0., -1., -0., -0.],
+ [0., -0., -0., -0., -0., -0., -0., -1., -0.],
+ [0., -0., -0., -0., -0., -0., -0., -0., -1.],
+ [0., 1., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 1., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 1., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 1., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 1., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 1., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 1., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0., 1.]
+ ])
+ b_ub = np.array([
+ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 1., 1., 1., 1., 1., 1., 1., 1.])
+ A_eq = np.array([[0., 1., 1., 1., 1., 1., 1., 1., 1.]])
+ b_eq = np.array([[1.]])
+ bounds = [(None, None)] * 9
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=108.568535, atol=1e-6)
+
+ def test_bug_8174(self):
+ # https://github.com/scipy/scipy/issues/8174
+ # The simplex method sometimes "explodes" if the pivot value is very
+ # close to zero.
+ A_ub = np.array([
+ [22714, 1008, 13380, -2713.5, -1116],
+ [-4986, -1092, -31220, 17386.5, 684],
+ [-4986, 0, 0, -2713.5, 0],
+ [22714, 0, 0, 17386.5, 0]])
+ b_ub = np.zeros(A_ub.shape[0])
+ c = -np.ones(A_ub.shape[1])
+ bounds = [(0, 1)] * A_ub.shape[1]
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ if self.options.get('tol', 1e-9) < 1e-10 and self.method == 'simplex':
+ _assert_unable_to_find_basic_feasible_sol(res)
+ else:
+ _assert_success(res, desired_fun=-2.0080717488789235, atol=1e-6)
+
+ def test_bug_8174_2(self):
+ # Test supplementary example from issue 8174.
+ # https://github.com/scipy/scipy/issues/8174
+ # https://stackoverflow.com/questions/47717012/linprog-in-scipy-optimize-checking-solution
+ c = np.array([1, 0, 0, 0, 0, 0, 0])
+ A_ub = -np.identity(7)
+ b_ub = np.array([[-2], [-2], [-2], [-2], [-2], [-2], [-2]])
+ A_eq = np.array([
+ [1, 1, 1, 1, 1, 1, 0],
+ [0.3, 1.3, 0.9, 0, 0, 0, -1],
+ [0.3, 0, 0, 0, 0, 0, -2/3],
+ [0, 0.65, 0, 0, 0, 0, -1/15],
+ [0, 0, 0.3, 0, 0, 0, -1/15]
+ ])
+ b_eq = np.array([[100], [0], [0], [0], [0]])
+
+ with warnings.catch_warnings():
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_fun=43.3333333331385)
+
+ def test_bug_8561(self):
+ # Test that pivot row is chosen correctly when using Bland's rule
+ # This was originally written for the simplex method with
+ # Bland's rule only, but it doesn't hurt to test all methods/options
+ # https://github.com/scipy/scipy/issues/8561
+ c = np.array([7, 0, -4, 1.5, 1.5])
+ A_ub = np.array([
+ [4, 5.5, 1.5, 1.0, -3.5],
+ [1, -2.5, -2, 2.5, 0.5],
+ [3, -0.5, 4, -12.5, -7],
+ [-1, 4.5, 2, -3.5, -2],
+ [5.5, 2, -4.5, -1, 9.5]])
+ b_ub = np.array([0, 0, 0, 0, 1])
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, options=self.options,
+ method=self.method)
+ _assert_success(res, desired_x=[0, 0, 19, 16/3, 29/3])
+
+ def test_bug_8662(self):
+ # linprog simplex used to report incorrect optimal results
+ # https://github.com/scipy/scipy/issues/8662
+ c = [-10, 10, 6, 3]
+ A_ub = [[8, -8, -4, 6],
+ [-8, 8, 4, -6],
+ [-4, 4, 8, -4],
+ [3, -3, -3, -10]]
+ b_ub = [9, -9, -9, -4]
+ bounds = [(0, None), (0, None), (0, None), (0, None)]
+ desired_fun = 36.0000000000
+
+ with warnings.catch_warnings():
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res1 = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+
+ # Set boundary condition as a constraint
+ A_ub.append([0, 0, -1, 0])
+ b_ub.append(0)
+ bounds[2] = (None, None)
+
+ with warnings.catch_warnings():
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res2 = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ rtol = 1e-5
+ _assert_success(res1, desired_fun=desired_fun, rtol=rtol)
+ _assert_success(res2, desired_fun=desired_fun, rtol=rtol)
+
+ def test_bug_8663(self):
+ # exposed a bug in presolve
+ # https://github.com/scipy/scipy/issues/8663
+ c = [1, 5]
+ A_eq = [[0, -7]]
+ b_eq = [-6]
+ bounds = [(0, None), (None, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[0, 6./7], desired_fun=5*6./7)
+
+ def test_bug_8664(self):
+ # interior-point has trouble with this when presolve is off
+ # tested for interior-point with presolve off in TestLinprogIPSpecific
+ # https://github.com/scipy/scipy/issues/8664
+ c = [4]
+ A_ub = [[2], [5]]
+ b_ub = [4, 4]
+ A_eq = [[0], [-8], [9]]
+ b_eq = [3, 2, 10]
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_infeasible(res)
+
+ def test_bug_8973(self):
+ """
+ Test whether bug described at:
+ https://github.com/scipy/scipy/issues/8973
+ was fixed.
+ """
+ c = np.array([0, 0, 0, 1, -1])
+ A_ub = np.array([[1, 0, 0, 0, 0], [0, 1, 0, 0, 0]])
+ b_ub = np.array([2, -2])
+ bounds = [(None, None), (None, None), (None, None), (-1, 1), (-1, 1)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ # solution vector x is not unique
+ _assert_success(res, desired_fun=-2)
+ # HiGHS IPM had an issue where the following wasn't true!
+ assert_equal(c @ res.x, res.fun)
+
+ def test_bug_8973_2(self):
+ """
+ Additional test for:
+ https://github.com/scipy/scipy/issues/8973
+ suggested in
+ https://github.com/scipy/scipy/pull/8985
+ review by @antonior92
+ """
+ c = np.zeros(1)
+ A_ub = np.array([[1]])
+ b_ub = np.array([-2])
+ bounds = (None, None)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[-2], desired_fun=0)
+
+ def test_bug_10124(self):
+ """
+ Test for linprog docstring problem
+ 'disp'=True caused revised simplex failure
+ """
+ c = np.zeros(1)
+ A_ub = np.array([[1]])
+ b_ub = np.array([-2])
+ bounds = (None, None)
+ c = [-1, 4]
+ A_ub = [[-3, 1], [1, 2]]
+ b_ub = [6, 4]
+ bounds = [(None, None), (-3, None)]
+ o = {"disp": True}
+ o.update(self.options)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ _assert_success(res, desired_x=[10, -3], desired_fun=-22)
+
+ def test_bug_10349(self):
+ """
+ Test for redundancy removal tolerance issue
+ https://github.com/scipy/scipy/issues/10349
+ """
+ A_eq = np.array([[1, 1, 0, 0, 0, 0],
+ [0, 0, 1, 1, 0, 0],
+ [0, 0, 0, 0, 1, 1],
+ [1, 0, 1, 0, 0, 0],
+ [0, 0, 0, 1, 1, 0],
+ [0, 1, 0, 0, 0, 1]])
+ b_eq = np.array([221, 210, 10, 141, 198, 102])
+ c = np.concatenate((0, 1, np.zeros(4)), axis=None)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options)
+ _assert_success(res, desired_x=[129, 92, 12, 198, 0, 10], desired_fun=92)
+
+ @pytest.mark.skipif(sys.platform == 'darwin',
+ reason=("Failing on some local macOS builds, "
+ "see gh-13846"))
+ def test_bug_10466(self):
+ """
+ Test that autoscale fixes poorly-scaled problem
+ """
+ c = [-8., -0., -8., -0., -8., -0., -0., -0., -0., -0., -0., -0., -0.]
+ A_eq = [[1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 1., 1., 0., 0., 0., 0., 0., 0., 0.],
+ [1., 0., 1., 0., 1., 0., -1., 0., 0., 0., 0., 0., 0.],
+ [1., 0., 1., 0., 1., 0., 0., 1., 0., 0., 0., 0., 0.],
+ [1., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0.],
+ [1., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0.],
+ [1., 0., 1., 0., 1., 0., 0., 0., 0., 0., 1., 0., 0.],
+ [0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 1., 0.],
+ [0., 0., 1., 0., 1., 0., 0., 0., 0., 0., 0., 0., 1.]]
+
+ b_eq = [3.14572800e+08, 4.19430400e+08, 5.24288000e+08,
+ 1.00663296e+09, 1.07374182e+09, 1.07374182e+09,
+ 1.07374182e+09, 1.07374182e+09, 1.07374182e+09,
+ 1.07374182e+09]
+
+ o = {}
+ # HiGHS methods don't use autoscale option
+ if not self.method.startswith("highs"):
+ o = {"autoscale": True}
+ o.update(self.options)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "scipy.linalg.solve\nIll...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "divide by zero encountered...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "overflow encountered...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "Ill-conditioned matrix...", LinAlgWarning)
+ warnings.filterwarnings(
+ "ignore", "An ill-conditioned...", LinAlgWarning)
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ assert_allclose(res.fun, -8589934560)
+
+
+#########################
+# Method-specific Tests #
+#########################
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class LinprogSimplexTests(LinprogCommonTests):
+ method = "simplex"
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class LinprogIPTests(LinprogCommonTests):
+ method = "interior-point"
+
+ def test_bug_10466(self):
+ pytest.skip("Test is failing, but solver is deprecated.")
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class LinprogRSTests(LinprogCommonTests):
+ method = "revised simplex"
+
+ # Revised simplex does not reliably solve these problems.
+ # Failure is intermittent due to the random choice of elements to complete
+ # the basis after phase 1 terminates. In any case, linprog exists
+ # gracefully, reporting numerical difficulties. I do not think this should
+ # prevent revised simplex from being merged, as it solves the problems
+ # most of the time and solves a broader range of problems than the existing
+ # simplex implementation.
+ # I believe that the root cause is the same for all three and that this
+ # same issue prevents revised simplex from solving many other problems
+ # reliably. Somehow the pivoting rule allows the algorithm to pivot into
+ # a singular basis. I haven't been able to find a reference that
+ # acknowledges this possibility, suggesting that there is a bug. On the
+ # other hand, the pivoting rule is quite simple, and I can't find a
+ # mistake, which suggests that this is a possibility with the pivoting
+ # rule. Hopefully, a better pivoting rule will fix the issue.
+
+ def test_bug_5400(self):
+ pytest.skip("Intermittent failure acceptable.")
+
+ def test_bug_8662(self):
+ pytest.skip("Intermittent failure acceptable.")
+
+ def test_network_flow(self):
+ pytest.skip("Intermittent failure acceptable.")
+
+
+class LinprogHiGHSTests(LinprogCommonTests):
+ def test_callback(self):
+ # this is the problem from test_callback
+ def cb(res):
+ return None
+ c = np.array([-3, -2])
+ A_ub = [[2, 1], [1, 1], [1, 0]]
+ b_ub = [10, 8, 4]
+ assert_raises(NotImplementedError, linprog, c, A_ub=A_ub, b_ub=b_ub,
+ callback=cb, method=self.method)
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, method=self.method)
+ _assert_success(res, desired_fun=-18.0, desired_x=[2, 6])
+
+ @pytest.mark.parametrize("options",
+ [{"maxiter": -1},
+ {"disp": -1},
+ {"presolve": -1},
+ {"time_limit": -1},
+ {"dual_feasibility_tolerance": -1},
+ {"primal_feasibility_tolerance": -1},
+ {"ipm_optimality_tolerance": -1},
+ {"simplex_dual_edge_weight_strategy": "ekki"},
+ ])
+ def test_invalid_option_values(self, options):
+ def f(options):
+ linprog(1, method=self.method, options=options)
+ options.update(self.options)
+ with pytest.warns(OptimizeWarning):
+ f(options=options)
+
+ def test_crossover(self):
+ A_eq, b_eq, c, _, _ = magic_square(4, rng=np.random.default_rng(2212392))
+ bounds = (0, 1)
+ res = linprog(c, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method, options=self.options)
+ # there should be nonzero crossover iterations for IPM (only)
+ assert_equal(res.crossover_nit == 0, self.method != "highs-ipm")
+
+ @pytest.mark.fail_slow(10)
+ def test_marginals(self):
+ # Ensure lagrange multipliers are correct by comparing the derivative
+ # w.r.t. b_ub/b_eq/ub/lb to the reported duals.
+ c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(seed=0)
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method, options=self.options)
+ lb, ub = bounds.T
+
+ # sensitivity w.r.t. b_ub
+ def f_bub(x):
+ return linprog(c, A_ub, x, A_eq, b_eq, bounds,
+ method=self.method).fun
+
+ dfdbub = approx_derivative(f_bub, b_ub, method='3-point', f0=res.fun)
+ assert_allclose(res.ineqlin.marginals, dfdbub)
+
+ # sensitivity w.r.t. b_eq
+ def f_beq(x):
+ return linprog(c, A_ub, b_ub, A_eq, x, bounds,
+ method=self.method).fun
+
+ dfdbeq = approx_derivative(f_beq, b_eq, method='3-point', f0=res.fun)
+ assert_allclose(res.eqlin.marginals, dfdbeq)
+
+ # sensitivity w.r.t. lb
+ def f_lb(x):
+ bounds = np.array([x, ub]).T
+ return linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method).fun
+
+ with np.errstate(invalid='ignore'):
+ # approx_derivative has trouble where lb is infinite
+ dfdlb = approx_derivative(f_lb, lb, method='3-point', f0=res.fun)
+ dfdlb[~np.isfinite(lb)] = 0
+
+ assert_allclose(res.lower.marginals, dfdlb)
+
+ # sensitivity w.r.t. ub
+ def f_ub(x):
+ bounds = np.array([lb, x]).T
+ return linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method).fun
+
+ with np.errstate(invalid='ignore'):
+ dfdub = approx_derivative(f_ub, ub, method='3-point', f0=res.fun)
+ dfdub[~np.isfinite(ub)] = 0
+
+ assert_allclose(res.upper.marginals, dfdub)
+
+ def test_dual_feasibility(self):
+ # Ensure solution is dual feasible using marginals
+ c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(seed=42)
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method, options=self.options)
+
+ # KKT dual feasibility equation from Theorem 1 from
+ # http://www.personal.psu.edu/cxg286/LPKKT.pdf
+ resid = (-c + A_ub.T @ res.ineqlin.marginals +
+ A_eq.T @ res.eqlin.marginals +
+ res.upper.marginals +
+ res.lower.marginals)
+ assert_allclose(resid, 0, atol=1e-12)
+
+ def test_complementary_slackness(self):
+ # Ensure that the complementary slackness condition is satisfied.
+ c, A_ub, b_ub, A_eq, b_eq, bounds = very_random_gen(seed=42)
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method, options=self.options)
+
+ # KKT complementary slackness equation from Theorem 1 from
+ # http://www.personal.psu.edu/cxg286/LPKKT.pdf modified for
+ # non-zero RHS
+ assert np.allclose(res.ineqlin.marginals @ (b_ub - A_ub @ res.x), 0)
+
+ @pytest.mark.xfail(reason='Upstream / Wrapper issue, see gh-20589')
+ def test_bug_20336(self):
+ """
+ Test that `linprog` now solves a poorly-scaled problem
+ """
+ boundaries = [(10000.0, 9010000.0), (0.0, None), (10000.0, None),
+ (0.0, 84.62623413258109), (10000.0, None), (10000.0, None),
+ (10000.0, None), (10000.0, None), (10000.0, None),
+ (10000.0, None), (10000.0, None), (10000.0, None),
+ (10000.0, None), (None, None), (None, None), (None, None),
+ (None, None), (None, None), (None, None), (None, None),
+ (None, None), (None, None), (None, None), (None, None),
+ (None, None), (None, None), (None, None), (None, None),
+ (None, None), (None, None), (None, None), (None, None),
+ (None, None)]
+ eq_entries = [-1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0,
+ -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, -1.0, 1.0, 1.0, 1.0, -1.0, 0.001,
+ -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0,
+ 0.001, -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10,
+ 1.0, -1.0, 0.001, -0.001, 3.7337777768059636e-10,
+ 3.7337777768059636e-10, 1.0, -1.0, 0.001, -0.001,
+ 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0, 0.001,
+ -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0,
+ 0.001, -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10,
+ 1.0, -1.0, 0.001, -0.001, 3.7337777768059636e-10,
+ 3.7337777768059636e-10, 1.0, -1.0, 0.001, -0.001,
+ 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0, -1.0, 0.001,
+ -0.001, 3.7337777768059636e-10, 3.7337777768059636e-10, 1.0,
+ -1.0, 0.001, -0.001, 3.7337777768059636e-10,
+ 3.7337777768059636e-10, 1.0, -1.0]
+ eq_indizes = [0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10,
+ 11, 11, 12, 12, 12, 12, 13, 13, 14, 14, 14, 14, 15, 15, 16, 16,
+ 16, 16, 17, 17, 18, 18, 18, 18, 19, 19, 20, 20, 20, 20, 21, 21,
+ 22, 22, 22, 22, 23, 23, 24, 24, 24, 24, 25, 25, 26, 26, 26, 26,
+ 27, 27, 28, 28, 28, 28, 29, 29, 30, 30, 30, 30, 31, 31]
+ eq_vars = [15, 14, 17, 16, 19, 18, 21, 20, 23, 22, 25, 24, 27, 26, 29, 28, 31,
+ 30, 13, 1, 0, 32, 3, 14, 13, 4, 0, 4, 0, 32, 31, 2, 12, 2, 12, 16,
+ 15, 5, 4, 5, 4, 18, 17, 6, 5, 6, 5, 20, 19, 7, 6, 7, 6, 22, 21, 8,
+ 7, 8, 7, 24, 23, 9, 8, 9, 8, 26, 25, 10, 9, 10, 9, 28, 27, 11, 10,
+ 11, 10, 30, 29, 12, 11, 12, 11]
+ eq_values = [0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 9000000.0, 0.0,
+ 0.006587392118285457, -5032.197406716549, 0.0041860502789104696,
+ -7918.93439542944, 0.0063205763583549035, -5244.625751707402,
+ 0.006053760598424349, -5475.7793929428, 0.005786944838493795,
+ -5728.248403917573, 0.0055201290785632405, -6005.123623538355,
+ 0.005253313318632687, -6310.123825488683, 0.004986497558702133,
+ -6647.763714796453, 0.004719681798771578, -7023.578908071522,
+ 0.004452866038841024, -7444.431798646482]
+ coefficients = [0.0, 0.0, 0.0, -0.011816666666666668, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]
+ np_eq_entries = np.asarray(eq_entries, dtype=np.float64)
+ np_eq_indizes = np.asarray(eq_indizes, dtype=np.int32)
+ np_eq_vars = np.asarray(eq_vars, dtype=np.int32)
+
+ a_eq= scipy.sparse.csr_array((np_eq_entries,(np_eq_indizes, np_eq_vars)),
+ shape=(32, 33))
+ b_eq = np.asarray(eq_values, dtype=np.float64)
+ c = np.asarray(coefficients, dtype=np.float64)
+
+ result = scipy.optimize.linprog(c, A_ub=None, b_ub=None, A_eq=a_eq, b_eq=b_eq,
+ bounds=boundaries)
+ assert result.status==0
+ x = result.x
+ n_r_x = np.linalg.norm(a_eq @ x - b_eq)
+ n_r = np.linalg.norm(result.eqlin.residual)
+ assert_allclose(n_r, n_r_x)
+
+
+################################
+# Simplex Option-Specific Tests#
+################################
+
+
+class TestLinprogSimplexDefault(LinprogSimplexTests):
+
+ def setup_method(self):
+ self.options = {}
+
+ def test_bug_5400(self):
+ pytest.skip("Simplex fails on this problem.")
+
+ def test_bug_7237_low_tol(self):
+ # Fails if the tolerance is too strict. Here, we test that
+ # even if the solution is wrong, the appropriate error is raised.
+ pytest.skip("Simplex fails on this problem.")
+
+ def test_bug_8174_low_tol(self):
+ # Fails if the tolerance is too strict. Here, we test that
+ # even if the solution is wrong, the appropriate warning is issued.
+ self.options.update({'tol': 1e-12})
+ with pytest.warns(OptimizeWarning):
+ super().test_bug_8174()
+
+
+class TestLinprogSimplexBland(LinprogSimplexTests):
+
+ def setup_method(self):
+ self.options = {'bland': True}
+
+ def test_bug_5400(self):
+ pytest.skip("Simplex fails on this problem.")
+
+ def test_bug_8174_low_tol(self):
+ # Fails if the tolerance is too strict. Here, we test that
+ # even if the solution is wrong, the appropriate error is raised.
+ self.options.update({'tol': 1e-12})
+ with pytest.raises(AssertionError):
+ with pytest.warns(OptimizeWarning):
+ super().test_bug_8174()
+
+
+class TestLinprogSimplexNoPresolve(LinprogSimplexTests):
+
+ def setup_method(self):
+ self.options = {'presolve': False}
+
+ is_32_bit = np.intp(0).itemsize < 8
+ is_linux = sys.platform.startswith('linux')
+
+ @pytest.mark.xfail(
+ condition=is_32_bit and is_linux,
+ reason='Fails with warning on 32-bit linux')
+ def test_bug_5400(self):
+ super().test_bug_5400()
+
+ def test_bug_6139_low_tol(self):
+ # Linprog(method='simplex') fails to find a basic feasible solution
+ # if phase 1 pseudo-objective function is outside the provided tol.
+ # https://github.com/scipy/scipy/issues/6139
+ # Without ``presolve`` eliminating such rows the result is incorrect.
+ self.options.update({'tol': 1e-12})
+ with pytest.raises(AssertionError, match='linprog status 4'):
+ return super().test_bug_6139()
+
+ def test_bug_7237_low_tol(self):
+ pytest.skip("Simplex fails on this problem.")
+
+ def test_bug_8174_low_tol(self):
+ # Fails if the tolerance is too strict. Here, we test that
+ # even if the solution is wrong, the appropriate warning is issued.
+ self.options.update({'tol': 1e-12})
+ with pytest.warns(OptimizeWarning):
+ super().test_bug_8174()
+
+ def test_unbounded_no_nontrivial_constraints_1(self):
+ pytest.skip("Tests behavior specific to presolve")
+
+ def test_unbounded_no_nontrivial_constraints_2(self):
+ pytest.skip("Tests behavior specific to presolve")
+
+
+#######################################
+# Interior-Point Option-Specific Tests#
+#######################################
+
+
+class TestLinprogIPDense(LinprogIPTests):
+ options = {"sparse": False}
+
+ # see https://github.com/scipy/scipy/issues/20216 for skip reason
+ @pytest.mark.skipif(
+ sys.platform == 'darwin',
+ reason="Fails on some macOS builds for reason not relevant to test"
+ )
+ def test_bug_6139(self):
+ super().test_bug_6139()
+
+if has_cholmod:
+ class TestLinprogIPSparseCholmod(LinprogIPTests):
+ options = {"sparse": True, "cholesky": True}
+
+
+if has_umfpack:
+ class TestLinprogIPSparseUmfpack(LinprogIPTests):
+ options = {"sparse": True, "cholesky": False}
+
+ def test_network_flow_limited_capacity(self):
+ pytest.skip("Failing due to numerical issues on some platforms.")
+
+
+class TestLinprogIPSparse(LinprogIPTests):
+ options = {"sparse": True, "cholesky": False, "sym_pos": False}
+
+ @pytest.mark.skipif(
+ sys.platform == 'darwin',
+ reason="Fails on macOS x86 Accelerate builds (gh-20510)"
+ )
+ @pytest.mark.xfail_on_32bit("This test is sensitive to machine epsilon level "
+ "perturbations in linear system solution in "
+ "_linprog_ip._sym_solve.")
+ def test_bug_6139(self):
+ super().test_bug_6139()
+
+ @pytest.mark.xfail(reason='Fails with ATLAS, see gh-7877')
+ def test_bug_6690(self):
+ # Test defined in base class, but can't mark as xfail there
+ super().test_bug_6690()
+
+ def test_magic_square_sparse_no_presolve(self):
+ # test linprog with a problem with a rank-deficient A_eq matrix
+ A_eq, b_eq, c, _, _ = magic_square(3)
+ bounds = (0, 1)
+
+ with warnings.catch_warnings():
+ if has_umfpack:
+ warnings.simplefilter("ignore", UmfpackWarning)
+ warnings.filterwarnings(
+ "ignore", "Matrix is exactly singular", MatrixRankWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+
+ o = {key: self.options[key] for key in self.options}
+ o["presolve"] = False
+
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ desired_fun = 1.7002011030086288 # method='highs' solution
+ _assert_success(res, desired_fun=desired_fun)
+
+ def test_sparse_solve_options(self):
+ # checking that problem is solved with all column permutation options
+ A_eq, b_eq, c, _, _ = magic_square(3)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "Invalid permc_spec option", OptimizeWarning)
+ o = {key: self.options[key] for key in self.options}
+ permc_specs = ('NATURAL', 'MMD_ATA', 'MMD_AT_PLUS_A',
+ 'COLAMD', 'ekki-ekki-ekki')
+ # 'ekki-ekki-ekki' raises warning about invalid permc_spec option
+ # and uses default
+ for permc_spec in permc_specs:
+ o["permc_spec"] = permc_spec
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=o)
+ desired_fun = 1.7002011030086288 # `method='highs' solution
+ _assert_success(res, desired_fun=desired_fun)
+
+
+class TestLinprogIPSparsePresolve(LinprogIPTests):
+ options = {"sparse": True, "_sparse_presolve": True}
+
+ @pytest.mark.skipif(
+ sys.platform == 'darwin',
+ reason="Fails on macOS x86 Accelerate builds (gh-20510)"
+ )
+ @pytest.mark.xfail_on_32bit("This test is sensitive to machine epsilon level "
+ "perturbations in linear system solution in "
+ "_linprog_ip._sym_solve.")
+ def test_bug_6139(self):
+ super().test_bug_6139()
+
+ def test_enzo_example_c_with_infeasibility(self):
+ pytest.skip('_sparse_presolve=True incompatible with presolve=False')
+
+ @pytest.mark.xfail(reason='Fails with ATLAS, see gh-7877')
+ def test_bug_6690(self):
+ # Test defined in base class, but can't mark as xfail there
+ super().test_bug_6690()
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class TestLinprogIPSpecific:
+ method = "interior-point"
+ # the following tests don't need to be performed separately for
+ # sparse presolve, sparse after presolve, and dense
+
+ def test_solver_select(self):
+ # check that default solver is selected as expected
+ if has_cholmod:
+ options = {'sparse': True, 'cholesky': True}
+ elif has_umfpack:
+ options = {'sparse': True, 'cholesky': False}
+ else:
+ options = {'sparse': True, 'cholesky': False, 'sym_pos': False}
+ A, b, c = lpgen_2d(20, 20)
+ res1 = linprog(c, A_ub=A, b_ub=b, method=self.method, options=options)
+ res2 = linprog(c, A_ub=A, b_ub=b, method=self.method) # default solver
+ assert_allclose(res1.fun, res2.fun,
+ err_msg="linprog default solver unexpected result",
+ rtol=2e-15, atol=1e-15)
+
+ def test_unbounded_below_no_presolve_original(self):
+ # formerly caused segfault in TravisCI w/ "cholesky":True
+ c = [-1]
+ bounds = [(None, 1)]
+ res = linprog(c=c, bounds=bounds,
+ method=self.method,
+ options={"presolve": False, "cholesky": True})
+ _assert_success(res, desired_fun=-1)
+
+ def test_cholesky(self):
+ # use cholesky factorization and triangular solves
+ A, b, c = lpgen_2d(20, 20)
+ res = linprog(c, A_ub=A, b_ub=b, method=self.method,
+ options={"cholesky": True}) # only for dense
+ _assert_success(res, desired_fun=-63.47967608020187) # method='highs' solution
+
+ def test_alternate_initial_point(self):
+ # use "improved" initial point
+ A, b, c = lpgen_2d(20, 20)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "scipy.linalg.solve\nIll...", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "Ill-conditioned matrix...", LinAlgWarning)
+ warnings.filterwarnings(
+ "ignore", "An ill-conditioned...", LinAlgWarning)
+
+ res = linprog(c, A_ub=A, b_ub=b, method=self.method,
+ options={"ip": True, "disp": True})
+ # ip code is independent of sparse/dense
+ _assert_success(res, desired_fun=-63.47967608020187) # method='highs' solution
+
+ def test_bug_8664(self):
+ # interior-point has trouble with this when presolve is off
+ c = [4]
+ A_ub = [[2], [5]]
+ b_ub = [4, 4]
+ A_eq = [[0], [-8], [9]]
+ b_eq = [3, 2, 10]
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "Solving system with option...", OptimizeWarning)
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options={"presolve": False})
+ assert_(not res.success, "Incorrectly reported success")
+
+
+########################################
+# Revised Simplex Option-Specific Tests#
+########################################
+
+
+class TestLinprogRSCommon(LinprogRSTests):
+ options = {}
+
+ def test_cyclic_bland(self):
+ pytest.skip("Intermittent failure acceptable.")
+
+ def test_nontrivial_problem_with_guess(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=x_star)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+ assert_equal(res.nit, 0)
+
+ def test_nontrivial_problem_with_unbounded_variables(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ bounds = [(None, None), (None, None), (0, None), (None, None)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=x_star)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+ assert_equal(res.nit, 0)
+
+ def test_nontrivial_problem_with_bounded_variables(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ bounds = [(None, 1), (1, None), (0, None), (.4, .6)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=x_star)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+ assert_equal(res.nit, 0)
+
+ def test_nontrivial_problem_with_negative_unbounded_variable(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ b_eq = [4]
+ x_star = np.array([-219/385, 582/385, 0, 4/10])
+ f_star = 3951/385
+ bounds = [(None, None), (1, None), (0, None), (.4, .6)]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=x_star)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+ assert_equal(res.nit, 0)
+
+ def test_nontrivial_problem_with_bad_guess(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ bad_guess = [1, 2, 3, .5]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=bad_guess)
+ assert_equal(res.status, 6)
+
+ def test_redundant_constraints_with_guess(self):
+ rng = np.random.default_rng(984298498729345)
+ A, b, c, _, _ = magic_square(3, rng=rng)
+ p = rng.random(c.shape)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "A_eq does not appear...", OptimizeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ warnings.simplefilter("ignore", LinAlgWarning)
+ res = linprog(c, A_eq=A, b_eq=b, method=self.method)
+ res2 = linprog(c, A_eq=A, b_eq=b, method=self.method, x0=res.x)
+ res3 = linprog(c + p, A_eq=A, b_eq=b, method=self.method, x0=res.x)
+ _assert_success(res2, desired_fun=res.fun)
+ assert_equal(res2.nit, 0)
+ _assert_success(res3)
+ assert_(res3.nit < res.nit) # hot start reduces iterations
+
+
+class TestLinprogRSBland(LinprogRSTests):
+ options = {"pivot": "bland"}
+
+
+############################################
+# HiGHS-Simplex-Dual Option-Specific Tests #
+############################################
+
+
+class TestLinprogHiGHSSimplexDual(LinprogHiGHSTests):
+ method = "highs-ds"
+ options = {}
+
+ def test_lad_regression(self):
+ '''
+ The scaled model should be optimal, i.e. not produce unscaled model
+ infeasible. See https://github.com/ERGO-Code/HiGHS/issues/494.
+ '''
+ # Test to ensure gh-13610 is resolved (mismatch between HiGHS scaled
+ # and unscaled model statuses)
+ c, A_ub, b_ub, bnds = l1_regression_prob()
+ res = linprog(c, A_ub=A_ub, b_ub=b_ub, bounds=bnds,
+ method=self.method, options=self.options)
+ assert_equal(res.status, 0)
+ assert_(res.x is not None)
+ assert_(np.all(res.slack > -1e-6))
+ assert_(np.all(res.x <= [np.inf if ub is None else ub
+ for lb, ub in bnds]))
+ assert_(np.all(res.x >= [-np.inf if lb is None else lb - 1e-7
+ for lb, ub in bnds]))
+
+
+###################################
+# HiGHS-IPM Option-Specific Tests #
+###################################
+
+
+class TestLinprogHiGHSIPM(LinprogHiGHSTests):
+ method = "highs-ipm"
+ options = {}
+
+
+###################################
+# HiGHS-MIP Option-Specific Tests #
+###################################
+
+
+class TestLinprogHiGHSMIP:
+ method = "highs"
+ options = {}
+
+ @pytest.mark.fail_slow(10)
+ @pytest.mark.xfail(condition=(sys.maxsize < 2 ** 32 and
+ platform.system() == "Linux"),
+ run=False,
+ reason="gh-16347")
+ def test_mip1(self):
+ # solve non-relaxed magic square problem (finally!)
+ # also check that values are all integers - they don't always
+ # come out of HiGHS that way
+ n = 4
+ A, b, c, numbers, M = magic_square(n)
+ bounds = [(0, 1)] * len(c)
+ integrality = [1] * len(c)
+
+ res = linprog(c=c*0, A_eq=A, b_eq=b, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ s = (numbers.flatten() * res.x).reshape(n**2, n, n)
+ square = np.sum(s, axis=0)
+ np.testing.assert_allclose(square.sum(axis=0), M)
+ np.testing.assert_allclose(square.sum(axis=1), M)
+ np.testing.assert_allclose(np.diag(square).sum(), M)
+ np.testing.assert_allclose(np.diag(square[:, ::-1]).sum(), M)
+
+ np.testing.assert_allclose(res.x, np.round(res.x), atol=1e-12)
+
+ def test_mip2(self):
+ # solve MIP with inequality constraints and all integer constraints
+ # source: slide 5,
+ # https://www.cs.upc.edu/~erodri/webpage/cps/theory/lp/milp/slides.pdf
+
+ # use all array inputs to test gh-16681 (integrality couldn't be array)
+ A_ub = np.array([[2, -2], [-8, 10]])
+ b_ub = np.array([-1, 13])
+ c = -np.array([1, 1])
+
+ bounds = np.array([(0, np.inf)] * len(c))
+ integrality = np.ones_like(c)
+
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ np.testing.assert_allclose(res.x, [1, 2])
+ np.testing.assert_allclose(res.fun, -3)
+
+ def test_mip3(self):
+ # solve MIP with inequality constraints and all integer constraints
+ # source: https://en.wikipedia.org/wiki/Integer_programming#Example
+ A_ub = np.array([[-1, 1], [3, 2], [2, 3]])
+ b_ub = np.array([1, 12, 12])
+ c = -np.array([0, 1])
+
+ bounds = [(0, np.inf)] * len(c)
+ integrality = [1] * len(c)
+
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ np.testing.assert_allclose(res.fun, -2)
+ # two optimal solutions possible, just need one of them
+ assert np.allclose(res.x, [1, 2]) or np.allclose(res.x, [2, 2])
+
+ def test_mip4(self):
+ # solve MIP with inequality constraints and only one integer constraint
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ A_ub = np.array([[-1, -2], [-4, -1], [2, 1]])
+ b_ub = np.array([14, -33, 20])
+ c = np.array([8, 1])
+
+ bounds = [(0, np.inf)] * len(c)
+ integrality = [0, 1]
+
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ np.testing.assert_allclose(res.x, [6.5, 7])
+ np.testing.assert_allclose(res.fun, 59)
+
+ def test_mip5(self):
+ # solve MIP with inequality and inequality constraints
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ A_ub = np.array([[1, 1, 1]])
+ b_ub = np.array([7])
+ A_eq = np.array([[4, 2, 1]])
+ b_eq = np.array([12])
+ c = np.array([-3, -2, -1])
+
+ bounds = [(0, np.inf), (0, np.inf), (0, 1)]
+ integrality = [0, 1, 0]
+
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method,
+ integrality=integrality)
+
+ np.testing.assert_allclose(res.x, [0, 6, 0])
+ np.testing.assert_allclose(res.fun, -12)
+
+ # gh-16897: these fields were not present, ensure that they are now
+ assert res.get("mip_node_count", None) is not None
+ assert res.get("mip_dual_bound", None) is not None
+ assert res.get("mip_gap", None) is not None
+
+ @pytest.mark.xslow
+ def test_mip6(self):
+ # solve a larger MIP with only equality constraints
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26],
+ [39, 16, 22, 28, 26, 30, 23, 24],
+ [18, 14, 29, 27, 30, 38, 26, 26],
+ [41, 26, 28, 36, 18, 38, 16, 26]])
+ b_eq = np.array([7872, 10466, 11322, 12058])
+ c = np.array([2, 10, 13, 17, 7, 5, 7, 3])
+
+ bounds = [(0, np.inf)]*8
+ integrality = [1]*8
+
+ res = linprog(c=c, A_eq=A_eq, b_eq=b_eq, bounds=bounds,
+ method=self.method, integrality=integrality)
+
+ np.testing.assert_allclose(res.fun, 1854)
+
+ @pytest.mark.xslow
+ def test_mip_rel_gap_passdown(self):
+ # MIP taken from test_mip6, solved with different values of mip_rel_gap
+ # solve a larger MIP with only equality constraints
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26],
+ [39, 16, 22, 28, 26, 30, 23, 24],
+ [18, 14, 29, 27, 30, 38, 26, 26],
+ [41, 26, 28, 36, 18, 38, 16, 26]])
+ b_eq = np.array([7872, 10466, 11322, 12058])
+ c = np.array([2, 10, 13, 17, 7, 5, 7, 3])
+
+ bounds = [(0, np.inf)]*8
+ integrality = [1]*8
+
+ mip_rel_gaps = [0.5, 0.25, 0.01, 0.001]
+ sol_mip_gaps = []
+ for mip_rel_gap in mip_rel_gaps:
+ res = linprog(c=c, A_ub=A_ub, b_ub=b_ub, A_eq=A_eq, b_eq=b_eq,
+ bounds=bounds, method=self.method,
+ integrality=integrality,
+ options={"mip_rel_gap": mip_rel_gap})
+ final_mip_gap = res["mip_gap"]
+ # assert that the solution actually has mip_gap lower than the
+ # required mip_rel_gap supplied
+ assert final_mip_gap <= mip_rel_gap
+ sol_mip_gaps.append(final_mip_gap)
+
+ # make sure that the mip_rel_gap parameter is actually doing something
+ # check that differences between solution gaps are declining
+ # monotonically with the mip_rel_gap parameter. np.diff does
+ # x[i+1] - x[i], so flip the array before differencing to get
+ # what should be a positive, monotone decreasing series of solution
+ # gaps
+ gap_diffs = np.diff(np.flip(sol_mip_gaps))
+ assert np.all(gap_diffs >= 0)
+ assert not np.all(gap_diffs == 0)
+
+ def test_semi_continuous(self):
+ # See issue #18106. This tests whether the solution is being
+ # checked correctly (status is 0) when integrality > 1:
+ # values are allowed to be 0 even if 0 is out of bounds.
+
+ c = np.array([1., 1., -1, -1])
+ bounds = np.array([[0.5, 1.5], [0.5, 1.5], [0.5, 1.5], [0.5, 1.5]])
+ integrality = np.array([2, 3, 2, 3])
+
+ res = linprog(c, bounds=bounds,
+ integrality=integrality, method='highs')
+
+ np.testing.assert_allclose(res.x, [0, 0, 1.5, 1])
+ assert res.status == 0
+
+ def test_bug_20584(self):
+ """
+ Test that when integrality is a list of all zeros, linprog gives the
+ same result as when it is an array of all zeros / integrality=None
+ """
+ c = [1, 1]
+ A_ub = [[-1, 0]]
+ b_ub = [-2.5]
+ res1 = linprog(c, A_ub=A_ub, b_ub=b_ub, integrality=[0, 0])
+ res2 = linprog(c, A_ub=A_ub, b_ub=b_ub, integrality=np.asarray([0, 0]))
+ res3 = linprog(c, A_ub=A_ub, b_ub=b_ub, integrality=None)
+ assert_equal(res1.x, res2.x)
+ assert_equal(res1.x, res3.x)
+
+
+###########################
+# Autoscale-Specific Tests#
+###########################
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class AutoscaleTests:
+ options = {"autoscale": True}
+
+ test_bug_6139 = LinprogCommonTests.test_bug_6139
+ test_bug_6690 = LinprogCommonTests.test_bug_6690
+ test_bug_7237 = LinprogCommonTests.test_bug_7237
+
+
+class TestAutoscaleIP(AutoscaleTests):
+ method = "interior-point"
+
+ def test_bug_6139(self):
+ self.options['tol'] = 1e-10
+ return AutoscaleTests.test_bug_6139(self)
+
+
+class TestAutoscaleSimplex(AutoscaleTests):
+ method = "simplex"
+
+
+class TestAutoscaleRS(AutoscaleTests):
+ method = "revised simplex"
+
+ def test_nontrivial_problem_with_guess(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=x_star)
+ _assert_success(res, desired_fun=f_star, desired_x=x_star)
+ assert_equal(res.nit, 0)
+
+ def test_nontrivial_problem_with_bad_guess(self):
+ c, A_ub, b_ub, A_eq, b_eq, x_star, f_star = nontrivial_problem()
+ bad_guess = [1, 2, 3, .5]
+ res = linprog(c, A_ub, b_ub, A_eq, b_eq, bounds,
+ method=self.method, options=self.options, x0=bad_guess)
+ assert_equal(res.status, 6)
+
+
+###########################
+# Redundancy Removal Tests#
+###########################
+
+
+@pytest.mark.filterwarnings("ignore::DeprecationWarning")
+class RRTests:
+ method = "interior-point"
+ LCT = LinprogCommonTests
+ # these are a few of the existing tests that have redundancy
+ test_RR_infeasibility = LCT.test_remove_redundancy_infeasibility
+ test_bug_10349 = LCT.test_bug_10349
+ test_bug_7044 = LCT.test_bug_7044
+ test_NFLC = LCT.test_network_flow_limited_capacity
+ test_enzo_example_b = LCT.test_enzo_example_b
+
+
+class TestRRSVD(RRTests):
+ options = {"rr_method": "SVD"}
+
+
+class TestRRPivot(RRTests):
+ options = {"rr_method": "pivot"}
+
+
+class TestRRID(RRTests):
+ options = {"rr_method": "ID"}
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_common.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_common.py
new file mode 100644
index 0000000000000000000000000000000000000000..650deedce88b6babd8a3f2b62a5839f1a6cb966c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_common.py
@@ -0,0 +1,297 @@
+from numpy.testing import assert_, assert_allclose, assert_equal
+from pytest import raises as assert_raises
+import numpy as np
+
+from scipy.optimize._lsq.common import (
+ step_size_to_bound, find_active_constraints, make_strictly_feasible,
+ CL_scaling_vector, intersect_trust_region, build_quadratic_1d,
+ minimize_quadratic_1d, evaluate_quadratic, reflective_transformation,
+ left_multiplied_operator, right_multiplied_operator)
+
+
+class TestBounds:
+ def test_step_size_to_bounds(self):
+ lb = np.array([-1.0, 2.5, 10.0])
+ ub = np.array([1.0, 5.0, 100.0])
+ x = np.array([0.0, 2.5, 12.0])
+
+ s = np.array([0.1, 0.0, 0.0])
+ step, hits = step_size_to_bound(x, s, lb, ub)
+ assert_equal(step, 10)
+ assert_equal(hits, [1, 0, 0])
+
+ s = np.array([0.01, 0.05, -1.0])
+ step, hits = step_size_to_bound(x, s, lb, ub)
+ assert_equal(step, 2)
+ assert_equal(hits, [0, 0, -1])
+
+ s = np.array([10.0, -0.0001, 100.0])
+ step, hits = step_size_to_bound(x, s, lb, ub)
+ assert_equal(step, np.array(-0))
+ assert_equal(hits, [0, -1, 0])
+
+ s = np.array([1.0, 0.5, -2.0])
+ step, hits = step_size_to_bound(x, s, lb, ub)
+ assert_equal(step, 1.0)
+ assert_equal(hits, [1, 0, -1])
+
+ s = np.zeros(3)
+ step, hits = step_size_to_bound(x, s, lb, ub)
+ assert_equal(step, np.inf)
+ assert_equal(hits, [0, 0, 0])
+
+ def test_find_active_constraints(self):
+ lb = np.array([0.0, -10.0, 1.0])
+ ub = np.array([1.0, 0.0, 100.0])
+
+ x = np.array([0.5, -5.0, 2.0])
+ active = find_active_constraints(x, lb, ub)
+ assert_equal(active, [0, 0, 0])
+
+ x = np.array([0.0, 0.0, 10.0])
+ active = find_active_constraints(x, lb, ub)
+ assert_equal(active, [-1, 1, 0])
+
+ active = find_active_constraints(x, lb, ub, rtol=0)
+ assert_equal(active, [-1, 1, 0])
+
+ x = np.array([1e-9, -1e-8, 100 - 1e-9])
+ active = find_active_constraints(x, lb, ub)
+ assert_equal(active, [0, 0, 1])
+
+ active = find_active_constraints(x, lb, ub, rtol=1.5e-9)
+ assert_equal(active, [-1, 0, 1])
+
+ lb = np.array([1.0, -np.inf, -np.inf])
+ ub = np.array([np.inf, 10.0, np.inf])
+
+ x = np.ones(3)
+ active = find_active_constraints(x, lb, ub)
+ assert_equal(active, [-1, 0, 0])
+
+ # Handles out-of-bound cases.
+ x = np.array([0.0, 11.0, 0.0])
+ active = find_active_constraints(x, lb, ub)
+ assert_equal(active, [-1, 1, 0])
+
+ active = find_active_constraints(x, lb, ub, rtol=0)
+ assert_equal(active, [-1, 1, 0])
+
+ def test_make_strictly_feasible(self):
+ lb = np.array([-0.5, -0.8, 2.0])
+ ub = np.array([0.8, 1.0, 3.0])
+
+ x = np.array([-0.5, 0.0, 2 + 1e-10])
+
+ x_new = make_strictly_feasible(x, lb, ub, rstep=0)
+ assert_(x_new[0] > -0.5)
+ assert_equal(x_new[1:], x[1:])
+
+ x_new = make_strictly_feasible(x, lb, ub, rstep=1e-4)
+ assert_equal(x_new, [-0.5 + 1e-4, 0.0, 2 * (1 + 1e-4)])
+
+ x = np.array([-0.5, -1, 3.1])
+ x_new = make_strictly_feasible(x, lb, ub)
+ assert_(np.all((x_new >= lb) & (x_new <= ub)))
+
+ x_new = make_strictly_feasible(x, lb, ub, rstep=0)
+ assert_(np.all((x_new >= lb) & (x_new <= ub)))
+
+ lb = np.array([-1, 100.0])
+ ub = np.array([1, 100.0 + 1e-10])
+ x = np.array([0, 100.0])
+ x_new = make_strictly_feasible(x, lb, ub, rstep=1e-8)
+ assert_equal(x_new, [0, 100.0 + 0.5e-10])
+
+ def test_scaling_vector(self):
+ lb = np.array([-np.inf, -5.0, 1.0, -np.inf])
+ ub = np.array([1.0, np.inf, 10.0, np.inf])
+ x = np.array([0.5, 2.0, 5.0, 0.0])
+ g = np.array([1.0, 0.1, -10.0, 0.0])
+ v, dv = CL_scaling_vector(x, g, lb, ub)
+ assert_equal(v, [1.0, 7.0, 5.0, 1.0])
+ assert_equal(dv, [0.0, 1.0, -1.0, 0.0])
+
+
+class TestQuadraticFunction:
+ def setup_method(self):
+ self.J = np.array([
+ [0.1, 0.2],
+ [-1.0, 1.0],
+ [0.5, 0.2]])
+ self.g = np.array([0.8, -2.0])
+ self.diag = np.array([1.0, 2.0])
+
+ def test_build_quadratic_1d(self):
+ s = np.zeros(2)
+ a, b = build_quadratic_1d(self.J, self.g, s)
+ assert_equal(a, 0)
+ assert_equal(b, 0)
+
+ a, b = build_quadratic_1d(self.J, self.g, s, diag=self.diag)
+ assert_equal(a, 0)
+ assert_equal(b, 0)
+
+ s = np.array([1.0, -1.0])
+ a, b = build_quadratic_1d(self.J, self.g, s)
+ assert_equal(a, 2.05)
+ assert_equal(b, 2.8)
+
+ a, b = build_quadratic_1d(self.J, self.g, s, diag=self.diag)
+ assert_equal(a, 3.55)
+ assert_equal(b, 2.8)
+
+ s0 = np.array([0.5, 0.5])
+ a, b, c = build_quadratic_1d(self.J, self.g, s, diag=self.diag, s0=s0)
+ assert_equal(a, 3.55)
+ assert_allclose(b, 2.39)
+ assert_allclose(c, -0.1525)
+
+ def test_minimize_quadratic_1d(self):
+ a = 5
+ b = -1
+
+ t, y = minimize_quadratic_1d(a, b, 1, 2)
+ assert_equal(t, 1)
+ assert_allclose(y, a * t**2 + b * t, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, -2, -1)
+ assert_equal(t, -1)
+ assert_allclose(y, a * t**2 + b * t, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, -1, 1)
+ assert_equal(t, 0.1)
+ assert_allclose(y, a * t**2 + b * t, rtol=1e-15)
+
+ c = 10
+ t, y = minimize_quadratic_1d(a, b, -1, 1, c=c)
+ assert_equal(t, 0.1)
+ assert_allclose(y, a * t**2 + b * t + c, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, -np.inf, np.inf, c=c)
+ assert_equal(t, 0.1)
+ assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, 0, np.inf, c=c)
+ assert_equal(t, 0.1)
+ assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15)
+
+ t, y = minimize_quadratic_1d(a, b, -np.inf, 0, c=c)
+ assert_equal(t, 0)
+ assert_allclose(y, a * t ** 2 + b * t + c, rtol=1e-15)
+
+ a = -1
+ b = 0.2
+ t, y = minimize_quadratic_1d(a, b, -np.inf, np.inf)
+ assert_equal(y, -np.inf)
+
+ t, y = minimize_quadratic_1d(a, b, 0, np.inf)
+ assert_equal(t, np.inf)
+ assert_equal(y, -np.inf)
+
+ t, y = minimize_quadratic_1d(a, b, -np.inf, 0)
+ assert_equal(t, -np.inf)
+ assert_equal(y, -np.inf)
+
+ def test_evaluate_quadratic(self):
+ s = np.array([1.0, -1.0])
+
+ value = evaluate_quadratic(self.J, self.g, s)
+ assert_equal(value, 4.85)
+
+ value = evaluate_quadratic(self.J, self.g, s, diag=self.diag)
+ assert_equal(value, 6.35)
+
+ s = np.array([[1.0, -1.0],
+ [1.0, 1.0],
+ [0.0, 0.0]])
+
+ values = evaluate_quadratic(self.J, self.g, s)
+ assert_allclose(values, [4.85, -0.91, 0.0])
+
+ values = evaluate_quadratic(self.J, self.g, s, diag=self.diag)
+ assert_allclose(values, [6.35, 0.59, 0.0])
+
+
+class TestTrustRegion:
+ def test_intersect(self):
+ Delta = 1.0
+
+ x = np.zeros(3)
+ s = np.array([1.0, 0.0, 0.0])
+ t_neg, t_pos = intersect_trust_region(x, s, Delta)
+ assert_equal(t_neg, -1)
+ assert_equal(t_pos, 1)
+
+ s = np.array([-1.0, 1.0, -1.0])
+ t_neg, t_pos = intersect_trust_region(x, s, Delta)
+ assert_allclose(t_neg, -3**-0.5)
+ assert_allclose(t_pos, 3**-0.5)
+
+ x = np.array([0.5, -0.5, 0])
+ s = np.array([0, 0, 1.0])
+ t_neg, t_pos = intersect_trust_region(x, s, Delta)
+ assert_allclose(t_neg, -2**-0.5)
+ assert_allclose(t_pos, 2**-0.5)
+
+ x = np.ones(3)
+ assert_raises(ValueError, intersect_trust_region, x, s, Delta)
+
+ x = np.zeros(3)
+ s = np.zeros(3)
+ assert_raises(ValueError, intersect_trust_region, x, s, Delta)
+
+
+def test_reflective_transformation():
+ lb = np.array([-1, -2], dtype=float)
+ ub = np.array([5, 3], dtype=float)
+
+ y = np.array([0, 0])
+ x, g = reflective_transformation(y, lb, ub)
+ assert_equal(x, y)
+ assert_equal(g, np.ones(2))
+
+ y = np.array([-4, 4], dtype=float)
+
+ x, g = reflective_transformation(y, lb, np.array([np.inf, np.inf]))
+ assert_equal(x, [2, 4])
+ assert_equal(g, [-1, 1])
+
+ x, g = reflective_transformation(y, np.array([-np.inf, -np.inf]), ub)
+ assert_equal(x, [-4, 2])
+ assert_equal(g, [1, -1])
+
+ x, g = reflective_transformation(y, lb, ub)
+ assert_equal(x, [2, 2])
+ assert_equal(g, [-1, -1])
+
+ lb = np.array([-np.inf, -2])
+ ub = np.array([5, np.inf])
+ y = np.array([10, 10], dtype=float)
+ x, g = reflective_transformation(y, lb, ub)
+ assert_equal(x, [0, 10])
+ assert_equal(g, [-1, 1])
+
+
+def test_linear_operators():
+ A = np.arange(6).reshape((3, 2))
+
+ d_left = np.array([-1, 2, 5])
+ DA = np.diag(d_left).dot(A)
+ J_left = left_multiplied_operator(A, d_left)
+
+ d_right = np.array([5, 10])
+ AD = A.dot(np.diag(d_right))
+ J_right = right_multiplied_operator(A, d_right)
+
+ x = np.array([-2, 3])
+ X = -2 * np.arange(2, 8).reshape((2, 3))
+ xt = np.array([0, -2, 15])
+
+ assert_allclose(DA.dot(x), J_left.matvec(x))
+ assert_allclose(DA.dot(X), J_left.matmat(X))
+ assert_allclose(DA.T.dot(xt), J_left.rmatvec(xt))
+
+ assert_allclose(AD.dot(x), J_right.matvec(x))
+ assert_allclose(AD.dot(X), J_right.matmat(X))
+ assert_allclose(AD.T.dot(xt), J_right.rmatvec(xt))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_linear.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_linear.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cc394a46ab5f8b4339ecd4b72002332f7e1639b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_lsq_linear.py
@@ -0,0 +1,290 @@
+import warnings
+
+import pytest
+
+import numpy as np
+from numpy.linalg import lstsq
+from numpy.testing import assert_allclose, assert_equal, assert_
+
+from scipy.sparse import random_array, coo_array
+from scipy.sparse.linalg import aslinearoperator
+from scipy.optimize import lsq_linear
+from scipy.optimize._minimize import Bounds
+
+
+A = np.array([
+ [0.171, -0.057],
+ [-0.049, -0.248],
+ [-0.166, 0.054],
+])
+b = np.array([0.074, 1.014, -0.383])
+
+
+class BaseMixin:
+ def setup_method(self):
+ self.rnd = np.random.default_rng(1092892)
+
+ def test_dense_no_bounds(self):
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, method=self.method, lsq_solver=lsq_solver)
+ assert_allclose(res.x, lstsq(A, b, rcond=-1)[0])
+ assert_allclose(res.x, res.unbounded_sol[0])
+
+ def test_dense_bounds(self):
+ # Solutions for comparison are taken from MATLAB.
+ lb = np.array([-1, -10])
+ ub = np.array([1, 0])
+ unbounded_sol = lstsq(A, b, rcond=-1)[0]
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, lstsq(A, b, rcond=-1)[0])
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ lb = np.array([0.0, -np.inf])
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, np.inf), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, np.array([0.0, -4.084174437334673]),
+ atol=1e-6)
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ lb = np.array([-1, 0])
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, np.inf), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, np.array([0.448427311733504, 0]),
+ atol=1e-15)
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ ub = np.array([np.inf, -5])
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, np.array([-0.105560998682388, -5]))
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ ub = np.array([-1, np.inf])
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (-np.inf, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, np.array([-1, -4.181102129483254]))
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ lb = np.array([0, -4])
+ ub = np.array([1, 0])
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, np.array([0.005236663400791, -4]))
+ assert_allclose(res.unbounded_sol[0], unbounded_sol)
+
+ def test_bounds_variants(self):
+ x = np.array([1, 3])
+ A = self.rnd.uniform(size=(2, 2))
+ b = A@x
+ lb = np.array([1, 1])
+ ub = np.array([2, 2])
+ bounds_old = (lb, ub)
+ bounds_new = Bounds(lb, ub)
+ res_old = lsq_linear(A, b, bounds_old)
+ res_new = lsq_linear(A, b, bounds_new)
+ assert not np.allclose(res_new.x, res_new.unbounded_sol[0])
+ assert_allclose(res_old.x, res_new.x)
+
+ def test_np_matrix(self):
+ # gh-10711
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", PendingDeprecationWarning)
+ A = np.matrix([[20, -4, 0, 2, 3], [10, -2, 1, 0, -1]])
+ k = np.array([20, 15])
+ lsq_linear(A, k)
+
+ def test_dense_rank_deficient(self):
+ A = np.array([[-0.307, -0.184]])
+ b = np.array([0.773])
+ lb = [-0.1, -0.1]
+ ub = [0.1, 0.1]
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.x, [-0.1, -0.1])
+ assert_allclose(res.unbounded_sol[0], lstsq(A, b, rcond=-1)[0])
+
+ A = np.array([
+ [0.334, 0.668],
+ [-0.516, -1.032],
+ [0.192, 0.384],
+ ])
+ b = np.array([-1.436, 0.135, 0.909])
+ lb = [0, -1]
+ ub = [1, -0.5]
+ for lsq_solver in self.lsq_solvers:
+ res = lsq_linear(A, b, (lb, ub), method=self.method,
+ lsq_solver=lsq_solver)
+ assert_allclose(res.optimality, 0, atol=1e-11)
+ assert_allclose(res.unbounded_sol[0], lstsq(A, b, rcond=-1)[0])
+
+ def test_full_result(self):
+ lb = np.array([0, -4])
+ ub = np.array([1, 0])
+ res = lsq_linear(A, b, (lb, ub), method=self.method)
+
+ assert_allclose(res.x, [0.005236663400791, -4])
+ assert_allclose(res.unbounded_sol[0], lstsq(A, b, rcond=-1)[0])
+
+ r = A.dot(res.x) - b
+ assert_allclose(res.cost, 0.5 * np.dot(r, r))
+ assert_allclose(res.fun, r)
+
+ assert_allclose(res.optimality, 0.0, atol=1e-12)
+ assert_equal(res.active_mask, [0, -1])
+ assert_(res.nit < 15)
+ assert_(res.status == 1 or res.status == 3)
+ assert_(isinstance(res.message, str))
+ assert_(res.success)
+
+ # This is a test for issue #9982.
+ def test_almost_singular(self):
+ A = np.array(
+ [[0.8854232310355122, 0.0365312146937765, 0.0365312146836789],
+ [0.3742460132129041, 0.0130523214078376, 0.0130523214077873],
+ [0.9680633871281361, 0.0319366128718639, 0.0319366128718388]])
+
+ b = np.array(
+ [0.0055029366538097, 0.0026677442422208, 0.0066612514782381])
+
+ result = lsq_linear(A, b, method=self.method)
+ assert_(result.cost < 1.1e-8)
+
+ @pytest.mark.xslow
+ def test_large_rank_deficient(self):
+ rng = np.random.default_rng(1290209)
+ n, m = np.sort(rng.integers(2, 1000, size=2))
+ m *= 2 # make m >> n
+ A = 1.0 * rng.integers(-99, 99, size=[m, n])
+ b = 1.0 * rng.integers(-99, 99, size=[m])
+ bounds = 1.0 * np.sort(rng.integers(-99, 99, size=(2, n)), axis=0)
+ bounds[1, :] += 1.0 # ensure up > lb
+
+ # Make the A matrix strongly rank deficient by replicating some columns
+ w = rng.choice(n, n) # Select random columns with duplicates
+ A = A[:, w]
+
+ x_bvls = lsq_linear(A, b, bounds=bounds, method='bvls').x
+ x_trf = lsq_linear(A, b, bounds=bounds, method='trf').x
+
+ cost_bvls = np.sum((A @ x_bvls - b)**2)
+ cost_trf = np.sum((A @ x_trf - b)**2)
+
+ assert_(abs(cost_bvls - cost_trf) < cost_trf*1e-10)
+
+ def test_convergence_small_array(self):
+ A = np.array([[49.0, 41.0, -32.0],
+ [-19.0, -32.0, -8.0],
+ [-13.0, 10.0, 69.0]])
+ b = np.array([-41.0, -90.0, 47.0])
+ bounds = np.array([[31.0, -44.0, 26.0],
+ [54.0, -32.0, 28.0]])
+
+ x_bvls = lsq_linear(A, b, bounds=bounds, method='bvls').x
+ x_trf = lsq_linear(A, b, bounds=bounds, method='trf').x
+
+ cost_bvls = np.sum((A @ x_bvls - b)**2)
+ cost_trf = np.sum((A @ x_trf - b)**2)
+
+ assert_(abs(cost_bvls - cost_trf) < cost_trf*1e-10)
+
+
+class SparseMixin:
+ def test_sparse_and_LinearOperator(self):
+ m = 5000
+ n = 1000
+ rng = np.random.RandomState(0)
+ A = random_array((m, n), random_state=rng)
+ b = rng.randn(m)
+ res = lsq_linear(A, b)
+ assert_allclose(res.optimality, 0, atol=1e-6)
+
+ A = aslinearoperator(A)
+ res = lsq_linear(A, b)
+ assert_allclose(res.optimality, 0, atol=1e-6)
+
+ @pytest.mark.fail_slow(10)
+ def test_sparse_bounds(self):
+ m = 5000
+ n = 1000
+
+ rng = np.random.RandomState(0)
+ A = random_array((m, n), random_state=rng)
+ b = rng.randn(m)
+ lb = rng.randn(n)
+ ub = lb + 1
+ res = lsq_linear(A, b, (lb, ub))
+ assert_allclose(res.optimality, 0.0, atol=1e-6)
+
+ res = lsq_linear(A, b, (lb, ub), lsmr_tol=1e-13,
+ lsmr_maxiter=1500)
+ assert_allclose(res.optimality, 0.0, atol=1e-6)
+
+ res = lsq_linear(A, b, (lb, ub), lsmr_tol='auto')
+ assert_allclose(res.optimality, 0.0, atol=1e-6)
+
+ def test_sparse_ill_conditioned(self):
+ # Sparse matrix with condition number of ~4 million
+ data = np.array([1., 1., 1., 1. + 1e-6, 1.])
+ row = np.array([0, 0, 1, 2, 2])
+ col = np.array([0, 2, 1, 0, 2])
+ A = coo_array((data, (row, col)), shape=(3, 3))
+
+ # Get the exact solution
+ exact_sol = lsq_linear(A.toarray(), b, lsq_solver='exact')
+
+ # Default lsmr arguments should not fully converge the solution
+ default_lsmr_sol = lsq_linear(A, b, lsq_solver='lsmr')
+ with pytest.raises(AssertionError):
+ assert_allclose(exact_sol.x, default_lsmr_sol.x)
+
+ # By increasing the maximum lsmr iters, it will converge
+ conv_lsmr = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=10)
+ assert_allclose(exact_sol.x, conv_lsmr.x)
+
+
+class TestTRF(BaseMixin, SparseMixin):
+ method = 'trf'
+ lsq_solvers = ['exact', 'lsmr']
+
+
+class TestBVLS(BaseMixin):
+ method = 'bvls'
+ lsq_solvers = ['exact']
+
+
+class TestErrorChecking:
+ def test_option_lsmr_tol(self):
+ # Should work with a positive float, string equal to 'auto', or None
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=1e-2)
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol='auto')
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=None)
+
+ # Should raise error with negative float, strings
+ # other than 'auto', and integers
+ err_message = "`lsmr_tol` must be None, 'auto', or positive float."
+ with pytest.raises(ValueError, match=err_message):
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=-0.1)
+ with pytest.raises(ValueError, match=err_message):
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol='foo')
+ with pytest.raises(ValueError, match=err_message):
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_tol=1)
+
+ def test_option_lsmr_maxiter(self):
+ # Should work with positive integers or None
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=1)
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=None)
+
+ # Should raise error with 0 or negative max iter
+ err_message = "`lsmr_maxiter` must be None or positive integer."
+ with pytest.raises(ValueError, match=err_message):
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=0)
+ with pytest.raises(ValueError, match=err_message):
+ _ = lsq_linear(A, b, lsq_solver='lsmr', lsmr_maxiter=-1)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_milp.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_milp.py
new file mode 100644
index 0000000000000000000000000000000000000000..4fdd5ae213d2aa072269aa890a4d934044665074
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_milp.py
@@ -0,0 +1,477 @@
+"""
+Unit test for Mixed Integer Linear Programming
+"""
+import re
+import sys
+
+import numpy as np
+from numpy.testing import assert_allclose, assert_array_equal
+import pytest
+
+from .test_linprog import magic_square
+from scipy.optimize import milp, Bounds, LinearConstraint
+from scipy import sparse
+
+
+_IS_32BIT = (sys.maxsize < 2**32)
+
+def test_milp_iv():
+
+ message = "`c` must be a dense array"
+ with pytest.raises(ValueError, match=message):
+ milp(sparse.coo_array([0, 0]))
+
+ message = "`c` must be a one-dimensional array of finite numbers with"
+ with pytest.raises(ValueError, match=message):
+ milp(np.zeros((3, 4)))
+ with pytest.raises(ValueError, match=message):
+ milp([])
+ with pytest.raises(ValueError, match=message):
+ milp(None)
+
+ message = "`bounds` must be convertible into an instance of..."
+ with pytest.raises(ValueError, match=message):
+ milp(1, bounds=10)
+
+ message = "`constraints` (or each element within `constraints`) must be"
+ with pytest.raises(ValueError, match=re.escape(message)):
+ milp(1, constraints=10)
+ with pytest.raises(ValueError, match=re.escape(message)):
+ milp(np.zeros(3), constraints=([[1, 2, 3]], [2, 3], [2, 3]))
+ with pytest.raises(ValueError, match=re.escape(message)):
+ milp(np.zeros(2), constraints=([[1, 2]], [2], sparse.coo_array([2])))
+
+ message = "The shape of `A` must be (len(b_l), len(c))."
+ with pytest.raises(ValueError, match=re.escape(message)):
+ milp(np.zeros(3), constraints=([[1, 2]], [2], [2]))
+
+ message = "`integrality` must be a dense array"
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2], integrality=sparse.coo_array([1, 2]))
+
+ message = ("`integrality` must contain integers 0-3 and be broadcastable "
+ "to `c.shape`.")
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], integrality=[1, 2])
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], integrality=[1, 5, 3])
+
+ message = "Lower and upper bounds must be dense arrays."
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2], sparse.coo_array([3, 4])))
+
+ message = "`lb`, `ub`, and `keep_feasible` must be broadcastable."
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2], [3, 4, 5]))
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2, 3], [4, 5]))
+
+ message = "`bounds.lb` and `bounds.ub` must contain reals and..."
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2], [3, 4]))
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2, 3], ["3+4", 4, 5]))
+ with pytest.raises(ValueError, match=message):
+ milp([1, 2, 3], bounds=([1, 2, 3], [set(), 4, 5]))
+
+
+@pytest.mark.xfail(run=False,
+ reason="Needs to be fixed in `_highs_wrapper`")
+def test_milp_options(capsys):
+ # run=False now because of gh-16347
+ message = "Unrecognized options detected: {'ekki'}..."
+ options = {'ekki': True}
+ with pytest.warns(RuntimeWarning, match=message):
+ milp(1, options=options)
+
+ A, b, c, numbers, M = magic_square(3)
+ options = {"disp": True, "presolve": False, "time_limit": 0.05}
+ res = milp(c=c, constraints=(A, b, b), bounds=(0, 1), integrality=1,
+ options=options)
+
+ captured = capsys.readouterr()
+ assert "Presolve is switched off" in captured.out
+ assert "Time Limit Reached" in captured.out
+ assert not res.success
+
+
+def test_result():
+ A, b, c, numbers, M = magic_square(3)
+ res = milp(c=c, constraints=(A, b, b), bounds=(0, 1), integrality=1)
+ assert res.status == 0
+ assert res.success
+ msg = "Optimization terminated successfully. (HiGHS Status 7:"
+ assert res.message.startswith(msg)
+ assert isinstance(res.x, np.ndarray)
+ assert isinstance(res.fun, float)
+ assert isinstance(res.mip_node_count, int)
+ assert isinstance(res.mip_dual_bound, float)
+ assert isinstance(res.mip_gap, float)
+
+ A, b, c, numbers, M = magic_square(6)
+ res = milp(c=c*0, constraints=(A, b, b), bounds=(0, 1), integrality=1,
+ options={'time_limit': 0.05})
+ assert res.status == 1
+ assert not res.success
+ msg = "Time limit reached. (HiGHS Status 13:"
+ assert res.message.startswith(msg)
+ assert (res.fun is res.mip_dual_bound is res.mip_gap
+ is res.mip_node_count is res.x is None)
+
+ res = milp(1, bounds=(1, -1))
+ assert res.status == 2
+ assert not res.success
+ msg = "The problem is infeasible. (HiGHS Status 8:"
+ assert res.message.startswith(msg)
+ assert (res.fun is res.mip_dual_bound is res.mip_gap
+ is res.mip_node_count is res.x is None)
+
+ res = milp(-1)
+ assert res.status == 3
+ assert not res.success
+ msg = "The problem is unbounded. (HiGHS Status 10:"
+ assert res.message.startswith(msg)
+ assert (res.fun is res.mip_dual_bound is res.mip_gap
+ is res.mip_node_count is res.x is None)
+
+
+def test_milp_optional_args():
+ # check that arguments other than `c` are indeed optional
+ res = milp(1)
+ assert res.fun == 0
+ assert_array_equal(res.x, [0])
+
+
+def test_milp_1():
+ # solve magic square problem
+ n = 3
+ A, b, c, numbers, M = magic_square(n)
+ A = sparse.csc_array(A) # confirm that sparse arrays are accepted
+ res = milp(c=c*0, constraints=(A, b, b), bounds=(0, 1), integrality=1)
+
+ # check that solution is a magic square
+ x = np.round(res.x)
+ s = (numbers.flatten() * x).reshape(n**2, n, n)
+ square = np.sum(s, axis=0)
+ np.testing.assert_allclose(square.sum(axis=0), M)
+ np.testing.assert_allclose(square.sum(axis=1), M)
+ np.testing.assert_allclose(np.diag(square).sum(), M)
+ np.testing.assert_allclose(np.diag(square[:, ::-1]).sum(), M)
+
+
+def test_milp_2():
+ # solve MIP with inequality constraints and all integer constraints
+ # source: slide 5,
+ # https://www.cs.upc.edu/~erodri/webpage/cps/theory/lp/milp/slides.pdf
+ # also check that `milp` accepts all valid ways of specifying constraints
+ c = -np.ones(2)
+ A = [[-2, 2], [-8, 10]]
+ b_l = [1, -np.inf]
+ b_u = [np.inf, 13]
+ linear_constraint = LinearConstraint(A, b_l, b_u)
+
+ # solve original problem
+ res1 = milp(c=c, constraints=(A, b_l, b_u), integrality=True)
+ res2 = milp(c=c, constraints=linear_constraint, integrality=True)
+ res3 = milp(c=c, constraints=[(A, b_l, b_u)], integrality=True)
+ res4 = milp(c=c, constraints=[linear_constraint], integrality=True)
+ res5 = milp(c=c, integrality=True,
+ constraints=[(A[:1], b_l[:1], b_u[:1]),
+ (A[1:], b_l[1:], b_u[1:])])
+ res6 = milp(c=c, integrality=True,
+ constraints=[LinearConstraint(A[:1], b_l[:1], b_u[:1]),
+ LinearConstraint(A[1:], b_l[1:], b_u[1:])])
+ res7 = milp(c=c, integrality=True,
+ constraints=[(A[:1], b_l[:1], b_u[:1]),
+ LinearConstraint(A[1:], b_l[1:], b_u[1:])])
+ xs = np.array([res1.x, res2.x, res3.x, res4.x, res5.x, res6.x, res7.x])
+ funs = np.array([res1.fun, res2.fun, res3.fun,
+ res4.fun, res5.fun, res6.fun, res7.fun])
+ np.testing.assert_allclose(xs, np.broadcast_to([1, 2], xs.shape))
+ np.testing.assert_allclose(funs, -3)
+
+ # solve relaxed problem
+ res = milp(c=c, constraints=(A, b_l, b_u))
+ np.testing.assert_allclose(res.x, [4, 4.5])
+ np.testing.assert_allclose(res.fun, -8.5)
+
+
+def test_milp_3():
+ # solve MIP with inequality constraints and all integer constraints
+ # source: https://en.wikipedia.org/wiki/Integer_programming#Example
+ c = [0, -1]
+ A = [[-1, 1], [3, 2], [2, 3]]
+ b_u = [1, 12, 12]
+ b_l = np.full_like(b_u, -np.inf, dtype=np.float64)
+ constraints = LinearConstraint(A, b_l, b_u)
+
+ integrality = np.ones_like(c)
+
+ # solve original problem
+ res = milp(c=c, constraints=constraints, integrality=integrality)
+ assert_allclose(res.fun, -2)
+ # two optimal solutions possible, just need one of them
+ assert np.allclose(res.x, [1, 2]) or np.allclose(res.x, [2, 2])
+
+ # solve relaxed problem
+ res = milp(c=c, constraints=constraints)
+ assert_allclose(res.fun, -2.8)
+ assert_allclose(res.x, [1.8, 2.8])
+
+
+def test_milp_4():
+ # solve MIP with inequality constraints and only one integer constraint
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ c = [8, 1]
+ integrality = [0, 1]
+ A = [[1, 2], [-4, -1], [2, 1]]
+ b_l = [-14, -np.inf, -np.inf]
+ b_u = [np.inf, -33, 20]
+ constraints = LinearConstraint(A, b_l, b_u)
+ bounds = Bounds(-np.inf, np.inf)
+
+ res = milp(c, integrality=integrality, bounds=bounds,
+ constraints=constraints)
+ assert_allclose(res.fun, 59)
+ assert_allclose(res.x, [6.5, 7])
+
+
+def test_milp_5():
+ # solve MIP with inequality and equality constraints
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ c = [-3, -2, -1]
+ integrality = [0, 0, 1]
+ lb = [0, 0, 0]
+ ub = [np.inf, np.inf, 1]
+ bounds = Bounds(lb, ub)
+ A = [[1, 1, 1], [4, 2, 1]]
+ b_l = [-np.inf, 12]
+ b_u = [7, 12]
+ constraints = LinearConstraint(A, b_l, b_u)
+
+ res = milp(c, integrality=integrality, bounds=bounds,
+ constraints=constraints)
+ # there are multiple solutions
+ assert_allclose(res.fun, -12)
+
+
+@pytest.mark.xslow
+def test_milp_6():
+ # solve a larger MIP with only equality constraints
+ # source: https://www.mathworks.com/help/optim/ug/intlinprog.html
+ integrality = 1
+ A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26],
+ [39, 16, 22, 28, 26, 30, 23, 24],
+ [18, 14, 29, 27, 30, 38, 26, 26],
+ [41, 26, 28, 36, 18, 38, 16, 26]])
+ b_eq = np.array([7872, 10466, 11322, 12058])
+ c = np.array([2, 10, 13, 17, 7, 5, 7, 3])
+
+ res = milp(c=c, constraints=(A_eq, b_eq, b_eq), integrality=integrality)
+
+ np.testing.assert_allclose(res.fun, 1854)
+
+
+def test_infeasible_prob_16609():
+ # Ensure presolve does not mark trivially infeasible problems
+ # as Optimal -- see gh-16609
+ c = [1.0, 0.0]
+ integrality = [0, 1]
+
+ lb = [0, -np.inf]
+ ub = [np.inf, np.inf]
+ bounds = Bounds(lb, ub)
+
+ A_eq = [[0.0, 1.0]]
+ b_eq = [0.5]
+ constraints = LinearConstraint(A_eq, b_eq, b_eq)
+
+ res = milp(c, integrality=integrality, bounds=bounds,
+ constraints=constraints)
+ np.testing.assert_equal(res.status, 2)
+
+
+_msg_time = "Time limit reached. (HiGHS Status 13:"
+_msg_iter = "Iteration limit reached. (HiGHS Status 14:"
+
+# See https://github.com/scipy/scipy/pull/19255#issuecomment-1778438888
+@pytest.mark.xfail(reason="Often buggy, revisit with callbacks, gh-19255")
+@pytest.mark.skipif(np.intp(0).itemsize < 8,
+ reason="Unhandled 32-bit GCC FP bug")
+@pytest.mark.slow
+@pytest.mark.parametrize(["options", "msg"], [({"time_limit": 0.1}, _msg_time),
+ ({"node_limit": 1}, _msg_iter)])
+def test_milp_timeout_16545(options, msg):
+ # Ensure solution is not thrown away if MILP solver times out
+ # -- see gh-16545
+ rng = np.random.default_rng(5123833489170494244)
+ A = rng.integers(0, 5, size=(100, 100))
+ b_lb = np.full(100, fill_value=-np.inf)
+ b_ub = np.full(100, fill_value=25)
+ constraints = LinearConstraint(A, b_lb, b_ub)
+ variable_lb = np.zeros(100)
+ variable_ub = np.ones(100)
+ variable_bounds = Bounds(variable_lb, variable_ub)
+ integrality = np.ones(100)
+ c_vector = -np.ones(100)
+ res = milp(
+ c_vector,
+ integrality=integrality,
+ bounds=variable_bounds,
+ constraints=constraints,
+ options=options,
+ )
+
+ assert res.message.startswith(msg)
+ assert res["x"] is not None
+
+ # ensure solution is feasible
+ x = res["x"]
+ tol = 1e-8 # sometimes needed due to finite numerical precision
+ assert np.all(b_lb - tol <= A @ x) and np.all(A @ x <= b_ub + tol)
+ assert np.all(variable_lb - tol <= x) and np.all(x <= variable_ub + tol)
+ assert np.allclose(x, np.round(x))
+
+
+def test_three_constraints_16878():
+ # `milp` failed when exactly three constraints were passed
+ # Ensure that this is no longer the case.
+ rng = np.random.default_rng(5123833489170494244)
+ A = rng.integers(0, 5, size=(6, 6))
+ bl = np.full(6, fill_value=-np.inf)
+ bu = np.full(6, fill_value=10)
+ constraints = [LinearConstraint(A[:2], bl[:2], bu[:2]),
+ LinearConstraint(A[2:4], bl[2:4], bu[2:4]),
+ LinearConstraint(A[4:], bl[4:], bu[4:])]
+ constraints2 = [(A[:2], bl[:2], bu[:2]),
+ (A[2:4], bl[2:4], bu[2:4]),
+ (A[4:], bl[4:], bu[4:])]
+ lb = np.zeros(6)
+ ub = np.ones(6)
+ variable_bounds = Bounds(lb, ub)
+ c = -np.ones(6)
+ res1 = milp(c, bounds=variable_bounds, constraints=constraints)
+ res2 = milp(c, bounds=variable_bounds, constraints=constraints2)
+ ref = milp(c, bounds=variable_bounds, constraints=(A, bl, bu))
+ assert res1.success and res2.success
+ assert_allclose(res1.x, ref.x)
+ assert_allclose(res2.x, ref.x)
+
+
+@pytest.mark.xslow
+def test_mip_rel_gap_passdown():
+ # Solve problem with decreasing mip_gap to make sure mip_rel_gap decreases
+ # Adapted from test_linprog::TestLinprogHiGHSMIP::test_mip_rel_gap_passdown
+ # MIP taken from test_mip_6 above
+ A_eq = np.array([[22, 13, 26, 33, 21, 3, 14, 26],
+ [39, 16, 22, 28, 26, 30, 23, 24],
+ [18, 14, 29, 27, 30, 38, 26, 26],
+ [41, 26, 28, 36, 18, 38, 16, 26]])
+ b_eq = np.array([7872, 10466, 11322, 12058])
+ c = np.array([2, 10, 13, 17, 7, 5, 7, 3])
+
+ mip_rel_gaps = [0.25, 0.01, 0.001]
+ sol_mip_gaps = []
+ for mip_rel_gap in mip_rel_gaps:
+ res = milp(c=c, bounds=(0, np.inf), constraints=(A_eq, b_eq, b_eq),
+ integrality=True, options={"mip_rel_gap": mip_rel_gap})
+ # assert that the solution actually has mip_gap lower than the
+ # required mip_rel_gap supplied
+ assert res.mip_gap <= mip_rel_gap
+ # check that `res.mip_gap` is as defined in the documentation
+ assert res.mip_gap == (res.fun - res.mip_dual_bound)/res.fun
+ sol_mip_gaps.append(res.mip_gap)
+
+ # make sure that the mip_rel_gap parameter is actually doing something
+ # check that differences between solution gaps are declining
+ # monotonically with the mip_rel_gap parameter.
+ assert np.all(np.diff(sol_mip_gaps) < 0)
+
+@pytest.mark.xfail(reason='Upstream / Wrapper issue, see gh-20116')
+def test_large_numbers_gh20116():
+ h = 10 ** 12
+ A = np.array([[100.4534, h], [100.4534, -h]])
+ b = np.array([h, 0])
+ constraints = LinearConstraint(A=A, ub=b)
+ bounds = Bounds([0, 0], [1, 1])
+ c = np.array([0, 0])
+ res = milp(c=c, constraints=constraints, bounds=bounds, integrality=1)
+ assert res.status == 0
+ assert np.all(A @ res.x < b)
+
+
+def test_presolve_gh18907():
+ from scipy.optimize import milp
+ import numpy as np
+ inf = np.inf
+
+ # set up problem
+ c = np.array([-0.85850509, -0.82892676, -0.80026454, -0.63015535, -0.5099006,
+ -0.50077193, -0.4894404, -0.47285865, -0.39867774, -0.38069646,
+ -0.36733012, -0.36733012, -0.35820411, -0.31576141, -0.20626091,
+ -0.12466144, -0.10679516, -0.1061887, -0.1061887, -0.1061887,
+ -0., -0., -0., -0., 0., 0., 0., 0.])
+
+ A = np.array([[1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.,
+ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1., 0., 0., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 1., 0., 0., 0., 0., 0., 1., 0., 0., 0., -25., -0., -0., -0.],
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ -1., 0., 0., 0., 0., 0., -1., 0., 0., 0., 2., 0., 0., 0.],
+ [0., 0., 0., 0., 1., 1., 1., 1., 0., 1., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0., 0., 0., 0., 0., 0., -0., -25., -0., -0.],
+ [0., 0., 0., 0., -1., -1., -1., -1., 0., -1., 0., 0., 0.,
+ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 2., 0., 0.],
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 1., 1., 1., 0., 0., 0., 0., -0., -0., -25., -0.],
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., -1., -1., -1., 0., 0., 0., 0., 0., 0., 2., 0.],
+ [1., 1., 1., 1., 0., 0., 0., 0., 1., 0., 1., 1., 1., 1., 0.,
+ 1., 1., 0., 0., 0., 0., 1., 1., 1., -0., -0., -0., -25.],
+ [-1., -1., -1., -1., 0., 0., 0., 0., -1., 0., -1., -1., -1., -1.,
+ 0., -1., -1., 0., 0., 0., 0., -1., -1., -1., 0., 0., 0., 2.]])
+ bl = np.array([-inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf, -inf])
+ bu = np.array([100., 0., 0., 0., 0., 0., 0., 0., 0.])
+ constraints = LinearConstraint(A, bl, bu)
+ integrality = 1
+ bounds = (0, 1)
+ r1 = milp(c=c, constraints=constraints, integrality=integrality, bounds=bounds,
+ options={'presolve': True})
+ r2 = milp(c=c, constraints=constraints, integrality=integrality, bounds=bounds,
+ options={'presolve': False})
+ assert r1.status == r2.status
+ assert_allclose(r1.fun, r2.fun)
+
+ # another example from the same issue
+ bounds = Bounds(lb=0, ub=1)
+ integrality = [1, 1, 0, 0]
+ c = [10, 9.52380952, -1000, -952.38095238]
+ A = [[1, 1, 0, 0], [0, 0, 1, 1], [200, 0, 0, 0], [0, 200, 0, 0],
+ [0, 0, 2000, 0], [0, 0, 0, 2000], [-1, 0, 1, 0], [-1, -1, 0, 1]]
+ ub = [1, 1, 200, 200, 1000, 1000, 0, 0]
+ constraints = LinearConstraint(A, ub=ub)
+ r1 = milp(c=c, constraints=constraints, bounds=bounds,
+ integrality=integrality, options={"presolve": False})
+ r2 = milp(c=c, constraints=constraints, bounds=bounds,
+ integrality=integrality, options={"presolve": False})
+ assert r1.status == r2.status
+ assert_allclose(r1.x, r2.x)
+
+def test_regression_gh24141():
+ c = np.ones(8, dtype=np.int64)
+ integrality = c.copy()
+
+ b = np.asarray([42, 252, 277, 41, 222, 48], dtype=np.int64)
+ a = np.asarray([
+ [0, 1, 1, 0, 1, 0, 0, 0],
+ [0, 0, 1, 1, 1, 0, 1, 1],
+ [1, 1, 1, 1, 1, 1, 0, 1],
+ [0, 1, 0, 1, 1, 1, 0, 0],
+ [0, 1, 0, 0, 1, 1, 0, 1],
+ [0, 1, 1, 1, 0, 1, 1, 0],
+ ], dtype=np.int64)
+
+ res = milp(c, integrality=integrality, constraints=(a, b, b))
+
+ assert res.success
+ assert_allclose(a @ res.x, b)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_minimize_constrained.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_minimize_constrained.py
new file mode 100644
index 0000000000000000000000000000000000000000..d798e975b00a421a27aafa24cf563056688c9046
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_minimize_constrained.py
@@ -0,0 +1,850 @@
+import warnings
+
+import numpy as np
+import pytest
+from scipy.linalg import block_diag
+from scipy.sparse import csc_array
+from numpy.testing import (assert_array_almost_equal,
+ assert_array_less, assert_)
+from scipy.optimize import (NonlinearConstraint,
+ LinearConstraint,
+ Bounds,
+ minimize,
+ BFGS,
+ SR1,
+ rosen)
+
+
+class Maratos:
+ """Problem 15.4 from Nocedal and Wright
+
+ The following optimization problem:
+ minimize 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+ Subject to: x[0]**2 + x[1]**2 - 1 = 0
+ """
+
+ def __init__(self, degrees=60, constr_jac=None, constr_hess=None):
+ rads = degrees/180*np.pi
+ self.x0 = [np.cos(rads), np.sin(rads)]
+ self.x_opt = np.array([1.0, 0.0])
+ self.constr_jac = constr_jac
+ self.constr_hess = constr_hess
+ self.bounds = None
+
+ def fun(self, x):
+ return 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+
+ def grad(self, x):
+ return np.array([4*x[0]-1, 4*x[1]])
+
+ def hess(self, x):
+ return 4*np.eye(2)
+
+ @property
+ def constr(self):
+ def fun(x):
+ return x[0]**2 + x[1]**2
+
+ if self.constr_jac is None:
+ def jac(x):
+ return [[2*x[0], 2*x[1]]]
+ else:
+ jac = self.constr_jac
+
+ if self.constr_hess is None:
+ def hess(x, v):
+ return 2*v[0]*np.eye(2)
+ else:
+ hess = self.constr_hess
+
+ return NonlinearConstraint(fun, 1, 1, jac, hess)
+
+
+class MaratosTestArgs:
+ """Problem 15.4 from Nocedal and Wright
+
+ The following optimization problem:
+ minimize 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+ Subject to: x[0]**2 + x[1]**2 - 1 = 0
+ """
+
+ def __init__(self, a, b, degrees=60, constr_jac=None, constr_hess=None):
+ rads = degrees/180*np.pi
+ self.x0 = [np.cos(rads), np.sin(rads)]
+ self.x_opt = np.array([1.0, 0.0])
+ self.constr_jac = constr_jac
+ self.constr_hess = constr_hess
+ self.a = a
+ self.b = b
+ self.bounds = None
+
+ def _test_args(self, a, b):
+ if self.a != a or self.b != b:
+ raise ValueError()
+
+ def fun(self, x, a, b):
+ self._test_args(a, b)
+ return 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+
+ def grad(self, x, a, b):
+ self._test_args(a, b)
+ return np.array([4*x[0]-1, 4*x[1]])
+
+ def hess(self, x, a, b):
+ self._test_args(a, b)
+ return 4*np.eye(2)
+
+ @property
+ def constr(self):
+ def fun(x):
+ return x[0]**2 + x[1]**2
+
+ if self.constr_jac is None:
+ def jac(x):
+ return [[4*x[0], 4*x[1]]]
+ else:
+ jac = self.constr_jac
+
+ if self.constr_hess is None:
+ def hess(x, v):
+ return 2*v[0]*np.eye(2)
+ else:
+ hess = self.constr_hess
+
+ return NonlinearConstraint(fun, 1, 1, jac, hess)
+
+
+class MaratosGradInFunc:
+ """Problem 15.4 from Nocedal and Wright
+
+ The following optimization problem:
+ minimize 2*(x[0]**2 + x[1]**2 - 1) - x[0]
+ Subject to: x[0]**2 + x[1]**2 - 1 = 0
+ """
+
+ def __init__(self, degrees=60, constr_jac=None, constr_hess=None):
+ rads = degrees/180*np.pi
+ self.x0 = [np.cos(rads), np.sin(rads)]
+ self.x_opt = np.array([1.0, 0.0])
+ self.constr_jac = constr_jac
+ self.constr_hess = constr_hess
+ self.bounds = None
+
+ def fun(self, x):
+ return (2*(x[0]**2 + x[1]**2 - 1) - x[0],
+ np.array([4*x[0]-1, 4*x[1]]))
+
+ @property
+ def grad(self):
+ return True
+
+ def hess(self, x):
+ return 4*np.eye(2)
+
+ @property
+ def constr(self):
+ def fun(x):
+ return x[0]**2 + x[1]**2
+
+ if self.constr_jac is None:
+ def jac(x):
+ return [[4*x[0], 4*x[1]]]
+ else:
+ jac = self.constr_jac
+
+ if self.constr_hess is None:
+ def hess(x, v):
+ return 2*v[0]*np.eye(2)
+ else:
+ hess = self.constr_hess
+
+ return NonlinearConstraint(fun, 1, 1, jac, hess)
+
+
+class HyperbolicIneq:
+ """Problem 15.1 from Nocedal and Wright
+
+ The following optimization problem:
+ minimize 1/2*(x[0] - 2)**2 + 1/2*(x[1] - 1/2)**2
+ Subject to: 1/(x[0] + 1) - x[1] >= 1/4
+ x[0] >= 0
+ x[1] >= 0
+ """
+ def __init__(self, constr_jac=None, constr_hess=None):
+ self.x0 = [0, 0]
+ self.x_opt = [1.952823, 0.088659]
+ self.constr_jac = constr_jac
+ self.constr_hess = constr_hess
+ self.bounds = Bounds(0, np.inf)
+
+ def fun(self, x):
+ return 1/2*(x[0] - 2)**2 + 1/2*(x[1] - 1/2)**2
+
+ def grad(self, x):
+ return [x[0] - 2, x[1] - 1/2]
+
+ def hess(self, x):
+ return np.eye(2)
+
+ @property
+ def constr(self):
+ def fun(x):
+ return 1/(x[0] + 1) - x[1]
+
+ if self.constr_jac is None:
+ def jac(x):
+ return [[-1/(x[0] + 1)**2, -1]]
+ else:
+ jac = self.constr_jac
+
+ if self.constr_hess is None:
+ def hess(x, v):
+ return 2*v[0]*np.array([[1/(x[0] + 1)**3, 0],
+ [0, 0]])
+ else:
+ hess = self.constr_hess
+
+ return NonlinearConstraint(fun, 0.25, np.inf, jac, hess)
+
+
+class Rosenbrock:
+ """Rosenbrock function.
+
+ The following optimization problem:
+ minimize sum(100.0*(x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0)
+ """
+
+ def __init__(self, n=2, random_state=0):
+ rng = np.random.RandomState(random_state)
+ self.x0 = rng.uniform(-1, 1, n)
+ self.x_opt = np.ones(n)
+ self.bounds = None
+
+ def fun(self, x):
+ x = np.asarray(x)
+ r = np.sum(100.0 * (x[1:] - x[:-1]**2.0)**2.0 + (1 - x[:-1])**2.0,
+ axis=0)
+ return r
+
+ def grad(self, x):
+ x = np.asarray(x)
+ xm = x[1:-1]
+ xm_m1 = x[:-2]
+ xm_p1 = x[2:]
+ der = np.zeros_like(x)
+ der[1:-1] = (200 * (xm - xm_m1**2) -
+ 400 * (xm_p1 - xm**2) * xm - 2 * (1 - xm))
+ der[0] = -400 * x[0] * (x[1] - x[0]**2) - 2 * (1 - x[0])
+ der[-1] = 200 * (x[-1] - x[-2]**2)
+ return der
+
+ def hess(self, x):
+ x = np.atleast_1d(x)
+ H = np.diag(-400 * x[:-1], 1) - np.diag(400 * x[:-1], -1)
+ diagonal = np.zeros(len(x), dtype=x.dtype)
+ diagonal[0] = 1200 * x[0]**2 - 400 * x[1] + 2
+ diagonal[-1] = 200
+ diagonal[1:-1] = 202 + 1200 * x[1:-1]**2 - 400 * x[2:]
+ H = H + np.diag(diagonal)
+ return H
+
+ @property
+ def constr(self):
+ return ()
+
+
+class IneqRosenbrock(Rosenbrock):
+ """Rosenbrock subject to inequality constraints.
+
+ The following optimization problem:
+ minimize sum(100.0*(x[1] - x[0]**2)**2.0 + (1 - x[0])**2)
+ subject to: x[0] + 2 x[1] <= 1
+
+ Taken from matlab ``fmincon`` documentation.
+ """
+ def __init__(self, random_state=0):
+ Rosenbrock.__init__(self, 2, random_state)
+ self.x0 = [-1, -0.5]
+ self.x_opt = [0.5022, 0.2489]
+ self.bounds = None
+
+ @property
+ def constr(self):
+ A = [[1, 2]]
+ b = 1
+ return LinearConstraint(A, -np.inf, b)
+
+
+class BoundedRosenbrock(Rosenbrock):
+ """Rosenbrock subject to inequality constraints.
+
+ The following optimization problem:
+ minimize sum(100.0*(x[1] - x[0]**2)**2.0 + (1 - x[0])**2)
+ subject to: -2 <= x[0] <= 0
+ 0 <= x[1] <= 2
+
+ Taken from matlab ``fmincon`` documentation.
+ """
+ def __init__(self, random_state=0):
+ Rosenbrock.__init__(self, 2, random_state)
+ self.x0 = [-0.2, 0.2]
+ self.x_opt = None
+ self.bounds = Bounds([-2, 0], [0, 2])
+
+
+class EqIneqRosenbrock(Rosenbrock):
+ """Rosenbrock subject to equality and inequality constraints.
+
+ The following optimization problem:
+ minimize sum(100.0*(x[1] - x[0]**2)**2.0 + (1 - x[0])**2)
+ subject to: x[0] + 2 x[1] <= 1
+ 2 x[0] + x[1] = 1
+
+ Taken from matlab ``fimincon`` documentation.
+ """
+ def __init__(self, random_state=0):
+ Rosenbrock.__init__(self, 2, random_state)
+ self.x0 = [-1, -0.5]
+ self.x_opt = [0.41494, 0.17011]
+ self.bounds = None
+
+ @property
+ def constr(self):
+ A_ineq = [[1, 2]]
+ b_ineq = 1
+ A_eq = [[2, 1]]
+ b_eq = 1
+ return (LinearConstraint(A_ineq, -np.inf, b_ineq),
+ LinearConstraint(A_eq, b_eq, b_eq))
+
+
+class Elec:
+ """Distribution of electrons on a sphere.
+
+ Problem no 2 from COPS collection [2]_. Find
+ the equilibrium state distribution (of minimal
+ potential) of the electrons positioned on a
+ conducting sphere.
+
+ References
+ ----------
+ .. [1] E. D. Dolan, J. J. Mor\'{e}, and T. S. Munson,
+ "Benchmarking optimization software with COPS 3.0.",
+ Argonne National Lab., Argonne, IL (US), 2004.
+ """
+ def __init__(self, n_electrons=200, random_state=0,
+ constr_jac=None, constr_hess=None):
+ self.n_electrons = n_electrons
+ self.rng = np.random.RandomState(random_state)
+ # Initial Guess
+ phi = self.rng.uniform(0, 2 * np.pi, self.n_electrons)
+ theta = self.rng.uniform(-np.pi, np.pi, self.n_electrons)
+ x = np.cos(theta) * np.cos(phi)
+ y = np.cos(theta) * np.sin(phi)
+ z = np.sin(theta)
+ self.x0 = np.hstack((x, y, z))
+ self.x_opt = None
+ self.constr_jac = constr_jac
+ self.constr_hess = constr_hess
+ self.bounds = None
+
+ def _get_cordinates(self, x):
+ x_coord = x[:self.n_electrons]
+ y_coord = x[self.n_electrons:2 * self.n_electrons]
+ z_coord = x[2 * self.n_electrons:]
+ return x_coord, y_coord, z_coord
+
+ def _compute_coordinate_deltas(self, x):
+ x_coord, y_coord, z_coord = self._get_cordinates(x)
+ dx = x_coord[:, None] - x_coord
+ dy = y_coord[:, None] - y_coord
+ dz = z_coord[:, None] - z_coord
+ return dx, dy, dz
+
+ def fun(self, x):
+ dx, dy, dz = self._compute_coordinate_deltas(x)
+ with np.errstate(divide='ignore'):
+ dm1 = (dx**2 + dy**2 + dz**2) ** -0.5
+ dm1[np.diag_indices_from(dm1)] = 0
+ return 0.5 * np.sum(dm1)
+
+ def grad(self, x):
+ dx, dy, dz = self._compute_coordinate_deltas(x)
+
+ with np.errstate(divide='ignore'):
+ dm3 = (dx**2 + dy**2 + dz**2) ** -1.5
+ dm3[np.diag_indices_from(dm3)] = 0
+
+ grad_x = -np.sum(dx * dm3, axis=1)
+ grad_y = -np.sum(dy * dm3, axis=1)
+ grad_z = -np.sum(dz * dm3, axis=1)
+
+ return np.hstack((grad_x, grad_y, grad_z))
+
+ def hess(self, x):
+ dx, dy, dz = self._compute_coordinate_deltas(x)
+ d = (dx**2 + dy**2 + dz**2) ** 0.5
+
+ with np.errstate(divide='ignore'):
+ dm3 = d ** -3
+ dm5 = d ** -5
+
+ i = np.arange(self.n_electrons)
+ dm3[i, i] = 0
+ dm5[i, i] = 0
+
+ Hxx = dm3 - 3 * dx**2 * dm5
+ Hxx[i, i] = -np.sum(Hxx, axis=1)
+
+ Hxy = -3 * dx * dy * dm5
+ Hxy[i, i] = -np.sum(Hxy, axis=1)
+
+ Hxz = -3 * dx * dz * dm5
+ Hxz[i, i] = -np.sum(Hxz, axis=1)
+
+ Hyy = dm3 - 3 * dy**2 * dm5
+ Hyy[i, i] = -np.sum(Hyy, axis=1)
+
+ Hyz = -3 * dy * dz * dm5
+ Hyz[i, i] = -np.sum(Hyz, axis=1)
+
+ Hzz = dm3 - 3 * dz**2 * dm5
+ Hzz[i, i] = -np.sum(Hzz, axis=1)
+
+ H = np.vstack((
+ np.hstack((Hxx, Hxy, Hxz)),
+ np.hstack((Hxy, Hyy, Hyz)),
+ np.hstack((Hxz, Hyz, Hzz))
+ ))
+
+ return H
+
+ @property
+ def constr(self):
+ def fun(x):
+ x_coord, y_coord, z_coord = self._get_cordinates(x)
+ return x_coord**2 + y_coord**2 + z_coord**2 - 1
+
+ if self.constr_jac is None:
+ def jac(x):
+ x_coord, y_coord, z_coord = self._get_cordinates(x)
+ Jx = 2 * np.diag(x_coord)
+ Jy = 2 * np.diag(y_coord)
+ Jz = 2 * np.diag(z_coord)
+ return csc_array(np.hstack((Jx, Jy, Jz)))
+ else:
+ jac = self.constr_jac
+
+ if self.constr_hess is None:
+ def hess(x, v):
+ D = 2 * np.diag(v)
+ return block_diag(D, D, D)
+ else:
+ hess = self.constr_hess
+
+ return NonlinearConstraint(fun, -np.inf, 0, jac, hess)
+
+
+class TestTrustRegionConstr:
+ list_of_problems = [Maratos(),
+ Maratos(constr_hess='2-point'),
+ Maratos(constr_hess=SR1()),
+ Maratos(constr_jac='2-point', constr_hess=SR1()),
+ MaratosGradInFunc(),
+ HyperbolicIneq(),
+ HyperbolicIneq(constr_hess='3-point'),
+ HyperbolicIneq(constr_hess=BFGS()),
+ HyperbolicIneq(constr_jac='3-point',
+ constr_hess=BFGS()),
+ Rosenbrock(),
+ IneqRosenbrock(),
+ EqIneqRosenbrock(),
+ BoundedRosenbrock(),
+ Elec(n_electrons=2),
+ Elec(n_electrons=2, constr_hess='2-point'),
+ Elec(n_electrons=2, constr_hess=SR1()),
+ Elec(n_electrons=2, constr_jac='3-point',
+ constr_hess=SR1())]
+
+ @pytest.mark.parametrize('prob', list_of_problems)
+ @pytest.mark.parametrize('grad', ('prob.grad', '3-point', False))
+ @pytest.mark.parametrize('hess', ("prob.hess", '3-point', lambda: SR1(),
+ lambda: BFGS(exception_strategy='damp_update'),
+ lambda: BFGS(exception_strategy='skip_update')))
+ def test_list_of_problems(self, prob, grad, hess):
+ grad = prob.grad if grad == "prob.grad" else grad
+ hess = hess() if callable(hess) else hess
+ hess = prob.hess if hess == "prob.hess" else hess
+ # Remove exceptions
+ if (grad in {'2-point', '3-point', 'cs', False} and
+ hess in {'2-point', '3-point', 'cs'}):
+ pytest.skip("Numerical Hessian needs analytical gradient")
+ if prob.grad is True and grad in {'3-point', False}:
+ pytest.skip("prob.grad incompatible with grad in {'3-point', False}")
+ sensitive = (isinstance(prob, BoundedRosenbrock) and grad == '3-point'
+ and isinstance(hess, BFGS))
+ if sensitive:
+ pytest.xfail("Seems sensitive to initial conditions w/ Accelerate")
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ result = minimize(prob.fun, prob.x0,
+ method='trust-constr',
+ jac=grad, hess=hess,
+ bounds=prob.bounds,
+ constraints=prob.constr)
+
+ if prob.x_opt is not None:
+ assert_array_almost_equal(result.x, prob.x_opt,
+ decimal=5)
+ # gtol
+ if result.status == 1:
+ assert_array_less(result.optimality, 1e-8)
+ # xtol
+ if result.status == 2:
+ assert_array_less(result.tr_radius, 1e-8)
+
+ if result.method == "tr_interior_point":
+ assert_array_less(result.barrier_parameter, 1e-8)
+
+ # check for max iter
+ message = f"Invalid termination condition: {result.status}."
+ assert result.status not in {0, 3}, message
+
+
+ def test_default_jac_and_hess(self):
+ def fun(x):
+ return (x - 1) ** 2
+ bounds = [(-2, 2)]
+ res = minimize(fun, x0=[-1.5], bounds=bounds, method='trust-constr')
+ assert_array_almost_equal(res.x, 1, decimal=5)
+
+ def test_default_hess(self):
+ def fun(x):
+ return (x - 1) ** 2
+ bounds = [(-2, 2)]
+ res = minimize(fun, x0=[-1.5], bounds=bounds, method='trust-constr',
+ jac='2-point')
+ assert_array_almost_equal(res.x, 1, decimal=5)
+
+ def test_no_constraints(self):
+ prob = Rosenbrock()
+ result = minimize(prob.fun, prob.x0,
+ method='trust-constr',
+ jac=prob.grad, hess=prob.hess)
+ result1 = minimize(prob.fun, prob.x0,
+ method='L-BFGS-B',
+ jac='2-point')
+
+ result2 = minimize(prob.fun, prob.x0,
+ method='L-BFGS-B',
+ jac='3-point')
+ assert_array_almost_equal(result.x, prob.x_opt, decimal=5)
+ assert_array_almost_equal(result1.x, prob.x_opt, decimal=5)
+ assert_array_almost_equal(result2.x, prob.x_opt, decimal=5)
+
+ def test_hessp(self):
+ prob = Maratos()
+
+ def hessp(x, p):
+ H = prob.hess(x)
+ return H.dot(p)
+
+ result = minimize(prob.fun, prob.x0,
+ method='trust-constr',
+ jac=prob.grad, hessp=hessp,
+ bounds=prob.bounds,
+ constraints=prob.constr)
+
+ if prob.x_opt is not None:
+ assert_array_almost_equal(result.x, prob.x_opt, decimal=2)
+
+ # gtol
+ if result.status == 1:
+ assert_array_less(result.optimality, 1e-8)
+ # xtol
+ if result.status == 2:
+ assert_array_less(result.tr_radius, 1e-8)
+
+ if result.method == "tr_interior_point":
+ assert_array_less(result.barrier_parameter, 1e-8)
+ # max iter
+ if result.status in (0, 3):
+ raise RuntimeError("Invalid termination condition.")
+
+ def test_args(self):
+ prob = MaratosTestArgs("a", 234)
+
+ result = minimize(prob.fun, prob.x0, ("a", 234),
+ method='trust-constr',
+ jac=prob.grad, hess=prob.hess,
+ bounds=prob.bounds,
+ constraints=prob.constr)
+
+ if prob.x_opt is not None:
+ assert_array_almost_equal(result.x, prob.x_opt, decimal=2)
+
+ # gtol
+ if result.status == 1:
+ assert_array_less(result.optimality, 1e-8)
+ # xtol
+ if result.status == 2:
+ assert_array_less(result.tr_radius, 1e-8)
+ if result.method == "tr_interior_point":
+ assert_array_less(result.barrier_parameter, 1e-8)
+ # max iter
+ if result.status in (0, 3):
+ raise RuntimeError("Invalid termination condition.")
+
+ def test_raise_exception(self):
+ prob = Maratos()
+ message = "Whenever the gradient is estimated via finite-differences"
+ with pytest.raises(ValueError, match=message):
+ minimize(prob.fun, prob.x0, method='trust-constr', jac='2-point',
+ hess='2-point', constraints=prob.constr)
+
+ def test_issue_9044(self):
+ # https://github.com/scipy/scipy/issues/9044
+ # Test the returned `OptimizeResult` contains keys consistent with
+ # other solvers.
+
+ def callback(x, info):
+ assert_('nit' in info)
+ assert_('niter' in info)
+
+ result = minimize(lambda x: x**2, [0], jac=lambda x: 2*x,
+ hess=lambda x: 2, callback=callback,
+ method='trust-constr')
+ assert_(result.get('success'))
+ assert_(result.get('nit', -1) == 1)
+
+ # Also check existence of the 'niter' attribute, for backward
+ # compatibility
+ assert_(result.get('niter', -1) == 1)
+
+ def test_issue_15093(self):
+ # scipy docs define bounds as inclusive, so it shouldn't be
+ # an issue to set x0 on the bounds even if keep_feasible is
+ # True. Previously, trust-constr would treat bounds as
+ # exclusive.
+
+ x0 = np.array([0., 0.5])
+
+ def obj(x):
+ x1 = x[0]
+ x2 = x[1]
+ return x1 ** 2 + x2 ** 2
+
+ bounds = Bounds(np.array([0., 0.]), np.array([1., 1.]),
+ keep_feasible=True)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ result = minimize(
+ method='trust-constr',
+ fun=obj,
+ x0=x0,
+ bounds=bounds)
+
+ assert result['success']
+
+class TestEmptyConstraint:
+ """
+ Here we minimize x^2+y^2 subject to x^2-y^2>1.
+ The actual minimum is at (0, 0) which fails the constraint.
+ Therefore we will find a minimum on the boundary at (+/-1, 0).
+
+ When minimizing on the boundary, optimize uses a set of
+ constraints that removes the constraint that sets that
+ boundary. In our case, there's only one constraint, so
+ the result is an empty constraint.
+
+ This tests that the empty constraint works.
+ """
+ def test_empty_constraint(self):
+
+ def function(x):
+ return x[0]**2 + x[1]**2
+
+ def functionjacobian(x):
+ return np.array([2.*x[0], 2.*x[1]])
+
+ def functionhvp(x, v):
+ return 2.*v
+
+ def constraint(x):
+ return np.array([x[0]**2 - x[1]**2])
+
+ def constraintjacobian(x):
+ return np.array([[2*x[0], -2*x[1]]])
+
+ def constraintlcoh(x, v):
+ return np.array([[2., 0.], [0., -2.]]) * v[0]
+
+ constraint = NonlinearConstraint(constraint, 1., np.inf,
+ constraintjacobian, constraintlcoh)
+
+ startpoint = [1., 2.]
+
+ bounds = Bounds([-np.inf, -np.inf], [np.inf, np.inf])
+
+ result = minimize(
+ function,
+ startpoint,
+ method='trust-constr',
+ jac=functionjacobian,
+ hessp=functionhvp,
+ constraints=[constraint],
+ bounds=bounds,
+ )
+
+ assert_array_almost_equal(abs(result.x), np.array([1, 0]), decimal=4)
+
+
+def test_bug_11886():
+ def opt(x):
+ return x[0]**2+x[1]**2
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", PendingDeprecationWarning)
+ A = np.matrix(np.diag([1, 1]))
+ lin_cons = LinearConstraint(A, -1, np.inf)
+ # just checking that there are no errors
+ minimize(opt, 2*[1], constraints = lin_cons)
+
+
+def test_gh11649():
+ # trust - constr error when attempting to keep bound constrained solutions
+ # feasible. Algorithm attempts to go outside bounds when evaluating finite
+ # differences. (don't give objective an analytic gradient)
+ bnds = Bounds(lb=[-1, -1], ub=[1, 1], keep_feasible=True)
+
+ def assert_inbounds(x):
+ assert np.all(x >= bnds.lb)
+ assert np.all(x <= bnds.ub)
+
+ def obj(x):
+ assert_inbounds(x)
+ return np.exp(x[0])*(4*x[0]**2 + 2*x[1]**2 + 4*x[0]*x[1] + 2*x[1] + 1)
+
+ def nce(x):
+ assert_inbounds(x)
+ return x[0]**2 + x[1]
+
+ def nce_jac(x):
+ return np.array([2*x[0], 1])
+
+ def nci(x):
+ assert_inbounds(x)
+ return x[0]*x[1]
+
+ x0 = np.array((0.99, -0.99))
+ nlcs = [NonlinearConstraint(nci, -10, np.inf),
+ NonlinearConstraint(nce, 1, 1, jac=nce_jac)]
+
+ res = minimize(fun=obj, x0=x0, method='trust-constr',
+ bounds=bnds, constraints=nlcs)
+ assert_inbounds(res.x)
+ assert nlcs[0].lb < nlcs[0].fun(res.x) < nlcs[0].ub
+
+
+def test_gh20665_too_many_constraints():
+ # gh-20665 reports a confusing error message when there are more equality
+ # constraints than variables. Check that the error message is improved.
+ message = "...more equality constraints than independent variables..."
+ with pytest.raises(ValueError, match=message):
+ x0 = np.ones((2,))
+ A_eq, b_eq = np.arange(6).reshape((3, 2)), np.ones((3,))
+ g = NonlinearConstraint(lambda x: A_eq @ x, lb=b_eq, ub=b_eq)
+ minimize(rosen, x0, method='trust-constr', constraints=[g])
+ # no error with `SVDFactorization`
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", UserWarning)
+ minimize(rosen, x0, method='trust-constr', constraints=[g],
+ options={'factorization_method': 'SVDFactorization'})
+
+def test_issue_18882():
+ def lsf(u):
+ u1, u2 = u
+ a, b = [3.0, 4.0]
+ return 1.0 + u1**2 / a**2 - u2**2 / b**2
+
+ def of(u):
+ return np.sum(u**2)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.0", UserWarning)
+ warnings.filterwarnings("ignore", "Singular Jacobian matrix.", UserWarning)
+ res = minimize(
+ of,
+ [0.0, 0.0],
+ method="trust-constr",
+ constraints=NonlinearConstraint(lsf, 0, 0),
+ )
+ assert (not res.success) and (res.constr_violation > 1e-8)
+
+class TestBoundedNelderMead:
+
+ @pytest.mark.parametrize('bounds, x_opt',
+ [(Bounds(-np.inf, np.inf), Rosenbrock().x_opt),
+ (Bounds(-np.inf, -0.8), [-0.8, -0.8]),
+ (Bounds(3.0, np.inf), [3.0, 9.0]),
+ (Bounds([3.0, 1.0], [4.0, 5.0]), [3., 5.]),
+ ])
+ def test_rosen_brock_with_bounds(self, bounds, x_opt):
+ prob = Rosenbrock()
+ with warnings.catch_warnings():
+ msg = "Initial guess is not within the specified bounds"
+ warnings.filterwarnings("ignore", msg, UserWarning)
+ result = minimize(prob.fun, [-10, -10],
+ method='Nelder-Mead',
+ bounds=bounds)
+ assert np.less_equal(bounds.lb, result.x).all()
+ assert np.less_equal(result.x, bounds.ub).all()
+ assert np.allclose(prob.fun(result.x), result.fun)
+ assert np.allclose(result.x, x_opt, atol=1.e-3)
+
+ def test_equal_all_bounds(self):
+ prob = Rosenbrock()
+ bounds = Bounds([4.0, 5.0], [4.0, 5.0])
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "Initial guess is not within the specified bounds",
+ UserWarning)
+ result = minimize(prob.fun, [-10, 8],
+ method='Nelder-Mead',
+ bounds=bounds)
+ assert np.allclose(result.x, [4.0, 5.0])
+
+ def test_equal_one_bounds(self):
+ prob = Rosenbrock()
+ bounds = Bounds([4.0, 5.0], [4.0, 20.0])
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "Initial guess is not within the specified bounds",
+ UserWarning)
+ result = minimize(prob.fun, [-10, 8],
+ method='Nelder-Mead',
+ bounds=bounds)
+ assert np.allclose(result.x, [4.0, 16.0])
+
+ def test_invalid_bounds(self):
+ prob = Rosenbrock()
+ message = 'An upper bound is less than the corresponding lower bound.'
+ with pytest.raises(ValueError, match=message):
+ bounds = Bounds([-np.inf, 1.0], [4.0, -5.0])
+ minimize(prob.fun, [-10, 3],
+ method='Nelder-Mead',
+ bounds=bounds)
+
+ @pytest.mark.xfail(reason="Failing on Azure Linux and macOS builds, "
+ "see gh-13846")
+ def test_outside_bounds_warning(self):
+ prob = Rosenbrock()
+ message = "Initial guess is not within the specified bounds"
+ with pytest.warns(UserWarning, match=message):
+ bounds = Bounds([-np.inf, 1.0], [4.0, 5.0])
+ minimize(prob.fun, [-10, 8],
+ method='Nelder-Mead',
+ bounds=bounds)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_minpack.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_minpack.py
new file mode 100644
index 0000000000000000000000000000000000000000..53a92c705b723188e27df7ddbeb40e33d044524d
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_minpack.py
@@ -0,0 +1,1195 @@
+"""
+Unit tests for optimization routines from minpack.py.
+"""
+import warnings
+import pytest
+import threading
+
+from numpy.testing import (assert_, assert_almost_equal, assert_array_equal,
+ assert_array_almost_equal, assert_allclose)
+from pytest import raises as assert_raises
+import numpy as np
+from numpy import array, float64
+from multiprocessing.pool import ThreadPool
+
+from scipy import optimize, linalg
+from scipy.special import lambertw
+from scipy.optimize._minpack_py import leastsq, curve_fit, fixed_point
+from scipy.optimize import OptimizeWarning
+from scipy.optimize._minimize import Bounds
+
+
+class ReturnShape:
+ """This class exists to create a callable that does not have a '__name__' attribute.
+
+ __init__ takes the argument 'shape', which should be a tuple of ints.
+ When an instance is called with a single argument 'x', it returns numpy.ones(shape).
+ """
+
+ def __init__(self, shape):
+ self.shape = shape
+
+ def __call__(self, x):
+ return np.ones(self.shape)
+
+
+def dummy_func(x, shape):
+ """A function that returns an array of ones of the given shape.
+ `x` is ignored.
+ """
+ return np.ones(shape)
+
+
+def sequence_parallel(fs):
+ with ThreadPool(len(fs)) as pool:
+ return pool.map(lambda f: f(), fs)
+
+
+# Function and Jacobian for tests of solvers for systems of nonlinear
+# equations
+
+
+def pressure_network(flow_rates, Qtot, k):
+ """Evaluate non-linear equation system representing
+ the pressures and flows in a system of n parallel pipes::
+
+ f_i = P_i - P_0, for i = 1..n
+ f_0 = sum(Q_i) - Qtot
+
+ where Q_i is the flow rate in pipe i and P_i the pressure in that pipe.
+ Pressure is modeled as a P=kQ**2 where k is a valve coefficient and
+ Q is the flow rate.
+
+ Parameters
+ ----------
+ flow_rates : float
+ A 1-D array of n flow rates [kg/s].
+ k : float
+ A 1-D array of n valve coefficients [1/kg m].
+ Qtot : float
+ A scalar, the total input flow rate [kg/s].
+
+ Returns
+ -------
+ F : float
+ A 1-D array, F[i] == f_i.
+
+ """
+ P = k * flow_rates**2
+ F = np.hstack((P[1:] - P[0], flow_rates.sum() - Qtot))
+ return F
+
+
+def pressure_network_jacobian(flow_rates, Qtot, k):
+ """Return the jacobian of the equation system F(flow_rates)
+ computed by `pressure_network` with respect to
+ *flow_rates*. See `pressure_network` for the detailed
+ description of parameters.
+
+ Returns
+ -------
+ jac : float
+ *n* by *n* matrix ``df_i/dQ_i`` where ``n = len(flow_rates)``
+ and *f_i* and *Q_i* are described in the doc for `pressure_network`
+ """
+ n = len(flow_rates)
+ pdiff = np.diag(flow_rates[1:] * 2 * k[1:] - 2 * flow_rates[0] * k[0])
+
+ jac = np.empty((n, n))
+ jac[:n-1, :n-1] = pdiff * 0
+ jac[:n-1, n-1] = 0
+ jac[n-1, :] = np.ones(n)
+
+ return jac
+
+
+def pressure_network_fun_and_grad(flow_rates, Qtot, k):
+ return (pressure_network(flow_rates, Qtot, k),
+ pressure_network_jacobian(flow_rates, Qtot, k))
+
+
+class TestFSolve:
+ def test_pressure_network_no_gradient(self):
+ # fsolve without gradient, equal pipes -> equal flows.
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows, info, ier, mesg = optimize.fsolve(
+ pressure_network, initial_guess, args=(Qtot, k),
+ full_output=True)
+ assert_array_almost_equal(final_flows, np.ones(4))
+ assert_(ier == 1, mesg)
+
+ def test_pressure_network_with_gradient(self):
+ # fsolve with gradient, equal pipes -> equal flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows = optimize.fsolve(
+ pressure_network, initial_guess, args=(Qtot, k),
+ fprime=pressure_network_jacobian)
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+ def test_wrong_shape_func_callable(self):
+ func = ReturnShape(1)
+ # x0 is a list of two elements, but func will return an array with
+ # length 1, so this should result in a TypeError.
+ x0 = [1.5, 2.0]
+ assert_raises(TypeError, optimize.fsolve, func, x0)
+
+ def test_wrong_shape_func_function(self):
+ # x0 is a list of two elements, but func will return an array with
+ # length 1, so this should result in a TypeError.
+ x0 = [1.5, 2.0]
+ assert_raises(TypeError, optimize.fsolve, dummy_func, x0, args=((1,),))
+
+ def test_wrong_shape_fprime_callable(self):
+ func = ReturnShape(1)
+ deriv_func = ReturnShape((2,2))
+ assert_raises(TypeError, optimize.fsolve, func, x0=[0,1], fprime=deriv_func)
+
+ def test_wrong_shape_fprime_function(self):
+ def func(x):
+ return dummy_func(x, (2,))
+ def deriv_func(x):
+ return dummy_func(x, (3, 3))
+ assert_raises(TypeError, optimize.fsolve, func, x0=[0,1], fprime=deriv_func)
+
+ def test_func_can_raise(self):
+ def func(*args):
+ raise ValueError('I raised')
+
+ with assert_raises(ValueError, match='I raised'):
+ optimize.fsolve(func, x0=[0])
+
+ def test_Dfun_can_raise(self):
+ def func(x):
+ return x - np.array([10])
+
+ def deriv_func(*args):
+ raise ValueError('I raised')
+
+ with assert_raises(ValueError, match='I raised'):
+ optimize.fsolve(func, x0=[0], fprime=deriv_func)
+
+ def test_float32(self):
+ def func(x):
+ return np.array([x[0] - 100, x[1] - 1000], dtype=np.float32) ** 2
+ p = optimize.fsolve(func, np.array([1, 1], np.float32))
+ assert_allclose(func(p), [0, 0], atol=1e-3)
+
+ def test_reentrant_func(self):
+ def func(*args):
+ self.test_pressure_network_no_gradient()
+ return pressure_network(*args)
+
+ # fsolve without gradient, equal pipes -> equal flows.
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows, info, ier, mesg = optimize.fsolve(
+ func, initial_guess, args=(Qtot, k),
+ full_output=True)
+ assert_array_almost_equal(final_flows, np.ones(4))
+ assert_(ier == 1, mesg)
+
+ def test_reentrant_Dfunc(self):
+ def deriv_func(*args):
+ self.test_pressure_network_with_gradient()
+ return pressure_network_jacobian(*args)
+
+ # fsolve with gradient, equal pipes -> equal flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows = optimize.fsolve(
+ pressure_network, initial_guess, args=(Qtot, k),
+ fprime=deriv_func)
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+ def test_concurrent_no_gradient(self):
+ v = sequence_parallel([self.test_pressure_network_no_gradient] * 10)
+ assert all([result is None for result in v])
+
+ def test_concurrent_with_gradient(self):
+ v = sequence_parallel([self.test_pressure_network_with_gradient] * 10)
+ assert all([result is None for result in v])
+
+
+class TestRootHybr:
+ def test_pressure_network_no_gradient(self):
+ # root/hybr without gradient, equal pipes -> equal flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows = optimize.root(pressure_network, initial_guess,
+ method='hybr', args=(Qtot, k)).x
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+ def test_pressure_network_with_gradient(self):
+ # root/hybr with gradient, equal pipes -> equal flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([[2., 0., 2., 0.]])
+ final_flows = optimize.root(pressure_network, initial_guess,
+ args=(Qtot, k), method='hybr',
+ jac=pressure_network_jacobian).x
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+ def test_pressure_network_with_gradient_combined(self):
+ # root/hybr with gradient and function combined, equal pipes -> equal
+ # flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows = optimize.root(pressure_network_fun_and_grad,
+ initial_guess, args=(Qtot, k),
+ method='hybr', jac=True).x
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+
+class TestRootLM:
+ def test_pressure_network_no_gradient(self):
+ # root/lm without gradient, equal pipes -> equal flows
+ k = np.full(4, 0.5)
+ Qtot = 4
+ initial_guess = array([2., 0., 2., 0.])
+ final_flows = optimize.root(pressure_network, initial_guess,
+ method='lm', args=(Qtot, k)).x
+ assert_array_almost_equal(final_flows, np.ones(4))
+
+
+class TestNfev:
+ def setup_method(self):
+ self.nfev = threading.local()
+
+ def zero_f(self, y):
+ if not hasattr(self.nfev, 'c'):
+ self.nfev.c = 0
+ self.nfev.c += 1
+ return y**2-3
+
+ @pytest.mark.parametrize('method', ['hybr', 'lm', 'broyden1',
+ 'broyden2', 'anderson',
+ 'linearmixing', 'diagbroyden',
+ 'excitingmixing', 'krylov',
+ 'df-sane'])
+ def test_root_nfev(self, method):
+ self.nfev.c = 0
+ solution = optimize.root(self.zero_f, 100, method=method)
+ assert solution.nfev == self.nfev.c
+
+ def test_fsolve_nfev(self):
+ self.nfev.c = 0
+ x, info, ier, mesg = optimize.fsolve(self.zero_f, 100, full_output=True)
+ assert info['nfev'] == self.nfev.c
+
+
+class TestLeastSq:
+ def setup_method(self):
+ x = np.linspace(0, 10, 40)
+ a,b,c = 3.1, 42, -304.2
+ self.x = x
+ self.abc = a,b,c
+ y_true = a*x**2 + b*x + c
+ rng = np.random.default_rng(123)
+ self.y_meas = y_true + 0.01*rng.standard_normal(y_true.shape)
+
+ def residuals(self, p, y, x):
+ a,b,c = p
+ err = y-(a*x**2 + b*x + c)
+ return err
+
+ def residuals_jacobian(self, _p, _y, x):
+ return -np.vstack([x**2, x, np.ones_like(x)]).T
+
+ def test_basic(self):
+ p0 = array([0,0,0])
+ params_fit, ier = leastsq(self.residuals, p0,
+ args=(self.y_meas, self.x))
+ assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
+ # low precision due to random
+ assert_array_almost_equal(params_fit, self.abc, decimal=2)
+
+ def test_basic_with_gradient(self):
+ p0 = array([0,0,0])
+ params_fit, ier = leastsq(self.residuals, p0,
+ args=(self.y_meas, self.x),
+ Dfun=self.residuals_jacobian)
+ assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
+ # low precision due to random
+ assert_array_almost_equal(params_fit, self.abc, decimal=2)
+
+ def test_full_output(self):
+ p0 = array([[0,0,0]])
+ full_output = leastsq(self.residuals, p0,
+ args=(self.y_meas, self.x),
+ full_output=True)
+ params_fit, cov_x, infodict, mesg, ier = full_output
+ assert_(ier in (1,2,3,4), f'solution not found: {mesg}')
+
+ def test_input_untouched(self):
+ p0 = array([0,0,0],dtype=float64)
+ p0_copy = array(p0, copy=True)
+ full_output = leastsq(self.residuals, p0,
+ args=(self.y_meas, self.x),
+ full_output=True)
+ params_fit, cov_x, infodict, mesg, ier = full_output
+ assert_(ier in (1,2,3,4), f'solution not found: {mesg}')
+ assert_array_equal(p0, p0_copy)
+
+ def test_wrong_shape_func_callable(self):
+ func = ReturnShape(1)
+ # x0 is a list of two elements, but func will return an array with
+ # length 1, so this should result in a TypeError.
+ x0 = [1.5, 2.0]
+ assert_raises(TypeError, optimize.leastsq, func, x0)
+
+ def test_wrong_shape_func_function(self):
+ # x0 is a list of two elements, but func will return an array with
+ # length 1, so this should result in a TypeError.
+ x0 = [1.5, 2.0]
+ assert_raises(TypeError, optimize.leastsq, dummy_func, x0, args=((1,),))
+
+ def test_wrong_shape_Dfun_callable(self):
+ func = ReturnShape(1)
+ deriv_func = ReturnShape((2,2))
+ assert_raises(TypeError, optimize.leastsq, func, x0=[0,1], Dfun=deriv_func)
+
+ def test_wrong_shape_Dfun_function(self):
+ def func(x):
+ return dummy_func(x, (2,))
+ def deriv_func(x):
+ return dummy_func(x, (3, 3))
+ assert_raises(TypeError, optimize.leastsq, func, x0=[0,1], Dfun=deriv_func)
+
+ def test_float32(self):
+ # Regression test for gh-1447
+ def func(p,x,y):
+ q = p[0]*np.exp(-(x-p[1])**2/(2.0*p[2]**2))+p[3]
+ return q - y
+
+ x = np.array([1.475,1.429,1.409,1.419,1.455,1.519,1.472, 1.368,1.286,
+ 1.231], dtype=np.float32)
+ y = np.array([0.0168,0.0193,0.0211,0.0202,0.0171,0.0151,0.0185,0.0258,
+ 0.034,0.0396], dtype=np.float32)
+ p0 = np.array([1.0,1.0,1.0,1.0])
+ p1, success = optimize.leastsq(func, p0, args=(x,y))
+
+ assert_(success in [1,2,3,4])
+ assert_((func(p1,x,y)**2).sum() < 1e-4 * (func(p0,x,y)**2).sum())
+
+ def test_func_can_raise(self):
+ def func(*args):
+ raise ValueError('I raised')
+
+ with assert_raises(ValueError, match='I raised'):
+ optimize.leastsq(func, x0=[0])
+
+ def test_Dfun_can_raise(self):
+ def func(x):
+ return x - np.array([10])
+
+ def deriv_func(*args):
+ raise ValueError('I raised')
+
+ with assert_raises(ValueError, match='I raised'):
+ optimize.leastsq(func, x0=[0], Dfun=deriv_func)
+
+ def test_reentrant_func(self):
+ def func(*args):
+ self.test_basic()
+ return self.residuals(*args)
+
+ p0 = array([0,0,0])
+ params_fit, ier = leastsq(func, p0,
+ args=(self.y_meas, self.x))
+ assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
+ # low precision due to random
+ assert_array_almost_equal(params_fit, self.abc, decimal=2)
+
+ def test_reentrant_Dfun(self):
+ def deriv_func(*args):
+ self.test_basic()
+ return self.residuals_jacobian(*args)
+
+ p0 = array([0,0,0])
+ params_fit, ier = leastsq(self.residuals, p0,
+ args=(self.y_meas, self.x),
+ Dfun=deriv_func)
+ assert_(ier in (1, 2, 3, 4), f'solution not found (ier={ier})')
+ # low precision due to random
+ assert_array_almost_equal(params_fit, self.abc, decimal=2)
+
+ def test_concurrent_no_gradient(self):
+ v = sequence_parallel([self.test_basic] * 10)
+ assert all([result is None for result in v])
+
+ def test_concurrent_with_gradient(self):
+ v = sequence_parallel([self.test_basic_with_gradient] * 10)
+ assert all([result is None for result in v])
+
+ def test_func_input_output_length_check(self):
+
+ def func(x):
+ return 2 * (x[0] - 3) ** 2 + 1
+
+ with assert_raises(TypeError,
+ match='Improper input: func input vector length N='):
+ optimize.leastsq(func, x0=[0, 1])
+
+
+class TestCurveFit:
+ def setup_method(self):
+ self.y = array([1.0, 3.2, 9.5, 13.7])
+ self.x = array([1.0, 2.0, 3.0, 4.0])
+
+ def test_one_argument(self):
+ def func(x,a):
+ return x**a
+ popt, pcov = curve_fit(func, self.x, self.y)
+ assert_(len(popt) == 1)
+ assert_(pcov.shape == (1,1))
+ assert_almost_equal(popt[0], 1.9149, decimal=4)
+ assert_almost_equal(pcov[0,0], 0.0016, decimal=4)
+
+ # Test if we get the same with full_output. Regression test for #1415.
+ # Also test if check_finite can be turned off.
+ res = curve_fit(func, self.x, self.y,
+ full_output=1, check_finite=False)
+ (popt2, pcov2, infodict, errmsg, ier) = res
+ assert_array_almost_equal(popt, popt2)
+
+ def test_two_argument(self):
+ def func(x, a, b):
+ return b*x**a
+ popt, pcov = curve_fit(func, self.x, self.y)
+ assert_(len(popt) == 2)
+ assert_(pcov.shape == (2,2))
+ assert_array_almost_equal(popt, [1.7989, 1.1642], decimal=4)
+ assert_array_almost_equal(pcov, [[0.0852, -0.1260], [-0.1260, 0.1912]],
+ decimal=4)
+
+ def test_func_is_classmethod(self):
+ class test_self:
+ """This class tests if curve_fit passes the correct number of
+ arguments when the model function is a class instance method.
+ """
+
+ def func(self, x, a, b):
+ return b * x**a
+
+ test_self_inst = test_self()
+ popt, pcov = curve_fit(test_self_inst.func, self.x, self.y)
+ assert_(pcov.shape == (2,2))
+ assert_array_almost_equal(popt, [1.7989, 1.1642], decimal=4)
+ assert_array_almost_equal(pcov, [[0.0852, -0.1260], [-0.1260, 0.1912]],
+ decimal=4)
+
+ def test_regression_2639(self):
+ # This test fails if epsfcn in leastsq is too large.
+ x = [574.14200000000005, 574.154, 574.16499999999996,
+ 574.17700000000002, 574.18799999999999, 574.19899999999996,
+ 574.21100000000001, 574.22199999999998, 574.23400000000004,
+ 574.245]
+ y = [859.0, 997.0, 1699.0, 2604.0, 2013.0, 1964.0, 2435.0,
+ 1550.0, 949.0, 841.0]
+ guess = [574.1861428571428, 574.2155714285715, 1302.0, 1302.0,
+ 0.0035019999999983615, 859.0]
+ good = [5.74177150e+02, 5.74209188e+02, 1.74187044e+03, 1.58646166e+03,
+ 1.0068462e-02, 8.57450661e+02]
+
+ def f_double_gauss(x, x0, x1, A0, A1, sigma, c):
+ return (A0*np.exp(-(x-x0)**2/(2.*sigma**2))
+ + A1*np.exp(-(x-x1)**2/(2.*sigma**2)) + c)
+ popt, pcov = curve_fit(f_double_gauss, x, y, guess, maxfev=10000)
+ assert_allclose(popt, good, rtol=1e-5)
+
+ def test_pcov(self):
+ xdata = np.array([0, 1, 2, 3, 4, 5])
+ ydata = np.array([1, 1, 5, 7, 8, 12])
+ sigma = np.array([1, 2, 1, 2, 1, 2])
+
+ def f(x, a, b):
+ return a*x + b
+
+ for method in ['lm', 'trf', 'dogbox']:
+ popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=sigma,
+ method=method)
+ perr_scaled = np.sqrt(np.diag(pcov))
+ assert_allclose(perr_scaled, [0.20659803, 0.57204404], rtol=1e-3)
+
+ popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=3*sigma,
+ method=method)
+ perr_scaled = np.sqrt(np.diag(pcov))
+ assert_allclose(perr_scaled, [0.20659803, 0.57204404], rtol=1e-3)
+
+ popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=sigma,
+ absolute_sigma=True, method=method)
+ perr = np.sqrt(np.diag(pcov))
+ assert_allclose(perr, [0.30714756, 0.85045308], rtol=1e-3)
+
+ popt, pcov = curve_fit(f, xdata, ydata, p0=[2, 0], sigma=3*sigma,
+ absolute_sigma=True, method=method)
+ perr = np.sqrt(np.diag(pcov))
+ assert_allclose(perr, [3*0.30714756, 3*0.85045308], rtol=1e-3)
+
+ # infinite variances
+
+ def f_flat(x, a, b):
+ return a*x
+
+ pcov_expected = np.array([np.inf]*4).reshape(2, 2)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "Covariance of the parameters could not be estimated",
+ OptimizeWarning)
+ popt, pcov = curve_fit(f_flat, xdata, ydata, p0=[2, 0], sigma=sigma)
+ popt1, pcov1 = curve_fit(f, xdata[:2], ydata[:2], p0=[2, 0])
+
+ assert_(pcov.shape == (2, 2))
+ assert_array_equal(pcov, pcov_expected)
+
+ assert_(pcov1.shape == (2, 2))
+ assert_array_equal(pcov1, pcov_expected)
+
+ def test_array_like(self):
+ # Test sequence input. Regression test for gh-3037.
+ def f_linear(x, a, b):
+ return a*x + b
+
+ x = [1, 2, 3, 4]
+ y = [3, 5, 7, 9]
+ assert_allclose(curve_fit(f_linear, x, y)[0], [2, 1], atol=1e-10)
+
+ def test_indeterminate_covariance(self):
+ # Test that a warning is returned when pcov is indeterminate
+ xdata = np.array([1, 2, 3, 4, 5, 6])
+ ydata = np.array([1, 2, 3, 4, 5.5, 6])
+ with pytest.warns(OptimizeWarning):
+ curve_fit(lambda x, a, b: a*x, xdata, ydata)
+
+ def test_NaN_handling(self):
+ # Test for correct handling of NaNs in input data: gh-3422
+
+ # create input with NaNs
+ xdata = np.array([1, np.nan, 3])
+ ydata = np.array([1, 2, 3])
+
+ assert_raises(ValueError, curve_fit,
+ lambda x, a, b: a*x + b, xdata, ydata)
+ assert_raises(ValueError, curve_fit,
+ lambda x, a, b: a*x + b, ydata, xdata)
+
+ assert_raises(ValueError, curve_fit, lambda x, a, b: a*x + b,
+ xdata, ydata, **{"check_finite": True})
+
+ @staticmethod
+ def _check_nan_policy(f, xdata_with_nan, xdata_without_nan,
+ ydata_with_nan, ydata_without_nan, method):
+ kwargs = {'f': f, 'xdata': xdata_with_nan, 'ydata': ydata_with_nan,
+ 'method': method, 'check_finite': False}
+ # propagate test
+ error_msg = ("`nan_policy='propagate'` is not supported "
+ "by this function.")
+ with assert_raises(ValueError, match=error_msg):
+ curve_fit(**kwargs, nan_policy="propagate", maxfev=2000)
+
+ # raise test
+ with assert_raises(ValueError, match="The input contains nan"):
+ curve_fit(**kwargs, nan_policy="raise")
+
+ # omit test
+ result_with_nan, _ = curve_fit(**kwargs, nan_policy="omit")
+ kwargs['xdata'] = xdata_without_nan
+ kwargs['ydata'] = ydata_without_nan
+ result_without_nan, _ = curve_fit(**kwargs)
+ assert_allclose(result_with_nan, result_without_nan)
+
+ # not valid policy test
+ # check for argument names in any order
+ error_msg = (r"nan_policy must be one of \{(?:'raise'|'omit'|None)"
+ r"(?:, ?(?:'raise'|'omit'|None))*\}")
+ with assert_raises(ValueError, match=error_msg):
+ curve_fit(**kwargs, nan_policy="hi")
+
+ @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"])
+ def test_nan_policy_1d(self, method):
+ def f(x, a, b):
+ return a*x + b
+
+ xdata_with_nan = np.array([2, 3, np.nan, 4, 4, np.nan])
+ ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7])
+ xdata_without_nan = np.array([2, 3, 4])
+ ydata_without_nan = np.array([1, 2, 3])
+
+ self._check_nan_policy(f, xdata_with_nan, xdata_without_nan,
+ ydata_with_nan, ydata_without_nan, method)
+
+ @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"])
+ def test_nan_policy_2d(self, method):
+ def f(x, a, b):
+ x1 = x[0, :]
+ x2 = x[1, :]
+ return a*x1 + b + x2
+
+ xdata_with_nan = np.array([[2, 3, np.nan, 4, 4, np.nan, 5],
+ [2, 3, np.nan, np.nan, 4, np.nan, 7]])
+ ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7, 10])
+ xdata_without_nan = np.array([[2, 3, 5], [2, 3, 7]])
+ ydata_without_nan = np.array([1, 2, 10])
+
+ self._check_nan_policy(f, xdata_with_nan, xdata_without_nan,
+ ydata_with_nan, ydata_without_nan, method)
+
+ @pytest.mark.parametrize('n', [2, 3])
+ @pytest.mark.parametrize('method', ["lm", "trf", "dogbox"])
+ def test_nan_policy_2_3d(self, n, method):
+ def f(x, a, b):
+ x1 = x[..., 0, :].squeeze()
+ x2 = x[..., 1, :].squeeze()
+ return a*x1 + b + x2
+
+ xdata_with_nan = np.array([[[2, 3, np.nan, 4, 4, np.nan, 5],
+ [2, 3, np.nan, np.nan, 4, np.nan, 7]]])
+ xdata_with_nan = xdata_with_nan.squeeze() if n == 2 else xdata_with_nan
+ ydata_with_nan = np.array([1, 2, 5, 3, np.nan, 7, 10])
+ xdata_without_nan = np.array([[[2, 3, 5], [2, 3, 7]]])
+ ydata_without_nan = np.array([1, 2, 10])
+
+ self._check_nan_policy(f, xdata_with_nan, xdata_without_nan,
+ ydata_with_nan, ydata_without_nan, method)
+
+ def test_empty_inputs(self):
+ # Test both with and without bounds (regression test for gh-9864)
+ assert_raises(ValueError, curve_fit, lambda x, a: a*x, [], [])
+ assert_raises(ValueError, curve_fit, lambda x, a: a*x, [], [],
+ bounds=(1, 2))
+ assert_raises(ValueError, curve_fit, lambda x, a: a*x, [1], [])
+ assert_raises(ValueError, curve_fit, lambda x, a: a*x, [2], [],
+ bounds=(1, 2))
+
+ def test_function_zero_params(self):
+ # Fit args is zero, so "Unable to determine number of fit parameters."
+ assert_raises(ValueError, curve_fit, lambda x: x, [1, 2], [3, 4])
+
+ def test_None_x(self): # Added in GH10196
+ popt, pcov = curve_fit(lambda _, a: a * np.arange(10),
+ None, 2 * np.arange(10))
+ assert_allclose(popt, [2.])
+
+ def test_method_argument(self):
+ def f(x, a, b):
+ return a * np.exp(-b*x)
+
+ xdata = np.linspace(0, 1, 11)
+ ydata = f(xdata, 2., 2.)
+
+ for method in ['trf', 'dogbox', 'lm', None]:
+ popt, pcov = curve_fit(f, xdata, ydata, method=method)
+ assert_allclose(popt, [2., 2.])
+
+ assert_raises(ValueError, curve_fit, f, xdata, ydata, method='unknown')
+
+ def test_full_output(self):
+ def f(x, a, b):
+ return a * np.exp(-b * x)
+
+ xdata = np.linspace(0, 1, 11)
+ ydata = f(xdata, 2., 2.)
+
+ for method in ['trf', 'dogbox', 'lm', None]:
+ popt, pcov, infodict, errmsg, ier = curve_fit(
+ f, xdata, ydata, method=method, full_output=True)
+ assert_allclose(popt, [2., 2.])
+ assert "nfev" in infodict
+ assert "fvec" in infodict
+ if method == 'lm' or method is None:
+ assert "fjac" in infodict
+ assert "ipvt" in infodict
+ assert "qtf" in infodict
+ assert isinstance(errmsg, str)
+ assert ier in (1, 2, 3, 4)
+
+ def test_bounds(self):
+ def f(x, a, b):
+ return a * np.exp(-b*x)
+
+ xdata = np.linspace(0, 1, 11)
+ ydata = f(xdata, 2., 2.)
+
+ # The minimum w/out bounds is at [2., 2.],
+ # and with bounds it's at [1.5, smth].
+ lb = [1., 0]
+ ub = [1.5, 3.]
+
+ # Test that both variants of the bounds yield the same result
+ bounds = (lb, ub)
+ bounds_class = Bounds(lb, ub)
+ for method in [None, 'trf', 'dogbox']:
+ popt, pcov = curve_fit(f, xdata, ydata, bounds=bounds,
+ method=method)
+ assert_allclose(popt[0], 1.5)
+
+ popt_class, pcov_class = curve_fit(f, xdata, ydata,
+ bounds=bounds_class,
+ method=method)
+ assert_allclose(popt_class, popt)
+
+ # With bounds, the starting estimate is feasible.
+ popt, pcov = curve_fit(f, xdata, ydata, method='trf',
+ bounds=([0., 0], [0.6, np.inf]))
+ assert_allclose(popt[0], 0.6)
+
+ # method='lm' doesn't support bounds.
+ assert_raises(ValueError, curve_fit, f, xdata, ydata, bounds=bounds,
+ method='lm')
+
+ def test_bounds_p0(self):
+ # This test is for issue #5719. The problem was that an initial guess
+ # was ignored when 'trf' or 'dogbox' methods were invoked.
+ def f(x, a):
+ return np.sin(x + a)
+
+ xdata = np.linspace(-2*np.pi, 2*np.pi, 40)
+ ydata = np.sin(xdata)
+ bounds = (-3 * np.pi, 3 * np.pi)
+ for method in ['trf', 'dogbox']:
+ popt_1, _ = curve_fit(f, xdata, ydata, p0=2.1*np.pi)
+ popt_2, _ = curve_fit(f, xdata, ydata, p0=2.1*np.pi,
+ bounds=bounds, method=method)
+
+ # If the initial guess is ignored, then popt_2 would be close 0.
+ assert_allclose(popt_1, popt_2)
+
+ def test_jac(self):
+ # Test that Jacobian callable is handled correctly and
+ # weighted if sigma is provided.
+ def f(x, a, b):
+ return a * np.exp(-b*x)
+
+ def jac(x, a, b):
+ e = np.exp(-b*x)
+ return np.vstack((e, -a * x * e)).T
+
+ xdata = np.linspace(0, 1, 11)
+ ydata = f(xdata, 2., 2.)
+
+ # Test numerical options for least_squares backend.
+ for method in ['trf', 'dogbox']:
+ for scheme in ['2-point', '3-point', 'cs']:
+ popt, pcov = curve_fit(f, xdata, ydata, jac=scheme,
+ method=method)
+ assert_allclose(popt, [2, 2])
+
+ # Test the analytic option.
+ for method in ['lm', 'trf', 'dogbox']:
+ popt, pcov = curve_fit(f, xdata, ydata, method=method, jac=jac)
+ assert_allclose(popt, [2, 2])
+
+ # Now add an outlier and provide sigma.
+ ydata[5] = 100
+ sigma = np.ones(xdata.shape[0])
+ sigma[5] = 200
+ for method in ['lm', 'trf', 'dogbox']:
+ popt, pcov = curve_fit(f, xdata, ydata, sigma=sigma, method=method,
+ jac=jac)
+ # Still the optimization process is influenced somehow,
+ # have to set rtol=1e-3.
+ assert_allclose(popt, [2, 2], rtol=1e-3)
+
+ def test_maxfev_and_bounds(self):
+ # gh-6340: with no bounds, curve_fit accepts parameter maxfev (via leastsq)
+ # but with bounds, the parameter is `max_nfev` (via least_squares)
+ x = np.arange(0, 10)
+ y = 2*x
+ popt1, _ = curve_fit(lambda x,p: p*x, x, y, bounds=(0, 3), maxfev=100)
+ popt2, _ = curve_fit(lambda x,p: p*x, x, y, bounds=(0, 3), max_nfev=100)
+
+ assert_allclose(popt1, 2, atol=1e-14)
+ assert_allclose(popt2, 2, atol=1e-14)
+
+ @pytest.mark.parametrize("sigma_dim", [0, 1, 2])
+ def test_curvefit_omitnan(self, sigma_dim):
+ def exponential(x, a, b):
+ return b * np.exp(a * x)
+
+ rng = np.random.default_rng(578285731148908)
+ N = 100
+ x = np.linspace(1, 10, N)
+ y = exponential(x, 0.2, 0.5)
+
+ if (sigma_dim == 0):
+ sigma = 0.05
+ y += rng.normal(0, sigma, N)
+
+ elif (sigma_dim == 1):
+ sigma = x * 0.05
+ y += rng.normal(0, sigma, N)
+
+ elif (sigma_dim == 2):
+ # The covariance matrix must be symmetric positive-semidefinite
+ a = rng.normal(0, 2, (N, N))
+ sigma = a @ a.T
+ y += rng.multivariate_normal(np.zeros_like(x), sigma)
+ else:
+ assert False, "The sigma must be a scalar, 1D array or 2D array."
+
+ p0 = [0.1, 1.0]
+
+ # Choose indices to place NaNs.
+ i_x = rng.integers(N, size=5)
+ i_y = rng.integers(N, size=5)
+
+ # Add NaNs and compute result using `curve_fit`
+ x[i_x] = np.nan
+ y[i_y] = np.nan
+ res_opt, res_cov = curve_fit(exponential, x, y, p0=p0, sigma=sigma,
+ nan_policy="omit")
+
+ # Manually remove elements that should be eliminated, and
+ # calculate reference using `curve_fit`
+ i_delete = np.unique(np.concatenate((i_x, i_y)))
+ x = np.delete(x, i_delete, axis=0)
+ y = np.delete(y, i_delete, axis=0)
+
+ sigma = np.asarray(sigma)
+ if sigma.ndim == 1:
+ sigma = np.delete(sigma, i_delete)
+ elif sigma.ndim == 2:
+ sigma = np.delete(sigma, i_delete, axis=0)
+ sigma = np.delete(sigma, i_delete, axis=1)
+ ref_opt, ref_cov = curve_fit(exponential, x, y, p0=p0, sigma=sigma)
+
+ assert_allclose(res_opt, ref_opt, atol=1e-14)
+ assert_allclose(res_cov, ref_cov, atol=1e-14)
+
+ def test_curvefit_simplecovariance(self):
+
+ def func(x, a, b):
+ return a * np.exp(-b*x)
+
+ def jac(x, a, b):
+ e = np.exp(-b*x)
+ return np.vstack((e, -a * x * e)).T
+
+ rng = np.random.default_rng(123)
+ xdata = np.linspace(0, 4, 50)
+ y = func(xdata, 2.5, 1.3)
+ ydata = y + 0.2 * rng.standard_normal(size=len(xdata))
+
+ sigma = np.zeros(len(xdata)) + 0.2
+ covar = np.diag(sigma**2)
+
+ for jac1, jac2 in [(jac, jac), (None, None)]:
+ for absolute_sigma in [False, True]:
+ popt1, pcov1 = curve_fit(func, xdata, ydata, sigma=sigma,
+ jac=jac1, absolute_sigma=absolute_sigma)
+ popt2, pcov2 = curve_fit(func, xdata, ydata, sigma=covar,
+ jac=jac2, absolute_sigma=absolute_sigma)
+
+ assert_allclose(popt1, popt2, atol=1e-14)
+ assert_allclose(pcov1, pcov2, atol=1e-14)
+
+ def test_curvefit_covariance(self):
+
+ def funcp(x, a, b):
+ rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0],
+ [1./np.sqrt(2), 1./np.sqrt(2), 0],
+ [0, 0, 1.0]])
+ return rotn.dot(a * np.exp(-b*x))
+
+ def jacp(x, a, b):
+ rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0],
+ [1./np.sqrt(2), 1./np.sqrt(2), 0],
+ [0, 0, 1.0]])
+ e = np.exp(-b*x)
+ return rotn.dot(np.vstack((e, -a * x * e)).T)
+
+ def func(x, a, b):
+ return a * np.exp(-b*x)
+
+ def jac(x, a, b):
+ e = np.exp(-b*x)
+ return np.vstack((e, -a * x * e)).T
+
+ rng = np.random.default_rng(1234)
+ xdata = np.arange(1, 4)
+ y = func(xdata, 2.5, 1.0)
+ ydata = y + 0.2 * rng.standard_normal(size=len(xdata))
+ sigma = np.zeros(len(xdata)) + 0.2
+ covar = np.diag(sigma**2)
+ # Get a rotation matrix, and obtain ydatap = R ydata
+ # Chisq = ydata^T C^{-1} ydata
+ # = ydata^T R^T R C^{-1} R^T R ydata
+ # = ydatap^T Cp^{-1} ydatap
+ # Cp^{-1} = R C^{-1} R^T
+ # Cp = R C R^T, since R^-1 = R^T
+ rotn = np.array([[1./np.sqrt(2), -1./np.sqrt(2), 0],
+ [1./np.sqrt(2), 1./np.sqrt(2), 0],
+ [0, 0, 1.0]])
+ ydatap = rotn.dot(ydata)
+ covarp = rotn.dot(covar).dot(rotn.T)
+
+ for jac1, jac2 in [(jac, jacp), (None, None)]:
+ for absolute_sigma in [False, True]:
+ popt1, pcov1 = curve_fit(func, xdata, ydata, sigma=sigma,
+ jac=jac1, absolute_sigma=absolute_sigma)
+ popt2, pcov2 = curve_fit(funcp, xdata, ydatap, sigma=covarp,
+ jac=jac2, absolute_sigma=absolute_sigma)
+
+ assert_allclose(popt1, popt2, rtol=1.4e-7, atol=1e-14)
+ assert_allclose(pcov1, pcov2, rtol=1.4e-7, atol=1e-14)
+
+ @pytest.mark.parametrize("absolute_sigma", [False, True])
+ def test_curvefit_scalar_sigma(self, absolute_sigma):
+ def func(x, a, b):
+ return a * x + b
+
+ x, y = self.x, self.y
+ _, pcov1 = curve_fit(func, x, y, sigma=2, absolute_sigma=absolute_sigma)
+ # Explicitly building the sigma 1D array
+ _, pcov2 = curve_fit(
+ func, x, y, sigma=np.full_like(y, 2), absolute_sigma=absolute_sigma
+ )
+ assert np.all(pcov1 == pcov2)
+
+ def test_dtypes(self):
+ # regression test for gh-9581: curve_fit fails if x and y dtypes differ
+ x = np.arange(-3, 5)
+ y = 1.5*x + 3.0 + 0.5*np.sin(x)
+
+ def func(x, a, b):
+ return a*x + b
+
+ for method in ['lm', 'trf', 'dogbox']:
+ for dtx in [np.float32, np.float64]:
+ for dty in [np.float32, np.float64]:
+ x = x.astype(dtx)
+ y = y.astype(dty)
+
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", OptimizeWarning)
+ p, cov = curve_fit(func, x, y, method=method)
+
+ assert np.isfinite(cov).all()
+ assert not np.allclose(p, 1) # curve_fit's initial value
+
+ def test_dtypes2(self):
+ # regression test for gh-7117: curve_fit fails if
+ # both inputs are float32
+ def hyperbola(x, s_1, s_2, o_x, o_y, c):
+ b_2 = (s_1 + s_2) / 2
+ b_1 = (s_2 - s_1) / 2
+ return o_y + b_1*(x-o_x) + b_2*np.sqrt((x-o_x)**2 + c**2/4)
+
+ min_fit = np.array([-3.0, 0.0, -2.0, -10.0, 0.0])
+ max_fit = np.array([0.0, 3.0, 3.0, 0.0, 10.0])
+ guess = np.array([-2.5/3.0, 4/3.0, 1.0, -4.0, 0.5])
+
+ params = [-2, .4, -1, -5, 9.5]
+ xdata = np.array([-32, -16, -8, 4, 4, 8, 16, 32])
+ ydata = hyperbola(xdata, *params)
+
+ # run optimization twice, with xdata being float32 and float64
+ popt_64, _ = curve_fit(f=hyperbola, xdata=xdata, ydata=ydata, p0=guess,
+ bounds=(min_fit, max_fit))
+
+ xdata = xdata.astype(np.float32)
+ ydata = hyperbola(xdata, *params)
+
+ popt_32, _ = curve_fit(f=hyperbola, xdata=xdata, ydata=ydata, p0=guess,
+ bounds=(min_fit, max_fit))
+
+ assert_allclose(popt_32, popt_64, atol=2e-5)
+
+ def test_broadcast_y(self):
+ xdata = np.arange(10)
+ rng = np.random.default_rng(123)
+ target = 4.7 * xdata ** 2 + 3.5 * xdata + rng.random(size=len(xdata))
+ def fit_func(x, a, b):
+ return a * x ** 2 + b * x - target
+ for method in ['lm', 'trf', 'dogbox']:
+ popt0, pcov0 = curve_fit(fit_func,
+ xdata=xdata,
+ ydata=np.zeros_like(xdata),
+ method=method)
+ popt1, pcov1 = curve_fit(fit_func,
+ xdata=xdata,
+ ydata=0,
+ method=method)
+ assert_allclose(pcov0, pcov1)
+
+ def test_args_in_kwargs(self):
+ # Ensure that `args` cannot be passed as keyword argument to `curve_fit`
+
+ def func(x, a, b):
+ return a * x + b
+
+ with assert_raises(ValueError):
+ curve_fit(func,
+ xdata=[1, 2, 3, 4],
+ ydata=[5, 9, 13, 17],
+ p0=[1],
+ args=(1,))
+
+ def test_data_point_number_validation(self):
+ def func(x, a, b, c, d, e):
+ return a * np.exp(-b * x) + c + d + e
+
+ with assert_raises(TypeError, match="The number of func parameters="):
+ curve_fit(func,
+ xdata=[1, 2, 3, 4],
+ ydata=[5, 9, 13, 17])
+
+ @pytest.mark.filterwarnings('ignore::RuntimeWarning')
+ def test_gh4555(self):
+ # gh-4555 reported that covariance matrices returned by `leastsq`
+ # can have negative diagonal elements and eigenvalues. (In fact,
+ # they can also be asymmetric.) This shows up in the output of
+ # `scipy.optimize.curve_fit`. Check that it has been resolved.giit
+ def f(x, a, b, c, d, e):
+ return a*np.log(x + 1 + b) + c*np.log(x + 1 + d) + e
+
+ rng = np.random.default_rng(408113519974467917)
+ n = 100
+ x = np.arange(n)
+ y = np.linspace(2, 7, n) + rng.random(n)
+ p, cov = optimize.curve_fit(f, x, y, maxfev=100000)
+ assert np.all(np.diag(cov) > 0)
+ eigs = linalg.eigh(cov)[0] # separate line for debugging
+ # some platforms see a small negative eigevenvalue
+ assert np.all(eigs > -1e-2)
+ assert_allclose(cov, cov.T)
+
+ def test_gh4555b(self):
+ # check that PR gh-17247 did not significantly change covariance matrix
+ # for simple cases
+ rng = np.random.default_rng(408113519974467917)
+
+ def func(x, a, b, c):
+ return a * np.exp(-b * x) + c
+
+ xdata = np.linspace(0, 4, 50)
+ y = func(xdata, 2.5, 1.3, 0.5)
+ y_noise = 0.2 * rng.normal(size=xdata.size)
+ ydata = y + y_noise
+ _, res = curve_fit(func, xdata, ydata)
+ # reference from commit 1d80a2f254380d2b45733258ca42eb6b55c8755b
+ ref = [[+0.0158972536486215, 0.0069207183284242, -0.0007474400714749],
+ [+0.0069207183284242, 0.0205057958128679, +0.0053997711275403],
+ [-0.0007474400714749, 0.0053997711275403, +0.0027833930320877]]
+ # Linux_Python_38_32bit_full fails with default tolerance
+ assert_allclose(res, ref, 2e-7)
+
+ def test_gh13670(self):
+ # gh-13670 reported that `curve_fit` executes callables
+ # with the same values of the parameters at the beginning of
+ # optimization. Check that this has been resolved.
+
+ rng = np.random.default_rng(8250058582555444926)
+ x = np.linspace(0, 3, 101)
+ y = 2 * x + 1 + rng.normal(size=101) * 0.5
+
+ def line(x, *p):
+ assert not np.all(line.last_p == p)
+ line.last_p = p
+ return x * p[0] + p[1]
+
+ def jac(x, *p):
+ assert not np.all(jac.last_p == p)
+ jac.last_p = p
+ return np.array([x, np.ones_like(x)]).T
+
+ line.last_p = None
+ jac.last_p = None
+ p0 = np.array([1.0, 5.0])
+ curve_fit(line, x, y, p0, method='lm', jac=jac)
+
+ @pytest.mark.parametrize('method', ['trf', 'dogbox'])
+ def test_gh20155_error_mentions_x0(self, method):
+ # `curve_fit` produced an error message that referred to an undocumented
+ # variable `x0`, which was really `p0`. Check that this is resolved.
+ def func(x,a):
+ return x**a
+ message = "Initial guess is outside of provided bounds"
+ with pytest.raises(ValueError, match=message):
+ curve_fit(func, self.x, self.y, p0=[1], bounds=(1000, 1001),
+ method=method)
+
+
+class TestFixedPoint:
+
+ def test_scalar_trivial(self):
+ # f(x) = 2x; fixed point should be x=0
+ def func(x):
+ return 2.0*x
+ x0 = 1.0
+ x = fixed_point(func, x0)
+ assert_almost_equal(x, 0.0)
+
+ def test_scalar_basic1(self):
+ # f(x) = x**2; x0=1.05; fixed point should be x=1
+ def func(x):
+ return x**2
+ x0 = 1.05
+ x = fixed_point(func, x0)
+ assert_almost_equal(x, 1.0)
+
+ def test_scalar_basic2(self):
+ # f(x) = x**0.5; x0=1.05; fixed point should be x=1
+ def func(x):
+ return x**0.5
+ x0 = 1.05
+ x = fixed_point(func, x0)
+ assert_almost_equal(x, 1.0)
+
+ def test_array_trivial(self):
+ def func(x):
+ return 2.0*x
+ x0 = [0.3, 0.15]
+ with np.errstate(all='ignore'):
+ x = fixed_point(func, x0)
+ assert_almost_equal(x, [0.0, 0.0])
+
+ def test_array_basic1(self):
+ # f(x) = c * x**2; fixed point should be x=1/c
+ def func(x, c):
+ return c * x**2
+ c = array([0.75, 1.0, 1.25])
+ x0 = [1.1, 1.15, 0.9]
+ with np.errstate(all='ignore'):
+ x = fixed_point(func, x0, args=(c,))
+ assert_almost_equal(x, 1.0/c)
+
+ def test_array_basic2(self):
+ # f(x) = c * x**0.5; fixed point should be x=c**2
+ def func(x, c):
+ return c * x**0.5
+ c = array([0.75, 1.0, 1.25])
+ x0 = [0.8, 1.1, 1.1]
+ x = fixed_point(func, x0, args=(c,))
+ assert_almost_equal(x, c**2)
+
+ def test_lambertw(self):
+ # python-list/2010-December/594592.html
+ xxroot = fixed_point(lambda xx: np.exp(-2.0*xx)/2.0, 1.0,
+ args=(), xtol=1e-12, maxiter=500)
+ assert_allclose(xxroot, np.exp(-2.0*xxroot)/2.0)
+ assert_allclose(xxroot, lambertw(1)/2)
+
+ def test_no_acceleration(self):
+ # GitHub issue 5460
+ ks = 2
+ kl = 6
+ m = 1.3
+ n0 = 1.001
+ i0 = ((m-1)/m)*(kl/ks/m)**(1/(m-1))
+
+ def func(n):
+ return np.log(kl/ks/n) / np.log(i0*n/(n - 1)) + 1
+
+ n = fixed_point(func, n0, method='iteration')
+ assert_allclose(n, m)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_nnls.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_nnls.py
new file mode 100644
index 0000000000000000000000000000000000000000..7ff42e2de8848b3b05d3abd2412a5d889c8a927e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_nnls.py
@@ -0,0 +1,469 @@
+import numpy as np
+from numpy.testing import assert_allclose
+from pytest import raises as assert_raises
+from scipy.optimize import nnls
+import pytest
+
+
+class TestNNLS:
+ def setup_method(self):
+ self.rng = np.random.default_rng(1685225766635251)
+
+ def test_nnls(self):
+ a = np.arange(25.0).reshape(-1, 5)
+ x = np.arange(5.0)
+ y = a @ x
+ x, res = nnls(a, y)
+ assert res < 1e-7
+ assert np.linalg.norm((a @ x) - y) < 1e-7
+
+ def test_nnls_tall(self):
+ a = self.rng.uniform(low=-10, high=10, size=[50, 10])
+ x = np.abs(self.rng.uniform(low=-2, high=2, size=[10]))
+ x[::2] = 0
+ b = a @ x
+ xact, rnorm = nnls(a, b)
+ assert_allclose(xact, x, rtol=0., atol=1e-10)
+ assert rnorm < 1e-12
+
+ def test_nnls_wide(self):
+ # If too wide then problem becomes too ill-conditioned ans starts
+ # emitting warnings, hence small m, n difference.
+ a = self.rng.uniform(low=-10, high=10, size=[100, 120])
+ x = np.abs(self.rng.uniform(low=-2, high=2, size=[120]))
+ x[::2] = 0
+ b = a @ x
+ xact, rnorm = nnls(a, b)
+ assert_allclose(xact, x, rtol=0., atol=1e-10)
+ assert rnorm < 1e-12
+
+ def test_maxiter(self):
+ # test that maxiter argument does stop iterations
+ a = self.rng.uniform(size=(5, 10))
+ b = self.rng.uniform(size=5)
+ with assert_raises(RuntimeError):
+ nnls(a, b, maxiter=1)
+
+ def test_nnls_inner_loop_case1(self):
+ # See gh-20168
+ n = np.array(
+ [3, 2, 0, 1, 1, 1, 3, 8, 14, 16, 29, 23, 41, 47, 53, 57, 67, 76,
+ 103, 89, 97, 94, 85, 95, 78, 78, 78, 77, 73, 50, 50, 56, 68, 98,
+ 95, 112, 134, 145, 158, 172, 213, 234, 222, 215, 216, 216, 206,
+ 183, 135, 156, 110, 92, 63, 60, 52, 29, 20, 16, 12, 5, 5, 5, 1, 2,
+ 3, 0, 2])
+ k = np.array(
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0.7205812007860187, 0., 1.4411624015720375,
+ 0.7205812007860187, 2.882324803144075, 5.76464960628815,
+ 5.76464960628815, 12.249880413362318, 15.132205216506394,
+ 20.176273622008523, 27.382085629868712, 48.27894045266326,
+ 47.558359251877235, 68.45521407467177, 97.99904330689854,
+ 108.0871801179028, 135.46926574777152, 140.51333415327366,
+ 184.4687874012208, 171.49832578707245, 205.36564222401535,
+ 244.27702706646033, 214.01261663344755, 228.42424064916793,
+ 232.02714665309804, 205.36564222401535, 172.9394881886445,
+ 191.67459940908097, 162.1307701768542, 153.48379576742198,
+ 110.96950492104689, 103.04311171240067, 86.46974409432225,
+ 60.528820866025576, 43.234872047161126, 23.779179625938617,
+ 24.499760826724636, 17.29394881886445, 11.5292992125763,
+ 5.76464960628815, 5.044068405502131, 3.6029060039300935, 0.,
+ 2.882324803144075, 0., 0., 0.])
+ d = np.array(
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0.003889242101538, 0., 0.007606268390096, 0.,
+ 0.025457371599973, 0.036952882091577, 0., 0.08518359183449,
+ 0.048201126400243, 0.196234990022205, 0.144116240157247,
+ 0.171145134062442, 0., 0., 0.269555036538714, 0., 0., 0.,
+ 0.010893241091872, 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0.048167058272886, 0.011238724891049, 0., 0., 0.055162603456078,
+ 0., 0., 0., 0., 0.027753339088588, 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0.])
+ # The following code sets up a system of equations such that
+ # $k_i-p_i*n_i$ is minimized for $p_i$ with weights $n_i$ and
+ # monotonicity constraints on $p_i$. This translates to a system of
+ # equations of the form $k_i - (d_1 + ... + d_i) * n_i$ and
+ # non-negativity constraints on the $d_i$. If $n_i$ is zero the
+ # system is modified such that $d_i - d_{i+1}$ is then minimized.
+ N = len(n)
+ A = np.diag(n) @ np.tril(np.ones((N, N)))
+ w = n ** 0.5
+
+ nz = (n == 0).nonzero()[0]
+ A[nz, nz] = 1
+ A[nz, np.minimum(nz + 1, N - 1)] = -1
+ w[nz] = 1
+ k[nz] = 0
+ W = np.diag(w)
+
+ # Small perturbations can already make the infinite loop go away (just
+ # uncomment the next line)
+ # k = k + 1e-10 * np.random.normal(size=N)
+ dact, _ = nnls(W @ A, W @ k)
+ assert_allclose(dact, d, rtol=0., atol=1e-10)
+
+ def test_nnls_inner_loop_case2(self):
+ # See gh-20168
+ n = np.array(
+ [1, 0, 1, 2, 2, 2, 3, 3, 5, 4, 14, 14, 19, 26, 36, 42, 36, 64, 64,
+ 64, 81, 85, 85, 95, 95, 95, 75, 76, 69, 81, 62, 59, 68, 64, 71, 67,
+ 74, 78, 118, 135, 153, 159, 210, 195, 218, 243, 236, 215, 196, 175,
+ 185, 149, 144, 103, 104, 75, 56, 40, 32, 26, 17, 9, 12, 8, 2, 1, 1,
+ 1])
+ k = np.array(
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0., 0., 0.7064355064917867, 0., 0., 2.11930651947536,
+ 0.7064355064917867, 0., 3.5321775324589333, 7.064355064917867,
+ 11.302968103868587, 16.95445215580288, 20.486629688261814,
+ 20.486629688261814, 37.44108184406469, 55.808405012851146,
+ 78.41434122058831, 103.13958394780086, 105.965325973768,
+ 125.74552015553803, 149.057891869767, 176.60887662294667,
+ 197.09550631120848, 211.930651947536, 204.86629688261814,
+ 233.8301526487814, 221.1143135319292, 195.6826352982249,
+ 197.80194181770025, 191.4440222592742, 187.91184472681525,
+ 144.11284332432447, 131.39700420747232, 116.5618585711448,
+ 93.24948685691584, 89.01087381796512, 53.68909849337579,
+ 45.211872415474346, 31.083162285638615, 24.72524272721253,
+ 16.95445215580288, 9.890097090885014, 9.890097090885014,
+ 2.8257420259671466, 2.8257420259671466, 1.4128710129835733,
+ 0.7064355064917867, 1.4128710129835733])
+ d = np.array(
+ [0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0., 0., 0.0021916146355674473, 0., 0.,
+ 0.011252740799789484, 0., 0., 0.037746623295934395,
+ 0.03602328132946222, 0.09509167709829734, 0.10505765870204821,
+ 0.01391037014274718, 0.0188296228752321, 0.20723559202324254,
+ 0.3056220879462608, 0.13304643490426477, 0., 0., 0., 0., 0., 0.,
+ 0., 0., 0., 0., 0., 0.043185876949706214, 0.0037266261379722554,
+ 0., 0., 0., 0., 0., 0.094797899357143, 0., 0., 0., 0., 0., 0., 0.,
+ 0., 0.23450935613672663, 0., 0., 0.07064355064917871])
+ # The following code sets up a system of equations such that
+ # $k_i-p_i*n_i$ is minimized for $p_i$ with weights $n_i$ and
+ # monotonicity constraints on $p_i$. This translates to a system of
+ # equations of the form $k_i - (d_1 + ... + d_i) * n_i$ and
+ # non-negativity constraints on the $d_i$. If $n_i$ is zero the
+ # system is modified such that $d_i - d_{i+1}$ is then minimized.
+ N = len(n)
+ A = np.diag(n) @ np.tril(np.ones((N, N)))
+ w = n ** 0.5
+
+ nz = (n == 0).nonzero()[0]
+ A[nz, nz] = 1
+ A[nz, np.minimum(nz + 1, N - 1)] = -1
+ w[nz] = 1
+ k[nz] = 0
+ W = np.diag(w)
+
+ dact, _ = nnls(W @ A, W @ k)
+
+ p = np.cumsum(dact)
+ assert np.all(dact >= 0)
+ assert np.linalg.norm(k - n * p, ord=np.inf) < 28
+ assert_allclose(dact, d, rtol=0., atol=1e-10)
+
+ def test_nnls_gh20302(self):
+ # See gh-20302
+ A = np.array(
+ [0.33408569134321575, 0.11136189711440525, 0.049140798007949286,
+ 0.03712063237146841, 0.055680948557202625, 0.16642814595936478,
+ 0.11095209730624318, 0.09791993030943345, 0.14793612974165757,
+ 0.44380838922497273, 0.11099502671044059, 0.11099502671044059,
+ 0.14693672599330593, 0.3329850801313218, 1.498432860590948,
+ 0.0832374225132955, 0.11098323001772734, 0.19589481249472837,
+ 0.5919105600945457, 3.5514633605672747, 0.06658716751427037,
+ 0.11097861252378394, 0.24485832778293645, 0.9248217710315328,
+ 6.936163282736496, 0.05547609388181014, 0.11095218776362029,
+ 0.29376003042571264, 1.3314262531634435, 11.982836278470993,
+ 0.047506113282944136, 0.11084759766020298, 0.3423969672933396,
+ 1.8105107617833156, 19.010362998724812, 0.041507335004505576,
+ 0.11068622667868154, 0.39074115283013344, 2.361306169145206,
+ 28.335674029742474, 0.03682846280947718, 0.11048538842843154,
+ 0.4387861797121048, 2.9831054875676517, 40.2719240821633,
+ 0.03311278164362387, 0.11037593881207958, 0.4870572300443105,
+ 3.6791979604026523, 55.187969406039784, 0.030079304092299915,
+ 0.11029078167176636, 0.5353496017200152, 4.448394860761242,
+ 73.3985152025605, 0.02545939709595835, 0.11032405408248619,
+ 0.6328767609778363, 6.214921713313388, 121.19097340961108,
+ 0.022080881724881523, 0.11040440862440762, 0.7307742886903428,
+ 8.28033064683057, 186.30743955368786, 0.020715838214945492,
+ 0.1104844704797093, 0.7800578384588346, 9.42800814760186,
+ 226.27219554244465, 0.01843179728340054, 0.11059078370040323,
+ 0.8784095015912599, 11.94380463964355, 322.48272527037585,
+ 0.015812787653789077, 0.11068951357652354, 1.0257259848595766,
+ 16.27135849574896, 512.5477926160922, 0.014438550529330062,
+ 0.11069555405819713, 1.1234754801775881, 19.519316032262093,
+ 673.4164031130423, 0.012760770585072577, 0.110593345070629,
+ 1.2688431112524712, 24.920367089248398, 971.8943164806875,
+ 0.011427556646114315, 0.11046638091243838, 1.413623342459821,
+ 30.967408782453557, 1347.0822820367298, 0.010033330264470307,
+ 0.11036663290917338, 1.6071533470570285, 40.063087746029936,
+ 1983.122843428482, 0.008950061496507258, 0.11038409179025618,
+ 1.802244865119193, 50.37194055362024, 2795.642700725923,
+ 0.008071078821135658, 0.11030474388885401, 1.9956465761433504,
+ 61.80742482572119, 3801.1566267818534, 0.007191031207777556,
+ 0.11026247851925586, 2.238160187262168, 77.7718015155818,
+ 5366.2543045751445, 0.00636834224248, 0.11038459886965334,
+ 2.5328963107984297, 99.49331844784753, 7760.4788389321075,
+ 0.005624259098118485, 0.11061042892966355, 2.879742607664547,
+ 128.34496770138628, 11358.529641572684, 0.0050354270614989555,
+ 0.11077939535297703, 3.2263279459292575, 160.85168205252265,
+ 15924.316523199741, 0.0044997853165982555, 0.1109947044760903,
+ 3.6244287189055613, 202.60233390369015, 22488.859063309606,
+ 0.004023601950058174, 0.1113196539516095, 4.07713905729421,
+ 255.6270320242126, 31825.565487014468, 0.0036024117873727094,
+ 0.111674765408554, 4.582933773135057, 321.9583486728612,
+ 44913.18963986413, 0.003201503089582304, 0.11205260813538065,
+ 5.191786833370116, 411.79333489752383, 64857.45024636,
+ 0.0028633044552448853, 0.11262330857296549, 5.864295861648949,
+ 522.7223161899905, 92521.84996562831, 0.0025691897303891965,
+ 0.11304434813712465, 6.584584405106342, 656.5615739804199,
+ 129999.19164812315, 0.0022992911894424675, 0.11343169867916175,
+ 7.4080129906658305, 828.2026426227864, 183860.98666225857,
+ 0.0020449922071108764, 0.11383789952917212, 8.388975556433872,
+ 1058.2750599896935, 265097.9025274183, 0.001831274615120854,
+ 0.11414945100919989, 9.419351803810935, 1330.564050780237,
+ 373223.2162438565, 0.0016363333454631633, 0.11454333418242145,
+ 10.6143816579462, 1683.787012481595, 530392.9089317025,
+ 0.0014598610433380044, 0.11484240207592301, 11.959688127956882,
+ 2132.0874753402027, 754758.9662704318, 0.0012985240015312626,
+ 0.11513579480243862, 13.514425358573531, 2715.5160990137824,
+ 1083490.9235064993, 0.0011614735761289934, 0.11537304189548002,
+ 15.171418602667567, 3415.195870828736, 1526592.554260445,
+ 0.0010347472698811352, 0.11554677847006009, 17.080800985009617,
+ 4322.412404600832, 2172012.2333119176, 0.0009232988811258664,
+ 0.1157201264344419, 19.20004861829407, 5453.349531598553,
+ 3075689.135821584, 0.0008228871862975205, 0.11602709326795038,
+ 21.65735242414206, 6920.203923780365, 4390869.389638642,
+ 0.00073528900066722, 0.11642075843897651, 24.40223571298994,
+ 8755.811207598026, 6238515.485413593, 0.0006602764384729194,
+ 0.11752920604817965, 27.694443541914293, 11171.386093291572,
+ 8948280.260726549, 0.0005935538977939806, 0.11851292825953147,
+ 31.325508920763063, 14174.185724149384, 12735505.873148222,
+ 0.0005310755355633124, 0.11913794514470308, 35.381052949627765,
+ 17987.010118815077, 18157886.71494382, 0.00047239949671590953,
+ 0.1190446731724092, 39.71342528048061, 22679.438775422022,
+ 25718483.571328573, 0.00041829129789387623, 0.11851586773659825,
+ 44.45299332965028, 28542.57147989741, 36391778.63686921,
+ 0.00037321512015419886, 0.11880681324908665, 50.0668539579632,
+ 36118.26128449941, 51739409.29004541, 0.0003315539616702064,
+ 0.1184752823034871, 56.04387059062639, 45383.29960621684,
+ 72976345.76679668, 0.00029456064937920213, 0.11831519416731286,
+ 62.91195073220101, 57265.53993693082, 103507463.43600245,
+ 0.00026301867496859703, 0.11862142241083726, 70.8217262087034,
+ 72383.14781936012, 146901598.49939138, 0.00023618734450420032,
+ 0.11966825454879482, 80.26535457124461, 92160.51176984518,
+ 210125966.835247, 0.00021165918071578316, 0.12043407382728061,
+ 90.7169587544247, 116975.56852918258, 299515943.218972,
+ 0.00018757727511329545, 0.11992440455576689, 101.49899864101785,
+ 147056.26174166967, 423080865.0307836, 0.00016654469159895833,
+ 0.11957908856805206, 113.65970431102812, 184937.67016486943,
+ 597533612.3026931, 0.00014717439179415048, 0.11872067604728138,
+ 126.77899683346702, 231758.58906776624, 841283678.3159915,
+ 0.00012868496382376066, 0.1166314722122684, 139.93635237349534,
+ 287417.30847929465, 1172231492.6328032, 0.00011225559452625302,
+ 0.11427619522772557, 154.0034283704458, 355281.4912295324,
+ 1627544511.322488, 9.879511142981067e-05, 0.11295574406808354,
+ 170.96532050841535, 442971.0111288653, 2279085852.2580123,
+ 8.71257780313587e-05, 0.11192758284428547, 190.35067416684697,
+ 554165.2523674504, 3203629323.93623, 7.665069027765277e-05,
+ 0.11060694607065294, 211.28835951100046, 690933.608546013,
+ 4486577387.093535, 6.734021094824451e-05, 0.10915848194710433,
+ 234.24338803525194, 860487.9079859136, 6276829044.8032465,
+ 5.9191625040287665e-05, 0.10776821865668373, 259.7454711820425,
+ 1071699.0387579766, 8780430224.544102, 5.1856803674907676e-05,
+ 0.10606444911641115, 287.1843540288165, 1331126.3723998806,
+ 12251687131.5685, 4.503421404759231e-05, 0.10347361247668461,
+ 314.7338642485931, 1638796.0697522392, 16944331963.203278,
+ 3.90470387455642e-05, 0.1007804070023012, 344.3427560918527,
+ 2014064.4865519698, 23392351979.057854, 3.46557661636393e-05,
+ 0.10046706610839032, 385.56603915081587, 2533036.2523656,
+ 33044724430.235435, 3.148745865254635e-05, 0.1025441570117926,
+ 442.09038234164746, 3262712.3882769793, 47815050050.199135,
+ 2.9790762078715404e-05, 0.1089845379379672, 527.8068231298969,
+ 4375751.903321453, 72035815708.42941, 2.8772639817606534e-05,
+ 0.11823636789048445, 643.2048194503195, 5989838.001888927,
+ 110764084330.93005, 2.7951691815106586e-05, 0.12903432664913705,
+ 788.5500418523591, 8249371.000613411, 171368308481.2427,
+ 2.6844392423114212e-05, 0.1392060709754626, 955.6296403631383,
+ 11230229.319931043, 262063016295.25085, 2.499458273851386e-05,
+ 0.14559344445184325, 1122.7022399726002, 14820229.698461473,
+ 388475270970.9214, 2.337386729019776e-05, 0.15294300496886065,
+ 1324.8158105672455, 19644861.137128454, 578442936182.7473,
+ 2.0081014872174113e-05, 0.14760215298210377, 1436.2385042492353,
+ 23923681.729276657, 791311658718.4193, 1.773374462991839e-05,
+ 0.14642752940923615, 1600.5596278736678, 29949429.82503553,
+ 1112815989293.9326, 1.5303115839590797e-05, 0.14194150045081785,
+ 1742.873058605698, 36634451.931305364, 1529085389160.7544,
+ 1.3148448731163076e-05, 0.13699368732998807, 1889.5284359054356,
+ 44614279.74469635, 2091762812969.9607, 1.1739194407590062e-05,
+ 0.13739553134643406, 2128.794599579694, 56462810.11822766,
+ 2973783283306.8145, 1.0293367506254706e-05, 0.13533033372723272,
+ 2355.372854690074, 70176508.28667311, 4151852759764.441,
+ 9.678312586863569e-06, 0.14293577249119244, 2794.531827932675,
+ 93528671.31952812, 6215821967224.52, -1.174086323572049e-05,
+ 0.1429501325944908, 3139.4804810720925, 118031680.16618933,
+ -6466892421886.174, -2.1188265307407812e-05, 0.1477108290912869,
+ 3644.1133424610953, 153900132.62392554, -4828013117542.036,
+ -8.614483025123122e-05, 0.16037100755883044, 4444.386620899393,
+ 210846007.89660168, -1766340937974.433, 4.981445776141726e-05,
+ 0.16053420251962536, 4997.558254401547, 266327328.4755411,
+ 3862250287024.725, 1.8500019169456637e-05, 0.15448417164977674,
+ 5402.289867444643, 323399508.1475582, 12152445411933.408,
+ -5.647882376069748e-05, 0.1406372975946189, 5524.633133597753,
+ 371512945.9909363, -4162951345292.1514, 2.8048523486337994e-05,
+ 0.13183417571186926, 5817.462495763679, 439447252.3728975,
+ 9294740538175.03]).reshape(89, 5)
+ b = np.ones(89, dtype=np.float64)
+ sol, rnorm = nnls(A, b)
+ assert_allclose(sol, np.array([0.61124315, 8.22262829, 0., 0., 0.]))
+ assert_allclose(rnorm, 1.0556460808977297)
+
+ def test_nnls_gh21021_ex1(self):
+ # Review examples used in gh-21021
+ A = [[0.004734199143798789, -0.09661916455815653, -0.04308779048103441,
+ 0.4039475561867938, -0.27742598780954364, -0.20816924034369574,
+ -0.17264070902176, 0.05251808558963846],
+ [-0.030263548855047975, -0.30356483926431466, 0.18080406600591398,
+ -0.06892233941254086, -0.41837298885432317, 0.30245352819647003,
+ -0.19008975278116397, -0.00990809825429995],
+ [-0.2561747595787612, -0.04376282125249583, 0.4422181991706678,
+ -0.13720906318924858, -0.0069523811763796475, -0.059238287107464795,
+ 0.028663214369642594, 0.5415531284893763],
+ [0.2949336072968401, 0.33997647534935094, 0.38441519339815755,
+ -0.306001783010386, 0.18120773805949028, -0.36669767490747895,
+ -0.021539960590992304, -0.2784251712424615],
+ [0.5009075736232653, -0.20161970347571165, 0.08404512586550646,
+ 0.2520496489348788, 0.14812015101612894, -0.25823455803981266,
+ -0.1596872058396596, 0.5960141613922691]
+ ]
+ b = [18.036779281222124, -18.126530733870887, 13.535652034584029,
+ -2.6654275476795966, 9.166315328199575]
+
+ # Obtained from matlab's lstnonneg
+ des_sol = np.array([0., 118.017802006619, 45.1996532316584, 102.62156313537,
+ 0., 55.8590204314398, 0., 29.7328833253434])
+ sol, res = nnls(A, b)
+ assert_allclose(sol, des_sol)
+ assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14
+
+ def test_nnls_gh21021_ex2(self):
+ A = np.array([
+ [0.2508259992635229, -0.24031300195203256],
+ [0.510647748500133, 0.2872936081767836],
+ [0.8196387904102849, -0.03520620107046682],
+ [0.030739759120097084, -0.07768656359879388]])
+ b = np.array([24.456141951303913,
+ 28.047143273432333,
+ 41.10526799545987,
+ -1.2078282698324068])
+
+ sol, res = nnls(A, b)
+ assert_allclose(sol, np.array([54.3047953202271, 0.0]))
+ assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14
+
+ def test_nnls_gh21021_ex3(self):
+ A = np.array([
+ [0.08247592017366788, 0.058398241636675674, -0.1031496693415968,
+ 0.03156983127072098, -0.029503680182026665],
+ [0.21463607509982277, -0.2164518969308173, -0.10816833396662294,
+ 0.12133867146012027, -0.15025010408668332],
+ [0.07251900316494089, -0.003044559315020767, 0.042682817961676424,
+ -0.018157525489298176, 0.11561953260568134],
+ [0.2328797918159187, -0.09112909645892767, 0.21348169727099078,
+ 0.00449447624089599, -0.16615256386885716],
+ [-0.02440856024843897, -0.20131427208575386, 0.030275781997161483,
+ -0.04560777213546784, 0.11007266012013553],
+ [-0.2928391429686263, -0.20437574856615687, -0.020892110811574407,
+ -0.10455040720819309, 0.05337267000160461],
+ [0.22041503019400316, 0.014262782992311842, 0.08274606359871121,
+ -0.17933172096518907, -0.11809690350702161],
+ [0.10440436007469953, 0.09171452270577712, 0.03942347724809893,
+ 0.11457669688231396, 0.07529747295631585],
+ [-0.052087576116032056, -0.15787717158077047, -0.08232202515883282,
+ -0.03194837933710708, -0.0546812506025729],
+ [-0.010388407673304468, 0.015174707581808923, 0.04764509565386281,
+ -0.1781221936030805, 0.10218894080536609],
+ [0.03272263140115928, -0.27576456949442574, 0.024897570959901753,
+ -0.1417129166632282, -0.03320796462136591],
+ [-0.12490006751823997, -0.03012003515442302, -0.051495264012509506,
+ 0.012070729698374614, 0.04811700123118234],
+ [0.15254854117990788, -0.051863547789218374, 0.058012914127346174,
+ -0.06717991061422621, -0.14514671564242257],
+ [0.12251250415395559, -0.17462495626695362, -0.025334728552179834,
+ 0.11425350676877533, 0.06183915953812639],
+ [0.19334259720491218, 0.2164301986218955, -0.018882278726614483,
+ 0.07950236716817938, -0.2220529357431092],
+ [-0.01822205701890852, 0.12630444976752267, -0.03118092027244001,
+ 0.02773743885242581, 0.06444433740044248],
+ [0.13344116850581977, -0.05142877469996826, 0.3385702016705455,
+ -0.25814970787123004, 0.2679034842977378],
+ [0.1309747058619377, 0.12090608957940627, -0.13957978654106512,
+ 0.17048819760322642, -0.241775259969348],
+ [0.28613102173467275, -0.47153463906732174, 0.20359970518269746,
+ -0.0962095202871843, -0.07703076550836387],
+ [0.2212788380372723, 0.02569245145758152, -0.021596152392209966,
+ 0.04610005150029433, -0.2024454395619734],
+ [-0.043225338359410316, 0.17816095186290315, -0.014709092962616079,
+ 0.06993970293287989, -0.09033722782555903],
+ [0.17747622942563512, -0.20991014784011458, 0.06265720409894943,
+ 0.0689704059061795, 0.024474319398401525],
+ [-0.1163880385601698, 0.29989570587630027, 0.033443765320984545,
+ 0.008470296514656, -0.0014457113271462002],
+ [0.024375314902718406, 0.05279830705548363, 0.02691082431023144,
+ 0.05265079368002343, 0.15542988147487913],
+ [-0.01855218360922308, -0.050265869142888164, 0.2567912677240452,
+ -0.2606428528561333, 0.25334396245022245]])
+
+ b = np.array([-7.876625373734849, -8.259856278691373, 3.2593082374900963,
+ 16.30170376973345, 2.311892943629045, -1.595345202555738,
+ 6.318582970536518, 3.0104212955340093, -6.286202915842167,
+ 3.6382333725029294, 1.9012066681249356, -3.932236581436514,
+ 4.4299317131740406, -1.9345885161292682, -1.4418721521970805,
+ -2.3810103256943926, 25.853603392922526, -10.658470311610483,
+ 15.547103681119214, -1.6491066136547277, -1.1232029689817422,
+ 4.7845749463206975, 2.553803732013229, 2.0549409701753705,
+ 19.60887153608244])
+
+ sol, res = nnls(A, b)
+ assert_allclose(sol, np.array([0.0, 0.0, 76.3611306173957, 0.0, 0.0]),
+ atol=5e-14)
+ assert np.abs(np.linalg.norm(A@sol - b) - res) < 5e-14
+
+ def test_atol_deprecation_warning(self):
+ """Test that using atol parameter triggers deprecation warning"""
+ a = np.array([[1, 0], [1, 0], [0, 1]])
+ b = np.array([2, 1, 1])
+
+ with pytest.warns(DeprecationWarning, match="{'atol'}"):
+ nnls(a, b, atol=1e-8)
+
+ def test_2D_singleton_RHS_input(self):
+ # Test that a 2D singleton RHS input is accepted
+ A = np.array([[1.0, 0.5, -1.],
+ [1.0, 0.5, 0.0],
+ [-1., 0.0, 1.0]])
+ b = np.array([[-1.0, 2.0, 2.0]]).T
+ x, r = nnls(A, b)
+ assert_allclose(x, np.array([1.0, 2.0, 3.0]))
+ assert_allclose(r, 0.0)
+
+ def test_2D_not_singleton_RHS_input_2(self):
+ # Test that a 2D but not a column vector RHS input is rejected
+ A = np.array([[1.0, 0.5, -1.],
+ [1.0, 0.5, 0.0],
+ [1.0, 0.5, 0.0],
+ [0.0, 0.0, 1.0]])
+ b = np.ones(shape=[4, 2], dtype=np.float64)
+ with pytest.raises(ValueError, match="Expected a 1D array"):
+ nnls(A, b)
+
+ def test_gh_22791_32bit(self):
+ # Scikit-learn got hit by this problem on 32-bit arch.
+ desired = [0, 0, 1.05617285, 0, 0, 0, 0, 0.23123048, 0, 0, 0, 0.26128651]
+ rng = np.random.RandomState(42)
+ n_samples, n_features = 5, 12
+ X = rng.randn(n_samples, n_features)
+ X[:2, :] = 0
+ y = rng.randn(n_samples)
+ coef, _ = nnls(X, y)
+ assert_allclose(coef, desired)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_nonlin.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_nonlin.py
new file mode 100644
index 0000000000000000000000000000000000000000..3cfc3a284ce3a3cfad81f447e72199a80f4fc572
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_nonlin.py
@@ -0,0 +1,571 @@
+""" Unit tests for nonlinear solvers
+Author: Ondrej Certik
+May 2007
+"""
+from numpy.testing import assert_
+import pytest
+from functools import partial
+
+from scipy.optimize import _nonlin as nonlin, root
+from scipy.sparse import csr_array
+from numpy import diag, dot
+from numpy.linalg import inv
+import numpy as np
+import scipy
+from scipy.sparse.linalg import minres
+
+from .test_minpack import pressure_network
+
+SOLVERS = {'anderson': nonlin.anderson,
+ 'diagbroyden': nonlin.diagbroyden,
+ 'linearmixing': nonlin.linearmixing,
+ 'excitingmixing': nonlin.excitingmixing,
+ 'broyden1': nonlin.broyden1,
+ 'broyden2': nonlin.broyden2,
+ 'krylov': nonlin.newton_krylov}
+MUST_WORK = {'anderson': nonlin.anderson, 'broyden1': nonlin.broyden1,
+ 'broyden2': nonlin.broyden2, 'krylov': nonlin.newton_krylov}
+
+# ----------------------------------------------------------------------------
+# Test problems
+# ----------------------------------------------------------------------------
+
+
+def F(x):
+ x = np.asarray(x).T
+ d = diag([3, 2, 1.5, 1, 0.5])
+ c = 0.01
+ f = -d @ x - c * float(x.T @ x) * x
+ return f
+
+
+F.xin = [1, 1, 1, 1, 1]
+F.KNOWN_BAD = {}
+F.JAC_KSP_BAD = {}
+F.ROOT_JAC_KSP_BAD = {}
+
+
+def F2(x):
+ return x
+
+
+F2.xin = [1, 2, 3, 4, 5, 6]
+F2.KNOWN_BAD = {'linearmixing': nonlin.linearmixing,
+ 'excitingmixing': nonlin.excitingmixing}
+F2.JAC_KSP_BAD = {}
+F2.ROOT_JAC_KSP_BAD = {}
+
+
+def F2_lucky(x):
+ return x
+
+
+F2_lucky.xin = [0, 0, 0, 0, 0, 0]
+F2_lucky.KNOWN_BAD = {}
+F2_lucky.JAC_KSP_BAD = {}
+F2_lucky.ROOT_JAC_KSP_BAD = {}
+
+
+def F3(x):
+ A = np.array([[-2, 1, 0.], [1, -2, 1], [0, 1, -2]])
+ b = np.array([1, 2, 3.])
+ return A @ x - b
+
+
+F3.xin = [1, 2, 3]
+F3.KNOWN_BAD = {}
+F3.JAC_KSP_BAD = {}
+F3.ROOT_JAC_KSP_BAD = {}
+
+
+def F4_powell(x):
+ A = 1e4
+ return [A*x[0]*x[1] - 1, np.exp(-x[0]) + np.exp(-x[1]) - (1 + 1/A)]
+
+
+F4_powell.xin = [-1, -2]
+F4_powell.KNOWN_BAD = {'linearmixing': nonlin.linearmixing,
+ 'excitingmixing': nonlin.excitingmixing,
+ 'diagbroyden': nonlin.diagbroyden}
+# In the extreme case, it does not converge for nolinear problem solved by
+# MINRES and root problem solved by GMRES/BiCGStab/CGS/MINRES/TFQMR when using
+# Krylov method to approximate Jacobian
+F4_powell.JAC_KSP_BAD = {'minres'}
+F4_powell.ROOT_JAC_KSP_BAD = {'gmres', 'bicgstab', 'cgs', 'minres', 'tfqmr'}
+
+
+def F5(x):
+ return pressure_network(x, 4, np.array([.5, .5, .5, .5]))
+
+
+F5.xin = [2., 0, 2, 0]
+F5.KNOWN_BAD = {'excitingmixing': nonlin.excitingmixing,
+ 'linearmixing': nonlin.linearmixing,
+ 'diagbroyden': nonlin.diagbroyden}
+# In the extreme case, the Jacobian inversion yielded zero vector for nonlinear
+# problem solved by CGS/MINRES and it does not converge for root problem solved
+# by MINRES and when using Krylov method to approximate Jacobian
+F5.JAC_KSP_BAD = {'cgs', 'minres'}
+F5.ROOT_JAC_KSP_BAD = {'minres'}
+
+
+def F6(x):
+ x1, x2 = x
+ J0 = np.array([[-4.256, 14.7],
+ [0.8394989, 0.59964207]])
+ v = np.array([(x1 + 3) * (x2**5 - 7) + 3*6,
+ np.sin(x2 * np.exp(x1) - 1)])
+ return -np.linalg.solve(J0, v)
+
+
+F6.xin = [-0.5, 1.4]
+F6.KNOWN_BAD = {'excitingmixing': nonlin.excitingmixing,
+ 'linearmixing': nonlin.linearmixing,
+ 'diagbroyden': nonlin.diagbroyden}
+F6.JAC_KSP_BAD = {}
+F6.ROOT_JAC_KSP_BAD = {}
+
+
+# ----------------------------------------------------------------------------
+# Tests
+# ----------------------------------------------------------------------------
+
+
+class TestNonlin:
+ """
+ Check the Broyden methods for a few test problems.
+
+ broyden1, broyden2, and newton_krylov must succeed for
+ all functions. Some of the others don't -- tests in KNOWN_BAD are skipped.
+
+ """
+
+ def _check_nonlin_func(self, f, func, f_tol=1e-2):
+ # Test all methods mentioned in the class `KrylovJacobian`
+ if func == SOLVERS['krylov']:
+ for method in ['gmres', 'bicgstab', 'cgs', 'minres', 'tfqmr']:
+ if method in f.JAC_KSP_BAD:
+ continue
+
+ x = func(f, f.xin, method=method, line_search=None,
+ f_tol=f_tol, maxiter=200, verbose=0)
+ assert_(np.absolute(f(x)).max() < f_tol)
+
+ x = func(f, f.xin, f_tol=f_tol, maxiter=200, verbose=0)
+ assert_(np.absolute(f(x)).max() < f_tol)
+
+ def _check_root(self, f, method, f_tol=1e-2):
+ # Test Krylov methods
+ if method == 'krylov':
+ for jac_method in ['gmres', 'bicgstab', 'cgs', 'minres', 'tfqmr']:
+ if jac_method in f.ROOT_JAC_KSP_BAD:
+ continue
+
+ res = root(f, f.xin, method=method,
+ options={'ftol': f_tol, 'maxiter': 200,
+ 'disp': 0,
+ 'jac_options': {'method': jac_method}})
+ assert_(np.absolute(res.fun).max() < f_tol)
+
+ res = root(f, f.xin, method=method,
+ options={'ftol': f_tol, 'maxiter': 200, 'disp': 0})
+ assert_(np.absolute(res.fun).max() < f_tol)
+
+ @pytest.mark.xfail
+ def _check_func_fail(self, *a, **kw):
+ pass
+
+ @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+ def test_problem_nonlin(self):
+ for f in [F, F2, F2_lucky, F3, F4_powell, F5, F6]:
+ for func in SOLVERS.values():
+ if func in f.KNOWN_BAD.values():
+ if func in MUST_WORK.values():
+ self._check_func_fail(f, func)
+ continue
+ self._check_nonlin_func(f, func)
+
+ @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+ @pytest.mark.parametrize("method", ['lgmres', 'gmres', 'bicgstab', 'cgs',
+ 'minres', 'tfqmr'])
+ def test_tol_norm_called(self, method):
+ # Check that supplying tol_norm keyword to nonlin_solve works
+ self._tol_norm_used = False
+
+ def local_norm_func(x):
+ self._tol_norm_used = True
+ return np.absolute(x).max()
+
+ nonlin.newton_krylov(F, F.xin, method=method, f_tol=1e-2,
+ maxiter=200, verbose=0,
+ tol_norm=local_norm_func)
+ assert_(self._tol_norm_used)
+
+ @pytest.mark.filterwarnings('ignore::DeprecationWarning')
+ def test_problem_root(self):
+ for f in [F, F2, F2_lucky, F3, F4_powell, F5, F6]:
+ for meth in SOLVERS:
+ if meth in f.KNOWN_BAD:
+ if meth in MUST_WORK:
+ self._check_func_fail(f, meth)
+ continue
+ self._check_root(f, meth)
+
+ def test_no_convergence(self):
+ def wont_converge(x):
+ return 1e3 + x
+
+ with pytest.raises(scipy.optimize.NoConvergence):
+ nonlin.newton_krylov(wont_converge, xin=[0], maxiter=1)
+
+ def test_warnings_invalid_inner_param(self):
+ """
+ Test for ENH #21986, for behavior of `nonlin.newton_krylov`
+ Test the following scenarios:
+ 1. Raise warning for invalid inner param
+ 2. No warning for valid inner param
+ 3. No warning for user-provided callable method
+ """
+ # This should raise exactly one warning
+ # (`inner_atol` is not valid for `minres`)
+ with pytest.warns(UserWarning,
+ match="Please check inner method documentation"):
+ nonlin.newton_krylov(F, F.xin, method="minres", inner_atol=1e-5)
+
+ # This should not raise a warning (`minres` without `inner_atol`,
+ # but with `inner_maxiter` which is valid)
+ nonlin.newton_krylov(F, F.xin, method="minres", inner_maxiter=100,
+ inner_callback= lambda _ : ...)
+
+ # Test newton_krylov with a user-provided callable method
+ def user_provided_callable_method_enh_21986(op, rhs, **kwargs):
+ """A dummy user-provided callable method for testing."""
+ # Return a dummy result (mimicking minres)
+ return minres(op, rhs, **kwargs)
+ # This should not raise any warnings
+ nonlin.newton_krylov(F, F.xin,
+ method=user_provided_callable_method_enh_21986)
+
+ def test_non_inner_prefix(self):
+ with pytest.raises(ValueError,
+ match="Unknown parameter"
+ ):
+ # Pass a parameter without 'inner_' prefix
+ nonlin.newton_krylov(F, F.xin, method="minres", invalid_param=1e-5)
+
+
+class TestSecant:
+ """Check that some Jacobian approximations satisfy the secant condition"""
+
+ xs = [np.array([1., 2., 3., 4., 5.]),
+ np.array([2., 3., 4., 5., 1.]),
+ np.array([3., 4., 5., 1., 2.]),
+ np.array([4., 5., 1., 2., 3.]),
+ np.array([9., 1., 9., 1., 3.]),
+ np.array([0., 1., 9., 1., 3.]),
+ np.array([5., 5., 7., 1., 1.]),
+ np.array([1., 2., 7., 5., 1.]),]
+ fs = [x**2 - 1 for x in xs]
+
+ def _check_secant(self, jac_cls, npoints=1, **kw):
+ """
+ Check that the given Jacobian approximation satisfies secant
+ conditions for last `npoints` points.
+ """
+ jac = jac_cls(**kw)
+ jac.setup(self.xs[0], self.fs[0], None)
+ for j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])):
+ jac.update(x, f)
+
+ for k in range(min(npoints, j+1)):
+ dx = self.xs[j-k+1] - self.xs[j-k]
+ df = self.fs[j-k+1] - self.fs[j-k]
+ assert_(np.allclose(dx, jac.solve(df)))
+
+ # Check that the `npoints` secant bound is strict
+ if j >= npoints:
+ dx = self.xs[j-npoints+1] - self.xs[j-npoints]
+ df = self.fs[j-npoints+1] - self.fs[j-npoints]
+ assert_(not np.allclose(dx, jac.solve(df)))
+
+ def test_broyden1(self):
+ self._check_secant(nonlin.BroydenFirst)
+
+ def test_broyden2(self):
+ self._check_secant(nonlin.BroydenSecond)
+
+ def test_broyden1_update(self):
+ # Check that BroydenFirst update works as for a dense matrix
+ jac = nonlin.BroydenFirst(alpha=0.1)
+ jac.setup(self.xs[0], self.fs[0], None)
+
+ B = np.identity(5) * (-1/0.1)
+
+ for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])):
+ df = f - self.fs[last_j]
+ dx = x - self.xs[last_j]
+ B += (df - dot(B, dx))[:, None] * dx[None, :] / dot(dx, dx)
+ jac.update(x, f)
+ assert_(np.allclose(jac.todense(), B, rtol=1e-10, atol=1e-13))
+
+ def test_broyden2_update(self):
+ # Check that BroydenSecond update works as for a dense matrix
+ jac = nonlin.BroydenSecond(alpha=0.1)
+ jac.setup(self.xs[0], self.fs[0], None)
+
+ H = np.identity(5) * (-0.1)
+
+ for last_j, (x, f) in enumerate(zip(self.xs[1:], self.fs[1:])):
+ df = f - self.fs[last_j]
+ dx = x - self.xs[last_j]
+ H += (dx - dot(H, df))[:, None] * df[None, :] / dot(df, df)
+ jac.update(x, f)
+ assert_(np.allclose(jac.todense(), inv(H), rtol=1e-10, atol=1e-13))
+
+ def test_anderson(self):
+ # Anderson mixing (with w0=0) satisfies secant conditions
+ # for the last M iterates, see [Ey]_
+ #
+ # .. [Ey] V. Eyert, J. Comp. Phys., 124, 271 (1996).
+ self._check_secant(nonlin.Anderson, M=3, w0=0, npoints=3)
+
+
+class TestLinear:
+ """Solve a linear equation;
+ some methods find the exact solution in a finite number of steps"""
+
+ def _check(self, jac, N, maxiter, complex=False, **kw):
+ rng = np.random.default_rng(123)
+
+ A = rng.standard_normal((N, N))
+ if complex:
+ A = A + 1j*rng.standard_normal((N, N))
+ b = rng.standard_normal(N)
+ if complex:
+ b = b + 1j*rng.standard_normal(N)
+
+ def func(x):
+ return dot(A, x) - b
+
+ sol = nonlin.nonlin_solve(func, np.zeros(N), jac, maxiter=maxiter,
+ f_tol=1e-6, line_search=None, verbose=0)
+ assert_(np.allclose(dot(A, sol), b, atol=1e-6))
+
+ def test_broyden1(self):
+ # Broyden methods solve linear systems exactly in 2*N steps
+ self._check(nonlin.BroydenFirst(alpha=1.0), 20, 41, False)
+ self._check(nonlin.BroydenFirst(alpha=1.0), 20, 41, True)
+
+ def test_broyden2(self):
+ # Broyden methods solve linear systems exactly in 2*N steps
+ self._check(nonlin.BroydenSecond(alpha=1.0), 20, 41, False)
+ self._check(nonlin.BroydenSecond(alpha=1.0), 20, 41, True)
+
+ def test_anderson(self):
+ # Anderson is rather similar to Broyden, if given enough storage space
+ self._check(nonlin.Anderson(M=50, alpha=1.0), 20, 29, False)
+ self._check(nonlin.Anderson(M=50, alpha=1.0), 20, 29, True)
+
+ def test_krylov(self):
+ # Krylov methods solve linear systems exactly in N inner steps
+ self._check(nonlin.KrylovJacobian, 20, 2, False, inner_m=10)
+ self._check(nonlin.KrylovJacobian, 20, 2, True, inner_m=10)
+
+ def _check_autojac(self, A, b):
+ def func(x):
+ return A.dot(x) - b
+
+ def jac(v):
+ return A
+
+ sol = nonlin.nonlin_solve(func, np.zeros(b.shape[0]), jac, maxiter=2,
+ f_tol=1e-6, line_search=None, verbose=0)
+ np.testing.assert_allclose(A @ sol, b, atol=1e-6)
+ # test jac input as array -- not a function
+ sol = nonlin.nonlin_solve(func, np.zeros(b.shape[0]), A, maxiter=2,
+ f_tol=1e-6, line_search=None, verbose=0)
+ np.testing.assert_allclose(A @ sol, b, atol=1e-6)
+
+ def test_jac_sparse(self):
+ A = csr_array([[1, 2], [2, 1]])
+ b = np.array([1, -1])
+ self._check_autojac(A, b)
+ self._check_autojac((1 + 2j) * A, (2 + 2j) * b)
+
+ def test_jac_ndarray(self):
+ A = np.array([[1, 2], [2, 1]])
+ b = np.array([1, -1])
+ self._check_autojac(A, b)
+ self._check_autojac((1 + 2j) * A, (2 + 2j) * b)
+
+
+class TestJacobianDotSolve:
+ """
+ Check that solve/dot methods in Jacobian approximations are consistent
+ """
+
+ def _func(self, x, A=None):
+ return x**2 - 1 + np.dot(A, x)
+
+ def _check_dot(self, jac_cls, complex=False, tol=1e-6, **kw):
+ rng = np.random.default_rng(123)
+
+ N = 7
+
+ def rand(*a):
+ q = rng.random(a)
+ if complex:
+ q = q + 1j*rng.random(a)
+ return q
+
+ def assert_close(a, b, msg):
+ d = abs(a - b).max()
+ f = tol + abs(b).max()*tol
+ if d > f:
+ raise AssertionError(f'{msg}: err {d:g}')
+
+ A = rand(N, N)
+
+ # initialize
+ x0 = rng.random(N)
+ jac = jac_cls(**kw)
+ jac.setup(x0, self._func(x0, A), partial(self._func, A=A))
+
+ # check consistency
+ for k in range(2*N):
+ v = rand(N)
+
+ if hasattr(jac, '__array__'):
+ Jd = np.array(jac)
+ if hasattr(jac, 'solve'):
+ Gv = jac.solve(v)
+ Gv2 = np.linalg.solve(Jd, v)
+ assert_close(Gv, Gv2, 'solve vs array')
+ if hasattr(jac, 'rsolve'):
+ Gv = jac.rsolve(v)
+ Gv2 = np.linalg.solve(Jd.T.conj(), v)
+ assert_close(Gv, Gv2, 'rsolve vs array')
+ if hasattr(jac, 'matvec'):
+ Jv = jac.matvec(v)
+ Jv2 = np.dot(Jd, v)
+ assert_close(Jv, Jv2, 'dot vs array')
+ if hasattr(jac, 'rmatvec'):
+ Jv = jac.rmatvec(v)
+ Jv2 = np.dot(Jd.T.conj(), v)
+ assert_close(Jv, Jv2, 'rmatvec vs array')
+
+ if hasattr(jac, 'matvec') and hasattr(jac, 'solve'):
+ Jv = jac.matvec(v)
+ Jv2 = jac.solve(jac.matvec(Jv))
+ assert_close(Jv, Jv2, 'dot vs solve')
+
+ if hasattr(jac, 'rmatvec') and hasattr(jac, 'rsolve'):
+ Jv = jac.rmatvec(v)
+ Jv2 = jac.rmatvec(jac.rsolve(Jv))
+ assert_close(Jv, Jv2, 'rmatvec vs rsolve')
+
+ x = rand(N)
+ jac.update(x, self._func(x, A))
+
+ def test_broyden1(self):
+ self._check_dot(nonlin.BroydenFirst, complex=False)
+ self._check_dot(nonlin.BroydenFirst, complex=True)
+
+ def test_broyden2(self):
+ self._check_dot(nonlin.BroydenSecond, complex=False)
+ self._check_dot(nonlin.BroydenSecond, complex=True)
+
+ def test_anderson(self):
+ self._check_dot(nonlin.Anderson, complex=False)
+ self._check_dot(nonlin.Anderson, complex=True)
+
+ def test_diagbroyden(self):
+ self._check_dot(nonlin.DiagBroyden, complex=False)
+ self._check_dot(nonlin.DiagBroyden, complex=True)
+
+ def test_linearmixing(self):
+ self._check_dot(nonlin.LinearMixing, complex=False)
+ self._check_dot(nonlin.LinearMixing, complex=True)
+
+ def test_excitingmixing(self):
+ self._check_dot(nonlin.ExcitingMixing, complex=False)
+ self._check_dot(nonlin.ExcitingMixing, complex=True)
+
+ def test_krylov(self):
+ self._check_dot(nonlin.KrylovJacobian, complex=False, tol=1e-3)
+ self._check_dot(nonlin.KrylovJacobian, complex=True, tol=1e-3)
+
+
+class TestNonlinOldTests:
+ """ Test case for a simple constrained entropy maximization problem
+ (the machine translation example of Berger et al in
+ Computational Linguistics, vol 22, num 1, pp 39--72, 1996.)
+ """
+
+ def test_broyden1(self):
+ x = nonlin.broyden1(F, F.xin, iter=12, alpha=1)
+ assert_(nonlin.norm(x) < 1e-9)
+ assert_(nonlin.norm(F(x)) < 1e-9)
+
+ def test_broyden2(self):
+ x = nonlin.broyden2(F, F.xin, iter=12, alpha=1)
+ assert_(nonlin.norm(x) < 1e-9)
+ assert_(nonlin.norm(F(x)) < 1e-9)
+
+ def test_anderson(self):
+ x = nonlin.anderson(F, F.xin, iter=12, alpha=0.03, M=5)
+ assert_(nonlin.norm(x) < 0.33)
+
+ def test_linearmixing(self):
+ x = nonlin.linearmixing(F, F.xin, iter=60, alpha=0.5)
+ assert_(nonlin.norm(x) < 1e-7)
+ assert_(nonlin.norm(F(x)) < 1e-7)
+
+ def test_exciting(self):
+ x = nonlin.excitingmixing(F, F.xin, iter=20, alpha=0.5)
+ assert_(nonlin.norm(x) < 1e-5)
+ assert_(nonlin.norm(F(x)) < 1e-5)
+
+ def test_diagbroyden(self):
+ x = nonlin.diagbroyden(F, F.xin, iter=11, alpha=1)
+ assert_(nonlin.norm(x) < 1e-8)
+ assert_(nonlin.norm(F(x)) < 1e-8)
+
+ def test_root_broyden1(self):
+ res = root(F, F.xin, method='broyden1',
+ options={'nit': 12, 'jac_options': {'alpha': 1}})
+ assert_(nonlin.norm(res.x) < 1e-9)
+ assert_(nonlin.norm(res.fun) < 1e-9)
+
+ def test_root_broyden2(self):
+ res = root(F, F.xin, method='broyden2',
+ options={'nit': 12, 'jac_options': {'alpha': 1}})
+ assert_(nonlin.norm(res.x) < 1e-9)
+ assert_(nonlin.norm(res.fun) < 1e-9)
+
+ def test_root_anderson(self):
+ res = root(F, F.xin, method='anderson',
+ options={'nit': 12,
+ 'jac_options': {'alpha': 0.03, 'M': 5}})
+ assert_(nonlin.norm(res.x) < 0.33)
+
+ def test_root_linearmixing(self):
+ res = root(F, F.xin, method='linearmixing',
+ options={'nit': 60,
+ 'jac_options': {'alpha': 0.5}})
+ assert_(nonlin.norm(res.x) < 1e-7)
+ assert_(nonlin.norm(res.fun) < 1e-7)
+
+ def test_root_excitingmixing(self):
+ res = root(F, F.xin, method='excitingmixing',
+ options={'nit': 20,
+ 'jac_options': {'alpha': 0.5}})
+ assert_(nonlin.norm(res.x) < 1e-5)
+ assert_(nonlin.norm(res.fun) < 1e-5)
+
+ def test_root_diagbroyden(self):
+ res = root(F, F.xin, method='diagbroyden',
+ options={'nit': 11,
+ 'jac_options': {'alpha': 1}})
+ assert_(nonlin.norm(res.x) < 1e-8)
+ assert_(nonlin.norm(res.fun) < 1e-8)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_optimize.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_optimize.py
new file mode 100644
index 0000000000000000000000000000000000000000..80e0198068d17ee98f14302040c478e4c4812625
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_optimize.py
@@ -0,0 +1,3603 @@
+"""
+Unit tests for optimization routines from optimize.py
+
+Authors:
+ Ed Schofield, Nov 2005
+ Andrew Straw, April 2008
+
+"""
+import sys
+import itertools
+import inspect
+import platform
+import threading
+import warnings
+import multiprocessing
+
+import numpy as np
+from numpy.testing import (assert_allclose, assert_equal,
+ assert_almost_equal,
+ assert_no_warnings,
+ assert_array_less)
+import pytest
+from pytest import raises as assert_raises
+
+import scipy
+from scipy._lib._gcutils import assert_deallocated
+from scipy import optimize
+from scipy.optimize._minimize import Bounds, NonlinearConstraint
+from scipy.optimize._minimize import (MINIMIZE_METHODS,
+ MINIMIZE_METHODS_NEW_CB,
+ MINIMIZE_SCALAR_METHODS)
+from scipy.optimize._linprog import LINPROG_METHODS
+from scipy.optimize._root import ROOT_METHODS
+from scipy.optimize._root_scalar import ROOT_SCALAR_METHODS
+from scipy.optimize._qap import QUADRATIC_ASSIGNMENT_METHODS
+from scipy.optimize._differentiable_functions import ScalarFunction, FD_METHODS
+from scipy.optimize._optimize import (
+ MemoizeJac, show_options, OptimizeResult, _minimize_bfgs
+)
+from scipy.optimize import rosen, rosen_der, rosen_hess
+
+from scipy.sparse import (coo_matrix, csc_matrix, csr_matrix, coo_array,
+ csr_array, csc_array)
+from scipy._lib._array_api_no_0d import xp_assert_equal
+from scipy._lib._array_api import make_xp_test_case
+from scipy._lib._util import MapWrapper
+
+lazy_xp_modules = [optimize]
+
+
+def test_check_grad():
+ # Verify if check_grad is able to estimate the derivative of the
+ # expit (logistic sigmoid) function.
+
+ def expit(x):
+ return 1 / (1 + np.exp(-x))
+
+ def der_expit(x):
+ return np.exp(-x) / (1 + np.exp(-x))**2
+
+ x0 = np.array([1.5])
+
+ r = optimize.check_grad(expit, der_expit, x0)
+ assert_almost_equal(r, 0)
+ # SPEC-007 leave one call with seed to check it still works
+ r = optimize.check_grad(expit, der_expit, x0,
+ direction='random', seed=1234)
+ assert_almost_equal(r, 0)
+
+ r = optimize.check_grad(expit, der_expit, x0, epsilon=1e-6)
+ assert_almost_equal(r, 0)
+ r = optimize.check_grad(expit, der_expit, x0, epsilon=1e-6,
+ direction='random', rng=1234)
+ assert_almost_equal(r, 0)
+
+ # Check if the epsilon parameter is being considered.
+ r = abs(optimize.check_grad(expit, der_expit, x0, epsilon=1e-1) - 0)
+ assert r > 1e-7
+ r = abs(optimize.check_grad(expit, der_expit, x0, epsilon=1e-1,
+ direction='random', rng=1234) - 0)
+ assert r > 1e-7
+
+ def x_sinx(x):
+ return (x*np.sin(x)).sum()
+
+ def der_x_sinx(x):
+ return np.sin(x) + x*np.cos(x)
+
+ x0 = np.arange(0, 2, 0.2)
+
+ r = optimize.check_grad(x_sinx, der_x_sinx, x0,
+ direction='random', rng=1234)
+ assert_almost_equal(r, 0)
+
+ assert_raises(ValueError, optimize.check_grad,
+ x_sinx, der_x_sinx, x0,
+ direction='random_projection', rng=1234)
+
+ # checking can be done for derivatives of vector valued functions
+ r = optimize.check_grad(himmelblau_grad, himmelblau_hess, himmelblau_x0,
+ direction='all', rng=1234)
+ assert r < 5e-7
+
+
+class CheckOptimize:
+ """ Base test case for a simple constrained entropy maximization problem
+ (the machine translation example of Berger et al in
+ Computational Linguistics, vol 22, num 1, pp 39--72, 1996.)
+ """
+
+ def setup_method(self):
+ self.F = np.array([[1, 1, 1],
+ [1, 1, 0],
+ [1, 0, 1],
+ [1, 0, 0],
+ [1, 0, 0]])
+ self.K = np.array([1., 0.3, 0.5])
+ self.startparams = np.zeros(3, np.float64)
+ self.solution = np.array([0., -0.524869316, 0.487525860])
+ self.maxiter = 1000
+ self.funccalls = threading.local()
+ self.gradcalls = threading.local()
+ self.trace = threading.local()
+
+ def func(self, x):
+ if not hasattr(self.funccalls, 'c'):
+ self.funccalls.c = 0
+
+ if not hasattr(self.gradcalls, 'c'):
+ self.gradcalls.c = 0
+
+ self.funccalls.c += 1
+ if self.funccalls.c > 6000:
+ raise RuntimeError("too many iterations in optimization routine")
+ log_pdot = np.dot(self.F, x)
+ logZ = np.log(sum(np.exp(log_pdot)))
+ f = logZ - np.dot(self.K, x)
+ if not hasattr(self.trace, 't'):
+ self.trace.t = []
+ self.trace.t.append(np.copy(x))
+ return f
+
+ def grad(self, x):
+ if not hasattr(self.gradcalls, 'c'):
+ self.gradcalls.c = 0
+ self.gradcalls.c += 1
+ log_pdot = np.dot(self.F, x)
+ logZ = np.log(sum(np.exp(log_pdot)))
+ p = np.exp(log_pdot - logZ)
+ return np.dot(self.F.transpose(), p) - self.K
+
+ def hess(self, x):
+ log_pdot = np.dot(self.F, x)
+ logZ = np.log(sum(np.exp(log_pdot)))
+ p = np.exp(log_pdot - logZ)
+ return np.dot(self.F.T,
+ np.dot(np.diag(p), self.F - np.dot(self.F.T, p)))
+
+ def hessp(self, x, p):
+ return np.dot(self.hess(x), p)
+
+
+class CheckOptimizeParameterized(CheckOptimize):
+
+ def test_cg(self):
+ # conjugate gradient optimization routine
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ method='CG', jac=self.grad,
+ options=opts)
+ params, fopt, func_calls, grad_calls, warnflag = \
+ res['x'], res['fun'], res['nfev'], res['njev'], res['status']
+ else:
+ retval = optimize.fmin_cg(self.func, self.startparams,
+ self.grad, (), maxiter=self.maxiter,
+ full_output=True, disp=self.disp,
+ retall=False)
+ (params, fopt, func_calls, grad_calls, warnflag) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c == 9, self.funccalls.c
+ assert self.gradcalls.c == 7, self.gradcalls.c
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[2:4],
+ [[0, -0.5, 0.5],
+ [0, -5.05700028e-01, 4.95985862e-01]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_cg_cornercase(self):
+ def f(r):
+ return 2.5 * (1 - np.exp(-1.5*(r - 0.5)))**2
+
+ # Check several initial guesses. (Too far away from the
+ # minimum, the function ends up in the flat region of exp.)
+ for x0 in np.linspace(-0.75, 3, 71):
+ sol = optimize.minimize(f, [x0], method='CG')
+ assert sol.success
+ assert_allclose(sol.x, [0.5], rtol=1e-5)
+
+ def test_bfgs(self):
+ # Broyden-Fletcher-Goldfarb-Shanno optimization routine
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams,
+ jac=self.grad, method='BFGS', args=(),
+ options=opts)
+
+ params, fopt, gopt, Hopt, func_calls, grad_calls, warnflag = (
+ res['x'], res['fun'], res['jac'], res['hess_inv'],
+ res['nfev'], res['njev'], res['status'])
+ else:
+ retval = optimize.fmin_bfgs(self.func, self.startparams, self.grad,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=self.disp,
+ retall=False)
+ (params, fopt, gopt, Hopt,
+ func_calls, grad_calls, warnflag) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c == 10, self.funccalls.c
+ assert self.gradcalls.c == 8, self.gradcalls.c
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[6:8],
+ [[0, -5.25060743e-01, 4.87748473e-01],
+ [0, -5.24885582e-01, 4.87530347e-01]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_bfgs_hess_inv0_neg(self):
+ # Ensure that BFGS does not accept neg. def. initial inverse
+ # Hessian estimate.
+ with pytest.raises(ValueError, match="'hess_inv0' matrix isn't "
+ "positive definite."):
+ x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
+ opts = {'disp': self.disp, 'hess_inv0': -np.eye(5)}
+ optimize.minimize(optimize.rosen, x0=x0, method='BFGS', args=(),
+ options=opts)
+
+ def test_bfgs_hess_inv0_semipos(self):
+ # Ensure that BFGS does not accept semi pos. def. initial inverse
+ # Hessian estimate.
+ with pytest.raises(ValueError, match="'hess_inv0' matrix isn't "
+ "positive definite."):
+ x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
+ hess_inv0 = np.eye(5)
+ hess_inv0[0, 0] = 0
+ opts = {'disp': self.disp, 'hess_inv0': hess_inv0}
+ optimize.minimize(optimize.rosen, x0=x0, method='BFGS', args=(),
+ options=opts)
+
+ def test_bfgs_hess_inv0_sanity(self):
+ # Ensure that BFGS handles `hess_inv0` parameter correctly.
+ fun = optimize.rosen
+ x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
+ opts = {'disp': self.disp, 'hess_inv0': 1e-2 * np.eye(5)}
+ res = optimize.minimize(fun, x0=x0, method='BFGS', args=(),
+ options=opts)
+ res_true = optimize.minimize(fun, x0=x0, method='BFGS', args=(),
+ options={'disp': self.disp})
+ assert_allclose(res.fun, res_true.fun, atol=1e-6)
+
+ @pytest.mark.filterwarnings('ignore::UserWarning')
+ def test_bfgs_infinite(self):
+ # Test corner case where -Inf is the minimum. See gh-2019.
+ def func(x):
+ return -np.e ** (-x)
+ def fprime(x):
+ return -func(x)
+ x0 = [0]
+ with np.errstate(over='ignore'):
+ if self.use_wrapper:
+ opts = {'disp': self.disp}
+ x = optimize.minimize(func, x0, jac=fprime, method='BFGS',
+ args=(), options=opts)['x']
+ else:
+ x = optimize.fmin_bfgs(func, x0, fprime, disp=self.disp)
+ assert not np.isfinite(func(x))
+
+ def test_bfgs_xrtol(self):
+ # test for #17345 to test xrtol parameter
+ x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
+ res = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'xrtol': 1e-3})
+ ref = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'gtol': 1e-3})
+ assert res.nit != ref.nit
+
+ def test_bfgs_c1(self):
+ # test for #18977 insufficiently low value of c1 leads to precision loss
+ # for poor starting parameters
+ x0 = [10.3, 20.7, 10.8, 1.9, -1.2]
+ res_c1_small = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'c1': 1e-8})
+ res_c1_big = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'c1': 1e-1})
+
+ assert res_c1_small.nfev > res_c1_big.nfev
+
+ def test_bfgs_c2(self):
+ # test that modification of c2 parameter
+ # results in different number of iterations
+ x0 = [1.3, 0.7, 0.8, 1.9, 1.2]
+ res_default = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'c2': .9})
+ res_mod = optimize.minimize(optimize.rosen,
+ x0, method='bfgs', options={'c2': 1e-2})
+ assert res_default.nit > res_mod.nit
+
+ @pytest.mark.parametrize(["c1", "c2"], [[0.5, 2],
+ [-0.1, 0.1],
+ [0.2, 0.1]])
+ def test_invalid_c1_c2(self, c1, c2):
+ with pytest.raises(ValueError, match="'c1' and 'c2'"):
+ x0 = [10.3, 20.7, 10.8, 1.9, -1.2]
+ optimize.minimize(optimize.rosen, x0, method='cg',
+ options={'c1': c1, 'c2': c2})
+
+ def test_powell(self):
+ # Powell (direction set) optimization routine
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ method='Powell', options=opts)
+ params, fopt, direc, numiter, func_calls, warnflag = (
+ res['x'], res['fun'], res['direc'], res['nit'],
+ res['nfev'], res['status'])
+ else:
+ retval = optimize.fmin_powell(self.func, self.startparams,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=self.disp,
+ retall=False)
+ (params, fopt, direc, numiter, func_calls, warnflag) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+ # params[0] does not affect the objective function
+ assert_allclose(params[1:], self.solution[1:], atol=5e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ #
+ # However, some leeway must be added: the exact evaluation
+ # count is sensitive to numerical error, and floating-point
+ # computations are not bit-for-bit reproducible across
+ # machines, and when using e.g., MKL, data alignment
+ # etc., affect the rounding error.
+ #
+ assert self.funccalls.c <= 116 + 20, self.funccalls.c
+ assert self.gradcalls.c == 0, self.gradcalls.c
+
+ @pytest.mark.xfail(reason="This part of test_powell fails on some "
+ "platforms, but the solution returned by powell is "
+ "still valid.")
+ def test_powell_gh14014(self):
+ # This part of test_powell started failing on some CI platforms;
+ # see gh-14014. Since the solution is still correct and the comments
+ # in test_powell suggest that small differences in the bits are known
+ # to change the "trace" of the solution, seems safe to xfail to get CI
+ # green now and investigate later.
+
+ # Powell (direction set) optimization routine
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ method='Powell', options=opts)
+ params, fopt, direc, numiter, func_calls, warnflag = (
+ res['x'], res['fun'], res['direc'], res['nit'],
+ res['nfev'], res['status'])
+ else:
+ retval = optimize.fmin_powell(self.func, self.startparams,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=self.disp,
+ retall=False)
+ (params, fopt, direc, numiter, func_calls, warnflag) = retval
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace[34:39],
+ [[0.72949016, -0.44156936, 0.47100962],
+ [0.72949016, -0.44156936, 0.48052496],
+ [1.45898031, -0.88313872, 0.95153458],
+ [0.72949016, -0.44156936, 0.47576729],
+ [1.72949016, -0.44156936, 0.47576729]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_powell_bounded(self):
+ # Powell (direction set) optimization routine
+ # same as test_powell above, but with bounds
+ bounds = [(-np.pi, np.pi) for _ in self.startparams]
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ bounds=bounds,
+ method='Powell', options=opts)
+ params, func_calls = (res['x'], res['nfev'])
+
+ assert func_calls == self.funccalls.c
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6, rtol=1e-5)
+
+ # The exact evaluation count is sensitive to numerical error, and
+ # floating-point computations are not bit-for-bit reproducible
+ # across machines, and when using e.g. MKL, data alignment etc.
+ # affect the rounding error.
+ # It takes 155 calls on my machine, but we can add the same +20
+ # margin as is used in `test_powell`
+ assert self.funccalls.c <= 155 + 20
+ assert self.gradcalls.c == 0
+
+ def test_neldermead(self):
+ # Nelder-Mead simplex algorithm
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ method='Nelder-mead', options=opts)
+ params, fopt, numiter, func_calls, warnflag = (
+ res['x'], res['fun'], res['nit'], res['nfev'],
+ res['status'])
+ else:
+ retval = optimize.fmin(self.func, self.startparams,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=self.disp,
+ retall=False)
+ (params, fopt, numiter, func_calls, warnflag) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c == 167, self.funccalls.c
+ assert self.gradcalls.c == 0, self.gradcalls.c
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[76:78],
+ [[0.1928968, -0.62780447, 0.35166118],
+ [0.19572515, -0.63648426, 0.35838135]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_neldermead_initial_simplex(self):
+ # Nelder-Mead simplex algorithm
+ simplex = np.zeros((4, 3))
+ simplex[...] = self.startparams
+ for j in range(3):
+ simplex[j+1, j] += 0.1
+
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': False,
+ 'return_all': True, 'initial_simplex': simplex}
+ res = optimize.minimize(self.func, self.startparams, args=(),
+ method='Nelder-mead', options=opts)
+ params, fopt, numiter, func_calls, warnflag = (res['x'],
+ res['fun'],
+ res['nit'],
+ res['nfev'],
+ res['status'])
+ assert_allclose(res['allvecs'][0], simplex[0])
+ else:
+ retval = optimize.fmin(self.func, self.startparams,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=False, retall=False,
+ initial_simplex=simplex)
+
+ (params, fopt, numiter, func_calls, warnflag) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.17.0. Don't allow them to increase.
+ assert self.funccalls.c == 100, self.funccalls.c
+ assert self.gradcalls.c == 0, self.gradcalls.c
+
+ # Ensure that the function behaves the same; this is from SciPy 0.15.0
+ assert_allclose(self.trace.t[50:52],
+ [[0.14687474, -0.5103282, 0.48252111],
+ [0.14474003, -0.5282084, 0.48743951]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_neldermead_initial_simplex_bad(self):
+ # Check it fails with a bad simplices
+ bad_simplices = []
+
+ simplex = np.zeros((3, 2))
+ simplex[...] = self.startparams[:2]
+ for j in range(2):
+ simplex[j+1, j] += 0.1
+ bad_simplices.append(simplex)
+
+ simplex = np.zeros((3, 3))
+ bad_simplices.append(simplex)
+
+ for simplex in bad_simplices:
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': False,
+ 'return_all': False, 'initial_simplex': simplex}
+ assert_raises(ValueError,
+ optimize.minimize,
+ self.func,
+ self.startparams,
+ args=(),
+ method='Nelder-mead',
+ options=opts)
+ else:
+ assert_raises(ValueError, optimize.fmin,
+ self.func, self.startparams,
+ args=(), maxiter=self.maxiter,
+ full_output=True, disp=False, retall=False,
+ initial_simplex=simplex)
+
+ def test_neldermead_x0_ub(self):
+ # checks whether minimisation occurs correctly for entries where
+ # x0 == ub
+ # gh19991
+ def quad(x):
+ return np.sum(x**2)
+
+ res = optimize.minimize(
+ quad,
+ [1],
+ bounds=[(0, 1.)],
+ method='nelder-mead'
+ )
+ assert_allclose(res.x, [0])
+
+ res = optimize.minimize(
+ quad,
+ [1, 2],
+ bounds=[(0, 1.), (1, 3.)],
+ method='nelder-mead'
+ )
+ assert_allclose(res.x, [0, 1])
+
+ def test_ncg_negative_maxiter(self):
+ # Regression test for gh-8241
+ opts = {'maxiter': -1}
+ result = optimize.minimize(self.func, self.startparams,
+ method='Newton-CG', jac=self.grad,
+ args=(), options=opts)
+ assert result.status == 1
+
+ def test_ncg_zero_xtol(self):
+ # Regression test for gh-20214
+ def cosine(x):
+ return np.cos(x[0])
+
+ def jac(x):
+ return -np.sin(x[0])
+
+ x0 = [0.1]
+ xtol = 0
+ result = optimize.minimize(cosine,
+ x0=x0,
+ jac=jac,
+ method="newton-cg",
+ options=dict(xtol=xtol))
+ assert result.status == 0
+ assert_almost_equal(result.x[0], np.pi)
+
+ def test_ncg(self):
+ # line-search Newton conjugate gradient optimization routine
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ retval = optimize.minimize(self.func, self.startparams,
+ method='Newton-CG', jac=self.grad,
+ args=(), options=opts)['x']
+ else:
+ retval = optimize.fmin_ncg(self.func, self.startparams, self.grad,
+ args=(), maxiter=self.maxiter,
+ full_output=False, disp=self.disp,
+ retall=False)
+
+ params = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c == 7, self.funccalls.c
+ assert self.gradcalls.c <= 22, self.gradcalls.c # 0.13.0
+ # assert self.gradcalls <= 18, self.gradcalls # 0.9.0
+ # assert self.gradcalls == 18, self.gradcalls # 0.8.0
+ # assert self.gradcalls == 22, self.gradcalls # 0.7.0
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[3:5],
+ [[-4.35700753e-07, -5.24869435e-01, 4.87527480e-01],
+ [-4.35700753e-07, -5.24869401e-01, 4.87527774e-01]],
+ atol=1e-6, rtol=1e-7)
+
+ def test_ncg_hess(self):
+ # Newton conjugate gradient with Hessian
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ retval = optimize.minimize(self.func, self.startparams,
+ method='Newton-CG', jac=self.grad,
+ hess=self.hess,
+ args=(), options=opts)['x']
+ else:
+ retval = optimize.fmin_ncg(self.func, self.startparams, self.grad,
+ fhess=self.hess,
+ args=(), maxiter=self.maxiter,
+ full_output=False, disp=self.disp,
+ retall=False)
+
+ params = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c <= 7, self.funccalls.c # gh10673
+ assert self.gradcalls.c <= 18, self.gradcalls.c # 0.9.0
+ # assert self.gradcalls == 18, self.gradcalls # 0.8.0
+ # assert self.gradcalls == 22, self.gradcalls # 0.7.0
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[3:5],
+ [[-4.35700753e-07, -5.24869435e-01, 4.87527480e-01],
+ [-4.35700753e-07, -5.24869401e-01, 4.87527774e-01]],
+ atol=1e-6, rtol=1e-7)
+
+ def test_ncg_hessp(self):
+ # Newton conjugate gradient with Hessian times a vector p.
+ if self.use_wrapper:
+ opts = {'maxiter': self.maxiter, 'disp': self.disp,
+ 'return_all': False}
+ retval = optimize.minimize(self.func, self.startparams,
+ method='Newton-CG', jac=self.grad,
+ hessp=self.hessp,
+ args=(), options=opts)['x']
+ else:
+ retval = optimize.fmin_ncg(self.func, self.startparams, self.grad,
+ fhess_p=self.hessp,
+ args=(), maxiter=self.maxiter,
+ full_output=False, disp=self.disp,
+ retall=False)
+
+ params = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c <= 7, self.funccalls.c # gh10673
+ assert self.gradcalls.c <= 18, self.gradcalls.c # 0.9.0
+ # assert self.gradcalls == 18, self.gradcalls # 0.8.0
+ # assert self.gradcalls == 22, self.gradcalls # 0.7.0
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ assert_allclose(self.trace.t[3:5],
+ [[-4.35700753e-07, -5.24869435e-01, 4.87527480e-01],
+ [-4.35700753e-07, -5.24869401e-01, 4.87527774e-01]],
+ atol=1e-6, rtol=1e-7)
+
+ def test_cobyqa(self):
+ # COBYQA method.
+ if self.use_wrapper:
+ res = optimize.minimize(
+ self.func,
+ self.startparams,
+ method='cobyqa',
+ options={'maxiter': self.maxiter, 'disp': self.disp},
+ )
+ assert_allclose(res.fun, self.func(self.solution), atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 1.14.0. Don't allow them to increase. The exact evaluation
+ # count is sensitive to numerical error and floating-point
+ # computations are not bit-for-bit reproducible across machines. It
+ # takes 45 calls on my machine, but we can add the same +20 margin
+ # as is used in `test_powell`
+ assert self.funccalls.c <= 45 + 20, self.funccalls.c
+
+
+def test_maxfev_test():
+ rng = np.random.default_rng(271707100830272976862395227613146332411)
+
+ def cost(x):
+ return rng.random(1) * 1000 # never converged problem
+
+ for imaxfev in [1, 10, 50]:
+ # "TNC" and "L-BFGS-B" also supports max function evaluation, but
+ # these may violate the limit because of evaluating gradients
+ # by numerical differentiation. See the discussion in PR #14805.
+ for method in ['Powell', 'Nelder-Mead']:
+ result = optimize.minimize(cost, rng.random(10),
+ method=method,
+ options={'maxfev': imaxfev})
+ assert result["nfev"] == imaxfev
+
+
+def test_wrap_scalar_function_with_validation():
+
+ def func_(x):
+ return x
+
+ fcalls, func = optimize._optimize.\
+ _wrap_scalar_function_maxfun_validation(func_, np.asarray(1), 5)
+
+ for i in range(5):
+ func(np.asarray(i))
+ assert fcalls[0] == i+1
+
+ msg = "Too many function calls"
+ with assert_raises(optimize._optimize._MaxFuncCallError, match=msg):
+ func(np.asarray(i)) # exceeded maximum function call
+
+ fcalls, func = optimize._optimize.\
+ _wrap_scalar_function_maxfun_validation(func_, np.asarray(1), 5)
+
+ msg = "The user-provided objective function must return a scalar value."
+ with assert_raises(ValueError, match=msg):
+ func(np.array([1, 1]))
+
+
+def test_obj_func_returns_scalar():
+ match = ("The user-provided "
+ "objective function must "
+ "return a scalar value.")
+ with assert_raises(ValueError, match=match):
+ optimize.minimize(lambda x: x, np.array([1, 1]), method='BFGS')
+
+
+def test_neldermead_iteration_num():
+ x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
+ res = optimize._minimize._minimize_neldermead(optimize.rosen, x0,
+ xatol=1e-8)
+ assert res.nit <= 339
+
+
+def test_neldermead_respect_fp():
+ # Nelder-Mead should respect the fp type of the input + function
+ x0 = np.array([5.0, 4.0]).astype(np.float32)
+ def rosen_(x):
+ assert x.dtype == np.float32
+ return optimize.rosen(x)
+
+ optimize.minimize(rosen_, x0, method='Nelder-Mead')
+
+
+def test_neldermead_xatol_fatol():
+ # gh4484
+ # test we can call with fatol, xatol specified
+ def func(x):
+ return x[0] ** 2 + x[1] ** 2
+
+ optimize._minimize._minimize_neldermead(func, [1, 1], maxiter=2,
+ xatol=1e-3, fatol=1e-3)
+
+
+def test_neldermead_adaptive():
+ def func(x):
+ return np.sum(x ** 2)
+ p0 = [0.15746215, 0.48087031, 0.44519198, 0.4223638, 0.61505159,
+ 0.32308456, 0.9692297, 0.4471682, 0.77411992, 0.80441652,
+ 0.35994957, 0.75487856, 0.99973421, 0.65063887, 0.09626474]
+
+ res = optimize.minimize(func, p0, method='Nelder-Mead')
+ assert_equal(res.success, False)
+
+ res = optimize.minimize(func, p0, method='Nelder-Mead',
+ options={'adaptive': True})
+ assert_equal(res.success, True)
+
+
+def test_bounded_powell_outsidebounds():
+ # With the bounded Powell method if you start outside the bounds the final
+ # should still be within the bounds (provided that the user doesn't make a
+ # bad choice for the `direc` argument).
+ def func(x):
+ return np.sum(x ** 2)
+ bounds = (-1, 1), (-1, 1), (-1, 1)
+ x0 = [-4, .5, -.8]
+
+ # we're starting outside the bounds, so we should get a warning
+ with pytest.warns(optimize.OptimizeWarning):
+ res = optimize.minimize(func, x0, bounds=bounds, method="Powell")
+ assert_allclose(res.x, np.array([0.] * len(x0)), atol=1e-6)
+ assert_equal(res.success, True)
+ assert_equal(res.status, 0)
+
+ # However, now if we change the `direc` argument such that the
+ # set of vectors does not span the parameter space, then we may
+ # not end up back within the bounds. Here we see that the first
+ # parameter cannot be updated!
+ direc = [[0, 0, 0], [0, 1, 0], [0, 0, 1]]
+ # we're starting outside the bounds, so we should get a warning
+ with pytest.warns(optimize.OptimizeWarning):
+ res = optimize.minimize(func, x0,
+ bounds=bounds, method="Powell",
+ options={'direc': direc})
+ assert_allclose(res.x, np.array([-4., 0, 0]), atol=1e-6)
+ assert_equal(res.success, False)
+ assert_equal(res.status, 4)
+
+
+def test_bounded_powell_vs_powell():
+ # here we test an example where the bounded Powell method
+ # will return a different result than the standard Powell
+ # method.
+
+ # first we test a simple example where the minimum is at
+ # the origin and the minimum that is within the bounds is
+ # larger than the minimum at the origin.
+ def func(x):
+ return np.sum(x ** 2)
+ bounds = (-5, -1), (-10, -0.1), (1, 9.2), (-4, 7.6), (-15.9, -2)
+ x0 = [-2.1, -5.2, 1.9, 0, -2]
+
+ options = {'ftol': 1e-10, 'xtol': 1e-10}
+
+ res_powell = optimize.minimize(func, x0, method="Powell", options=options)
+ assert_allclose(res_powell.x, 0., atol=1e-6)
+ assert_allclose(res_powell.fun, 0., atol=1e-6)
+
+ res_bounded_powell = optimize.minimize(func, x0, options=options,
+ bounds=bounds,
+ method="Powell")
+ p = np.array([-1, -0.1, 1, 0, -2])
+ assert_allclose(res_bounded_powell.x, p, atol=1e-6)
+ assert_allclose(res_bounded_powell.fun, func(p), atol=1e-6)
+
+ # now we test bounded Powell but with a mix of inf bounds.
+ bounds = (None, -1), (-np.inf, -.1), (1, np.inf), (-4, None), (-15.9, -2)
+ res_bounded_powell = optimize.minimize(func, x0, options=options,
+ bounds=bounds,
+ method="Powell")
+ p = np.array([-1, -0.1, 1, 0, -2])
+ assert_allclose(res_bounded_powell.x, p, atol=1e-6)
+ assert_allclose(res_bounded_powell.fun, func(p), atol=1e-6)
+
+ # next we test an example where the global minimum is within
+ # the bounds, but the bounded Powell method performs better
+ # than the standard Powell method.
+ def func(x):
+ t = np.sin(-x[0]) * np.cos(x[1]) * np.sin(-x[0] * x[1]) * np.cos(x[1])
+ t -= np.cos(np.sin(x[1] * x[2]) * np.cos(x[2]))
+ return t**2
+
+ bounds = [(-2, 5)] * 3
+ x0 = [-0.5, -0.5, -0.5]
+
+ res_powell = optimize.minimize(func, x0, method="Powell")
+ res_bounded_powell = optimize.minimize(func, x0,
+ bounds=bounds,
+ method="Powell")
+ assert_allclose(res_powell.fun, 0.007136253919761627, atol=1e-6)
+ assert_allclose(res_bounded_powell.fun, 0, atol=1e-6)
+
+ # next we test the previous example where the we provide Powell
+ # with (-inf, inf) bounds, and compare it to providing Powell
+ # with no bounds. They should end up the same.
+ bounds = [(-np.inf, np.inf)] * 3
+
+ res_bounded_powell = optimize.minimize(func, x0,
+ bounds=bounds,
+ method="Powell")
+ assert_allclose(res_powell.fun, res_bounded_powell.fun, atol=1e-6)
+ assert_allclose(res_powell.nfev, res_bounded_powell.nfev, atol=1e-6)
+ assert_allclose(res_powell.x, res_bounded_powell.x, atol=1e-6)
+
+ # now test when x0 starts outside of the bounds.
+ x0 = [45.46254415, -26.52351498, 31.74830248]
+ bounds = [(-2, 5)] * 3
+ # we're starting outside the bounds, so we should get a warning
+ with pytest.warns(optimize.OptimizeWarning):
+ res_bounded_powell = optimize.minimize(func, x0,
+ bounds=bounds,
+ method="Powell")
+ assert_allclose(res_bounded_powell.fun, 0, atol=1e-6)
+
+
+def test_onesided_bounded_powell_stability():
+ # When the Powell method is bounded on only one side, a
+ # np.tan transform is done in order to convert it into a
+ # completely bounded problem. Here we do some simple tests
+ # of one-sided bounded Powell where the optimal solutions
+ # are large to test the stability of the transformation.
+ kwargs = {'method': 'Powell',
+ 'bounds': [(-np.inf, 1e6)] * 3,
+ 'options': {'ftol': 1e-8, 'xtol': 1e-8}}
+ x0 = [1, 1, 1]
+
+ # df/dx is constant.
+ def f(x):
+ return -np.sum(x)
+ res = optimize.minimize(f, x0, **kwargs)
+ assert_allclose(res.fun, -3e6, atol=1e-4)
+
+ # df/dx gets smaller and smaller.
+ def f(x):
+ return -np.abs(np.sum(x)) ** (0.1) * (1 if np.all(x > 0) else -1)
+
+ res = optimize.minimize(f, x0, **kwargs)
+ assert_allclose(res.fun, -(3e6) ** (0.1))
+
+ # df/dx gets larger and larger.
+ def f(x):
+ return -np.abs(np.sum(x)) ** 10 * (1 if np.all(x > 0) else -1)
+
+ res = optimize.minimize(f, x0, **kwargs)
+ assert_allclose(res.fun, -(3e6) ** 10, rtol=1e-7)
+
+ # df/dx gets larger for some of the variables and smaller for others.
+ def f(x):
+ t = -np.abs(np.sum(x[:2])) ** 5 - np.abs(np.sum(x[2:])) ** (0.1)
+ t *= (1 if np.all(x > 0) else -1)
+ return t
+
+ kwargs['bounds'] = [(-np.inf, 1e3)] * 3
+ res = optimize.minimize(f, x0, **kwargs)
+ assert_allclose(res.fun, -(2e3) ** 5 - (1e6) ** (0.1), rtol=1e-7)
+
+
+class TestOptimizeWrapperDisp(CheckOptimizeParameterized):
+ use_wrapper = True
+ disp = True
+
+
+class TestOptimizeWrapperNoDisp(CheckOptimizeParameterized):
+ use_wrapper = True
+ disp = False
+
+
+class TestOptimizeNoWrapperDisp(CheckOptimizeParameterized):
+ use_wrapper = False
+ disp = True
+
+
+class TestOptimizeNoWrapperNoDisp(CheckOptimizeParameterized):
+ use_wrapper = False
+ disp = False
+
+
+class TestOptimizeSimple(CheckOptimize):
+
+ def test_bfgs_nan(self):
+ # Test corner case where nan is fed to optimizer. See gh-2067.
+ def func(x):
+ return x
+ def fprime(x):
+ return np.ones_like(x)
+ x0 = [np.nan]
+ with np.errstate(over='ignore', invalid='ignore'):
+ x = optimize.fmin_bfgs(func, x0, fprime, disp=False)
+ assert np.isnan(func(x))
+
+ def test_bfgs_nan_return(self):
+ # Test corner cases where fun returns NaN. See gh-4793.
+
+ # First case: NaN from first call.
+ def func(x):
+ return np.nan
+ with np.errstate(invalid='ignore'):
+ result = optimize.minimize(func, 0)
+
+ assert np.isnan(result['fun'])
+ assert result['success'] is False
+
+ # Second case: NaN from second call.
+ def func(x):
+ return 0 if x == 0 else np.nan
+ def fprime(x):
+ return np.ones_like(x) # Steer away from zero.
+ with np.errstate(invalid='ignore'):
+ result = optimize.minimize(func, 0, jac=fprime)
+
+ assert np.isnan(result['fun'])
+ assert result['success'] is False
+
+ def test_bfgs_numerical_jacobian(self):
+ # BFGS with numerical Jacobian and a vector epsilon parameter.
+ # define the epsilon parameter using a random vector
+ rng = np.random.default_rng(1234)
+ epsilon = np.sqrt(np.spacing(1.)) * rng.random(len(self.solution))
+
+ params = optimize.fmin_bfgs(self.func, self.startparams,
+ epsilon=epsilon, args=(),
+ maxiter=self.maxiter, disp=False)
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ def test_finite_differences_jac(self):
+ methods = ['BFGS', 'CG', 'TNC']
+ jacs = ['2-point', '3-point', None]
+ for method, jac in itertools.product(methods, jacs):
+ result = optimize.minimize(self.func, self.startparams,
+ method=method, jac=jac)
+ assert_allclose(self.func(result.x), self.func(self.solution),
+ atol=1e-6)
+
+ def test_finite_differences_hess(self):
+ # test that all the methods that require hess can use finite-difference
+ # For Newton-CG, trust-ncg, trust-krylov the FD estimated hessian is
+ # wrapped in a hessp function
+ # dogleg, trust-exact actually require true hessians at the moment, so
+ # they're excluded.
+ methods = ['trust-constr', 'Newton-CG', 'trust-ncg', 'trust-krylov']
+ hesses = FD_METHODS + (optimize.BFGS,)
+ for method, hess in itertools.product(methods, hesses):
+ if hess is optimize.BFGS:
+ hess = hess()
+ result = optimize.minimize(self.func, self.startparams,
+ method=method, jac=self.grad,
+ hess=hess)
+ assert result.success
+
+ # check that the methods demand some sort of Hessian specification
+ # Newton-CG creates its own hessp, and trust-constr doesn't need a hess
+ # specified either
+ methods = ['trust-ncg', 'trust-krylov', 'dogleg', 'trust-exact']
+ for method in methods:
+ with pytest.raises(ValueError):
+ optimize.minimize(self.func, self.startparams,
+ method=method, jac=self.grad,
+ hess=None)
+
+ def test_bfgs_gh_2169(self):
+ def f(x):
+ if x < 0:
+ return 1.79769313e+308
+ else:
+ return x + 1./x
+ xs = optimize.fmin_bfgs(f, [10.], disp=False)
+ assert_allclose(xs, 1.0, rtol=1e-4, atol=1e-4)
+
+ def test_bfgs_double_evaluations(self):
+ # check BFGS does not evaluate twice in a row at same point
+ def f(x):
+ xp = x[0]
+ assert xp not in seen
+ seen.add(xp)
+ return 10*x**2, 20*x
+
+ seen = set()
+ optimize.minimize(f, -100, method='bfgs', jac=True, tol=1e-7)
+
+ def test_l_bfgs_b(self):
+ # limited-memory bound-constrained BFGS algorithm
+ retval = optimize.fmin_l_bfgs_b(self.func, self.startparams,
+ self.grad, args=(),
+ maxiter=self.maxiter)
+
+ (params, fopt, d) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ # Ensure that function call counts are 'known good'; these are from
+ # SciPy 0.7.0. Don't allow them to increase.
+ assert self.funccalls.c == 7, self.funccalls.c
+ assert self.gradcalls.c == 5, self.gradcalls.c
+
+ # Ensure that the function behaves the same; this is from SciPy 0.7.0
+ # test fixed in gh10673
+ assert_allclose(self.trace.t[3:5],
+ [[8.117083e-16, -5.196198e-01, 4.897617e-01],
+ [0., -0.52489628, 0.48753042]],
+ atol=1e-14, rtol=1e-7)
+
+ def test_l_bfgs_b_numjac(self):
+ # L-BFGS-B with numerical Jacobian
+ retval = optimize.fmin_l_bfgs_b(self.func, self.startparams,
+ approx_grad=True,
+ maxiter=self.maxiter)
+
+ (params, fopt, d) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ def test_l_bfgs_b_funjac(self):
+ # L-BFGS-B with combined objective function and Jacobian
+ def fun(x):
+ return self.func(x), self.grad(x)
+
+ retval = optimize.fmin_l_bfgs_b(fun, self.startparams,
+ maxiter=self.maxiter)
+
+ (params, fopt, d) = retval
+
+ assert_allclose(self.func(params), self.func(self.solution),
+ atol=1e-6)
+
+ def test_l_bfgs_b_maxiter(self):
+ # gh7854
+ # Ensure that not more than maxiters are ever run.
+ class Callback:
+ def __init__(self):
+ self.nit = 0
+ self.fun = None
+ self.x = None
+
+ def __call__(self, x):
+ self.x = x
+ self.fun = optimize.rosen(x)
+ self.nit += 1
+
+ c = Callback()
+ res = optimize.minimize(optimize.rosen, [0., 0.], method='l-bfgs-b',
+ callback=c, options={'maxiter': 5})
+
+ assert_equal(res.nit, 5)
+ assert_almost_equal(res.x, c.x)
+ assert_almost_equal(res.fun, c.fun)
+ assert_equal(res.status, 1)
+ assert res.success is False
+ assert_equal(res.message,
+ 'STOP: TOTAL NO. OF ITERATIONS REACHED LIMIT')
+
+ def test_minimize_l_bfgs_b(self):
+ # Minimize with L-BFGS-B method
+ opts = {'maxiter': self.maxiter}
+ r = optimize.minimize(self.func, self.startparams,
+ method='L-BFGS-B', jac=self.grad,
+ options=opts)
+ assert_allclose(self.func(r.x), self.func(self.solution),
+ atol=1e-6)
+ assert self.gradcalls.c == r.njev
+
+ self.funccalls.c = self.gradcalls.c = 0
+ # approximate jacobian
+ ra = optimize.minimize(self.func, self.startparams,
+ method='L-BFGS-B', options=opts)
+ # check that function evaluations in approximate jacobian are counted
+ # assert_(ra.nfev > r.nfev)
+ assert self.funccalls.c == ra.nfev
+ assert_allclose(self.func(ra.x), self.func(self.solution),
+ atol=1e-6)
+
+ self.funccalls.c = self.gradcalls.c = 0
+ # approximate jacobian
+ ra = optimize.minimize(self.func, self.startparams, jac='3-point',
+ method='L-BFGS-B', options=opts)
+ assert self.funccalls.c == ra.nfev
+ assert_allclose(self.func(ra.x), self.func(self.solution),
+ atol=1e-6)
+
+ def test_minimize_l_bfgs_b_ftol(self):
+ # Check that the `ftol` parameter in l_bfgs_b works as expected
+ v0 = None
+ for tol in [1e-1, 1e-4, 1e-7, 1e-10]:
+ opts = {'maxiter': self.maxiter, 'ftol': tol}
+ sol = optimize.minimize(self.func, self.startparams,
+ method='L-BFGS-B', jac=self.grad,
+ options=opts)
+ v = self.func(sol.x)
+
+ if v0 is None:
+ v0 = v
+ else:
+ assert v < v0
+
+ assert_allclose(v, self.func(self.solution), rtol=tol)
+
+ def test_minimize_l_bfgs_maxls(self):
+ # check that the maxls is passed down to the Fortran routine
+ sol = optimize.minimize(optimize.rosen, np.array([-1.2, 1.0]),
+ method='L-BFGS-B', jac=optimize.rosen_der,
+ options={'maxls': 1})
+ assert not sol.success
+
+ def test_minimize_l_bfgs_b_maxfun_interruption(self):
+ # gh-6162
+ f = optimize.rosen
+ g = optimize.rosen_der
+ values = []
+ x0 = np.full(7, 1000)
+
+ def objfun(x):
+ value = f(x)
+ values.append(value)
+ return value
+
+ # Look for an interesting test case.
+ # Request a maxfun that stops at a particularly bad function
+ # evaluation somewhere between 100 and 300 evaluations.
+ low, medium, high = 30, 100, 300
+ optimize.fmin_l_bfgs_b(objfun, x0, fprime=g, maxfun=high)
+ v, k = max((y, i) for i, y in enumerate(values[medium:]))
+ maxfun = medium + k
+ # If the minimization strategy is reasonable,
+ # the minimize() result should not be worse than the best
+ # of the first 30 function evaluations.
+ target = min(values[:low])
+ xmin, fmin, d = optimize.fmin_l_bfgs_b(f, x0, fprime=g, maxfun=maxfun)
+ assert_array_less(fmin, target)
+
+ def test_custom(self):
+ # This function comes from the documentation example.
+ def custmin(fun, x0, args=(), maxfev=None, stepsize=0.1,
+ maxiter=100, callback=None, **options):
+ bestx = x0
+ besty = fun(x0)
+ funcalls = 1
+ niter = 0
+ improved = True
+ stop = False
+
+ while improved and not stop and niter < maxiter:
+ improved = False
+ niter += 1
+ for dim in range(np.size(x0)):
+ for s in [bestx[dim] - stepsize, bestx[dim] + stepsize]:
+ testx = np.copy(bestx)
+ testx[dim] = s
+ testy = fun(testx, *args)
+ funcalls += 1
+ if testy < besty:
+ besty = testy
+ bestx = testx
+ improved = True
+ if callback is not None:
+ callback(bestx)
+ if maxfev is not None and funcalls >= maxfev:
+ stop = True
+ break
+
+ return optimize.OptimizeResult(fun=besty, x=bestx, nit=niter,
+ nfev=funcalls, success=(niter > 1))
+
+ x0 = [1.35, 0.9, 0.8, 1.1, 1.2]
+ res = optimize.minimize(optimize.rosen, x0, method=custmin,
+ options=dict(stepsize=0.05))
+ assert_allclose(res.x, 1.0, rtol=1e-4, atol=1e-4)
+
+ def test_gh10771(self):
+ # check that minimize passes bounds and constraints to a custom
+ # minimizer without altering them.
+ bounds = [(-2, 2), (0, 3)]
+ constraints = 'constraints'
+
+ def custmin(fun, x0, **options):
+ assert options['bounds'] is bounds
+ assert options['constraints'] is constraints
+ return optimize.OptimizeResult()
+
+ x0 = [1, 1]
+ optimize.minimize(optimize.rosen, x0, method=custmin,
+ bounds=bounds, constraints=constraints)
+
+ def test_minimize_tol_parameter(self):
+ # Check that the minimize() tol= argument does something
+ def func(z):
+ x, y = z
+ return x**2*y**2 + x**4 + 1
+
+ def dfunc(z):
+ x, y = z
+ return np.array([2*x*y**2 + 4*x**3, 2*x**2*y])
+
+ for method in ['nelder-mead', 'powell', 'cg', 'bfgs',
+ 'newton-cg', 'l-bfgs-b', 'tnc',
+ 'cobyla', 'cobyqa', 'slsqp']:
+ if method in ('nelder-mead', 'powell', 'cobyla', 'cobyqa'):
+ jac = None
+ else:
+ jac = dfunc
+
+ sol1 = optimize.minimize(func, [2, 2], jac=jac, tol=1e-10,
+ method=method)
+ sol2 = optimize.minimize(func, [2, 2], jac=jac, tol=1.0,
+ method=method)
+ assert func(sol1.x) < func(sol2.x), \
+ f"{method}: {func(sol1.x)} vs. {func(sol2.x)}"
+
+ @pytest.mark.fail_slow(10)
+ @pytest.mark.filterwarnings('ignore::UserWarning')
+ @pytest.mark.filterwarnings('ignore::RuntimeWarning') # See gh-18547
+ @pytest.mark.parametrize('method',
+ ['fmin', 'fmin_powell', 'fmin_cg', 'fmin_bfgs',
+ 'fmin_ncg', 'fmin_l_bfgs_b', 'fmin_tnc',
+ 'fmin_slsqp'] + MINIMIZE_METHODS)
+ def test_minimize_callback_copies_array(self, method):
+ # Check that arrays passed to callbacks are not modified
+ # inplace by the optimizer afterward
+
+ if method in ('fmin_tnc', 'fmin_l_bfgs_b'):
+ def func(x):
+ return optimize.rosen(x), optimize.rosen_der(x)
+ else:
+ func = optimize.rosen
+ jac = optimize.rosen_der
+ hess = optimize.rosen_hess
+
+ x0 = np.zeros(10)
+
+ # Set options
+ kwargs = {}
+ if method.startswith('fmin'):
+ routine = getattr(optimize, method)
+ if method == 'fmin_slsqp':
+ kwargs['iter'] = 5
+ elif method == 'fmin_tnc':
+ kwargs['maxfun'] = 100
+ elif method in ('fmin', 'fmin_powell'):
+ kwargs['maxiter'] = 3500
+ else:
+ kwargs['maxiter'] = 5
+ else:
+ def routine(*a, **kw):
+ kw['method'] = method
+ return optimize.minimize(*a, **kw)
+
+ if method == 'tnc':
+ kwargs['options'] = dict(maxfun=100)
+ elif method == 'cobyla':
+ kwargs['options'] = dict(maxiter=100)
+ else:
+ kwargs['options'] = dict(maxiter=5)
+
+ if method in ('fmin_ncg',):
+ kwargs['fprime'] = jac
+ elif method in ('newton-cg',):
+ kwargs['jac'] = jac
+ elif method in ('trust-krylov', 'trust-exact', 'trust-ncg', 'dogleg',
+ 'trust-constr'):
+ kwargs['jac'] = jac
+ kwargs['hess'] = hess
+
+ # Run with callback
+ results = []
+
+ def callback(x, *args, **kwargs):
+ assert not isinstance(x, optimize.OptimizeResult)
+ results.append((x, np.copy(x)))
+
+ routine(func, x0, callback=callback, **kwargs)
+
+ # Check returned arrays coincide with their copies
+ # and have no memory overlap
+ assert len(results) > 2
+ assert all(np.all(x == y) for x, y in results)
+ combinations = itertools.combinations(results, 2)
+ assert not any(np.may_share_memory(x[0], y[0]) for x, y in combinations)
+
+ @pytest.mark.parametrize('method', ['nelder-mead', 'powell', 'cg',
+ 'bfgs', 'newton-cg', 'l-bfgs-b',
+ 'tnc', 'cobyla', 'cobyqa', 'slsqp'])
+ def test_no_increase(self, method):
+ # Check that the solver doesn't return a value worse than the
+ # initial point.
+
+ def func(x):
+ return (x - 1)**2
+
+ def bad_grad(x):
+ # purposefully invalid gradient function, simulates a case
+ # where line searches start failing
+ return 2*(x - 1) * (-1) - 2
+
+ x0 = np.array([2.0])
+ f0 = func(x0)
+ jac = bad_grad
+ options = dict(maxfun=20) if method == 'tnc' else dict(maxiter=20)
+ if method in ['nelder-mead', 'powell', 'cobyla', 'cobyqa']:
+ jac = None
+ sol = optimize.minimize(func, x0, jac=jac, method=method,
+ options=options)
+ assert_equal(func(sol.x), sol.fun)
+
+ if method == 'slsqp':
+ pytest.xfail("SLSQP returns slightly worse")
+ assert func(sol.x) <= f0
+
+ def test_slsqp_respect_bounds(self):
+ # Regression test for gh-3108
+ def f(x):
+ return sum((x - np.array([1., 2., 3., 4.]))**2)
+
+ def cons(x):
+ a = np.array([[-1, -1, -1, -1], [-3, -3, -2, -1]])
+ return np.concatenate([np.dot(a, x) + np.array([5, 10]), x])
+
+ x0 = np.array([0.5, 1., 1.5, 2.])
+ res = optimize.minimize(f, x0, method='slsqp',
+ constraints={'type': 'ineq', 'fun': cons})
+ assert_allclose(res.x, np.array([0., 2, 5, 8])/3, atol=1e-12)
+
+ @pytest.mark.parametrize('method', ['Nelder-Mead', 'Powell', 'CG', 'BFGS',
+ 'Newton-CG', 'L-BFGS-B', 'SLSQP',
+ 'trust-constr', 'dogleg', 'trust-ncg',
+ 'trust-exact', 'trust-krylov',
+ 'cobyqa'])
+ def test_respect_maxiter(self, method):
+ # Check that the number of iterations equals max_iter, assuming
+ # convergence doesn't establish before
+ MAXITER = 4
+
+ x0 = np.zeros(10)
+
+ sf = ScalarFunction(optimize.rosen, x0, (), optimize.rosen_der,
+ optimize.rosen_hess, None, None)
+
+ # Set options
+ kwargs = {'method': method, 'options': dict(maxiter=MAXITER)}
+
+ if method in ('Newton-CG',):
+ kwargs['jac'] = sf.grad
+ elif method in ('trust-krylov', 'trust-exact', 'trust-ncg', 'dogleg',
+ 'trust-constr'):
+ kwargs['jac'] = sf.grad
+ kwargs['hess'] = sf.hess
+
+ sol = optimize.minimize(sf.fun, x0, **kwargs)
+ assert sol.nit == MAXITER
+ assert sol.nfev >= sf.nfev
+ if hasattr(sol, 'njev'):
+ assert sol.njev >= sf.ngev
+
+ # method specific tests
+ if method == 'SLSQP':
+ assert sol.status == 9 # Iteration limit reached
+ elif method == 'cobyqa':
+ assert sol.status == 6 # Iteration limit reached
+
+ @pytest.mark.parametrize('method', ['Nelder-Mead', 'Powell',
+ 'fmin', 'fmin_powell'])
+ def test_runtime_warning(self, method):
+ x0 = np.zeros(10)
+ sf = ScalarFunction(optimize.rosen, x0, (), optimize.rosen_der,
+ optimize.rosen_hess, None, None)
+ options = {"maxiter": 1, "disp": True}
+ with pytest.warns(RuntimeWarning,
+ match=r'Maximum number of iterations'):
+ if method.startswith('fmin'):
+ routine = getattr(optimize, method)
+ routine(sf.fun, x0, **options)
+ else:
+ optimize.minimize(sf.fun, x0, method=method, options=options)
+
+ def test_respect_maxiter_trust_constr_ineq_constraints(self):
+ # special case of minimization with trust-constr and inequality
+ # constraints to check maxiter limit is obeyed when using internal
+ # method 'tr_interior_point'
+ MAXITER = 4
+ f = optimize.rosen
+ jac = optimize.rosen_der
+ hess = optimize.rosen_hess
+
+ def fun(x):
+ return np.array([0.2 * x[0] - 0.4 * x[1] - 0.33 * x[2]])
+ cons = ({'type': 'ineq',
+ 'fun': fun},)
+
+ x0 = np.zeros(10)
+ sol = optimize.minimize(f, x0, constraints=cons, jac=jac, hess=hess,
+ method='trust-constr',
+ options=dict(maxiter=MAXITER))
+ assert sol.nit == MAXITER
+
+ def test_minimize_automethod(self):
+ def f(x):
+ return x**2
+
+ def cons(x):
+ return x - 2
+
+ x0 = np.array([10.])
+ sol_0 = optimize.minimize(f, x0)
+ sol_1 = optimize.minimize(f, x0, constraints=[{'type': 'ineq',
+ 'fun': cons}])
+ sol_2 = optimize.minimize(f, x0, bounds=[(5, 10)])
+ sol_3 = optimize.minimize(f, x0,
+ constraints=[{'type': 'ineq', 'fun': cons}],
+ bounds=[(5, 10)])
+ sol_4 = optimize.minimize(f, x0,
+ constraints=[{'type': 'ineq', 'fun': cons}],
+ bounds=[(1, 10)])
+ for sol in [sol_0, sol_1, sol_2, sol_3, sol_4]:
+ assert sol.success
+ assert_allclose(sol_0.x, 0, atol=1e-7)
+ assert_allclose(sol_1.x, 2, atol=1e-7)
+ assert_allclose(sol_2.x, 5, atol=1e-7)
+ assert_allclose(sol_3.x, 5, atol=1e-7)
+ assert_allclose(sol_4.x, 2, atol=1e-7)
+
+ def test_minimize_coerce_args_param(self):
+ # Regression test for gh-3503
+ def Y(x, c):
+ return np.sum((x-c)**2)
+
+ def dY_dx(x, c=None):
+ return 2*(x-c)
+
+ c = np.array([3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5])
+ rng = np.random.default_rng(1234)
+ xinit = rng.standard_normal(len(c))
+ optimize.minimize(Y, xinit, jac=dY_dx, args=(c), method="BFGS")
+
+ def test_initial_step_scaling(self):
+ # Check that optimizer initial step is not huge even if the
+ # function and gradients are
+
+ scales = [1e-50, 1, 1e50]
+ methods = ['CG', 'BFGS', 'L-BFGS-B', 'Newton-CG']
+
+ def f(x):
+ if first_step_size[0] is None and x[0] != x0[0]:
+ first_step_size[0] = abs(x[0] - x0[0])
+ if abs(x).max() > 1e4:
+ raise AssertionError("Optimization stepped far away!")
+ return scale*(x[0] - 1)**2
+
+ def g(x):
+ return np.array([scale*(x[0] - 1)])
+
+ for scale, method in itertools.product(scales, methods):
+ if method in ('CG', 'BFGS'):
+ options = dict(gtol=scale*1e-8)
+ else:
+ options = dict()
+
+ if scale < 1e-10 and method in ('L-BFGS-B', 'Newton-CG'):
+ # XXX: return initial point if they see small gradient
+ continue
+
+ x0 = [-1.0]
+ first_step_size = [None]
+ res = optimize.minimize(f, x0, jac=g, method=method,
+ options=options)
+
+ err_msg = f"{method} {scale}: {first_step_size}: {res}"
+
+ assert res.success, err_msg
+ assert_allclose(res.x, [1.0], err_msg=err_msg)
+ assert res.nit <= 3, err_msg
+
+ if scale > 1e-10:
+ if method in ('CG', 'BFGS'):
+ assert_allclose(first_step_size[0], 1.01, err_msg=err_msg)
+ else:
+ # Newton-CG and L-BFGS-B use different logic for the first
+ # step, but are both scaling invariant with step sizes ~ 1
+ assert first_step_size[0] > 0.5 and first_step_size[0] < 3, err_msg
+ else:
+ # step size has upper bound of ||grad||, so line
+ # search makes many small steps
+ pass
+
+ @pytest.mark.parametrize('method', ['nelder-mead', 'powell', 'cg', 'bfgs',
+ 'newton-cg', 'l-bfgs-b', 'tnc',
+ 'cobyqa', 'slsqp',
+ 'trust-constr', 'dogleg', 'trust-ncg',
+ 'trust-exact', 'trust-krylov'])
+ def test_nan_values(self, method):
+
+ # Check nan values result to failed exit status
+
+ # test is dependent on exact seed
+ rng = np.random.default_rng(123122)
+
+ count = [0]
+
+ def func(x):
+ return np.nan
+
+ def func2(x):
+ count[0] += 1
+ if count[0] > 2:
+ return np.nan
+ else:
+ return rng.random()
+
+ def grad(x):
+ return np.array([1.0])
+
+ def hess(x):
+ return np.array([[1.0]])
+
+ x0 = np.array([1.0])
+
+ needs_grad = method in ('newton-cg', 'trust-krylov', 'trust-exact',
+ 'trust-ncg', 'dogleg')
+ needs_hess = method in ('trust-krylov', 'trust-exact', 'trust-ncg',
+ 'dogleg')
+
+ funcs = [func, func2]
+ grads = [grad] if needs_grad else [grad, None]
+ hesss = [hess] if needs_hess else [hess, None]
+ options = dict(maxfun=20) if method == 'tnc' else dict(maxiter=20)
+
+ with np.errstate(invalid='ignore'), warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.*", UserWarning)
+ warnings.filterwarnings(
+ "ignore", ".*does not use Hessian.*", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", ".*does not use gradient.*", RuntimeWarning)
+
+ for f, g, h in itertools.product(funcs, grads, hesss):
+ count = [0]
+ sol = optimize.minimize(f, x0, jac=g, hess=h, method=method,
+ options=options)
+ assert_equal(sol.success, False)
+
+ @pytest.mark.parametrize('method', ['nelder-mead', 'cg', 'bfgs',
+ 'l-bfgs-b', 'tnc',
+ 'cobyla', 'cobyqa', 'slsqp',
+ 'trust-constr', 'dogleg', 'trust-ncg',
+ 'trust-exact', 'trust-krylov'])
+ def test_duplicate_evaluations(self, method):
+ # check that there are no duplicate evaluations for any methods
+ jac = hess = None
+ if method in ('newton-cg', 'trust-krylov', 'trust-exact',
+ 'trust-ncg', 'dogleg'):
+ jac = self.grad
+ if method in ('trust-krylov', 'trust-exact', 'trust-ncg',
+ 'dogleg'):
+ hess = self.hess
+
+ with np.errstate(invalid='ignore'), warnings.catch_warnings():
+ # for trust-constr
+ warnings.filterwarnings("ignore", "delta_grad == 0.*", UserWarning)
+ optimize.minimize(self.func, self.startparams,
+ method=method, jac=jac, hess=hess)
+
+ for i in range(1, len(self.trace.t)):
+ if np.array_equal(self.trace.t[i - 1], self.trace.t[i]):
+ raise RuntimeError(
+ f"Duplicate evaluations made by {method}")
+
+ @pytest.mark.filterwarnings('ignore::RuntimeWarning')
+ @pytest.mark.parametrize('method', MINIMIZE_METHODS_NEW_CB)
+ @pytest.mark.parametrize('new_cb_interface', [0, 1, 2])
+ def test_callback_stopiteration(self, method, new_cb_interface):
+ # Check that if callback raises StopIteration, optimization
+ # terminates with the same result as if iterations were limited
+
+ def f(x):
+ f.flag = False # check that f isn't called after StopIteration
+ return optimize.rosen(x)
+ f.flag = False
+
+ def g(x):
+ f.flag = False
+ return optimize.rosen_der(x)
+
+ def h(x):
+ f.flag = False
+ return optimize.rosen_hess(x)
+
+ maxiter = 5
+
+ if new_cb_interface == 1:
+ def callback_interface(*, intermediate_result):
+ assert intermediate_result.fun == f(intermediate_result.x)
+ callback()
+ elif new_cb_interface == 2:
+ class Callback:
+ def __call__(self, intermediate_result: OptimizeResult):
+ assert intermediate_result.fun == f(intermediate_result.x)
+ callback()
+ callback_interface = Callback()
+ else:
+ def callback_interface(xk, *args): # type: ignore[misc]
+ callback()
+
+ def callback():
+ callback.i += 1
+ callback.flag = False
+ if callback.i == maxiter:
+ callback.flag = True
+ raise StopIteration()
+ callback.i = 0
+ callback.flag = False
+
+ kwargs = {'x0': [1.1]*5, 'method': method,
+ 'fun': f, 'jac': g, 'hess': h}
+
+ res = optimize.minimize(**kwargs, callback=callback_interface)
+ if method == 'nelder-mead':
+ maxiter = maxiter + 1 # nelder-mead counts differently
+ if method == 'cobyqa':
+ ref = optimize.minimize(**kwargs, options={'maxfev': maxiter})
+ assert res.nfev == ref.nfev == maxiter
+ elif method == 'cobyla':
+ # COBYLA calls the callback once per iteration, not once per function
+ # evaluation, so this test is not applicable. However we can test
+ # the COBYLA status to verify that res stopped back on the callback
+ # and ref stopped based on the iteration limit.
+ # COBYLA requires at least n+2 function evaluations
+ maxiter = max(maxiter, len(kwargs['x0'])+2)
+ ref = optimize.minimize(**kwargs, options={'maxiter': maxiter})
+ assert res.status == 30
+ assert res.message == ("Return from COBYLA because the callback function "
+ "requested termination")
+ assert ref.status == 3
+ assert ref.message == ("Return from COBYLA because the objective function "
+ "has been evaluated MAXFUN times.")
+ # Return early because res/ref will be unequal for COBYLA for the reasons
+ # mentioned above.
+ return
+ else:
+ ref = optimize.minimize(**kwargs, options={'maxiter': maxiter})
+ assert res.message.startswith("`callback` raised `StopIteration`")
+ assert res.nit == ref.nit == maxiter
+ if method != 'slsqp':
+ # Unlike all other methods, apparently SLSQP updates x/fun after the last
+ # call to the callback
+ assert res.fun == ref.fun
+ assert_equal(res.x, ref.x)
+ assert res.status == 3 if method in {'trust-constr', 'cobyqa'} else 99
+ if method != 'cobyqa':
+ assert not res.success
+
+ def test_ndim_error(self):
+ msg = "'x0' must only have one dimension."
+ with assert_raises(ValueError, match=msg):
+ optimize.minimize(lambda x: x, np.ones((2, 1)))
+
+ @pytest.mark.parametrize('method', ('nelder-mead', 'l-bfgs-b', 'tnc',
+ 'powell', 'cobyla', 'cobyqa',
+ 'trust-constr'))
+ def test_minimize_invalid_bounds(self, method):
+ def f(x):
+ return np.sum(x**2)
+
+ bounds = Bounds([1, 2], [3, 4])
+ msg = 'The number of bounds is not compatible with the length of `x0`.'
+ with pytest.raises(ValueError, match=msg):
+ optimize.minimize(f, x0=[1, 2, 3], method=method, bounds=bounds)
+
+ bounds = Bounds([1, 6, 1], [3, 4, 2])
+ msg = 'An upper bound is less than the corresponding lower bound.'
+ with pytest.raises(ValueError, match=msg):
+ optimize.minimize(f, x0=[1, 2, 3], method=method, bounds=bounds)
+
+ @pytest.mark.parametrize('method', ['bfgs', 'cg', 'newton-cg', 'powell'])
+ def test_minimize_warnings_gh1953(self, method):
+ # test that minimize methods produce warnings rather than just using
+ # `print`; see gh-1953.
+ kwargs = {} if method=='powell' else {'jac': optimize.rosen_der}
+ warning_type = (RuntimeWarning if method=='powell'
+ else optimize.OptimizeWarning)
+
+ options = {'disp': True, 'maxiter': 10}
+ with pytest.warns(warning_type, match='Maximum number'):
+ optimize.minimize(lambda x: optimize.rosen(x), [0, 0],
+ method=method, options=options, **kwargs)
+
+ options['disp'] = False
+ optimize.minimize(lambda x: optimize.rosen(x), [0, 0],
+ method=method, options=options, **kwargs)
+
+
+@pytest.mark.parametrize(
+ 'method',
+ ['l-bfgs-b', 'tnc', 'Powell', 'Nelder-Mead', 'cobyqa']
+)
+def test_minimize_with_scalar(method):
+ # checks that minimize works with a scalar being provided to it.
+ def f(x):
+ return np.sum(x ** 2)
+
+ res = optimize.minimize(f, 17, bounds=[(-100, 100)], method=method)
+ assert res.success
+ assert_allclose(res.x, [0.0], atol=1e-5)
+
+
+class TestLBFGSBBounds:
+ def setup_method(self):
+ self.bounds = ((1, None), (None, None))
+ self.solution = (1, 0)
+
+ def fun(self, x, p=2.0):
+ return 1.0 / p * (x[0]**p + x[1]**p)
+
+ def jac(self, x, p=2.0):
+ return x**(p - 1)
+
+ def fj(self, x, p=2.0):
+ return self.fun(x, p), self.jac(x, p)
+
+ def test_l_bfgs_b_bounds(self):
+ x, f, d = optimize.fmin_l_bfgs_b(self.fun, [0, -1],
+ fprime=self.jac,
+ bounds=self.bounds)
+ assert d['warnflag'] == 0, d['task']
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ def test_l_bfgs_b_funjac(self):
+ # L-BFGS-B with fun and jac combined and extra arguments
+ x, f, d = optimize.fmin_l_bfgs_b(self.fj, [0, -1], args=(2.0, ),
+ bounds=self.bounds)
+ assert d['warnflag'] == 0, d['task']
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ def test_minimize_l_bfgs_b_bounds(self):
+ # Minimize with method='L-BFGS-B' with bounds
+ res = optimize.minimize(self.fun, [0, -1], method='L-BFGS-B',
+ jac=self.jac, bounds=self.bounds)
+ assert res['success'], res['message']
+ assert_allclose(res.x, self.solution, atol=1e-6)
+
+ @pytest.mark.parametrize('bounds', [
+ ([(10, 1), (1, 10)]),
+ ([(1, 10), (10, 1)]),
+ ([(10, 1), (10, 1)])
+ ])
+ def test_minimize_l_bfgs_b_incorrect_bounds(self, bounds):
+ with pytest.raises(ValueError, match='.*bound.*'):
+ optimize.minimize(self.fun, [0, -1], method='L-BFGS-B',
+ jac=self.jac, bounds=bounds)
+
+ def test_minimize_l_bfgs_b_bounds_FD(self):
+ # test that initial starting value outside bounds doesn't raise
+ # an error (done with clipping).
+ # test all different finite differences combos, with and without args
+
+ jacs = ['2-point', '3-point', None]
+ argss = [(2.,), ()]
+ for jac, args in itertools.product(jacs, argss):
+ res = optimize.minimize(self.fun, [0, -1], args=args,
+ method='L-BFGS-B',
+ jac=jac, bounds=self.bounds,
+ options={'finite_diff_rel_step': None})
+ assert res['success'], res['message']
+ assert_allclose(res.x, self.solution, atol=1e-6)
+
+
+class TestOptimizeScalar:
+ def setup_method(self):
+ self.solution = 1.5
+
+ def fun(self, x, a=1.5):
+ """Objective function"""
+ return (x - a)**2 - 0.8
+
+ def test_brent(self):
+ x = optimize.brent(self.fun)
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.brent(self.fun, brack=(-3, -2))
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.brent(self.fun, full_output=True)
+ assert_allclose(x[0], self.solution, atol=1e-6)
+
+ x = optimize.brent(self.fun, brack=(-15, -1, 15))
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ message = r"\(f\(xb\) < f\(xa\)\) and \(f\(xb\) < f\(xc\)\)"
+ with pytest.raises(ValueError, match=message):
+ optimize.brent(self.fun, brack=(-1, 0, 1))
+
+ message = r"\(xa < xb\) and \(xb < xc\)"
+ with pytest.raises(ValueError, match=message):
+ optimize.brent(self.fun, brack=(0, -1, 1))
+
+ @pytest.mark.filterwarnings('ignore::UserWarning')
+ def test_golden(self):
+ x = optimize.golden(self.fun)
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.golden(self.fun, brack=(-3, -2))
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.golden(self.fun, full_output=True)
+ assert_allclose(x[0], self.solution, atol=1e-6)
+
+ x = optimize.golden(self.fun, brack=(-15, -1, 15))
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.golden(self.fun, tol=0)
+ assert_allclose(x, self.solution)
+
+ maxiter_test_cases = [0, 1, 5]
+ for maxiter in maxiter_test_cases:
+ x0 = optimize.golden(self.fun, maxiter=0, full_output=True)
+ x = optimize.golden(self.fun, maxiter=maxiter, full_output=True)
+ nfev0, nfev = x0[2], x[2]
+ assert_equal(nfev - nfev0, maxiter)
+
+ message = r"\(f\(xb\) < f\(xa\)\) and \(f\(xb\) < f\(xc\)\)"
+ with pytest.raises(ValueError, match=message):
+ optimize.golden(self.fun, brack=(-1, 0, 1))
+
+ message = r"\(xa < xb\) and \(xb < xc\)"
+ with pytest.raises(ValueError, match=message):
+ optimize.golden(self.fun, brack=(0, -1, 1))
+
+ def test_fminbound(self):
+ x = optimize.fminbound(self.fun, 0, 1)
+ assert_allclose(x, 1, atol=1e-4)
+
+ x = optimize.fminbound(self.fun, 1, 5)
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.fminbound(self.fun, np.array([1]), np.array([5]))
+ assert_allclose(x, self.solution, atol=1e-6)
+ assert_raises(ValueError, optimize.fminbound, self.fun, 5, 1)
+
+ def test_fminbound_scalar(self):
+ with pytest.raises(ValueError, match='.*must be finite scalars.*'):
+ optimize.fminbound(self.fun, np.zeros((1, 2)), 1)
+
+ x = optimize.fminbound(self.fun, 1, np.array(5))
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ def test_gh11207(self):
+ def fun(x):
+ return x**2
+ optimize.fminbound(fun, 0, 0)
+
+ def test_minimize_scalar(self):
+ # combine all tests above for the minimize_scalar wrapper
+ x = optimize.minimize_scalar(self.fun).x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, method='Brent')
+ assert x.success
+
+ x = optimize.minimize_scalar(self.fun, method='Brent',
+ options=dict(maxiter=3))
+ assert not x.success
+
+ x = optimize.minimize_scalar(self.fun, bracket=(-3, -2),
+ args=(1.5, ), method='Brent').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, method='Brent',
+ args=(1.5,)).x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, bracket=(-15, -1, 15),
+ args=(1.5, ), method='Brent').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, bracket=(-3, -2),
+ args=(1.5, ), method='golden').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, method='golden',
+ args=(1.5,)).x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, bracket=(-15, -1, 15),
+ args=(1.5, ), method='golden').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, bounds=(0, 1), args=(1.5,),
+ method='Bounded').x
+ assert_allclose(x, 1, atol=1e-4)
+
+ x = optimize.minimize_scalar(self.fun, bounds=(1, 5), args=(1.5, ),
+ method='bounded').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ x = optimize.minimize_scalar(self.fun, bounds=(np.array([1]),
+ np.array([5])),
+ args=(np.array([1.5]), ),
+ method='bounded').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ assert_raises(ValueError, optimize.minimize_scalar, self.fun,
+ bounds=(5, 1), method='bounded', args=(1.5, ))
+
+ assert_raises(ValueError, optimize.minimize_scalar, self.fun,
+ bounds=(np.zeros(2), 1), method='bounded', args=(1.5, ))
+
+ x = optimize.minimize_scalar(self.fun, bounds=(1, np.array(5)),
+ method='bounded').x
+ assert_allclose(x, self.solution, atol=1e-6)
+
+ def test_minimize_scalar_custom(self):
+ # This function comes from the documentation example.
+ def custmin(fun, bracket, args=(), maxfev=None, stepsize=0.1,
+ maxiter=100, callback=None, **options):
+ bestx = (bracket[1] + bracket[0]) / 2.0
+ besty = fun(bestx)
+ funcalls = 1
+ niter = 0
+ improved = True
+ stop = False
+
+ while improved and not stop and niter < maxiter:
+ improved = False
+ niter += 1
+ for testx in [bestx - stepsize, bestx + stepsize]:
+ testy = fun(testx, *args)
+ funcalls += 1
+ if testy < besty:
+ besty = testy
+ bestx = testx
+ improved = True
+ if callback is not None:
+ callback(bestx)
+ if maxfev is not None and funcalls >= maxfev:
+ stop = True
+ break
+
+ return optimize.OptimizeResult(fun=besty, x=bestx, nit=niter,
+ nfev=funcalls, success=(niter > 1))
+
+ res = optimize.minimize_scalar(self.fun, bracket=(0, 4),
+ method=custmin,
+ options=dict(stepsize=0.05))
+ assert_allclose(res.x, self.solution, atol=1e-6)
+
+ def test_minimize_scalar_coerce_args_param(self):
+ # Regression test for gh-3503
+ optimize.minimize_scalar(self.fun, args=1.5)
+
+ @pytest.mark.parametrize('method', ['brent', 'bounded', 'golden'])
+ def test_disp(self, method):
+ # test that all minimize_scalar methods accept a disp option.
+ for disp in [0, 1, 2, 3]:
+ optimize.minimize_scalar(self.fun, options={"disp": disp})
+
+ @pytest.mark.parametrize('method', ['brent', 'bounded', 'golden'])
+ def test_result_attributes(self, method):
+ kwargs = {"bounds": [-10, 10]} if method == 'bounded' else {}
+ result = optimize.minimize_scalar(self.fun, method=method, **kwargs)
+ assert hasattr(result, "x")
+ assert hasattr(result, "success")
+ assert hasattr(result, "message")
+ assert hasattr(result, "fun")
+ assert hasattr(result, "nfev")
+ assert hasattr(result, "nit")
+
+ @pytest.mark.filterwarnings('ignore::UserWarning')
+ @pytest.mark.parametrize('method', ['brent', 'bounded', 'golden'])
+ def test_nan_values(self, method):
+ # Check nan values result to failed exit status
+
+ count = [0]
+
+ def func(x):
+ count[0] += 1
+ if count[0] > 4:
+ return np.nan
+ else:
+ return x**2 + 0.1 * np.sin(x)
+
+ bracket = (-1, 0, 1)
+ bounds = (-1, 1)
+
+ with np.errstate(invalid='ignore'), warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "delta_grad == 0.*", UserWarning)
+ warnings.filterwarnings(
+ "ignore", ".*does not use Hessian.*", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", ".*does not use gradient.*", RuntimeWarning)
+
+ count = [0]
+
+ kwargs = {"bounds": bounds} if method == 'bounded' else {}
+ sol = optimize.minimize_scalar(func, bracket=bracket,
+ **kwargs, method=method,
+ options=dict(maxiter=20))
+ assert_equal(sol.success, False)
+
+ def test_minimize_scalar_defaults_gh10911(self):
+ # Previously, bounds were silently ignored unless `method='bounds'`
+ # was chosen. See gh-10911. Check that this is no longer the case.
+ def f(x):
+ return x**2
+
+ res = optimize.minimize_scalar(f)
+ assert_allclose(res.x, 0, atol=1e-8)
+
+ res = optimize.minimize_scalar(f, bounds=(1, 100),
+ options={'xatol': 1e-10})
+ assert_allclose(res.x, 1)
+
+ def test_minimize_non_finite_bounds_gh10911(self):
+ # Previously, minimize_scalar misbehaved with infinite bounds.
+ # See gh-10911. Check that it now raises an error, instead.
+ msg = "Optimization bounds must be finite scalars."
+ with pytest.raises(ValueError, match=msg):
+ optimize.minimize_scalar(np.sin, bounds=(1, np.inf))
+ with pytest.raises(ValueError, match=msg):
+ optimize.minimize_scalar(np.sin, bounds=(np.nan, 1))
+
+ @pytest.mark.parametrize("method", ['brent', 'golden'])
+ def test_minimize_unbounded_method_with_bounds_gh10911(self, method):
+ # Previously, `bounds` were silently ignored when `method='brent'` or
+ # `method='golden'`. See gh-10911. Check that error is now raised.
+ msg = "Use of `bounds` is incompatible with..."
+ with pytest.raises(ValueError, match=msg):
+ optimize.minimize_scalar(np.sin, method=method, bounds=(1, 2))
+
+ @pytest.mark.filterwarnings('ignore::RuntimeWarning')
+ @pytest.mark.parametrize("method", MINIMIZE_SCALAR_METHODS)
+ @pytest.mark.parametrize("tol", [1, 1e-6])
+ @pytest.mark.parametrize("fshape", [(), (1,), (1, 1)])
+ def test_minimize_scalar_dimensionality_gh16196(self, method, tol, fshape):
+ # gh-16196 reported that the output shape of `minimize_scalar` was not
+ # consistent when an objective function returned an array. Check that
+ # `res.fun` and `res.x` are now consistent.
+ def f(x):
+ return np.array(x**4).reshape(fshape)
+
+ a, b = -0.1, 0.2
+ kwargs = (dict(bracket=(a, b)) if method != "bounded"
+ else dict(bounds=(a, b)))
+ kwargs.update(dict(method=method, tol=tol))
+
+ res = optimize.minimize_scalar(f, **kwargs)
+ assert res.x.shape == res.fun.shape == f(res.x).shape == fshape
+
+ @pytest.mark.parametrize('method', ['bounded', 'brent', 'golden'])
+ def test_minimize_scalar_warnings_gh1953(self, method):
+ # test that minimize_scalar methods produce warnings rather than just
+ # using `print`; see gh-1953.
+ def f(x):
+ return (x - 1)**2
+
+ kwargs = {}
+ kwd = 'bounds' if method == 'bounded' else 'bracket'
+ kwargs[kwd] = [-2, 10]
+
+ options = {'disp': True, 'maxiter': 3}
+ with pytest.warns(optimize.OptimizeWarning, match='Maximum number'):
+ optimize.minimize_scalar(f, method=method, options=options,
+ **kwargs)
+
+ options['disp'] = False
+ optimize.minimize_scalar(f, method=method, options=options, **kwargs)
+
+
+class TestBracket:
+
+ @pytest.mark.filterwarnings('ignore::RuntimeWarning')
+ def test_errors_and_status_false(self):
+ # Check that `bracket` raises the errors it is supposed to
+ def f(x): # gh-14858
+ return x**2 if ((-1 < x) & (x < 1)) else 100.0
+
+ message = "The algorithm terminated without finding a valid bracket."
+ with pytest.raises(RuntimeError, match=message):
+ optimize.bracket(f, -1, 1)
+ with pytest.raises(RuntimeError, match=message):
+ optimize.bracket(f, -1, np.inf)
+ with pytest.raises(RuntimeError, match=message):
+ optimize.brent(f, brack=(-1, 1))
+ with pytest.raises(RuntimeError, match=message):
+ optimize.golden(f, brack=(-1, 1))
+
+ def f(x): # gh-5899
+ return -5 * x**5 + 4 * x**4 - 12 * x**3 + 11 * x**2 - 2 * x + 1
+
+ message = "No valid bracket was found before the iteration limit..."
+ with pytest.raises(RuntimeError, match=message):
+ optimize.bracket(f, -0.5, 0.5, maxiter=10)
+
+ @pytest.mark.parametrize('method', ('brent', 'golden'))
+ def test_minimize_scalar_success_false(self, method):
+ # Check that status information from `bracket` gets to minimize_scalar
+ def f(x): # gh-14858
+ return x**2 if ((-1 < x) & (x < 1)) else 100.0
+
+ message = "The algorithm terminated without finding a valid bracket."
+
+ res = optimize.minimize_scalar(f, bracket=(-1, 1), method=method)
+ assert not res.success
+ assert message in res.message
+ assert res.nfev == 3
+ assert res.nit == 0
+ assert res.fun == 100
+
+
+def test_brent_negative_tolerance():
+ assert_raises(ValueError, optimize.brent, np.cos, tol=-.01)
+
+
+class TestNewtonCg:
+ def test_rosenbrock(self):
+ x0 = np.array([-1.2, 1.0])
+ sol = optimize.minimize(optimize.rosen, x0,
+ jac=optimize.rosen_der,
+ hess=optimize.rosen_hess,
+ tol=1e-5,
+ method='Newton-CG')
+ assert sol.success, sol.message
+ assert_allclose(sol.x, np.array([1, 1]), rtol=1e-4)
+
+ def test_himmelblau(self):
+ x0 = np.array(himmelblau_x0)
+ sol = optimize.minimize(himmelblau,
+ x0,
+ jac=himmelblau_grad,
+ hess=himmelblau_hess,
+ method='Newton-CG',
+ tol=1e-6)
+ assert sol.success, sol.message
+ assert_allclose(sol.x, himmelblau_xopt, rtol=1e-4)
+ assert_allclose(sol.fun, himmelblau_min, atol=1e-4)
+
+ def test_finite_difference(self):
+ x0 = np.array([-1.2, 1.0])
+ sol = optimize.minimize(optimize.rosen, x0,
+ jac=optimize.rosen_der,
+ hess='2-point',
+ tol=1e-5,
+ method='Newton-CG')
+ assert sol.success, sol.message
+ assert_allclose(sol.x, np.array([1, 1]), rtol=1e-4)
+
+ def test_hessian_update_strategy(self):
+ x0 = np.array([-1.2, 1.0])
+ sol = optimize.minimize(optimize.rosen, x0,
+ jac=optimize.rosen_der,
+ hess=optimize.BFGS(),
+ tol=1e-5,
+ method='Newton-CG')
+ assert sol.success, sol.message
+ assert_allclose(sol.x, np.array([1, 1]), rtol=1e-4)
+
+
+def test_line_for_search():
+ # _line_for_search is only used in _linesearch_powell, which is also
+ # tested below. Thus there are more tests of _line_for_search in the
+ # test_linesearch_powell_bounded function.
+
+ line_for_search = optimize._optimize._line_for_search
+ # args are x0, alpha, lower_bound, upper_bound
+ # returns lmin, lmax
+
+ lower_bound = np.array([-5.3, -1, -1.5, -3])
+ upper_bound = np.array([1.9, 1, 2.8, 3])
+
+ # test when starting in the bounds
+ x0 = np.array([0., 0, 0, 0])
+ # and when starting outside of the bounds
+ x1 = np.array([0., 2, -3, 0])
+
+ all_tests = (
+ (x0, np.array([1., 0, 0, 0]), -5.3, 1.9),
+ (x0, np.array([0., 1, 0, 0]), -1, 1),
+ (x0, np.array([0., 0, 1, 0]), -1.5, 2.8),
+ (x0, np.array([0., 0, 0, 1]), -3, 3),
+ (x0, np.array([1., 1, 0, 0]), -1, 1),
+ (x0, np.array([1., 0, -1, 2]), -1.5, 1.5),
+ (x0, np.array([2., 0, -1, 2]), -1.5, 0.95),
+ (x1, np.array([1., 0, 0, 0]), -5.3, 1.9),
+ (x1, np.array([0., 1, 0, 0]), -3, -1),
+ (x1, np.array([0., 0, 1, 0]), 1.5, 5.8),
+ (x1, np.array([0., 0, 0, 1]), -3, 3),
+ (x1, np.array([1., 1, 0, 0]), -3, -1),
+ (x1, np.array([1., 0, -1, 0]), -5.3, -1.5),
+ )
+
+ for x, alpha, lmin, lmax in all_tests:
+ mi, ma = line_for_search(x, alpha, lower_bound, upper_bound)
+ assert_allclose(mi, lmin, atol=1e-6)
+ assert_allclose(ma, lmax, atol=1e-6)
+
+ # now with infinite bounds
+ lower_bound = np.array([-np.inf, -1, -np.inf, -3])
+ upper_bound = np.array([np.inf, 1, 2.8, np.inf])
+
+ all_tests = (
+ (x0, np.array([1., 0, 0, 0]), -np.inf, np.inf),
+ (x0, np.array([0., 1, 0, 0]), -1, 1),
+ (x0, np.array([0., 0, 1, 0]), -np.inf, 2.8),
+ (x0, np.array([0., 0, 0, 1]), -3, np.inf),
+ (x0, np.array([1., 1, 0, 0]), -1, 1),
+ (x0, np.array([1., 0, -1, 2]), -1.5, np.inf),
+ (x1, np.array([1., 0, 0, 0]), -np.inf, np.inf),
+ (x1, np.array([0., 1, 0, 0]), -3, -1),
+ (x1, np.array([0., 0, 1, 0]), -np.inf, 5.8),
+ (x1, np.array([0., 0, 0, 1]), -3, np.inf),
+ (x1, np.array([1., 1, 0, 0]), -3, -1),
+ (x1, np.array([1., 0, -1, 0]), -5.8, np.inf),
+ )
+
+ for x, alpha, lmin, lmax in all_tests:
+ mi, ma = line_for_search(x, alpha, lower_bound, upper_bound)
+ assert_allclose(mi, lmin, atol=1e-6)
+ assert_allclose(ma, lmax, atol=1e-6)
+
+
+def test_linesearch_powell():
+ # helper function in optimize.py, not a public function.
+ linesearch_powell = optimize._optimize._linesearch_powell
+ # args are func, p, xi, fval, lower_bound=None, upper_bound=None, tol=1e-3
+ # returns new_fval, p + direction, direction
+ def func(x):
+ return np.sum((x - np.array([-1.0, 2.0, 1.5, -0.4])) ** 2)
+ p0 = np.array([0., 0, 0, 0])
+ fval = func(p0)
+ lower_bound = np.array([-np.inf] * 4)
+ upper_bound = np.array([np.inf] * 4)
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), -1),
+ (np.array([0., 1, 0, 0]), 2),
+ (np.array([0., 0, 1, 0]), 1.5),
+ (np.array([0., 0, 0, 1]), -.4),
+ (np.array([-1., 0, 1, 0]), 1.25),
+ (np.array([0., 0, 1, 1]), .55),
+ (np.array([2., 0, -1, 1]), -.65),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi,
+ fval=fval, tol=1e-5)
+ assert_allclose(f, func(l * xi), atol=1e-6)
+ assert_allclose(p, l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(l * xi), atol=1e-6)
+ assert_allclose(p, l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+
+def test_linesearch_powell_bounded():
+ # helper function in optimize.py, not a public function.
+ linesearch_powell = optimize._optimize._linesearch_powell
+ # args are func, p, xi, fval, lower_bound=None, upper_bound=None, tol=1e-3
+ # returns new_fval, p+direction, direction
+ def func(x):
+ return np.sum((x - np.array([-1.0, 2.0, 1.5, -0.4])) ** 2)
+ p0 = np.array([0., 0, 0, 0])
+ fval = func(p0)
+
+ # first choose bounds such that the same tests from
+ # test_linesearch_powell should pass.
+ lower_bound = np.array([-2.]*4)
+ upper_bound = np.array([2.]*4)
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), -1),
+ (np.array([0., 1, 0, 0]), 2),
+ (np.array([0., 0, 1, 0]), 1.5),
+ (np.array([0., 0, 0, 1]), -.4),
+ (np.array([-1., 0, 1, 0]), 1.25),
+ (np.array([0., 0, 1, 1]), .55),
+ (np.array([2., 0, -1, 1]), -.65),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(l * xi), atol=1e-6)
+ assert_allclose(p, l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+ # now choose bounds such that unbounded vs bounded gives different results
+ lower_bound = np.array([-.3]*3 + [-1])
+ upper_bound = np.array([.45]*3 + [.9])
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), -.3),
+ (np.array([0., 1, 0, 0]), .45),
+ (np.array([0., 0, 1, 0]), .45),
+ (np.array([0., 0, 0, 1]), -.4),
+ (np.array([-1., 0, 1, 0]), .3),
+ (np.array([0., 0, 1, 1]), .45),
+ (np.array([2., 0, -1, 1]), -.15),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(l * xi), atol=1e-6)
+ assert_allclose(p, l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+ # now choose as above but start outside the bounds
+ p0 = np.array([-1., 0, 0, 2])
+ fval = func(p0)
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), .7),
+ (np.array([0., 1, 0, 0]), .45),
+ (np.array([0., 0, 1, 0]), .45),
+ (np.array([0., 0, 0, 1]), -2.4),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(p0 + l * xi), atol=1e-6)
+ assert_allclose(p, p0 + l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+ # now mix in inf
+ p0 = np.array([0., 0, 0, 0])
+ fval = func(p0)
+
+ # now choose bounds that mix inf
+ lower_bound = np.array([-.3, -np.inf, -np.inf, -1])
+ upper_bound = np.array([np.inf, .45, np.inf, .9])
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), -.3),
+ (np.array([0., 1, 0, 0]), .45),
+ (np.array([0., 0, 1, 0]), 1.5),
+ (np.array([0., 0, 0, 1]), -.4),
+ (np.array([-1., 0, 1, 0]), .3),
+ (np.array([0., 0, 1, 1]), .55),
+ (np.array([2., 0, -1, 1]), -.15),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(l * xi), atol=1e-6)
+ assert_allclose(p, l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+ # now choose as above but start outside the bounds
+ p0 = np.array([-1., 0, 0, 2])
+ fval = func(p0)
+
+ all_tests = (
+ (np.array([1., 0, 0, 0]), .7),
+ (np.array([0., 1, 0, 0]), .45),
+ (np.array([0., 0, 1, 0]), 1.5),
+ (np.array([0., 0, 0, 1]), -2.4),
+ )
+
+ for xi, l in all_tests:
+ f, p, direction = linesearch_powell(func, p0, xi, tol=1e-5,
+ lower_bound=lower_bound,
+ upper_bound=upper_bound,
+ fval=fval)
+ assert_allclose(f, func(p0 + l * xi), atol=1e-6)
+ assert_allclose(p, p0 + l * xi, atol=1e-6)
+ assert_allclose(direction, l * xi, atol=1e-6)
+
+
+def test_powell_limits():
+ # gh15342 - powell was going outside bounds for some function evaluations.
+ bounds = optimize.Bounds([0, 0], [0.6, 20])
+
+ def fun(x):
+ a, b = x
+ assert (x >= bounds.lb).all() and (x <= bounds.ub).all()
+ return a ** 2 + b ** 2
+
+ optimize.minimize(fun, x0=[0.6, 20], method='Powell', bounds=bounds)
+
+ # Another test from the original report - gh-13411
+ bounds = optimize.Bounds(lb=[0,], ub=[1,], keep_feasible=[True,])
+
+ def func(x):
+ assert x >= 0 and x <= 1
+ return np.exp(x)
+
+ optimize.minimize(fun=func, x0=[0.5], method='powell', bounds=bounds)
+
+
+def test_powell_output():
+ funs = [rosen, lambda x: np.array(rosen(x)), lambda x: np.array([rosen(x)])]
+ for fun in funs:
+ res = optimize.minimize(fun, x0=[0.6, 20], method='Powell')
+ assert np.isscalar(res.fun)
+
+
+class TestRosen:
+ @make_xp_test_case(optimize.rosen)
+ def test_rosen(self, xp):
+ # integer input should be promoted to the default floating type
+ x = xp.asarray([1, 1, 1])
+ xp_assert_equal(optimize.rosen(x),
+ xp.asarray(0.))
+
+ @make_xp_test_case(optimize.rosen_der)
+ def test_rosen_der(self, xp):
+ x = xp.asarray([1, 1, 1, 1])
+ xp_assert_equal(optimize.rosen_der(x),
+ xp.zeros_like(x, dtype=xp.asarray(1.).dtype))
+
+ @make_xp_test_case(optimize.rosen_hess, optimize.rosen_hess_prod)
+ def test_hess_prod(self, xp):
+ one = xp.asarray(1.)
+
+ # Compare rosen_hess(x) times p with rosen_hess_prod(x,p). See gh-1775.
+ x = xp.asarray([3, 4, 5])
+ p = xp.asarray([2, 2, 2])
+ hp = optimize.rosen_hess_prod(x, p)
+ p = xp.astype(p, one.dtype)
+ dothp = optimize.rosen_hess(x) @ p
+ xp_assert_equal(hp, dothp)
+
+
+def himmelblau(p):
+ """
+ R^2 -> R^1 test function for optimization. The function has four local
+ minima where himmelblau(xopt) == 0.
+ """
+ x, y = p
+ a = x*x + y - 11
+ b = x + y*y - 7
+ return a*a + b*b
+
+
+def himmelblau_grad(p):
+ x, y = p
+ return np.array([4*x**3 + 4*x*y - 42*x + 2*y**2 - 14,
+ 2*x**2 + 4*x*y + 4*y**3 - 26*y - 22])
+
+
+def himmelblau_hess(p):
+ x, y = p
+ return np.array([[12*x**2 + 4*y - 42, 4*x + 4*y],
+ [4*x + 4*y, 4*x + 12*y**2 - 26]])
+
+
+himmelblau_x0 = [-0.27, -0.9]
+himmelblau_xopt = [3, 2]
+himmelblau_min = 0.0
+
+
+def test_minimize_multiple_constraints():
+ # Regression test for gh-4240.
+ def func(x):
+ return np.array([25 - 0.2 * x[0] - 0.4 * x[1] - 0.33 * x[2]])
+
+ def func1(x):
+ return np.array([x[1]])
+
+ def func2(x):
+ return np.array([x[2]])
+
+ cons = ({'type': 'ineq', 'fun': func},
+ {'type': 'ineq', 'fun': func1},
+ {'type': 'ineq', 'fun': func2})
+
+ def f(x):
+ return -1 * (x[0] + x[1] + x[2])
+
+ res = optimize.minimize(f, [0, 0, 0], method='SLSQP', constraints=cons)
+ assert_allclose(res.x, [125, 0, 0], atol=1e-10)
+
+
+class TestOptimizeResultAttributes:
+ # Test that all minimizers return an OptimizeResult containing
+ # all the OptimizeResult attributes
+ def setup_method(self):
+ self.x0 = [5, 5]
+ self.func = optimize.rosen
+ self.jac = optimize.rosen_der
+ self.hess = optimize.rosen_hess
+ self.hessp = optimize.rosen_hess_prod
+ self.bounds = [(0., 10.), (0., 10.)]
+
+ @pytest.mark.fail_slow(2)
+ def test_attributes_present(self):
+ attributes = ['nit', 'nfev', 'x', 'success', 'status', 'fun',
+ 'message']
+ skip = {'cobyla': ['nit']}
+ for method in MINIMIZE_METHODS:
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore",
+ ("Method .+ does not use (gradient|Hessian.*)"
+ " information"), RuntimeWarning)
+ res = optimize.minimize(self.func, self.x0, method=method,
+ jac=self.jac, hess=self.hess,
+ hessp=self.hessp)
+ for attribute in attributes:
+ if method in skip and attribute in skip[method]:
+ continue
+
+ assert hasattr(res, attribute)
+ assert attribute in dir(res)
+
+ # gh13001, OptimizeResult.message should be a str
+ assert isinstance(res.message, str)
+
+
+def f1(z, *params):
+ x, y = z
+ a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ return (a * x**2 + b * x * y + c * y**2 + d*x + e*y + f)
+
+
+def f2(z, *params):
+ x, y = z
+ a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ return (-g*np.exp(-((x-h)**2 + (y-i)**2) / scale))
+
+
+def f3(z, *params):
+ x, y = z
+ a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ return (-j*np.exp(-((x-k)**2 + (y-l)**2) / scale))
+
+
+def brute_func(z, *params):
+ return f1(z, *params) + f2(z, *params) + f3(z, *params)
+
+
+class TestBrute:
+ # Test the "brute force" method
+ def setup_method(self):
+ self.params = (2, 3, 7, 8, 9, 10, 44, -1, 2, 26, 1, -2, 0.5)
+ self.rranges = (slice(-4, 4, 0.25), slice(-4, 4, 0.25))
+ self.solution = np.array([-1.05665192, 1.80834843])
+
+ def brute_func(self, z, *params):
+ # an instance method optimizing
+ return brute_func(z, *params)
+
+ def test_brute(self):
+ # test fmin
+ resbrute = optimize.brute(brute_func, self.rranges, args=self.params,
+ full_output=True, finish=optimize.fmin)
+ assert_allclose(resbrute[0], self.solution, atol=1e-3)
+ assert_allclose(resbrute[1], brute_func(self.solution, *self.params),
+ atol=1e-3)
+
+ # test minimize
+ resbrute = optimize.brute(brute_func, self.rranges, args=self.params,
+ full_output=True,
+ finish=optimize.minimize)
+ assert_allclose(resbrute[0], self.solution, atol=1e-3)
+ assert_allclose(resbrute[1], brute_func(self.solution, *self.params),
+ atol=1e-3)
+
+ # test that brute can optimize an instance method (the other tests use
+ # a non-class based function
+ resbrute = optimize.brute(self.brute_func, self.rranges,
+ args=self.params, full_output=True,
+ finish=optimize.minimize)
+ assert_allclose(resbrute[0], self.solution, atol=1e-3)
+
+ def test_1D(self):
+ # test that for a 1-D problem the test function is passed an array,
+ # not a scalar.
+ def f(x):
+ assert len(x.shape) == 1
+ assert x.shape[0] == 1
+ return x ** 2
+
+ optimize.brute(f, [(-1, 1)], Ns=3, finish=None)
+
+ @pytest.mark.fail_slow(10)
+ def test_workers(self):
+ # check that parallel evaluation works
+ resbrute = optimize.brute(brute_func, self.rranges, args=self.params,
+ full_output=True, finish=None)
+
+ resbrute1 = optimize.brute(brute_func, self.rranges, args=self.params,
+ full_output=True, finish=None, workers=2)
+
+ assert_allclose(resbrute1[-1], resbrute[-1])
+ assert_allclose(resbrute1[0], resbrute[0])
+
+ def test_runtime_warning(self, capsys):
+ rng = np.random.default_rng(1234)
+
+ def func(z, *params):
+ return rng.random(1) * 1000 # never converged problem
+
+ msg = "final optimization did not succeed.*|Maximum number of function eval.*"
+ with pytest.warns(RuntimeWarning, match=msg):
+ optimize.brute(func, self.rranges, args=self.params, disp=True)
+
+ def test_coerce_args_param(self):
+ # optimize.brute should coerce non-iterable args to a tuple.
+ def f(x, *args):
+ return x ** args[0]
+
+ resbrute = optimize.brute(f, (slice(-4, 4, .25),), args=2)
+ assert_allclose(resbrute, 0)
+
+
+@pytest.mark.fail_slow(20)
+def test_cobyla_threadsafe():
+
+ # Verify that cobyla is threadsafe. Will segfault if it is not.
+
+ import concurrent.futures
+ import time
+
+ def objective1(x):
+ time.sleep(0.1)
+ return x[0]**2
+
+ def objective2(x):
+ time.sleep(0.1)
+ return (x[0]-1)**2
+
+ min_method = "COBYLA"
+
+ def minimizer1():
+ return optimize.minimize(objective1,
+ [0.0],
+ method=min_method)
+
+ def minimizer2():
+ return optimize.minimize(objective2,
+ [0.0],
+ method=min_method)
+
+ with concurrent.futures.ThreadPoolExecutor() as pool:
+ tasks = []
+ tasks.append(pool.submit(minimizer1))
+ tasks.append(pool.submit(minimizer2))
+ for t in tasks:
+ t.result()
+
+
+class TestIterationLimits:
+ # Tests that optimisation does not give up before trying requested
+ # number of iterations or evaluations. And that it does not succeed
+ # by exceeding the limits.
+ def setup_method(self):
+ self.funcalls = threading.local()
+
+ def slow_func(self, v):
+ if not hasattr(self.funcalls, 'c'):
+ self.funcalls.c = 0
+ self.funcalls.c += 1
+ r, t = np.sqrt(v[0]**2+v[1]**2), np.arctan2(v[0], v[1])
+ return np.sin(r*20 + t)+r*0.5
+
+ @pytest.mark.fail_slow(10)
+ def test_neldermead_limit(self):
+ self.check_limits("Nelder-Mead", 200)
+
+ def test_powell_limit(self):
+ self.check_limits("powell", 1000)
+
+ def check_limits(self, method, default_iters):
+ for start_v in [[0.1, 0.1], [1, 1], [2, 2]]:
+ for mfev in [50, 500, 5000]:
+ self.funcalls.c = 0
+ res = optimize.minimize(self.slow_func, start_v,
+ method=method,
+ options={"maxfev": mfev})
+ assert self.funcalls.c == res["nfev"]
+ if res["success"]:
+ assert res["nfev"] < mfev
+ else:
+ assert res["nfev"] >= mfev
+ for mit in [50, 500, 5000]:
+ res = optimize.minimize(self.slow_func, start_v,
+ method=method,
+ options={"maxiter": mit})
+ if res["success"]:
+ assert res["nit"] <= mit
+ else:
+ assert res["nit"] >= mit
+ for mfev, mit in [[50, 50], [5000, 5000], [5000, np.inf]]:
+ self.funcalls.c = 0
+ res = optimize.minimize(self.slow_func, start_v,
+ method=method,
+ options={"maxiter": mit,
+ "maxfev": mfev})
+ assert self.funcalls.c == res["nfev"]
+ if res["success"]:
+ assert res["nfev"] < mfev and res["nit"] <= mit
+ else:
+ assert res["nfev"] >= mfev or res["nit"] >= mit
+ for mfev, mit in [[np.inf, None], [None, np.inf]]:
+ self.funcalls.c = 0
+ res = optimize.minimize(self.slow_func, start_v,
+ method=method,
+ options={"maxiter": mit,
+ "maxfev": mfev})
+ assert self.funcalls.c == res["nfev"]
+ if res["success"]:
+ if mfev is None:
+ assert res["nfev"] < default_iters*2
+ else:
+ assert res["nit"] <= default_iters*2
+ else:
+ assert (res["nfev"] >= default_iters*2
+ or res["nit"] >= default_iters*2)
+
+
+def test_result_x_shape_when_len_x_is_one():
+ def fun(x):
+ return x * x
+
+ def jac(x):
+ return 2. * x
+
+ def hess(x):
+ return np.array([[2.]])
+
+ methods = ['Nelder-Mead', 'Powell', 'CG', 'BFGS', 'L-BFGS-B', 'TNC',
+ 'COBYLA', 'COBYQA', 'SLSQP']
+ for method in methods:
+ res = optimize.minimize(fun, np.array([0.1]), method=method)
+ assert res.x.shape == (1,)
+
+ # use jac + hess
+ methods = ['trust-constr', 'dogleg', 'trust-ncg', 'trust-exact',
+ 'trust-krylov', 'Newton-CG']
+ for method in methods:
+ res = optimize.minimize(fun, np.array([0.1]), method=method, jac=jac,
+ hess=hess)
+ assert res.x.shape == (1,)
+
+
+class FunctionWithGradient:
+ def __init__(self):
+ self.number_of_calls = threading.local()
+
+ def __call__(self, x):
+ if not hasattr(self.number_of_calls, 'c'):
+ self.number_of_calls.c = 0
+ self.number_of_calls.c += 1
+ return np.sum(x**2), 2 * x
+
+
+@pytest.fixture
+def function_with_gradient():
+ return FunctionWithGradient()
+
+
+def test_memoize_jac_function_before_gradient(function_with_gradient):
+ memoized_function = MemoizeJac(function_with_gradient)
+
+ x0 = np.array([1.0, 2.0])
+ assert_allclose(memoized_function(x0), 5.0)
+ assert function_with_gradient.number_of_calls.c == 1
+
+ assert_allclose(memoized_function.derivative(x0), 2 * x0)
+ assert function_with_gradient.number_of_calls.c == 1, \
+ "function is not recomputed " \
+ "if gradient is requested after function value"
+
+ assert_allclose(
+ memoized_function(2 * x0), 20.0,
+ err_msg="different input triggers new computation")
+ assert function_with_gradient.number_of_calls.c == 2, \
+ "different input triggers new computation"
+
+
+def test_memoize_jac_gradient_before_function(function_with_gradient):
+ memoized_function = MemoizeJac(function_with_gradient)
+
+ x0 = np.array([1.0, 2.0])
+ assert_allclose(memoized_function.derivative(x0), 2 * x0)
+ assert function_with_gradient.number_of_calls.c == 1
+
+ assert_allclose(memoized_function(x0), 5.0)
+ assert function_with_gradient.number_of_calls.c == 1, \
+ "function is not recomputed " \
+ "if function value is requested after gradient"
+
+ assert_allclose(
+ memoized_function.derivative(2 * x0), 4 * x0,
+ err_msg="different input triggers new computation")
+ assert function_with_gradient.number_of_calls.c == 2, \
+ "different input triggers new computation"
+
+
+def test_memoize_jac_with_bfgs(function_with_gradient):
+ """ Tests that using MemoizedJac in combination with ScalarFunction
+ and BFGS does not lead to repeated function evaluations.
+ Tests changes made in response to GH11868.
+ """
+ memoized_function = MemoizeJac(function_with_gradient)
+ jac = memoized_function.derivative
+ hess = optimize.BFGS()
+
+ x0 = np.array([1.0, 0.5])
+ scalar_function = ScalarFunction(
+ memoized_function, x0, (), jac, hess, None, None)
+ assert function_with_gradient.number_of_calls.c == 1
+
+ scalar_function.fun(x0 + 0.1)
+ assert function_with_gradient.number_of_calls.c == 2
+
+ scalar_function.fun(x0 + 0.2)
+ assert function_with_gradient.number_of_calls.c == 3
+
+
+def test_gh12696():
+ # Test that optimize doesn't throw warning gh-12696
+ with assert_no_warnings():
+ optimize.fminbound(
+ lambda x: np.array([x**2]), -np.pi, np.pi, disp=False)
+
+
+# --- Test minimize with equal upper and lower bounds --- #
+
+def setup_test_equal_bounds():
+ # the success of test_equal_bounds depends on the exact seed
+ rng = np.random.default_rng(12223)
+ x0 = rng.random(4)
+ lb = np.array([0, 2, -1, -1.0])
+ ub = np.array([3, 2, 2, -1.0])
+ i_eb = (lb == ub)
+
+ def check_x(x, check_size=True, check_values=True):
+ if check_size:
+ assert x.size == 4
+ if check_values:
+ assert_allclose(x[i_eb], lb[i_eb])
+
+ def func(x):
+ check_x(x)
+ return optimize.rosen(x)
+
+ def grad(x):
+ check_x(x)
+ return optimize.rosen_der(x)
+
+ def callback(x, *args):
+ check_x(x)
+
+ def callback2(intermediate_result):
+ assert isinstance(intermediate_result, OptimizeResult)
+ check_x(intermediate_result.x)
+
+ def constraint1(x):
+ check_x(x, check_values=False)
+ return x[0:1] - 1
+
+ def jacobian1(x):
+ check_x(x, check_values=False)
+ dc = np.zeros_like(x)
+ dc[0] = 1
+ return dc
+
+ def constraint2(x):
+ check_x(x, check_values=False)
+ return x[2:3] - 0.5
+
+ def jacobian2(x):
+ check_x(x, check_values=False)
+ dc = np.zeros_like(x)
+ dc[2] = 1
+ return dc
+
+ c1a = NonlinearConstraint(constraint1, -np.inf, 0)
+ c1b = NonlinearConstraint(constraint1, -np.inf, 0, jacobian1)
+ c2a = NonlinearConstraint(constraint2, -np.inf, 0)
+ c2b = NonlinearConstraint(constraint2, -np.inf, 0, jacobian2)
+
+ # test using the three methods that accept bounds, use derivatives, and
+ # have some trouble when bounds fix variables
+ methods = ('L-BFGS-B', 'SLSQP', 'TNC')
+
+ # test w/out gradient, w/ gradient, and w/ combined objective/gradient
+ kwds = ({"fun": func, "jac": False},
+ {"fun": func, "jac": grad},
+ {"fun": (lambda x: (func(x), grad(x))),
+ "jac": True})
+
+ # test with both old- and new-style bounds
+ bound_types = (lambda lb, ub: list(zip(lb, ub)),
+ Bounds)
+
+ # Test for many combinations of constraints w/ and w/out jacobian
+ # Pairs in format: (test constraints, reference constraints)
+ # (always use analytical jacobian in reference)
+ constraints = ((None, None), ([], []),
+ (c1a, c1b), (c2b, c2b),
+ ([c1b], [c1b]), ([c2a], [c2b]),
+ ([c1a, c2a], [c1b, c2b]),
+ ([c1a, c2b], [c1b, c2b]),
+ ([c1b, c2b], [c1b, c2b]))
+
+ # test with and without callback function
+ callbacks = (None, callback, callback2)
+
+ data = {"methods": methods, "kwds": kwds, "bound_types": bound_types,
+ "constraints": constraints, "callbacks": callbacks,
+ "lb": lb, "ub": ub, "x0": x0, "i_eb": i_eb}
+
+ return data
+
+
+eb_data = setup_test_equal_bounds()
+
+
+# This test is about handling fixed variables, not the accuracy of the solvers
+@pytest.mark.xfail_on_32bit("Failures due to floating point issues, not logic")
+@pytest.mark.xfail(scipy.show_config(mode='dicts')['Compilers']['fortran']['name'] ==
+ "intel-llvm",
+ reason="Failures due to floating point issues, not logic")
+@pytest.mark.parametrize('method', eb_data["methods"])
+@pytest.mark.parametrize('kwds', eb_data["kwds"])
+@pytest.mark.parametrize('bound_type', eb_data["bound_types"])
+@pytest.mark.parametrize('constraints', eb_data["constraints"])
+@pytest.mark.parametrize('callback', eb_data["callbacks"])
+def test_equal_bounds(method, kwds, bound_type, constraints, callback):
+ """
+ Tests that minimizers still work if (bounds.lb == bounds.ub).any()
+ gh12502 - Divide by zero in Jacobian numerical differentiation when
+ equality bounds constraints are used
+ """
+ # GH-15051; slightly more skips than necessary; hopefully fixed by GH-14882
+ if (platform.machine() == 'aarch64' and method == "TNC"
+ and kwds["jac"] is False and callback is not None):
+ pytest.skip('Tolerance violation on aarch')
+
+ lb, ub = eb_data["lb"], eb_data["ub"]
+ x0, i_eb = eb_data["x0"], eb_data["i_eb"]
+
+ test_constraints, reference_constraints = constraints
+ if test_constraints and not method == 'SLSQP':
+ pytest.skip('Only SLSQP supports nonlinear constraints')
+
+ if method in ['SLSQP', 'TNC'] and callable(callback):
+ sig = inspect.signature(callback)
+ if 'intermediate_result' in set(sig.parameters):
+ pytest.skip("SLSQP, TNC don't support intermediate_result")
+
+ # reference constraints always have analytical jacobian
+ # if test constraints are not the same, we'll need finite differences
+ fd_needed = (test_constraints != reference_constraints)
+
+ bounds = bound_type(lb, ub) # old- or new-style
+
+ kwds.update({"x0": x0, "method": method, "bounds": bounds,
+ "constraints": test_constraints, "callback": callback})
+ res = optimize.minimize(**kwds)
+
+ expected = optimize.minimize(optimize.rosen, x0, method=method,
+ jac=optimize.rosen_der, bounds=bounds,
+ constraints=reference_constraints)
+
+ # compare the output of a solution with FD vs that of an analytic grad
+ assert res.success
+ assert_allclose(res.fun, expected.fun, rtol=5.0e-6)
+ assert_allclose(res.x, expected.x, rtol=5e-4)
+
+ if fd_needed or kwds['jac'] is False:
+ expected.jac[i_eb] = np.nan
+ assert res.jac.shape[0] == 4
+ assert_allclose(res.jac[i_eb], expected.jac[i_eb], rtol=1e-6)
+
+ if not (kwds['jac'] or test_constraints or isinstance(bounds, Bounds)):
+ # compare the output to an equivalent FD minimization that doesn't
+ # need factorization
+ def fun(x):
+ new_x = np.array([np.nan, 2, np.nan, -1])
+ new_x[[0, 2]] = x
+ return optimize.rosen(new_x)
+
+ fd_res = optimize.minimize(fun,
+ x0[[0, 2]],
+ method=method,
+ bounds=bounds[::2])
+ assert_allclose(res.fun, fd_res.fun)
+ # TODO this test should really be equivalent to factorized version
+ # above, down to res.nfev. However, testing found that when TNC is
+ # called with or without a callback the output is different. The two
+ # should be the same! This indicates that the TNC callback may be
+ # mutating something when it shouldn't.
+ assert_allclose(res.x[[0, 2]], fd_res.x, rtol=2e-6)
+
+
+@pytest.mark.parametrize('method', eb_data["methods"])
+def test_all_bounds_equal(method):
+ # this only tests methods that have parameters factored out when lb==ub
+ # it does not test other methods that work with bounds
+ def f(x, p1=1):
+ return np.linalg.norm(x) + p1
+
+ bounds = [(1, 1), (2, 2)]
+ x0 = (1.0, 3.0)
+ res = optimize.minimize(f, x0, bounds=bounds, method=method)
+ assert res.success
+ assert_allclose(res.fun, f([1.0, 2.0]))
+ assert res.nfev == 1
+ assert res.message == 'All independent variables were fixed by bounds.'
+
+ args = (2,)
+ res = optimize.minimize(f, x0, bounds=bounds, method=method, args=args)
+ assert res.success
+ assert_allclose(res.fun, f([1.0, 2.0], 2))
+
+ if method.upper() == 'SLSQP':
+ def con(x):
+ return np.sum(x)
+ nlc = NonlinearConstraint(con, -np.inf, 0.0)
+ res = optimize.minimize(
+ f, x0, bounds=bounds, method=method, constraints=[nlc]
+ )
+ assert res.success is False
+ assert_allclose(res.fun, f([1.0, 2.0]))
+ assert res.nfev == 1
+ message = "All independent variables were fixed by bounds, but"
+ assert res.message.startswith(message)
+
+ nlc = NonlinearConstraint(con, -np.inf, 4)
+ res = optimize.minimize(
+ f, x0, bounds=bounds, method=method, constraints=[nlc]
+ )
+ assert res.success is True
+ assert_allclose(res.fun, f([1.0, 2.0]))
+ assert res.nfev == 1
+ message = "All independent variables were fixed by bounds at values"
+ assert res.message.startswith(message)
+
+
+def test_eb_constraints():
+ # make sure constraint functions aren't overwritten when equal bounds
+ # are employed, and a parameter is factored out. GH14859
+ def f(x):
+ return x[0]**3 + x[1]**2 + x[2]*x[3]
+
+ def cfun(x):
+ return x[0] + x[1] + x[2] + x[3] - 40
+
+ constraints = [{'type': 'ineq', 'fun': cfun}]
+
+ bounds = [(0, 20)] * 4
+ bounds[1] = (5, 5)
+ optimize.minimize(
+ f,
+ x0=[1, 2, 3, 4],
+ method='SLSQP',
+ bounds=bounds,
+ constraints=constraints,
+ )
+ assert constraints[0]['fun'] == cfun
+
+
+def test_show_options():
+ solver_methods = {
+ 'minimize': MINIMIZE_METHODS,
+ 'minimize_scalar': MINIMIZE_SCALAR_METHODS,
+ 'root': ROOT_METHODS,
+ 'root_scalar': ROOT_SCALAR_METHODS,
+ 'linprog': LINPROG_METHODS,
+ 'quadratic_assignment': QUADRATIC_ASSIGNMENT_METHODS,
+ }
+ for solver, methods in solver_methods.items():
+ for method in methods:
+ # testing that `show_options` works without error
+ show_options(solver, method)
+
+ unknown_solver_method = {
+ 'minimize': "ekki", # unknown method
+ 'maximize': "cg", # unknown solver
+ 'maximize_scalar': "ekki", # unknown solver and method
+ }
+ for solver, method in unknown_solver_method.items():
+ # testing that `show_options` raises ValueError
+ assert_raises(ValueError, show_options, solver, method)
+
+
+def test_bounds_with_list():
+ # gh13501. Bounds created with lists weren't working for Powell.
+ bounds = optimize.Bounds(lb=[5., 5.], ub=[10., 10.])
+ optimize.minimize(
+ optimize.rosen, x0=np.array([9, 9]), method='Powell', bounds=bounds
+ )
+
+
+@pytest.mark.parametrize('method', (
+ 'slsqp', 'cg', 'cobyqa', 'powell','nelder-mead', 'bfgs', 'l-bfgs-b',
+ 'trust-constr'))
+def test_minimize_maxiter_noninteger(method):
+ # Regression test for gh-23430
+ x0 = np.array([1.3, 0.7, 0.8, 1.9, 1.2])
+ optimize.minimize(rosen, x0, method=method, options={'maxiter': 100.1})
+
+
+def test_x_overwritten_user_function():
+ # if the user overwrites the x-array in the user function it's likely
+ # that the minimizer stops working properly.
+ # gh13740
+ def fquad(x):
+ a = np.arange(np.size(x))
+ x -= a
+ x *= x
+ return np.sum(x)
+
+ def fquad_jac(x):
+ a = np.arange(np.size(x))
+ x *= 2
+ x -= 2 * a
+ return x
+
+ def fquad_hess(x):
+ return np.eye(np.size(x)) * 2.0
+
+ meth_jac = [
+ 'newton-cg', 'dogleg', 'trust-ncg', 'trust-exact',
+ 'trust-krylov', 'trust-constr'
+ ]
+ meth_hess = [
+ 'dogleg', 'trust-ncg', 'trust-exact', 'trust-krylov', 'trust-constr'
+ ]
+
+ x0 = np.ones(5) * 1.5
+
+ for meth in MINIMIZE_METHODS:
+ jac = None
+ hess = None
+ if meth in meth_jac:
+ jac = fquad_jac
+ if meth in meth_hess:
+ hess = fquad_hess
+ res = optimize.minimize(fquad, x0, method=meth, jac=jac, hess=hess)
+ assert_allclose(res.x, np.arange(np.size(x0)), atol=2e-4)
+
+
+class TestGlobalOptimization:
+
+ def test_optimize_result_attributes(self):
+ def func(x):
+ return x ** 2
+
+ # Note that `brute` solver does not return `OptimizeResult`
+ results = [optimize.basinhopping(func, x0=1),
+ optimize.differential_evolution(func, [(-4, 4)]),
+ optimize.shgo(func, [(-4, 4)]),
+ optimize.dual_annealing(func, [(-4, 4)]),
+ optimize.direct(func, [(-4, 4)]),
+ ]
+
+ for result in results:
+ assert isinstance(result, optimize.OptimizeResult)
+ assert hasattr(result, "x")
+ assert hasattr(result, "success")
+ assert hasattr(result, "message")
+ assert hasattr(result, "fun")
+ assert hasattr(result, "nfev")
+ assert hasattr(result, "nit")
+
+
+def test_approx_fprime():
+ # check that approx_fprime (serviced by approx_derivative) works for
+ # jac and hess
+ g = optimize.approx_fprime(himmelblau_x0, himmelblau)
+ assert_allclose(g, himmelblau_grad(himmelblau_x0), rtol=5e-6)
+
+ h = optimize.approx_fprime(himmelblau_x0, himmelblau_grad)
+ assert_allclose(h, himmelblau_hess(himmelblau_x0), rtol=5e-6)
+
+
+def test_gh12594():
+ # gh-12594 reported an error in `_linesearch_powell` and
+ # `_line_for_search` when `Bounds` was passed lists instead of arrays.
+ # Check that results are the same whether the inputs are lists or arrays.
+
+ def f(x):
+ return x[0]**2 + (x[1] - 1)**2
+
+ bounds = Bounds(lb=[-10, -10], ub=[10, 10])
+ res = optimize.minimize(f, x0=(0, 0), method='Powell', bounds=bounds)
+ bounds = Bounds(lb=np.array([-10, -10]), ub=np.array([10, 10]))
+ ref = optimize.minimize(f, x0=(0, 0), method='Powell', bounds=bounds)
+
+ assert_allclose(res.fun, ref.fun)
+ assert_allclose(res.x, ref.x)
+
+def test_gh12513_trustregion_exact_infinite_loop():
+ # gh-12513 reported that optimize.minimize might hang when
+ # method='trust-exact', using the option ``subproblem_maxiter``,
+ # this can be avoided.
+ H = np.array(
+ [[3.67335930e01, -2.52334820e02, 1.15477558e01, -1.19933725e-03,
+ -2.06408851e03, -2.05821411e00, -2.52334820e02, -6.52076924e02,
+ -2.71362566e-01, -1.98885126e00, 1.22085415e00, 2.30220713e00,
+ -9.71278532e-02, -5.11210123e-01, -1.00399562e00, 1.43319679e-01,
+ 6.03815471e00, -6.38719934e-02, 1.65623929e-01],
+ [-2.52334820e02, 1.76757312e03, -9.92814996e01, 1.06533600e-02,
+ 1.44442941e04, 1.43811694e01, 1.76757312e03, 4.56694461e03,
+ 2.22263363e00, 1.62977318e01, -7.81539315e00, -1.24938012e01,
+ 6.74029088e-01, 3.22802671e00, 5.14978971e00, -9.58561209e-01,
+ -3.92199895e01, 4.47201278e-01, -1.17866744e00],
+ [1.15477558e01, -9.92814996e01, 3.63872363e03, -4.40007197e-01,
+ -9.55435081e02, -1.13985105e00, -9.92814996e01, -2.58307255e02,
+ -5.21335218e01, -3.77485107e02, -6.75338369e01, -1.89457169e02,
+ 5.67828623e00, 5.82402681e00, 1.72734354e01, -4.29114840e00,
+ -7.84885258e01, 3.17594634e00, 2.45242852e00],
+ [-1.19933725e-03, 1.06533600e-02, -4.40007197e-01, 5.73576663e-05,
+ 1.01563710e-01, 1.18838745e-04, 1.06533600e-02, 2.76535767e-02,
+ 6.25788669e-03, 4.50699620e-02, 8.64152333e-03, 2.27772377e-02,
+ -8.51026855e-04, 1.65316383e-04, 1.38977551e-03, 5.51629259e-04,
+ 1.38447755e-02, -5.17956723e-04, -1.29260347e-04],
+ [-2.06408851e03, 1.44442941e04, -9.55435081e02, 1.01563710e-01,
+ 1.23101825e05, 1.26467259e02, 1.44442941e04, 3.74590279e04,
+ 2.18498571e01, 1.60254460e02, -7.52977260e01, -1.17989623e02,
+ 6.58253160e00, 3.14949206e01, 4.98527190e01, -9.33338661e00,
+ -3.80465752e02, 4.33872213e00, -1.14768816e01],
+ [-2.05821411e00, 1.43811694e01, -1.13985105e00, 1.18838745e-04,
+ 1.26467259e02, 1.46226198e-01, 1.43811694e01, 3.74509252e01,
+ 2.76928748e-02, 2.03023837e-01, -8.84279903e-02, -1.29523344e-01,
+ 8.06424434e-03, 3.83330661e-02, 5.81579023e-02, -1.12874980e-02,
+ -4.48118297e-01, 5.15022284e-03, -1.41501894e-02],
+ [-2.52334820e02, 1.76757312e03, -9.92814996e01, 1.06533600e-02,
+ 1.44442941e04, 1.43811694e01, 1.76757312e03, 4.56694461e03,
+ 2.22263363e00, 1.62977318e01, -7.81539315e00, -1.24938012e01,
+ 6.74029088e-01, 3.22802671e00, 5.14978971e00, -9.58561209e-01,
+ -3.92199895e01, 4.47201278e-01, -1.17866744e00],
+ [-6.52076924e02, 4.56694461e03, -2.58307255e02, 2.76535767e-02,
+ 3.74590279e04, 3.74509252e01, 4.56694461e03, 1.18278398e04,
+ 5.82242837e00, 4.26867612e01, -2.03167952e01, -3.22894255e01,
+ 1.75705078e00, 8.37153730e00, 1.32246076e01, -2.49238529e00,
+ -1.01316422e02, 1.16165466e00, -3.09390862e00],
+ [-2.71362566e-01, 2.22263363e00, -5.21335218e01, 6.25788669e-03,
+ 2.18498571e01, 2.76928748e-02, 2.22263363e00, 5.82242837e00,
+ 4.36278066e01, 3.14836583e02, -2.04747938e01, -3.05535101e01,
+ -1.24881456e-01, 1.15775394e01, 4.06907410e01, -1.39317748e00,
+ -3.90902798e01, -9.71716488e-02, 1.06851340e-01],
+ [-1.98885126e00, 1.62977318e01, -3.77485107e02, 4.50699620e-02,
+ 1.60254460e02, 2.03023837e-01, 1.62977318e01, 4.26867612e01,
+ 3.14836583e02, 2.27255216e03, -1.47029712e02, -2.19649109e02,
+ -8.83963155e-01, 8.28571708e01, 2.91399776e02, -9.97382920e00,
+ -2.81069124e02, -6.94946614e-01, 7.38151960e-01],
+ [1.22085415e00, -7.81539315e00, -6.75338369e01, 8.64152333e-03,
+ -7.52977260e01, -8.84279903e-02, -7.81539315e00, -2.03167952e01,
+ -2.04747938e01, -1.47029712e02, 7.83372613e01, 1.64416651e02,
+ -4.30243758e00, -2.59579610e01, -6.25644064e01, 6.69974667e00,
+ 2.31011701e02, -2.68540084e00, 5.44531151e00],
+ [2.30220713e00, -1.24938012e01, -1.89457169e02, 2.27772377e-02,
+ -1.17989623e02, -1.29523344e-01, -1.24938012e01, -3.22894255e01,
+ -3.05535101e01, -2.19649109e02, 1.64416651e02, 3.75893031e02,
+ -7.42084715e00, -4.56437599e01, -1.11071032e02, 1.18761368e01,
+ 4.78724142e02, -5.06804139e00, 8.81448081e00],
+ [-9.71278532e-02, 6.74029088e-01, 5.67828623e00, -8.51026855e-04,
+ 6.58253160e00, 8.06424434e-03, 6.74029088e-01, 1.75705078e00,
+ -1.24881456e-01, -8.83963155e-01, -4.30243758e00, -7.42084715e00,
+ 9.62009425e-01, 1.53836355e00, 2.23939458e00, -8.01872920e-01,
+ -1.92191084e01, 3.77713908e-01, -8.32946970e-01],
+ [-5.11210123e-01, 3.22802671e00, 5.82402681e00, 1.65316383e-04,
+ 3.14949206e01, 3.83330661e-02, 3.22802671e00, 8.37153730e00,
+ 1.15775394e01, 8.28571708e01, -2.59579610e01, -4.56437599e01,
+ 1.53836355e00, 2.63851056e01, 7.34859767e01, -4.39975402e00,
+ -1.12015747e02, 5.11542219e-01, -2.64962727e00],
+ [-1.00399562e00, 5.14978971e00, 1.72734354e01, 1.38977551e-03,
+ 4.98527190e01, 5.81579023e-02, 5.14978971e00, 1.32246076e01,
+ 4.06907410e01, 2.91399776e02, -6.25644064e01, -1.11071032e02,
+ 2.23939458e00, 7.34859767e01, 2.36535458e02, -1.09636675e01,
+ -2.72152068e02, 6.65888059e-01, -6.29295273e00],
+ [1.43319679e-01, -9.58561209e-01, -4.29114840e00, 5.51629259e-04,
+ -9.33338661e00, -1.12874980e-02, -9.58561209e-01, -2.49238529e00,
+ -1.39317748e00, -9.97382920e00, 6.69974667e00, 1.18761368e01,
+ -8.01872920e-01, -4.39975402e00, -1.09636675e01, 1.16820748e00,
+ 3.00817252e01, -4.51359819e-01, 9.82625204e-01],
+ [6.03815471e00, -3.92199895e01, -7.84885258e01, 1.38447755e-02,
+ -3.80465752e02, -4.48118297e-01, -3.92199895e01, -1.01316422e02,
+ -3.90902798e01, -2.81069124e02, 2.31011701e02, 4.78724142e02,
+ -1.92191084e01, -1.12015747e02, -2.72152068e02, 3.00817252e01,
+ 1.13232557e03, -1.33695932e01, 2.22934659e01],
+ [-6.38719934e-02, 4.47201278e-01, 3.17594634e00, -5.17956723e-04,
+ 4.33872213e00, 5.15022284e-03, 4.47201278e-01, 1.16165466e00,
+ -9.71716488e-02, -6.94946614e-01, -2.68540084e00, -5.06804139e00,
+ 3.77713908e-01, 5.11542219e-01, 6.65888059e-01, -4.51359819e-01,
+ -1.33695932e01, 4.27994168e-01, -5.09020820e-01],
+ [1.65623929e-01, -1.17866744e00, 2.45242852e00, -1.29260347e-04,
+ -1.14768816e01, -1.41501894e-02, -1.17866744e00, -3.09390862e00,
+ 1.06851340e-01, 7.38151960e-01, 5.44531151e00, 8.81448081e00,
+ -8.32946970e-01, -2.64962727e00, -6.29295273e00, 9.82625204e-01,
+ 2.22934659e01, -5.09020820e-01, 4.09964606e00]]
+ )
+ J = np.array([
+ -2.53298102e-07, 1.76392040e-06, 1.74776130e-06, -4.19479903e-10,
+ 1.44167498e-05, 1.41703911e-08, 1.76392030e-06, 4.96030153e-06,
+ -2.35771675e-07, -1.68844985e-06, 4.29218258e-07, 6.65445159e-07,
+ -3.87045830e-08, -3.17236594e-07, -1.21120169e-06, 4.59717313e-08,
+ 1.67123246e-06, 1.46624675e-08, 4.22723383e-08
+ ])
+
+ def fun(x):
+ return np.dot(np.dot(x, H), x) / 2 + np.dot(x, J)
+
+ def jac(x):
+ return np.dot(x, H) + J
+
+ def hess(x):
+ return H
+
+ x0 = np.zeros(19)
+
+ res = optimize.minimize(
+ fun,
+ x0,
+ jac=jac,
+ hess=hess,
+ method="trust-exact",
+ options={"gtol": 1e-6, "subproblem_maxiter": 10},
+ )
+ assert res.success
+ assert abs(fun(res.x)) < 1e-5
+
+
+@pytest.mark.parametrize('method', ['Newton-CG', 'trust-constr'])
+@pytest.mark.parametrize('sparse_type', [coo_matrix, csc_matrix, csr_matrix,
+ coo_array, csr_array, csc_array])
+def test_sparse_hessian(method, sparse_type):
+ # gh-8792 reported an error for minimization with `newton_cg` when `hess`
+ # returns a sparse array. Check that results are the same whether `hess`
+ # returns a dense or sparse array for optimization methods that accept
+ # sparse Hessian matrices.
+
+ def sparse_rosen_hess(x):
+ return sparse_type(rosen_hess(x))
+
+ x0 = [2., 2.]
+
+ res_sparse = optimize.minimize(rosen, x0, method=method,
+ jac=rosen_der, hess=sparse_rosen_hess)
+ res_dense = optimize.minimize(rosen, x0, method=method,
+ jac=rosen_der, hess=rosen_hess)
+
+ assert_allclose(res_dense.fun, res_sparse.fun)
+ assert_allclose(res_dense.x, res_sparse.x)
+ assert res_dense.nfev == res_sparse.nfev
+ assert res_dense.njev == res_sparse.njev
+ assert res_dense.nhev == res_sparse.nhev
+
+
+@pytest.mark.parametrize('workers', [None, 2])
+@pytest.mark.parametrize(
+ 'method',
+ ['l-bfgs-b',
+ 'bfgs',
+ 'slsqp',
+ 'trust-constr',
+ 'Newton-CG',
+ 'CG',
+ 'tnc',
+ 'trust-ncg',
+ 'trust-krylov'])
+class TestWorkers:
+
+ def setup_method(self):
+ self.x0 = np.array([1.0, 2.0, 3.0])
+
+ def test_smoke(self, workers, method):
+ # checks parallelised optimization output is same as serial
+ workers = workers or map
+
+ kwds = {'jac': None, 'hess': None}
+ if method in ['Newton-CG', 'trust-ncg', 'trust-krylov']:
+ # methods that require a callable jac
+ kwds['jac'] = rosen_der
+ kwds['hess'] = '2-point'
+
+ with MapWrapper(workers) as mf:
+ res = optimize.minimize(
+ rosen, self.x0, options={"workers":mf}, method=method, **kwds
+ )
+ res_default = optimize.minimize(
+ rosen, self.x0, method=method, **kwds
+ )
+ assert_equal(res.x, res_default.x)
+ assert_equal(res.nfev, res_default.nfev)
+
+ def test_equal_bounds(self, workers, method):
+ workers = workers or map
+ if method not in ['l-bfgs-b', 'slsqp', 'trust-constr', 'tnc']:
+ pytest.skip(f"{method} cannot use bounds")
+
+ bounds = Bounds([0, 2.0, 0.], [10., 2.0, 10.])
+ with MapWrapper(workers) as mf:
+ res = optimize.minimize(
+ rosen, self.x0, bounds=bounds, options={"workers": mf}, method=method
+ )
+ assert res.success
+ assert_allclose(res.x[1], 2.0)
+
+
+# Tests for PEP 649/749 style annotations in callback and objective functions
+if sys.version_info < (3, 14):
+ from typing import Any
+ _DUMMY_TYPE = Any
+else:
+ import typing
+ if typing.TYPE_CHECKING:
+ _DUMMY_TYPE = typing.Any
+
+def rosen_annotated(x: _DUMMY_TYPE) -> float:
+ return rosen(x) + 1
+
+def rosen_der_annotated(x: _DUMMY_TYPE) -> _DUMMY_TYPE:
+ return rosen_der(x)
+
+def rosen_hess_annotated(x: _DUMMY_TYPE) -> _DUMMY_TYPE:
+ return rosen_hess(x)
+
+def callable_annotated(intermediate_result: _DUMMY_TYPE) -> None:
+ pass
+
+@pytest.mark.skipif(sys.version_info < (3, 14),
+ reason="Requires PEP 649/749 from Python 3.14+.")
+class TestAnnotations:
+
+ def setup_method(self):
+ self.x0 = np.array([1.0, 1.01])
+ self.brute_params = (2, 3, 7, 8, 9, 10, 44, -1, 2, 26, 1, -2, 0.5)
+
+ @pytest.mark.parametrize("method", [
+ 'Nelder-Mead',
+ 'Powell',
+ 'CG',
+ 'bfgs',
+ 'Newton-CG',
+ 'l-bfgs-b',
+ 'tnc',
+ 'COBYLA',
+ # 'COBYQA', # External module. Will trigger NameError, skip for now
+ 'slsqp',
+ 'trust-constr',
+ 'dogleg',
+ 'trust-ncg',
+ 'trust-exact',
+ 'trust-krylov'
+ ])
+ def test_callable_annotations(self, method):
+ kwds = {'jac': None, 'hess': None, 'callback': callable_annotated}
+ if method in ['CG', 'BFGS', 'Newton-CG', "L-BFGS-B", 'TNC', 'SLSQP', 'dogleg',
+ 'trust-ncg', 'trust-krylov', 'trust-exact', 'trust-constr']:
+ # methods that require a callable jac
+ kwds['jac'] = rosen_der_annotated
+ if method in ['Newton-CG', 'dogleg', 'trust-ncg', 'trust-exact',
+ 'trust-krylov', 'trust-constr']:
+ kwds['hess'] = rosen_hess_annotated
+ optimize.minimize(rosen_annotated, self.x0, method=method, **kwds)
+
+ def test_differential_evolution_annotations(self):
+ bounds = [(-5, 5), (-5, 5)]
+ res = optimize.differential_evolution(rosen_annotated, bounds, seed=1,
+ callback=callable_annotated)
+ assert res.success, f"Unexpected error: {res.message}"
+
+ def test_curve_fit_annotations(self):
+
+ def model_func(x: _DUMMY_TYPE, a: float, b, c) -> _DUMMY_TYPE:
+ return a * np.exp(-b * x) + c
+
+ def model_jac(x: _DUMMY_TYPE, a: float, b, c) -> _DUMMY_TYPE:
+ return np.array([
+ np.exp(-b * x),
+ -a * x * np.exp(-b * x),
+ np.ones_like(x)
+ ]).T
+
+ xdata = np.linspace(0, 4, 10)
+ ydata = model_func(xdata, 2.5, 1.3, 0.5)
+
+ _,_,_,_,res = optimize.curve_fit(model_func, xdata, ydata, jac=model_jac,
+ full_output=True)
+ assert (res in [1, 2, 3, 4]), f"Unexpected error: {res.message}"
+
+ def test_brute_annotations(self):
+ def f1(z: _DUMMY_TYPE, *params: float) -> float:
+ x, y = z
+ a, b, c, d, e, f, g, h, i, j, k, l, scale = params
+ return (a * x**2 + b * x * y + c * y**2 + d*x + e*y + f)
+
+ def annotated_fmin(callable: _DUMMY_TYPE, x0: _DUMMY_TYPE,
+ *args, **kwargs) -> _DUMMY_TYPE:
+ return optimize.fmin(callable, x0, *args, **kwargs)
+
+ rranges = (slice(-4, 4, 0.25), slice(-4, 4, 0.25))
+ optimize.brute(f1, rranges, args=self.brute_params, finish=annotated_fmin)
+
+ def test_basinhopping_annotations(self):
+ # NOTE: basinhopping callback does not match
+ # callback(intermediate_result: OptimizeResult)
+ # signature. Consider adding when updated.
+ def acceptable_test(f_new: float, x_new: _DUMMY_TYPE,
+ f_old: float,x_old: _DUMMY_TYPE) -> bool:
+ return True
+
+ res = optimize.basinhopping(rosen_annotated, self.x0, niter=2, seed=1,
+ accept_test=acceptable_test)
+
+ assert res.success, f"Unexpected error: {res.message}"
+
+
+def test_multiprocessing_too_many_open_files_23080():
+ # https://github.com/scipy/scipy/issues/23080
+ x0 = np.array([0.9, 0.9])
+ # check that ScalarHessWrapper doesn't keep pool object alive
+ with assert_deallocated(multiprocessing.Pool, 2) as pool_obj:
+ with pool_obj as p:
+ _minimize_bfgs(rosen, x0, workers=p.map)
+ del p
+ del pool_obj
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_quadratic_assignment.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_quadratic_assignment.py
new file mode 100644
index 0000000000000000000000000000000000000000..6b291838d0382fbfbc0e3d1f9ec60e83420228b4
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_quadratic_assignment.py
@@ -0,0 +1,452 @@
+import pytest
+import numpy as np
+from numpy.random import default_rng
+from scipy.optimize import quadratic_assignment, OptimizeWarning
+from scipy.optimize._qap import _calc_score as _score
+from numpy.testing import assert_equal, assert_
+
+
+################
+# Common Tests #
+################
+
+def chr12c():
+ A = [
+ [0, 90, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0],
+ [90, 0, 0, 23, 0, 0, 0, 0, 0, 0, 0, 0],
+ [10, 0, 0, 0, 43, 0, 0, 0, 0, 0, 0, 0],
+ [0, 23, 0, 0, 0, 88, 0, 0, 0, 0, 0, 0],
+ [0, 0, 43, 0, 0, 0, 26, 0, 0, 0, 0, 0],
+ [0, 0, 0, 88, 0, 0, 0, 16, 0, 0, 0, 0],
+ [0, 0, 0, 0, 26, 0, 0, 0, 1, 0, 0, 0],
+ [0, 0, 0, 0, 0, 16, 0, 0, 0, 96, 0, 0],
+ [0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 29, 0],
+ [0, 0, 0, 0, 0, 0, 0, 96, 0, 0, 0, 37],
+ [0, 0, 0, 0, 0, 0, 0, 0, 29, 0, 0, 0],
+ [0, 0, 0, 0, 0, 0, 0, 0, 0, 37, 0, 0],
+ ]
+ B = [
+ [0, 36, 54, 26, 59, 72, 9, 34, 79, 17, 46, 95],
+ [36, 0, 73, 35, 90, 58, 30, 78, 35, 44, 79, 36],
+ [54, 73, 0, 21, 10, 97, 58, 66, 69, 61, 54, 63],
+ [26, 35, 21, 0, 93, 12, 46, 40, 37, 48, 68, 85],
+ [59, 90, 10, 93, 0, 64, 5, 29, 76, 16, 5, 76],
+ [72, 58, 97, 12, 64, 0, 96, 55, 38, 54, 0, 34],
+ [9, 30, 58, 46, 5, 96, 0, 83, 35, 11, 56, 37],
+ [34, 78, 66, 40, 29, 55, 83, 0, 44, 12, 15, 80],
+ [79, 35, 69, 37, 76, 38, 35, 44, 0, 64, 39, 33],
+ [17, 44, 61, 48, 16, 54, 11, 12, 64, 0, 70, 86],
+ [46, 79, 54, 68, 5, 0, 56, 15, 39, 70, 0, 18],
+ [95, 36, 63, 85, 76, 34, 37, 80, 33, 86, 18, 0],
+ ]
+ A, B = np.array(A), np.array(B)
+ n = A.shape[0]
+
+ opt_perm = np.array([7, 5, 1, 3, 10, 4, 8, 6, 9, 11, 2, 12]) - [1] * n
+
+ return A, B, opt_perm
+
+
+@pytest.mark.filterwarnings("ignore:The NumPy global RNG was seeded by calling")
+class QAPCommonTests:
+ """
+ Base class for `quadratic_assignment` tests.
+ """
+ # Test global optima of problem from Umeyama IVB
+ # https://pcl.sitehost.iu.edu/rgoldsto/papers/weighted%20graph%20match2.pdf
+ # Graph matching maximum is in the paper
+ # QAP minimum determined by brute force
+ def test_accuracy_1(self):
+ # besides testing accuracy, check that A and B can be lists
+ rng = np.random.default_rng(4358764578823597324)
+
+ A = [[0, 3, 4, 2],
+ [0, 0, 1, 2],
+ [1, 0, 0, 1],
+ [0, 0, 1, 0]]
+
+ B = [[0, 4, 2, 4],
+ [0, 0, 1, 0],
+ [0, 2, 0, 2],
+ [0, 1, 2, 0]]
+
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, "maximize": False})
+
+ assert_equal(res.fun, 10)
+ assert_equal(res.col_ind, np.array([1, 2, 3, 0]))
+
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, "maximize": True})
+
+ if self.method == 'faq':
+ # Global optimum is 40, but FAQ gets 37
+ assert_equal(res.fun, 37)
+ assert_equal(res.col_ind, np.array([0, 2, 3, 1]))
+ else:
+ assert_equal(res.fun, 40)
+ assert_equal(res.col_ind, np.array([0, 3, 1, 2]))
+
+ quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, "maximize": True})
+
+ # Test global optima of problem from Umeyama IIIB
+ # https://pcl.sitehost.iu.edu/rgoldsto/papers/weighted%20graph%20match2.pdf
+ # Graph matching maximum is in the paper
+ # QAP minimum determined by brute force
+ def test_accuracy_2(self):
+ rng = np.random.default_rng(4358764578823597324)
+
+ A = np.array([[0, 5, 8, 6],
+ [5, 0, 5, 1],
+ [8, 5, 0, 2],
+ [6, 1, 2, 0]])
+
+ B = np.array([[0, 1, 8, 4],
+ [1, 0, 5, 2],
+ [8, 5, 0, 5],
+ [4, 2, 5, 0]])
+
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, "maximize": False})
+
+ if self.method == 'faq':
+ # Global optimum is 176, but FAQ gets 178
+ assert_equal(res.fun, 178)
+ assert_equal(res.col_ind, np.array([1, 0, 3, 2]))
+ else:
+ assert_equal(res.fun, 176)
+ assert_equal(res.col_ind, np.array([1, 2, 3, 0]))
+
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, "maximize": True})
+
+ assert_equal(res.fun, 286)
+ assert_equal(res.col_ind, np.array([2, 3, 0, 1]))
+
+ def test_accuracy_3(self):
+ rng = np.random.default_rng(4358764578823597324)
+ A, B, opt_perm = chr12c()
+
+ # basic minimization
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng})
+ assert_(11156 <= res.fun < 21000)
+ assert_equal(res.fun, _score(A, B, res.col_ind))
+
+ # basic maximization
+ res = quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, 'maximize': True})
+ assert_(74000 <= res.fun < 85000)
+ assert_equal(res.fun, _score(A, B, res.col_ind))
+
+ # check ofv with strictly partial match
+ seed_cost = np.array([4, 8, 10])
+ seed = np.asarray([seed_cost, opt_perm[seed_cost]]).T
+ res = quadratic_assignment(A, B, method=self.method,
+ options={'partial_match': seed, "rng": rng})
+ assert_(11156 <= res.fun < 21000)
+ assert_equal(res.col_ind[seed_cost], opt_perm[seed_cost])
+
+ # check performance when partial match is the global optimum
+ seed = np.asarray([np.arange(len(A)), opt_perm]).T
+ res = quadratic_assignment(A, B, method=self.method,
+ options={'partial_match': seed, "rng": rng})
+ assert_equal(res.col_ind, seed[:, 1].T)
+ assert_equal(res.fun, 11156)
+ assert_equal(res.nit, 0)
+
+ # check performance with zero sized matrix inputs
+ empty = np.empty((0, 0))
+ res = quadratic_assignment(empty, empty, method=self.method,
+ options={"rng": rng})
+ assert_equal(res.nit, 0)
+ assert_equal(res.fun, 0)
+
+ def test_unknown_options(self):
+ A, B, opt_perm = chr12c()
+
+ with pytest.warns(OptimizeWarning):
+ quadratic_assignment(A, B, method=self.method,
+ options={"ekki-ekki": True})
+
+ def test_deprecation_future_warnings(self):
+ # May be removed after SPEC-7 transition is complete in SciPy 1.17
+ A = np.arange(16).reshape((4, 4))
+ B = np.arange(16).reshape((4, 4))
+
+ with pytest.warns(DeprecationWarning, match="Use of `RandomState`*"):
+ rng = np.random.RandomState(0)
+ quadratic_assignment(A, B, method=self.method,
+ options={"rng": rng, "maximize": False})
+
+ with pytest.warns(FutureWarning, match="The NumPy global RNG was seeded*"):
+ np.random.seed(0)
+ quadratic_assignment(A, B, method=self.method,
+ options={"maximize": False})
+
+ with pytest.warns(FutureWarning, match="The behavior when the rng option*"):
+ quadratic_assignment(A, B, method=self.method,
+ options={"rng": 0, "maximize": False})
+
+
+class TestFAQ(QAPCommonTests):
+ method = "faq"
+
+ def test_options(self):
+ # cost and distance matrices of QAPLIB instance chr12c
+ rng = np.random.default_rng(4358764578823597324)
+
+ A, B, opt_perm = chr12c()
+ n = len(A)
+
+ # check that max_iter is obeying with low input value
+ res = quadratic_assignment(A, B, options={'maxiter': 5})
+ assert_equal(res.nit, 5)
+
+ # test with shuffle
+ res = quadratic_assignment(A, B, options={'shuffle_input': True})
+ assert_(11156 <= res.fun < 21000)
+
+ # test with randomized init
+ res = quadratic_assignment(A, B, options={'rng': rng, 'P0': "randomized"})
+ assert_(11156 <= res.fun < 21000)
+
+ # check with specified P0
+ K = np.ones((n, n)) / float(n)
+ K = _doubly_stochastic(K)
+ res = quadratic_assignment(A, B, options={'P0': K})
+ assert_(11156 <= res.fun < 21000)
+
+ def test_specific_input_validation(self):
+
+ A = np.identity(2)
+ B = A
+
+ # method is implicitly faq
+
+ # ValueError Checks: making sure single value parameters are of
+ # correct value
+ with pytest.raises(ValueError, match="Invalid 'P0' parameter"):
+ quadratic_assignment(A, B, options={'P0': "random"})
+ with pytest.raises(
+ ValueError, match="'maxiter' must be a positive integer"):
+ quadratic_assignment(A, B, options={'maxiter': -1})
+ with pytest.raises(ValueError, match="'tol' must be a positive float"):
+ quadratic_assignment(A, B, options={'tol': -1})
+
+ # TypeError Checks: making sure single value parameters are of
+ # correct type
+ with pytest.raises(TypeError):
+ quadratic_assignment(A, B, options={'maxiter': 1.5})
+
+ # test P0 matrix input
+ with pytest.raises(
+ ValueError,
+ match="`P0` matrix must have shape m' x m', where m'=n-m"):
+ quadratic_assignment(
+ np.identity(4), np.identity(4),
+ options={'P0': np.ones((3, 3))}
+ )
+
+ K = [[0.4, 0.2, 0.3],
+ [0.3, 0.6, 0.2],
+ [0.2, 0.2, 0.7]]
+ # matrix that isn't quite doubly stochastic
+ with pytest.raises(
+ ValueError, match="`P0` matrix must be doubly stochastic"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3), options={'P0': K}
+ )
+
+
+class Test2opt(QAPCommonTests):
+ method = "2opt"
+
+ def test_deterministic(self):
+ n = 20
+ rng = default_rng(51982908)
+ A = rng.random(size=(n, n))
+ B = rng.random(size=(n, n))
+ res1 = quadratic_assignment(A, B, method=self.method, options={'rng': rng})
+
+ rng = default_rng(51982908)
+ A = rng.random(size=(n, n))
+ B = rng.random(size=(n, n))
+ res2 = quadratic_assignment(A, B, method=self.method, options={'rng': rng})
+
+ assert_equal(res1.nit, res2.nit)
+
+ def test_partial_guess(self):
+ n = 5
+ rng = np.random.default_rng(4358764578823597324)
+
+ A = rng.random(size=(n, n))
+ B = rng.random(size=(n, n))
+
+ res1 = quadratic_assignment(A, B, method=self.method,
+ options={'rng': rng})
+ guess = np.array([np.arange(5), res1.col_ind]).T
+ res2 = quadratic_assignment(A, B, method=self.method,
+ options={'rng': rng, 'partial_guess': guess})
+ fix = [2, 4]
+ match = np.array([np.arange(5)[fix], res1.col_ind[fix]]).T
+ res3 = quadratic_assignment(A, B, method=self.method,
+ options={'rng': rng, 'partial_guess': guess,
+ 'partial_match': match})
+ assert_(res1.nit != n*(n+1)/2)
+ assert_equal(res2.nit, n*(n+1)/2) # tests each swap exactly once
+ assert_equal(res3.nit, (n-2)*(n-1)/2) # tests free swaps exactly once
+
+ def test_specific_input_validation(self):
+ # can't have more seed nodes than cost/dist nodes
+ _rm = _range_matrix
+ with pytest.raises(
+ ValueError,
+ match="`partial_guess` can have only as many entries as"):
+ quadratic_assignment(np.identity(3), np.identity(3),
+ method=self.method,
+ options={'partial_guess': _rm(5, 2)})
+ # test for only two seed columns
+ with pytest.raises(
+ ValueError, match="`partial_guess` must have two columns"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3), method=self.method,
+ options={'partial_guess': _range_matrix(2, 3)}
+ )
+ # test that seed has no more than two dimensions
+ with pytest.raises(
+ ValueError, match="`partial_guess` must have exactly two"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3), method=self.method,
+ options={'partial_guess': np.random.rand(3, 2, 2)}
+ )
+ # seeds cannot be negative valued
+ with pytest.raises(
+ ValueError, match="`partial_guess` must contain only pos"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3), method=self.method,
+ options={'partial_guess': -1 * _range_matrix(2, 2)}
+ )
+ # seeds can't have values greater than number of nodes
+ with pytest.raises(
+ ValueError,
+ match="`partial_guess` entries must be less than number"):
+ quadratic_assignment(
+ np.identity(5), np.identity(5), method=self.method,
+ options={'partial_guess': 2 * _range_matrix(4, 2)}
+ )
+ # columns of seed matrix must be unique
+ with pytest.raises(
+ ValueError,
+ match="`partial_guess` column entries must be unique"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3), method=self.method,
+ options={'partial_guess': np.ones((2, 2))}
+ )
+
+
+@pytest.mark.filterwarnings("ignore:The NumPy global RNG was seeded by calling")
+class TestQAPOnce:
+
+ # these don't need to be repeated for each method
+ def test_common_input_validation(self):
+ rng = default_rng(12349038)
+ # test that non square matrices return error
+ with pytest.raises(ValueError, match="`A` must be square"):
+ quadratic_assignment(
+ rng.random((3, 4)),
+ rng.random((3, 3)),
+ )
+ with pytest.raises(ValueError, match="`B` must be square"):
+ quadratic_assignment(
+ rng.random((3, 3)),
+ rng.random((3, 4)),
+ )
+ # test that cost and dist matrices have no more than two dimensions
+ with pytest.raises(
+ ValueError, match="`A` and `B` must have exactly two"):
+ quadratic_assignment(
+ rng.random((3, 3, 3)),
+ rng.random((3, 3, 3)),
+ )
+ # test that cost and dist matrices of different sizes return error
+ with pytest.raises(
+ ValueError,
+ match="`A` and `B` matrices must be of equal size"):
+ quadratic_assignment(
+ rng.random((3, 3)),
+ rng.random((4, 4)),
+ )
+ # can't have more seed nodes than cost/dist nodes
+ _rm = _range_matrix
+ with pytest.raises(
+ ValueError,
+ match="`partial_match` can have only as many seeds as"):
+ quadratic_assignment(np.identity(3), np.identity(3),
+ options={'partial_match': _rm(5, 2)})
+ # test for only two seed columns
+ with pytest.raises(
+ ValueError, match="`partial_match` must have two columns"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3),
+ options={'partial_match': _range_matrix(2, 3)}
+ )
+ # test that seed has no more than two dimensions
+ with pytest.raises(
+ ValueError, match="`partial_match` must have exactly two"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3),
+ options={'partial_match': np.random.rand(3, 2, 2)}
+ )
+ # seeds cannot be negative valued
+ with pytest.raises(
+ ValueError, match="`partial_match` must contain only pos"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3),
+ options={'partial_match': -1 * _range_matrix(2, 2)}
+ )
+ # seeds can't have values greater than number of nodes
+ with pytest.raises(
+ ValueError,
+ match="`partial_match` entries must be less than number"):
+ quadratic_assignment(
+ np.identity(5), np.identity(5),
+ options={'partial_match': 2 * _range_matrix(4, 2)}
+ )
+ # columns of seed matrix must be unique
+ with pytest.raises(
+ ValueError,
+ match="`partial_match` column entries must be unique"):
+ quadratic_assignment(
+ np.identity(3), np.identity(3),
+ options={'partial_match': np.ones((2, 2))}
+ )
+
+
+def _range_matrix(a, b):
+ mat = np.zeros((a, b))
+ for i in range(b):
+ mat[:, i] = np.arange(a)
+ return mat
+
+
+def _doubly_stochastic(P, tol=1e-3):
+ # cleaner implementation of btaba/sinkhorn_knopp
+
+ max_iter = 1000
+ c = 1 / P.sum(axis=0)
+ r = 1 / (P @ c)
+ P_eps = P
+
+ for it in range(max_iter):
+ if ((np.abs(P_eps.sum(axis=1) - 1) < tol).all() and
+ (np.abs(P_eps.sum(axis=0) - 1) < tol).all()):
+ # All column/row sums ~= 1 within threshold
+ break
+
+ c = 1 / (r @ P)
+ r = 1 / (P @ c)
+ P_eps = r[:, None] * P * c
+
+ return P_eps
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_regression.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_regression.py
new file mode 100644
index 0000000000000000000000000000000000000000..44916ba96293db19756b8222422e76945aa48ebb
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_regression.py
@@ -0,0 +1,40 @@
+"""Regression tests for optimize.
+
+"""
+import numpy as np
+from numpy.testing import assert_almost_equal
+from pytest import raises as assert_raises
+
+import scipy.optimize
+
+
+class TestRegression:
+
+ def test_newton_x0_is_0(self):
+ # Regression test for gh-1601
+ tgt = 1
+ res = scipy.optimize.newton(lambda x: x - 1, 0)
+ assert_almost_equal(res, tgt)
+
+ def test_newton_integers(self):
+ # Regression test for gh-1741
+ root = scipy.optimize.newton(lambda x: x**2 - 1, x0=2,
+ fprime=lambda x: 2*x)
+ assert_almost_equal(root, 1.0)
+
+ def test_lmdif_errmsg(self):
+ # This shouldn't cause a crash on Python 3
+ class SomeError(Exception):
+ pass
+ counter = [0]
+
+ def func(x):
+ counter[0] += 1
+ if counter[0] < 3:
+ return x**2 - np.array([9, 10, 11])
+ else:
+ raise SomeError()
+ assert_raises(SomeError,
+ scipy.optimize.leastsq,
+ func, [1, 2, 3])
+
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_slsqp.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_slsqp.py
new file mode 100644
index 0000000000000000000000000000000000000000..43cb377dab41b734f59a5f600794beefd6e9c00b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_slsqp.py
@@ -0,0 +1,679 @@
+"""
+Unit test for SLSQP optimization.
+"""
+from numpy.testing import (assert_, assert_array_almost_equal,
+ assert_allclose, assert_equal)
+from pytest import raises as assert_raises
+import pytest
+import numpy as np
+import scipy
+
+from scipy.optimize import (fmin_slsqp, minimize, Bounds, NonlinearConstraint,
+ OptimizeResult)
+
+
+class MyCallBack:
+ """pass a custom callback function
+
+ This makes sure it's being used.
+ """
+ def __init__(self):
+ self.been_called = False
+ self.ncalls = 0
+
+ def __call__(self, x):
+ assert not isinstance(x, OptimizeResult)
+ self.been_called = True
+ self.ncalls += 1
+
+ def callback2(self, intermediate_result):
+ assert isinstance(intermediate_result, OptimizeResult)
+ self.been_called = True
+ self.ncalls += 1
+
+ def callback3(self, intermediate_result):
+ assert isinstance(intermediate_result, OptimizeResult)
+ raise StopIteration
+
+
+class TestSLSQP:
+ """
+ Test SLSQP algorithm using Example 14.4 from Numerical Methods for
+ Engineers by Steven Chapra and Raymond Canale.
+ This example maximizes the function f(x) = 2*x*y + 2*x - x**2 - 2*y**2,
+ which has a maximum at x=2, y=1.
+ """
+ def setup_method(self):
+ self.opts = {'disp': False}
+
+ def fun(self, d, sign=1.0):
+ """
+ Arguments:
+ d - A list of two elements, where d[0] represents x and d[1] represents y
+ in the following equation.
+ sign - A multiplier for f. Since we want to optimize it, and the SciPy
+ optimizers can only minimize functions, we need to multiply it by
+ -1 to achieve the desired solution
+ Returns:
+ 2*x*y + 2*x - x**2 - 2*y**2
+
+ """
+ x = d[0]
+ y = d[1]
+ return sign*(2*x*y + 2*x - x**2 - 2*y**2)
+
+ def jac(self, d, sign=1.0):
+ """
+ This is the derivative of fun, returning a NumPy array
+ representing df/dx and df/dy.
+
+ """
+ x = d[0]
+ y = d[1]
+ dfdx = sign*(-2*x + 2*y + 2)
+ dfdy = sign*(2*x - 4*y)
+ return np.array([dfdx, dfdy], float)
+
+ def fun_and_jac(self, d, sign=1.0):
+ return self.fun(d, sign), self.jac(d, sign)
+
+ def f_eqcon(self, x, sign=1.0):
+ """ Equality constraint """
+ return np.array([x[0] - x[1]])
+
+ def fprime_eqcon(self, x, sign=1.0):
+ """ Equality constraint, derivative """
+ return np.array([[1, -1]])
+
+ def f_eqcon_scalar(self, x, sign=1.0):
+ """ Scalar equality constraint """
+ return self.f_eqcon(x, sign)[0]
+
+ def fprime_eqcon_scalar(self, x, sign=1.0):
+ """ Scalar equality constraint, derivative """
+ return self.fprime_eqcon(x, sign)[0].tolist()
+
+ def f_ieqcon(self, x, sign=1.0):
+ """ Inequality constraint """
+ return np.array([x[0] - x[1] - 1.0])
+
+ def fprime_ieqcon(self, x, sign=1.0):
+ """ Inequality constraint, derivative """
+ return np.array([[1, -1]])
+
+ def f_ieqcon2(self, x):
+ """ Vector inequality constraint """
+ return np.asarray(x)
+
+ def fprime_ieqcon2(self, x):
+ """ Vector inequality constraint, derivative """
+ return np.identity(x.shape[0])
+
+ # minimize
+ def test_minimize_unbounded_approximated(self):
+ # Minimize, method='SLSQP': unbounded, approximated jacobian.
+ jacs = [None, False, '2-point', '3-point']
+ for jac in jacs:
+ res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ jac=jac, method='SLSQP',
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2, 1])
+
+ def test_minimize_unbounded_given(self):
+ # Minimize, method='SLSQP': unbounded, given Jacobian.
+ res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ jac=self.jac, method='SLSQP', options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2, 1])
+
+ def test_minimize_bounded_approximated(self):
+ # Minimize, method='SLSQP': bounded, approximated jacobian.
+ jacs = [None, False, '2-point', '3-point']
+ for jac in jacs:
+ with np.errstate(invalid='ignore'):
+ res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ jac=jac,
+ bounds=((2.5, None), (None, 0.5)),
+ method='SLSQP', options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2.5, 0.5])
+ assert_(2.5 <= res.x[0])
+ assert_(res.x[1] <= 0.5)
+
+ def test_minimize_unbounded_combined(self):
+ # Minimize, method='SLSQP': unbounded, combined function and Jacobian.
+ res = minimize(self.fun_and_jac, [-1.0, 1.0], args=(-1.0, ),
+ jac=True, method='SLSQP', options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2, 1])
+
+ def test_minimize_equality_approximated(self):
+ # Minimize with method='SLSQP': equality constraint, approx. jacobian.
+ jacs = [None, False, '2-point', '3-point']
+ for jac in jacs:
+ res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ jac=jac,
+ constraints={'type': 'eq',
+ 'fun': self.f_eqcon,
+ 'args': (-1.0, )},
+ method='SLSQP', options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [1, 1])
+
+ def test_minimize_equality_given(self):
+ # Minimize with method='SLSQP': equality constraint, given Jacobian.
+ res = minimize(self.fun, [-1.0, 1.0], jac=self.jac,
+ method='SLSQP', args=(-1.0,),
+ constraints={'type': 'eq', 'fun':self.f_eqcon,
+ 'args': (-1.0, )},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [1, 1])
+
+ def test_minimize_equality_given2(self):
+ # Minimize with method='SLSQP': equality constraint, given Jacobian
+ # for fun and const.
+ res = minimize(self.fun, [-1.0, 1.0], method='SLSQP',
+ jac=self.jac, args=(-1.0,),
+ constraints={'type': 'eq',
+ 'fun': self.f_eqcon,
+ 'args': (-1.0, ),
+ 'jac': self.fprime_eqcon},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [1, 1])
+
+ def test_minimize_equality_given_cons_scalar(self):
+ # Minimize with method='SLSQP': scalar equality constraint, given
+ # Jacobian for fun and const.
+ res = minimize(self.fun, [-1.0, 1.0], method='SLSQP',
+ jac=self.jac, args=(-1.0,),
+ constraints={'type': 'eq',
+ 'fun': self.f_eqcon_scalar,
+ 'args': (-1.0, ),
+ 'jac': self.fprime_eqcon_scalar},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [1, 1])
+
+ def test_minimize_inequality_given(self):
+ # Minimize with method='SLSQP': inequality constraint, given Jacobian.
+ res = minimize(self.fun, [-1.0, 1.0], method='SLSQP',
+ jac=self.jac, args=(-1.0, ),
+ constraints={'type': 'ineq',
+ 'fun': self.f_ieqcon,
+ 'args': (-1.0, )},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2, 1], atol=1e-3)
+
+ def test_minimize_inequality_given_vector_constraints(self):
+ # Minimize with method='SLSQP': vector inequality constraint, given
+ # Jacobian.
+ res = minimize(self.fun, [-1.0, 1.0], jac=self.jac,
+ method='SLSQP', args=(-1.0,),
+ constraints={'type': 'ineq',
+ 'fun': self.f_ieqcon2,
+ 'jac': self.fprime_ieqcon2},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [2, 1])
+
+ def test_minimize_bounded_constraint(self):
+ # when the constraint makes the solver go up against a parameter
+ # bound make sure that the numerical differentiation of the
+ # jacobian doesn't try to exceed that bound using a finite difference.
+ # gh11403
+ def c(x):
+ assert 0 <= x[0] <= 1 and 0 <= x[1] <= 1, x
+ return x[0] ** 0.5 + x[1]
+
+ def f(x):
+ assert 0 <= x[0] <= 1 and 0 <= x[1] <= 1, x
+ return -x[0] ** 2 + x[1] ** 2
+
+ cns = [NonlinearConstraint(c, 0, 1.5)]
+ x0 = np.asarray([0.9, 0.5])
+ bnd = Bounds([0., 0.], [1.0, 1.0])
+ minimize(f, x0, method='SLSQP', bounds=bnd, constraints=cns)
+
+ def test_minimize_bound_equality_given2(self):
+ # Minimize with method='SLSQP': bounds, eq. const., given jac. for
+ # fun. and const.
+ res = minimize(self.fun, [-1.0, 1.0], method='SLSQP',
+ jac=self.jac, args=(-1.0, ),
+ bounds=[(-0.8, 1.), (-1, 0.8)],
+ constraints={'type': 'eq',
+ 'fun': self.f_eqcon,
+ 'args': (-1.0, ),
+ 'jac': self.fprime_eqcon},
+ options=self.opts)
+ assert_(res['success'], res['message'])
+ assert_allclose(res.x, [0.8, 0.8], atol=1e-3)
+ assert_(-0.8 <= res.x[0] <= 1)
+ assert_(-1 <= res.x[1] <= 0.8)
+
+ # fmin_slsqp
+ def test_unbounded_approximated(self):
+ # SLSQP: unbounded, approximated Jacobian.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ iprint = 0, full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [2, 1])
+
+ def test_unbounded_given(self):
+ # SLSQP: unbounded, given Jacobian.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ fprime = self.jac, iprint = 0,
+ full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [2, 1])
+
+ def test_equality_approximated(self):
+ # SLSQP: equality constraint, approximated Jacobian.
+ res = fmin_slsqp(self.fun,[-1.0,1.0], args=(-1.0,),
+ eqcons = [self.f_eqcon],
+ iprint = 0, full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [1, 1])
+
+ def test_equality_given(self):
+ # SLSQP: equality constraint, given Jacobian.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0],
+ fprime=self.jac, args=(-1.0,),
+ eqcons = [self.f_eqcon], iprint = 0,
+ full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [1, 1])
+
+ def test_equality_given2(self):
+ # SLSQP: equality constraint, given Jacobian for fun and const.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0],
+ fprime=self.jac, args=(-1.0,),
+ f_eqcons = self.f_eqcon,
+ fprime_eqcons = self.fprime_eqcon,
+ iprint = 0,
+ full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [1, 1])
+
+ def test_inequality_given(self):
+ # SLSQP: inequality constraint, given Jacobian.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0],
+ fprime=self.jac, args=(-1.0, ),
+ ieqcons = [self.f_ieqcon],
+ iprint = 0, full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [2, 1], decimal=3)
+
+ def test_bound_equality_given2(self):
+ # SLSQP: bounds, eq. const., given jac. for fun. and const.
+ res = fmin_slsqp(self.fun, [-1.0, 1.0],
+ fprime=self.jac, args=(-1.0, ),
+ bounds = [(-0.8, 1.), (-1, 0.8)],
+ f_eqcons = self.f_eqcon,
+ fprime_eqcons = self.fprime_eqcon,
+ iprint = 0, full_output = 1)
+ x, fx, its, imode, smode = res
+ assert_(imode == 0, imode)
+ assert_array_almost_equal(x, [0.8, 0.8], decimal=3)
+ assert_(-0.8 <= x[0] <= 1)
+ assert_(-1 <= x[1] <= 0.8)
+
+ def test_scalar_constraints(self):
+ # Regression test for gh-2182
+ x = fmin_slsqp(lambda z: z**2, [3.],
+ ieqcons=[lambda z: z[0] - 1],
+ iprint=0)
+ assert_array_almost_equal(x, [1.])
+
+ x = fmin_slsqp(lambda z: z**2, [3.],
+ f_ieqcons=lambda z: [z[0] - 1],
+ iprint=0)
+ assert_array_almost_equal(x, [1.])
+
+ def test_integer_bounds(self):
+ # This should not raise an exception
+ fmin_slsqp(lambda z: z**2 - 1, [0], bounds=[[0, 1]], iprint=0)
+
+ def test_array_bounds(self):
+ # NumPy used to treat n-dimensional 1-element arrays as scalars
+ # in some cases. The handling of `bounds` by `fmin_slsqp` still
+ # supports this behavior.
+ bounds = [(-np.inf, np.inf), (np.array([2]), np.array([3]))]
+ x = fmin_slsqp(lambda z: np.sum(z**2 - 1), [2.5, 2.5], bounds=bounds,
+ iprint=0)
+ assert_array_almost_equal(x, [0, 2])
+
+ def test_obj_must_return_scalar(self):
+ # Regression test for Github Issue #5433
+ # If objective function does not return a scalar, raises ValueError
+ with assert_raises(ValueError):
+ fmin_slsqp(lambda x: [0, 1], [1, 2, 3])
+
+ def test_obj_returns_scalar_in_list(self):
+ # Test for Github Issue #5433 and PR #6691
+ # Objective function should be able to return length-1 Python list
+ # containing the scalar
+ fmin_slsqp(lambda x: [0], [1, 2, 3], iprint=0)
+
+ def test_callback(self):
+ # Minimize, method='SLSQP': unbounded, approximated jacobian. Check for callback
+ callback = MyCallBack()
+ res = minimize(self.fun, [-1.0, 1.0], args=(-1.0, ),
+ method='SLSQP', callback=callback, options=self.opts)
+ assert res.success
+ assert res.message
+ assert callback.been_called
+ assert_equal(callback.ncalls, res['nit'])
+
+ res = minimize(
+ self.fun,
+ [-1.0, 1.0],
+ args=(-1.0, ),
+ method='SLSQP',
+ callback=callback.callback2,
+ options=self.opts
+ )
+ assert res.success
+ assert callback.been_called
+
+ res = minimize(
+ self.fun,
+ [-1.0, 1.0],
+ args=(-1.0, ),
+ method='SLSQP',
+ callback=callback.callback3,
+ options=self.opts
+ )
+ assert not res.success
+ assert res.message.startswith("`callback` raised `StopIteration`")
+
+ def test_inconsistent_linearization(self):
+ # SLSQP must be able to solve this problem, even if the
+ # linearized problem at the starting point is infeasible.
+
+ # Linearized constraints are
+ #
+ # 2*x0[0]*x[0] >= 1
+ #
+ # At x0 = [0, 1], the second constraint is clearly infeasible.
+ # This triggers a call with n2==1 in the LSQ subroutine.
+ x = [0, 1]
+ def f1(x):
+ return x[0] + x[1] - 2
+ def f2(x):
+ return x[0] ** 2 - 1
+ sol = minimize(
+ lambda x: x[0]**2 + x[1]**2,
+ x,
+ constraints=({'type':'eq','fun': f1},
+ {'type':'ineq','fun': f2}),
+ bounds=((0,None), (0,None)),
+ method='SLSQP')
+ x = sol.x
+
+ assert_allclose(f1(x), 0, atol=1e-8)
+ assert_(f2(x) >= -1e-8)
+ assert_(sol.success, sol)
+
+ def test_regression_5743(self):
+ # SLSQP must not indicate success for this problem,
+ # which is infeasible.
+ x = [1, 2]
+ sol = minimize(
+ lambda x: x[0]**2 + x[1]**2,
+ x,
+ constraints=({'type':'eq','fun': lambda x: x[0]+x[1]-1},
+ {'type':'ineq','fun': lambda x: x[0]-2}),
+ bounds=((0,None), (0,None)),
+ method='SLSQP')
+ assert_(not sol.success, sol)
+
+ def test_gh_6676(self):
+ def func(x):
+ return (x[0] - 1)**2 + 2*(x[1] - 1)**2 + 0.5*(x[2] - 1)**2
+
+ sol = minimize(func, [0, 0, 0], method='SLSQP')
+ assert_(sol.jac.shape == (3,))
+
+ def test_invalid_bounds(self):
+ # Raise correct error when lower bound is greater than upper bound.
+ # See Github issue 6875.
+ bounds_list = [
+ ((1, 2), (2, 1)),
+ ((2, 1), (1, 2)),
+ ((2, 1), (2, 1)),
+ ((np.inf, 0), (np.inf, 0)),
+ ((1, -np.inf), (0, 1)),
+ ]
+ for bounds in bounds_list:
+ with assert_raises(ValueError):
+ minimize(self.fun, [-1.0, 1.0], bounds=bounds, method='SLSQP')
+
+ def test_bounds_clipping(self):
+ #
+ # SLSQP returns bogus results for initial guess out of bounds, gh-6859
+ #
+ def f(x):
+ return (x[0] - 1)**2
+
+ sol = minimize(f, [10], method='slsqp', bounds=[(None, 0)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [-10], method='slsqp', bounds=[(2, None)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 2, atol=1e-10)
+
+ sol = minimize(f, [-10], method='slsqp', bounds=[(None, 0)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [10], method='slsqp', bounds=[(2, None)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 2, atol=1e-10)
+
+ sol = minimize(f, [-0.5], method='slsqp', bounds=[(-1, 0)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [10], method='slsqp', bounds=[(-1, 0)])
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ def test_infeasible_initial(self):
+ # Check SLSQP behavior with infeasible initial point
+ def f(x):
+ x, = x
+ return x*x - 2*x + 1
+
+ cons_u = [{'type': 'ineq', 'fun': lambda x: 0 - x}]
+ cons_l = [{'type': 'ineq', 'fun': lambda x: x - 2}]
+ cons_ul = [{'type': 'ineq', 'fun': lambda x: 0 - x},
+ {'type': 'ineq', 'fun': lambda x: x + 1}]
+
+ sol = minimize(f, [10], method='slsqp', constraints=cons_u)
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [-10], method='slsqp', constraints=cons_l)
+ assert_(sol.success)
+ assert_allclose(sol.x, 2, atol=1e-10)
+
+ sol = minimize(f, [-10], method='slsqp', constraints=cons_u)
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [10], method='slsqp', constraints=cons_l)
+ assert_(sol.success)
+ assert_allclose(sol.x, 2, atol=1e-10)
+
+ sol = minimize(f, [-0.5], method='slsqp', constraints=cons_ul)
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ sol = minimize(f, [10], method='slsqp', constraints=cons_ul)
+ assert_(sol.success)
+ assert_allclose(sol.x, 0, atol=1e-10)
+
+ @pytest.mark.xfail(scipy.show_config(mode='dicts')['Compilers']['fortran']['name']
+ == "intel-llvm",
+ reason="Runtime warning due to floating point issues, not logic")
+ def test_inconsistent_inequalities(self):
+ # gh-7618
+
+ def cost(x):
+ return -1 * x[0] + 4 * x[1]
+
+ def ineqcons1(x):
+ return x[1] - x[0] - 1
+
+ def ineqcons2(x):
+ return x[0] - x[1]
+
+ # The inequalities are inconsistent, so no solution can exist:
+ #
+ # x1 >= x0 + 1
+ # x0 >= x1
+
+ x0 = (1,5)
+ bounds = ((-5, 5), (-5, 5))
+ cons = (dict(type='ineq', fun=ineqcons1), dict(type='ineq', fun=ineqcons2))
+ res = minimize(cost, x0, method='SLSQP', bounds=bounds, constraints=cons)
+
+ assert_(not res.success)
+
+ def test_new_bounds_type(self):
+ def f(x):
+ return x[0] ** 2 + x[1] ** 2
+ bounds = Bounds([1, 0], [np.inf, np.inf])
+ sol = minimize(f, [0, 0], method='slsqp', bounds=bounds)
+ assert_(sol.success)
+ assert_allclose(sol.x, [1, 0])
+
+ def test_nested_minimization(self):
+
+ class NestedProblem:
+
+ def __init__(self):
+ self.F_outer_count = 0
+
+ def F_outer(self, x):
+ self.F_outer_count += 1
+ if self.F_outer_count > 1000:
+ raise Exception("Nested minimization failed to terminate.")
+ inner_res = minimize(self.F_inner, (3, 4), method="SLSQP")
+ assert_(inner_res.success)
+ assert_allclose(inner_res.x, [1, 1])
+ return x[0]**2 + x[1]**2 + x[2]**2
+
+ def F_inner(self, x):
+ return (x[0] - 1)**2 + (x[1] - 1)**2
+
+ def solve(self):
+ outer_res = minimize(self.F_outer, (5, 5, 5), method="SLSQP")
+ assert_(outer_res.success)
+ assert_allclose(outer_res.x, [0, 0, 0])
+
+ problem = NestedProblem()
+ problem.solve()
+
+ def test_gh1758(self):
+ # the test suggested in gh1758
+ # https://nlopt.readthedocs.io/en/latest/NLopt_Tutorial/
+ # implement two equality constraints, in R^2.
+ def fun(x):
+ return np.sqrt(x[1])
+
+ def f_eqcon(x):
+ """ Equality constraint """
+ return x[1] - (2 * x[0]) ** 3
+
+ def f_eqcon2(x):
+ """ Equality constraint """
+ return x[1] - (-x[0] + 1) ** 3
+
+ c1 = {'type': 'eq', 'fun': f_eqcon}
+ c2 = {'type': 'eq', 'fun': f_eqcon2}
+
+ res = minimize(fun, [8, 0.25], method='SLSQP',
+ constraints=[c1, c2], bounds=[(-0.5, 1), (0, 8)])
+
+ np.testing.assert_allclose(res.fun, 0.5443310539518)
+ np.testing.assert_allclose(res.x, [0.33333333, 0.2962963])
+ assert res.success
+
+ def test_gh9640(self):
+ cons = ({'type': 'ineq', 'fun': lambda x: -x[0] - x[1] - 3},
+ {'type': 'ineq', 'fun': lambda x: x[1] + x[2] - 2})
+ bnds = ((-2, 2), (-2, 2), (-2, 2))
+
+ def target(x):
+ return 1
+ x0 = [-1.8869783504471584, -0.640096352696244, -0.8174212253407696]
+ res = minimize(target, x0, method='SLSQP', bounds=bnds, constraints=cons,
+ options={'disp':False, 'maxiter':10000})
+
+ # The problem is infeasible, so it cannot succeed
+ assert not res.success
+
+ def test_parameters_stay_within_bounds(self):
+ # gh11403. For some problems the SLSQP Fortran code suggests a step
+ # outside one of the lower/upper bounds. When this happens
+ # approx_derivative complains because it's being asked to evaluate
+ # a gradient outside its domain.
+
+ # gh21872, removal of random initial position, replacing with specific
+ # starting point, because success/fail depends on the seed used.
+ bounds = Bounds(np.array([0.1]), np.array([1.0]))
+ x0 = np.array(bounds.lb + (bounds.ub - bounds.lb) *
+ 0.417022004702574)
+
+ def f(x):
+ assert (x >= bounds.lb).all()
+ return np.linalg.norm(x)
+ # The following should not raise any warnings which was the case, with the
+ # old Fortran code.
+ res = minimize(f, x0, method='SLSQP', bounds=bounds)
+ assert res.success
+
+
+def test_slsqp_segfault_wrong_workspace_computation():
+ # See gh-14915
+ # This problem is not well-defined, however should not cause a segfault.
+ # The previous F77 workspace computation did not handle only equality-
+ # constrained problems correctly.
+ rng = np.random.default_rng(1742651087222879)
+ x = rng.uniform(size=[22,365])
+ target = np.linspace(0.9, 4.0, 50)
+
+ def metric(v, weights):
+ return [[0, 0],[1, 1]]
+
+ def efficient_metric(v, target):
+ def metric_a(weights):
+ return metric(v, weights)[1][0]
+
+ def metric_b(weights, v):
+ return metric(v, weights)[0][0]
+
+ constraints = ({'type': 'eq', 'fun': lambda x: metric_a(x) - target},
+ {'type': 'eq', 'fun': lambda x: np.sum(x) - 1})
+ weights = np.array([len(v)*[1./len(v)]])[0]
+ result = minimize(metric_b,
+ weights,
+ args=(v,),
+ method='SLSQP',
+ constraints=constraints)
+ return result
+
+ efficient_metric(x, target)
+
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_tnc.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..2cde9837bfd08e62916660a9750d833629b6b547
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_tnc.py
@@ -0,0 +1,345 @@
+"""
+Unit tests for TNC optimization routine from tnc.py
+"""
+import pytest
+from numpy.testing import assert_allclose, assert_equal
+
+import numpy as np
+from math import pow
+
+from scipy import optimize
+
+
+class TestTnc:
+ """TNC non-linear optimization.
+
+ These tests are taken from Prof. K. Schittkowski's test examples
+ for constrained non-linear programming.
+
+ http://www.uni-bayreuth.de/departments/math/~kschittkowski/home.htm
+
+ """
+ def setup_method(self):
+ # options for minimize
+ self.opts = {'disp': False, 'maxfun': 200}
+
+ # objective functions and Jacobian for each test
+ def f1(self, x, a=100.0):
+ return a * pow((x[1] - pow(x[0], 2)), 2) + pow(1.0 - x[0], 2)
+
+ def g1(self, x, a=100.0):
+ dif = [0, 0]
+ dif[1] = 2 * a * (x[1] - pow(x[0], 2))
+ dif[0] = -2.0 * (x[0] * (dif[1] - 1.0) + 1.0)
+ return dif
+
+ def fg1(self, x, a=100.0):
+ return self.f1(x, a), self.g1(x, a)
+
+ def f3(self, x):
+ return x[1] + pow(x[1] - x[0], 2) * 1.0e-5
+
+ def g3(self, x):
+ dif = [0, 0]
+ dif[0] = -2.0 * (x[1] - x[0]) * 1.0e-5
+ dif[1] = 1.0 - dif[0]
+ return dif
+
+ def fg3(self, x):
+ return self.f3(x), self.g3(x)
+
+ def f4(self, x):
+ return pow(x[0] + 1.0, 3) / 3.0 + x[1]
+
+ def g4(self, x):
+ dif = [0, 0]
+ dif[0] = pow(x[0] + 1.0, 2)
+ dif[1] = 1.0
+ return dif
+
+ def fg4(self, x):
+ return self.f4(x), self.g4(x)
+
+ def f5(self, x):
+ return np.sin(x[0] + x[1]) + pow(x[0] - x[1], 2) - \
+ 1.5 * x[0] + 2.5 * x[1] + 1.0
+
+ def g5(self, x):
+ dif = [0, 0]
+ v1 = np.cos(x[0] + x[1])
+ v2 = 2.0*(x[0] - x[1])
+
+ dif[0] = v1 + v2 - 1.5
+ dif[1] = v1 - v2 + 2.5
+ return dif
+
+ def fg5(self, x):
+ return self.f5(x), self.g5(x)
+
+ def f38(self, x):
+ return (100.0 * pow(x[1] - pow(x[0], 2), 2) +
+ pow(1.0 - x[0], 2) + 90.0 * pow(x[3] - pow(x[2], 2), 2) +
+ pow(1.0 - x[2], 2) + 10.1 * (pow(x[1] - 1.0, 2) +
+ pow(x[3] - 1.0, 2)) +
+ 19.8 * (x[1] - 1.0) * (x[3] - 1.0)) * 1.0e-5
+
+ def g38(self, x):
+ dif = [0, 0, 0, 0]
+ dif[0] = (-400.0 * x[0] * (x[1] - pow(x[0], 2)) -
+ 2.0 * (1.0 - x[0])) * 1.0e-5
+ dif[1] = (200.0 * (x[1] - pow(x[0], 2)) + 20.2 * (x[1] - 1.0) +
+ 19.8 * (x[3] - 1.0)) * 1.0e-5
+ dif[2] = (- 360.0 * x[2] * (x[3] - pow(x[2], 2)) -
+ 2.0 * (1.0 - x[2])) * 1.0e-5
+ dif[3] = (180.0 * (x[3] - pow(x[2], 2)) + 20.2 * (x[3] - 1.0) +
+ 19.8 * (x[1] - 1.0)) * 1.0e-5
+ return dif
+
+ def fg38(self, x):
+ return self.f38(x), self.g38(x)
+
+ def f45(self, x):
+ return 2.0 - x[0] * x[1] * x[2] * x[3] * x[4] / 120.0
+
+ def g45(self, x):
+ dif = [0] * 5
+ dif[0] = - x[1] * x[2] * x[3] * x[4] / 120.0
+ dif[1] = - x[0] * x[2] * x[3] * x[4] / 120.0
+ dif[2] = - x[0] * x[1] * x[3] * x[4] / 120.0
+ dif[3] = - x[0] * x[1] * x[2] * x[4] / 120.0
+ dif[4] = - x[0] * x[1] * x[2] * x[3] / 120.0
+ return dif
+
+ def fg45(self, x):
+ return self.f45(x), self.g45(x)
+
+ # tests
+ # minimize with method=TNC
+ def test_minimize_tnc1(self):
+ x0, bnds = [-2, 1], ([-np.inf, None], [-1.5, None])
+ xopt = [1, 1]
+ iterx = [] # to test callback
+
+ res = optimize.minimize(self.f1, x0, method='TNC', jac=self.g1,
+ bounds=bnds, options=self.opts,
+ callback=iterx.append)
+ assert_allclose(res.fun, self.f1(xopt), atol=1e-8)
+ assert_equal(len(iterx), res.nit)
+
+ def test_minimize_tnc1b(self):
+ x0, bnds = np.array([-2, 1]), ([-np.inf, None], [-1.5, None])
+ xopt = [1, 1]
+ x = optimize.minimize(self.f1, x0, method='TNC',
+ bounds=bnds, options=self.opts).x
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-4)
+
+ def test_minimize_tnc1c(self):
+ x0, bnds = [-2, 1], ([-np.inf, None],[-1.5, None])
+ xopt = [1, 1]
+ x = optimize.minimize(self.fg1, x0, method='TNC',
+ jac=True, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8)
+
+ def test_minimize_tnc2(self):
+ x0, bnds = [-2, 1], ([-np.inf, None], [1.5, None])
+ xopt = [-1.2210262419616387, 1.5]
+ x = optimize.minimize(self.f1, x0, method='TNC',
+ jac=self.g1, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8)
+
+ def test_minimize_tnc3(self):
+ x0, bnds = [10, 1], ([-np.inf, None], [0.0, None])
+ xopt = [0, 0]
+ x = optimize.minimize(self.f3, x0, method='TNC',
+ jac=self.g3, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f3(x), self.f3(xopt), atol=1e-8)
+
+ def test_minimize_tnc4(self):
+ x0,bnds = [1.125, 0.125], [(1, None), (0, None)]
+ xopt = [1, 0]
+ x = optimize.minimize(self.f4, x0, method='TNC',
+ jac=self.g4, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f4(x), self.f4(xopt), atol=1e-8)
+
+ def test_minimize_tnc5(self):
+ x0, bnds = [0, 0], [(-1.5, 4),(-3, 3)]
+ xopt = [-0.54719755119659763, -1.5471975511965976]
+ x = optimize.minimize(self.f5, x0, method='TNC',
+ jac=self.g5, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f5(x), self.f5(xopt), atol=1e-8)
+
+ def test_minimize_tnc38(self):
+ x0, bnds = np.array([-3, -1, -3, -1]), [(-10, 10)]*4
+ xopt = [1]*4
+ x = optimize.minimize(self.f38, x0, method='TNC',
+ jac=self.g38, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f38(x), self.f38(xopt), atol=1e-8)
+
+ def test_minimize_tnc45(self):
+ x0, bnds = [2] * 5, [(0, 1), (0, 2), (0, 3), (0, 4), (0, 5)]
+ xopt = [1, 2, 3, 4, 5]
+ x = optimize.minimize(self.f45, x0, method='TNC',
+ jac=self.g45, bounds=bnds,
+ options=self.opts).x
+ assert_allclose(self.f45(x), self.f45(xopt), atol=1e-8)
+
+ # fmin_tnc
+ def test_tnc1(self):
+ fg, x, bounds = self.fg1, [-2, 1], ([-np.inf, None], [-1.5, None])
+ xopt = [1, 1]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds, args=(100.0, ),
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc1b(self):
+ x, bounds = [-2, 1], ([-np.inf, None], [-1.5, None])
+ xopt = [1, 1]
+
+ x, nf, rc = optimize.fmin_tnc(self.f1, x, approx_grad=True,
+ bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-4,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc1c(self):
+ x, bounds = [-2, 1], ([-np.inf, None], [-1.5, None])
+ xopt = [1, 1]
+
+ x, nf, rc = optimize.fmin_tnc(self.f1, x, fprime=self.g1,
+ bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc2(self):
+ fg, x, bounds = self.fg1, [-2, 1], ([-np.inf, None], [1.5, None])
+ xopt = [-1.2210262419616387, 1.5]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f1(x), self.f1(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc3(self):
+ fg, x, bounds = self.fg3, [10, 1], ([-np.inf, None], [0.0, None])
+ xopt = [0, 0]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f3(x), self.f3(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc4(self):
+ fg, x, bounds = self.fg4, [1.125, 0.125], [(1, None), (0, None)]
+ xopt = [1, 0]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f4(x), self.f4(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc5(self):
+ fg, x, bounds = self.fg5, [0, 0], [(-1.5, 4),(-3, 3)]
+ xopt = [-0.54719755119659763, -1.5471975511965976]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f5(x), self.f5(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc38(self):
+ fg, x, bounds = self.fg38, np.array([-3, -1, -3, -1]), [(-10, 10)]*4
+ xopt = [1]*4
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f38(x), self.f38(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_tnc45(self):
+ fg, x, bounds = self.fg45, [2] * 5, [(0, 1), (0, 2), (0, 3),
+ (0, 4), (0, 5)]
+ xopt = [1, 2, 3, 4, 5]
+
+ x, nf, rc = optimize.fmin_tnc(fg, x, bounds=bounds,
+ messages=optimize._tnc.MSG_NONE,
+ maxfun=200)
+
+ assert_allclose(self.f45(x), self.f45(xopt), atol=1e-8,
+ err_msg="TNC failed with status: " +
+ optimize._tnc.RCSTRINGS[rc])
+
+ def test_raising_exceptions(self):
+ # tnc was ported to cython from hand-crafted cpython code
+ # check that Exception handling works.
+ def myfunc(x):
+ raise RuntimeError("myfunc")
+
+ def myfunc1(x):
+ return optimize.rosen(x)
+
+ def callback(x):
+ raise ValueError("callback")
+
+ with pytest.raises(RuntimeError):
+ optimize.minimize(myfunc, [0, 1], method="TNC")
+
+ with pytest.raises(ValueError):
+ optimize.minimize(
+ myfunc1, [0, 1], method="TNC", callback=callback
+ )
+
+ def test_callback_shouldnt_affect_minimization(self):
+ # gh14879. The output of a TNC minimization was different depending
+ # on whether a callback was used or not. The two should be equivalent.
+ # The issue was that TNC was unscaling/scaling x, and this process was
+ # altering x in the process. Now the callback uses an unscaled
+ # temporary copy of x.
+ def callback(x):
+ pass
+
+ fun = optimize.rosen
+ bounds = [(0, 10)] * 4
+ x0 = [1, 2, 3, 4.]
+ res = optimize.minimize(
+ fun, x0, bounds=bounds, method="TNC", options={"maxfun": 1000}
+ )
+ res2 = optimize.minimize(
+ fun, x0, bounds=bounds, method="TNC", options={"maxfun": 1000},
+ callback=callback
+ )
+ assert_allclose(res2.x, res.x)
+ assert_allclose(res2.fun, res.fun)
+ assert_equal(res2.nfev, res.nfev)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion.py
new file mode 100644
index 0000000000000000000000000000000000000000..e62d1045e73b7107fbd530e86dd2578de4d51c3f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion.py
@@ -0,0 +1,109 @@
+"""
+Unit tests for trust-region optimization routines.
+
+"""
+import pytest
+import numpy as np
+from numpy.testing import assert_, assert_equal, assert_allclose
+from scipy.optimize import (minimize, rosen, rosen_der, rosen_hess,
+ rosen_hess_prod)
+
+
+class Accumulator:
+ """ This is for testing callbacks."""
+ def __init__(self):
+ self.count = 0
+ self.accum = None
+
+ def __call__(self, x):
+ self.count += 1
+ if self.accum is None:
+ self.accum = np.array(x)
+ else:
+ self.accum += x
+
+
+class TestTrustRegionSolvers:
+
+ def setup_method(self):
+ self.x_opt = [1.0, 1.0]
+ self.easy_guess = [2.0, 2.0]
+ self.hard_guess = [-1.2, 1.0]
+
+ def test_dogleg_accuracy(self):
+ # test the accuracy and the return_all option
+ x0 = self.hard_guess
+ r = minimize(rosen, x0, jac=rosen_der, hess=rosen_hess, tol=1e-8,
+ method='dogleg', options={'return_all': True},)
+ assert_allclose(x0, r['allvecs'][0])
+ assert_allclose(r['x'], r['allvecs'][-1])
+ assert_allclose(r['x'], self.x_opt)
+
+ def test_dogleg_callback(self):
+ # test the callback mechanism and the maxiter and return_all options
+ accumulator = Accumulator()
+ maxiter = 5
+ r = minimize(rosen, self.hard_guess, jac=rosen_der, hess=rosen_hess,
+ callback=accumulator, method='dogleg',
+ options={'return_all': True, 'maxiter': maxiter},)
+ assert_equal(accumulator.count, maxiter)
+ assert_equal(len(r['allvecs']), maxiter+1)
+ assert_allclose(r['x'], r['allvecs'][-1])
+ assert_allclose(sum(r['allvecs'][1:]), accumulator.accum)
+
+ def test_dogleg_user_warning(self):
+ with pytest.warns(RuntimeWarning,
+ match=r'Maximum number of iterations'):
+ minimize(rosen, self.hard_guess, jac=rosen_der,
+ hess=rosen_hess, method='dogleg',
+ options={'disp': True, 'maxiter': 1}, )
+
+ def test_solver_concordance(self):
+ # Assert that dogleg uses fewer iterations than ncg on the Rosenbrock
+ # test function, although this does not necessarily mean
+ # that dogleg is faster or better than ncg even for this function
+ # and especially not for other test functions.
+ f = rosen
+ g = rosen_der
+ h = rosen_hess
+ for x0 in (self.easy_guess, self.hard_guess):
+ r_dogleg = minimize(f, x0, jac=g, hess=h, tol=1e-8,
+ method='dogleg', options={'return_all': True})
+ r_trust_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8,
+ method='trust-ncg',
+ options={'return_all': True})
+ r_trust_krylov = minimize(f, x0, jac=g, hess=h, tol=1e-8,
+ method='trust-krylov',
+ options={'return_all': True})
+ r_ncg = minimize(f, x0, jac=g, hess=h, tol=1e-8,
+ method='newton-cg', options={'return_all': True})
+ r_iterative = minimize(f, x0, jac=g, hess=h, tol=1e-8,
+ method='trust-exact',
+ options={'return_all': True})
+ assert_allclose(self.x_opt, r_dogleg['x'])
+ assert_allclose(self.x_opt, r_trust_ncg['x'])
+ assert_allclose(self.x_opt, r_trust_krylov['x'])
+ assert_allclose(self.x_opt, r_ncg['x'])
+ assert_allclose(self.x_opt, r_iterative['x'])
+ assert_(len(r_dogleg['allvecs']) < len(r_ncg['allvecs']))
+
+ def test_trust_ncg_hessp(self):
+ for x0 in (self.easy_guess, self.hard_guess, self.x_opt):
+ r = minimize(rosen, x0, jac=rosen_der, hessp=rosen_hess_prod,
+ tol=1e-8, method='trust-ncg')
+ assert_allclose(self.x_opt, r['x'])
+
+ def test_trust_ncg_start_in_optimum(self):
+ r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess,
+ tol=1e-8, method='trust-ncg')
+ assert_allclose(self.x_opt, r['x'])
+
+ def test_trust_krylov_start_in_optimum(self):
+ r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess,
+ tol=1e-8, method='trust-krylov')
+ assert_allclose(self.x_opt, r['x'])
+
+ def test_trust_exact_start_in_optimum(self):
+ r = minimize(rosen, x0=self.x_opt, jac=rosen_der, hess=rosen_hess,
+ tol=1e-8, method='trust-exact')
+ assert_allclose(self.x_opt, r['x'])
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_exact.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_exact.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc5a22cba2a6ebbcf8976b48ac1200ffbf07f8c9
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_exact.py
@@ -0,0 +1,479 @@
+"""
+Unit tests for trust-region iterative subproblem.
+
+"""
+import pytest
+import numpy as np
+from scipy.optimize._trustregion_exact import (
+ estimate_smallest_singular_value,
+ singular_leading_submatrix,
+ IterativeSubproblem)
+from scipy.linalg import (svd, get_lapack_funcs, det, qr, norm)
+from numpy.testing import (assert_array_equal,
+ assert_equal, assert_array_almost_equal)
+
+
+def random_entry(n, min_eig, max_eig, case, rng=None):
+ rng = np.random.default_rng(rng)
+
+ # Generate random matrix
+ rand = rng.uniform(low=-1, high=1, size=(n, n))
+
+ # QR decomposition
+ Q, _, _ = qr(rand, pivoting='True')
+
+ # Generate random eigenvalues
+ eigvalues = rng.uniform(low=min_eig, high=max_eig, size=n)
+ eigvalues = np.sort(eigvalues)[::-1]
+
+ # Generate matrix
+ Qaux = np.multiply(eigvalues, Q)
+ A = np.dot(Qaux, Q.T)
+
+ # Generate gradient vector accordingly
+ # to the case is being tested.
+ if case == 'hard':
+ g = np.zeros(n)
+ g[:-1] = rng.uniform(low=-1, high=1, size=n-1)
+ g = np.dot(Q, g)
+ elif case == 'jac_equal_zero':
+ g = np.zeros(n)
+ else:
+ g = rng.uniform(low=-1, high=1, size=n)
+
+ return A, g
+
+
+class TestEstimateSmallestSingularValue:
+
+ def test_for_ill_condiotioned_matrix(self):
+
+ # Ill-conditioned triangular matrix
+ C = np.array([[1, 2, 3, 4],
+ [0, 0.05, 60, 7],
+ [0, 0, 0.8, 9],
+ [0, 0, 0, 10]])
+
+ # Get svd decomposition
+ U, s, Vt = svd(C)
+
+ # Get smallest singular value and correspondent right singular vector.
+ smin_svd = s[-1]
+ zmin_svd = Vt[-1, :]
+
+ # Estimate smallest singular value
+ smin, zmin = estimate_smallest_singular_value(C)
+
+ # Check the estimation
+ assert_array_almost_equal(smin, smin_svd, decimal=8)
+ assert_array_almost_equal(abs(zmin), abs(zmin_svd), decimal=8)
+
+
+class TestSingularLeadingSubmatrix:
+
+ def test_for_already_singular_leading_submatrix(self):
+
+ # Define test matrix A.
+ # Note that the leading 2x2 submatrix is singular.
+ A = np.array([[1, 2, 3],
+ [2, 4, 5],
+ [3, 5, 6]])
+
+ # Get Cholesky from lapack functions
+ cholesky, = get_lapack_funcs(('potrf',), (A,))
+
+ # Compute Cholesky Decomposition
+ c, k = cholesky(A, lower=False, overwrite_a=False, clean=True)
+
+ delta, v = singular_leading_submatrix(A, c, k)
+
+ A[k-1, k-1] += delta
+
+ # Check if the leading submatrix is singular.
+ assert_array_almost_equal(det(A[:k, :k]), 0)
+
+ # Check if `v` fulfil the specified properties
+ quadratic_term = np.dot(v, np.dot(A, v))
+ assert_array_almost_equal(quadratic_term, 0)
+
+ def test_for_simetric_indefinite_matrix(self):
+
+ # Define test matrix A.
+ # Note that the leading 5x5 submatrix is indefinite.
+ A = np.asarray([[1, 2, 3, 7, 8],
+ [2, 5, 5, 9, 0],
+ [3, 5, 11, 1, 2],
+ [7, 9, 1, 7, 5],
+ [8, 0, 2, 5, 8]])
+
+ # Get Cholesky from lapack functions
+ cholesky, = get_lapack_funcs(('potrf',), (A,))
+
+ # Compute Cholesky Decomposition
+ c, k = cholesky(A, lower=False, overwrite_a=False, clean=True)
+
+ delta, v = singular_leading_submatrix(A, c, k)
+
+ A[k-1, k-1] += delta
+
+ # Check if the leading submatrix is singular.
+ assert_array_almost_equal(det(A[:k, :k]), 0)
+
+ # Check if `v` fulfil the specified properties
+ quadratic_term = np.dot(v, np.dot(A, v))
+ assert_array_almost_equal(quadratic_term, 0)
+
+ def test_for_first_element_equal_to_zero(self):
+
+ # Define test matrix A.
+ # Note that the leading 2x2 submatrix is singular.
+ A = np.array([[0, 3, 11],
+ [3, 12, 5],
+ [11, 5, 6]])
+
+ # Get Cholesky from lapack functions
+ cholesky, = get_lapack_funcs(('potrf',), (A,))
+
+ # Compute Cholesky Decomposition
+ c, k = cholesky(A, lower=False, overwrite_a=False, clean=True)
+
+ delta, v = singular_leading_submatrix(A, c, k)
+
+ A[k-1, k-1] += delta
+
+ # Check if the leading submatrix is singular
+ assert_array_almost_equal(det(A[:k, :k]), 0)
+
+ # Check if `v` fulfil the specified properties
+ quadratic_term = np.dot(v, np.dot(A, v))
+ assert_array_almost_equal(quadratic_term, 0)
+
+
+class TestIterativeSubproblem:
+
+ def test_for_the_easy_case(self):
+
+ # `H` is chosen such that `g` is not orthogonal to the
+ # eigenvector associated with the smallest eigenvalue `s`.
+ H = [[10, 2, 3, 4],
+ [2, 1, 7, 1],
+ [3, 7, 1, 7],
+ [4, 1, 7, 2]]
+ g = [1, 1, 1, 1]
+
+ # Trust Radius
+ trust_radius = 1
+
+ # Solve Subproblem
+ subprob = IterativeSubproblem(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: np.array(g),
+ hess=lambda x: np.array(H),
+ k_easy=1e-10,
+ k_hard=1e-10)
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(p, [0.00393332, -0.55260862,
+ 0.67065477, -0.49480341])
+ assert_array_almost_equal(hits_boundary, True)
+
+ def test_for_the_hard_case(self):
+
+ # `H` is chosen such that `g` is orthogonal to the
+ # eigenvector associated with the smallest eigenvalue `s`.
+ H = [[10, 2, 3, 4],
+ [2, 1, 7, 1],
+ [3, 7, 1, 7],
+ [4, 1, 7, 2]]
+ g = [6.4852641521327437, 1, 1, 1]
+ s = -8.2151519874416614
+
+ # Trust Radius
+ trust_radius = 1
+
+ # Solve Subproblem
+ subprob = IterativeSubproblem(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: np.array(g),
+ hess=lambda x: np.array(H),
+ k_easy=1e-10,
+ k_hard=1e-10)
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(-s, subprob.lambda_current)
+
+ def test_for_interior_convergence(self):
+
+ H = [[1.812159, 0.82687265, 0.21838879, -0.52487006, 0.25436988],
+ [0.82687265, 2.66380283, 0.31508988, -0.40144163, 0.08811588],
+ [0.21838879, 0.31508988, 2.38020726, -0.3166346, 0.27363867],
+ [-0.52487006, -0.40144163, -0.3166346, 1.61927182, -0.42140166],
+ [0.25436988, 0.08811588, 0.27363867, -0.42140166, 1.33243101]]
+
+ g = [0.75798952, 0.01421945, 0.33847612, 0.83725004, -0.47909534]
+
+ # Solve Subproblem
+ subprob = IterativeSubproblem(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: np.array(g),
+ hess=lambda x: np.array(H))
+ p, hits_boundary = subprob.solve(1.1)
+
+ assert_array_almost_equal(p, [-0.68585435, 0.1222621, -0.22090999,
+ -0.67005053, 0.31586769])
+ assert_array_almost_equal(hits_boundary, False)
+ assert_array_almost_equal(subprob.lambda_current, 0)
+ assert_array_almost_equal(subprob.niter, 1)
+
+ def test_for_jac_equal_zero(self):
+
+ H = [[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809],
+ [2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396],
+ [0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957],
+ [-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298],
+ [-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]]
+
+ g = [0, 0, 0, 0, 0]
+
+ # Solve Subproblem
+ subprob = IterativeSubproblem(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: np.array(g),
+ hess=lambda x: np.array(H),
+ k_easy=1e-10,
+ k_hard=1e-10)
+ p, hits_boundary = subprob.solve(1.1)
+
+ assert_array_almost_equal(p, [0.06910534, -0.01432721,
+ -0.65311947, -0.23815972,
+ -0.84954934])
+ assert_array_almost_equal(hits_boundary, True)
+
+ def test_for_jac_very_close_to_zero(self):
+
+ H = [[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809],
+ [2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396],
+ [0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957],
+ [-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298],
+ [-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]]
+
+ g = [0, 0, 0, 0, 1e-15]
+
+ # Solve Subproblem
+ subprob = IterativeSubproblem(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: np.array(g),
+ hess=lambda x: np.array(H),
+ k_easy=1e-10,
+ k_hard=1e-10)
+ p, hits_boundary = subprob.solve(1.1)
+
+ assert_array_almost_equal(p, [0.06910534, -0.01432721,
+ -0.65311947, -0.23815972,
+ -0.84954934])
+ assert_array_almost_equal(hits_boundary, True)
+
+ @pytest.mark.thread_unsafe(reason="fails in parallel")
+ @pytest.mark.fail_slow(10)
+ def test_for_random_entries(self):
+ rng = np.random.default_rng(1)
+
+ # Dimension
+ n = 5
+
+ for case in ('easy', 'hard', 'jac_equal_zero'):
+
+ eig_limits = [(-20, -15),
+ (-10, -5),
+ (-10, 0),
+ (-5, 5),
+ (-10, 10),
+ (0, 10),
+ (5, 10),
+ (15, 20)]
+
+ for min_eig, max_eig in eig_limits:
+ # Generate random symmetric matrix H with
+ # eigenvalues between min_eig and max_eig.
+ H, g = random_entry(n, min_eig, max_eig, case, rng=rng)
+
+ # Trust radius
+ trust_radius_list = [0.1, 0.3, 0.6, 0.8, 1, 1.2, 3.3, 5.5, 10]
+
+ for trust_radius in trust_radius_list:
+ # Solve subproblem with very high accuracy
+ subprob_ac = IterativeSubproblem(0,
+ lambda x: 0,
+ lambda x: g,
+ lambda x: H,
+ k_easy=1e-10,
+ k_hard=1e-10)
+
+ p_ac, hits_boundary_ac = subprob_ac.solve(trust_radius)
+
+ # Compute objective function value
+ J_ac = 1/2*np.dot(p_ac, np.dot(H, p_ac))+np.dot(g, p_ac)
+
+ stop_criteria = [(0.1, 2),
+ (0.5, 1.1),
+ (0.9, 1.01)]
+
+ for k_opt, k_trf in stop_criteria:
+
+ # k_easy and k_hard computed in function
+ # of k_opt and k_trf accordingly to
+ # Conn, A. R., Gould, N. I., & Toint, P. L. (2000).
+ # "Trust region methods". Siam. p. 197.
+ k_easy = min(k_trf-1,
+ 1-np.sqrt(k_opt))
+ k_hard = 1-k_opt
+
+ # Solve subproblem
+ subprob = IterativeSubproblem(0,
+ lambda x: 0,
+ lambda x: g,
+ lambda x: H,
+ k_easy=k_easy,
+ k_hard=k_hard)
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ # Compute objective function value
+ J = 1/2*np.dot(p, np.dot(H, p))+np.dot(g, p)
+
+ # Check if it respect k_trf
+ if hits_boundary:
+ assert_array_equal(np.abs(norm(p)-trust_radius) <=
+ (k_trf-1)*trust_radius, True)
+ else:
+ assert_equal(norm(p) <= trust_radius, True)
+
+ # Check if it respect k_opt
+ assert_equal(J <= k_opt*J_ac, True)
+
+
+ def test_for_finite_number_of_iterations(self):
+ """Regression test for gh-12513"""
+ H = np.array(
+ [[3.67335930e01, -2.52334820e02, 1.15477558e01, -1.19933725e-03,
+ -2.06408851e03, -2.05821411e00, -2.52334820e02, -6.52076924e02,
+ -2.71362566e-01, -1.98885126e00, 1.22085415e00, 2.30220713e00,
+ -9.71278532e-02, -5.11210123e-01, -1.00399562e00, 1.43319679e-01,
+ 6.03815471e00, -6.38719934e-02, 1.65623929e-01],
+ [-2.52334820e02, 1.76757312e03, -9.92814996e01, 1.06533600e-02,
+ 1.44442941e04, 1.43811694e01, 1.76757312e03, 4.56694461e03,
+ 2.22263363e00, 1.62977318e01, -7.81539315e00, -1.24938012e01,
+ 6.74029088e-01, 3.22802671e00, 5.14978971e00, -9.58561209e-01,
+ -3.92199895e01, 4.47201278e-01, -1.17866744e00],
+ [1.15477558e01, -9.92814996e01, 3.63872363e03, -4.40007197e-01,
+ -9.55435081e02, -1.13985105e00, -9.92814996e01, -2.58307255e02,
+ -5.21335218e01, -3.77485107e02, -6.75338369e01, -1.89457169e02,
+ 5.67828623e00, 5.82402681e00, 1.72734354e01, -4.29114840e00,
+ -7.84885258e01, 3.17594634e00, 2.45242852e00],
+ [-1.19933725e-03, 1.06533600e-02, -4.40007197e-01, 5.73576663e-05,
+ 1.01563710e-01, 1.18838745e-04, 1.06533600e-02, 2.76535767e-02,
+ 6.25788669e-03, 4.50699620e-02, 8.64152333e-03, 2.27772377e-02,
+ -8.51026855e-04, 1.65316383e-04, 1.38977551e-03, 5.51629259e-04,
+ 1.38447755e-02, -5.17956723e-04, -1.29260347e-04],
+ [-2.06408851e03, 1.44442941e04, -9.55435081e02, 1.01563710e-01,
+ 1.23101825e05, 1.26467259e02, 1.44442941e04, 3.74590279e04,
+ 2.18498571e01, 1.60254460e02, -7.52977260e01, -1.17989623e02,
+ 6.58253160e00, 3.14949206e01, 4.98527190e01, -9.33338661e00,
+ -3.80465752e02, 4.33872213e00, -1.14768816e01],
+ [-2.05821411e00, 1.43811694e01, -1.13985105e00, 1.18838745e-04,
+ 1.26467259e02, 1.46226198e-01, 1.43811694e01, 3.74509252e01,
+ 2.76928748e-02, 2.03023837e-01, -8.84279903e-02, -1.29523344e-01,
+ 8.06424434e-03, 3.83330661e-02, 5.81579023e-02, -1.12874980e-02,
+ -4.48118297e-01, 5.15022284e-03, -1.41501894e-02],
+ [-2.52334820e02, 1.76757312e03, -9.92814996e01, 1.06533600e-02,
+ 1.44442941e04, 1.43811694e01, 1.76757312e03, 4.56694461e03,
+ 2.22263363e00, 1.62977318e01, -7.81539315e00, -1.24938012e01,
+ 6.74029088e-01, 3.22802671e00, 5.14978971e00, -9.58561209e-01,
+ -3.92199895e01, 4.47201278e-01, -1.17866744e00],
+ [-6.52076924e02, 4.56694461e03, -2.58307255e02, 2.76535767e-02,
+ 3.74590279e04, 3.74509252e01, 4.56694461e03, 1.18278398e04,
+ 5.82242837e00, 4.26867612e01, -2.03167952e01, -3.22894255e01,
+ 1.75705078e00, 8.37153730e00, 1.32246076e01, -2.49238529e00,
+ -1.01316422e02, 1.16165466e00, -3.09390862e00],
+ [-2.71362566e-01, 2.22263363e00, -5.21335218e01, 6.25788669e-03,
+ 2.18498571e01, 2.76928748e-02, 2.22263363e00, 5.82242837e00,
+ 4.36278066e01, 3.14836583e02, -2.04747938e01, -3.05535101e01,
+ -1.24881456e-01, 1.15775394e01, 4.06907410e01, -1.39317748e00,
+ -3.90902798e01, -9.71716488e-02, 1.06851340e-01],
+ [-1.98885126e00, 1.62977318e01, -3.77485107e02, 4.50699620e-02,
+ 1.60254460e02, 2.03023837e-01, 1.62977318e01, 4.26867612e01,
+ 3.14836583e02, 2.27255216e03, -1.47029712e02, -2.19649109e02,
+ -8.83963155e-01, 8.28571708e01, 2.91399776e02, -9.97382920e00,
+ -2.81069124e02, -6.94946614e-01, 7.38151960e-01],
+ [1.22085415e00, -7.81539315e00, -6.75338369e01, 8.64152333e-03,
+ -7.52977260e01, -8.84279903e-02, -7.81539315e00, -2.03167952e01,
+ -2.04747938e01, -1.47029712e02, 7.83372613e01, 1.64416651e02,
+ -4.30243758e00, -2.59579610e01, -6.25644064e01, 6.69974667e00,
+ 2.31011701e02, -2.68540084e00, 5.44531151e00],
+ [2.30220713e00, -1.24938012e01, -1.89457169e02, 2.27772377e-02,
+ -1.17989623e02, -1.29523344e-01, -1.24938012e01, -3.22894255e01,
+ -3.05535101e01, -2.19649109e02, 1.64416651e02, 3.75893031e02,
+ -7.42084715e00, -4.56437599e01, -1.11071032e02, 1.18761368e01,
+ 4.78724142e02, -5.06804139e00, 8.81448081e00],
+ [-9.71278532e-02, 6.74029088e-01, 5.67828623e00, -8.51026855e-04,
+ 6.58253160e00, 8.06424434e-03, 6.74029088e-01, 1.75705078e00,
+ -1.24881456e-01, -8.83963155e-01, -4.30243758e00, -7.42084715e00,
+ 9.62009425e-01, 1.53836355e00, 2.23939458e00, -8.01872920e-01,
+ -1.92191084e01, 3.77713908e-01, -8.32946970e-01],
+ [-5.11210123e-01, 3.22802671e00, 5.82402681e00, 1.65316383e-04,
+ 3.14949206e01, 3.83330661e-02, 3.22802671e00, 8.37153730e00,
+ 1.15775394e01, 8.28571708e01, -2.59579610e01, -4.56437599e01,
+ 1.53836355e00, 2.63851056e01, 7.34859767e01, -4.39975402e00,
+ -1.12015747e02, 5.11542219e-01, -2.64962727e00],
+ [-1.00399562e00, 5.14978971e00, 1.72734354e01, 1.38977551e-03,
+ 4.98527190e01, 5.81579023e-02, 5.14978971e00, 1.32246076e01,
+ 4.06907410e01, 2.91399776e02, -6.25644064e01, -1.11071032e02,
+ 2.23939458e00, 7.34859767e01, 2.36535458e02, -1.09636675e01,
+ -2.72152068e02, 6.65888059e-01, -6.29295273e00],
+ [1.43319679e-01, -9.58561209e-01, -4.29114840e00, 5.51629259e-04,
+ -9.33338661e00, -1.12874980e-02, -9.58561209e-01, -2.49238529e00,
+ -1.39317748e00, -9.97382920e00, 6.69974667e00, 1.18761368e01,
+ -8.01872920e-01, -4.39975402e00, -1.09636675e01, 1.16820748e00,
+ 3.00817252e01, -4.51359819e-01, 9.82625204e-01],
+ [6.03815471e00, -3.92199895e01, -7.84885258e01, 1.38447755e-02,
+ -3.80465752e02, -4.48118297e-01, -3.92199895e01, -1.01316422e02,
+ -3.90902798e01, -2.81069124e02, 2.31011701e02, 4.78724142e02,
+ -1.92191084e01, -1.12015747e02, -2.72152068e02, 3.00817252e01,
+ 1.13232557e03, -1.33695932e01, 2.22934659e01],
+ [-6.38719934e-02, 4.47201278e-01, 3.17594634e00, -5.17956723e-04,
+ 4.33872213e00, 5.15022284e-03, 4.47201278e-01, 1.16165466e00,
+ -9.71716488e-02, -6.94946614e-01, -2.68540084e00, -5.06804139e00,
+ 3.77713908e-01, 5.11542219e-01, 6.65888059e-01, -4.51359819e-01,
+ -1.33695932e01, 4.27994168e-01, -5.09020820e-01],
+ [1.65623929e-01, -1.17866744e00, 2.45242852e00, -1.29260347e-04,
+ -1.14768816e01, -1.41501894e-02, -1.17866744e00, -3.09390862e00,
+ 1.06851340e-01, 7.38151960e-01, 5.44531151e00, 8.81448081e00,
+ -8.32946970e-01, -2.64962727e00, -6.29295273e00, 9.82625204e-01,
+ 2.22934659e01, -5.09020820e-01, 4.09964606e00]]
+ )
+ J = np.array([
+ -2.53298102e-07, 1.76392040e-06, 1.74776130e-06, -4.19479903e-10,
+ 1.44167498e-05, 1.41703911e-08, 1.76392030e-06, 4.96030153e-06,
+ -2.35771675e-07, -1.68844985e-06, 4.29218258e-07, 6.65445159e-07,
+ -3.87045830e-08, -3.17236594e-07, -1.21120169e-06, 4.59717313e-08,
+ 1.67123246e-06, 1.46624675e-08, 4.22723383e-08
+ ])
+
+ subproblem_maxiter = [None, 10]
+ for maxiter in subproblem_maxiter:
+ # Solve Subproblem
+ subprob = IterativeSubproblem(
+ x=0,
+ fun=lambda x: 0,
+ jac=lambda x: J,
+ hess=lambda x: H,
+ k_easy=0.1,
+ k_hard=0.2,
+ maxiter=maxiter,
+ )
+ trust_radius = 1
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ if maxiter is None:
+ assert subprob.niter <= IterativeSubproblem.MAXITER_DEFAULT
+ else:
+ assert subprob.niter <= maxiter
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_krylov.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_krylov.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2c18f931ab3e938ca7fc039dd9fa21783830aee
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_trustregion_krylov.py
@@ -0,0 +1,168 @@
+"""
+Unit tests for Krylov space trust-region subproblem solver.
+
+"""
+import numpy as np
+from scipy.optimize._trlib import (get_trlib_quadratic_subproblem)
+from numpy.testing import (assert_,
+ assert_almost_equal,
+ assert_equal, assert_array_almost_equal)
+
+KrylovQP = get_trlib_quadratic_subproblem(tol_rel_i=1e-8, tol_rel_b=1e-6)
+KrylovQP_disp = get_trlib_quadratic_subproblem(tol_rel_i=1e-8, tol_rel_b=1e-6,
+ disp=True)
+
+class TestKrylovQuadraticSubproblem:
+
+ def test_for_the_easy_case(self):
+
+ # `H` is chosen such that `g` is not orthogonal to the
+ # eigenvector associated with the smallest eigenvalue.
+ H = np.array([[1.0, 0.0, 4.0],
+ [0.0, 2.0, 0.0],
+ [4.0, 0.0, 3.0]])
+ g = np.array([5.0, 0.0, 4.0])
+
+ # Trust Radius
+ trust_radius = 1.0
+
+ # Solve Subproblem
+ subprob = KrylovQP(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: g,
+ hess=lambda x: None,
+ hessp=lambda x, y: H.dot(y))
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(p, np.array([-1.0, 0.0, 0.0]))
+ assert_equal(hits_boundary, True)
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+ # check trust region constraint
+ assert_almost_equal(np.linalg.norm(p), trust_radius)
+
+ trust_radius = 0.5
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(p,
+ np.array([-0.46125446, 0., -0.19298788]))
+ assert_equal(hits_boundary, True)
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+ # check trust region constraint
+ assert_almost_equal(np.linalg.norm(p), trust_radius)
+
+ def test_for_the_hard_case(self):
+
+ # `H` is chosen such that `g` is orthogonal to the
+ # eigenvector associated with the smallest eigenvalue.
+ H = np.array([[1.0, 0.0, 4.0],
+ [0.0, 2.0, 0.0],
+ [4.0, 0.0, 3.0]])
+ g = np.array([0.0, 2.0, 0.0])
+
+ # Trust Radius
+ trust_radius = 1.0
+
+ # Solve Subproblem
+ subprob = KrylovQP(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: g,
+ hess=lambda x: None,
+ hessp=lambda x, y: H.dot(y))
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(p, np.array([0.0, -1.0, 0.0]))
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+ # check trust region constraint
+ assert_almost_equal(np.linalg.norm(p), trust_radius)
+
+ trust_radius = 0.5
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ assert_array_almost_equal(p, np.array([0.0, -0.5, 0.0]))
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+ # check trust region constraint
+ assert_almost_equal(np.linalg.norm(p), trust_radius)
+
+ def test_for_interior_convergence(self):
+
+ H = np.array([[1.812159, 0.82687265, 0.21838879, -0.52487006, 0.25436988],
+ [0.82687265, 2.66380283, 0.31508988, -0.40144163, 0.08811588],
+ [0.21838879, 0.31508988, 2.38020726, -0.3166346, 0.27363867],
+ [-0.52487006, -0.40144163, -0.3166346, 1.61927182, -0.42140166],
+ [0.25436988, 0.08811588, 0.27363867, -0.42140166, 1.33243101]])
+ g = np.array([0.75798952, 0.01421945, 0.33847612, 0.83725004, -0.47909534])
+ trust_radius = 1.1
+
+ # Solve Subproblem
+ subprob = KrylovQP(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: g,
+ hess=lambda x: None,
+ hessp=lambda x, y: H.dot(y))
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+
+ assert_array_almost_equal(p, [-0.68585435, 0.1222621, -0.22090999,
+ -0.67005053, 0.31586769])
+ assert_array_almost_equal(hits_boundary, False)
+
+ def test_for_very_close_to_zero(self):
+
+ H = np.array([[0.88547534, 2.90692271, 0.98440885, -0.78911503, -0.28035809],
+ [2.90692271, -0.04618819, 0.32867263, -0.83737945, 0.17116396],
+ [0.98440885, 0.32867263, -0.87355957, -0.06521957, -1.43030957],
+ [-0.78911503, -0.83737945, -0.06521957, -1.645709, -0.33887298],
+ [-0.28035809, 0.17116396, -1.43030957, -0.33887298, -1.68586978]])
+ g = np.array([0, 0, 0, 0, 1e-6])
+ trust_radius = 1.1
+
+ # Solve Subproblem
+ subprob = KrylovQP(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: g,
+ hess=lambda x: None,
+ hessp=lambda x, y: H.dot(y))
+ p, hits_boundary = subprob.solve(trust_radius)
+
+ # check kkt satisfaction
+ assert_almost_equal(
+ np.linalg.norm(H.dot(p) + subprob.lam * p + g),
+ 0.0)
+ # check trust region constraint
+ assert_almost_equal(np.linalg.norm(p), trust_radius)
+
+ assert_array_almost_equal(p, [0.06910534, -0.01432721,
+ -0.65311947, -0.23815972,
+ -0.84954934])
+ assert_array_almost_equal(hits_boundary, True)
+
+ def test_disp(self, capsys):
+ H = -np.eye(5)
+ g = np.array([0, 0, 0, 0, 1e-6])
+ trust_radius = 1.1
+
+ subprob = KrylovQP_disp(x=0,
+ fun=lambda x: 0,
+ jac=lambda x: g,
+ hess=lambda x: None,
+ hessp=lambda x, y: H.dot(y))
+ p, hits_boundary = subprob.solve(trust_radius)
+ out, err = capsys.readouterr()
+ assert_(out.startswith(' TR Solving trust region problem'), repr(out))
+
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_zeros.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_zeros.py
new file mode 100644
index 0000000000000000000000000000000000000000..5dd8bdae65dbaaf3af41d702ef301424e45ae477
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tests/test_zeros.py
@@ -0,0 +1,995 @@
+import warnings
+
+from functools import lru_cache
+
+import pytest
+
+from numpy.testing import (assert_,
+ assert_allclose,
+ assert_equal,
+ assert_array_equal)
+import numpy as np
+from numpy import finfo, power, nan, isclose, sqrt, exp, sin, cos
+
+from scipy import optimize
+from scipy.optimize import (_zeros_py as zeros, newton, root_scalar,
+ OptimizeResult)
+
+from scipy._lib._util import getfullargspec_no_self as _getfullargspec
+
+# Import testing parameters
+from scipy.optimize._tstutils import get_tests, functions as tstutils_functions
+
+TOL = 4*np.finfo(float).eps # tolerance
+
+_FLOAT_EPS = finfo(float).eps
+
+bracket_methods = [zeros.bisect, zeros.ridder, zeros.brentq, zeros.brenth,
+ zeros.toms748]
+gradient_methods = [zeros.newton]
+all_methods = bracket_methods + gradient_methods
+
+# A few test functions used frequently:
+# # A simple quadratic, (x-1)^2 - 1
+def f1(x):
+ return x ** 2 - 2 * x - 1
+
+
+def f1_1(x):
+ return 2 * x - 2
+
+
+def f1_2(x):
+ return 2.0 + 0 * x
+
+
+def f1_and_p_and_pp(x):
+ return f1(x), f1_1(x), f1_2(x)
+
+
+# Simple transcendental function
+def f2(x):
+ return exp(x) - cos(x)
+
+
+def f2_1(x):
+ return exp(x) + sin(x)
+
+
+def f2_2(x):
+ return exp(x) + cos(x)
+
+
+# lru cached function
+@lru_cache
+def f_lrucached(x):
+ return x
+
+
+class TestScalarRootFinders:
+ # Basic tests for all scalar root finders
+
+ xtol = 4 * np.finfo(float).eps
+ rtol = 4 * np.finfo(float).eps
+
+ def _run_one_test(self, tc, method, sig_args_keys=None,
+ sig_kwargs_keys=None, **kwargs):
+ method_args = []
+ for k in sig_args_keys or []:
+ if k not in tc:
+ # If a,b not present use x0, x1. Similarly for f and func
+ k = {'a': 'x0', 'b': 'x1', 'func': 'f'}.get(k, k)
+ method_args.append(tc[k])
+
+ method_kwargs = dict(**kwargs)
+ method_kwargs.update({'full_output': True, 'disp': False})
+ for k in sig_kwargs_keys or []:
+ method_kwargs[k] = tc[k]
+
+ root = tc.get('root')
+ func_args = tc.get('args', ())
+
+ try:
+ r, rr = method(*method_args, args=func_args, **method_kwargs)
+ return root, rr, tc
+ except Exception:
+ return root, zeros.RootResults(nan, -1, -1, zeros._EVALUEERR, method), tc
+
+ def run_tests(self, tests, method, name, known_fail=None, **kwargs):
+ r"""Run test-cases using the specified method and the supplied signature.
+
+ Extract the arguments for the method call from the test case
+ dictionary using the supplied keys for the method's signature."""
+ # The methods have one of two base signatures:
+ # (f, a, b, **kwargs) # newton
+ # (func, x0, **kwargs) # bisect/brentq/...
+
+ # FullArgSpec with args, varargs, varkw, defaults, ...
+ sig = _getfullargspec(method)
+ assert_(not sig.kwonlyargs)
+ nDefaults = len(sig.defaults)
+ nRequired = len(sig.args) - nDefaults
+ sig_args_keys = sig.args[:nRequired]
+ sig_kwargs_keys = []
+ if name in ['secant', 'newton', 'halley']:
+ if name in ['newton', 'halley']:
+ sig_kwargs_keys.append('fprime')
+ if name in ['halley']:
+ sig_kwargs_keys.append('fprime2')
+ kwargs['tol'] = self.xtol
+ else:
+ kwargs['xtol'] = self.xtol
+ kwargs['rtol'] = self.rtol
+
+ results = [list(self._run_one_test(
+ tc, method, sig_args_keys=sig_args_keys,
+ sig_kwargs_keys=sig_kwargs_keys, **kwargs)) for tc in tests]
+ # results= [[true root, full output, tc], ...]
+
+ known_fail = known_fail or []
+ notcvgd = [elt for elt in results if not elt[1].converged]
+ notcvgd = [elt for elt in notcvgd if elt[-1]['ID'] not in known_fail]
+ notcvged_IDS = [elt[-1]['ID'] for elt in notcvgd]
+ assert_equal([len(notcvged_IDS), notcvged_IDS], [0, []])
+
+ # The usable xtol and rtol depend on the test
+ tols = {'xtol': self.xtol, 'rtol': self.rtol}
+ tols.update(**kwargs)
+ rtol = tols['rtol']
+ atol = tols.get('tol', tols['xtol'])
+
+ cvgd = [elt for elt in results if elt[1].converged]
+ approx = [elt[1].root for elt in cvgd]
+ correct = [elt[0] for elt in cvgd]
+ # See if the root matches the reference value
+ notclose = [[a] + elt for a, c, elt in zip(approx, correct, cvgd) if
+ not isclose(a, c, rtol=rtol, atol=atol)
+ and elt[-1]['ID'] not in known_fail]
+ # If not, evaluate the function and see if is 0 at the purported root
+ fvs = [tc['f'](aroot, *tc.get('args', tuple()))
+ for aroot, c, fullout, tc in notclose]
+ notclose = [[fv] + elt for fv, elt in zip(fvs, notclose) if fv != 0]
+ assert_equal([notclose, len(notclose)], [[], 0])
+ method_from_result = [result[1].method for result in results]
+ expected_method = [name for _ in results]
+ assert_equal(method_from_result, expected_method)
+
+ def run_collection(self, collection, method, name, smoothness=None,
+ known_fail=None, **kwargs):
+ r"""Run a collection of tests using the specified method.
+
+ The name is used to determine some optional arguments."""
+ tests = get_tests(collection, smoothness=smoothness)
+ self.run_tests(tests, method, name, known_fail=known_fail, **kwargs)
+
+
+class TestBracketMethods(TestScalarRootFinders):
+ @pytest.mark.parametrize('method', bracket_methods)
+ @pytest.mark.parametrize('function', tstutils_functions)
+ def test_basic_root_scalar(self, method, function):
+ # Tests bracketing root finders called via `root_scalar` on a small
+ # set of simple problems, each of which has a root at `x=1`. Checks for
+ # converged status and that the root was found.
+ a, b = .5, sqrt(3)
+
+ r = root_scalar(function, method=method.__name__, bracket=[a, b], x0=a,
+ xtol=self.xtol, rtol=self.rtol)
+ assert r.converged
+ assert_allclose(r.root, 1.0, atol=self.xtol, rtol=self.rtol)
+ assert r.method == method.__name__
+
+ @pytest.mark.parametrize('method', bracket_methods)
+ @pytest.mark.parametrize('function', tstutils_functions)
+ def test_basic_individual(self, method, function):
+ # Tests individual bracketing root finders on a small set of simple
+ # problems, each of which has a root at `x=1`. Checks for converged
+ # status and that the root was found.
+ a, b = .5, sqrt(3)
+ root, r = method(function, a, b, xtol=self.xtol, rtol=self.rtol,
+ full_output=True)
+
+ assert r.converged
+ assert_allclose(root, 1.0, atol=self.xtol, rtol=self.rtol)
+
+ @pytest.mark.parametrize('method', bracket_methods)
+ @pytest.mark.parametrize('function', tstutils_functions)
+ def test_bracket_is_array(self, method, function):
+ # Test bracketing root finders called via `root_scalar` on a small set
+ # of simple problems, each of which has a root at `x=1`. Check that
+ # passing `bracket` as a `ndarray` is accepted and leads to finding the
+ # correct root.
+ a, b = .5, sqrt(3)
+ r = root_scalar(function, method=method.__name__,
+ bracket=np.array([a, b]), x0=a, xtol=self.xtol,
+ rtol=self.rtol)
+ assert r.converged
+ assert_allclose(r.root, 1.0, atol=self.xtol, rtol=self.rtol)
+ assert r.method == method.__name__
+
+ @pytest.mark.parametrize('method', bracket_methods)
+ def test_aps_collection(self, method):
+ self.run_collection('aps', method, method.__name__, smoothness=1)
+
+ @pytest.mark.parametrize('method', [zeros.bisect, zeros.ridder,
+ zeros.toms748])
+ def test_chandrupatla_collection(self, method):
+ known_fail = {'fun7.4'} if method == zeros.ridder else {}
+ self.run_collection('chandrupatla', method, method.__name__,
+ known_fail=known_fail)
+
+ @pytest.mark.parametrize('method', bracket_methods)
+ def test_lru_cached_individual(self, method):
+ # check that https://github.com/scipy/scipy/issues/10846 is fixed
+ # (`root_scalar` failed when passed a function that was `@lru_cache`d)
+ a, b = -1, 1
+ root, r = method(f_lrucached, a, b, full_output=True)
+ assert r.converged
+ assert_allclose(root, 0)
+
+ def test_gh_22934(self):
+ with pytest.raises(ValueError, match="maxiter must be >= 0"):
+ zeros.brentq(lambda x: x**2 - 1, -2, 0, maxiter=-1)
+
+
+class TestNewton(TestScalarRootFinders):
+ def test_newton_collections(self):
+ known_fail = ['aps.13.00']
+ known_fail += ['aps.12.05', 'aps.12.17'] # fails under Windows Py27
+ for collection in ['aps', 'complex']:
+ self.run_collection(collection, zeros.newton, 'newton',
+ smoothness=2, known_fail=known_fail)
+
+ def test_halley_collections(self):
+ known_fail = ['aps.12.06', 'aps.12.07', 'aps.12.08', 'aps.12.09',
+ 'aps.12.10', 'aps.12.11', 'aps.12.12', 'aps.12.13',
+ 'aps.12.14', 'aps.12.15', 'aps.12.16', 'aps.12.17',
+ 'aps.12.18', 'aps.13.00']
+ for collection in ['aps', 'complex']:
+ self.run_collection(collection, zeros.newton, 'halley',
+ smoothness=2, known_fail=known_fail)
+
+ def test_newton(self):
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ x = zeros.newton(f, 3, tol=1e-6)
+ assert_allclose(f(x), 0, atol=1e-6)
+ x = zeros.newton(f, 3, x1=5, tol=1e-6) # secant, x0 and x1
+ assert_allclose(f(x), 0, atol=1e-6)
+ x = zeros.newton(f, 3, fprime=f_1, tol=1e-6) # newton
+ assert_allclose(f(x), 0, atol=1e-6)
+ x = zeros.newton(f, 3, fprime=f_1, fprime2=f_2, tol=1e-6) # halley
+ assert_allclose(f(x), 0, atol=1e-6)
+
+ def test_newton_by_name(self):
+ r"""Invoke newton through root_scalar()"""
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ r = root_scalar(f, method='newton', x0=3, fprime=f_1, xtol=1e-6)
+ assert_allclose(f(r.root), 0, atol=1e-6)
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ r = root_scalar(f, method='newton', x0=3, xtol=1e-6) # without f'
+ assert_allclose(f(r.root), 0, atol=1e-6)
+
+ def test_secant_by_name(self):
+ r"""Invoke secant through root_scalar()"""
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ r = root_scalar(f, method='secant', x0=3, x1=2, xtol=1e-6)
+ assert_allclose(f(r.root), 0, atol=1e-6)
+ r = root_scalar(f, method='secant', x0=3, x1=5, xtol=1e-6)
+ assert_allclose(f(r.root), 0, atol=1e-6)
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ r = root_scalar(f, method='secant', x0=3, xtol=1e-6) # without x1
+ assert_allclose(f(r.root), 0, atol=1e-6)
+
+ def test_halley_by_name(self):
+ r"""Invoke halley through root_scalar()"""
+ for f, f_1, f_2 in [(f1, f1_1, f1_2), (f2, f2_1, f2_2)]:
+ r = root_scalar(f, method='halley', x0=3,
+ fprime=f_1, fprime2=f_2, xtol=1e-6)
+ assert_allclose(f(r.root), 0, atol=1e-6)
+
+ def test_root_scalar_fail(self):
+ message = 'fprime2 must be specified for halley'
+ with pytest.raises(ValueError, match=message):
+ root_scalar(f1, method='halley', fprime=f1_1, x0=3, xtol=1e-6) # no fprime2
+ message = 'fprime must be specified for halley'
+ with pytest.raises(ValueError, match=message):
+ root_scalar(f1, method='halley', fprime2=f1_2, x0=3, xtol=1e-6) # no fprime
+
+ def test_array_newton(self):
+ """test newton with array"""
+
+ def f1(x, *a):
+ b = a[0] + x * a[3]
+ return a[1] - a[2] * (np.exp(b / a[5]) - 1.0) - b / a[4] - x
+
+ def f1_1(x, *a):
+ b = a[3] / a[5]
+ return -a[2] * np.exp(a[0] / a[5] + x * b) * b - a[3] / a[4] - 1
+
+ def f1_2(x, *a):
+ b = a[3] / a[5]
+ return -a[2] * np.exp(a[0] / a[5] + x * b) * b**2
+
+ a0 = np.array([
+ 5.32725221, 5.48673747, 5.49539973,
+ 5.36387202, 4.80237316, 1.43764452,
+ 5.23063958, 5.46094772, 5.50512718,
+ 5.42046290
+ ])
+ a1 = (np.sin(range(10)) + 1.0) * 7.0
+ args = (a0, a1, 1e-09, 0.004, 10, 0.27456)
+ x0 = [7.0] * 10
+ x = zeros.newton(f1, x0, f1_1, args)
+ x_expected = (
+ 6.17264965, 11.7702805, 12.2219954,
+ 7.11017681, 1.18151293, 0.143707955,
+ 4.31928228, 10.5419107, 12.7552490,
+ 8.91225749
+ )
+ assert_allclose(x, x_expected)
+ # test halley's
+ x = zeros.newton(f1, x0, f1_1, args, fprime2=f1_2)
+ assert_allclose(x, x_expected)
+ # test secant
+ x = zeros.newton(f1, x0, args=args)
+ assert_allclose(x, x_expected)
+
+ def test_array_newton_complex(self):
+ def f(x):
+ return x + 1+1j
+
+ def fprime(x):
+ return 1.0
+
+ t = np.full(4, 1j)
+ x = zeros.newton(f, t, fprime=fprime)
+ assert_allclose(f(x), 0.)
+
+ # should work even if x0 is not complex
+ t = np.ones(4)
+ x = zeros.newton(f, t, fprime=fprime)
+ assert_allclose(f(x), 0.)
+
+ x = zeros.newton(f, t)
+ assert_allclose(f(x), 0.)
+
+ def test_array_secant_active_zero_der(self):
+ """test secant doesn't continue to iterate zero derivatives"""
+ x = zeros.newton(lambda x, *a: x*x - a[0], x0=[4.123, 5],
+ args=[np.array([17, 25])])
+ assert_allclose(x, (4.123105625617661, 5.0))
+
+ def test_array_newton_integers(self):
+ # test secant with float
+ x = zeros.newton(lambda y, z: z - y ** 2, [4.0] * 2,
+ args=([15.0, 17.0],))
+ assert_allclose(x, (3.872983346207417, 4.123105625617661))
+ # test integer becomes float
+ x = zeros.newton(lambda y, z: z - y ** 2, [4] * 2, args=([15, 17],))
+ assert_allclose(x, (3.872983346207417, 4.123105625617661))
+
+ def test_array_newton_zero_der_failures(self):
+ # test derivative zero warning
+ with pytest.warns(RuntimeWarning):
+ zeros.newton(lambda y: y**2 - 2, [0., 0.], lambda y: 2 * y)
+ # test failures and zero_der
+ with pytest.warns(RuntimeWarning):
+ results = zeros.newton(lambda y: y**2 - 2, [0., 0.],
+ lambda y: 2*y, full_output=True)
+ assert_allclose(results.root, 0)
+ assert results.zero_der.all()
+ assert not results.converged.any()
+
+ def test_newton_combined(self):
+ def f1(x):
+ return x ** 2 - 2 * x - 1
+ def f1_1(x):
+ return 2 * x - 2
+ def f1_2(x):
+ return 2.0 + 0 * x
+
+ def f1_and_p_and_pp(x):
+ return x**2 - 2*x-1, 2*x-2, 2.0
+
+ sol0 = root_scalar(f1, method='newton', x0=3, fprime=f1_1)
+ sol = root_scalar(f1_and_p_and_pp, method='newton', x0=3, fprime=True)
+ assert_allclose(sol0.root, sol.root, atol=1e-8)
+ assert_equal(2*sol.function_calls, sol0.function_calls)
+
+ sol0 = root_scalar(f1, method='halley', x0=3, fprime=f1_1, fprime2=f1_2)
+ sol = root_scalar(f1_and_p_and_pp, method='halley', x0=3, fprime2=True)
+ assert_allclose(sol0.root, sol.root, atol=1e-8)
+ assert_equal(3*sol.function_calls, sol0.function_calls)
+
+ def test_newton_full_output(self, capsys):
+ # Test the full_output capability, both when converging and not.
+ # Use simple polynomials, to avoid hitting platform dependencies
+ # (e.g., exp & trig) in number of iterations
+
+ x0 = 3
+ expected_counts = [(6, 7), (5, 10), (3, 9)]
+
+ for derivs in range(3):
+ kwargs = {'tol': 1e-6, 'full_output': True, }
+ for k, v in [['fprime', f1_1], ['fprime2', f1_2]][:derivs]:
+ kwargs[k] = v
+
+ x, r = zeros.newton(f1, x0, disp=False, **kwargs)
+ assert_(r.converged)
+ assert_equal(x, r.root)
+ assert_equal((r.iterations, r.function_calls), expected_counts[derivs])
+ if derivs == 0:
+ assert r.function_calls <= r.iterations + 1
+ else:
+ assert_equal(r.function_calls, (derivs + 1) * r.iterations)
+
+ # Now repeat, allowing one fewer iteration to force convergence failure
+ iters = r.iterations - 1
+ x, r = zeros.newton(f1, x0, maxiter=iters, disp=False, **kwargs)
+ assert_(not r.converged)
+ assert_equal(x, r.root)
+ assert_equal(r.iterations, iters)
+
+ if derivs == 1:
+ # Check that the correct Exception is raised and
+ # validate the start of the message.
+ msg = f'Failed to converge after {iters} iterations, value is .*'
+ with pytest.raises(RuntimeError, match=msg):
+ x, r = zeros.newton(f1, x0, maxiter=iters, disp=True, **kwargs)
+
+ def test_deriv_zero_warning(self):
+ def func(x):
+ return x ** 2 - 2.0
+ def dfunc(x):
+ return 2 * x
+ with pytest.warns(RuntimeWarning):
+ zeros.newton(func, 0.0, dfunc, disp=False)
+ with pytest.raises(RuntimeError, match='Derivative was zero'):
+ zeros.newton(func, 0.0, dfunc)
+
+ def test_newton_does_not_modify_x0(self):
+ # https://github.com/scipy/scipy/issues/9964
+ x0 = np.array([0.1, 3])
+ x0_copy = x0.copy() # Copy to test for equality.
+ newton(np.sin, x0, np.cos)
+ assert_array_equal(x0, x0_copy)
+
+ def test_gh17570_defaults(self):
+ # Previously, when fprime was not specified, root_scalar would default
+ # to secant. When x1 was not specified, secant failed.
+ # Check that without fprime, the default is secant if x1 is specified
+ # and newton otherwise.
+ # Also confirm that `x` is always a scalar (gh-21148)
+ def f(x):
+ assert np.isscalar(x)
+ return f1(x)
+
+ res_newton_default = root_scalar(f, method='newton', x0=3, xtol=1e-6)
+ res_secant_default = root_scalar(f, method='secant', x0=3, x1=2,
+ xtol=1e-6)
+ # `newton` uses the secant method when `x1` and `x2` are specified
+ res_secant = newton(f, x0=3, x1=2, tol=1e-6, full_output=True)[1]
+
+ # all three found a root
+ assert_allclose(f(res_newton_default.root), 0, atol=1e-6)
+ assert res_newton_default.root.shape == tuple()
+ assert_allclose(f(res_secant_default.root), 0, atol=1e-6)
+ assert res_secant_default.root.shape == tuple()
+ assert_allclose(f(res_secant.root), 0, atol=1e-6)
+ assert res_secant.root.shape == tuple()
+
+ # Defaults are correct
+ assert (res_secant_default.root
+ == res_secant.root
+ != res_newton_default.iterations)
+ assert (res_secant_default.iterations
+ == res_secant_default.function_calls - 1 # true for secant
+ == res_secant.iterations
+ != res_newton_default.iterations
+ == res_newton_default.function_calls/2) # newton 2-point diff
+
+ @pytest.mark.parametrize('kwargs', [dict(), {'method': 'newton'}])
+ def test_args_gh19090(self, kwargs):
+ def f(x, a, b):
+ assert a == 3
+ assert b == 1
+ return (x ** a - b)
+
+ res = optimize.root_scalar(f, x0=3, args=(3, 1), **kwargs)
+ assert res.converged
+ assert_allclose(res.root, 1)
+
+ @pytest.mark.parametrize('method', ['secant', 'newton'])
+ def test_int_x0_gh19280(self, method):
+ # Originally, `newton` ensured that only floats were passed to the
+ # callable. This was inadvertently changed by gh-17669. Check that
+ # it has been changed back.
+ def f(x):
+ # an integer raised to a negative integer power would fail
+ return x**-2 - 2
+
+ res = optimize.root_scalar(f, x0=1, method=method)
+ assert res.converged
+ assert_allclose(abs(res.root), 2**-0.5)
+ assert res.root.dtype == np.dtype(np.float64)
+
+ def test_newton_special_parameters(self):
+ # give zeros.newton() some strange parameters
+ # and check whether an exception appears
+ with pytest.raises(ValueError, match="tol too small"):
+ zeros.newton(f1, 3, tol=-1e-6)
+
+ with pytest.raises(ValueError, match="maxiter must be greater than 0"):
+ zeros.newton(f1, 3, tol=1e-6, maxiter=-50)
+
+ with pytest.raises(ValueError, match="x1 and x0 must be different" ):
+ zeros.newton(f1, 3, x1=3)
+
+
+def test_gh_5555():
+ root = 0.1
+
+ def f(x):
+ return x - root
+
+ methods = [zeros.bisect, zeros.ridder]
+ xtol = rtol = TOL
+ for method in methods:
+ res = method(f, -1e8, 1e7, xtol=xtol, rtol=rtol)
+ assert_allclose(root, res, atol=xtol, rtol=rtol,
+ err_msg=f'method {method.__name__}')
+
+
+def test_gh_5557():
+ # Show that without the changes in 5557 brentq and brenth might
+ # only achieve a tolerance of 2*(xtol + rtol*|res|).
+
+ # f linearly interpolates (0, -0.1), (0.5, -0.1), and (1,
+ # 0.4). The important parts are that |f(0)| < |f(1)| (so that
+ # brent takes 0 as the initial guess), |f(0)| < atol (so that
+ # brent accepts 0 as the root), and that the exact root of f lies
+ # more than atol away from 0 (so that brent doesn't achieve the
+ # desired tolerance).
+ def f(x):
+ if x < 0.5:
+ return -0.1
+ else:
+ return x - 0.6
+
+ atol = 0.51
+ rtol = 4 * _FLOAT_EPS
+ methods = [zeros.brentq, zeros.brenth]
+ for method in methods:
+ res = method(f, 0, 1, xtol=atol, rtol=rtol)
+ assert_allclose(0.6, res, atol=atol, rtol=rtol)
+
+
+def test_brent_underflow_in_root_bracketing():
+ # Testing if an interval [a,b] brackets a zero of a function
+ # by checking f(a)*f(b) < 0 is not reliable when the product
+ # underflows/overflows. (reported in issue# 13737)
+
+ underflow_scenario = (-450.0, -350.0, -400.0)
+ overflow_scenario = (350.0, 450.0, 400.0)
+
+ for a, b, root in [underflow_scenario, overflow_scenario]:
+ c = np.exp(root)
+ for method in [zeros.brenth, zeros.brentq]:
+ res = method(lambda x: np.exp(x)-c, a, b)
+ assert_allclose(root, res)
+
+
+class TestRootResults:
+ r = zeros.RootResults(root=1.0, iterations=44, function_calls=46, flag=0,
+ method="newton")
+
+ def test_repr(self):
+ expected_repr = (" converged: True\n flag: converged"
+ "\n function_calls: 46\n iterations: 44\n"
+ " root: 1.0\n method: newton")
+ assert_equal(repr(self.r), expected_repr)
+
+ def test_type(self):
+ assert isinstance(self.r, OptimizeResult)
+
+
+def test_complex_halley():
+ """Test Halley's works with complex roots"""
+ def f(x, *a):
+ return a[0] * x**2 + a[1] * x + a[2]
+
+ def f_1(x, *a):
+ return 2 * a[0] * x + a[1]
+
+ def f_2(x, *a):
+ retval = 2 * a[0]
+ try:
+ size = len(x)
+ except TypeError:
+ return retval
+ else:
+ return [retval] * size
+
+ z = complex(1.0, 2.0)
+ coeffs = (2.0, 3.0, 4.0)
+ y = zeros.newton(f, z, args=coeffs, fprime=f_1, fprime2=f_2, tol=1e-6)
+ # (-0.75000000000000078+1.1989578808281789j)
+ assert_allclose(f(y, *coeffs), 0, atol=1e-6)
+ z = [z] * 10
+ coeffs = (2.0, 3.0, 4.0)
+ y = zeros.newton(f, z, args=coeffs, fprime=f_1, fprime2=f_2, tol=1e-6)
+ assert_allclose(f(y, *coeffs), 0, atol=1e-6)
+
+
+def test_zero_der_nz_dp(capsys):
+ """Test secant method with a non-zero dp, but an infinite newton step"""
+ # pick a symmetrical functions and choose a point on the side that with dx
+ # makes a secant that is a flat line with zero slope, EG: f = (x - 100)**2,
+ # which has a root at x = 100 and is symmetrical around the line x = 100
+ # we have to pick a really big number so that it is consistently true
+ # now find a point on each side so that the secant has a zero slope
+ dx = np.finfo(float).eps ** 0.33
+ # 100 - p0 = p1 - 100 = p0 * (1 + dx) + dx - 100
+ # -> 200 = p0 * (2 + dx) + dx
+ p0 = (200.0 - dx) / (2.0 + dx)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "RMS of", RuntimeWarning)
+ x = zeros.newton(lambda y: (y - 100.0)**2, x0=[p0] * 10)
+ assert_allclose(x, [100] * 10)
+ # test scalar cases too
+ p0 = (2.0 - 1e-4) / (2.0 + 1e-4)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "Tolerance of", RuntimeWarning)
+ x = zeros.newton(lambda y: (y - 1.0) ** 2, x0=p0, disp=False)
+ assert_allclose(x, 1)
+ with pytest.raises(RuntimeError, match='Tolerance of'):
+ x = zeros.newton(lambda y: (y - 1.0) ** 2, x0=p0, disp=True)
+ p0 = (-2.0 + 1e-4) / (2.0 + 1e-4)
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "Tolerance of", RuntimeWarning)
+ x = zeros.newton(lambda y: (y + 1.0) ** 2, x0=p0, disp=False)
+ assert_allclose(x, -1)
+ with pytest.raises(RuntimeError, match='Tolerance of'):
+ x = zeros.newton(lambda y: (y + 1.0) ** 2, x0=p0, disp=True)
+
+
+def test_array_newton_failures():
+ """Test that array newton fails as expected"""
+ # p = 0.68 # [MPa]
+ # dp = -0.068 * 1e6 # [Pa]
+ # T = 323 # [K]
+ diameter = 0.10 # [m]
+ # L = 100 # [m]
+ roughness = 0.00015 # [m]
+ rho = 988.1 # [kg/m**3]
+ mu = 5.4790e-04 # [Pa*s]
+ u = 2.488 # [m/s]
+ reynolds_number = rho * u * diameter / mu # Reynolds number
+
+ def colebrook_eqn(darcy_friction, re, dia):
+ return (1 / np.sqrt(darcy_friction) +
+ 2 * np.log10(roughness / 3.7 / dia +
+ 2.51 / re / np.sqrt(darcy_friction)))
+
+ # only some failures
+ with pytest.warns(RuntimeWarning):
+ result = zeros.newton(
+ colebrook_eqn, x0=[0.01, 0.2, 0.02223, 0.3], maxiter=2,
+ args=[reynolds_number, diameter], full_output=True
+ )
+ assert not result.converged.all()
+ # they all fail
+ with pytest.raises(RuntimeError):
+ result = zeros.newton(
+ colebrook_eqn, x0=[0.01] * 2, maxiter=2,
+ args=[reynolds_number, diameter], full_output=True
+ )
+
+
+# this test should **not** raise a RuntimeWarning
+def test_gh8904_zeroder_at_root_fails():
+ """Test that Newton or Halley don't warn if zero derivative at root"""
+
+ # a function that has a zero derivative at it's root
+ def f_zeroder_root(x):
+ return x**3 - x**2
+
+ # should work with secant
+ r = zeros.newton(f_zeroder_root, x0=0)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ # test again with array
+ r = zeros.newton(f_zeroder_root, x0=[0]*10)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+
+ # 1st derivative
+ def fder(x):
+ return 3 * x**2 - 2 * x
+
+ # 2nd derivative
+ def fder2(x):
+ return 6*x - 2
+
+ # should work with newton and halley
+ r = zeros.newton(f_zeroder_root, x0=0, fprime=fder)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ r = zeros.newton(f_zeroder_root, x0=0, fprime=fder,
+ fprime2=fder2)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ # test again with array
+ r = zeros.newton(f_zeroder_root, x0=[0]*10, fprime=fder)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ r = zeros.newton(f_zeroder_root, x0=[0]*10, fprime=fder,
+ fprime2=fder2)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+
+ # also test that if a root is found we do not raise RuntimeWarning even if
+ # the derivative is zero, EG: at x = 0.5, then fval = -0.125 and
+ # fder = -0.25 so the next guess is 0.5 - (-0.125/-0.5) = 0 which is the
+ # root, but if the solver continued with that guess, then it will calculate
+ # a zero derivative, so it should return the root w/o RuntimeWarning
+ r = zeros.newton(f_zeroder_root, x0=0.5, fprime=fder)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ # test again with array
+ r = zeros.newton(f_zeroder_root, x0=[0.5]*10, fprime=fder)
+ assert_allclose(r, 0, atol=zeros._xtol, rtol=zeros._rtol)
+ # doesn't apply to halley
+
+
+def test_gh_8881():
+ r"""Test that Halley's method realizes that the 2nd order adjustment
+ is too big and drops off to the 1st order adjustment."""
+ n = 9
+
+ def f(x):
+ return power(x, 1.0/n) - power(n, 1.0/n)
+
+ def fp(x):
+ return power(x, (1.0-n)/n)/n
+
+ def fpp(x):
+ return power(x, (1.0-2*n)/n) * (1.0/n) * (1.0-n)/n
+
+ x0 = 0.1
+ # The root is at x=9.
+ # The function has positive slope, x0 < root.
+ # Newton succeeds in 8 iterations
+ rt, r = newton(f, x0, fprime=fp, full_output=True)
+ assert r.converged
+ # Before the Issue 8881/PR 8882, halley would send x in the wrong direction.
+ # Check that it now succeeds.
+ rt, r = newton(f, x0, fprime=fp, fprime2=fpp, full_output=True)
+ assert r.converged
+
+
+def test_gh_9608_preserve_array_shape():
+ """
+ Test that shape is preserved for array inputs even if fprime or fprime2 is
+ scalar
+ """
+ def f(x):
+ return x**2
+
+ def fp(x):
+ return 2 * x
+
+ def fpp(x):
+ return 2
+
+ x0 = np.array([-2], dtype=np.float32)
+ rt, r = newton(f, x0, fprime=fp, fprime2=fpp, full_output=True)
+ assert r.converged
+
+ x0_array = np.array([-2, -3], dtype=np.float32)
+ # This next invocation should fail
+ with pytest.raises(IndexError):
+ result = zeros.newton(
+ f, x0_array, fprime=fp, fprime2=fpp, full_output=True
+ )
+
+ def fpp_array(x):
+ return np.full(np.shape(x), 2, dtype=np.float32)
+
+ result = zeros.newton(
+ f, x0_array, fprime=fp, fprime2=fpp_array, full_output=True
+ )
+ assert result.converged.all()
+
+
+@pytest.mark.parametrize(
+ "maximum_iterations,flag_expected",
+ [(10, zeros.CONVERR), (100, zeros.CONVERGED)])
+def test_gh9254_flag_if_maxiter_exceeded(maximum_iterations, flag_expected):
+ """
+ Test that if the maximum iterations is exceeded that the flag is not
+ converged.
+ """
+ result = zeros.brentq(
+ lambda x: ((1.2*x - 2.3)*x + 3.4)*x - 4.5,
+ -30, 30, (), 1e-6, 1e-6, maximum_iterations,
+ full_output=True, disp=False)
+ assert result[1].flag == flag_expected
+ if flag_expected == zeros.CONVERR:
+ # didn't converge because exceeded maximum iterations
+ assert result[1].iterations == maximum_iterations
+ elif flag_expected == zeros.CONVERGED:
+ # converged before maximum iterations
+ assert result[1].iterations < maximum_iterations
+
+
+def test_gh9551_raise_error_if_disp_true():
+ """Test that if disp is true then zero derivative raises RuntimeError"""
+
+ def f(x):
+ return x*x + 1
+
+ def f_p(x):
+ return 2*x
+
+ with pytest.warns(RuntimeWarning):
+ zeros.newton(f, 1.0, f_p, disp=False)
+ with pytest.raises(
+ RuntimeError,
+ match=r'^Derivative was zero\. Failed to converge after \d+ iterations, '
+ r'value is [+-]?\d*\.\d+\.$'):
+ zeros.newton(f, 1.0, f_p)
+ root = zeros.newton(f, complex(10.0, 10.0), f_p)
+ assert_allclose(root, complex(0.0, 1.0))
+
+
+@pytest.mark.parametrize('solver_name',
+ ['brentq', 'brenth', 'bisect', 'ridder', 'toms748'])
+def test_gh3089_8394(solver_name):
+ # gh-3089 and gh-8394 reported that bracketing solvers returned incorrect
+ # results when they encountered NaNs. Check that this is resolved.
+ def f(x):
+ return np.nan
+
+ solver = getattr(zeros, solver_name)
+ with pytest.raises(ValueError, match="The function value at x..."):
+ solver(f, 0, 1)
+
+
+@pytest.mark.parametrize('method',
+ ['brentq', 'brenth', 'bisect', 'ridder', 'toms748'])
+def test_gh18171(method):
+ # gh-3089 and gh-8394 reported that bracketing solvers returned incorrect
+ # results when they encountered NaNs. Check that `root_scalar` returns
+ # normally but indicates that convergence was unsuccessful. See gh-18171.
+ def f(x):
+ f._count += 1
+ return np.nan
+ f._count = 0
+
+ res = root_scalar(f, bracket=(0, 1), method=method)
+ assert res.converged is False
+ assert res.flag.startswith("The function value at x")
+ assert res.function_calls == f._count
+ assert str(res.root) in res.flag
+
+
+@pytest.mark.parametrize('solver_name',
+ ['brentq', 'brenth', 'bisect', 'ridder', 'toms748'])
+@pytest.mark.parametrize('rs_interface', [True, False])
+def test_function_calls(solver_name, rs_interface):
+ # There do not appear to be checks that the bracketing solvers report the
+ # correct number of function evaluations. Check that this is the case.
+ solver = ((lambda f, a, b, **kwargs: root_scalar(f, bracket=(a, b)))
+ if rs_interface else getattr(zeros, solver_name))
+
+ def f(x):
+ f.calls += 1
+ return x**2 - 1
+ f.calls = 0
+
+ res = solver(f, 0, 10, full_output=True)
+
+ if rs_interface:
+ assert res.function_calls == f.calls
+ else:
+ assert res[1].function_calls == f.calls
+
+
+def test_gh_14486_converged_false():
+ """Test that zero slope with secant method results in a converged=False"""
+ def lhs(x):
+ return x * np.exp(-x*x) - 0.07
+
+ with pytest.warns(RuntimeWarning, match='Tolerance of'):
+ res = root_scalar(lhs, method='secant', x0=-0.15, x1=1.0)
+ assert not res.converged
+ assert res.flag == 'convergence error'
+
+ with pytest.warns(RuntimeWarning, match='Tolerance of'):
+ res = newton(lhs, x0=-0.15, x1=1.0, disp=False, full_output=True)[1]
+ assert not res.converged
+ assert res.flag == 'convergence error'
+
+
+@pytest.mark.parametrize('solver_name',
+ ['brentq', 'brenth', 'bisect', 'ridder', 'toms748'])
+@pytest.mark.parametrize('rs_interface', [True, False])
+def test_gh5584(solver_name, rs_interface):
+ # gh-5584 reported that an underflow can cause sign checks in the algorithm
+ # to fail. Check that this is resolved.
+ solver = ((lambda f, a, b, **kwargs: root_scalar(f, bracket=(a, b)))
+ if rs_interface else getattr(zeros, solver_name))
+
+ def f(x):
+ return 1e-200*x
+
+ # Report failure when signs are the same
+ with pytest.raises(ValueError, match='...must have different signs'):
+ solver(f, -0.5, -0.4, full_output=True)
+
+ # Solve successfully when signs are different
+ res = solver(f, -0.5, 0.4, full_output=True)
+ res = res if rs_interface else res[1]
+ assert res.converged
+ assert_allclose(res.root, 0, atol=1e-8)
+
+ # Solve successfully when one side is negative zero
+ res = solver(f, -0.5, float('-0.0'), full_output=True)
+ res = res if rs_interface else res[1]
+ assert res.converged
+ assert_allclose(res.root, 0, atol=1e-8)
+
+
+def test_gh13407():
+ # gh-13407 reported that the message produced by `scipy.optimize.toms748`
+ # when `rtol < eps` is incorrect, and also that toms748 is unusual in
+ # accepting `rtol` as low as eps while other solvers raise at 4*eps. Check
+ # that the error message has been corrected and that `rtol=eps` can produce
+ # a lower function value than `rtol=4*eps`.
+ def f(x):
+ return x**3 - 2*x - 5
+
+ xtol = 1e-300
+ eps = np.finfo(float).eps
+ x1 = zeros.toms748(f, 1e-10, 1e10, xtol=xtol, rtol=1*eps)
+ f1 = f(x1)
+ x4 = zeros.toms748(f, 1e-10, 1e10, xtol=xtol, rtol=4*eps)
+ f4 = f(x4)
+ assert f1 < f4
+
+ # using old-style syntax to get exactly the same message
+ message = fr"rtol too small \({eps/2:g} < {eps:g}\)"
+ with pytest.raises(ValueError, match=message):
+ zeros.toms748(f, 1e-10, 1e10, xtol=xtol, rtol=eps/2)
+
+
+def test_newton_complex_gh10103():
+ # gh-10103 reported a problem when `newton` is pass a Python complex x0,
+ # no `fprime` (secant method), and no `x1` (`x1` must be constructed).
+ # Check that this is resolved.
+ def f(z):
+ return z - 1
+ res = newton(f, 1+1j)
+ assert_allclose(res, 1, atol=1e-12)
+
+ res = root_scalar(f, x0=1+1j, x1=2+1.5j, method='secant')
+ assert_allclose(res.root, 1, atol=1e-12)
+
+
+@pytest.mark.parametrize('method', all_methods)
+def test_maxiter_int_check_gh10236(method):
+ # gh-10236 reported that the error message when `maxiter` is not an integer
+ # was difficult to interpret. Check that this was resolved (by gh-10907).
+ message = "'float' object cannot be interpreted as an integer"
+ with pytest.raises(TypeError, match=message):
+ method(f1, 0.0, 1.0, maxiter=72.45)
+
+@pytest.mark.parametrize("method", [zeros.bisect, zeros.ridder,
+ zeros.brentq, zeros.brenth])
+def test_bisect_special_parameter(method):
+ # give some zeros method strange parameters
+ # and check whether an exception appears
+ root = 0.1
+ args = (1e-09, 0.004, 10, 0.27456)
+ rtolbad = 4 * np.finfo(float).eps / 2
+
+ def f(x):
+ return x - root
+
+ with pytest.raises(ValueError, match="xtol too small"):
+ method(f, -1e8, 1e7, args=args, xtol=-1e-6, rtol=TOL)
+ with pytest.raises(ValueError, match="rtol too small"):
+ method(f, -1e8, 1e7, args=args, xtol=1e-6, rtol=rtolbad)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tnc.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tnc.py
new file mode 100644
index 0000000000000000000000000000000000000000..e0f66058bbcc501eb1303eb3075cb55705b93192
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/tnc.py
@@ -0,0 +1,22 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'OptimizeResult',
+ 'fmin_tnc',
+ 'zeros',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="tnc",
+ private_modules=["_tnc"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/zeros.py b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/zeros.py
new file mode 100644
index 0000000000000000000000000000000000000000..907d49d37fc1e7476e81a25dbbc0d3910cbbe004
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/optimize/zeros.py
@@ -0,0 +1,26 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.optimize` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = [ # noqa: F822
+ 'RootResults',
+ 'bisect',
+ 'brenth',
+ 'brentq',
+ 'newton',
+ 'ridder',
+ 'toms748',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="optimize", module="zeros",
+ private_modules=["_zeros_py"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__arraytools.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__arraytools.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__arraytools.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__czt.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__czt.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__czt.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__delegators.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__delegators.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__delegators.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__filter_design.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__fir_filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__fir_filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__fir_filter_design.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__lti_conversion.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__lti_conversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__lti_conversion.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__ltisys.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__ltisys.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__ltisys.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__max_len_seq.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__max_len_seq.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__max_len_seq.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__max_len_seq_inner.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__max_len_seq_inner.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__max_len_seq_inner.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__peak_finding.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__peak_finding.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__peak_finding.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__peak_finding_utils.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__peak_finding_utils.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__peak_finding_utils.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__polyutils.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__polyutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__polyutils.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__savitzky_golay.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__savitzky_golay.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__savitzky_golay.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__short_time_fft.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__short_time_fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__short_time_fft.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__signal_api.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__signal_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__signal_api.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__signaltools.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__signaltools.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__signaltools.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__sigtools.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__sigtools.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__sigtools.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__sosfilt.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__sosfilt.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__sosfilt.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spectral_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spectral_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spectral_py.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spline.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spline.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spline.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spline.pyi b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spline.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spline.pyi differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spline_filters.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spline_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__spline_filters.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__support_alternative_backends.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__support_alternative_backends.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__upfirdn.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__upfirdn.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__upfirdn.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__upfirdn_apply.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__upfirdn_apply.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__upfirdn_apply.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__waveforms.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__waveforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__waveforms.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__wavelets.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__wavelets.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/.__wavelets.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._bsplines.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._bsplines.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._bsplines.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._filter_design.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._fir_filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._fir_filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._fir_filter_design.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._lti_conversion.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._lti_conversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._lti_conversion.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._ltisys.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._ltisys.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._ltisys.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._signaltools.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._signaltools.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._signaltools.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._spectral.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._spectral.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._spline.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._spline.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._spline.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._tests b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._tests
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._tests differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._waveforms.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._waveforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._waveforms.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._wavelets.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._wavelets.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._wavelets.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._windows b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._windows
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/._windows differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..c778768fe5d97313fbabe0fd0f901dcd1bda27f3
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/__init__.py
@@ -0,0 +1,321 @@
+"""
+=======================================
+Signal processing (:mod:`scipy.signal`)
+=======================================
+
+.. toctree::
+ :hidden:
+
+ signal.windows
+
+Convolution
+===========
+
+.. autosummary::
+ :toctree: generated/
+
+ convolve -- N-D convolution.
+ correlate -- N-D correlation.
+ fftconvolve -- N-D convolution using the FFT.
+ oaconvolve -- N-D convolution using the overlap-add method.
+ convolve2d -- 2-D convolution (more options).
+ correlate2d -- 2-D correlation (more options).
+ sepfir2d -- Convolve with a 2-D separable FIR filter.
+ choose_conv_method -- Chooses faster of FFT and direct convolution methods.
+ correlation_lags -- Determines lag indices for 1D cross-correlation.
+
+B-splines
+=========
+
+.. autosummary::
+ :toctree: generated/
+
+ gauss_spline -- Gaussian approximation to the B-spline basis function.
+ cspline1d -- Coefficients for 1-D cubic (3rd order) B-spline.
+ qspline1d -- Coefficients for 1-D quadratic (2nd order) B-spline.
+ cspline2d -- Coefficients for 2-D cubic (3rd order) B-spline.
+ qspline2d -- Coefficients for 2-D quadratic (2nd order) B-spline.
+ cspline1d_eval -- Evaluate a cubic spline at the given points.
+ qspline1d_eval -- Evaluate a quadratic spline at the given points.
+ spline_filter -- Smoothing spline (cubic) filtering of a rank-2 array.
+
+Filtering
+=========
+
+.. autosummary::
+ :toctree: generated/
+
+ order_filter -- N-D order filter.
+ medfilt -- N-D median filter.
+ medfilt2d -- 2-D median filter (faster).
+ wiener -- N-D Wiener filter.
+
+ symiirorder1 -- 2nd-order IIR filter (cascade of first-order systems).
+ symiirorder2 -- 4th-order IIR filter (cascade of second-order systems).
+ lfilter -- 1-D FIR and IIR digital linear filtering.
+ lfiltic -- Construct initial conditions for `lfilter`.
+ lfilter_zi -- Compute an initial state zi for the lfilter function that
+ -- corresponds to the steady state of the step response.
+ filtfilt -- A forward-backward filter.
+ savgol_filter -- Filter a signal using the Savitzky-Golay filter.
+
+ deconvolve -- 1-D deconvolution using lfilter.
+
+ sosfilt -- 1-D IIR digital linear filtering using
+ -- a second-order sections filter representation.
+ sosfilt_zi -- Compute an initial state zi for the sosfilt function that
+ -- corresponds to the steady state of the step response.
+ sosfiltfilt -- A forward-backward filter for second-order sections.
+ hilbert -- Compute 1-D analytic signal, using the Hilbert transform.
+ hilbert2 -- Compute 2-D analytic signal, using the Hilbert transform.
+ envelope -- Compute the envelope of a real- or complex-valued signal.
+
+ decimate -- Downsample a signal.
+ detrend -- Remove linear and/or constant trends from data.
+ resample -- Resample using Fourier method.
+ resample_poly -- Resample using polyphase filtering method.
+ upfirdn -- Upsample, apply FIR filter, downsample.
+
+Filter design
+=============
+
+.. autosummary::
+ :toctree: generated/
+
+ bilinear -- Digital filter from an analog filter using
+ -- the bilinear transform.
+ bilinear_zpk -- Digital filter from an analog filter using
+ -- the bilinear transform.
+ findfreqs -- Find array of frequencies for computing filter response.
+ firls -- FIR filter design using least-squares error minimization.
+ firwin -- Windowed FIR filter design, with frequency response
+ -- defined as pass and stop bands.
+ firwin2 -- Windowed FIR filter design, with arbitrary frequency
+ -- response.
+ firwin_2d -- Windowed FIR filter design, with frequency response for
+ -- 2D using 1D design.
+ freqs -- Analog filter frequency response from TF coefficients.
+ freqs_zpk -- Analog filter frequency response from ZPK coefficients.
+ freqz -- Digital filter frequency response from TF coefficients.
+ sosfreqz -- Digital filter frequency response for SOS format filter (legacy).
+ freqz_sos -- Digital filter frequency response for SOS format filter.
+ freqz_zpk -- Digital filter frequency response from ZPK coefficients.
+ gammatone -- FIR and IIR gammatone filter design.
+ group_delay -- Digital filter group delay.
+ iirdesign -- IIR filter design given bands and gains.
+ iirfilter -- IIR filter design given order and critical frequencies.
+ kaiser_atten -- Compute the attenuation of a Kaiser FIR filter, given
+ -- the number of taps and the transition width at
+ -- discontinuities in the frequency response.
+ kaiser_beta -- Compute the Kaiser parameter beta, given the desired
+ -- FIR filter attenuation.
+ kaiserord -- Design a Kaiser window to limit ripple and width of
+ -- transition region.
+ minimum_phase -- Convert a linear phase FIR filter to minimum phase.
+ savgol_coeffs -- Compute the FIR filter coefficients for a Savitzky-Golay
+ -- filter.
+ remez -- Optimal FIR filter design.
+
+ unique_roots -- Unique roots and their multiplicities.
+ residue -- Partial fraction expansion of b(s) / a(s).
+ residuez -- Partial fraction expansion of b(z) / a(z).
+ invres -- Inverse partial fraction expansion for analog filter.
+ invresz -- Inverse partial fraction expansion for digital filter.
+ BadCoefficients -- Warning on badly conditioned filter coefficients.
+
+Lower-level filter design functions:
+
+.. autosummary::
+ :toctree: generated/
+
+ abcd_normalize -- Check state-space matrices compatibility and ensure they are 2d.
+ band_stop_obj -- Band Stop Objective Function for order minimization.
+ besselap -- Return (z,p,k) for analog prototype of Bessel filter.
+ buttap -- Return (z,p,k) for analog prototype of Butterworth filter.
+ cheb1ap -- Return (z,p,k) for type I Chebyshev filter.
+ cheb2ap -- Return (z,p,k) for type II Chebyshev filter.
+ ellipap -- Return (z,p,k) for analog prototype of elliptic filter.
+ lp2bp -- Transform a lowpass filter prototype to a bandpass filter.
+ lp2bp_zpk -- Transform a lowpass filter prototype to a bandpass filter.
+ lp2bs -- Transform a lowpass filter prototype to a bandstop filter.
+ lp2bs_zpk -- Transform a lowpass filter prototype to a bandstop filter.
+ lp2hp -- Transform a lowpass filter prototype to a highpass filter.
+ lp2hp_zpk -- Transform a lowpass filter prototype to a highpass filter.
+ lp2lp -- Transform a lowpass filter prototype to a lowpass filter.
+ lp2lp_zpk -- Transform a lowpass filter prototype to a lowpass filter.
+ normalize -- Normalize polynomial representation of a transfer function.
+
+
+
+Matlab-style IIR filter design
+==============================
+
+.. autosummary::
+ :toctree: generated/
+
+ butter -- Butterworth
+ buttord
+ cheby1 -- Chebyshev Type I
+ cheb1ord
+ cheby2 -- Chebyshev Type II
+ cheb2ord
+ ellip -- Elliptic (Cauer)
+ ellipord
+ bessel -- Bessel (no order selection available -- try butterod)
+ iirnotch -- Design second-order IIR notch digital filter.
+ iirpeak -- Design second-order IIR peak (resonant) digital filter.
+ iircomb -- Design IIR comb filter.
+
+Continuous-time linear systems
+==============================
+
+.. autosummary::
+ :toctree: generated/
+
+ lti -- Continuous-time linear time invariant system base class.
+ StateSpace -- Linear time invariant system in state space form.
+ TransferFunction -- Linear time invariant system in transfer function form.
+ ZerosPolesGain -- Linear time invariant system in zeros, poles, gain form.
+ lsim -- Continuous-time simulation of output to linear system.
+ impulse -- Impulse response of linear, time-invariant (LTI) system.
+ step -- Step response of continuous-time LTI system.
+ freqresp -- Frequency response of a continuous-time LTI system.
+ bode -- Bode magnitude and phase data (continuous-time LTI).
+
+Discrete-time linear systems
+============================
+
+.. autosummary::
+ :toctree: generated/
+
+ dlti -- Discrete-time linear time invariant system base class.
+ StateSpace -- Linear time invariant system in state space form.
+ TransferFunction -- Linear time invariant system in transfer function form.
+ ZerosPolesGain -- Linear time invariant system in zeros, poles, gain form.
+ dlsim -- Simulation of output to a discrete-time linear system.
+ dimpulse -- Impulse response of a discrete-time LTI system.
+ dstep -- Step response of a discrete-time LTI system.
+ dfreqresp -- Frequency response of a discrete-time LTI system.
+ dbode -- Bode magnitude and phase data (discrete-time LTI).
+
+LTI representations
+===================
+
+.. autosummary::
+ :toctree: generated/
+
+ tf2zpk -- Transfer function to zero-pole-gain.
+ tf2sos -- Transfer function to second-order sections.
+ tf2ss -- Transfer function to state-space.
+ zpk2tf -- Zero-pole-gain to transfer function.
+ zpk2sos -- Zero-pole-gain to second-order sections.
+ zpk2ss -- Zero-pole-gain to state-space.
+ ss2tf -- State-pace to transfer function.
+ ss2zpk -- State-space to pole-zero-gain.
+ sos2zpk -- Second-order sections to zero-pole-gain.
+ sos2tf -- Second-order sections to transfer function.
+ cont2discrete -- Continuous-time to discrete-time LTI conversion.
+ place_poles -- Pole placement.
+
+Waveforms
+=========
+
+.. autosummary::
+ :toctree: generated/
+
+ chirp -- Frequency swept cosine signal, with several freq functions.
+ gausspulse -- Gaussian modulated sinusoid.
+ max_len_seq -- Maximum length sequence.
+ sawtooth -- Periodic sawtooth.
+ square -- Square wave.
+ sweep_poly -- Frequency swept cosine signal; freq is arbitrary polynomial.
+ unit_impulse -- Discrete unit impulse.
+
+Window functions
+================
+
+For window functions, see the `scipy.signal.windows` namespace.
+
+In the `scipy.signal` namespace, there is a convenience function to
+obtain these windows by name:
+
+.. autosummary::
+ :toctree: generated/
+
+ get_window -- Convenience function for creating various windows.
+
+Peak finding
+============
+
+.. autosummary::
+ :toctree: generated/
+
+ argrelmin -- Calculate the relative minima of data.
+ argrelmax -- Calculate the relative maxima of data.
+ argrelextrema -- Calculate the relative extrema of data.
+ find_peaks -- Find a subset of peaks inside a signal.
+ find_peaks_cwt -- Find peaks in a 1-D array with wavelet transformation.
+ peak_prominences -- Calculate the prominence of each peak in a signal.
+ peak_widths -- Calculate the width of each peak in a signal.
+
+Spectral analysis
+=================
+
+.. autosummary::
+ :toctree: generated/
+
+ periodogram -- Compute a (modified) periodogram.
+ welch -- Compute a periodogram using Welch's method.
+ csd -- Compute the cross spectral density, using Welch's method.
+ coherence -- Compute the magnitude squared coherence, using Welch's method.
+ spectrogram -- Compute the spectrogram (legacy).
+ lombscargle -- Computes the Lomb-Scargle periodogram.
+ vectorstrength -- Computes the vector strength.
+ ShortTimeFFT -- Interface for calculating the \
+ :ref:`Short Time Fourier Transform ` and \
+ its inverse.
+ closest_STFT_dual_window -- Calculate the STFT dual window of a given window \
+ closest to a desired dual window.
+ stft -- Compute the Short Time Fourier Transform (legacy).
+ istft -- Compute the Inverse Short Time Fourier Transform (legacy).
+ check_COLA -- Check the COLA constraint for iSTFT reconstruction (legacy).
+ check_NOLA -- Check the NOLA constraint for iSTFT reconstruction.
+
+Chirp Z-transform and Zoom FFT
+============================================
+
+.. autosummary::
+ :toctree: generated/
+
+ czt - Chirp z-transform convenience function
+ zoom_fft - Zoom FFT convenience function
+ CZT - Chirp z-transform function generator
+ ZoomFFT - Zoom FFT function generator
+ czt_points - Output the z-plane points sampled by a chirp z-transform
+
+The functions are simpler to use than the classes, but are less efficient when
+using the same transform on many arrays of the same length, since they
+repeatedly generate the same chirp signal with every call. In these cases,
+use the classes to create a reusable function instead.
+
+"""
+# bring in the public functionality from private namespaces
+
+# mypy: ignore-errors
+
+from ._support_alternative_backends import *
+from . import _support_alternative_backends
+__all__ = _support_alternative_backends.__all__
+del _support_alternative_backends, _signal_api, _delegators # noqa: F821
+
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import (
+ bsplines, filter_design, fir_filter_design, lti_conversion, ltisys,
+ spectral, signaltools, waveforms, wavelets, spline
+)
+
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_arraytools.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_arraytools.py
new file mode 100644
index 0000000000000000000000000000000000000000..87ce75d8d892a64021da7abc5d149556c22cf983
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_arraytools.py
@@ -0,0 +1,264 @@
+"""
+Functions for acting on a axis of an array.
+"""
+import numpy as np
+
+
+def axis_slice(a, start=None, stop=None, step=None, axis=-1):
+ """Take a slice along axis 'axis' from 'a'.
+
+ Parameters
+ ----------
+ a : numpy.ndarray
+ The array to be sliced.
+ start, stop, step : int or None
+ The slice parameters.
+ axis : int, optional
+ The axis of `a` to be sliced.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._arraytools import axis_slice
+ >>> a = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
+ >>> axis_slice(a, start=0, stop=1, axis=1)
+ array([[1],
+ [4],
+ [7]])
+ >>> axis_slice(a, start=1, axis=0)
+ array([[4, 5, 6],
+ [7, 8, 9]])
+
+ Notes
+ -----
+ The keyword arguments start, stop and step are used by calling
+ slice(start, stop, step). This implies axis_slice() does not
+ handle its arguments the exactly the same as indexing. To select
+ a single index k, for example, use
+ axis_slice(a, start=k, stop=k+1)
+ In this case, the length of the axis 'axis' in the result will
+ be 1; the trivial dimension is not removed. (Use numpy.squeeze()
+ to remove trivial axes.)
+ """
+ a_slice = [slice(None)] * a.ndim
+ a_slice[axis] = slice(start, stop, step)
+ b = a[tuple(a_slice)]
+ return b
+
+
+def axis_reverse(a, axis=-1):
+ """Reverse the 1-D slices of `a` along axis `axis`.
+
+ Returns axis_slice(a, step=-1, axis=axis).
+ """
+ return axis_slice(a, step=-1, axis=axis)
+
+
+def odd_ext(x, n, axis=-1):
+ """
+ Odd extension at the boundaries of an array
+
+ Generate a new ndarray by making an odd extension of `x` along an axis.
+
+ Parameters
+ ----------
+ x : ndarray
+ The array to be extended.
+ n : int
+ The number of elements by which to extend `x` at each end of the axis.
+ axis : int, optional
+ The axis along which to extend `x`. Default is -1.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._arraytools import odd_ext
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
+ >>> odd_ext(a, 2)
+ array([[-1, 0, 1, 2, 3, 4, 5, 6, 7],
+ [-4, -1, 0, 1, 4, 9, 16, 23, 28]])
+
+ Odd extension is a "180 degree rotation" at the endpoints of the original
+ array:
+
+ >>> t = np.linspace(0, 1.5, 100)
+ >>> a = 0.9 * np.sin(2 * np.pi * t**2)
+ >>> b = odd_ext(a, 40)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='odd extension')
+ >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original')
+ >>> plt.legend(loc='best')
+ >>> plt.show()
+ """
+ if n < 1:
+ return x
+ if n > x.shape[axis] - 1:
+ raise ValueError(("The extension length n (%d) is too big. " +
+ "It must not exceed x.shape[axis]-1, which is %d.")
+ % (n, x.shape[axis] - 1))
+ left_end = axis_slice(x, start=0, stop=1, axis=axis)
+ left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis)
+ right_end = axis_slice(x, start=-1, axis=axis)
+ right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis)
+ ext = np.concatenate((2 * left_end - left_ext,
+ x,
+ 2 * right_end - right_ext),
+ axis=axis)
+ return ext
+
+
+def even_ext(x, n, axis=-1):
+ """
+ Even extension at the boundaries of an array
+
+ Generate a new ndarray by making an even extension of `x` along an axis.
+
+ Parameters
+ ----------
+ x : ndarray
+ The array to be extended.
+ n : int
+ The number of elements by which to extend `x` at each end of the axis.
+ axis : int, optional
+ The axis along which to extend `x`. Default is -1.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._arraytools import even_ext
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
+ >>> even_ext(a, 2)
+ array([[ 3, 2, 1, 2, 3, 4, 5, 4, 3],
+ [ 4, 1, 0, 1, 4, 9, 16, 9, 4]])
+
+ Even extension is a "mirror image" at the boundaries of the original array:
+
+ >>> t = np.linspace(0, 1.5, 100)
+ >>> a = 0.9 * np.sin(2 * np.pi * t**2)
+ >>> b = even_ext(a, 40)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='even extension')
+ >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original')
+ >>> plt.legend(loc='best')
+ >>> plt.show()
+ """
+ if n < 1:
+ return x
+ if n > x.shape[axis] - 1:
+ raise ValueError(("The extension length n (%d) is too big. " +
+ "It must not exceed x.shape[axis]-1, which is %d.")
+ % (n, x.shape[axis] - 1))
+ left_ext = axis_slice(x, start=n, stop=0, step=-1, axis=axis)
+ right_ext = axis_slice(x, start=-2, stop=-(n + 2), step=-1, axis=axis)
+ ext = np.concatenate((left_ext,
+ x,
+ right_ext),
+ axis=axis)
+ return ext
+
+
+def const_ext(x, n, axis=-1):
+ """
+ Constant extension at the boundaries of an array
+
+ Generate a new ndarray that is a constant extension of `x` along an axis.
+
+ The extension repeats the values at the first and last element of
+ the axis.
+
+ Parameters
+ ----------
+ x : ndarray
+ The array to be extended.
+ n : int
+ The number of elements by which to extend `x` at each end of the axis.
+ axis : int, optional
+ The axis along which to extend `x`. Default is -1.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._arraytools import const_ext
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
+ >>> const_ext(a, 2)
+ array([[ 1, 1, 1, 2, 3, 4, 5, 5, 5],
+ [ 0, 0, 0, 1, 4, 9, 16, 16, 16]])
+
+ Constant extension continues with the same values as the endpoints of the
+ array:
+
+ >>> t = np.linspace(0, 1.5, 100)
+ >>> a = 0.9 * np.sin(2 * np.pi * t**2)
+ >>> b = const_ext(a, 40)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(np.arange(-40, 140), b, 'b', lw=1, label='constant extension')
+ >>> plt.plot(np.arange(100), a, 'r', lw=2, label='original')
+ >>> plt.legend(loc='best')
+ >>> plt.show()
+ """
+ if n < 1:
+ return x
+ left_end = axis_slice(x, start=0, stop=1, axis=axis)
+ ones_shape = [1] * x.ndim
+ ones_shape[axis] = n
+ ones = np.ones(ones_shape, dtype=x.dtype)
+ left_ext = ones * left_end
+ right_end = axis_slice(x, start=-1, axis=axis)
+ right_ext = ones * right_end
+ ext = np.concatenate((left_ext,
+ x,
+ right_ext),
+ axis=axis)
+ return ext
+
+
+def zero_ext(x, n, axis=-1):
+ """
+ Zero padding at the boundaries of an array
+
+ Generate a new ndarray that is a zero-padded extension of `x` along
+ an axis.
+
+ Parameters
+ ----------
+ x : ndarray
+ The array to be extended.
+ n : int
+ The number of elements by which to extend `x` at each end of the
+ axis.
+ axis : int, optional
+ The axis along which to extend `x`. Default is -1.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._arraytools import zero_ext
+ >>> a = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]])
+ >>> zero_ext(a, 2)
+ array([[ 0, 0, 1, 2, 3, 4, 5, 0, 0],
+ [ 0, 0, 0, 1, 4, 9, 16, 0, 0]])
+ """
+ if n < 1:
+ return x
+ zeros_shape = list(x.shape)
+ zeros_shape[axis] = n
+ zeros = np.zeros(zeros_shape, dtype=x.dtype)
+ ext = np.concatenate((zeros, x, zeros), axis=axis)
+ return ext
+
+
+def _validate_fs(fs, allow_none=True):
+ """
+ Check if the given sampling frequency is a scalar and raises an exception
+ otherwise. If allow_none is False, also raises an exception for none
+ sampling rates. Returns the sampling frequency as float or none if the
+ input is none.
+ """
+ if fs is None:
+ if not allow_none:
+ raise ValueError("Sampling frequency can not be none.")
+ else: # should be float
+ if not np.isscalar(fs):
+ raise ValueError("Sampling frequency fs must be a single scalar.")
+ fs = float(fs)
+ return fs
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_czt.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_czt.py
new file mode 100644
index 0000000000000000000000000000000000000000..c5e5715b460fb2719b68d4694474bc1efc0a9fa0
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_czt.py
@@ -0,0 +1,575 @@
+# This program is public domain
+# Authors: Paul Kienzle, Nadav Horesh
+"""
+Chirp z-transform.
+
+We provide two interfaces to the chirp z-transform: an object interface
+which precalculates part of the transform and can be applied efficiently
+to many different data sets, and a functional interface which is applied
+only to the given data set.
+
+Transforms
+----------
+
+CZT : callable (x, axis=-1) -> array
+ Define a chirp z-transform that can be applied to different signals.
+ZoomFFT : callable (x, axis=-1) -> array
+ Define a Fourier transform on a range of frequencies.
+
+Functions
+---------
+
+czt : array
+ Compute the chirp z-transform for a signal.
+zoom_fft : array
+ Compute the Fourier transform on a range of frequencies.
+"""
+
+import cmath
+import numbers
+import numpy as np
+from numpy import pi, arange
+from scipy.fft import fft, ifft, next_fast_len
+
+__all__ = ['czt', 'zoom_fft', 'CZT', 'ZoomFFT', 'czt_points']
+
+
+def _validate_sizes(n, m):
+ if n < 1 or not isinstance(n, numbers.Integral):
+ raise ValueError('Invalid number of CZT data '
+ f'points ({n}) specified. '
+ 'n must be positive and integer type.')
+
+ if m is None:
+ m = n
+ elif m < 1 or not isinstance(m, numbers.Integral):
+ raise ValueError('Invalid number of CZT output '
+ f'points ({m}) specified. '
+ 'm must be positive and integer type.')
+
+ return m
+
+
+def czt_points(m, w=None, a=1+0j):
+ """
+ Return the points at which the chirp z-transform is computed.
+
+ Parameters
+ ----------
+ m : int
+ The number of points desired.
+ w : complex, optional
+ The ratio between points in each step.
+ Defaults to equally spaced points around the entire unit circle.
+ a : complex, optional
+ The starting point in the complex plane. Default is 1+0j.
+
+ Returns
+ -------
+ out : ndarray
+ The points in the Z plane at which `CZT` samples the z-transform,
+ when called with arguments `m`, `w`, and `a`, as complex numbers.
+
+ See Also
+ --------
+ CZT : Class that creates a callable chirp z-transform function.
+ czt : Convenience function for quickly calculating CZT.
+
+ Examples
+ --------
+ Plot the points of a 16-point FFT:
+
+ >>> import numpy as np
+ >>> from scipy.signal import czt_points
+ >>> points = czt_points(16)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(points.real, points.imag, 'o')
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
+ >>> plt.axis('equal')
+ >>> plt.show()
+
+ and a 91-point logarithmic spiral that crosses the unit circle:
+
+ >>> m, w, a = 91, 0.995*np.exp(-1j*np.pi*.05), 0.8*np.exp(1j*np.pi/6)
+ >>> points = czt_points(m, w, a)
+ >>> plt.plot(points.real, points.imag, 'o')
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
+ >>> plt.axis('equal')
+ >>> plt.show()
+ """
+ m = _validate_sizes(1, m)
+
+ k = arange(m)
+
+ a = 1.0 * a # at least float
+
+ if w is None:
+ # Nothing specified, default to FFT
+ return a * np.exp(2j * pi * k / m)
+ else:
+ # w specified
+ w = 1.0 * w # at least float
+ return a * w**-k
+
+
+class CZT:
+ """
+ Create a callable chirp z-transform function.
+
+ Transform to compute the frequency response around a spiral.
+ Objects of this class are callables which can compute the
+ chirp z-transform on their inputs. This object precalculates the constant
+ chirps used in the given transform.
+
+ Parameters
+ ----------
+ n : int
+ The size of the signal.
+ m : int, optional
+ The number of output points desired. Default is `n`.
+ w : complex, optional
+ The ratio between points in each step. This must be precise or the
+ accumulated error will degrade the tail of the output sequence.
+ Defaults to equally spaced points around the entire unit circle.
+ a : complex, optional
+ The starting point in the complex plane. Default is 1+0j.
+
+ Returns
+ -------
+ f : CZT
+ Callable object ``f(x, axis=-1)`` for computing the chirp z-transform
+ on `x`.
+
+ See Also
+ --------
+ czt : Convenience function for quickly calculating CZT.
+ ZoomFFT : Class that creates a callable partial FFT function.
+
+ Notes
+ -----
+ The defaults are chosen such that ``f(x)`` is equivalent to
+ ``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, m)`` is equivalent to
+ ``fft.fft(x, m)``.
+
+ If `w` does not lie on the unit circle, then the transform will be
+ around a spiral with exponentially-increasing radius. Regardless,
+ angle will increase linearly.
+
+ For transforms that do lie on the unit circle, accuracy is better when
+ using `ZoomFFT`, since any numerical error in `w` is
+ accumulated for long data lengths, drifting away from the unit circle.
+
+ The chirp z-transform can be faster than an equivalent FFT with
+ zero padding. Try it with your own array sizes to see.
+
+ However, the chirp z-transform is considerably less precise than the
+ equivalent zero-padded FFT.
+
+ As this CZT is implemented using the Bluestein algorithm, it can compute
+ large prime-length Fourier transforms in O(N log N) time, rather than the
+ O(N**2) time required by the direct DFT calculation. (`scipy.fft` also
+ uses Bluestein's algorithm'.)
+
+ (The name "chirp z-transform" comes from the use of a chirp in the
+ Bluestein algorithm. It does not decompose signals into chirps, like
+ other transforms with "chirp" in the name.)
+
+ References
+ ----------
+ .. [1] Leo I. Bluestein, "A linear filtering approach to the computation
+ of the discrete Fourier transform," Northeast Electronics Research
+ and Engineering Meeting Record 10, 218-219 (1968).
+ .. [2] Rabiner, Schafer, and Rader, "The chirp z-transform algorithm and
+ its application," Bell Syst. Tech. J. 48, 1249-1292 (1969).
+
+ Examples
+ --------
+ Compute multiple prime-length FFTs:
+
+ >>> from scipy.signal import CZT
+ >>> import numpy as np
+ >>> a = np.random.rand(7)
+ >>> b = np.random.rand(7)
+ >>> c = np.random.rand(7)
+ >>> czt_7 = CZT(n=7)
+ >>> A = czt_7(a)
+ >>> B = czt_7(b)
+ >>> C = czt_7(c)
+
+ Display the points at which the FFT is calculated:
+
+ >>> czt_7.points()
+ array([ 1.00000000+0.j , 0.62348980+0.78183148j,
+ -0.22252093+0.97492791j, -0.90096887+0.43388374j,
+ -0.90096887-0.43388374j, -0.22252093-0.97492791j,
+ 0.62348980-0.78183148j])
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(czt_7.points().real, czt_7.points().imag, 'o')
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
+ >>> plt.axis('equal')
+ >>> plt.show()
+ """
+
+ def __init__(self, n, m=None, w=None, a=1+0j):
+ m = _validate_sizes(n, m)
+
+ k = arange(max(m, n), dtype=np.min_scalar_type(-max(m, n)**2))
+
+ if w is None:
+ # Nothing specified, default to FFT-like
+ w = cmath.exp(-2j*pi/m)
+ wk2 = np.exp(-(1j * pi * ((k**2) % (2*m))) / m)
+ else:
+ # w specified
+ wk2 = w**(k**2/2.)
+
+ a = 1.0 * a # at least float
+
+ self.w, self.a = w, a
+ self.m, self.n = m, n
+
+ nfft = next_fast_len(n + m - 1)
+ self._Awk2 = a**-k[:n] * wk2[:n]
+ self._nfft = nfft
+ self._Fwk2 = fft(1/np.hstack((wk2[n-1:0:-1], wk2[:m])), nfft)
+ self._wk2 = wk2[:m]
+ self._yidx = slice(n-1, n+m-1)
+
+ def __call__(self, x, *, axis=-1):
+ """
+ Calculate the chirp z-transform of a signal.
+
+ Parameters
+ ----------
+ x : array
+ The signal to transform.
+ axis : int, optional
+ Axis over which to compute the FFT. If not given, the last axis is
+ used.
+
+ Returns
+ -------
+ out : ndarray
+ An array of the same dimensions as `x`, but with the length of the
+ transformed axis set to `m`.
+ """
+ x = np.asarray(x)
+ if x.shape[axis] != self.n:
+ raise ValueError(f"CZT defined for length {self.n}, not "
+ f"{x.shape[axis]}")
+ # Calculate transpose coordinates, to allow operation on any given axis
+ trnsp = np.arange(x.ndim)
+ trnsp[[axis, -1]] = [-1, axis]
+ x = x.transpose(*trnsp)
+ y = ifft(self._Fwk2 * fft(x*self._Awk2, self._nfft))
+ y = y[..., self._yidx] * self._wk2
+ return y.transpose(*trnsp)
+
+ def points(self):
+ """
+ Return the points at which the chirp z-transform is computed.
+ """
+ return czt_points(self.m, self.w, self.a)
+
+
+class ZoomFFT(CZT):
+ """
+ Create a callable zoom FFT transform function.
+
+ This is a specialization of the chirp z-transform (`CZT`) for a set of
+ equally-spaced frequencies around the unit circle, used to calculate a
+ section of the FFT more efficiently than calculating the entire FFT and
+ truncating.
+
+ Parameters
+ ----------
+ n : int
+ The size of the signal.
+ fn : array_like
+ A length-2 sequence [`f1`, `f2`] giving the frequency range, or a
+ scalar, for which the range [0, `fn`] is assumed.
+ m : int, optional
+ The number of points to evaluate. Default is `n`.
+ fs : float, optional
+ The sampling frequency. If ``fs=10`` represented 10 kHz, for example,
+ then `f1` and `f2` would also be given in kHz.
+ The default sampling frequency is 2, so `f1` and `f2` should be
+ in the range [0, 1] to keep the transform below the Nyquist
+ frequency.
+ endpoint : bool, optional
+ If True, `f2` is the last sample. Otherwise, it is not included.
+ Default is False.
+
+ Returns
+ -------
+ f : ZoomFFT
+ Callable object ``f(x, axis=-1)`` for computing the zoom FFT on `x`.
+
+ See Also
+ --------
+ zoom_fft : Convenience function for calculating a zoom FFT.
+
+ Notes
+ -----
+ The defaults are chosen such that ``f(x, 2)`` is equivalent to
+ ``fft.fft(x)`` and, if ``m > len(x)``, that ``f(x, 2, m)`` is equivalent to
+ ``fft.fft(x, m)``.
+
+ Sampling frequency is 1/dt, the time step between samples in the
+ signal `x`. The unit circle corresponds to frequencies from 0 up
+ to the sampling frequency. The default sampling frequency of 2
+ means that `f1`, `f2` values up to the Nyquist frequency are in the
+ range [0, 1). For `f1`, `f2` values expressed in radians, a sampling
+ frequency of 2*pi should be used.
+
+ Remember that a zoom FFT can only interpolate the points of the existing
+ FFT. It cannot help to resolve two separate nearby frequencies.
+ Frequency resolution can only be increased by increasing acquisition
+ time.
+
+ These functions are implemented using Bluestein's algorithm (as is
+ `scipy.fft`). [2]_
+
+ References
+ ----------
+ .. [1] Steve Alan Shilling, "A study of the chirp z-transform and its
+ applications", pg 29 (1970)
+ https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf
+ .. [2] Leo I. Bluestein, "A linear filtering approach to the computation
+ of the discrete Fourier transform," Northeast Electronics Research
+ and Engineering Meeting Record 10, 218-219 (1968).
+
+ Examples
+ --------
+ To plot the transform results use something like the following:
+
+ >>> import numpy as np
+ >>> from scipy.signal import ZoomFFT
+ >>> t = np.linspace(0, 1, 1021)
+ >>> x = np.cos(2*np.pi*15*t) + np.sin(2*np.pi*17*t)
+ >>> f1, f2 = 5, 27
+ >>> transform = ZoomFFT(len(x), [f1, f2], len(x), fs=1021)
+ >>> X = transform(x)
+ >>> f = np.linspace(f1, f2, len(x))
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(f, 20*np.log10(np.abs(X)))
+ >>> plt.show()
+ """
+
+ def __init__(self, n, fn, m=None, *, fs=2, endpoint=False):
+ m = _validate_sizes(n, m)
+
+ k = arange(max(m, n), dtype=np.min_scalar_type(-max(m, n)**2))
+
+ if np.size(fn) == 2:
+ f1, f2 = fn
+ elif np.size(fn) == 1:
+ f1, f2 = 0.0, fn
+ else:
+ raise ValueError('fn must be a scalar or 2-length sequence')
+
+ self.f1, self.f2, self.fs = f1, f2, fs
+
+ if endpoint:
+ scale = ((f2 - f1) * m) / (fs * (m - 1))
+ else:
+ scale = (f2 - f1) / fs
+ a = cmath.exp(2j * pi * f1/fs)
+ wk2 = np.exp(-(1j * pi * scale * k**2) / m)
+
+ self.w = cmath.exp(-2j*pi/m * scale)
+ self.a = a
+ self.m, self.n = m, n
+
+ ak = np.exp(-2j * pi * f1/fs * k[:n])
+ self._Awk2 = ak * wk2[:n]
+
+ nfft = next_fast_len(n + m - 1)
+ self._nfft = nfft
+ self._Fwk2 = fft(1/np.hstack((wk2[n-1:0:-1], wk2[:m])), nfft)
+ self._wk2 = wk2[:m]
+ self._yidx = slice(n-1, n+m-1)
+
+
+def czt(x, m=None, w=None, a=1+0j, *, axis=-1):
+ """
+ Compute the frequency response around a spiral in the Z plane.
+
+ Parameters
+ ----------
+ x : array
+ The signal to transform.
+ m : int, optional
+ The number of output points desired. Default is the length of the
+ input data.
+ w : complex, optional
+ The ratio between points in each step. This must be precise or the
+ accumulated error will degrade the tail of the output sequence.
+ Defaults to equally spaced points around the entire unit circle.
+ a : complex, optional
+ The starting point in the complex plane. Default is 1+0j.
+ axis : int, optional
+ Axis over which to compute the FFT. If not given, the last axis is
+ used.
+
+ Returns
+ -------
+ out : ndarray
+ An array of the same dimensions as `x`, but with the length of the
+ transformed axis set to `m`.
+
+ See Also
+ --------
+ CZT : Class that creates a callable chirp z-transform function.
+ zoom_fft : Convenience function for partial FFT calculations.
+
+ Notes
+ -----
+ The defaults are chosen such that ``signal.czt(x)`` is equivalent to
+ ``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.czt(x, m)`` is
+ equivalent to ``fft.fft(x, m)``.
+
+ If the transform needs to be repeated, use `CZT` to construct a
+ specialized transform function which can be reused without
+ recomputing constants.
+
+ An example application is in system identification, repeatedly evaluating
+ small slices of the z-transform of a system, around where a pole is
+ expected to exist, to refine the estimate of the pole's true location. [1]_
+
+ References
+ ----------
+ .. [1] Steve Alan Shilling, "A study of the chirp z-transform and its
+ applications", pg 20 (1970)
+ https://krex.k-state.edu/dspace/bitstream/handle/2097/7844/LD2668R41972S43.pdf
+
+ Examples
+ --------
+ Generate a sinusoid:
+
+ >>> import numpy as np
+ >>> f1, f2, fs = 8, 10, 200 # Hz
+ >>> t = np.linspace(0, 1, fs, endpoint=False)
+ >>> x = np.sin(2*np.pi*t*f2)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(t, x)
+ >>> plt.axis([0, 1, -1.1, 1.1])
+ >>> plt.show()
+
+ Its discrete Fourier transform has all of its energy in a single frequency
+ bin:
+
+ >>> from scipy.fft import rfft, rfftfreq
+ >>> from scipy.signal import czt, czt_points
+ >>> plt.plot(rfftfreq(fs, 1/fs), abs(rfft(x)))
+ >>> plt.margins(0, 0.1)
+ >>> plt.show()
+
+ However, if the sinusoid is logarithmically-decaying:
+
+ >>> x = np.exp(-t*f1) * np.sin(2*np.pi*t*f2)
+ >>> plt.plot(t, x)
+ >>> plt.axis([0, 1, -1.1, 1.1])
+ >>> plt.show()
+
+ the DFT will have spectral leakage:
+
+ >>> plt.plot(rfftfreq(fs, 1/fs), abs(rfft(x)))
+ >>> plt.margins(0, 0.1)
+ >>> plt.show()
+
+ While the DFT always samples the z-transform around the unit circle, the
+ chirp z-transform allows us to sample the Z-transform along any
+ logarithmic spiral, such as a circle with radius smaller than unity:
+
+ >>> M = fs // 2 # Just positive frequencies, like rfft
+ >>> a = np.exp(-f1/fs) # Starting point of the circle, radius < 1
+ >>> w = np.exp(-1j*np.pi/M) # "Step size" of circle
+ >>> points = czt_points(M + 1, w, a) # M + 1 to include Nyquist
+ >>> plt.plot(points.real, points.imag, '.')
+ >>> plt.gca().add_patch(plt.Circle((0,0), radius=1, fill=False, alpha=.3))
+ >>> plt.axis('equal'); plt.axis([-1.05, 1.05, -0.05, 1.05])
+ >>> plt.show()
+
+ With the correct radius, this transforms the decaying sinusoid (and others
+ with the same decay rate) without spectral leakage:
+
+ >>> z_vals = czt(x, M + 1, w, a) # Include Nyquist for comparison to rfft
+ >>> freqs = np.angle(points)*fs/(2*np.pi) # angle = omega, radius = sigma
+ >>> plt.plot(freqs, abs(z_vals))
+ >>> plt.margins(0, 0.1)
+ >>> plt.show()
+ """
+ x = np.asarray(x)
+ transform = CZT(x.shape[axis], m=m, w=w, a=a)
+ return transform(x, axis=axis)
+
+
+def zoom_fft(x, fn, m=None, *, fs=2, endpoint=False, axis=-1):
+ """
+ Compute the DFT of `x` only for frequencies in range `fn`.
+
+ Parameters
+ ----------
+ x : array
+ The signal to transform.
+ fn : array_like
+ A length-2 sequence [`f1`, `f2`] giving the frequency range, or a
+ scalar, for which the range [0, `fn`] is assumed.
+ m : int, optional
+ The number of points to evaluate. The default is the length of `x`.
+ fs : float, optional
+ The sampling frequency. If ``fs=10`` represented 10 kHz, for example,
+ then `f1` and `f2` would also be given in kHz.
+ The default sampling frequency is 2, so `f1` and `f2` should be
+ in the range [0, 1] to keep the transform below the Nyquist
+ frequency.
+ endpoint : bool, optional
+ If True, `f2` is the last sample. Otherwise, it is not included.
+ Default is False.
+ axis : int, optional
+ Axis over which to compute the FFT. If not given, the last axis is
+ used.
+
+ Returns
+ -------
+ out : ndarray
+ The transformed signal. The Fourier transform will be calculated
+ at the points f1, f1+df, f1+2df, ..., f2, where df=(f2-f1)/m.
+
+ See Also
+ --------
+ ZoomFFT : Class that creates a callable partial FFT function.
+
+ Notes
+ -----
+ The defaults are chosen such that ``signal.zoom_fft(x, 2)`` is equivalent
+ to ``fft.fft(x)`` and, if ``m > len(x)``, that ``signal.zoom_fft(x, 2, m)``
+ is equivalent to ``fft.fft(x, m)``.
+
+ To graph the magnitude of the resulting transform, use::
+
+ plot(linspace(f1, f2, m, endpoint=False), abs(zoom_fft(x, [f1, f2], m)))
+
+ If the transform needs to be repeated, use `ZoomFFT` to construct
+ a specialized transform function which can be reused without
+ recomputing constants.
+
+ Examples
+ --------
+ To plot the transform results use something like the following:
+
+ >>> import numpy as np
+ >>> from scipy.signal import zoom_fft
+ >>> t = np.linspace(0, 1, 1021)
+ >>> x = np.cos(2*np.pi*15*t) + np.sin(2*np.pi*17*t)
+ >>> f1, f2 = 5, 27
+ >>> X = zoom_fft(x, [f1, f2], len(x), fs=1021)
+ >>> f = np.linspace(f1, f2, len(x))
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(f, 20*np.log10(np.abs(X)))
+ >>> plt.show()
+ """
+ x = np.asarray(x)
+ transform = ZoomFFT(x.shape[axis], fn, m=m, fs=fs, endpoint=endpoint)
+ return transform(x, axis=axis)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_delegators.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_delegators.py
new file mode 100644
index 0000000000000000000000000000000000000000..1227602ef042b36427890b6e1a764aea7615d536
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_delegators.py
@@ -0,0 +1,574 @@
+"""Delegators for alternative backends in scipy.signal.
+
+The signature of `func_signature` must match the signature of signal.func.
+The job of a `func_signature` is to know which arguments of `signal.func`
+are arrays.
+
+* signatures are generated by
+
+--------------
+ import inspect
+ from scipy import signal
+
+ names = [x for x in dir(signal) if not x.startswith('_')]
+ objs = [getattr(signal, name) for name in names]
+ funcs = [obj for obj in objs if inspect.isroutine(obj)]
+
+ for func in funcs:
+ try:
+ sig = inspect.signature(func)
+ except ValueError:
+ sig = "( FIXME )"
+ print(f"def {func.__name__}_signature{sig}:\n\treturn array_namespace(...
+ )\n\n")
+---------------
+
+* which arguments to delegate on: manually trawled the documentation for
+ array-like and array arguments
+
+"""
+import numpy as np
+from scipy._lib._array_api import array_namespace, np_compat, is_jax
+
+
+def _skip_if_lti(arg):
+ """Handle `system` arg overloads.
+
+ ATM, only pass tuples through. Consider updating when cupyx.lti class
+ is supported.
+ """
+ if isinstance(arg, tuple):
+ return arg
+ else:
+ return (None,)
+
+
+def _skip_if_str_or_tuple(window):
+ """Handle `window` being a str or a tuple or an array-like.
+ """
+ if isinstance(window, str) or isinstance(window, tuple) or callable(window):
+ return None
+ else:
+ return window
+
+
+def _skip_if_poly1d(arg):
+ return None if isinstance(arg, np.poly1d) else arg
+
+
+###################
+
+def abcd_normalize_signature(A=None, B=None, C=None, D=None):
+ return array_namespace(A, B, C, D)
+
+
+def argrelextrema_signature(data, *args, **kwds):
+ return array_namespace(data)
+
+argrelmax_signature = argrelextrema_signature
+argrelmin_signature = argrelextrema_signature
+
+
+def band_stop_obj_signature(wp, ind, passb, stopb, gpass, gstop, type):
+ return array_namespace(passb, stopb)
+
+
+def bessel_signature(N, Wn, *args, **kwds):
+ return array_namespace(Wn)
+
+butter_signature = bessel_signature
+
+
+def cheby2_signature(N, rs, Wn, *args, **kwds):
+ return array_namespace(Wn)
+
+
+def cheby1_signature(N, rp, Wn, *args, **kwds):
+ return array_namespace(Wn)
+
+
+def ellip_signature(N, rp, rs, Wn, *args, **kwds):
+ return array_namespace(Wn)
+
+
+########################## XXX: no arrays in, arrays out
+def besselap_signature(N, norm='phase', *, xp=None, device=None):
+ return np if xp is None else xp
+
+
+def buttap_signature(N, *, xp=None, device=None):
+ return np if xp is None else xp
+
+
+def cheb1ap_signature(N, rp, *, xp=None, device=None):
+ return np if xp is None else xp
+
+
+def cheb2ap_signature(N, rs, *, xp=None, device=None):
+ return np if xp is None else xp
+
+def ellipap_signature(N, rp, rs, *, xp=None, device=None):
+ return np if xp is None else xp
+
+def correlation_lags_signature(in1_len, in2_len, mode='full'):
+ return np
+
+
+def czt_points_signature(m, w=None, a=(1+0j)):
+ return np
+
+
+def gammatone_signature(
+ freq, ftype, order=None, numtaps=None, fs=None, *, xp=None, device=None
+ ):
+ return np_compat if xp is None else xp
+
+
+def iircomb_signature(
+ w0, Q, ftype='notch', fs=2.0, *, pass_zero=False, xp=None, device=None
+):
+ return np_compat if xp is None else xp
+
+
+def iirnotch_signature(w0, Q, fs=2.0, *, xp=None, device=None):
+ return np if xp is None else xp
+
+iirpeak_signature = iirnotch_signature
+
+
+def savgol_coeffs_signature(
+ window_length, polyorder, deriv=0, delta=1.0, pos=None, use='conv',
+ *, xp=None, device=None
+):
+ return np if xp is None else xp
+
+
+
+def unit_impulse_signature(shape, idx=None, dtype=float):
+ return np
+############################
+
+
+def buttord_signature(wp, ws, gpass, gstop, analog=False, fs=None):
+ return array_namespace(wp, ws)
+
+cheb1ord_signature = buttord_signature
+cheb2ord_signature = buttord_signature
+ellipord_signature = buttord_signature
+
+
+########### NB: scalars in, scalars out
+def kaiser_atten_signature(numtaps, width):
+ return np
+
+def kaiser_beta_signature(a):
+ return np
+
+def kaiserord_signature(ripple, width):
+ return np
+
+def get_window_signature(window, Nx, fftbins=True, *, xp=None, device=None):
+ return np if xp is None else xp
+#################################
+
+
+def bode_signature(system, w=None, n=100):
+ return array_namespace(*_skip_if_lti(system), w)
+
+dbode_signature = bode_signature
+
+
+def freqresp_signature(system, w=None, n=10000):
+ return array_namespace(*_skip_if_lti(system), w)
+
+dfreqresp_signature = freqresp_signature
+
+
+def impulse_signature(system, X0=None, T=None, N=None):
+ return array_namespace(*_skip_if_lti(system), X0, T)
+
+
+def dimpulse_signature(system, x0=None, t=None, n=None):
+ return array_namespace(*_skip_if_lti(system), x0, t)
+
+
+def lsim_signature(system, U, T, X0=None, interp=True):
+ return array_namespace(*_skip_if_lti(system), U, T, X0)
+
+
+def dlsim_signature(system, u, t=None, x0=None):
+ return array_namespace(*_skip_if_lti(system), u, t, x0)
+
+
+def step_signature(system, X0=None, T=None, N=None):
+ return array_namespace(*_skip_if_lti(system), X0, T)
+
+def dstep_signature(system, x0=None, t=None, n=None):
+ return array_namespace(*_skip_if_lti(system), x0, t)
+
+
+def cont2discrete_signature(system, dt, method='zoh', alpha=None):
+ return array_namespace(*_skip_if_lti(system))
+
+
+def bilinear_signature(b, a, fs=1.0):
+ return array_namespace(b, a)
+
+
+def bilinear_zpk_signature(z, p, k, fs):
+ return array_namespace(z, p)
+
+
+def chirp_signature(t,*args, **kwds):
+ return array_namespace(t)
+
+
+############## XXX: array-likes in, str out
+def choose_conv_method_signature(in1, in2, *args, **kwds):
+ return array_namespace(in1, in2)
+############################################
+
+
+def convolve_signature(in1, in2, *args, **kwds):
+ return array_namespace(in1, in2)
+
+fftconvolve_signature = convolve_signature
+oaconvolve_signature = convolve_signature
+correlate_signature = convolve_signature
+correlate_signature = convolve_signature
+convolve2d_signature = convolve_signature
+correlate2d_signature = convolve_signature
+
+
+def coherence_signature(x, y, fs=1.0, window='hann_periodic', *args, **kwds):
+ return array_namespace(x, y, _skip_if_str_or_tuple(window))
+
+
+def csd_signature(x, y, fs=1.0, window='hann_periodic', *args, **kwds):
+ return array_namespace(x, y, _skip_if_str_or_tuple(window))
+
+
+def periodogram_signature(x, fs=1.0, window='boxcar', *args, **kwds):
+ return array_namespace(x, _skip_if_str_or_tuple(window))
+
+
+def welch_signature(x, fs=1.0, window='hann_periodic', *args, **kwds):
+ return array_namespace(x, _skip_if_str_or_tuple(window))
+
+
+def spectrogram_signature(x, fs=1.0, window=('tukey_periodic', 0.25), *args, **kwds):
+ return array_namespace(x, _skip_if_str_or_tuple(window))
+
+
+def stft_signature(x, fs=1.0, window='hann_periodic', *args, **kwds):
+ return array_namespace(x, _skip_if_str_or_tuple(window))
+
+
+def istft_signature(Zxx, fs=1.0, window='hann_periodic', *args, **kwds):
+ return array_namespace(Zxx, _skip_if_str_or_tuple(window))
+
+
+def resample_signature(x, num, t=None, axis=0, window=None, domain='time'):
+ return array_namespace(x, t, _skip_if_str_or_tuple(window))
+
+
+def resample_poly_signature(x, up, down, axis=0, window=('kaiser', 5.0), *args, **kwds):
+ return array_namespace(x, _skip_if_str_or_tuple(window))
+
+
+def check_COLA_signature(window, nperseg, noverlap, tol=1e-10):
+ return array_namespace(_skip_if_str_or_tuple(window))
+
+
+def check_NOLA_signature(window, nperseg, noverlap, tol=1e-10):
+ return array_namespace(_skip_if_str_or_tuple(window))
+
+
+def czt_signature(x, *args, **kwds):
+ return array_namespace(x)
+
+decimate_signature = czt_signature
+gauss_spline_signature = czt_signature
+
+
+def deconvolve_signature(signal, divisor):
+ return array_namespace(signal, divisor)
+
+
+def detrend_signature(data, axis=1, type='linear', bp=0, *args, **kwds):
+ xp = array_namespace(data)
+ # JAX doesn't accept JAX arrays for bp, only ints, lists and NumPy
+ # arrays.
+ return xp if is_jax(xp) else array_namespace(data, bp)
+
+
+def filtfilt_signature(b, a, x, *args, **kwds):
+ return array_namespace(b, a, x)
+
+
+def lfilter_signature(b, a, x, axis=-1, zi=None):
+ return array_namespace(b, a, x, zi)
+
+
+def envelope_signature(z, *args, **kwds):
+ return array_namespace(z)
+
+
+def find_peaks_signature(
+ x, height=None, threshold=None, distance=None, prominence=None, width=None,
+ wlen=None, rel_height=0.5, plateau_size=None
+):
+ # TODO: fix me - `prominence` is not necessarily an array.
+ # return array_namespace(x, height, threshold, prominence, width, plateau_size)
+ # See https://github.com/scipy/scipy/pull/22644#issuecomment-3568443768. For now:
+ return np_compat
+
+def find_peaks_cwt_signature(
+ vector, widths, wavelet=None, max_distances=None, *args, **kwds
+):
+ return array_namespace(vector, widths, max_distances)
+
+
+def findfreqs_signature(num, den, N, kind='ba'):
+ return array_namespace(num, den)
+
+
+def firls_signature(numtaps, bands, desired, *, weight=None, fs=None):
+ return array_namespace(bands, desired, weight)
+
+
+def firwin_signature(numtaps, cutoff, *args, **kwds):
+ if isinstance(cutoff, int | float):
+ xp = np_compat
+ else:
+ xp = array_namespace(cutoff)
+ return xp
+
+
+def firwin2_signature(numtaps, freq, gain, *args, **kwds):
+ return array_namespace(freq, gain)
+
+
+def freqs_zpk_signature(z, p, k, worN=200, *args, **kwds):
+ return array_namespace(z, p, worN)
+
+freqz_zpk_signature = freqs_zpk_signature
+
+
+def freqs_signature(b, a, worN=200, *args, **kwds):
+ return array_namespace(b, a, worN)
+
+
+def freqz_signature(b, a=1, worN=512, *args, **kwds):
+ # differs from freqs: `a` has a default value
+ return array_namespace(b, a, worN)
+
+
+def freqz_sos_signature(sos, worN=512, *args, **kwds):
+ return array_namespace(sos, worN)
+
+sosfreqz_signature = freqz_sos_signature
+
+
+def gausspulse_signature(t, *args, **kwds):
+ arr_t = None if isinstance(t, str) else t
+ return array_namespace(arr_t)
+
+
+def group_delay_signature(system, w=512, whole=False, fs=6.283185307179586):
+ return array_namespace(*system, w)
+
+
+def hilbert_signature(x, *args, **kwds):
+ return array_namespace(x)
+
+hilbert2_signature = hilbert_signature
+
+
+def iirdesign_signature(wp, ws, *args, **kwds):
+ return array_namespace(wp, ws)
+
+
+def iirfilter_signature(N, Wn, *args, **kwds):
+ return array_namespace(Wn)
+
+
+def invres_signature(r, p, k, tol=0.001, rtype='avg'):
+ return array_namespace(r, p, k)
+
+invresz_signature = invres_signature
+
+
+############################### XXX: excluded, blacklisted on CuPy (mismatched API)
+def lfilter_zi_signature(b, a):
+ return array_namespace(b, a)
+
+def sosfilt_zi_signature(sos):
+ return array_namespace(sos)
+
+# needs to be blacklisted on CuPy (is not implemented)
+def remez_signature(numtaps, bands, desired, *, weight=None, **kwds):
+ return array_namespace(bands, desired, weight)
+#############################################
+
+def lfiltic_signature(b, a, y, x=None):
+ return array_namespace(b, a, y, x)
+
+
+def lombscargle_signature(
+ x, y, freqs, precenter=False, normalize=False, *,
+ weights=None, floating_mean=False
+):
+ return array_namespace(x, y, freqs, weights)
+
+
+def lp2bp_signature(b, a, *args, **kwds):
+ return array_namespace(b, a)
+
+lp2bs_signature = lp2bp_signature
+lp2hp_signature = lp2bp_signature
+lp2lp_signature = lp2bp_signature
+
+tf2zpk_signature = lp2bp_signature
+tf2sos_signature = lp2bp_signature
+
+normalize_signature = lp2bp_signature
+residue_signature = lp2bp_signature
+residuez_signature = residue_signature
+
+
+def lp2bp_zpk_signature(z, p, k, *args, **kwds):
+ return array_namespace(z, p)
+
+lp2bs_zpk_signature = lp2bp_zpk_signature
+lp2hp_zpk_signature = lp2bs_zpk_signature
+lp2lp_zpk_signature = lp2bs_zpk_signature
+
+
+def zpk2sos_signature(z, p, k, *args, **kwds):
+ return array_namespace(z, p)
+
+zpk2ss_signature = zpk2sos_signature
+zpk2tf_signature = zpk2sos_signature
+
+
+def max_len_seq_signature(nbits, state=None, length=None, taps=None):
+ return array_namespace(state, taps)
+
+
+def medfilt_signature(volume, kernel_size=None):
+ return array_namespace(volume)
+
+
+def medfilt2d_signature(input, kernel_size=3):
+ return array_namespace(input)
+
+
+def minimum_phase_signature(h, *args, **kwds):
+ return array_namespace(h)
+
+
+def order_filter_signature(a, domain, rank):
+ return array_namespace(a, domain)
+
+
+def peak_prominences_signature(x, peaks, *args, **kwds):
+ return array_namespace(x, peaks)
+
+
+peak_widths_signature = peak_prominences_signature
+
+
+def place_poles_signature(A, B, poles, method='YT', rtol=0.001, maxiter=30):
+ return array_namespace(A, B, poles)
+
+
+def savgol_filter_signature(x, *args, **kwds):
+ return array_namespace(x)
+
+
+def sawtooth_signature(t, width=1):
+ return array_namespace(t)
+
+
+def sepfir2d_signature(input, hrow, hcol):
+ return array_namespace(input, hrow, hcol)
+
+
+def sos2tf_signature(sos):
+ return array_namespace(sos)
+
+
+sos2zpk_signature = sos2tf_signature
+
+
+def sosfilt_signature(sos, x, axis=-1, zi=None):
+ return array_namespace(sos, x, zi)
+
+
+def sosfiltfilt_signature(sos, x, *args, **kwds):
+ return array_namespace(sos, x)
+
+
+def spline_filter_signature(Iin, lmbda=5.0):
+ return array_namespace(Iin)
+
+
+def square_signature(t, duty=0.5):
+ return array_namespace(t)
+
+
+def ss2tf_signature(A, B, C, D, input=0):
+ return array_namespace(A, B, C, D)
+
+ss2zpk_signature = ss2tf_signature
+
+
+def sweep_poly_signature(t, poly, phi=0):
+ return array_namespace(t, _skip_if_poly1d(poly))
+
+
+def symiirorder1_signature(signal, c0, z1, precision=-1.0):
+ return array_namespace(signal)
+
+
+def symiirorder2_signature(input, r, omega, precision=-1.0):
+ return array_namespace(input, r, omega)
+
+
+def cspline1d_signature(signal, *args, **kwds):
+ return array_namespace(signal)
+
+qspline1d_signature = cspline1d_signature
+cspline2d_signature = cspline1d_signature
+qspline2d_signature = qspline1d_signature
+
+
+def cspline1d_eval_signature(cj, newx, *args, **kwds):
+ return array_namespace(cj, newx)
+
+qspline1d_eval_signature = cspline1d_eval_signature
+
+
+def tf2ss_signature(num, den):
+ return array_namespace(num, den)
+
+
+def unique_roots_signature(p, tol=0.001, rtype='min'):
+ return array_namespace(p)
+
+
+def upfirdn_signature(h, x, up=1, down=1, axis=-1, mode='constant', cval=0):
+ return array_namespace(h, x)
+
+
+def vectorstrength_signature(events, period):
+ return array_namespace(events, period)
+
+
+def wiener_signature(im, mysize=None, noise=None):
+ return array_namespace(im)
+
+
+def zoom_fft_signature(x, fn, m=None, *, fs=2, endpoint=False, axis=-1):
+ return array_namespace(x, fn)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..14dc6b7976cd80a2ec619f3dba5daaaf7c2f28e4
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_filter_design.py
@@ -0,0 +1,6101 @@
+"""Filter design."""
+import math
+import cmath
+import operator
+import warnings
+import builtins
+
+from math import pi
+
+import numpy as np
+from numpy.polynomial.polynomial import polyval as npp_polyval
+
+from scipy import special, optimize, fft as sp_fft
+from scipy.special import comb
+from scipy._lib import doccer
+from scipy._lib._util import float_factorial
+from scipy.signal._arraytools import _validate_fs
+from scipy.signal import _polyutils as _pu
+
+import scipy._lib.array_api_extra as xpx
+from scipy._lib._array_api import (
+ array_namespace, xp_promote, xp_size, xp_default_dtype, is_jax, xp_float_to_complex,
+)
+from scipy._lib.array_api_compat import numpy as np_compat
+
+
+__all__ = ['findfreqs', 'freqs', 'freqz', 'tf2zpk', 'zpk2tf', 'normalize',
+ 'lp2lp', 'lp2hp', 'lp2bp', 'lp2bs', 'bilinear', 'iirdesign',
+ 'iirfilter', 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel',
+ 'band_stop_obj', 'buttord', 'cheb1ord', 'cheb2ord', 'ellipord',
+ 'buttap', 'cheb1ap', 'cheb2ap', 'ellipap', 'besselap',
+ 'BadCoefficients', 'freqs_zpk', 'freqz_zpk',
+ 'tf2sos', 'sos2tf', 'zpk2sos', 'sos2zpk', 'group_delay',
+ 'sosfreqz', 'freqz_sos', 'iirnotch', 'iirpeak', 'bilinear_zpk',
+ 'lp2lp_zpk', 'lp2hp_zpk', 'lp2bp_zpk', 'lp2bs_zpk',
+ 'gammatone', 'iircomb']
+
+
+class BadCoefficients(UserWarning):
+ """Warning about badly conditioned filter coefficients"""
+ pass
+
+
+abs = np.absolute
+
+
+def _is_int_type(x):
+ """
+ Check if input is of a scalar integer type (so ``5`` and ``array(5)`` will
+ pass, while ``5.0`` and ``array([5])`` will fail.
+ """
+ if np.ndim(x) != 0:
+ # Older versions of NumPy did not raise for np.array([1]).__index__()
+ # This is safe to remove when support for those versions is dropped
+ return False
+ try:
+ operator.index(x)
+ except TypeError:
+ return False
+ else:
+ return True
+
+
+def _real_dtype_for_complex(dtyp, *, xp):
+ if xp.isdtype(dtyp, 'real floating'):
+ return dtyp
+ if dtyp == xp.complex64:
+ return xp.float32
+ elif dtyp == xp.complex128:
+ return xp.float64
+ else:
+ raise ValueError(f"Unknown dtype {dtyp}.")
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/_core/function_base.py#L195-L302
+def _logspace(start, stop, num=50, endpoint=True, base=10.0, dtype=None, *, xp):
+ if not isinstance(base, float | int) and xp.asarray(base).ndim > 0:
+ # If base is non-scalar, broadcast it with the others, since it
+ # may influence how axis is interpreted.
+ start, stop, base = map(xp.asarray, (start, stop, base))
+ ndmax = xp.broadcast_arrays(start, stop, base).ndim
+ start, stop, base = (
+ xpx.atleast_nd(a, ndim=ndmax)
+ for a in (start, stop, base)
+ )
+ base = xp.expand_dims(base)
+ try:
+ result_dt = xp.result_type(start, stop, base)
+ except ValueError:
+ # all of start, stop and base are python scalars
+ result_dt = xp_default_dtype(xp)
+ y = xp.linspace(start, stop, num=num, endpoint=endpoint, dtype=result_dt)
+
+ yp = xp.pow(base, y)
+ if dtype is None:
+ return yp
+ return xp.astype(yp, dtype, copy=False)
+
+
+def findfreqs(num, den, N, kind='ba'):
+ """
+ Find array of frequencies for computing the response of an analog filter.
+
+ Parameters
+ ----------
+ num, den : array_like, 1-D
+ The polynomial coefficients of the numerator and denominator of the
+ transfer function of the filter or LTI system, where the coefficients
+ are ordered from highest to lowest degree. Or, the roots of the
+ transfer function numerator and denominator (i.e., zeroes and poles).
+ N : int
+ The length of the array to be computed.
+ kind : str {'ba', 'zp'}, optional
+ Specifies whether the numerator and denominator are specified by their
+ polynomial coefficients ('ba'), or their roots ('zp').
+
+ Returns
+ -------
+ w : (N,) ndarray
+ A 1-D array of frequencies, logarithmically spaced.
+
+ Examples
+ --------
+ Find a set of nine frequencies that span the "interesting part" of the
+ frequency response for the filter with the transfer function
+
+ H(s) = s / (s^2 + 8s + 25)
+
+ >>> from scipy import signal
+ >>> signal.findfreqs([1, 0], [1, 8, 25], N=9)
+ array([ 1.00000000e-02, 3.16227766e-02, 1.00000000e-01,
+ 3.16227766e-01, 1.00000000e+00, 3.16227766e+00,
+ 1.00000000e+01, 3.16227766e+01, 1.00000000e+02])
+ """
+ xp = array_namespace(num, den)
+ num, den = map(xp.asarray, (num, den))
+
+ if kind == 'ba':
+ ep = xpx.atleast_nd(_pu.polyroots(den, xp=xp), ndim=1, xp=xp)
+ tz = xpx.atleast_nd(_pu.polyroots(num, xp=xp), ndim=1, xp=xp)
+ elif kind == 'zp':
+ ep = xpx.atleast_nd(den, ndim=1, xp=xp)
+ tz = xpx.atleast_nd(num, ndim=1, xp=xp)
+ else:
+ raise ValueError("input must be one of {'ba', 'zp'}")
+
+ ep = xp_float_to_complex(ep, xp=xp)
+ tz = xp_float_to_complex(tz, xp=xp)
+
+ if ep.shape[0] == 0:
+ ep = xp.asarray([-1000], dtype=ep.dtype)
+
+ ez = xp.concat((
+ ep[xp.imag(ep) >= 0],
+ tz[(xp.abs(tz) < 1e5) & (xp.imag(tz) >= 0)]
+ ))
+
+ integ = xp.astype(xp.abs(ez) < 1e-10, ez.dtype) # XXX True->1, False->0
+ hfreq = xp.round(
+ xp.log10(xp.max(3*xp.abs(xp.real(ez) + integ) + 1.5*xp.imag(ez))) + 0.5
+ )
+
+ # the fudge factor is for backwards compatibility: round(-1.5) can be -1 or -2
+ # depending on the floating-point jitter in -1.5
+ fudge = 1e-14 if is_jax(xp) else 0
+ lfreq = xp.round(
+ xp.log10(0.1*xp.min(xp.abs(xp.real(ez + integ)) + 2*xp.imag(ez))) - 0.5 - fudge
+ )
+
+ w = _logspace(lfreq, hfreq, N, xp=xp)
+ return w
+
+
+def freqs(b, a, worN=200, plot=None):
+ """
+ Compute frequency response of analog filter.
+
+ Given the M-order numerator `b` and N-order denominator `a` of an analog
+ filter, compute its frequency response::
+
+ b[0]*(jw)**M + b[1]*(jw)**(M-1) + ... + b[M]
+ H(w) = ----------------------------------------------
+ a[0]*(jw)**N + a[1]*(jw)**(N-1) + ... + a[N]
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator of a linear filter.
+ a : array_like
+ Denominator of a linear filter.
+ worN : {None, int, array_like}, optional
+ If None, then compute at 200 frequencies around the interesting parts
+ of the response curve (determined by pole-zero locations). If a single
+ integer, then compute at that many frequencies. Otherwise, compute the
+ response at the angular frequencies (e.g., rad/s) given in `worN`.
+ plot : callable, optional
+ A callable that takes two arguments. If given, the return parameters
+ `w` and `h` are passed to plot. Useful for plotting the frequency
+ response inside `freqs`.
+
+ Returns
+ -------
+ w : ndarray
+ The angular frequencies at which `h` was computed.
+ h : ndarray
+ The frequency response.
+
+ See Also
+ --------
+ freqz : Compute the frequency response of a digital filter.
+
+ Notes
+ -----
+ Using Matplotlib's "plot" function as the callable for `plot` produces
+ unexpected results, this plots the real part of the complex transfer
+ function, not the magnitude. Try ``lambda w, h: plot(w, abs(h))``.
+
+ Examples
+ --------
+ >>> from scipy.signal import freqs, iirfilter
+ >>> import numpy as np
+
+ >>> b, a = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1')
+
+ >>> w, h = freqs(b, a, worN=np.logspace(-1, 2, 1000))
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude response [dB]')
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ """
+ xp = array_namespace(b, a, worN)
+
+ if worN is None:
+ # For backwards compatibility
+ w = findfreqs(b, a, 200)
+ elif _is_int_type(worN):
+ w = findfreqs(b, a, worN)
+ else:
+ w = xpx.atleast_nd(xp.asarray(worN), ndim=1, xp=xp)
+
+ s = 1j * w
+ h = _pu.polyval(b, s, xp=xp) / _pu.polyval(a, s, xp=xp)
+ if plot is not None:
+ plot(w, h)
+
+ return w, h
+
+
+def freqs_zpk(z, p, k, worN=200):
+ """
+ Compute frequency response of analog filter.
+
+ Given the zeros `z`, poles `p`, and gain `k` of a filter, compute its
+ frequency response::
+
+ (jw-z[0]) * (jw-z[1]) * ... * (jw-z[-1])
+ H(w) = k * ----------------------------------------
+ (jw-p[0]) * (jw-p[1]) * ... * (jw-p[-1])
+
+ Parameters
+ ----------
+ z : array_like
+ Zeroes of a linear filter
+ p : array_like
+ Poles of a linear filter
+ k : scalar
+ Gain of a linear filter
+ worN : {None, int, array_like}, optional
+ If None, then compute at 200 frequencies around the interesting parts
+ of the response curve (determined by pole-zero locations). If a single
+ integer, then compute at that many frequencies. Otherwise, compute the
+ response at the angular frequencies (e.g., rad/s) given in `worN`.
+
+ Returns
+ -------
+ w : ndarray
+ The angular frequencies at which `h` was computed.
+ h : ndarray
+ The frequency response.
+
+ See Also
+ --------
+ freqs : Compute the frequency response of an analog filter in TF form
+ freqz : Compute the frequency response of a digital filter in TF form
+ freqz_zpk : Compute the frequency response of a digital filter in ZPK form
+
+ Notes
+ -----
+ .. versionadded:: 0.19.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import freqs_zpk, iirfilter
+
+ >>> z, p, k = iirfilter(4, [1, 10], 1, 60, analog=True, ftype='cheby1',
+ ... output='zpk')
+
+ >>> w, h = freqs_zpk(z, p, k, worN=np.logspace(-1, 2, 1000))
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude response [dB]')
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ """
+ xp = array_namespace(z, p)
+ z, p = map(xp.asarray, (z, p))
+
+ # NB: k is documented to be a scalar; for backwards compat we keep allowing it
+ # to be a size-1 array, but it does not influence the namespace calculation.
+ k = xp.asarray(k, dtype=xp_default_dtype(xp))
+ if xp_size(k) > 1:
+ raise ValueError('k must be a single scalar gain')
+
+ if worN is None:
+ # For backwards compatibility
+ w = findfreqs(z, p, 200, kind='zp')
+ elif _is_int_type(worN):
+ w = findfreqs(z, p, worN, kind='zp')
+ else:
+ w = worN
+
+ w = xpx.atleast_nd(xp.asarray(w), ndim=1, xp=xp)
+ s = 1j * w
+ num = _pu.npp_polyvalfromroots(s, z, xp=xp)
+ den = _pu.npp_polyvalfromroots(s, p, xp=xp)
+ h = k * num/den
+ return w, h
+
+
+def freqz(b, a=1, worN=512, whole=False, plot=None, fs=2*pi,
+ include_nyquist=False):
+ """
+ Compute the frequency response of a digital filter.
+
+ Given the M-order numerator `b` and N-order denominator `a` of a digital
+ filter, compute its frequency response::
+
+ jw -jw -jwM
+ jw B(e ) b[0] + b[1]e + ... + b[M]e
+ H(e ) = ------ = -----------------------------------
+ jw -jw -jwN
+ A(e ) a[0] + a[1]e + ... + a[N]e
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator of a linear filter. If `b` has dimension greater than 1,
+ it is assumed that the coefficients are stored in the first dimension,
+ and ``b.shape[1:]``, ``a.shape[1:]``, and the shape of the frequencies
+ array must be compatible for broadcasting.
+ a : array_like
+ Denominator of a linear filter. If `b` has dimension greater than 1,
+ it is assumed that the coefficients are stored in the first dimension,
+ and ``b.shape[1:]``, ``a.shape[1:]``, and the shape of the frequencies
+ array must be compatible for broadcasting.
+ worN : {None, int, array_like}, optional
+ If a single integer, then compute at that many frequencies (default is
+ N=512). This is a convenient alternative to::
+
+ np.linspace(0, fs if whole else fs/2, N, endpoint=include_nyquist)
+
+ Using a number that is fast for FFT computations can result in
+ faster computations (see Notes).
+
+ If an array_like, compute the response at the frequencies given.
+ These are in the same units as `fs`.
+ whole : bool, optional
+ Normally, frequencies are computed from 0 to the Nyquist frequency,
+ fs/2 (upper-half of unit-circle). If `whole` is True, compute
+ frequencies from 0 to fs. Ignored if worN is array_like.
+ plot : callable
+ A callable that takes two arguments. If given, the return parameters
+ `w` and `h` are passed to plot. Useful for plotting the frequency
+ response inside `freqz`.
+ fs : float, optional
+ The sampling frequency of the digital system. Defaults to 2*pi
+ radians/sample (so w is from 0 to pi).
+
+ .. versionadded:: 1.2.0
+ include_nyquist : bool, optional
+ If `whole` is False and `worN` is an integer, setting `include_nyquist`
+ to True will include the last frequency (Nyquist frequency) and is
+ otherwise ignored.
+
+ .. versionadded:: 1.5.0
+
+ Returns
+ -------
+ w : ndarray
+ The frequencies at which `h` was computed, in the same units as `fs`.
+ By default, `w` is normalized to the range [0, pi) (radians/sample).
+ h : ndarray
+ The frequency response, as complex numbers.
+
+ See Also
+ --------
+ freqz_zpk
+ freqz_sos
+
+ Notes
+ -----
+ Using Matplotlib's :func:`matplotlib.pyplot.plot` function as the callable
+ for `plot` produces unexpected results, as this plots the real part of the
+ complex transfer function, not the magnitude.
+ Try ``lambda w, h: plot(w, np.abs(h))``.
+
+ A direct computation via (R)FFT is used to compute the frequency response
+ when the following conditions are met:
+
+ 1. An integer value is given for `worN`.
+ 2. `worN` is fast to compute via FFT (i.e.,
+ `next_fast_len(worN) ` equals `worN`).
+ 3. The denominator coefficients are a single value (``a.shape[0] == 1``).
+ 4. `worN` is at least as long as the numerator coefficients
+ (``worN >= b.shape[0]``).
+ 5. If ``b.ndim > 1``, then ``b.shape[-1] == 1``.
+
+ For long FIR filters, the FFT approach can have lower error and be much
+ faster than the equivalent direct polynomial calculation.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import numpy as np
+ >>> taps, f_c = 80, 1.0 # number of taps and cut-off frequency
+ >>> b = signal.firwin(taps, f_c, window=('kaiser', 8), fs=2*np.pi)
+ >>> w, h = signal.freqz(b)
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, ax1 = plt.subplots(tight_layout=True)
+ >>> ax1.set_title(f"Frequency Response of {taps} tap FIR Filter" +
+ ... f"($f_c={f_c}$ rad/sample)")
+ >>> ax1.axvline(f_c, color='black', linestyle=':', linewidth=0.8)
+ >>> ax1.plot(w, 20 * np.log10(abs(h)), 'C0')
+ >>> ax1.set_ylabel("Amplitude in dB", color='C0')
+ >>> ax1.set(xlabel="Frequency in rad/sample", xlim=(0, np.pi))
+
+ >>> ax2 = ax1.twinx()
+ >>> phase = np.unwrap(np.angle(h))
+ >>> ax2.plot(w, phase, 'C1')
+ >>> ax2.set_ylabel('Phase [rad]', color='C1')
+ >>> ax2.grid(True)
+ >>> ax2.axis('tight')
+ >>> plt.show()
+
+ Broadcasting Examples
+
+ Suppose we have two FIR filters whose coefficients are stored in the
+ rows of an array with shape (2, 25). For this demonstration, we'll
+ use random data:
+
+ >>> rng = np.random.default_rng()
+ >>> b = rng.random((2, 25))
+
+ To compute the frequency response for these two filters with one call
+ to `freqz`, we must pass in ``b.T``, because `freqz` expects the first
+ axis to hold the coefficients. We must then extend the shape with a
+ trivial dimension of length 1 to allow broadcasting with the array
+ of frequencies. That is, we pass in ``b.T[..., np.newaxis]``, which has
+ shape (25, 2, 1):
+
+ >>> w, h = signal.freqz(b.T[..., np.newaxis], worN=1024)
+ >>> w.shape
+ (1024,)
+ >>> h.shape
+ (2, 1024)
+
+ Now, suppose we have two transfer functions, with the same numerator
+ coefficients ``b = [0.5, 0.5]``. The coefficients for the two denominators
+ are stored in the first dimension of the 2-D array `a`::
+
+ a = [ 1 1 ]
+ [ -0.25, -0.5 ]
+
+ >>> b = np.array([0.5, 0.5])
+ >>> a = np.array([[1, 1], [-0.25, -0.5]])
+
+ Only `a` is more than 1-D. To make it compatible for
+ broadcasting with the frequencies, we extend it with a trivial dimension
+ in the call to `freqz`:
+
+ >>> w, h = signal.freqz(b, a[..., np.newaxis], worN=1024)
+ >>> w.shape
+ (1024,)
+ >>> h.shape
+ (2, 1024)
+
+ """
+ xp = array_namespace(b, a)
+
+ b, a = map(xp.asarray, (b, a))
+ if xp.isdtype(a.dtype, 'integral'):
+ a = xp.astype(a, xp_default_dtype(xp))
+ res_dtype = xp.result_type(b, a)
+ real_dtype = _real_dtype_for_complex(res_dtype, xp=xp)
+
+ b = xpx.atleast_nd(b, ndim=1, xp=xp)
+ a = xpx.atleast_nd(a, ndim=1, xp=xp)
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ if worN is None:
+ # For backwards compatibility
+ worN = 512
+
+ h = None
+
+ if _is_int_type(worN):
+ N = operator.index(worN)
+ del worN
+ if N < 0:
+ raise ValueError(f'worN must be nonnegative, got {N}')
+ lastpoint = 2 * pi if whole else pi
+ # if include_nyquist is true and whole is false, w should
+ # include end point
+ w = xp.linspace(0, lastpoint, N,
+ endpoint=include_nyquist and not whole, dtype=real_dtype)
+ n_fft = N if whole else 2 * (N - 1) if include_nyquist else 2 * N
+ if (xp_size(a) == 1 and (b.ndim == 1 or (b.shape[-1] == 1))
+ and n_fft >= b.shape[0]
+ and n_fft > 0): # TODO: review threshold acc. to benchmark?
+
+ if (xp.isdtype(b.dtype, "real floating") and
+ xp.isdtype(a.dtype, "real floating")
+ ):
+ fft_func = sp_fft.rfft
+ else:
+ fft_func = sp_fft.fft
+
+ h = fft_func(b, n=n_fft, axis=0)
+ h = h[:min(N, h.shape[0]), ...]
+ h /= a
+
+ if fft_func is sp_fft.rfft and whole:
+ # exclude DC and maybe Nyquist (no need to use axis_reverse
+ # here because we can build reversal with the truncation)
+ stop = None if n_fft % 2 == 1 else -1
+ h_flipped = xp.flip(h[1:stop, ...], axis=0)
+ h = xp.concat((h, xp.conj(h_flipped)))
+ if b.ndim > 1:
+ # Last axis of h has length 1, so drop it.
+ h = h[..., 0]
+ # Move the first axis of h to the end.
+ h = xp.moveaxis(h, 0, -1)
+ else:
+ if isinstance(worN, complex):
+ # backwards compat
+ worN = worN.real
+ w = xpx.atleast_nd(xp.asarray(worN, dtype=res_dtype), ndim=1, xp=xp)
+ if xp.isdtype(w.dtype, 'integral'):
+ w = xp.astype(w, xp_default_dtype(xp))
+ del worN
+ w = 2 * pi * w / fs
+
+ if h is None: # still need to compute using freqs w
+ zm1 = xp.exp(-1j * w)
+ h = (_pu.npp_polyval(zm1, b, tensor=False, xp=xp) /
+ _pu.npp_polyval(zm1, a, tensor=False, xp=xp))
+
+ w = w * (fs / (2 * pi))
+
+ if plot is not None:
+ plot(w, h)
+
+ return w, h
+
+
+def freqz_zpk(z, p, k, worN=512, whole=False, fs=2*pi):
+ r"""
+ Compute the frequency response of a digital filter in ZPK form.
+
+ Given the Zeros, Poles and Gain of a digital filter, compute its frequency
+ response:
+
+ :math:`H(z)=k \prod_i (z - Z[i]) / \prod_j (z - P[j])`
+
+ where :math:`k` is the `gain`, :math:`Z` are the `zeros` and :math:`P` are
+ the `poles`.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeroes of a linear filter
+ p : array_like
+ Poles of a linear filter
+ k : scalar
+ Gain of a linear filter
+ worN : {None, int, array_like}, optional
+ If a single integer, then compute at that many frequencies (default is
+ N=512).
+
+ If an array_like, compute the response at the frequencies given.
+ These are in the same units as `fs`.
+ whole : bool, optional
+ Normally, frequencies are computed from 0 to the Nyquist frequency,
+ fs/2 (upper-half of unit-circle). If `whole` is True, compute
+ frequencies from 0 to fs. Ignored if w is array_like.
+ fs : float, optional
+ The sampling frequency of the digital system. Defaults to 2*pi
+ radians/sample (so w is from 0 to pi).
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ w : ndarray
+ The frequencies at which `h` was computed, in the same units as `fs`.
+ By default, `w` is normalized to the range [0, pi) (radians/sample).
+ h : ndarray
+ The frequency response, as complex numbers.
+
+ See Also
+ --------
+ freqs : Compute the frequency response of an analog filter in TF form
+ freqs_zpk : Compute the frequency response of an analog filter in ZPK form
+ freqz : Compute the frequency response of a digital filter in TF form
+
+ Notes
+ -----
+ .. versionadded:: 0.19.0
+
+ Examples
+ --------
+ Design a 4th-order digital Butterworth filter with cut-off of 100 Hz in a
+ system with sample rate of 1000 Hz, and plot the frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> z, p, k = signal.butter(4, 100, output='zpk', fs=1000)
+ >>> w, h = signal.freqz_zpk(z, p, k, fs=1000)
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig = plt.figure()
+ >>> ax1 = fig.add_subplot(1, 1, 1)
+ >>> ax1.set_title('Digital filter frequency response')
+
+ >>> ax1.plot(w, 20 * np.log10(abs(h)), 'b')
+ >>> ax1.set_ylabel('Amplitude [dB]', color='b')
+ >>> ax1.set_xlabel('Frequency [Hz]')
+ >>> ax1.grid(True)
+
+ >>> ax2 = ax1.twinx()
+ >>> phase = np.unwrap(np.angle(h))
+ >>> ax2.plot(w, phase, 'g')
+ >>> ax2.set_ylabel('Phase [rad]', color='g')
+
+ >>> plt.axis('tight')
+ >>> plt.show()
+
+ """
+ xp = array_namespace(z, p)
+ z, p = map(xp.asarray, (z, p))
+
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+ res_dtype = xp.result_type(z, p)
+ res_dtype = xp.float64 if res_dtype in (xp.float64, xp.complex128) else xp.float32
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ if whole:
+ lastpoint = 2 * pi
+ else:
+ lastpoint = pi
+
+ if worN is None:
+ # For backwards compatibility
+ w = xp.linspace(0, lastpoint, 512, endpoint=False, dtype=res_dtype)
+ elif _is_int_type(worN):
+ w = xp.linspace(0, lastpoint, worN, endpoint=False, dtype=res_dtype)
+ else:
+ w = xp.asarray(worN)
+ if xp.isdtype(w.dtype, 'integral'):
+ w = xp.astype(w, xp_default_dtype(xp))
+ w = xpx.atleast_nd(w, ndim=1, xp=xp)
+ w = 2 * pi * w / fs
+
+ zm1 = xp.exp(1j * w)
+ func = _pu.npp_polyvalfromroots
+ h = xp.asarray(k, dtype=res_dtype) * func(zm1, z, xp=xp) / func(zm1, p, xp=xp)
+
+ w = w*(fs/(2*pi))
+
+ return w, h
+
+
+def group_delay(system, w=512, whole=False, fs=2*pi):
+ r"""Compute the group delay of a digital filter.
+
+ The group delay measures by how many samples amplitude envelopes of
+ various spectral components of a signal are delayed by a filter.
+ It is formally defined as the derivative of continuous (unwrapped) phase::
+
+ d jw
+ D(w) = - -- arg H(e)
+ dw
+
+ Parameters
+ ----------
+ system : tuple of array_like (b, a)
+ Numerator and denominator coefficients of a filter transfer function.
+ w : {None, int, array_like}, optional
+ If a single integer, then compute at that many frequencies (default is
+ N=512).
+
+ If an array_like, compute the delay at the frequencies given. These
+ are in the same units as `fs`.
+ whole : bool, optional
+ Normally, frequencies are computed from 0 to the Nyquist frequency,
+ fs/2 (upper-half of unit-circle). If `whole` is True, compute
+ frequencies from 0 to fs. Ignored if w is array_like.
+ fs : float, optional
+ The sampling frequency of the digital system. Defaults to 2*pi
+ radians/sample (so w is from 0 to pi).
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ w : ndarray
+ The frequencies at which group delay was computed, in the same units
+ as `fs`. By default, `w` is normalized to the range [0, pi)
+ (radians/sample).
+ gd : ndarray
+ The group delay.
+
+ See Also
+ --------
+ freqz : Frequency response of a digital filter
+
+ Notes
+ -----
+ The similar function in MATLAB is called `grpdelay`.
+
+ If the transfer function :math:`H(z)` has zeros or poles on the unit
+ circle, the group delay at corresponding frequencies is undefined.
+ When such a case arises the warning is raised and the group delay
+ is set to 0 at those frequencies.
+
+ For the details of numerical computation of the group delay refer to [1]_ or [2]_.
+
+ .. versionadded:: 0.16.0
+
+ References
+ ----------
+ .. [1] Richard G. Lyons, "Understanding Digital Signal Processing,
+ 3rd edition", p. 830.
+ .. [2] Julius O. Smith III, "Numerical Computation of Group Delay",
+ in "Introduction to Digital Filters with Audio Applications",
+ online book, 2007,
+ https://ccrma.stanford.edu/~jos/fp/Numerical_Computation_Group_Delay.html
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> b, a = signal.iirdesign(0.1, 0.3, 5, 50, ftype='cheby1')
+ >>> w, gd = signal.group_delay((b, a))
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.title('Digital filter group delay')
+ >>> plt.plot(w, gd)
+ >>> plt.ylabel('Group delay [samples]')
+ >>> plt.xlabel('Frequency [rad/sample]')
+ >>> plt.show()
+
+ """
+ xp = array_namespace(*system, w)
+ b, a = map(np.atleast_1d, system)
+
+ if w is None:
+ # For backwards compatibility
+ w = 512
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ if _is_int_type(w):
+ if whole:
+ w = np.linspace(0, 2 * pi, w, endpoint=False)
+ else:
+ w = np.linspace(0, pi, w, endpoint=False)
+ else:
+ w = np.atleast_1d(w)
+ w = 2*pi*w/fs
+
+ c = np.convolve(b, np.conjugate(a[::-1]))
+ cr = c * np.arange(c.size)
+ z = np.exp(-1j * w)
+ num = np.polyval(cr[::-1], z)
+ den = np.polyval(c[::-1], z)
+ gd = np.real(num / den) - a.size + 1
+ singular = ~np.isfinite(gd)
+ near_singular = np.absolute(den) < 10 * EPSILON
+
+ if np.any(singular):
+ gd[singular] = 0
+ warnings.warn(
+ "The group delay is singular at frequencies "
+ f"[{', '.join(f'{ws:.3f}' for ws in w[singular])}], setting to 0",
+ stacklevel=2
+ )
+
+ elif np.any(near_singular):
+ warnings.warn(
+ "The filter's denominator is extremely small at frequencies "
+ f"[{', '.join(f'{ws:.3f}' for ws in w[near_singular])}], "
+ "around which a singularity may be present",
+ stacklevel=2
+ )
+
+ w = w * (fs / (2 * xp.pi))
+
+ return xp.asarray(w), xp.asarray(gd)
+
+
+def _validate_sos(sos, xp=None):
+ """Helper to validate a SOS input"""
+ if xp is None:
+ xp = np # backcompat, cf sosfilt, sosfiltfilt
+
+ sos = xp.asarray(sos)
+ sos = xpx.atleast_nd(sos, ndim=2, xp=xp)
+ if sos.ndim != 2:
+ raise ValueError('sos array must be 2D')
+ n_sections, m = sos.shape
+ if m != 6:
+ raise ValueError('sos array must be shape (n_sections, 6)')
+ if not xp.all(sos[:, 3] == 1):
+ raise ValueError('sos[:, 3] should be all ones')
+ return sos, n_sections
+
+
+def freqz_sos(sos, worN=512, whole=False, fs=2*pi):
+ r"""
+ Compute the frequency response of a digital filter in SOS format.
+
+ Given `sos`, an array with shape (n, 6) of second order sections of
+ a digital filter, compute the frequency response of the system function::
+
+ B0(z) B1(z) B{n-1}(z)
+ H(z) = ----- * ----- * ... * ---------
+ A0(z) A1(z) A{n-1}(z)
+
+ for z = exp(omega*1j), where B{k}(z) and A{k}(z) are numerator and
+ denominator of the transfer function of the k-th second order section.
+
+ Parameters
+ ----------
+ sos : array_like
+ Array of second-order filter coefficients, must have shape
+ ``(n_sections, 6)``. Each row corresponds to a second-order
+ section, with the first three columns providing the numerator
+ coefficients and the last three providing the denominator
+ coefficients.
+ worN : {None, int, array_like}, optional
+ If a single integer, then compute at that many frequencies (default is
+ N=512). Using a number that is fast for FFT computations can result
+ in faster computations (see Notes of `freqz`).
+
+ If an array_like, compute the response at the frequencies given (must
+ be 1-D). These are in the same units as `fs`.
+ whole : bool, optional
+ Normally, frequencies are computed from 0 to the Nyquist frequency,
+ fs/2 (upper-half of unit-circle). If `whole` is True, compute
+ frequencies from 0 to fs.
+ fs : float, optional
+ The sampling frequency of the digital system. Defaults to 2*pi
+ radians/sample (so w is from 0 to pi).
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ w : ndarray
+ The frequencies at which `h` was computed, in the same units as `fs`.
+ By default, `w` is normalized to the range [0, pi) (radians/sample).
+ h : ndarray
+ The frequency response, as complex numbers.
+
+ See Also
+ --------
+ freqz, sosfilt, sosfreqz
+
+ Notes
+ -----
+ This function used to be called ``sosfreqz`` in older versions (≥ 0.19.0)
+
+ .. versionadded:: 1.15.0
+
+ Examples
+ --------
+ Design a 15th-order bandpass filter in SOS format.
+
+ >>> from scipy import signal
+ >>> import numpy as np
+ >>> sos = signal.ellip(15, 0.5, 60, (0.2, 0.4), btype='bandpass',
+ ... output='sos')
+
+ Compute the frequency response at 1500 points from DC to Nyquist.
+
+ >>> w, h = signal.freqz_sos(sos, worN=1500)
+
+ Plot the response.
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.subplot(2, 1, 1)
+ >>> db = 20*np.log10(np.maximum(np.abs(h), 1e-5))
+ >>> plt.plot(w/np.pi, db)
+ >>> plt.ylim(-75, 5)
+ >>> plt.grid(True)
+ >>> plt.yticks([0, -20, -40, -60])
+ >>> plt.ylabel('Gain [dB]')
+ >>> plt.title('Frequency Response')
+ >>> plt.subplot(2, 1, 2)
+ >>> plt.plot(w/np.pi, np.angle(h))
+ >>> plt.grid(True)
+ >>> plt.yticks([-np.pi, -0.5*np.pi, 0, 0.5*np.pi, np.pi],
+ ... [r'$-\pi$', r'$-\pi/2$', '0', r'$\pi/2$', r'$\pi$'])
+ >>> plt.ylabel('Phase [rad]')
+ >>> plt.xlabel('Normalized frequency (1.0 = Nyquist)')
+ >>> plt.show()
+
+ If the same filter is implemented as a single transfer function,
+ numerical error corrupts the frequency response:
+
+ >>> b, a = signal.ellip(15, 0.5, 60, (0.2, 0.4), btype='bandpass',
+ ... output='ba')
+ >>> w, h = signal.freqz(b, a, worN=1500)
+ >>> plt.subplot(2, 1, 1)
+ >>> db = 20*np.log10(np.maximum(np.abs(h), 1e-5))
+ >>> plt.plot(w/np.pi, db)
+ >>> plt.ylim(-75, 5)
+ >>> plt.grid(True)
+ >>> plt.yticks([0, -20, -40, -60])
+ >>> plt.ylabel('Gain [dB]')
+ >>> plt.title('Frequency Response')
+ >>> plt.subplot(2, 1, 2)
+ >>> plt.plot(w/np.pi, np.angle(h))
+ >>> plt.grid(True)
+ >>> plt.yticks([-np.pi, -0.5*np.pi, 0, 0.5*np.pi, np.pi],
+ ... [r'$-\pi$', r'$-\pi/2$', '0', r'$\pi/2$', r'$\pi$'])
+ >>> plt.ylabel('Phase [rad]')
+ >>> plt.xlabel('Normalized frequency (1.0 = Nyquist)')
+ >>> plt.show()
+
+ """
+ xp = array_namespace(sos)
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ sos, n_sections = _validate_sos(sos, xp)
+ if n_sections == 0:
+ raise ValueError('Cannot compute frequencies with no sections')
+ h = 1.
+ for j in range(sos.shape[0]):
+ row = sos[j, :]
+ w, rowh = freqz(row[:3], row[3:], worN=worN, whole=whole, fs=fs)
+ h *= rowh
+ return w, h
+
+
+def sosfreqz(*args, **kwargs):
+ """
+ Compute the frequency response of a digital filter in SOS format (legacy).
+
+ .. legacy:: function
+
+ This function is an alias, provided for backward compatibility.
+ New code should use the function :func:`scipy.signal.freqz_sos`.
+ This function became obsolete from version 1.15.0.
+
+ """
+ return freqz_sos(*args, **kwargs)
+
+
+def _cplxreal(z, tol=None):
+ """
+ Split into complex and real parts, combining conjugate pairs.
+
+ The 1-D input vector `z` is split up into its complex (`zc`) and real (`zr`)
+ elements. Every complex element must be part of a complex-conjugate pair,
+ which are combined into a single number (with positive imaginary part) in
+ the output. Two complex numbers are considered a conjugate pair if their
+ real and imaginary parts differ in magnitude by less than ``tol * abs(z)``.
+
+ Parameters
+ ----------
+ z : array_like
+ Vector of complex numbers to be sorted and split
+ tol : float, optional
+ Relative tolerance for testing realness and conjugate equality.
+ Default is ``100 * spacing(1)`` of `z`'s data type (i.e., 2e-14 for
+ float64)
+
+ Returns
+ -------
+ zc : ndarray
+ Complex elements of `z`, with each pair represented by a single value
+ having positive imaginary part, sorted first by real part, and then
+ by magnitude of imaginary part. The pairs are averaged when combined
+ to reduce error.
+ zr : ndarray
+ Real elements of `z` (those having imaginary part less than
+ `tol` times their magnitude), sorted by value.
+
+ Raises
+ ------
+ ValueError
+ If there are any complex numbers in `z` for which a conjugate
+ cannot be found.
+
+ See Also
+ --------
+ _cplxpair
+
+ Examples
+ --------
+ >>> from scipy.signal._filter_design import _cplxreal
+ >>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j]
+ >>> zc, zr = _cplxreal(a)
+ >>> print(zc)
+ [ 1.+1.j 2.+1.j 2.+1.j 2.+2.j]
+ >>> print(zr)
+ [ 1. 3. 4.]
+ """
+
+ z = np.atleast_1d(z)
+ if z.size == 0:
+ return z, z
+ elif z.ndim != 1:
+ raise ValueError('_cplxreal only accepts 1-D input')
+
+ if tol is None:
+ # Get tolerance from dtype of input
+ tol = 100 * np.finfo((1.0 * z).dtype).eps
+
+ # Sort by real part, magnitude of imaginary part (speed up further sorting)
+ z = z[np.lexsort((abs(z.imag), z.real))]
+
+ # Split reals from conjugate pairs
+ real_indices = abs(z.imag) <= tol * abs(z)
+ zr = z[real_indices].real
+
+ if len(zr) == len(z):
+ # Input is entirely real
+ return np.array([]), zr
+
+ # Split positive and negative halves of conjugates
+ z = z[~real_indices]
+ zp = z[z.imag > 0]
+ zn = z[z.imag < 0]
+
+ if len(zp) != len(zn):
+ raise ValueError('Array contains complex value with no matching '
+ 'conjugate.')
+
+ # Find runs of (approximately) the same real part
+ same_real = np.diff(zp.real) <= tol * abs(zp[:-1])
+ diffs = np.diff(np.concatenate(([0], same_real, [0])))
+ run_starts = np.nonzero(diffs > 0)[0]
+ run_stops = np.nonzero(diffs < 0)[0]
+
+ # Sort each run by their imaginary parts
+ for i in range(len(run_starts)):
+ start = run_starts[i]
+ stop = run_stops[i] + 1
+ for chunk in (zp[start:stop], zn[start:stop]):
+ chunk[...] = chunk[np.lexsort([abs(chunk.imag)])]
+
+ # Check that negatives match positives
+ if any(abs(zp - zn.conj()) > tol * abs(zn)):
+ raise ValueError('Array contains complex value with no matching '
+ 'conjugate.')
+
+ # Average out numerical inaccuracy in real vs imag parts of pairs
+ zc = (zp + zn.conj()) / 2
+
+ return zc, zr
+
+
+def _cplxpair(z, tol=None):
+ """
+ Sort into pairs of complex conjugates.
+
+ Complex conjugates in `z` are sorted by increasing real part. In each
+ pair, the number with negative imaginary part appears first.
+
+ If pairs have identical real parts, they are sorted by increasing
+ imaginary magnitude.
+
+ Two complex numbers are considered a conjugate pair if their real and
+ imaginary parts differ in magnitude by less than ``tol * abs(z)``. The
+ pairs are forced to be exact complex conjugates by averaging the positive
+ and negative values.
+
+ Purely real numbers are also sorted, but placed after the complex
+ conjugate pairs. A number is considered real if its imaginary part is
+ smaller than `tol` times the magnitude of the number.
+
+ Parameters
+ ----------
+ z : array_like
+ 1-D input array to be sorted.
+ tol : float, optional
+ Relative tolerance for testing realness and conjugate equality.
+ Default is ``100 * spacing(1)`` of `z`'s data type (i.e., 2e-14 for
+ float64)
+
+ Returns
+ -------
+ y : ndarray
+ Complex conjugate pairs followed by real numbers.
+
+ Raises
+ ------
+ ValueError
+ If there are any complex numbers in `z` for which a conjugate
+ cannot be found.
+
+ See Also
+ --------
+ _cplxreal
+
+ Examples
+ --------
+ >>> from scipy.signal._filter_design import _cplxpair
+ >>> a = [4, 3, 1, 2-2j, 2+2j, 2-1j, 2+1j, 2-1j, 2+1j, 1+1j, 1-1j]
+ >>> z = _cplxpair(a)
+ >>> print(z)
+ [ 1.-1.j 1.+1.j 2.-1.j 2.+1.j 2.-1.j 2.+1.j 2.-2.j 2.+2.j 1.+0.j
+ 3.+0.j 4.+0.j]
+ """
+
+ z = np.atleast_1d(z)
+ if z.size == 0 or np.isrealobj(z):
+ return np.sort(z)
+
+ if z.ndim != 1:
+ raise ValueError('z must be 1-D')
+
+ zc, zr = _cplxreal(z, tol)
+
+ # Interleave complex values and their conjugates, with negative imaginary
+ # parts first in each pair
+ zc = np.dstack((zc.conj(), zc)).flatten()
+ z = np.append(zc, zr)
+ return z
+
+
+def tf2zpk(b, a):
+ r"""Return zero, pole, gain (z, p, k) representation from a numerator,
+ denominator representation of a linear filter.
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator polynomial coefficients.
+ a : array_like
+ Denominator polynomial coefficients.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transfer function.
+ p : ndarray
+ Poles of the transfer function.
+ k : float
+ System gain.
+
+ Notes
+ -----
+ If some values of `b` are too close to 0, they are removed. In that case,
+ a BadCoefficients warning is emitted.
+
+ The `b` and `a` arrays are interpreted as coefficients for positive,
+ descending powers of the transfer function variable. So the inputs
+ :math:`b = [b_0, b_1, ..., b_M]` and :math:`a =[a_0, a_1, ..., a_N]`
+ can represent an analog filter of the form:
+
+ .. math::
+
+ H(s) = \frac
+ {b_0 s^M + b_1 s^{(M-1)} + \cdots + b_M}
+ {a_0 s^N + a_1 s^{(N-1)} + \cdots + a_N}
+
+ or a discrete-time filter of the form:
+
+ .. math::
+
+ H(z) = \frac
+ {b_0 z^M + b_1 z^{(M-1)} + \cdots + b_M}
+ {a_0 z^N + a_1 z^{(N-1)} + \cdots + a_N}
+
+ This "positive powers" form is found more commonly in controls
+ engineering. If `M` and `N` are equal (which is true for all filters
+ generated by the bilinear transform), then this happens to be equivalent
+ to the "negative powers" discrete-time form preferred in DSP:
+
+ .. math::
+
+ H(z) = \frac
+ {b_0 + b_1 z^{-1} + \cdots + b_M z^{-M}}
+ {a_0 + a_1 z^{-1} + \cdots + a_N z^{-N}}
+
+ Although this is true for common filters, remember that this is not true
+ in the general case. If `M` and `N` are not equal, the discrete-time
+ transfer function coefficients must first be converted to the "positive
+ powers" form before finding the poles and zeros.
+
+ Examples
+ --------
+ Find the zeroes, poles and gain of
+ a filter with the transfer function
+
+ .. math::
+
+ H(s) = \frac{3s^2}{s^2 + 5s + 13}
+
+ >>> from scipy.signal import tf2zpk
+ >>> tf2zpk([3, 0, 0], [1, 5, 13])
+ ( array([ 0. , 0. ]),
+ array([ -2.5+2.59807621j , -2.5-2.59807621j]),
+ 3.0)
+ """
+ xp = array_namespace(b, a)
+ b, a = normalize(b, a)
+
+ a, b = xp_promote(a, b, xp=xp, force_floating=True)
+
+ k = b[0]
+ b = b / b[0]
+ z = _pu.polyroots(b, xp=xp)
+ p = _pu.polyroots(a, xp=xp)
+ return z, p, k
+
+
+def zpk2tf(z, p, k):
+ r"""
+ Return polynomial transfer function representation from zeros and poles
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the transfer function.
+ p : array_like
+ Poles of the transfer function.
+ k : float
+ System gain.
+
+ Returns
+ -------
+ b : ndarray
+ Numerator polynomial coefficients.
+ a : ndarray
+ Denominator polynomial coefficients.
+
+ Examples
+ --------
+ Find the polynomial representation of a transfer function H(s)
+ using its 'zpk' (Zero-Pole-Gain) representation.
+
+ .. math::
+
+ H(z) = 5 \frac
+ { (s - 2)(s - 6) }
+ { (s - 1)(s - 8) }
+
+ >>> from scipy.signal import zpk2tf
+ >>> z = [2, 6]
+ >>> p = [1, 8]
+ >>> k = 5
+ >>> zpk2tf(z, p, k)
+ ( array([ 5., -40., 60.]), array([ 1., -9., 8.]))
+ """
+ xp = array_namespace(z, p)
+ z, p = map(xp.asarray, (z, p))
+ k = xp.asarray(k, dtype=xp.result_type(xp.real(z), xp.real(p), k))
+ if xp.isdtype(k.dtype, "integral"):
+ k = xp.astype(k, xp.float64)
+
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ k = xpx.atleast_nd(k, ndim=1, xp=xp)
+
+ if z.ndim > 1:
+ temp = _pu.poly(z[0, ...], xp=xp)
+ b = xp.empty((z.shape[0], z.shape[1] + 1), dtype=temp.dtype)
+ if k.shape[0] == 1:
+ k = [k[0]] * z.shape[0]
+ for i in range(z.shape[0]):
+ k_i = xp.asarray(k[i], dtype=b.dtype)
+ b_i = k_i * _pu.poly(z[i, ...], xp=xp)
+ b = xpx.at(b)[i, ...].set(b_i)
+ else:
+ # Use xp.multiply to work around torch type promotion
+ # non-compliance for operations between 0d and higher
+ # dimensional arrays.
+ b = xp.multiply(k, _pu.poly(z, xp=xp))
+
+ a = _pu.poly(p, xp=xp)
+ a = xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp)
+
+ return b, a
+
+
+def tf2sos(b, a, pairing=None, *, analog=False):
+ r"""
+ Return second-order sections from transfer function representation
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator polynomial coefficients.
+ a : array_like
+ Denominator polynomial coefficients.
+ pairing : {None, 'nearest', 'keep_odd', 'minimal'}, optional
+ The method to use to combine pairs of poles and zeros into sections.
+ See `zpk2sos` for information and restrictions on `pairing` and
+ `analog` arguments.
+ analog : bool, optional
+ If True, system is analog, otherwise discrete.
+
+ .. versionadded:: 1.8.0
+
+ Returns
+ -------
+ sos : ndarray
+ Array of second-order filter coefficients, with shape
+ ``(n_sections, 6)``. See `sosfilt` for the SOS filter format
+ specification.
+
+ See Also
+ --------
+ zpk2sos, sosfilt
+
+ Notes
+ -----
+ It is generally discouraged to convert from TF to SOS format, since doing
+ so usually will not improve numerical precision errors. Instead, consider
+ designing filters in ZPK format and converting directly to SOS. TF is
+ converted to SOS by first converting to ZPK format, then converting
+ ZPK to SOS.
+
+ .. versionadded:: 0.16.0
+
+ Examples
+ --------
+ Find the 'sos' (second-order sections) of the transfer function H(s)
+ using its polynomial representation.
+
+ .. math::
+
+ H(s) = \frac{s^2 - 3.5s - 2}{s^4 + 3s^3 - 15s^2 - 19s + 30}
+
+ >>> from scipy.signal import tf2sos
+ >>> tf2sos([1, -3.5, -2], [1, 3, -15, -19, 30], analog=True)
+ array([[ 0. , 0. , 1. , 1. , 2. , -15. ],
+ [ 1. , -3.5, -2. , 1. , 1. , -2. ]])
+ """
+ return zpk2sos(*tf2zpk(b, a), pairing=pairing, analog=analog)
+
+
+def sos2tf(sos):
+ r"""
+ Return a single transfer function from a series of second-order sections
+
+ Parameters
+ ----------
+ sos : array_like
+ Array of second-order filter coefficients, must have shape
+ ``(n_sections, 6)``. See `sosfilt` for the SOS filter format
+ specification.
+
+ Returns
+ -------
+ b : ndarray
+ Numerator polynomial coefficients.
+ a : ndarray
+ Denominator polynomial coefficients.
+
+ Notes
+ -----
+ .. versionadded:: 0.16.0
+
+ Examples
+ --------
+ Find the polynomial representation of an elliptic filter
+ using its 'sos' (second-order sections) format.
+
+ >>> from scipy.signal import sos2tf
+ >>> from scipy import signal
+ >>> sos = signal.ellip(1, 0.001, 50, 0.1, output='sos')
+ >>> sos2tf(sos)
+ ( array([0.91256522, 0.91256522, 0. ]),
+ array([1. , 0.82513043, 0. ]))
+ """
+ xp = array_namespace(sos)
+ sos = xp.asarray(sos)
+
+ result_type = sos.dtype
+ if xp.isdtype(result_type, 'integral'):
+ result_type = xp_default_dtype(xp)
+
+ b = xp.asarray([1], dtype=result_type)
+ a = xp.asarray([1], dtype=result_type)
+
+ n_sections = sos.shape[0]
+ for section in range(n_sections):
+ b = _pu.polymul(b, sos[section, :3], xp=xp)
+ a = _pu.polymul(a, sos[section, 3:], xp=xp)
+ return b, a
+
+
+def sos2zpk(sos):
+ """
+ Return zeros, poles, and gain of a series of second-order sections
+
+ Parameters
+ ----------
+ sos : array_like
+ Array of second-order filter coefficients, must have shape
+ ``(n_sections, 6)``. See `sosfilt` for the SOS filter format
+ specification.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transfer function.
+ p : ndarray
+ Poles of the transfer function.
+ k : float
+ System gain.
+
+ Notes
+ -----
+ The number of zeros and poles returned will be ``n_sections * 2``
+ even if some of these are (effectively) zero.
+
+ .. versionadded:: 0.16.0
+ """
+ xp = array_namespace(sos)
+ sos = xp.asarray(sos)
+
+ n_sections = sos.shape[0]
+ z = xp.zeros(n_sections*2, dtype=xp.complex128)
+ p = xp.zeros(n_sections*2, dtype=xp.complex128)
+ k = 1.
+ for section in range(n_sections):
+ zpk = tf2zpk(sos[section, :3], sos[section, 3:])
+ z = xpx.at(z, slice(2*section, 2*section + zpk[0].shape[0])).set(zpk[0])
+ p = xpx.at(p, slice(2*section, 2*section + zpk[1].shape[0])).set(zpk[1])
+ k *= zpk[2]
+ return z, p, k
+
+
+def _nearest_real_complex_idx(fro, to, which):
+ """Get the next closest real or complex element based on distance"""
+ assert which in ('real', 'complex', 'any')
+ order = np.argsort(np.abs(fro - to))
+ if which == 'any':
+ return order[0]
+ else:
+ mask = np.isreal(fro[order])
+ if which == 'complex':
+ mask = ~mask
+ return order[np.nonzero(mask)[0][0]]
+
+
+def _single_zpksos(z, p, k):
+ """Create one second-order section from up to two zeros and poles"""
+ sos = np.zeros(6)
+ b, a = zpk2tf(z, p, k)
+ sos[3-len(b):3] = b
+ sos[6-len(a):6] = a
+ return sos
+
+
+def zpk2sos(z, p, k, pairing=None, *, analog=False):
+ """Return second-order sections from zeros, poles, and gain of a system
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the transfer function.
+ p : array_like
+ Poles of the transfer function.
+ k : float
+ System gain.
+ pairing : {None, 'nearest', 'keep_odd', 'minimal'}, optional
+ The method to use to combine pairs of poles and zeros into sections.
+ If analog is False and pairing is None, pairing is set to 'nearest';
+ if analog is True, pairing must be 'minimal', and is set to that if
+ it is None.
+ analog : bool, optional
+ If True, system is analog, otherwise discrete.
+
+ .. versionadded:: 1.8.0
+
+ Returns
+ -------
+ sos : ndarray
+ Array of second-order filter coefficients, with shape
+ ``(n_sections, 6)``. See `sosfilt` for the SOS filter format
+ specification.
+
+ See Also
+ --------
+ sosfilt
+
+ Notes
+ -----
+ The algorithm used to convert ZPK to SOS format is designed to
+ minimize errors due to numerical precision issues. The pairing
+ algorithm attempts to minimize the peak gain of each biquadratic
+ section. This is done by pairing poles with the nearest zeros, starting
+ with the poles closest to the unit circle for discrete-time systems, and
+ poles closest to the imaginary axis for continuous-time systems.
+
+ ``pairing='minimal'`` outputs may not be suitable for `sosfilt`,
+ and ``analog=True`` outputs will never be suitable for `sosfilt`.
+
+ *Algorithms*
+
+ The steps in the ``pairing='nearest'``, ``pairing='keep_odd'``,
+ and ``pairing='minimal'`` algorithms are mostly shared. The
+ ``'nearest'`` algorithm attempts to minimize the peak gain, while
+ ``'keep_odd'`` minimizes peak gain under the constraint that
+ odd-order systems should retain one section as first order.
+ ``'minimal'`` is similar to ``'keep_odd'``, but no additional
+ poles or zeros are introduced
+
+ The algorithm steps are as follows:
+
+ As a pre-processing step for ``pairing='nearest'``,
+ ``pairing='keep_odd'``, add poles or zeros to the origin as
+ necessary to obtain the same number of poles and zeros for
+ pairing. If ``pairing == 'nearest'`` and there are an odd number
+ of poles, add an additional pole and a zero at the origin.
+
+ The following steps are then iterated over until no more poles or
+ zeros remain:
+
+ 1. Take the (next remaining) pole (complex or real) closest to the
+ unit circle (or imaginary axis, for ``analog=True``) to
+ begin a new filter section.
+
+ 2. If the pole is real and there are no other remaining real poles [#]_,
+ add the closest real zero to the section and leave it as a first
+ order section. Note that after this step we are guaranteed to be
+ left with an even number of real poles, complex poles, real zeros,
+ and complex zeros for subsequent pairing iterations.
+
+ 3. Else:
+
+ 1. If the pole is complex and the zero is the only remaining real
+ zero*, then pair the pole with the *next* closest zero
+ (guaranteed to be complex). This is necessary to ensure that
+ there will be a real zero remaining to eventually create a
+ first-order section (thus keeping the odd order).
+
+ 2. Else pair the pole with the closest remaining zero (complex or
+ real).
+
+ 3. Proceed to complete the second-order section by adding another
+ pole and zero to the current pole and zero in the section:
+
+ 1. If the current pole and zero are both complex, add their
+ conjugates.
+
+ 2. Else if the pole is complex and the zero is real, add the
+ conjugate pole and the next closest real zero.
+
+ 3. Else if the pole is real and the zero is complex, add the
+ conjugate zero and the real pole closest to those zeros.
+
+ 4. Else (we must have a real pole and real zero) add the next
+ real pole closest to the unit circle, and then add the real
+ zero closest to that pole.
+
+ .. [#] This conditional can only be met for specific odd-order inputs
+ with the ``pairing = 'keep_odd'`` or ``'minimal'`` methods.
+
+ .. versionadded:: 0.16.0
+
+ Examples
+ --------
+
+ Design a 6th order low-pass elliptic digital filter for a system with a
+ sampling rate of 8000 Hz that has a pass-band corner frequency of
+ 1000 Hz. The ripple in the pass-band should not exceed 0.087 dB, and
+ the attenuation in the stop-band should be at least 90 dB.
+
+ In the following call to `ellip`, we could use ``output='sos'``,
+ but for this example, we'll use ``output='zpk'``, and then convert
+ to SOS format with `zpk2sos`:
+
+ >>> from scipy import signal
+ >>> import numpy as np
+ >>> z, p, k = signal.ellip(6, 0.087, 90, 1000/(0.5*8000), output='zpk')
+
+ Now convert to SOS format.
+
+ >>> sos = signal.zpk2sos(z, p, k)
+
+ The coefficients of the numerators of the sections:
+
+ >>> sos[:, :3]
+ array([[0.0014152 , 0.00248677, 0.0014152 ],
+ [1. , 0.72976874, 1. ],
+ [1. , 0.17607852, 1. ]])
+
+ The symmetry in the coefficients occurs because all the zeros are on the
+ unit circle.
+
+ The coefficients of the denominators of the sections:
+
+ >>> sos[:, 3:]
+ array([[ 1. , -1.32544025, 0.46989976],
+ [ 1. , -1.26118294, 0.62625924],
+ [ 1. , -1.2570723 , 0.8619958 ]])
+
+ The next example shows the effect of the `pairing` option. We have a
+ system with three poles and three zeros, so the SOS array will have
+ shape (2, 6). The means there is, in effect, an extra pole and an extra
+ zero at the origin in the SOS representation.
+
+ >>> z1 = np.array([-1, -0.5-0.5j, -0.5+0.5j])
+ >>> p1 = np.array([0.75, 0.8+0.1j, 0.8-0.1j])
+
+ With ``pairing='nearest'`` (the default), we obtain
+
+ >>> signal.zpk2sos(z1, p1, 1)
+ array([[ 1. , 1. , 0.5 , 1. , -0.75, 0. ],
+ [ 1. , 1. , 0. , 1. , -1.6 , 0.65]])
+
+ The first section has the zeros {-0.5-0.05j, -0.5+0.5j} and the poles
+ {0, 0.75}, and the second section has the zeros {-1, 0} and poles
+ {0.8+0.1j, 0.8-0.1j}. Note that the extra pole and zero at the origin
+ have been assigned to different sections.
+
+ With ``pairing='keep_odd'``, we obtain:
+
+ >>> signal.zpk2sos(z1, p1, 1, pairing='keep_odd')
+ array([[ 1. , 1. , 0. , 1. , -0.75, 0. ],
+ [ 1. , 1. , 0.5 , 1. , -1.6 , 0.65]])
+
+ The extra pole and zero at the origin are in the same section.
+ The first section is, in effect, a first-order section.
+
+ With ``pairing='minimal'``, the first-order section doesn't have
+ the extra pole and zero at the origin:
+
+ >>> signal.zpk2sos(z1, p1, 1, pairing='minimal')
+ array([[ 0. , 1. , 1. , 0. , 1. , -0.75],
+ [ 1. , 1. , 0.5 , 1. , -1.6 , 0.65]])
+
+ """
+ # TODO in the near future:
+ # 1. Add SOS capability to `filtfilt`, `freqz`, etc. somehow (#3259).
+ # 2. Make `decimate` use `sosfilt` instead of `lfilter`.
+ # 3. Make sosfilt automatically simplify sections to first order
+ # when possible. Note this might make `sosfiltfilt` a bit harder (ICs).
+ # 4. Further optimizations of the section ordering / pole-zero pairing.
+ # See the wiki for other potential issues.
+
+ xp = array_namespace(z, p)
+
+ # convert to numpy, convert back on exit XXX
+ z, p = map(np.asarray, (z, p))
+ k = np.asarray(k)
+
+ if pairing is None:
+ pairing = 'minimal' if analog else 'nearest'
+
+ valid_pairings = ['nearest', 'keep_odd', 'minimal']
+ if pairing not in valid_pairings:
+ raise ValueError(f'pairing must be one of {valid_pairings}, not {pairing}')
+
+ if analog and pairing != 'minimal':
+ raise ValueError('for analog zpk2sos conversion, '
+ 'pairing must be "minimal"')
+
+ if len(z) == len(p) == 0:
+ if not analog:
+ return xp.asarray(np.asarray([[k, 0., 0., 1., 0., 0.]]))
+ else:
+ return xp.asarray(np.asarray([[0., 0., k, 0., 0., 1.]]))
+
+ if pairing != 'minimal':
+ # ensure we have the same number of poles and zeros, and make copies
+ p = np.concatenate((p, np.zeros(max(len(z) - len(p), 0))))
+ z = np.concatenate((z, np.zeros(max(len(p) - len(z), 0))))
+ n_sections = (max(len(p), len(z)) + 1) // 2
+
+ if len(p) % 2 == 1 and pairing == 'nearest':
+ p = np.concatenate((p, [0.]))
+ z = np.concatenate((z, [0.]))
+ assert len(p) == len(z)
+ else:
+ if len(p) < len(z):
+ raise ValueError('for analog zpk2sos conversion, '
+ 'must have len(p)>=len(z)')
+
+ n_sections = (len(p) + 1) // 2
+
+ # Ensure we have complex conjugate pairs
+ # (note that _cplxreal only gives us one element of each complex pair):
+ z = np.concatenate(_cplxreal(z))
+ p = np.concatenate(_cplxreal(p))
+ if not np.isreal(k):
+ raise ValueError('k must be real')
+ k = k.real
+
+ if not analog:
+ # digital: "worst" is the closest to the unit circle
+ def idx_worst(p):
+ return np.argmin(np.abs(1 - np.abs(p)))
+ else:
+ # analog: "worst" is the closest to the imaginary axis
+ def idx_worst(p):
+ return np.argmin(np.abs(np.real(p)))
+
+ sos = np.zeros((n_sections, 6))
+
+ # Construct the system, reversing order so the "worst" are last
+ for si in range(n_sections-1, -1, -1):
+ # Select the next "worst" pole
+ p1_idx = idx_worst(p)
+ p1 = p[p1_idx]
+ p = np.delete(p, p1_idx)
+
+ # Pair that pole with a zero
+
+ if np.isreal(p1) and np.isreal(p).sum() == 0:
+ # Special case (1): last remaining real pole
+ if pairing != 'minimal':
+ z1_idx = _nearest_real_complex_idx(z, p1, 'real')
+ z1 = z[z1_idx]
+ z = np.delete(z, z1_idx)
+ sos[si] = _single_zpksos([z1, 0], [p1, 0], 1)
+ elif len(z) > 0:
+ z1_idx = _nearest_real_complex_idx(z, p1, 'real')
+ z1 = z[z1_idx]
+ z = np.delete(z, z1_idx)
+ sos[si] = _single_zpksos([z1], [p1], 1)
+ else:
+ sos[si] = _single_zpksos([], [p1], 1)
+
+ elif (len(p) + 1 == len(z)
+ and not np.isreal(p1)
+ and np.isreal(p).sum() == 1
+ and np.isreal(z).sum() == 1):
+
+ # Special case (2): there's one real pole and one real zero
+ # left, and an equal number of poles and zeros to pair up.
+ # We *must* pair with a complex zero
+
+ z1_idx = _nearest_real_complex_idx(z, p1, 'complex')
+ z1 = z[z1_idx]
+ z = np.delete(z, z1_idx)
+ sos[si] = _single_zpksos([z1, z1.conj()], [p1, p1.conj()], 1)
+
+ else:
+ if np.isreal(p1):
+ prealidx = np.flatnonzero(np.isreal(p))
+ p2_idx = prealidx[idx_worst(p[prealidx])]
+ p2 = p[p2_idx]
+ p = np.delete(p, p2_idx)
+ else:
+ p2 = p1.conj()
+
+ # find closest zero
+ if len(z) > 0:
+ z1_idx = _nearest_real_complex_idx(z, p1, 'any')
+ z1 = z[z1_idx]
+ z = np.delete(z, z1_idx)
+
+ if not np.isreal(z1):
+ sos[si] = _single_zpksos([z1, z1.conj()], [p1, p2], 1)
+ else:
+ if len(z) > 0:
+ z2_idx = _nearest_real_complex_idx(z, p1, 'real')
+ z2 = z[z2_idx]
+ assert np.isreal(z2)
+ z = np.delete(z, z2_idx)
+ sos[si] = _single_zpksos([z1, z2], [p1, p2], 1)
+ else:
+ sos[si] = _single_zpksos([z1], [p1, p2], 1)
+ else:
+ # no more zeros
+ sos[si] = _single_zpksos([], [p1, p2], 1)
+
+ assert len(p) == len(z) == 0 # we've consumed all poles and zeros
+ del p, z
+
+ # put gain in first sos
+ sos[0][:3] *= k
+ return xp.asarray(sos)
+
+
+def _align_nums(nums, xp):
+ """Aligns the shapes of multiple numerators.
+
+ Given an array of numerator coefficient arrays [[a_1, a_2,...,
+ a_n],..., [b_1, b_2,..., b_m]], this function pads shorter numerator
+ arrays with zero's so that all numerators have the same length. Such
+ alignment is necessary for functions like 'tf2ss', which needs the
+ alignment when dealing with SIMO transfer functions.
+
+ Parameters
+ ----------
+ nums: array_like
+ Numerator or list of numerators. Not necessarily with same length.
+
+ Returns
+ -------
+ nums: array
+ The numerator. If `nums` input was a list of numerators then a 2-D
+ array with padded zeros for shorter numerators is returned. Otherwise
+ returns ``np.asarray(nums)``.
+ """
+ try:
+ # The statement can throw a ValueError if one
+ # of the numerators is a single digit and another
+ # is array-like e.g. if nums = [5, [1, 2, 3]]
+ nums = xp.asarray(nums)
+
+ if not xp.isdtype(nums.dtype, "numeric"):
+ raise ValueError("dtype of numerator is non-numeric")
+
+ return nums
+
+ except ValueError:
+ nums = [xpx.atleast_nd(xp.asarray(num), ndim=1) for num in nums]
+ max_width = max(xp_size(num) for num in nums)
+
+ # pre-allocate
+ aligned_nums = xp.zeros((len(nums), max_width))
+
+ # Create numerators with padded zeros
+ for index, num in enumerate(nums):
+ aligned_nums[index, -num.size:] = num
+
+ return aligned_nums
+
+
+def normalize(b, a):
+ """Normalize numerator/denominator of a continuous-time transfer function.
+
+ If values of `b` are too close to 0, they are removed. In that case, a
+ BadCoefficients warning is emitted.
+
+ Parameters
+ ----------
+ b: array_like
+ Numerator of the transfer function. Can be a 2-D array to normalize
+ multiple transfer functions.
+ a: array_like
+ Denominator of the transfer function. At most 1-D.
+
+ Returns
+ -------
+ num: array
+ The numerator of the normalized transfer function. At least a 1-D
+ array. A 2-D array if the input `num` is a 2-D array.
+ den: 1-D array
+ The denominator of the normalized transfer function.
+
+ Notes
+ -----
+ Coefficients for both the numerator and denominator should be specified in
+ descending exponent order (e.g., ``s^2 + 3s + 5`` would be represented as
+ ``[1, 3, 5]``).
+
+ Examples
+ --------
+ >>> from scipy.signal import normalize
+
+ Normalize the coefficients of the transfer function
+ ``(3*s^2 - 2*s + 5) / (2*s^2 + 3*s + 1)``:
+
+ >>> b = [3, -2, 5]
+ >>> a = [2, 3, 1]
+ >>> normalize(b, a)
+ (array([ 1.5, -1. , 2.5]), array([1. , 1.5, 0.5]))
+
+ A warning is generated if, for example, the first coefficient of
+ `b` is 0. In the following example, the result is as expected:
+
+ >>> import warnings
+ >>> with warnings.catch_warnings(record=True) as w:
+ ... num, den = normalize([0, 3, 6], [2, -5, 4])
+
+ >>> num
+ array([1.5, 3. ])
+ >>> den
+ array([ 1. , -2.5, 2. ])
+
+ >>> print(w[0].message)
+ Badly conditioned filter coefficients (numerator): the results may be meaningless
+
+ """
+ try:
+ xp = array_namespace(b, a)
+ except TypeError:
+ # object arrays, test_ltisys.py::TestSS2TF::test_simo_round_trip
+ xp = np_compat
+
+ den = xp.asarray(a)
+ den = xpx.atleast_nd(den, ndim=1, xp=xp)
+
+ num = xp.asarray(b)
+ num = xpx.atleast_nd(_align_nums(num, xp), ndim=2, xp=xp)
+
+ if den.ndim != 1:
+ raise ValueError("Denominator polynomial must be rank-1 array.")
+ if num.ndim > 2:
+ raise ValueError("Numerator polynomial must be rank-1 or"
+ " rank-2 array.")
+ if xp.all(den == 0):
+ raise ValueError("Denominator must have at least on nonzero element.")
+
+ # Trim leading zeros in denominator, leave at least one.
+ den = _pu._trim_zeros(den, 'f')
+
+ # Normalize transfer function
+ num, den = num / den[0], den / den[0]
+
+ # Count numerator columns that are all zero
+ leading_zeros = 0
+ for j in range(num.shape[-1]):
+ col = num[:, j]
+ if xp.all(xp.abs(col) <= 1e-14):
+ leading_zeros += 1
+ else:
+ break
+
+ # Trim leading zeros of numerator
+ if leading_zeros > 0:
+ warnings.warn("Badly conditioned filter coefficients (numerator): the "
+ "results may be meaningless",
+ BadCoefficients, stacklevel=2)
+ # Make sure at least one column remains
+ if leading_zeros == num.shape[1]:
+ leading_zeros -= 1
+ num = num[:, leading_zeros:]
+
+ # Squeeze first dimension if singular
+ if num.shape[0] == 1:
+ num = num[0, :]
+
+ return num, den
+
+
+def lp2lp(b, a, wo=1.0):
+ r"""
+ Transform a lowpass filter prototype to a different frequency.
+
+ Return an analog low-pass filter with cutoff frequency `wo`
+ from an analog low-pass filter prototype with unity cutoff frequency, in
+ transfer function ('ba') representation.
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator polynomial coefficients.
+ a : array_like
+ Denominator polynomial coefficients.
+ wo : float
+ Desired cutoff, as angular frequency (e.g. rad/s).
+ Defaults to no change.
+
+ Returns
+ -------
+ b : array_like
+ Numerator polynomial coefficients of the transformed low-pass filter.
+ a : array_like
+ Denominator polynomial coefficients of the transformed low-pass filter.
+
+ See Also
+ --------
+ lp2hp, lp2bp, lp2bs, bilinear
+ lp2lp_zpk
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s}{\omega_0}
+
+ Examples
+ --------
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> lp = signal.lti([1.0], [1.0, 1.0])
+ >>> lp2 = signal.lti(*signal.lp2lp(lp.num, lp.den, 2))
+ >>> w, mag_lp, p_lp = lp.bode()
+ >>> w, mag_lp2, p_lp2 = lp2.bode(w)
+
+ >>> plt.plot(w, mag_lp, label='Lowpass')
+ >>> plt.plot(w, mag_lp2, label='Transformed Lowpass')
+ >>> plt.semilogx()
+ >>> plt.grid(True)
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.legend()
+
+ """
+ xp = array_namespace(a, b)
+ a, b = map(xp.asarray, (a, b))
+ a, b = xp_promote(a, b, force_floating=True, xp=xp)
+ a = xpx.atleast_nd(a, ndim=1, xp=xp)
+ b = xpx.atleast_nd(b, ndim=1, xp=xp)
+
+ try:
+ wo = float(wo)
+ except TypeError:
+ wo = float(wo[0])
+ d = a.shape[0]
+ n = b.shape[0]
+ M = max((d, n))
+ pwo = wo ** xp.arange(M - 1, -1, -1, dtype=xp.float64)
+ start1 = max((n - d, 0))
+ start2 = max((d - n, 0))
+ b = b * pwo[start1] / pwo[start2:]
+ a = a * pwo[start1] / pwo[start1:]
+ return normalize(b, a)
+
+
+def _resize(a, new_shape, xp):
+ # https://github.com/numpy/numpy/blob/v2.2.4/numpy/_core/fromnumeric.py#L1535
+ a = xp.reshape(a, (-1,))
+
+ new_size = 1
+ for dim_length in new_shape:
+ new_size *= dim_length
+ if dim_length < 0:
+ raise ValueError(
+ 'all elements of `new_shape` must be non-negative'
+ )
+
+ if xp_size(a) == 0 or new_size == 0:
+ # First case must zero fill. The second would have repeats == 0.
+ return xp.zeros_like(a, shape=new_shape)
+
+ repeats = -(-new_size // xp_size(a)) # ceil division
+ a = xp.concat((a,) * repeats)[:new_size]
+
+ return xp.reshape(a, new_shape)
+
+
+def lp2hp(b, a, wo=1.0):
+ r"""
+ Transform a lowpass filter prototype to a highpass filter.
+
+ Return an analog high-pass filter with cutoff frequency `wo`
+ from an analog low-pass filter prototype with unity cutoff frequency, in
+ transfer function ('ba') representation.
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator polynomial coefficients.
+ a : array_like
+ Denominator polynomial coefficients.
+ wo : float
+ Desired cutoff, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+
+ Returns
+ -------
+ b : array_like
+ Numerator polynomial coefficients of the transformed high-pass filter.
+ a : array_like
+ Denominator polynomial coefficients of the transformed high-pass filter.
+
+ See Also
+ --------
+ lp2lp, lp2bp, lp2bs, bilinear
+ lp2hp_zpk
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{\omega_0}{s}
+
+ This maintains symmetry of the lowpass and highpass responses on a
+ logarithmic scale.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> lp = signal.lti([1.0], [1.0, 1.0])
+ >>> hp = signal.lti(*signal.lp2hp(lp.num, lp.den))
+ >>> w, mag_lp, p_lp = lp.bode()
+ >>> w, mag_hp, p_hp = hp.bode(w)
+
+ >>> plt.plot(w, mag_lp, label='Lowpass')
+ >>> plt.plot(w, mag_hp, label='Highpass')
+ >>> plt.semilogx()
+ >>> plt.grid(True)
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.legend()
+
+ """
+ xp = array_namespace(a, b)
+
+ a, b = map(xp.asarray, (a, b))
+ a, b = xp_promote(a, b, force_floating=True, xp=xp)
+ a = xpx.atleast_nd(a, ndim=1, xp=xp)
+ b = xpx.atleast_nd(b, ndim=1, xp=xp)
+
+ try:
+ wo = float(wo)
+ except TypeError:
+ wo = float(wo[0])
+ d = a.shape[0]
+ n = b.shape[0]
+ if wo != 1:
+ pwo = wo ** xp.arange(max((d, n)), dtype=b.dtype)
+ else:
+ pwo = xp.ones(max((d, n)), dtype=b.dtype)
+ if d >= n:
+ outa = xp.flip(a) * pwo
+ outb = _resize(b, (d,), xp=xp)
+ outb[n:] = 0.0
+ outb[:n] = xp.flip(b) * pwo[:n]
+ else:
+ outb = xp.flip(b) * pwo
+ outa = _resize(a, (n,), xp=xp)
+ outa[d:] = 0.0
+ outa[:d] = xp.flip(a) * pwo[:d]
+
+ return normalize(outb, outa)
+
+
+def lp2bp(b, a, wo=1.0, bw=1.0):
+ r"""
+ Transform a lowpass filter prototype to a bandpass filter.
+
+ Return an analog band-pass filter with center frequency `wo` and
+ bandwidth `bw` from an analog low-pass filter prototype with unity
+ cutoff frequency, in transfer function ('ba') representation.
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator polynomial coefficients.
+ a : array_like
+ Denominator polynomial coefficients.
+ wo : float
+ Desired passband center, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+ bw : float
+ Desired passband width, as angular frequency (e.g., rad/s).
+ Defaults to 1.
+
+ Returns
+ -------
+ b : array_like
+ Numerator polynomial coefficients of the transformed band-pass filter.
+ a : array_like
+ Denominator polynomial coefficients of the transformed band-pass filter.
+
+ See Also
+ --------
+ lp2lp, lp2hp, lp2bs, bilinear
+ lp2bp_zpk
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s^2 + {\omega_0}^2}{s \cdot \mathrm{BW}}
+
+ This is the "wideband" transformation, producing a passband with
+ geometric (log frequency) symmetry about `wo`.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> lp = signal.lti([1.0], [1.0, 1.0])
+ >>> bp = signal.lti(*signal.lp2bp(lp.num, lp.den))
+ >>> w, mag_lp, p_lp = lp.bode()
+ >>> w, mag_bp, p_bp = bp.bode(w)
+
+ >>> plt.plot(w, mag_lp, label='Lowpass')
+ >>> plt.plot(w, mag_bp, label='Bandpass')
+ >>> plt.semilogx()
+ >>> plt.grid(True)
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.legend()
+ """
+ xp = array_namespace(a, b)
+
+ a, b = map(xp.asarray, (a, b))
+ a, b = xp_promote(a, b, force_floating=True, xp=xp)
+ a = xpx.atleast_nd(a, ndim=1, xp=xp)
+ b = xpx.atleast_nd(b, ndim=1, xp=xp)
+
+ D = a.shape[0] - 1
+ N = b.shape[0] - 1
+ ma = max([N, D])
+ Np = N + ma
+ Dp = D + ma
+ bprime = xp.empty(Np + 1, dtype=b.dtype)
+ aprime = xp.empty(Dp + 1, dtype=a.dtype)
+ wosq = wo * wo
+ for j in range(Np + 1):
+ val = 0.0
+ for i in range(0, N + 1):
+ for k in range(0, i + 1):
+ if ma - i + 2 * k == j:
+ val += comb(i, k) * b[N - i] * (wosq) ** (i - k) / bw ** i
+ bprime[Np - j] = val
+ for j in range(Dp + 1):
+ val = 0.0
+ for i in range(0, D + 1):
+ for k in range(0, i + 1):
+ if ma - i + 2 * k == j:
+ val += comb(i, k) * a[D - i] * (wosq) ** (i - k) / bw ** i
+ aprime[Dp - j] = val
+
+ return normalize(bprime, aprime)
+
+
+def lp2bs(b, a, wo=1.0, bw=1.0):
+ r"""
+ Transform a lowpass filter prototype to a bandstop filter.
+
+ Return an analog band-stop filter with center frequency `wo` and
+ bandwidth `bw` from an analog low-pass filter prototype with unity
+ cutoff frequency, in transfer function ('ba') representation.
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator polynomial coefficients.
+ a : array_like
+ Denominator polynomial coefficients.
+ wo : float
+ Desired stopband center, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+ bw : float
+ Desired stopband width, as angular frequency (e.g., rad/s).
+ Defaults to 1.
+
+ Returns
+ -------
+ b : array_like
+ Numerator polynomial coefficients of the transformed band-stop filter.
+ a : array_like
+ Denominator polynomial coefficients of the transformed band-stop filter.
+
+ See Also
+ --------
+ lp2lp, lp2hp, lp2bp, bilinear
+ lp2bs_zpk
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s \cdot \mathrm{BW}}{s^2 + {\omega_0}^2}
+
+ This is the "wideband" transformation, producing a stopband with
+ geometric (log frequency) symmetry about `wo`.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> lp = signal.lti([1.0], [1.0, 1.5])
+ >>> bs = signal.lti(*signal.lp2bs(lp.num, lp.den))
+ >>> w, mag_lp, p_lp = lp.bode()
+ >>> w, mag_bs, p_bs = bs.bode(w)
+ >>> plt.plot(w, mag_lp, label='Lowpass')
+ >>> plt.plot(w, mag_bs, label='Bandstop')
+ >>> plt.semilogx()
+ >>> plt.grid(True)
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.legend()
+ """
+ xp = array_namespace(a, b)
+
+ a, b = map(xp.asarray, (a, b))
+ a, b = xp_promote(a, b, force_floating=True, xp=xp)
+ a = xpx.atleast_nd(a, ndim=1, xp=xp)
+ b = xpx.atleast_nd(b, ndim=1, xp=xp)
+
+ D = a.shape[0] - 1
+ N = b.shape[0] - 1
+ M = max([N, D])
+ Np = M + M
+ Dp = M + M
+ bprime = xp.empty(Np + 1, dtype=b.dtype)
+ aprime = xp.empty(Dp + 1, dtype=a.dtype)
+ wosq = wo * wo
+ for j in range(Np + 1):
+ val = 0.0
+ for i in range(0, N + 1):
+ for k in range(0, M - i + 1):
+ if i + 2 * k == j:
+ val += (comb(M - i, k) * b[N - i] *
+ (wosq) ** (M - i - k) * bw ** i)
+ bprime[Np - j] = val
+ for j in range(Dp + 1):
+ val = 0.0
+ for i in range(0, D + 1):
+ for k in range(0, M - i + 1):
+ if i + 2 * k == j:
+ val += (comb(M - i, k) * a[D - i] *
+ (wosq) ** (M - i - k) * bw ** i)
+ aprime[Dp - j] = val
+
+ return normalize(bprime, aprime)
+
+
+def bilinear(b, a, fs=1.0):
+ r"""Calculate a digital IIR filter from an analog transfer function by utilizing
+ the bilinear transform.
+
+ Parameters
+ ----------
+ b : array_like
+ Coefficients of the numerator polynomial of the analog transfer function in
+ form of a complex- or real-valued 1d array.
+ a : array_like
+ Coefficients of the denominator polynomial of the analog transfer function in
+ form of a complex- or real-valued 1d array.
+ fs : float
+ Sample rate, as ordinary frequency (e.g., hertz). No pre-warping is
+ done in this function.
+
+ Returns
+ -------
+ beta : ndarray
+ Coefficients of the numerator polynomial of the digital transfer function in
+ form of a complex- or real-valued 1d array.
+ alpha : ndarray
+ Coefficients of the denominator polynomial of the digital transfer function in
+ form of a complex- or real-valued 1d array.
+
+ Notes
+ -----
+ The parameters :math:`b = [b_0, \ldots, b_Q]` and :math:`a = [a_0, \ldots, a_P]`
+ are 1d arrays of length :math:`Q+1` and :math:`P+1`. They define the analog
+ transfer function
+
+ .. math::
+
+ H_a(s) = \frac{b_0 s^Q + b_1 s^{Q-1} + \cdots + b_Q}{
+ a_0 s^P + a_1 s^{P-1} + \cdots + a_P}\ .
+
+ The bilinear transform [1]_ is applied by substituting
+
+ .. math::
+
+ s = \kappa \frac{z-1}{z+1}\ , \qquad \kappa := 2 f_s\ ,
+
+ into :math:`H_a(s)`, with :math:`f_s` being the sampling rate.
+ This results in the digital transfer function in the :math:`z`-domain
+
+ .. math::
+
+ H_d(z) = \frac{b_0 \left(\kappa \frac{z-1}{z+1}\right)^Q +
+ b_1 \left(\kappa \frac{z-1}{z+1}\right)^{Q-1} +
+ \cdots + b_Q}{
+ a_0 \left(\kappa \frac{z-1}{z+1}\right)^P +
+ a_1 \left(\kappa \frac{z-1}{z+1}\right)^{P-1} +
+ \cdots + a_P}\ .
+
+ This expression can be simplified by multiplying numerator and denominator by
+ :math:`(z+1)^N`, with :math:`N=\max(P, Q)`. This allows :math:`H_d(z)` to be
+ reformulated as
+
+ .. math::
+
+ & & \frac{b_0 \big(\kappa (z-1)\big)^Q (z+1)^{N-Q} +
+ b_1 \big(\kappa (z-1)\big)^{Q-1} (z+1)^{N-Q+1} +
+ \cdots + b_Q(z+1)^N}{
+ a_0 \big(\kappa (z-1)\big)^P (z+1)^{N-P} +
+ a_1 \big(\kappa (z-1)\big)^{P-1} (z+1)^{N-P+1} +
+ \cdots + a_P(z+1)^N}\\
+ &=:& \frac{\beta_0 + \beta_1 z^{-1} + \cdots + \beta_N z^{-N}}{
+ \alpha_0 + \alpha_1 z^{-1} + \cdots + \alpha_N z^{-N}}\ .
+
+
+ This is the equation implemented to perform the bilinear transform. Note that for
+ large :math:`f_s`, :math:`\kappa^Q` or :math:`\kappa^P` can cause a numeric
+ overflow for sufficiently large :math:`P` or :math:`Q`.
+
+ References
+ ----------
+ .. [1] "Bilinear Transform", Wikipedia,
+ https://en.wikipedia.org/wiki/Bilinear_transform
+
+ See Also
+ --------
+ lp2lp, lp2hp, lp2bp, lp2bs, bilinear_zpk
+
+ Examples
+ --------
+ The following example shows the frequency response of an analog bandpass filter and
+ the corresponding digital filter derived by utilitzing the bilinear transform:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ ...
+ >>> fs = 100 # sampling frequency
+ >>> om_c = 2 * np.pi * np.array([7, 13]) # corner frequencies
+ >>> bb_s, aa_s = signal.butter(4, om_c, btype='bandpass', analog=True, output='ba')
+ >>> bb_z, aa_z = signal.bilinear(bb_s, aa_s, fs)
+ ...
+ >>> w_z, H_z = signal.freqz(bb_z, aa_z) # frequency response of digitial filter
+ >>> w_s, H_s = signal.freqs(bb_s, aa_s, worN=w_z*fs) # analog filter response
+ ...
+ >>> f_z, f_s = w_z * fs / (2*np.pi), w_s / (2*np.pi)
+ >>> Hz_dB, Hs_dB = (20*np.log10(np.abs(H_).clip(1e-10)) for H_ in (H_z, H_s))
+ >>> fg0, ax0 = plt.subplots()
+ >>> ax0.set_title("Frequency Response of 4-th order Bandpass Filter")
+ >>> ax0.set(xlabel='Frequency $f$ in Hertz', ylabel='Magnitude in dB',
+ ... xlim=[f_z[1], fs/2], ylim=[-200, 2])
+ >>> ax0.semilogx(f_z, Hz_dB, alpha=.5, label=r'$|H_z(e^{j 2 \pi f})|$')
+ >>> ax0.semilogx(f_s, Hs_dB, alpha=.5, label=r'$|H_s(j 2 \pi f)|$')
+ >>> ax0.legend()
+ >>> ax0.grid(which='both', axis='x')
+ >>> ax0.grid(which='major', axis='y')
+ >>> plt.show()
+
+ The difference in the higher frequencies shown in the plot is caused by an effect
+ called "frequency warping". [1]_ describes a method called "pre-warping" to
+ reduce those deviations.
+ """
+ xp = array_namespace(b, a)
+
+ b, a = map(np.asarray, (b, a))
+ b, a = np.atleast_1d(b), np.atleast_1d(a) # convert scalars, if needed
+ if not a.ndim == 1:
+ raise ValueError(f"Parameter a is not a 1d array since {a.shape=}")
+ if not b.ndim == 1:
+ raise ValueError(f"Parameter b is not a 1d array since {b.shape=}")
+ b, a = np.trim_zeros(b, 'f'), np.trim_zeros(a, 'f') # remove leading zeros
+ fs = _validate_fs(fs, allow_none=False)
+
+ # Splitting the factor fs*2 between numerator and denominator reduces the chance of
+ # numeric overflow for large fs and large N:
+ fac = np.sqrt(fs*2)
+ zp1 = np.polynomial.Polynomial((+1, 1)) / fac # Polynomial (z + 1) / fac
+ zm1 = np.polynomial.Polynomial((-1, 1)) * fac # Polynomial (z - 1) * fac
+ # Note that NumPy's Polynomial coefficient order is backward compared to a and b.
+
+ N = max(len(a), len(b)) - 1
+ numerator = sum(b_ * zp1**(N-q) * zm1**q for q, b_ in enumerate(b[::-1]))
+ denominator = sum(a_ * zp1**(N-p) * zm1**p for p, a_ in enumerate(a[::-1]))
+
+ return normalize(
+ xp.asarray(numerator.coef[::-1].copy()),
+ xp.asarray(denominator.coef[::-1].copy())
+ )
+
+
+def _validate_gpass_gstop(gpass, gstop):
+
+ if gpass <= 0.0:
+ raise ValueError("gpass should be larger than 0.0")
+ elif gstop <= 0.0:
+ raise ValueError("gstop should be larger than 0.0")
+ elif gpass > gstop:
+ raise ValueError("gpass should be smaller than gstop")
+
+
+def iirdesign(wp, ws, gpass, gstop, analog=False, ftype='ellip', output='ba',
+ fs=None):
+ """Complete IIR digital and analog filter design.
+
+ Given passband and stopband frequencies and gains, construct an analog or
+ digital IIR filter of minimum order for a given basic type. Return the
+ output in numerator, denominator ('ba'), pole-zero ('zpk') or second order
+ sections ('sos') form.
+
+ Parameters
+ ----------
+ wp, ws : float or array like, shape (2,)
+ Passband and stopband edge frequencies. Possible values are scalars
+ (for lowpass and highpass filters) or ranges (for bandpass and bandstop
+ filters).
+ For digital filters, these are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. For example:
+
+ - Lowpass: wp = 0.2, ws = 0.3
+ - Highpass: wp = 0.3, ws = 0.2
+ - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
+ - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
+
+ For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s).
+ Note, that for bandpass and bandstop filters passband must lie strictly
+ inside stopband or vice versa. Also note that the cutoff at the band edges
+ for IIR filters is defined as half-power, so -3dB, not half-amplitude (-6dB)
+ like for `scipy.signal.fiwin`.
+ gpass : float
+ The maximum loss in the passband (dB).
+ gstop : float
+ The minimum attenuation in the stopband (dB).
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ ftype : str, optional
+ The type of IIR filter to design:
+
+ - Butterworth : 'butter'
+ - Chebyshev I : 'cheby1'
+ - Chebyshev II : 'cheby2'
+ - Cauer/elliptic: 'ellip'
+
+ output : {'ba', 'zpk', 'sos'}, optional
+ Filter form of the output:
+
+ - second-order sections (recommended): 'sos'
+ - numerator/denominator (default) : 'ba'
+ - pole-zero : 'zpk'
+
+ In general the second-order sections ('sos') form is
+ recommended because inferring the coefficients for the
+ numerator/denominator form ('ba') suffers from numerical
+ instabilities. For reasons of backward compatibility the default
+ form is the numerator/denominator form ('ba'), where the 'b'
+ and the 'a' in 'ba' refer to the commonly used names of the
+ coefficients used.
+
+ Note: Using the second-order sections form ('sos') is sometimes
+ associated with additional computational costs: for
+ data-intense use cases it is therefore recommended to also
+ investigate the numerator/denominator form ('ba').
+
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ butter : Filter design using order and critical points
+ cheby1, cheby2, ellip, bessel
+ buttord : Find order and critical points from passband and stopband spec
+ cheb1ord, cheb2ord, ellipord
+ iirfilter : General filter design using order and critical frequencies
+
+ Notes
+ -----
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import matplotlib.ticker
+
+ >>> wp = 0.2
+ >>> ws = 0.3
+ >>> gpass = 1
+ >>> gstop = 40
+
+ >>> system = signal.iirdesign(wp, ws, gpass, gstop)
+ >>> w, h = signal.freqz(*system)
+
+ >>> fig, ax1 = plt.subplots()
+ >>> ax1.set_title('Digital filter frequency response')
+ >>> ax1.plot(w, 20 * np.log10(abs(h)), 'b')
+ >>> ax1.set_ylabel('Amplitude [dB]', color='b')
+ >>> ax1.set_xlabel('Frequency [rad/sample]')
+ >>> ax1.grid(True)
+ >>> ax1.set_ylim([-120, 20])
+ >>> ax2 = ax1.twinx()
+ >>> phase = np.unwrap(np.angle(h))
+ >>> ax2.plot(w, phase, 'g')
+ >>> ax2.set_ylabel('Phase [rad]', color='g')
+ >>> ax2.grid(True)
+ >>> ax2.axis('tight')
+ >>> ax2.set_ylim([-6, 1])
+ >>> nticks = 8
+ >>> ax1.yaxis.set_major_locator(matplotlib.ticker.LinearLocator(nticks))
+ >>> ax2.yaxis.set_major_locator(matplotlib.ticker.LinearLocator(nticks))
+
+ """
+ xp = array_namespace(wp, ws)
+ wp, ws = map(xp.asarray, (wp, ws))
+
+ try:
+ ordfunc = filter_dict[ftype][1]
+ except KeyError as e:
+ raise ValueError(f"Invalid IIR filter type: {ftype}") from e
+ except IndexError as e:
+ raise ValueError(f"{ftype} does not have order selection. "
+ "Use iirfilter function.") from e
+
+ _validate_gpass_gstop(gpass, gstop)
+
+ wp = xpx.atleast_nd(wp, ndim=1, xp=xp)
+ ws = xpx.atleast_nd(ws, ndim=1, xp=xp)
+
+ fs = _validate_fs(fs, allow_none=True)
+
+ if wp.shape[0] != ws.shape[0] or wp.shape not in [(1,), (2,)]:
+ raise ValueError("wp and ws must have one or two elements each, and "
+ f"the same shape, got {wp.shape} and {ws.shape}")
+
+ if xp.any(wp <= 0) or xp.any(ws <= 0):
+ raise ValueError("Values for wp, ws must be greater than 0")
+
+ if not analog:
+ if fs is None:
+ if xp.any(wp >= 1) or xp.any(ws >= 1):
+ raise ValueError("Values for wp, ws must be less than 1")
+ elif xp.any(wp >= fs/2) or xp.any(ws >= fs/2):
+ raise ValueError("Values for wp, ws must be less than fs/2 "
+ f"(fs={fs} -> fs/2={fs/2})")
+
+ if wp.shape[0] == 2:
+ if not ((ws[0] < wp[0] and wp[1] < ws[1]) or
+ (wp[0] < ws[0] and ws[1] < wp[1])):
+ raise ValueError("Passband must lie strictly inside stopband "
+ "or vice versa")
+
+ band_type = 2 * (wp.shape[0] - 1)
+ band_type += 1
+ if wp[0] >= ws[0]:
+ band_type += 1
+
+ btype = {1: 'lowpass', 2: 'highpass',
+ 3: 'bandstop', 4: 'bandpass'}[band_type]
+
+ N, Wn = ordfunc(wp, ws, gpass, gstop, analog=analog, fs=fs)
+ return iirfilter(N, Wn, rp=gpass, rs=gstop, analog=analog, btype=btype,
+ ftype=ftype, output=output, fs=fs)
+
+
+def iirfilter(N, Wn, rp=None, rs=None, btype='band', analog=False,
+ ftype='butter', output='ba', fs=None):
+ """
+ IIR digital and analog filter design given order and critical points.
+
+ Design an Nth-order digital or analog filter and return the filter
+ coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ Wn : array_like
+ A scalar or length-2 sequence giving the critical frequencies.
+
+ For digital filters, `Wn` are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`Wn` is thus in
+ half-cycles / sample.)
+
+ For analog filters, `Wn` is an angular frequency (e.g., rad/s).
+
+ When Wn is a length-2 sequence, ``Wn[0]`` must be less than ``Wn[1]``.
+ rp : float, optional
+ For Chebyshev and elliptic filters, provides the maximum ripple
+ in the passband. (dB)
+ rs : float, optional
+ For Chebyshev and elliptic filters, provides the minimum attenuation
+ in the stop band. (dB)
+ btype : {'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional
+ The type of filter. Default is 'bandpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ ftype : str, optional
+ The type of IIR filter to design:
+
+ - Butterworth : 'butter'
+ - Chebyshev I : 'cheby1'
+ - Chebyshev II : 'cheby2'
+ - Cauer/elliptic: 'ellip'
+ - Bessel/Thomson: 'bessel'
+
+ output : {'ba', 'zpk', 'sos'}, optional
+ Filter form of the output:
+
+ - second-order sections (recommended): 'sos'
+ - numerator/denominator (default) : 'ba'
+ - pole-zero : 'zpk'
+
+ In general the second-order sections ('sos') form is
+ recommended because inferring the coefficients for the
+ numerator/denominator form ('ba') suffers from numerical
+ instabilities. For reasons of backward compatibility the default
+ form is the numerator/denominator form ('ba'), where the 'b'
+ and the 'a' in 'ba' refer to the commonly used names of the
+ coefficients used.
+
+ Note: Using the second-order sections form ('sos') is sometimes
+ associated with additional computational costs: for
+ data-intense use cases it is therefore recommended to also
+ investigate the numerator/denominator form ('ba').
+
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ butter : Filter design using order and critical points
+ cheby1, cheby2, ellip, bessel
+ buttord : Find order and critical points from passband and stopband spec
+ cheb1ord, cheb2ord, ellipord
+ iirdesign : General filter design using passband and stopband spec
+
+ Notes
+ -----
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ Examples
+ --------
+ Generate a 17th-order Chebyshev II analog bandpass filter from 50 Hz to
+ 200 Hz and plot the frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> b, a = signal.iirfilter(17, [2*np.pi*50, 2*np.pi*200], rs=60,
+ ... btype='band', analog=True, ftype='cheby2')
+ >>> w, h = signal.freqs(b, a, 1000)
+ >>> fig = plt.figure()
+ >>> ax = fig.add_subplot(1, 1, 1)
+ >>> ax.semilogx(w / (2*np.pi), 20 * np.log10(np.maximum(abs(h), 1e-5)))
+ >>> ax.set_title('Chebyshev Type II bandpass frequency response')
+ >>> ax.set_xlabel('Frequency [Hz]')
+ >>> ax.set_ylabel('Amplitude [dB]')
+ >>> ax.axis((10, 1000, -100, 10))
+ >>> ax.grid(which='both', axis='both')
+ >>> plt.show()
+
+ Create a digital filter with the same properties, in a system with
+ sampling rate of 2000 Hz, and plot the frequency response. (Second-order
+ sections implementation is required to ensure stability of a filter of
+ this order):
+
+ >>> sos = signal.iirfilter(17, [50, 200], rs=60, btype='band',
+ ... analog=False, ftype='cheby2', fs=2000,
+ ... output='sos')
+ >>> w, h = signal.freqz_sos(sos, 2000, fs=2000)
+ >>> fig = plt.figure()
+ >>> ax = fig.add_subplot(1, 1, 1)
+ >>> ax.semilogx(w, 20 * np.log10(np.maximum(abs(h), 1e-5)))
+ >>> ax.set_title('Chebyshev Type II bandpass frequency response')
+ >>> ax.set_xlabel('Frequency [Hz]')
+ >>> ax.set_ylabel('Amplitude [dB]')
+ >>> ax.axis((10, 1000, -100, 10))
+ >>> ax.grid(which='both', axis='both')
+ >>> plt.show()
+
+ """
+ xp = array_namespace(Wn)
+ # For now, outputs will have float64 base dtype regardless of
+ # the dtype of Wn, so cast to float64 here to ensure 64 bit
+ # precision for all calculations.
+ Wn = xp.asarray(Wn, dtype=xp.float64)
+
+ fs = _validate_fs(fs, allow_none=True)
+ ftype, btype, output = (x.lower() for x in (ftype, btype, output))
+ if fs is not None:
+ if analog:
+ raise ValueError("fs cannot be specified for an analog filter")
+ Wn = Wn / (fs/2)
+
+ if xp.any(Wn <= 0):
+ raise ValueError("filter critical frequencies must be greater than 0")
+
+ if xp_size(Wn) > 1 and not Wn[0] < Wn[1]:
+ raise ValueError("Wn[0] must be less than Wn[1]")
+
+ try:
+ btype = band_dict[btype]
+ except KeyError as e:
+ raise ValueError(f"'{btype}' is an invalid bandtype for filter.") from e
+
+ try:
+ typefunc = filter_dict[ftype][0]
+ except KeyError as e:
+ raise ValueError(f"'{ftype}' is not a valid basic IIR filter.") from e
+
+ if output not in ['ba', 'zpk', 'sos']:
+ raise ValueError(f"'{output}' is not a valid output form.")
+
+ if rp is not None and rp < 0:
+ raise ValueError("passband ripple (rp) must be positive")
+
+ if rs is not None and rs < 0:
+ raise ValueError("stopband attenuation (rs) must be positive")
+
+ # Get analog lowpass prototype
+ if typefunc == buttap:
+ z, p, k = typefunc(N, xp=xp)
+ elif typefunc == besselap:
+ z, p, k = typefunc(N, norm=bessel_norms[ftype], xp=xp)
+ elif typefunc == cheb1ap:
+ if rp is None:
+ raise ValueError("passband ripple (rp) must be provided to "
+ "design a Chebyshev I filter.")
+ z, p, k = typefunc(N, rp, xp=xp)
+ elif typefunc == cheb2ap:
+ if rs is None:
+ raise ValueError("stopband attenuation (rs) must be provided to "
+ "design an Chebyshev II filter.")
+ z, p, k = typefunc(N, rs, xp=xp)
+ elif typefunc == ellipap:
+ if rs is None or rp is None:
+ raise ValueError("Both rp and rs must be provided to design an "
+ "elliptic filter.")
+ z, p, k = typefunc(N, rp, rs, xp=xp)
+ else:
+ raise NotImplementedError(f"'{ftype}' not implemented in iirfilter.")
+
+ # Pre-warp frequencies for digital filter design
+ if not analog:
+ if xp.any(Wn <= 0) or xp.any(Wn >= 1):
+ if fs is not None:
+ raise ValueError("Digital filter critical frequencies must "
+ f"be 0 < Wn < fs/2 (fs={fs} -> fs/2={fs/2})")
+ raise ValueError("Digital filter critical frequencies "
+ "must be 0 < Wn < 1")
+ fs = 2.0
+ warped = 2 * fs * xp.tan(xp.pi * Wn / fs)
+ else:
+ warped = Wn
+
+ # transform to lowpass, bandpass, highpass, or bandstop
+ if btype in ('lowpass', 'highpass'):
+ if xp_size(Wn) != 1:
+ raise ValueError('Must specify a single critical frequency Wn '
+ 'for lowpass or highpass filter')
+
+ if btype == 'lowpass':
+ z, p, k = lp2lp_zpk(z, p, k, wo=warped)
+ elif btype == 'highpass':
+ z, p, k = lp2hp_zpk(z, p, k, wo=warped)
+ elif btype in ('bandpass', 'bandstop'):
+ try:
+ bw = warped[1] - warped[0]
+ wo = xp.sqrt(warped[0] * warped[1])
+ except IndexError as e:
+ raise ValueError('Wn must specify start and stop frequencies for '
+ 'bandpass or bandstop filter') from e
+
+ if btype == 'bandpass':
+ z, p, k = lp2bp_zpk(z, p, k, wo=wo, bw=bw)
+ elif btype == 'bandstop':
+ z, p, k = lp2bs_zpk(z, p, k, wo=wo, bw=bw)
+ else:
+ raise NotImplementedError(f"'{btype}' not implemented in iirfilter.")
+
+ # Find discrete equivalent if necessary
+ if not analog:
+ z, p, k = bilinear_zpk(z, p, k, fs=fs)
+
+ # Transform to proper out type (pole-zero, state-space, numer-denom)
+ if output == 'zpk':
+ return z, p, k
+ elif output == 'ba':
+ return zpk2tf(z, p, k)
+ elif output == 'sos':
+ return zpk2sos(z, p, k, analog=analog)
+
+
+def _relative_degree(z, p):
+ """
+ Return relative degree of transfer function from zeros and poles
+ """
+ degree = p.shape[0] - z.shape[0]
+ if degree < 0:
+ raise ValueError("Improper transfer function. "
+ "Must have at least as many poles as zeros.")
+ else:
+ return degree
+
+
+def bilinear_zpk(z, p, k, fs):
+ r"""
+ Return a digital IIR filter from an analog one using a bilinear transform.
+
+ Transform a set of poles and zeros from the analog s-plane to the digital
+ z-plane using Tustin's method, which substitutes ``2*fs*(z-1) / (z+1)`` for
+ ``s``, maintaining the shape of the frequency response.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the analog filter transfer function.
+ p : array_like
+ Poles of the analog filter transfer function.
+ k : float
+ System gain of the analog filter transfer function.
+ fs : float
+ Sample rate, as ordinary frequency (e.g., hertz). No prewarping is
+ done in this function.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transformed digital filter transfer function.
+ p : ndarray
+ Poles of the transformed digital filter transfer function.
+ k : float
+ System gain of the transformed digital filter.
+
+ See Also
+ --------
+ lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, lp2bs_zpk
+ bilinear
+
+ Notes
+ -----
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> fs = 100
+ >>> bf = 2 * np.pi * np.array([7, 13])
+ >>> filts = signal.lti(*signal.butter(4, bf, btype='bandpass', analog=True,
+ ... output='zpk'))
+ >>> filtz = signal.lti(*signal.bilinear_zpk(filts.zeros, filts.poles,
+ ... filts.gain, fs))
+ >>> wz, hz = signal.freqz_zpk(filtz.zeros, filtz.poles, filtz.gain)
+ >>> ws, hs = signal.freqs_zpk(filts.zeros, filts.poles, filts.gain,
+ ... worN=fs*wz)
+ >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hz).clip(1e-15)),
+ ... label=r'$|H_z(e^{j \omega})|$')
+ >>> plt.semilogx(wz*fs/(2*np.pi), 20*np.log10(np.abs(hs).clip(1e-15)),
+ ... label=r'$|H(j \omega)|$')
+ >>> plt.legend()
+ >>> plt.xlabel('Frequency [Hz]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.grid(True)
+ """
+ xp = array_namespace(z, p)
+
+ z, p = map(xp.asarray, (z, p))
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ degree = _relative_degree(z, p)
+
+ fs2 = 2.0*fs
+
+ # Bilinear transform the poles and zeros
+ z_z = (fs2 + z) / (fs2 - z)
+ p_z = (fs2 + p) / (fs2 - p)
+
+ # Any zeros that were at infinity get moved to the Nyquist frequency
+ z_z = xp.concat((z_z, -xp.ones(degree)))
+
+ # Compensate for gain change
+ k_z = k * xp.real(xp.prod(fs2 - z) / xp.prod(fs2 - p))
+
+ return z_z, p_z, k_z
+
+
+def lp2lp_zpk(z, p, k, wo=1.0):
+ r"""
+ Transform a lowpass filter prototype to a different frequency.
+
+ Return an analog low-pass filter with cutoff frequency `wo`
+ from an analog low-pass filter prototype with unity cutoff frequency,
+ using zeros, poles, and gain ('zpk') representation.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the analog filter transfer function.
+ p : array_like
+ Poles of the analog filter transfer function.
+ k : float
+ System gain of the analog filter transfer function.
+ wo : float
+ Desired cutoff, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transformed low-pass filter transfer function.
+ p : ndarray
+ Poles of the transformed low-pass filter transfer function.
+ k : float
+ System gain of the transformed low-pass filter.
+
+ See Also
+ --------
+ lp2hp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear
+ lp2lp
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s}{\omega_0}
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to
+ transform it to a new 'zpk' representation associated with a cutoff frequency wo.
+
+ >>> from scipy.signal import lp2lp_zpk
+ >>> z = [7, 2]
+ >>> p = [5, 13]
+ >>> k = 0.8
+ >>> wo = 0.4
+ >>> lp2lp_zpk(z, p, k, wo)
+ ( array([2.8, 0.8]), array([2. , 5.2]), 0.8)
+ """
+ xp = array_namespace(z, p)
+
+ z, p = map(xp.asarray, (z, p))
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+
+ wo = float(wo) # Avoid int wraparound
+
+ degree = _relative_degree(z, p)
+
+ # Scale all points radially from origin to shift cutoff frequency
+ z_lp = wo * z
+ p_lp = wo * p
+
+ # Each shifted pole decreases gain by wo, each shifted zero increases it.
+ # Cancel out the net change to keep overall gain the same
+ k_lp = k * wo**degree
+
+ return z_lp, p_lp, k_lp
+
+
+def lp2hp_zpk(z, p, k, wo=1.0):
+ r"""
+ Transform a lowpass filter prototype to a highpass filter.
+
+ Return an analog high-pass filter with cutoff frequency `wo`
+ from an analog low-pass filter prototype with unity cutoff frequency,
+ using zeros, poles, and gain ('zpk') representation.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the analog filter transfer function.
+ p : array_like
+ Poles of the analog filter transfer function.
+ k : float
+ System gain of the analog filter transfer function.
+ wo : float
+ Desired cutoff, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transformed high-pass filter transfer function.
+ p : ndarray
+ Poles of the transformed high-pass filter transfer function.
+ k : float
+ System gain of the transformed high-pass filter.
+
+ See Also
+ --------
+ lp2lp_zpk, lp2bp_zpk, lp2bs_zpk, bilinear
+ lp2hp
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{\omega_0}{s}
+
+ This maintains symmetry of the lowpass and highpass responses on a
+ logarithmic scale.
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to
+ transform it to a highpass filter with a cutoff frequency wo.
+
+ >>> from scipy.signal import lp2hp_zpk
+ >>> z = [ -2 + 3j , -0.5 - 0.8j ]
+ >>> p = [ -1 , -4 ]
+ >>> k = 10
+ >>> wo = 0.6
+ >>> lp2hp_zpk(z, p, k, wo)
+ ( array([-0.09230769-0.13846154j, -0.33707865+0.53932584j]),
+ array([-0.6 , -0.15]),
+ 8.5)
+ """
+ xp = array_namespace(z, p)
+
+ z, p = map(xp.asarray, (z, p))
+ # XXX: no xp_promote here since that breaks TestButter
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+
+ wo = float(wo)
+
+ degree = _relative_degree(z, p)
+
+ # Invert positions radially about unit circle to convert LPF to HPF
+ # Scale all points radially from origin to shift cutoff frequency
+ z_hp = wo / z
+ p_hp = wo / p
+
+ # If lowpass had zeros at infinity, inverting moves them to origin.
+ z_hp = xp.concat((z_hp, xp.zeros(degree)))
+
+ # Cancel out gain change caused by inversion
+ k_hp = k * xp.real(xp.prod(-z) / xp.prod(-p))
+
+ return z_hp, p_hp, k_hp
+
+
+def lp2bp_zpk(z, p, k, wo=1.0, bw=1.0):
+ r"""
+ Transform a lowpass filter prototype to a bandpass filter.
+
+ Return an analog band-pass filter with center frequency `wo` and
+ bandwidth `bw` from an analog low-pass filter prototype with unity
+ cutoff frequency, using zeros, poles, and gain ('zpk') representation.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the analog filter transfer function.
+ p : array_like
+ Poles of the analog filter transfer function.
+ k : float
+ System gain of the analog filter transfer function.
+ wo : float
+ Desired passband center, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+ bw : float
+ Desired passband width, as angular frequency (e.g., rad/s).
+ Defaults to 1.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transformed band-pass filter transfer function.
+ p : ndarray
+ Poles of the transformed band-pass filter transfer function.
+ k : float
+ System gain of the transformed band-pass filter.
+
+ See Also
+ --------
+ lp2lp_zpk, lp2hp_zpk, lp2bs_zpk, bilinear
+ lp2bp
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s^2 + {\omega_0}^2}{s \cdot \mathrm{BW}}
+
+ This is the "wideband" transformation, producing a passband with
+ geometric (log frequency) symmetry about `wo`.
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ Use the 'zpk' (Zero-Pole-Gain) representation of a lowpass filter to
+ transform it to a bandpass filter with a center frequency wo and
+ bandwidth bw.
+
+ >>> from scipy.signal import lp2bp_zpk
+ >>> z = [ 5 + 2j , 5 - 2j ]
+ >>> p = [ 7 , -16 ]
+ >>> k = 0.8
+ >>> wo = 0.62
+ >>> bw = 15
+ >>> lp2bp_zpk(z, p, k, wo, bw)
+ ( array([7.49955815e+01+3.00017676e+01j, 7.49955815e+01-3.00017676e+01j,
+ 4.41850748e-03-1.76761126e-03j, 4.41850748e-03+1.76761126e-03j]),
+ array([1.04996339e+02+0.j, -1.60167736e-03+0.j, 3.66108003e-03+0.j,
+ -2.39998398e+02+0.j]), 0.8)
+ """
+ xp = array_namespace(z, p)
+
+ z, p = map(xp.asarray, (z, p))
+ z, p = xp_promote(z, p, force_floating=True, xp=xp)
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+
+ wo = float(wo)
+ bw = float(bw)
+
+ degree = _relative_degree(z, p)
+
+ # Scale poles and zeros to desired bandwidth
+ z_lp = z * bw/2
+ p_lp = p * bw/2
+
+ # Square root needs to produce complex result, not NaN
+ z_lp = xp.astype(z_lp, xp.complex128)
+ p_lp = xp.astype(p_lp, xp.complex128)
+
+ # Duplicate poles and zeros and shift from baseband to +wo and -wo
+ z_bp = xp.concat((z_lp + xp.sqrt(z_lp**2 - wo**2),
+ z_lp - xp.sqrt(z_lp**2 - wo**2)))
+ p_bp = xp.concat((p_lp + xp.sqrt(p_lp**2 - wo**2),
+ p_lp - xp.sqrt(p_lp**2 - wo**2)))
+
+ # Move degree zeros to origin, leaving degree zeros at infinity for BPF
+ z_bp = xp.concat((z_bp, xp.zeros(degree)))
+
+ # Cancel out gain change from frequency scaling
+ k_bp = k * bw**degree
+
+ return z_bp, p_bp, k_bp
+
+
+def lp2bs_zpk(z, p, k, wo=1.0, bw=1.0):
+ r"""
+ Transform a lowpass filter prototype to a bandstop filter.
+
+ Return an analog band-stop filter with center frequency `wo` and
+ stopband width `bw` from an analog low-pass filter prototype with unity
+ cutoff frequency, using zeros, poles, and gain ('zpk') representation.
+
+ Parameters
+ ----------
+ z : array_like
+ Zeros of the analog filter transfer function.
+ p : array_like
+ Poles of the analog filter transfer function.
+ k : float
+ System gain of the analog filter transfer function.
+ wo : float
+ Desired stopband center, as angular frequency (e.g., rad/s).
+ Defaults to no change.
+ bw : float
+ Desired stopband width, as angular frequency (e.g., rad/s).
+ Defaults to 1.
+
+ Returns
+ -------
+ z : ndarray
+ Zeros of the transformed band-stop filter transfer function.
+ p : ndarray
+ Poles of the transformed band-stop filter transfer function.
+ k : float
+ System gain of the transformed band-stop filter.
+
+ See Also
+ --------
+ lp2lp_zpk, lp2hp_zpk, lp2bp_zpk, bilinear
+ lp2bs
+
+ Notes
+ -----
+ This is derived from the s-plane substitution
+
+ .. math:: s \rightarrow \frac{s \cdot \mathrm{BW}}{s^2 + {\omega_0}^2}
+
+ This is the "wideband" transformation, producing a stopband with
+ geometric (log frequency) symmetry about `wo`.
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ Transform a low-pass filter represented in 'zpk' (Zero-Pole-Gain) form
+ into a bandstop filter represented in 'zpk' form, with a center frequency wo and
+ bandwidth bw.
+
+ >>> from scipy.signal import lp2bs_zpk
+ >>> z = [ ]
+ >>> p = [ 0.7 , -1 ]
+ >>> k = 9
+ >>> wo = 0.5
+ >>> bw = 10
+ >>> lp2bs_zpk(z, p, k, wo, bw)
+ ( array([0.+0.5j, 0.+0.5j, 0.-0.5j, 0.-0.5j]),
+ array([14.2681928 +0.j, -0.02506281+0.j, 0.01752149+0.j, -9.97493719+0.j]),
+ -12.857142857142858)
+ """
+ xp = array_namespace(z, p)
+
+ z, p = map(xp.asarray, (z, p))
+ z, p = xp_promote(z, p, force_floating=True, xp=xp)
+ z = xpx.atleast_nd(z, ndim=1, xp=xp)
+ p = xpx.atleast_nd(p, ndim=1, xp=xp)
+
+ wo = float(wo)
+ bw = float(bw)
+
+ degree = _relative_degree(z, p)
+
+ # Invert to a highpass filter with desired bandwidth
+ z_hp = (bw/2) / z
+ p_hp = (bw/2) / p
+
+ # Square root needs to produce complex result, not NaN
+ z_hp = xp.astype(z_hp, xp.complex128)
+ p_hp = xp.astype(p_hp, xp.complex128)
+
+ # Duplicate poles and zeros and shift from baseband to +wo and -wo
+ z_bs = xp.concat((z_hp + xp.sqrt(z_hp**2 - wo**2),
+ z_hp - xp.sqrt(z_hp**2 - wo**2)))
+ p_bs = xp.concat((p_hp + xp.sqrt(p_hp**2 - wo**2),
+ p_hp - xp.sqrt(p_hp**2 - wo**2)))
+
+ # Move any zeros that were at infinity to the center of the stopband
+ z_bs = xp.concat((z_bs, xp.full(degree, +1j*wo)))
+ z_bs = xp.concat((z_bs, xp.full(degree, -1j*wo)))
+
+ # Cancel out gain change caused by inversion
+ k_bs = k * xp.real(xp.prod(-z) / xp.prod(-p))
+
+ return z_bs, p_bs, k_bs
+
+
+def butter(N, Wn, btype='low', analog=False, output='ba', fs=None):
+ """
+ Butterworth digital and analog filter design.
+
+ Design an Nth-order digital or analog Butterworth filter and return
+ the filter coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter. For 'bandpass' and 'bandstop' filters,
+ the resulting order of the final second-order sections ('sos')
+ matrix is ``2*N``, with `N` the number of biquad sections
+ of the desired system.
+ Wn : array_like
+ The critical frequency or frequencies. For lowpass and highpass
+ filters, Wn is a scalar; for bandpass and bandstop filters,
+ Wn is a length-2 sequence.
+
+ For a Butterworth filter, this is the point at which the gain
+ drops to 1/sqrt(2) that of the passband (the "-3 dB point").
+
+ For digital filters, if `fs` is not specified, `Wn` units are
+ normalized from 0 to 1, where 1 is the Nyquist frequency (`Wn` is
+ thus in half cycles / sample and defined as 2*critical frequencies
+ / `fs`). If `fs` is specified, `Wn` is in the same units as `fs`.
+
+ For analog filters, `Wn` is an angular frequency (e.g. rad/s).
+ btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
+ The type of filter. Default is 'lowpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ output : {'ba', 'zpk', 'sos'}, optional
+ Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
+ second-order sections ('sos'). Default is 'ba' for backwards
+ compatibility, but 'sos' should be used for general-purpose filtering.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ buttord, buttap
+
+ Notes
+ -----
+ The Butterworth filter has maximally flat frequency response in the
+ passband.
+
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ If the transfer function form ``[b, a]`` is requested, numerical
+ problems can occur since the conversion between roots and
+ the polynomial coefficients is a numerically sensitive operation,
+ even for N >= 4. It is recommended to work with the SOS
+ representation.
+
+ .. warning::
+ Designing high-order and narrowband IIR filters in TF form can
+ result in unstable or incorrect filtering due to floating point
+ numerical precision issues. Consider inspecting output filter
+ characteristics `freqz` or designing the filters with second-order
+ sections via ``output='sos'``.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ Examples
+ --------
+ Design an analog filter and plot its frequency response, showing the
+ critical points:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> b, a = signal.butter(4, 100, 'low', analog=True)
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Butterworth filter frequency response')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.show()
+
+ Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz
+
+ >>> t = np.linspace(0, 1, 1000, False) # 1 second
+ >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)
+ >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
+ >>> ax1.plot(t, sig)
+ >>> ax1.set_title('10 Hz and 20 Hz sinusoids')
+ >>> ax1.axis([0, 1, -2, 2])
+
+ Design a digital high-pass filter at 15 Hz to remove the 10 Hz tone, and
+ apply it to the signal. (It's recommended to use second-order sections
+ format when filtering, to avoid numerical error with transfer function
+ (``ba``) format):
+
+ >>> sos = signal.butter(10, 15, 'hp', fs=1000, output='sos')
+ >>> filtered = signal.sosfilt(sos, sig)
+ >>> ax2.plot(t, filtered)
+ >>> ax2.set_title('After 15 Hz high-pass filter')
+ >>> ax2.axis([0, 1, -2, 2])
+ >>> ax2.set_xlabel('Time [s]')
+ >>> plt.tight_layout()
+ >>> plt.show()
+ """
+ return iirfilter(N, Wn, btype=btype, analog=analog,
+ output=output, ftype='butter', fs=fs)
+
+
+def cheby1(N, rp, Wn, btype='low', analog=False, output='ba', fs=None):
+ """
+ Chebyshev type I digital and analog filter design.
+
+ Design an Nth-order digital or analog Chebyshev type I filter and
+ return the filter coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ rp : float
+ The maximum ripple allowed below unity gain in the passband.
+ Specified in decibels, as a positive number.
+ Wn : array_like
+ A scalar or length-2 sequence giving the critical frequencies.
+ For Type I filters, this is the point in the transition band at which
+ the gain first drops below -`rp`.
+
+ For digital filters, `Wn` are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`Wn` is thus in
+ half-cycles / sample.)
+
+ For analog filters, `Wn` is an angular frequency (e.g., rad/s).
+ btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
+ The type of filter. Default is 'lowpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ output : {'ba', 'zpk', 'sos'}, optional
+ Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
+ second-order sections ('sos'). Default is 'ba' for backwards
+ compatibility, but 'sos' should be used for general-purpose filtering.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ cheb1ord, cheb1ap
+
+ Notes
+ -----
+ The Chebyshev type I filter maximizes the rate of cutoff between the
+ frequency response's passband and stopband, at the expense of ripple in
+ the passband and increased ringing in the step response.
+
+ Type I filters roll off faster than Type II (`cheby2`), but Type II
+ filters do not have any ripple in the passband.
+
+ The equiripple passband has N maxima or minima (for example, a
+ 5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is
+ unity for odd-order filters, or -rp dB for even-order filters.
+
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ Examples
+ --------
+ Design an analog filter and plot its frequency response, showing the
+ critical points:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> b, a = signal.cheby1(4, 5, 100, 'low', analog=True)
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Chebyshev Type I frequency response (rp=5)')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.axhline(-5, color='green') # rp
+ >>> plt.show()
+
+ Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz
+
+ >>> t = np.linspace(0, 1, 1000, False) # 1 second
+ >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)
+ >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
+ >>> ax1.plot(t, sig)
+ >>> ax1.set_title('10 Hz and 20 Hz sinusoids')
+ >>> ax1.axis([0, 1, -2, 2])
+
+ Design a digital high-pass filter at 15 Hz to remove the 10 Hz tone, and
+ apply it to the signal. (It's recommended to use second-order sections
+ format when filtering, to avoid numerical error with transfer function
+ (``ba``) format):
+
+ >>> sos = signal.cheby1(10, 1, 15, 'hp', fs=1000, output='sos')
+ >>> filtered = signal.sosfilt(sos, sig)
+ >>> ax2.plot(t, filtered)
+ >>> ax2.set_title('After 15 Hz high-pass filter')
+ >>> ax2.axis([0, 1, -2, 2])
+ >>> ax2.set_xlabel('Time [s]')
+ >>> plt.tight_layout()
+ >>> plt.show()
+ """
+ return iirfilter(N, Wn, rp=rp, btype=btype, analog=analog,
+ output=output, ftype='cheby1', fs=fs)
+
+
+def cheby2(N, rs, Wn, btype='low', analog=False, output='ba', fs=None):
+ """
+ Chebyshev type II digital and analog filter design.
+
+ Design an Nth-order digital or analog Chebyshev type II filter and
+ return the filter coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ rs : float
+ The minimum attenuation required in the stop band.
+ Specified in decibels, as a positive number.
+ Wn : array_like
+ A scalar or length-2 sequence giving the critical frequencies.
+ For Type II filters, this is the point in the transition band at which
+ the gain first reaches -`rs`.
+
+ For digital filters, `Wn` are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`Wn` is thus in
+ half-cycles / sample.)
+
+ For analog filters, `Wn` is an angular frequency (e.g., rad/s).
+ btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
+ The type of filter. Default is 'lowpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ output : {'ba', 'zpk', 'sos'}, optional
+ Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
+ second-order sections ('sos'). Default is 'ba' for backwards
+ compatibility, but 'sos' should be used for general-purpose filtering.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ cheb2ord, cheb2ap
+
+ Notes
+ -----
+ The Chebyshev type II filter maximizes the rate of cutoff between the
+ frequency response's passband and stopband, at the expense of ripple in
+ the stopband and increased ringing in the step response.
+
+ Type II filters do not roll off as fast as Type I (`cheby1`).
+
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ Examples
+ --------
+ Design an analog filter and plot its frequency response, showing the
+ critical points:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> b, a = signal.cheby2(4, 40, 100, 'low', analog=True)
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Chebyshev Type II frequency response (rs=40)')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.axhline(-40, color='green') # rs
+ >>> plt.show()
+
+ Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz
+
+ >>> t = np.linspace(0, 1, 1000, False) # 1 second
+ >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)
+ >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
+ >>> ax1.plot(t, sig)
+ >>> ax1.set_title('10 Hz and 20 Hz sinusoids')
+ >>> ax1.axis([0, 1, -2, 2])
+
+ Design a digital high-pass filter at 17 Hz to remove the 10 Hz tone, and
+ apply it to the signal. (It's recommended to use second-order sections
+ format when filtering, to avoid numerical error with transfer function
+ (``ba``) format):
+
+ >>> sos = signal.cheby2(12, 20, 17, 'hp', fs=1000, output='sos')
+ >>> filtered = signal.sosfilt(sos, sig)
+ >>> ax2.plot(t, filtered)
+ >>> ax2.set_title('After 17 Hz high-pass filter')
+ >>> ax2.axis([0, 1, -2, 2])
+ >>> ax2.set_xlabel('Time [s]')
+ >>> plt.show()
+ """
+ return iirfilter(N, Wn, rs=rs, btype=btype, analog=analog,
+ output=output, ftype='cheby2', fs=fs)
+
+
+def ellip(N, rp, rs, Wn, btype='low', analog=False, output='ba', fs=None):
+ """
+ Elliptic (Cauer) digital and analog filter design.
+
+ Design an Nth-order digital or analog elliptic filter and return
+ the filter coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ rp : float
+ The maximum ripple allowed below unity gain in the passband.
+ Specified in decibels, as a positive number.
+ rs : float
+ The minimum attenuation required in the stop band.
+ Specified in decibels, as a positive number.
+ Wn : array_like
+ A scalar or length-2 sequence giving the critical frequencies.
+ For elliptic filters, this is the point in the transition band at
+ which the gain first drops below -`rp`.
+
+ For digital filters, `Wn` are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`Wn` is thus in
+ half-cycles / sample.)
+
+ For analog filters, `Wn` is an angular frequency (e.g., rad/s).
+ btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
+ The type of filter. Default is 'lowpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ output : {'ba', 'zpk', 'sos'}, optional
+ Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
+ second-order sections ('sos'). Default is 'ba' for backwards
+ compatibility, but 'sos' should be used for general-purpose filtering.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ See Also
+ --------
+ ellipord, ellipap
+
+ Notes
+ -----
+ Also known as Cauer or Zolotarev filters, the elliptical filter maximizes
+ the rate of transition between the frequency response's passband and
+ stopband, at the expense of ripple in both, and increased ringing in the
+ step response.
+
+ As `rp` approaches 0, the elliptical filter becomes a Chebyshev
+ type II filter (`cheby2`). As `rs` approaches 0, it becomes a Chebyshev
+ type I filter (`cheby1`). As both approach 0, it becomes a Butterworth
+ filter (`butter`).
+
+ The equiripple passband has N maxima or minima (for example, a
+ 5th-order filter has 3 maxima and 2 minima). Consequently, the DC gain is
+ unity for odd-order filters, or -rp dB for even-order filters.
+
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ Examples
+ --------
+ Design an analog filter and plot its frequency response, showing the
+ critical points:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> b, a = signal.ellip(4, 5, 40, 100, 'low', analog=True)
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Elliptic filter frequency response (rp=5, rs=40)')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.axhline(-40, color='green') # rs
+ >>> plt.axhline(-5, color='green') # rp
+ >>> plt.show()
+
+ Generate a signal made up of 10 Hz and 20 Hz, sampled at 1 kHz
+
+ >>> t = np.linspace(0, 1, 1000, False) # 1 second
+ >>> sig = np.sin(2*np.pi*10*t) + np.sin(2*np.pi*20*t)
+ >>> fig, (ax1, ax2) = plt.subplots(2, 1, sharex=True)
+ >>> ax1.plot(t, sig)
+ >>> ax1.set_title('10 Hz and 20 Hz sinusoids')
+ >>> ax1.axis([0, 1, -2, 2])
+
+ Design a digital high-pass filter at 17 Hz to remove the 10 Hz tone, and
+ apply it to the signal. (It's recommended to use second-order sections
+ format when filtering, to avoid numerical error with transfer function
+ (``ba``) format):
+
+ >>> sos = signal.ellip(8, 1, 100, 17, 'hp', fs=1000, output='sos')
+ >>> filtered = signal.sosfilt(sos, sig)
+ >>> ax2.plot(t, filtered)
+ >>> ax2.set_title('After 17 Hz high-pass filter')
+ >>> ax2.axis([0, 1, -2, 2])
+ >>> ax2.set_xlabel('Time [s]')
+ >>> plt.tight_layout()
+ >>> plt.show()
+ """
+ return iirfilter(N, Wn, rs=rs, rp=rp, btype=btype, analog=analog,
+ output=output, ftype='elliptic', fs=fs)
+
+
+def bessel(N, Wn, btype='low', analog=False, output='ba', norm='phase',
+ fs=None):
+ """
+ Bessel/Thomson digital and analog filter design.
+
+ Design an Nth-order digital or analog Bessel filter and return the
+ filter coefficients.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ Wn : array_like
+ A scalar or length-2 sequence giving the critical frequencies (defined
+ by the `norm` parameter).
+ For analog filters, `Wn` is an angular frequency (e.g., rad/s).
+
+ For digital filters, `Wn` are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`Wn` is thus in
+ half-cycles / sample.)
+ btype : {'lowpass', 'highpass', 'bandpass', 'bandstop'}, optional
+ The type of filter. Default is 'lowpass'.
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned. (See Notes.)
+ output : {'ba', 'zpk', 'sos'}, optional
+ Type of output: numerator/denominator ('ba'), pole-zero ('zpk'), or
+ second-order sections ('sos'). Default is 'ba'.
+ norm : {'phase', 'delay', 'mag'}, optional
+ Critical frequency normalization:
+
+ ``phase``
+ The filter is normalized such that the phase response reaches its
+ midpoint at angular (e.g. rad/s) frequency `Wn`. This happens for
+ both low-pass and high-pass filters, so this is the
+ "phase-matched" case.
+
+ The magnitude response asymptotes are the same as a Butterworth
+ filter of the same order with a cutoff of `Wn`.
+
+ This is the default, and matches MATLAB's implementation.
+
+ ``delay``
+ The filter is normalized such that the group delay in the passband
+ is 1/`Wn` (e.g., seconds). This is the "natural" type obtained by
+ solving Bessel polynomials.
+
+ ``mag``
+ The filter is normalized such that the gain magnitude is -3 dB at
+ angular frequency `Wn`.
+
+ .. versionadded:: 0.18.0
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (`b`) and denominator (`a`) polynomials of the IIR filter.
+ Only returned if ``output='ba'``.
+ z, p, k : ndarray, ndarray, float
+ Zeros, poles, and system gain of the IIR filter transfer
+ function. Only returned if ``output='zpk'``.
+ sos : ndarray
+ Second-order sections representation of the IIR filter.
+ Only returned if ``output='sos'``.
+
+ Notes
+ -----
+ Also known as a Thomson filter, the analog Bessel filter has maximally
+ flat group delay and maximally linear phase response, with very little
+ ringing in the step response. [1]_
+
+ The Bessel is inherently an analog filter. This function generates digital
+ Bessel filters using the bilinear transform, which does not preserve the
+ phase response of the analog filter. As such, it is only approximately
+ correct at frequencies below about fs/4. To get maximally-flat group
+ delay at higher frequencies, the analog Bessel filter must be transformed
+ using phase-preserving techniques.
+
+ See `besselap` for implementation details and references.
+
+ The ``'sos'`` output parameter was added in 0.16.0.
+
+ The current behavior is for ``ndarray`` outputs to have 64 bit precision
+ (``float64`` or ``complex128``) regardless of the dtype of `Wn` but
+ outputs may respect the dtype of `Wn` in a future version.
+
+ References
+ ----------
+ .. [1] Thomson, W.E., "Delay Networks having Maximally Flat Frequency
+ Characteristics", Proceedings of the Institution of Electrical
+ Engineers, Part III, November 1949, Vol. 96, No. 44, pp. 487-490.
+
+ Examples
+ --------
+ Plot the phase-normalized frequency response, showing the relationship
+ to the Butterworth's cutoff frequency (green):
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> b, a = signal.butter(4, 100, 'low', analog=True)
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(np.abs(h)), color='silver', ls='dashed')
+ >>> b, a = signal.bessel(4, 100, 'low', analog=True, norm='phase')
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(np.abs(h)))
+ >>> plt.title('Bessel filter magnitude response (with Butterworth)')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.show()
+
+ and the phase midpoint:
+
+ >>> plt.figure()
+ >>> plt.semilogx(w, np.unwrap(np.angle(h)))
+ >>> plt.axvline(100, color='green') # cutoff frequency
+ >>> plt.axhline(-np.pi, color='red') # phase midpoint
+ >>> plt.title('Bessel filter phase response')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Phase [rad]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.show()
+
+ Plot the magnitude-normalized frequency response, showing the -3 dB cutoff:
+
+ >>> b, a = signal.bessel(3, 10, 'low', analog=True, norm='mag')
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.semilogx(w, 20 * np.log10(np.abs(h)))
+ >>> plt.axhline(-3, color='red') # -3 dB magnitude
+ >>> plt.axvline(10, color='green') # cutoff frequency
+ >>> plt.title('Amplitude-normalized Bessel filter frequency response')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.show()
+
+ Plot the delay-normalized filter, showing the maximally-flat group delay
+ at 0.1 seconds:
+
+ >>> b, a = signal.bessel(5, 1/0.1, 'low', analog=True, norm='delay')
+ >>> w, h = signal.freqs(b, a)
+ >>> plt.figure()
+ >>> plt.semilogx(w[1:], -np.diff(np.unwrap(np.angle(h)))/np.diff(w))
+ >>> plt.axhline(0.1, color='red') # 0.1 seconds group delay
+ >>> plt.title('Bessel filter group delay')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Group delay [s]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.show()
+
+ """
+ return iirfilter(N, Wn, btype=btype, analog=analog,
+ output=output, ftype='bessel_'+norm, fs=fs)
+
+
+def maxflat():
+ pass
+
+
+def yulewalk():
+ pass
+
+
+def band_stop_obj(wp, ind, passb, stopb, gpass, gstop, type):
+ """
+ Band Stop Objective Function for order minimization.
+
+ Returns the non-integer order for an analog band stop filter.
+
+ Parameters
+ ----------
+ wp : scalar
+ Edge of passband `passb`.
+ ind : int, {0, 1}
+ Index specifying which `passb` edge to vary (0 or 1).
+ passb : ndarray
+ Two element sequence of fixed passband edges.
+ stopb : ndarray
+ Two element sequence of fixed stopband edges.
+ gstop : float
+ Amount of attenuation in stopband in dB.
+ gpass : float
+ Amount of ripple in the passband in dB.
+ type : {'butter', 'cheby', 'ellip'}
+ Type of filter.
+
+ Returns
+ -------
+ n : scalar
+ Filter order (possibly non-integer).
+
+ Notes
+ -----
+ Band-stop filters are used in applications where certain frequency
+ components need to be blocked while others are allowed; for instance,
+ removing noise at specific frequencies while allowing the desired signal
+ to pass through. The order of a filter often determines its complexity and
+ accuracy. Determining the right order can be a challenge. This function
+ aims to provide an appropriate order for an analog band stop filter.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> from scipy.signal import band_stop_obj
+ >>> wp = 2
+ >>> ind = 1
+ >>> passb = np.array([1, 3])
+ >>> stopb = np.array([0.5, 4])
+ >>> gstop = 30
+ >>> gpass = 3
+ >>> filter_type = 'butter'
+ >>> band_stop_obj(wp, ind, passb, stopb, gpass, gstop, filter_type)
+ np.float64(-2.758504160760643)
+
+ """
+
+ _validate_gpass_gstop(gpass, gstop)
+
+ passbC = passb.copy()
+ passbC[ind] = wp
+ nat = (stopb * (passbC[0] - passbC[1]) /
+ (stopb ** 2 - passbC[0] * passbC[1]))
+ nat = min(abs(nat))
+
+ if type == 'butter':
+ GSTOP = 10 ** (0.1 * abs(gstop))
+ GPASS = 10 ** (0.1 * abs(gpass))
+ n = (np.log10((GSTOP - 1.0) / (GPASS - 1.0)) / (2 * np.log10(nat)))
+ elif type == 'cheby':
+ GSTOP = 10 ** (0.1 * abs(gstop))
+ GPASS = 10 ** (0.1 * abs(gpass))
+ n = np.arccosh(np.sqrt((GSTOP - 1.0) / (GPASS - 1.0))) / np.arccosh(nat)
+ elif type == 'ellip':
+ GSTOP = 10 ** (0.1 * gstop)
+ GPASS = 10 ** (0.1 * gpass)
+ arg1 = np.sqrt((GPASS - 1.0) / (GSTOP - 1.0))
+ arg0 = 1.0 / nat
+ d0 = special.ellipk([arg0 ** 2, 1 - arg0 ** 2])
+ d1 = special.ellipk([arg1 ** 2, 1 - arg1 ** 2])
+ n = (d0[0] * d1[1] / (d0[1] * d1[0]))
+ else:
+ raise ValueError(f"Incorrect type: {type}")
+ return n
+
+
+def _pre_warp(wp, ws, analog, *, xp):
+ # Pre-warp frequencies for digital filter design
+ if not analog:
+ passb = xp.tan(xp.pi * wp / 2.0)
+ stopb = xp.tan(xp.pi * ws / 2.0)
+ else:
+ passb, stopb = wp, ws
+ return passb, stopb
+
+
+def _validate_wp_ws(wp, ws, fs, analog, *, xp):
+ wp = xpx.atleast_nd(wp, ndim=1, xp=xp)
+ ws = xpx.atleast_nd(ws, ndim=1, xp=xp)
+ wp, ws = xp_promote(wp, ws, force_floating=True, xp=xp)
+
+ if fs is not None:
+ if analog:
+ raise ValueError("fs cannot be specified for an analog filter")
+ wp = 2 * wp / fs
+ ws = 2 * ws / fs
+
+ filter_type = 2 * (wp.shape[0] - 1) + 1
+ if wp[0] >= ws[0]:
+ filter_type += 1
+
+ return wp, ws, filter_type
+
+
+def _find_nat_freq(stopb, passb, gpass, gstop, filter_type, filter_kind, *, xp):
+ if filter_type == 1: # low
+ nat = stopb / passb
+ elif filter_type == 2: # high
+ nat = passb / stopb
+ elif filter_type == 3: # stop
+
+ passb, stopb = np.asarray(passb), np.asarray(stopb) # XXX fminbound array API
+ wp0 = optimize.fminbound(band_stop_obj, passb[0], stopb[0] - 1e-12,
+ args=(0, passb, stopb, gpass, gstop,
+ filter_kind),
+ disp=0)
+ wp1 = optimize.fminbound(band_stop_obj, stopb[1] + 1e-12, passb[1],
+ args=(1, passb, stopb, gpass, gstop,
+ filter_kind),
+ disp=0)
+ passb = [float(wp0), float(wp1)]
+ passb, stopb = xp.asarray(passb), xp.asarray(stopb)
+ nat = ((stopb * (passb[0] - passb[1])) /
+ (stopb ** 2 - passb[0] * passb[1]))
+ elif filter_type == 4: # pass
+ nat = ((stopb ** 2 - passb[0] * passb[1]) /
+ (stopb * (passb[0] - passb[1])))
+ else:
+ raise ValueError(f"should not happen: {filter_type =}.")
+
+ nat = xp.min(xp.abs(nat))
+ return nat, passb
+
+
+def _postprocess_wn(WN, analog, fs, *, xp):
+ wn = WN if analog else xp.atan(WN) * 2.0 / xp.pi
+ if wn.shape[0] == 1:
+ wn = wn[0]
+ if fs is not None:
+ wn = wn * fs / 2
+ return wn
+
+
+def buttord(wp, ws, gpass, gstop, analog=False, fs=None):
+ """Butterworth filter order selection.
+
+ Return the order of the lowest order digital or analog Butterworth filter
+ that loses no more than `gpass` dB in the passband and has at least
+ `gstop` dB attenuation in the stopband.
+
+ Parameters
+ ----------
+ wp, ws : float or array-like
+ Passband and stopband edge frequencies.
+
+ For digital filters, these are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
+ half-cycles / sample.) For example:
+
+ - Lowpass: wp = 0.2, ws = 0.3
+ - Highpass: wp = 0.3, ws = 0.2
+ - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
+ - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
+
+ For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s).
+ gpass : float
+ The maximum loss in the passband (dB).
+ gstop : float
+ The minimum attenuation in the stopband (dB).
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ ord : int
+ The lowest order for a Butterworth filter which meets specs.
+ wn : ndarray or float
+ The Butterworth natural frequency (i.e. the "3dB frequency"). Should
+ be used with `butter` to give filter results. If `fs` is specified,
+ this is in the same units, and `fs` must also be passed to `butter`.
+
+ See Also
+ --------
+ butter : Filter design using order and critical points
+ cheb1ord : Find order and critical points from passband and stopband spec
+ cheb2ord, ellipord
+ iirfilter : General filter design using order and critical frequencies
+ iirdesign : General filter design using passband and stopband spec
+
+ Examples
+ --------
+ Design an analog bandpass filter with passband within 3 dB from 20 to
+ 50 rad/s, while rejecting at least -40 dB below 14 and above 60 rad/s.
+ Plot its frequency response, showing the passband and stopband
+ constraints in gray.
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> N, Wn = signal.buttord([20, 50], [14, 60], 3, 40, True)
+ >>> b, a = signal.butter(N, Wn, 'band', True)
+ >>> w, h = signal.freqs(b, a, np.logspace(1, 2, 500))
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Butterworth bandpass filter fit to constraints')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.fill([1, 14, 14, 1], [-40, -40, 99, 99], '0.9', lw=0) # stop
+ >>> plt.fill([20, 20, 50, 50], [-99, -3, -3, -99], '0.9', lw=0) # pass
+ >>> plt.fill([60, 60, 1e9, 1e9], [99, -40, -40, 99], '0.9', lw=0) # stop
+ >>> plt.axis([10, 100, -60, 3])
+ >>> plt.show()
+
+ """
+ xp = array_namespace(wp, ws)
+ wp, ws = map(xp.asarray, (wp, ws))
+
+ _validate_gpass_gstop(gpass, gstop)
+ fs = _validate_fs(fs, allow_none=True)
+ wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog, xp=xp)
+ passb, stopb = _pre_warp(wp, ws, analog, xp=xp)
+ nat, passb = _find_nat_freq(
+ stopb, passb, gpass, gstop, filter_type, 'butter', xp=xp
+ )
+
+ GSTOP = 10 ** (0.1 * builtins.abs(gstop))
+ GPASS = 10 ** (0.1 * builtins.abs(gpass))
+ ord = int(
+ math.ceil(math.log10((GSTOP - 1.0) / (GPASS - 1.0)) / (2 * math.log10(nat)))
+ )
+
+ # Find the Butterworth natural frequency WN (or the "3dB" frequency")
+ # to give exactly gpass at passb.
+ try:
+ W0 = (GPASS - 1.0) ** (-1.0 / (2.0 * ord))
+ except ZeroDivisionError:
+ W0 = 1.0
+ warnings.warn("Order is zero...check input parameters.",
+ RuntimeWarning, stacklevel=2)
+
+ # now convert this frequency back from lowpass prototype
+ # to the original analog filter
+
+ if filter_type == 1: # low
+ WN = W0 * passb
+ elif filter_type == 2: # high
+ WN = passb / W0
+ elif filter_type == 3: # stop
+ discr = xp.sqrt((passb[1] - passb[0]) ** 2 +
+ 4 * W0 ** 2 * passb[0] * passb[1])
+ WN0 = ((passb[1] - passb[0]) + discr) / (2 * W0)
+ WN1 = ((passb[1] - passb[0]) - discr) / (2 * W0)
+ WN = xp.asarray([float(WN0), float(WN1)])
+ WN = xp.sort(xp.abs(WN))
+
+ elif filter_type == 4: # pass
+ W0 = xp.asarray([-W0, W0], dtype=xp.float64)
+ WN = (-W0 * (passb[1] - passb[0]) / 2.0 +
+ xp.sqrt(W0 ** 2 / 4.0 * (passb[1] - passb[0]) ** 2 +
+ passb[0] * passb[1]))
+ WN = xp.sort(xp.abs(WN))
+ else:
+ raise ValueError(f"Bad type: {filter_type}")
+
+ wn = _postprocess_wn(WN, analog, fs, xp=xp)
+
+ return ord, wn
+
+
+def cheb1ord(wp, ws, gpass, gstop, analog=False, fs=None):
+ """Chebyshev type I filter order selection.
+
+ Return the order of the lowest order digital or analog Chebyshev Type I
+ filter that loses no more than `gpass` dB in the passband and has at
+ least `gstop` dB attenuation in the stopband.
+
+ Parameters
+ ----------
+ wp, ws : float
+ Passband and stopband edge frequencies.
+
+ For digital filters, these are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
+ half-cycles / sample.) For example:
+
+ - Lowpass: wp = 0.2, ws = 0.3
+ - Highpass: wp = 0.3, ws = 0.2
+ - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
+ - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
+
+ For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s).
+ gpass : float
+ The maximum loss in the passband (dB).
+ gstop : float
+ The minimum attenuation in the stopband (dB).
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ ord : int
+ The lowest order for a Chebyshev type I filter that meets specs.
+ wn : ndarray or float
+ The Chebyshev natural frequency (the "3dB frequency") for use with
+ `cheby1` to give filter results. If `fs` is specified,
+ this is in the same units, and `fs` must also be passed to `cheby1`.
+
+ See Also
+ --------
+ cheby1 : Filter design using order and critical points
+ buttord : Find order and critical points from passband and stopband spec
+ cheb2ord, ellipord
+ iirfilter : General filter design using order and critical frequencies
+ iirdesign : General filter design using passband and stopband spec
+
+ Examples
+ --------
+ Design a digital lowpass filter such that the passband is within 3 dB up
+ to 0.2*(fs/2), while rejecting at least -40 dB above 0.3*(fs/2). Plot its
+ frequency response, showing the passband and stopband constraints in gray.
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> N, Wn = signal.cheb1ord(0.2, 0.3, 3, 40)
+ >>> b, a = signal.cheby1(N, 3, Wn, 'low')
+ >>> w, h = signal.freqz(b, a)
+ >>> plt.semilogx(w / np.pi, 20 * np.log10(abs(h)))
+ >>> plt.title('Chebyshev I lowpass filter fit to constraints')
+ >>> plt.xlabel('Normalized frequency')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.fill([.01, 0.2, 0.2, .01], [-3, -3, -99, -99], '0.9', lw=0) # stop
+ >>> plt.fill([0.3, 0.3, 2, 2], [ 9, -40, -40, 9], '0.9', lw=0) # pass
+ >>> plt.axis([0.08, 1, -60, 3])
+ >>> plt.show()
+
+ """
+ xp = array_namespace(wp, ws)
+ wp, ws = map(xp.asarray, (wp, ws))
+
+ fs = _validate_fs(fs, allow_none=True)
+ _validate_gpass_gstop(gpass, gstop)
+ wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog, xp=xp)
+ passb, stopb = _pre_warp(wp, ws, analog, xp=xp)
+ nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'cheby', xp=xp)
+
+ GSTOP = 10 ** (0.1 * builtins.abs(gstop))
+ GPASS = 10 ** (0.1 * builtins.abs(gpass))
+ v_pass_stop = math.acosh(math.sqrt((GSTOP - 1.0) / (GPASS - 1.0)))
+ ord = int(xp.ceil(v_pass_stop / xp.acosh(nat)))
+
+ # Natural frequencies are just the passband edges
+ wn = _postprocess_wn(passb, analog, fs, xp=xp)
+
+ return ord, wn
+
+
+def cheb2ord(wp, ws, gpass, gstop, analog=False, fs=None):
+ """Chebyshev type II filter order selection.
+
+ Return the order of the lowest order digital or analog Chebyshev Type II
+ filter that loses no more than `gpass` dB in the passband and has at least
+ `gstop` dB attenuation in the stopband.
+
+ Parameters
+ ----------
+ wp, ws : float
+ Passband and stopband edge frequencies.
+
+ For digital filters, these are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
+ half-cycles / sample.) For example:
+
+ - Lowpass: wp = 0.2, ws = 0.3
+ - Highpass: wp = 0.3, ws = 0.2
+ - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
+ - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
+
+ For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s).
+ gpass : float
+ The maximum loss in the passband (dB).
+ gstop : float
+ The minimum attenuation in the stopband (dB).
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ ord : int
+ The lowest order for a Chebyshev type II filter that meets specs.
+ wn : ndarray or float
+ The Chebyshev natural frequency (the "3dB frequency") for use with
+ `cheby2` to give filter results. If `fs` is specified,
+ this is in the same units, and `fs` must also be passed to `cheby2`.
+
+ See Also
+ --------
+ cheby2 : Filter design using order and critical points
+ buttord : Find order and critical points from passband and stopband spec
+ cheb1ord, ellipord
+ iirfilter : General filter design using order and critical frequencies
+ iirdesign : General filter design using passband and stopband spec
+
+ Examples
+ --------
+ Design a digital bandstop filter which rejects -60 dB from 0.2*(fs/2) to
+ 0.5*(fs/2), while staying within 3 dB below 0.1*(fs/2) or above
+ 0.6*(fs/2). Plot its frequency response, showing the passband and
+ stopband constraints in gray.
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> N, Wn = signal.cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60)
+ >>> b, a = signal.cheby2(N, 60, Wn, 'stop')
+ >>> w, h = signal.freqz(b, a)
+ >>> plt.semilogx(w / np.pi, 20 * np.log10(abs(h)))
+ >>> plt.title('Chebyshev II bandstop filter fit to constraints')
+ >>> plt.xlabel('Normalized frequency')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.fill([.01, .1, .1, .01], [-3, -3, -99, -99], '0.9', lw=0) # stop
+ >>> plt.fill([.2, .2, .5, .5], [ 9, -60, -60, 9], '0.9', lw=0) # pass
+ >>> plt.fill([.6, .6, 2, 2], [-99, -3, -3, -99], '0.9', lw=0) # stop
+ >>> plt.axis([0.06, 1, -80, 3])
+ >>> plt.show()
+
+ """
+ xp = array_namespace(wp, ws)
+ wp, ws = map(xp.asarray, (wp, ws))
+
+ fs = _validate_fs(fs, allow_none=True)
+ _validate_gpass_gstop(gpass, gstop)
+ wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog, xp=xp)
+ passb, stopb = _pre_warp(wp, ws, analog, xp=xp)
+ nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'cheby', xp=xp)
+
+ GSTOP = 10 ** (0.1 * builtins.abs(gstop))
+ GPASS = 10 ** (0.1 * builtins.abs(gpass))
+ v_pass_stop = math.acosh(math.sqrt((GSTOP - 1.0) / (GPASS - 1.0)))
+ ord = int(xp.ceil(v_pass_stop / xp.acosh(nat)))
+
+ # Find frequency where analog response is -gpass dB.
+ # Then convert back from low-pass prototype to the original filter.
+
+ new_freq = math.cosh(1.0 / ord * v_pass_stop)
+ new_freq = 1.0 / new_freq
+
+ if filter_type == 1:
+ nat = passb / new_freq
+ elif filter_type == 2:
+ nat = passb * new_freq
+ elif filter_type == 3:
+ nat0 = (new_freq / 2.0 * (passb[0] - passb[1]) +
+ math.sqrt(new_freq ** 2 * (passb[1] - passb[0]) ** 2 / 4.0 +
+ passb[1] * passb[0]))
+ nat1 = passb[1] * passb[0] / nat0
+ nat = xp.asarray([float(nat0), float(nat1)])
+ elif filter_type == 4:
+ nat0 = (1.0 / (2.0 * new_freq) * (passb[0] - passb[1]) +
+ math.sqrt((passb[1] - passb[0]) ** 2 / (4.0 * new_freq ** 2) +
+ passb[1] * passb[0]))
+ nat1 = passb[0] * passb[1] / nat0
+ nat = xp.asarray([float(nat0), float(nat1)])
+
+ wn = _postprocess_wn(nat, analog, fs, xp=xp)
+
+ return ord, wn
+
+
+_POW10_LOG10 = math.log(10)
+
+
+def _pow10m1(x):
+ """10 ** x - 1 for x near 0"""
+ return math.expm1(_POW10_LOG10 * x)
+
+
+def ellipord(wp, ws, gpass, gstop, analog=False, fs=None):
+ """Elliptic (Cauer) filter order selection.
+
+ Return the order of the lowest order digital or analog elliptic filter
+ that loses no more than `gpass` dB in the passband and has at least
+ `gstop` dB attenuation in the stopband.
+
+ Parameters
+ ----------
+ wp, ws : float
+ Passband and stopband edge frequencies.
+
+ For digital filters, these are in the same units as `fs`. By default,
+ `fs` is 2 half-cycles/sample, so these are normalized from 0 to 1,
+ where 1 is the Nyquist frequency. (`wp` and `ws` are thus in
+ half-cycles / sample.) For example:
+
+ - Lowpass: wp = 0.2, ws = 0.3
+ - Highpass: wp = 0.3, ws = 0.2
+ - Bandpass: wp = [0.2, 0.5], ws = [0.1, 0.6]
+ - Bandstop: wp = [0.1, 0.6], ws = [0.2, 0.5]
+
+ For analog filters, `wp` and `ws` are angular frequencies (e.g., rad/s).
+ gpass : float
+ The maximum loss in the passband (dB).
+ gstop : float
+ The minimum attenuation in the stopband (dB).
+ analog : bool, optional
+ When True, return an analog filter, otherwise a digital filter is
+ returned.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ ord : int
+ The lowest order for an Elliptic (Cauer) filter that meets specs.
+ wn : ndarray or float
+ The Chebyshev natural frequency (the "3dB frequency") for use with
+ `ellip` to give filter results. If `fs` is specified,
+ this is in the same units, and `fs` must also be passed to `ellip`.
+
+ See Also
+ --------
+ ellip : Filter design using order and critical points
+ buttord : Find order and critical points from passband and stopband spec
+ cheb1ord, cheb2ord
+ iirfilter : General filter design using order and critical frequencies
+ iirdesign : General filter design using passband and stopband spec
+
+ Examples
+ --------
+ Design an analog highpass filter such that the passband is within 3 dB
+ above 30 rad/s, while rejecting -60 dB at 10 rad/s. Plot its
+ frequency response, showing the passband and stopband constraints in gray.
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> N, Wn = signal.ellipord(30, 10, 3, 60, True)
+ >>> b, a = signal.ellip(N, 3, 60, Wn, 'high', True)
+ >>> w, h = signal.freqs(b, a, np.logspace(0, 3, 500))
+ >>> plt.semilogx(w, 20 * np.log10(abs(h)))
+ >>> plt.title('Elliptical highpass filter fit to constraints')
+ >>> plt.xlabel('Frequency [rad/s]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.fill([.1, 10, 10, .1], [1e4, 1e4, -60, -60], '0.9', lw=0) # stop
+ >>> plt.fill([30, 30, 1e9, 1e9], [-99, -3, -3, -99], '0.9', lw=0) # pass
+ >>> plt.axis([1, 300, -80, 3])
+ >>> plt.show()
+
+ """
+ xp = array_namespace(wp, ws)
+ wp, ws = map(xp.asarray, (wp, ws))
+
+ fs = _validate_fs(fs, allow_none=True)
+ _validate_gpass_gstop(gpass, gstop)
+ wp, ws, filter_type = _validate_wp_ws(wp, ws, fs, analog, xp=xp)
+ passb, stopb = _pre_warp(wp, ws, analog, xp=xp)
+ nat, passb = _find_nat_freq(stopb, passb, gpass, gstop, filter_type, 'ellip', xp=xp)
+
+ arg1_sq = _pow10m1(0.1 * gpass) / _pow10m1(0.1 * gstop)
+ arg0 = 1.0 / nat
+ arg0 = np.asarray(arg0)
+ d0 = special.ellipk(arg0 ** 2), special.ellipkm1(arg0 ** 2)
+ d1 = special.ellipk(arg1_sq), special.ellipkm1(arg1_sq)
+ ord = int(np.ceil(d0[0] * d1[1] / (d0[1] * d1[0])))
+
+ wn = _postprocess_wn(passb, analog, fs, xp=xp)
+
+ return ord, wn
+
+
+def buttap(N, *, xp=None, device=None):
+ """Return (z,p,k) for analog prototype of Nth-order Butterworth filter.
+
+ The filter will have an angular (e.g., rad/s) cutoff frequency of 1.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ z : ndarray[float64]
+ Zeros of the transfer function. Is always an empty array.
+ p : ndarray[complex128]
+ Poles of the transfer function.
+ k : float
+ Gain of the transfer function.
+
+ See Also
+ --------
+ butter : Filter design function using this prototype
+
+ """
+ if xp is None:
+ xp = np_compat
+ if abs(int(N)) != N:
+ raise ValueError("Filter order must be a nonnegative integer")
+ z = xp.asarray([], device=device, dtype=xp.float64)
+ m = xp.arange(-N+1, N, 2, device=device, dtype=xp.float64)
+ # Middle value is 0 to ensure an exactly real pole
+ p = -xp.exp(1j * xp.pi * m / (2 * N))
+ k = 1.0
+ return z, p, k
+
+
+def cheb1ap(N, rp, *, xp=None, device=None):
+ """
+ Return (z,p,k) for Nth-order Chebyshev type I analog lowpass filter.
+
+ The returned filter prototype has `rp` decibels of ripple in the passband.
+
+ The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
+ defined as the point at which the gain first drops below ``-rp``.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter
+ rp: float
+ The ripple intensity
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ z : ndarray[float64]
+ Zeros of the transfer function. Is always an empty array.
+ p : ndarray[complex128]
+ Poles of the transfer function.
+ k : float
+ Gain of the transfer function.
+
+ See Also
+ --------
+ cheby1 : Filter design function using this prototype
+
+ """
+ if xp is None:
+ xp = np_compat
+ if abs(int(N)) != N:
+ raise ValueError("Filter order must be a nonnegative integer")
+ elif N == 0:
+ # Avoid divide-by-zero error
+ # Even order filters have DC gain of -rp dB
+ return (
+ xp.asarray([], device=device, dtype=xp.float64),
+ xp.asarray([], device=device, dtype=xp.complex128), 10**(-rp/20)
+ )
+ z = xp.asarray([], device=device, dtype=xp.float64)
+
+ # Ripple factor (epsilon)
+ eps = math.sqrt(10 ** (0.1 * rp) - 1.0)
+ mu = 1.0 / N * math.asinh(1 / eps)
+
+ # Arrange poles in an ellipse on the left half of the S-plane
+ m = xp.arange(-N+1, N, 2, dtype=xp.float64, device=device)
+ theta = xp.pi * m / (2*N)
+ p = -xp.sinh(mu + 1j*theta)
+
+ k = xp.real(xp.prod(-p, axis=0))
+ if N % 2 == 0:
+ k = k / math.sqrt(1 + eps * eps)
+
+ return z, p, k
+
+
+def cheb2ap(N, rs, *, xp=None, device=None):
+ """
+ Return (z,p,k) for Nth-order Chebyshev type II analog lowpass filter.
+
+ The returned filter prototype has attenuation of at least ``rs`` decibels
+ in the stopband.
+
+ The filter's angular (e.g. rad/s) cutoff frequency is normalized to 1,
+ defined as the point at which the attenuation first reaches ``rs``.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter
+ rs : float
+ The attenuation in the stopband
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ z : ndarray[complex128]
+ Zeros of the transfer function.
+ p : ndarray[complex128]
+ Poles of the transfer function.
+ k : float
+ Gain of the transfer function.
+
+ See Also
+ --------
+ cheby2 : Filter design function using this prototype
+
+ """
+ if xp is None:
+ xp = np_compat
+ if abs(int(N)) != N:
+ raise ValueError("Filter order must be a nonnegative integer")
+ elif N == 0:
+ # Avoid divide-by-zero warning
+ return (
+ xp.asarray([], device=device, dtype=xp.complex128),
+ xp.asarray([], device=device, dtype=xp.complex128),
+ 1.0
+ )
+
+ # Ripple factor (epsilon)
+ de = 1.0 / math.sqrt(10 ** (0.1 * rs) - 1)
+ mu = math.asinh(1.0 / de) / N
+
+ if N % 2:
+ m = xp.concat(
+ (xp.arange(-N + 1, 0, 2, dtype=xp.float64, device=device),
+ xp.arange(2, N, 2, dtype=xp.float64, device=device)
+ )
+ )
+ else:
+ m = xp.arange(-N+1, N, 2, dtype=xp.float64, device=device)
+
+ z = 1j / xp.sin(m * xp.pi / (2 * N))
+
+ # Poles around the unit circle like Butterworth
+ m1 = xp.arange(-N+1, N, 2, dtype=xp.float64, device=device)
+ theta1 = xp.pi * m1 / (2 * N)
+ p = -1 / xp.sinh(mu + 1j*theta1)
+
+ k = xp.real(xp.prod(-p, axis=0) / xp.prod(-z, axis=0))
+ return z, p, k
+
+
+EPSILON = 2e-16
+
+# number of terms in solving degree equation
+_ELLIPDEG_MMAX = 7
+
+
+def _ellipdeg(n, m1):
+ """Solve degree equation using nomes
+
+ Given n, m1, solve
+ n * K(m) / K'(m) = K1(m1) / K1'(m1)
+ for m
+
+ See [1], Eq. (49)
+
+ References
+ ----------
+ .. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design",
+ https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf
+ """
+ K1 = special.ellipk(m1)
+ K1p = special.ellipkm1(m1)
+
+ q1 = np.exp(-np.pi * K1p / K1)
+ q = q1 ** (1/n)
+
+ mnum = np.arange(_ELLIPDEG_MMAX + 1)
+ mden = np.arange(1, _ELLIPDEG_MMAX + 2)
+
+ num = np.sum(q ** (mnum * (mnum+1)))
+ den = 1 + 2 * np.sum(q ** (mden**2))
+
+ return 16 * q * (num / den) ** 4
+
+
+# Maximum number of iterations in Landen transformation recursion
+# sequence. 10 is conservative; unit tests pass with 4, Orfanidis
+# (see _arc_jac_cn [1]) suggests 5.
+_ARC_JAC_SN_MAXITER = 10
+
+
+def _arc_jac_sn(w, m):
+ """Inverse Jacobian elliptic sn
+
+ Solve for z in w = sn(z, m)
+
+ Parameters
+ ----------
+ w : complex scalar
+ argument
+
+ m : scalar
+ modulus; in interval [0, 1]
+
+
+ See [1], Eq. (56)
+
+ References
+ ----------
+ .. [1] Orfanidis, "Lecture Notes on Elliptic Filter Design",
+ https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf
+
+ """
+
+ def _complement(kx):
+ # (1-k**2) ** 0.5; the expression below
+ # works for small kx
+ return ((1 - kx) * (1 + kx)) ** 0.5
+
+ k = m ** 0.5
+
+ if k > 1:
+ return np.nan
+ elif k == 1:
+ return np.arctanh(w)
+
+ ks = [k]
+ niter = 0
+ while ks[-1] != 0:
+ k_ = ks[-1]
+ k_p = _complement(k_)
+ ks.append((1 - k_p) / (1 + k_p))
+ niter += 1
+ if niter > _ARC_JAC_SN_MAXITER:
+ raise ValueError('Landen transformation not converging')
+
+ K = np.prod(1 + np.array(ks[1:])) * np.pi/2
+
+ wns = [w]
+
+ for kn, knext in zip(ks[:-1], ks[1:]):
+ wn = wns[-1]
+ wnext = (2 * wn /
+ ((1 + knext) * (1 + _complement(kn * wn))))
+ wns.append(wnext)
+
+ u = 2 / np.pi * np.arcsin(wns[-1])
+
+ z = K * u
+ return z
+
+
+def _arc_jac_sc1(w, m):
+ """Real inverse Jacobian sc, with complementary modulus
+
+ Solve for z in w = sc(z, 1-m)
+
+ w - real scalar
+
+ m - modulus
+
+ From [1], sc(z, m) = -i * sn(i * z, 1 - m)
+
+ References
+ ----------
+ # noqa: E501
+ .. [1] https://functions.wolfram.com/EllipticFunctions/JacobiSC/introductions/JacobiPQs/ShowAll.html,
+ "Representations through other Jacobi functions"
+
+ """
+
+ zcomplex = _arc_jac_sn(1j * w, m)
+ if abs(zcomplex.real) > 1e-14:
+ raise ValueError
+
+ return zcomplex.imag
+
+
+def ellipap(N, rp, rs, *, xp=None, device=None):
+ """Return (z,p,k) of Nth-order elliptic analog lowpass filter.
+
+ The filter is a normalized prototype that has `rp` decibels of ripple
+ in the passband and a stopband `rs` decibels down.
+
+ The filter's angular (e.g., rad/s) cutoff frequency is normalized to 1,
+ defined as the point at which the gain first drops below ``-rp``.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter
+ rp : float
+ The passband ripple intensity
+ rs : float
+ The stopband attenuation
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ z : ndarray[complex128]
+ Zeros of the transfer function.
+ p : ndarray[complex128]
+ Poles of the transfer function.
+ k : float
+ Gain of the transfer function.
+
+ See Also
+ --------
+ ellip : Filter design function using this prototype
+
+ References
+ ----------
+ .. [1] Lutovac, Tosic, and Evans, "Filter Design for Signal Processing",
+ Chapters 5 and 12.
+
+ .. [2] Orfanidis, "Lecture Notes on Elliptic Filter Design",
+ https://www.ece.rutgers.edu/~orfanidi/ece521/notes.pdf
+
+ """
+ if xp is None:
+ xp = np_compat
+
+ if abs(int(N)) != N:
+ raise ValueError("Filter order must be a nonnegative integer")
+ elif N == 0:
+ # Avoid divide-by-zero warning
+ # Even order filters have DC gain of -rp dB
+ return (
+ xp.asarray([], device=device, dtype=xp.complex128),
+ xp.asarray([], device=device, dtype=xp.complex128),
+ 10**(-rp/20)
+ )
+ elif N == 1:
+ p = -math.sqrt(1.0 / _pow10m1(0.1 * rp))
+ k = -p
+ z = []
+ return (
+ xp.asarray(z, device=device, dtype=xp.complex128),
+ xp.asarray(p, device=device, dtype=xp.complex128), k
+ )
+
+ eps_sq = _pow10m1(0.1 * rp)
+
+ eps = math.sqrt(eps_sq)
+ ck1_sq = eps_sq / _pow10m1(0.1 * rs)
+ if ck1_sq == 0:
+ raise ValueError("Cannot design a filter with given rp and rs"
+ " specifications.")
+
+ # do computations with numpy, xp.asarray the return values
+
+ val = special.ellipk(ck1_sq), special.ellipkm1(ck1_sq)
+
+ m = _ellipdeg(N, ck1_sq)
+
+ capk = special.ellipk(m)
+
+ j = np.arange(1 - N % 2, N, 2)
+ jj = len(j)
+
+ [s, c, d, phi] = special.ellipj(j * capk / N, m * np.ones(jj))
+ snew = np.compress(abs(s) > EPSILON, s, axis=-1)
+ z = 1.0 / (np.sqrt(m) * snew)
+ z = 1j * z
+ z = np.concatenate((z, np.conjugate(z)))
+
+ r = _arc_jac_sc1(1. / eps, ck1_sq)
+ v0 = capk * r / (N * val[0])
+
+ [sv, cv, dv, phi] = special.ellipj(v0, 1 - m)
+ p = -(c * d * sv * cv + 1j * s * dv) / (1 - (d * sv) ** 2.0)
+
+ if N % 2:
+ newp = np.compress(
+ abs(p.imag) > EPSILON * np.sqrt(np.sum(p * np.conjugate(p), axis=0).real),
+ p, axis=-1
+ )
+ p = np.concatenate((p, np.conjugate(newp)))
+ else:
+ p = np.concatenate((p, np.conjugate(p)))
+
+ k = (np.prod(-p, axis=0) / np.prod(-z, axis=0)).real
+ if N % 2 == 0:
+ k = k / np.sqrt(1 + eps_sq)
+
+ return (
+ xp.asarray(z, device=device, dtype=xp.complex128),
+ xp.asarray(p, device=device, dtype=xp.complex128), float(k)
+ )
+
+
+# TODO: Make this a real public function scipy.misc.ff
+def _falling_factorial(x, n):
+ r"""
+ Return the factorial of `x` to the `n` falling.
+
+ This is defined as:
+
+ .. math:: x^\underline n = (x)_n = x (x-1) \cdots (x-n+1)
+
+ This can more efficiently calculate ratios of factorials, since:
+
+ n!/m! == falling_factorial(n, n-m)
+
+ where n >= m
+
+ skipping the factors that cancel out
+
+ the usual factorial n! == ff(n, n)
+ """
+ val = 1
+ for k in range(x - n + 1, x + 1):
+ val *= k
+ return val
+
+
+def _bessel_poly(n, reverse=False):
+ """
+ Return the coefficients of Bessel polynomial of degree `n`
+
+ If `reverse` is true, a reverse Bessel polynomial is output.
+
+ Output is a list of coefficients:
+ [1] = 1
+ [1, 1] = 1*s + 1
+ [1, 3, 3] = 1*s^2 + 3*s + 3
+ [1, 6, 15, 15] = 1*s^3 + 6*s^2 + 15*s + 15
+ [1, 10, 45, 105, 105] = 1*s^4 + 10*s^3 + 45*s^2 + 105*s + 105
+ etc.
+
+ Output is a Python list of arbitrary precision long ints, so n is only
+ limited by your hardware's memory.
+
+ Sequence is http://oeis.org/A001498, and output can be confirmed to
+ match http://oeis.org/A001498/b001498.txt :
+
+ >>> from scipy.signal._filter_design import _bessel_poly
+ >>> i = 0
+ >>> for n in range(51):
+ ... for x in _bessel_poly(n, reverse=True):
+ ... print(i, x)
+ ... i += 1
+
+ """
+ if abs(int(n)) != n:
+ raise ValueError("Polynomial order must be a nonnegative integer")
+ else:
+ n = int(n) # np.int32 doesn't work, for instance
+
+ out = []
+ for k in range(n + 1):
+ num = _falling_factorial(2*n - k, n)
+ den = 2**(n - k) * math.factorial(k)
+ out.append(num // den)
+
+ if reverse:
+ return out[::-1]
+ else:
+ return out
+
+
+def _campos_zeros(n):
+ """
+ Return approximate zero locations of Bessel polynomials y_n(x) for order
+ `n` using polynomial fit (Campos-Calderon 2011)
+ """
+ if n == 1:
+ return np.asarray([-1+0j])
+
+ s = npp_polyval(n, [0, 0, 2, 0, -3, 1])
+ b3 = npp_polyval(n, [16, -8]) / s
+ b2 = npp_polyval(n, [-24, -12, 12]) / s
+ b1 = npp_polyval(n, [8, 24, -12, -2]) / s
+ b0 = npp_polyval(n, [0, -6, 0, 5, -1]) / s
+
+ r = npp_polyval(n, [0, 0, 2, 1])
+ a1 = npp_polyval(n, [-6, -6]) / r
+ a2 = 6 / r
+
+ k = np.arange(1, n+1)
+ x = npp_polyval(k, [0, a1, a2])
+ y = npp_polyval(k, [b0, b1, b2, b3])
+
+ return x + 1j*y
+
+
+def _aberth(f, fp, x0, tol=1e-15, maxiter=50):
+ """
+ Given a function `f`, its first derivative `fp`, and a set of initial
+ guesses `x0`, simultaneously find the roots of the polynomial using the
+ Aberth-Ehrlich method.
+
+ ``len(x0)`` should equal the number of roots of `f`.
+
+ (This is not a complete implementation of Bini's algorithm.)
+ """
+
+ N = len(x0)
+
+ x = np.array(x0, complex)
+ beta = np.empty_like(x0)
+
+ for iteration in range(maxiter):
+ alpha = -f(x) / fp(x) # Newton's method
+
+ # Model "repulsion" between zeros
+ for k in range(N):
+ beta[k] = np.sum(1/(x[k] - x[k+1:]))
+ beta[k] += np.sum(1/(x[k] - x[:k]))
+
+ x += alpha / (1 + alpha * beta)
+
+ if not all(np.isfinite(x)):
+ raise RuntimeError('Root-finding calculation failed')
+
+ # Mekwi: The iterative process can be stopped when |hn| has become
+ # less than the largest error one is willing to permit in the root.
+ if all(abs(alpha) <= tol):
+ break
+ else:
+ raise Exception('Zeros failed to converge')
+
+ return x
+
+
+def _bessel_zeros(N):
+ """
+ Find zeros of ordinary Bessel polynomial of order `N`, by root-finding of
+ modified Bessel function of the second kind
+ """
+ if N == 0:
+ return np.asarray([])
+
+ # Generate starting points
+ x0 = _campos_zeros(N)
+
+ # Zeros are the same for exp(1/x)*K_{N+0.5}(1/x) and Nth-order ordinary
+ # Bessel polynomial y_N(x)
+ def f(x):
+ return special.kve(N+0.5, 1/x)
+
+ # First derivative of above
+ def fp(x):
+ return (special.kve(N-0.5, 1/x)/(2*x**2) -
+ special.kve(N+0.5, 1/x)/(x**2) +
+ special.kve(N+1.5, 1/x)/(2*x**2))
+
+ # Starting points converge to true zeros
+ x = _aberth(f, fp, x0)
+
+ # Improve precision using Newton's method on each
+ for i in range(len(x)):
+ x[i] = optimize.newton(f, x[i], fp, tol=1e-15)
+
+ # Average complex conjugates to make them exactly symmetrical
+ x = np.mean((x, x[::-1].conj()), 0)
+
+ # Zeros should sum to -1
+ if abs(np.sum(x) + 1) > 1e-15:
+ raise RuntimeError('Generated zeros are inaccurate')
+
+ return x
+
+
+def _norm_factor(p, k):
+ """
+ Numerically find frequency shift to apply to delay-normalized filter such
+ that -3 dB point is at 1 rad/sec.
+
+ `p` is an array_like of polynomial poles
+ `k` is a float gain
+
+ First 10 values are listed in "Bessel Scale Factors" table,
+ "Bessel Filters Polynomials, Poles and Circuit Elements 2003, C. Bond."
+ """
+ p = np.asarray(p, dtype=np.complex128)
+
+ def G(w):
+ """
+ Gain of filter
+ """
+ return np.abs(k / np.prod(1j*w - p))
+
+ def cutoff(w):
+ """
+ When gain = -3 dB, return 0
+ """
+ return G(w) - 1/math.sqrt(2)
+
+ return optimize.newton(cutoff, 1.5)
+
+
+def besselap(N, norm='phase', *, xp=None, device=None):
+ """
+ Return (z,p,k) for analog prototype of an Nth-order Bessel filter.
+
+ Parameters
+ ----------
+ N : int
+ The order of the filter.
+ norm : {'phase', 'delay', 'mag'}, optional
+ Frequency normalization:
+
+ ``phase``
+ The filter is normalized such that the phase response reaches its
+ midpoint at an angular (e.g., rad/s) cutoff frequency of 1. This
+ happens for both low-pass and high-pass filters, so this is the
+ "phase-matched" case. [6]_
+
+ The magnitude response asymptotes are the same as a Butterworth
+ filter of the same order with a cutoff of `Wn`.
+
+ This is the default, and matches MATLAB's implementation.
+
+ ``delay``
+ The filter is normalized such that the group delay in the passband
+ is 1 (e.g., 1 second). This is the "natural" type obtained by
+ solving Bessel polynomials
+
+ ``mag``
+ The filter is normalized such that the gain magnitude is -3 dB at
+ angular frequency 1. This is called "frequency normalization" by
+ Bond. [1]_
+
+ .. versionadded:: 0.18.0
+
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ z : ndarray[float64]
+ Zeros of the transfer function. Is always an empty array.
+ p : ndarray[complex128]
+ Poles of the transfer function.
+ k : float
+ Gain of the transfer function. For phase-normalized, this is always 1.
+
+ See Also
+ --------
+ bessel : Filter design function using this prototype
+
+ Notes
+ -----
+ To find the pole locations, approximate starting points are generated [2]_
+ for the zeros of the ordinary Bessel polynomial [3]_, then the
+ Aberth-Ehrlich method [4]_ [5]_ is used on the Kv(x) Bessel function to
+ calculate more accurate zeros, and these locations are then inverted about
+ the unit circle.
+
+ References
+ ----------
+ .. [1] C.R. Bond, "Bessel Filter Constants",
+ http://www.crbond.com/papers/bsf.pdf
+ .. [2] Campos and Calderon, "Approximate closed-form formulas for the
+ zeros of the Bessel Polynomials", :arXiv:`1105.0957`.
+ .. [3] Thomson, W.E., "Delay Networks having Maximally Flat Frequency
+ Characteristics", Proceedings of the Institution of Electrical
+ Engineers, Part III, November 1949, Vol. 96, No. 44, pp. 487-490.
+ .. [4] Aberth, "Iteration Methods for Finding all Zeros of a Polynomial
+ Simultaneously", Mathematics of Computation, Vol. 27, No. 122,
+ April 1973
+ .. [5] Ehrlich, "A modified Newton method for polynomials", Communications
+ of the ACM, Vol. 10, Issue 2, pp. 107-108, Feb. 1967,
+ :DOI:`10.1145/363067.363115`
+ .. [6] Miller and Bohn, "A Bessel Filter Crossover, and Its Relation to
+ Others", RaneNote 147, 1998,
+ https://www.ranecommercial.com/legacy/note147.html
+
+ """
+ if xp is None:
+ xp = np_compat
+
+ if abs(int(N)) != N:
+ raise ValueError("Filter order must be a nonnegative integer")
+
+ N = int(N) # calculation below doesn't always fit in np.int64
+ if N == 0:
+ p = []
+ k = 1
+ else:
+ # Find roots of reverse Bessel polynomial
+ p = 1/_bessel_zeros(N)
+
+ a_last = _falling_factorial(2*N, N) // 2**N
+
+ # Shift them to a different normalization if required
+ if norm in ('delay', 'mag'):
+ # Normalized for group delay of 1
+ k = a_last
+ if norm == 'mag':
+ # -3 dB magnitude point is at 1 rad/sec
+ norm_factor = _norm_factor(p, k)
+ p /= norm_factor
+ k = norm_factor**-N * a_last
+ elif norm == 'phase':
+ # Phase-matched (1/2 max phase shift at 1 rad/sec)
+ # Asymptotes are same as Butterworth filter
+ p *= 10**(-math.log10(a_last)/N)
+ k = 1
+ else:
+ raise ValueError('normalization not understood')
+
+ z = xp.asarray([], device=device, dtype=xp.float64)
+ return (
+ z,
+ xp.asarray(p, device=device, dtype=xp.complex128),
+ float(k)
+ )
+
+
+def iirnotch(w0, Q, fs=2.0, *, xp=None, device=None):
+ """
+ Design second-order IIR notch digital filter.
+
+ A notch filter is a band-stop filter with a narrow bandwidth
+ (high quality factor). It rejects a narrow frequency band and
+ leaves the rest of the spectrum little changed.
+
+ Parameters
+ ----------
+ w0 : float
+ Frequency to remove from a signal. If `fs` is specified, this is in
+ the same units as `fs`. By default, it is a normalized scalar that must
+ satisfy ``0 < w0 < 1``, with ``w0 = 1`` corresponding to half of the
+ sampling frequency.
+ Q : float
+ Quality factor. Dimensionless parameter that characterizes
+ notch filter -3 dB bandwidth ``bw`` relative to its center
+ frequency, ``Q = w0/bw``.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (``b``) and denominator (``a``) polynomials
+ of the IIR filter.
+
+ See Also
+ --------
+ iirpeak
+
+ Notes
+ -----
+ .. versionadded:: 0.19.0
+
+ References
+ ----------
+ .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing",
+ Prentice-Hall, 1996
+
+ Examples
+ --------
+ Design and plot filter to remove the 60 Hz component from a
+ signal sampled at 200 Hz, using a quality factor Q = 30
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> fs = 200.0 # Sample frequency (Hz)
+ >>> f0 = 60.0 # Frequency to be removed from signal (Hz)
+ >>> Q = 30.0 # Quality factor
+ >>> # Design notch filter
+ >>> b, a = signal.iirnotch(f0, Q, fs)
+
+ >>> # Frequency response
+ >>> freq, h = signal.freqz(b, a, fs=fs)
+ >>> # Plot
+ >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6))
+ >>> ax[0].plot(freq, 20*np.log10(abs(h)), color='blue')
+ >>> ax[0].set_title("Frequency Response")
+ >>> ax[0].set_ylabel("Amplitude [dB]", color='blue')
+ >>> ax[0].set_xlim([0, 100])
+ >>> ax[0].set_ylim([-25, 10])
+ >>> ax[0].grid(True)
+ >>> ax[1].plot(freq, np.unwrap(np.angle(h))*180/np.pi, color='green')
+ >>> ax[1].set_ylabel("Phase [deg]", color='green')
+ >>> ax[1].set_xlabel("Frequency [Hz]")
+ >>> ax[1].set_xlim([0, 100])
+ >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90])
+ >>> ax[1].set_ylim([-90, 90])
+ >>> ax[1].grid(True)
+ >>> plt.show()
+ """
+
+ return _design_notch_peak_filter(w0, Q, "notch", fs, xp=xp, device=device)
+
+
+def iirpeak(w0, Q, fs=2.0, *, xp=None, device=None):
+ """
+ Design second-order IIR peak (resonant) digital filter.
+
+ A peak filter is a band-pass filter with a narrow bandwidth
+ (high quality factor). It rejects components outside a narrow
+ frequency band.
+
+ Parameters
+ ----------
+ w0 : float
+ Frequency to be retained in a signal. If `fs` is specified, this is in
+ the same units as `fs`. By default, it is a normalized scalar that must
+ satisfy ``0 < w0 < 1``, with ``w0 = 1`` corresponding to half of the
+ sampling frequency.
+ Q : float
+ Quality factor. Dimensionless parameter that characterizes
+ peak filter -3 dB bandwidth ``bw`` relative to its center
+ frequency, ``Q = w0/bw``.
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0
+
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (``b``) and denominator (``a``) polynomials
+ of the IIR filter.
+
+ See Also
+ --------
+ iirnotch
+
+ Notes
+ -----
+ .. versionadded:: 0.19.0
+
+ References
+ ----------
+ .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing",
+ Prentice-Hall, 1996
+
+ Examples
+ --------
+ Design and plot filter to remove the frequencies other than the 300 Hz
+ component from a signal sampled at 1000 Hz, using a quality factor Q = 30
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> fs = 1000.0 # Sample frequency (Hz)
+ >>> f0 = 300.0 # Frequency to be retained (Hz)
+ >>> Q = 30.0 # Quality factor
+ >>> # Design peak filter
+ >>> b, a = signal.iirpeak(f0, Q, fs)
+
+ >>> # Frequency response
+ >>> freq, h = signal.freqz(b, a, fs=fs)
+ >>> # Plot
+ >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6))
+ >>> ax[0].plot(freq, 20*np.log10(np.maximum(abs(h), 1e-5)), color='blue')
+ >>> ax[0].set_title("Frequency Response")
+ >>> ax[0].set_ylabel("Amplitude [dB]", color='blue')
+ >>> ax[0].set_xlim([0, 500])
+ >>> ax[0].set_ylim([-50, 10])
+ >>> ax[0].grid(True)
+ >>> ax[1].plot(freq, np.unwrap(np.angle(h))*180/np.pi, color='green')
+ >>> ax[1].set_ylabel("Phase [deg]", color='green')
+ >>> ax[1].set_xlabel("Frequency [Hz]")
+ >>> ax[1].set_xlim([0, 500])
+ >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90])
+ >>> ax[1].set_ylim([-90, 90])
+ >>> ax[1].grid(True)
+ >>> plt.show()
+ """
+
+ return _design_notch_peak_filter(w0, Q, "peak", fs, xp=xp, device=device)
+
+
+def _design_notch_peak_filter(w0, Q, ftype, fs=2.0, *, xp=None, device=None):
+ """
+ Design notch or peak digital filter.
+
+ Parameters
+ ----------
+ w0 : float
+ Normalized frequency to remove from a signal. If `fs` is specified,
+ this is in the same units as `fs`. By default, it is a normalized
+ scalar that must satisfy ``0 < w0 < 1``, with ``w0 = 1``
+ corresponding to half of the sampling frequency.
+ Q : float
+ Quality factor. Dimensionless parameter that characterizes
+ notch filter -3 dB bandwidth ``bw`` relative to its center
+ frequency, ``Q = w0/bw``.
+ ftype : str
+ The type of IIR filter to design:
+
+ - notch filter : ``notch``
+ - peak filter : ``peak``
+ fs : float, optional
+ The sampling frequency of the digital system.
+
+ .. versionadded:: 1.2.0:
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (``b``) and denominator (``a``) polynomials
+ of the IIR filter.
+ """
+ if xp is None:
+ xp = np_compat
+
+ fs = _validate_fs(fs, allow_none=False)
+
+ # Guarantee that the inputs are floats
+ w0 = float(w0)
+ Q = float(Q)
+ w0 = 2 * w0 / fs
+
+ # Checks if w0 is within the range
+ if w0 > 1.0 or w0 < 0.0:
+ raise ValueError("w0 should be such that 0 < w0 < 1")
+
+ # Get bandwidth
+ bw = w0/Q
+
+ # Normalize inputs
+ bw = bw * xp.pi
+ w0 = w0 * xp.pi
+
+ if ftype not in ("notch", "peak"):
+ raise ValueError("Unknown ftype.")
+
+ # Compute beta according to Eqs. 11.3.4 (p.575) and 11.3.19 (p.579) from
+ # reference [1]. Due to assuming a -3 dB attenuation value, i.e, assuming
+ # gb = 1 / np.sqrt(2), the following terms simplify to:
+ # (np.sqrt(1.0 - gb**2.0) / gb) = 1
+ # (gb / np.sqrt(1.0 - gb**2.0)) = 1
+ beta = math.tan(bw / 2.0)
+
+ # Compute gain: formula 11.3.6 (p.575) from reference [1]
+ gain = 1.0 / (1.0 + beta)
+
+ # Compute numerator b and denominator a
+ # formulas 11.3.7 (p.575) and 11.3.21 (p.579)
+ # from reference [1]
+ if ftype == "notch":
+ b = gain * xp.asarray([1.0, -2.0*math.cos(w0), 1.0], device=device)
+ else:
+ b = (1.0 - gain) * xp.asarray([1.0, 0.0, -1.0], device=device)
+ a = xp.asarray([1.0, -2.0 * gain * math.cos(w0), (2.0*gain - 1.0)], device=device)
+
+ return b, a
+
+
+def iircomb(w0, Q, ftype='notch', fs=2.0, *, pass_zero=False, xp=None, device=None):
+ """
+ Design IIR notching or peaking digital comb filter.
+
+ A notching comb filter consists of regularly-spaced band-stop filters with
+ a narrow bandwidth (high quality factor). Each rejects a narrow frequency
+ band and leaves the rest of the spectrum little changed.
+
+ A peaking comb filter consists of regularly-spaced band-pass filters with
+ a narrow bandwidth (high quality factor). Each rejects components outside
+ a narrow frequency band.
+
+ Parameters
+ ----------
+ w0 : float
+ The fundamental frequency of the comb filter (the spacing between its
+ peaks). This must evenly divide the sampling frequency. If `fs` is
+ specified, this is in the same units as `fs`. By default, it is
+ a normalized scalar that must satisfy ``0 < w0 < 1``, with
+ ``w0 = 1`` corresponding to half of the sampling frequency.
+ Q : float
+ Quality factor. Dimensionless parameter that characterizes
+ notch filter -3 dB bandwidth ``bw`` relative to its center
+ frequency, ``Q = w0/bw``.
+ ftype : {'notch', 'peak'}
+ The type of comb filter generated by the function. If 'notch', then
+ the Q factor applies to the notches. If 'peak', then the `Q` factor
+ applies to the peaks. Default is 'notch'.
+ fs : float, optional
+ The sampling frequency of the signal. Default is 2.0.
+ pass_zero : bool, optional
+ If False (default), the notches (nulls) of the filter are centered on
+ frequencies ``[0, w0, 2*w0, ...]``, and the peaks are centered on the
+ midpoints ``[w0/2, 3*w0/2, 5*w0/2, ...]``. If True, the peaks are centered
+ on ``[0, w0, 2*w0, ...]`` (passing zero frequency) and vice versa.
+
+ .. versionadded:: 1.9.0
+
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (``b``) and denominator (``a``) polynomials
+ of the IIR filter.
+
+ Raises
+ ------
+ ValueError
+ If `w0` is less than or equal to 0 or greater than or equal to
+ ``fs/2``, if `fs` is not divisible by `w0`, if `ftype`
+ is not 'notch' or 'peak'
+
+ See Also
+ --------
+ iirnotch
+ iirpeak
+
+ Notes
+ -----
+ For implementation details, see [1]_. The TF implementation of the
+ comb filter is numerically stable even at higher orders due to the
+ use of a single repeated pole, which won't suffer from precision loss.
+
+ References
+ ----------
+ .. [1] Sophocles J. Orfanidis, "Introduction To Signal Processing",
+ Prentice-Hall, 1996, ch. 11, "Digital Filter Design"
+
+ Examples
+ --------
+ Design and plot notching comb filter at 20 Hz for a
+ signal sampled at 200 Hz, using quality factor Q = 30
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> fs = 200.0 # Sample frequency (Hz)
+ >>> f0 = 20.0 # Frequency to be removed from signal (Hz)
+ >>> Q = 30.0 # Quality factor
+ >>> # Design notching comb filter
+ >>> b, a = signal.iircomb(f0, Q, ftype='notch', fs=fs)
+
+ >>> # Frequency response
+ >>> freq, h = signal.freqz(b, a, fs=fs)
+ >>> response = abs(h)
+ >>> # To avoid divide by zero when graphing
+ >>> response[response == 0] = 1e-20
+ >>> # Plot
+ >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
+ >>> ax[0].plot(freq, 20*np.log10(abs(response)), color='blue')
+ >>> ax[0].set_title("Frequency Response")
+ >>> ax[0].set_ylabel("Amplitude [dB]", color='blue')
+ >>> ax[0].set_xlim([0, 100])
+ >>> ax[0].set_ylim([-30, 10])
+ >>> ax[0].grid(True)
+ >>> ax[1].plot(freq, np.mod(np.angle(h, deg=True) + 180, 360) - 180, color='green')
+ >>> ax[1].set_ylabel("Phase [deg]", color='green')
+ >>> ax[1].set_xlabel("Frequency [Hz]")
+ >>> ax[1].set_xlim([0, 100])
+ >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90])
+ >>> ax[1].set_ylim([-90, 90])
+ >>> ax[1].grid(True)
+ >>> plt.show()
+
+ Design and plot peaking comb filter at 250 Hz for a
+ signal sampled at 1000 Hz, using quality factor Q = 30
+
+ >>> fs = 1000.0 # Sample frequency (Hz)
+ >>> f0 = 250.0 # Frequency to be retained (Hz)
+ >>> Q = 30.0 # Quality factor
+ >>> # Design peaking filter
+ >>> b, a = signal.iircomb(f0, Q, ftype='peak', fs=fs, pass_zero=True)
+
+ >>> # Frequency response
+ >>> freq, h = signal.freqz(b, a, fs=fs)
+ >>> response = abs(h)
+ >>> # To avoid divide by zero when graphing
+ >>> response[response == 0] = 1e-20
+ >>> # Plot
+ >>> fig, ax = plt.subplots(2, 1, figsize=(8, 6), sharex=True)
+ >>> ax[0].plot(freq, 20*np.log10(np.maximum(abs(h), 1e-5)), color='blue')
+ >>> ax[0].set_title("Frequency Response")
+ >>> ax[0].set_ylabel("Amplitude [dB]", color='blue')
+ >>> ax[0].set_xlim([0, 500])
+ >>> ax[0].set_ylim([-80, 10])
+ >>> ax[0].grid(True)
+ >>> ax[1].plot(freq, np.mod(np.angle(h)*180/np.pi + 180, 360) - 180, color='green')
+ >>> ax[1].set_ylabel("Phase [deg]", color='green')
+ >>> ax[1].set_xlabel("Frequency [Hz]")
+ >>> ax[1].set_xlim([0, 500])
+ >>> ax[1].set_yticks([-90, -60, -30, 0, 30, 60, 90])
+ >>> ax[1].set_ylim([-90, 90])
+ >>> ax[1].grid(True)
+ >>> plt.show()
+ """
+ if xp is None:
+ xp = np_compat
+
+ # Convert w0, Q, and fs to float
+ w0 = float(w0)
+ Q = float(Q)
+ fs = _validate_fs(fs, allow_none=False)
+
+ # Check for invalid cutoff frequency or filter type
+ ftype = ftype.lower()
+ if not 0 < w0 < fs / 2:
+ raise ValueError(f"w0 must be between 0 and {fs / 2}"
+ f" (Nyquist), but given {w0}.")
+ if ftype not in ('notch', 'peak'):
+ raise ValueError('ftype must be either notch or peak.')
+
+ # Compute the order of the filter
+ N = round(fs / w0)
+
+ # Check for cutoff frequency divisibility
+ if abs(w0 - fs/N)/fs > 1e-14:
+ raise ValueError('fs must be divisible by w0.')
+
+ # Compute frequency in radians and filter bandwidth
+ # Eq. 11.3.1 (p. 574) from reference [1]
+ w0 = (2 * xp.pi * w0) / fs
+ w_delta = w0 / Q
+
+ # Define base gain values depending on notch or peak filter
+ # Compute -3dB attenuation
+ # Eqs. 11.4.1 and 11.4.2 (p. 582) from reference [1]
+ if ftype == 'notch':
+ G0, G = 1, 0
+ elif ftype == 'peak':
+ G0, G = 0, 1
+
+ # Compute beta according to Eq. 11.5.3 (p. 591) from reference [1]. Due to
+ # assuming a -3 dB attenuation value, i.e, assuming GB = 1 / np.sqrt(2),
+ # the following term simplifies to:
+ # np.sqrt((GB**2 - G0**2) / (G**2 - GB**2)) = 1
+ beta = math.tan(N * w_delta / 4)
+
+ # Compute filter coefficients
+ # Eq 11.5.1 (p. 590) variables a, b, c from reference [1]
+ ax = (1 - beta) / (1 + beta)
+ bx = (G0 + G * beta) / (1 + beta)
+ cx = (G0 - G * beta) / (1 + beta)
+
+ # Last coefficients are negative to get peaking comb that passes zero or
+ # notching comb that doesn't.
+ negative_coef = ((ftype == 'peak' and pass_zero) or
+ (ftype == 'notch' and not pass_zero))
+
+ # Compute numerator coefficients
+ # Eq 11.5.1 (p. 590) or Eq 11.5.4 (p. 591) from reference [1]
+ # b - cz^-N or b + cz^-N
+ b = xp.zeros(N + 1, device=device)
+ sgn = -1. if negative_coef else 1
+ xpx.at(b, 0).set(bx)
+ xpx.at(b, -1).set(sgn * cx)
+
+ # Compute denominator coefficients
+ # Eq 11.5.1 (p. 590) or Eq 11.5.4 (p. 591) from reference [1]
+ # 1 - az^-N or 1 + az^-N
+ a = xp.zeros(N + 1, device=device)
+ xpx.at(a, 0).set(1.)
+ xpx.at(a, -1).set(sgn * ax)
+
+ return b, a
+
+
+def _hz_to_erb(hz):
+ """
+ Utility for converting from frequency (Hz) to the
+ Equivalent Rectangular Bandwidth (ERB) scale
+ ERB = frequency / EarQ + minBW
+ """
+ EarQ = 9.26449
+ minBW = 24.7
+ return hz / EarQ + minBW
+
+
+def gammatone(freq, ftype, order=None, numtaps=None, fs=None, *, xp=None, device=None):
+ """
+ Gammatone filter design.
+
+ This function computes the coefficients of an FIR or IIR gammatone
+ digital filter [1]_.
+
+ Parameters
+ ----------
+ freq : float
+ Center frequency of the filter (expressed in the same units
+ as `fs`).
+ ftype : {'fir', 'iir'}
+ The type of filter the function generates. If 'fir', the function
+ will generate an Nth order FIR gammatone filter. If 'iir', the
+ function will generate an 8th order digital IIR filter, modeled as
+ as 4th order gammatone filter.
+ order : int, optional
+ The order of the filter. Only used when ``ftype='fir'``.
+ Default is 4 to model the human auditory system. Must be between
+ 0 and 24.
+ numtaps : int, optional
+ Length of the filter. Only used when ``ftype='fir'``.
+ Default is ``fs*0.015`` if `fs` is greater than 1000,
+ 15 if `fs` is less than or equal to 1000.
+ fs : float, optional
+ The sampling frequency of the signal. `freq` must be between
+ 0 and ``fs/2``. Default is 2.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ b, a : ndarray, ndarray
+ Numerator (``b``) and denominator (``a``) polynomials of the filter.
+
+ Raises
+ ------
+ ValueError
+ If `freq` is less than or equal to 0 or greater than or equal to
+ ``fs/2``, if `ftype` is not 'fir' or 'iir', if `order` is less than
+ or equal to 0 or greater than 24 when ``ftype='fir'``
+
+ See Also
+ --------
+ firwin
+ iirfilter
+
+ References
+ ----------
+ .. [1] Slaney, Malcolm, "An Efficient Implementation of the
+ Patterson-Holdsworth Auditory Filter Bank", Apple Computer
+ Technical Report 35, 1993, pp.3-8, 34-39.
+
+ Examples
+ --------
+ 16-sample 4th order FIR Gammatone filter centered at 440 Hz
+
+ >>> from scipy import signal
+ >>> signal.gammatone(440, 'fir', numtaps=16, fs=16000)
+ (array([ 0.00000000e+00, 2.22196719e-07, 1.64942101e-06, 4.99298227e-06,
+ 1.01993969e-05, 1.63125770e-05, 2.14648940e-05, 2.29947263e-05,
+ 1.76776931e-05, 2.04980537e-06, -2.72062858e-05, -7.28455299e-05,
+ -1.36651076e-04, -2.19066855e-04, -3.18905076e-04, -4.33156712e-04]),
+ [1.0])
+
+ IIR Gammatone filter centered at 440 Hz
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+
+ >>> fc, fs = 440, 16000
+ >>> b, a = signal.gammatone(fc, 'iir', fs=fs)
+ >>> w, h = signal.freqz(b, a)
+ >>> plt.plot(w * fs / (2 * np.pi), 20 * np.log10(abs(h)))
+ >>> plt.xscale('log')
+ >>> plt.title('Gammatone filter frequency response')
+ >>> plt.xlabel('Frequency [Hz]')
+ >>> plt.ylabel('Amplitude [dB]')
+ >>> plt.margins(0, 0.1)
+ >>> plt.grid(which='both', axis='both')
+ >>> plt.axvline(fc, color='green') # cutoff frequency
+ >>> plt.show()
+ """
+ if xp is None:
+ xp = np_compat
+
+ # Converts freq to float
+ freq = float(freq)
+
+ # Set sampling rate if not passed
+ if fs is None:
+ fs = 2
+ fs = _validate_fs(fs, allow_none=False)
+
+ # Check for invalid cutoff frequency or filter type
+ ftype = ftype.lower()
+ filter_types = ['fir', 'iir']
+ if not 0 < freq < fs / 2:
+ raise ValueError(f"The frequency must be between 0 and {fs / 2}"
+ f" (Nyquist), but given {freq}.")
+ if ftype not in filter_types:
+ raise ValueError('ftype must be either fir or iir.')
+
+ # Calculate FIR gammatone filter
+ if ftype == 'fir':
+ # Set order and numtaps if not passed
+ if order is None:
+ order = 4
+ order = operator.index(order)
+
+ if numtaps is None:
+ numtaps = max(int(fs * 0.015), 15)
+ numtaps = operator.index(numtaps)
+
+ # Check for invalid order
+ if not 0 < order <= 24:
+ raise ValueError("Invalid order: order must be > 0 and <= 24.")
+
+ # Gammatone impulse response settings
+ t = xp.arange(numtaps, device=device, dtype=xp_default_dtype(xp)) / fs
+ bw = 1.019 * _hz_to_erb(freq)
+
+ # Calculate the FIR gammatone filter
+ b = (t ** (order - 1)) * xp.exp(-2 * xp.pi * bw * t)
+ b = b * xp.cos(2 * xp.pi * freq * t)
+
+ # Scale the FIR filter so the frequency response is 1 at cutoff
+ scale_factor = 2 * (2 * xp.pi * bw) ** (order)
+ scale_factor /= float_factorial(order - 1)
+ scale_factor /= fs
+ b = b * scale_factor
+ a = xp.asarray([1.0], device=device)
+
+ # Calculate IIR gammatone filter
+ elif ftype == 'iir':
+ # Raise warning if order and/or numtaps is passed
+ if order is not None:
+ warnings.warn('order is not used for IIR gammatone filter.', stacklevel=2)
+ if numtaps is not None:
+ warnings.warn('numtaps is not used for IIR gammatone filter.', stacklevel=2)
+
+ # Gammatone impulse response settings
+ T = 1./fs
+ bw = 2 * math.pi * 1.019 * _hz_to_erb(freq)
+ fr = 2 * freq * math.pi * T
+ bwT = bw * T
+
+ # Calculate the gain to normalize the volume at the center frequency
+ g1 = -2 * cmath.exp(2j * fr) * T
+ g2 = 2 * cmath.exp(-(bwT) + 1j * fr) * T
+ g3 = math.sqrt(3 + 2 ** (3 / 2)) * math.sin(fr)
+ g4 = math.sqrt(3 - 2 ** (3 / 2)) * math.sin(fr)
+ g5 = cmath.exp(2j * fr)
+
+ g = g1 + g2 * (math.cos(fr) - g4)
+ g *= (g1 + g2 * (math.cos(fr) + g4))
+ g *= (g1 + g2 * (math.cos(fr) - g3))
+ g *= (g1 + g2 * (math.cos(fr) + g3))
+ g /= ((-2 / math.exp(2 * bwT) - 2 * g5 + 2 * (1 + g5) / math.exp(bwT)) ** 4)
+ g = math.hypot(g.real, g.imag)
+
+ # Create empty filter coefficient lists
+ b = [None] * 5 #np.empty(5)
+ a = [None] * 9 # np.empty(9)
+
+ # Calculate the numerator coefficients
+ b[0] = (T ** 4) / g
+ b[1] = -4 * T ** 4 * math.cos(fr) / math.exp(bw * T) / g
+ b[2] = 6 * T ** 4 * math.cos(2 * fr) / math.exp(2 * bw * T) / g
+ b[3] = -4 * T ** 4 * math.cos(3 * fr) / math.exp(3 * bw * T) / g
+ b[4] = T ** 4 * math.cos(4 * fr) / math.exp(4 * bw * T) / g
+
+ # Calculate the denominator coefficients
+ a[0] = 1
+ a[1] = -8 * math.cos(fr) / math.exp(bw * T)
+ a[2] = 4 * (4 + 3 * math.cos(2 * fr)) / math.exp(2 * bw * T)
+ a[3] = -8 * (6 * math.cos(fr) + math.cos(3 * fr))
+ a[3] /= math.exp(3 * bw * T)
+ a[4] = 2 * (18 + 16 * math.cos(2 * fr) + math.cos(4 * fr))
+ a[4] /= math.exp(4 * bw * T)
+ a[5] = -8 * (6 * math.cos(fr) + math.cos(3 * fr))
+ a[5] /= math.exp(5 * bw * T)
+ a[6] = 4 * (4 + 3 * math.cos(2 * fr)) / math.exp(6 * bw * T)
+ a[7] = -8 * math.cos(fr) / math.exp(7 * bw * T)
+ a[8] = math.exp(-8 * bw * T)
+
+ return xp.asarray(b, device=device), xp.asarray(a, device=device)
+
+
+filter_dict = {'butter': [buttap, buttord],
+ 'butterworth': [buttap, buttord],
+
+ 'cauer': [ellipap, ellipord],
+ 'elliptic': [ellipap, ellipord],
+ 'ellip': [ellipap, ellipord],
+
+ 'bessel': [besselap],
+ 'bessel_phase': [besselap],
+ 'bessel_delay': [besselap],
+ 'bessel_mag': [besselap],
+
+ 'cheby1': [cheb1ap, cheb1ord],
+ 'chebyshev1': [cheb1ap, cheb1ord],
+ 'chebyshevi': [cheb1ap, cheb1ord],
+
+ 'cheby2': [cheb2ap, cheb2ord],
+ 'chebyshev2': [cheb2ap, cheb2ord],
+ 'chebyshevii': [cheb2ap, cheb2ord],
+ }
+
+band_dict = {'band': 'bandpass',
+ 'bandpass': 'bandpass',
+ 'pass': 'bandpass',
+ 'bp': 'bandpass',
+
+ 'bs': 'bandstop',
+ 'bandstop': 'bandstop',
+ 'bands': 'bandstop',
+ 'stop': 'bandstop',
+
+ 'l': 'lowpass',
+ 'low': 'lowpass',
+ 'lowpass': 'lowpass',
+ 'lp': 'lowpass',
+
+ 'high': 'highpass',
+ 'highpass': 'highpass',
+ 'h': 'highpass',
+ 'hp': 'highpass',
+ }
+
+bessel_norms = {'bessel': 'phase',
+ 'bessel_phase': 'phase',
+ 'bessel_delay': 'delay',
+ 'bessel_mag': 'mag'}
+
+
+########## complete the docstrings, on import
+_xp_device_snippet = {'xp_device_snippet':
+"""\
+xp : array_namespace, optional
+ Optional array namespace.
+ Should be compatible with the array API standard, or supported by array-api-compat.
+ Default: ``numpy``
+device: any
+ optional device specification for output. Should match one of the
+ supported device specification in ``xp``.
+"""
+}
+
+
+_names = ["buttap", "cheb1ap", "cheb2ap", "ellipap", "besselap",
+ "iirnotch", "iirpeak", "iircomb", "gammatone",
+]
+for name in _names:
+ window = vars()[name]
+ window.__doc__ = doccer.docformat(window.__doc__, _xp_device_snippet)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_fir_filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_fir_filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..a1653dfb4cbb20a8c4d8dc414286d467d283ef99
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_fir_filter_design.py
@@ -0,0 +1,1557 @@
+"""Functions for FIR filter design."""
+
+from math import ceil, log, log2
+import warnings
+from typing import Literal
+
+import numpy as np
+from scipy.fft import irfft, fft, ifft
+from scipy.linalg import (toeplitz, hankel, solve, LinAlgError, LinAlgWarning,
+ lstsq)
+from scipy.signal._arraytools import _validate_fs
+from .windows import get_window
+from . import _sigtools
+
+from scipy._lib._array_api import array_namespace, xp_size, xp_default_dtype
+import scipy._lib.array_api_extra as xpx
+
+
+__all__ = ['kaiser_beta', 'kaiser_atten', 'kaiserord',
+ 'firwin', 'firwin2', 'firwin_2d', 'remez', 'firls', 'minimum_phase']
+
+
+# Some notes on function parameters:
+#
+# `cutoff` and `width` are given as numbers between 0 and 1. These are
+# relative frequencies, expressed as a fraction of the Nyquist frequency.
+# For example, if the Nyquist frequency is 2 KHz, then width=0.15 is a width
+# of 300 Hz.
+#
+# The `order` of a FIR filter is one less than the number of taps.
+# This is a potential source of confusion, so in the following code,
+# we will always use the number of taps as the parameterization of
+# the 'size' of the filter. The "number of taps" means the number
+# of coefficients, which is the same as the length of the impulse
+# response of the filter.
+
+
+def kaiser_beta(a):
+ """Compute the Kaiser parameter `beta`, given the attenuation `a`.
+
+ Parameters
+ ----------
+ a : float
+ The desired attenuation in the stopband and maximum ripple in
+ the passband, in dB. This should be a *positive* number.
+
+ Returns
+ -------
+ beta : float
+ The `beta` parameter to be used in the formula for a Kaiser window.
+
+ References
+ ----------
+ Oppenheim, Schafer, "Discrete-Time Signal Processing", p.475-476.
+
+ Examples
+ --------
+ Suppose we want to design a lowpass filter, with 65 dB attenuation
+ in the stop band. The Kaiser window parameter to be used in the
+ window method is computed by ``kaiser_beta(65)``:
+
+ >>> from scipy.signal import kaiser_beta
+ >>> kaiser_beta(65)
+ 6.20426
+
+ """
+ if a > 50:
+ beta = 0.1102 * (a - 8.7)
+ elif a > 21:
+ beta = 0.5842 * (a - 21) ** 0.4 + 0.07886 * (a - 21)
+ else:
+ beta = 0.0
+ return beta
+
+
+def kaiser_atten(numtaps, width):
+ """Compute the attenuation of a Kaiser FIR filter.
+
+ Given the number of taps `N` and the transition width `width`, compute the
+ attenuation `a` in dB, given by Kaiser's formula:
+
+ a = 2.285 * (N - 1) * pi * width + 7.95
+
+ Parameters
+ ----------
+ numtaps : int
+ The number of taps in the FIR filter.
+ width : float
+ The desired width of the transition region between passband and
+ stopband (or, in general, at any discontinuity) for the filter,
+ expressed as a fraction of the Nyquist frequency.
+
+ Returns
+ -------
+ a : float
+ The attenuation of the ripple, in dB.
+
+ See Also
+ --------
+ kaiserord, kaiser_beta
+
+ Examples
+ --------
+ Suppose we want to design a FIR filter using the Kaiser window method
+ that will have 211 taps and a transition width of 9 Hz for a signal that
+ is sampled at 480 Hz. Expressed as a fraction of the Nyquist frequency,
+ the width is 9/(0.5*480) = 0.0375. The approximate attenuation (in dB)
+ is computed as follows:
+
+ >>> from scipy.signal import kaiser_atten
+ >>> kaiser_atten(211, 0.0375)
+ 64.48099630593983
+
+ """
+ a = 2.285 * (numtaps - 1) * np.pi * width + 7.95
+ return a
+
+
+def kaiserord(ripple, width):
+ """
+ Determine the filter window parameters for the Kaiser window method.
+
+ The parameters returned by this function are generally used to create
+ a finite impulse response filter using the window method, with either
+ `firwin` or `firwin2`.
+
+ Parameters
+ ----------
+ ripple : float
+ Upper bound for the deviation (in dB) of the magnitude of the
+ filter's frequency response from that of the desired filter (not
+ including frequencies in any transition intervals). That is, if w
+ is the frequency expressed as a fraction of the Nyquist frequency,
+ A(w) is the actual frequency response of the filter and D(w) is the
+ desired frequency response, the design requirement is that::
+
+ abs(A(w) - D(w))) < 10**(-ripple/20)
+
+ for 0 <= w <= 1 and w not in a transition interval.
+ width : float
+ Width of transition region, normalized so that 1 corresponds to pi
+ radians / sample. That is, the frequency is expressed as a fraction
+ of the Nyquist frequency.
+
+ Returns
+ -------
+ numtaps : int
+ The length of the Kaiser window.
+ beta : float
+ The beta parameter for the Kaiser window.
+
+ See Also
+ --------
+ kaiser_beta, kaiser_atten
+
+ Notes
+ -----
+ There are several ways to obtain the Kaiser window:
+
+ - ``signal.windows.kaiser(numtaps, beta, sym=True)``
+ - ``signal.get_window(beta, numtaps)``
+ - ``signal.get_window(('kaiser', beta), numtaps)``
+
+ The empirical equations discovered by Kaiser are used.
+
+ References
+ ----------
+ Oppenheim, Schafer, "Discrete-Time Signal Processing", pp.475-476.
+
+ Examples
+ --------
+ We will use the Kaiser window method to design a lowpass FIR filter
+ for a signal that is sampled at 1000 Hz.
+
+ We want at least 65 dB rejection in the stop band, and in the pass
+ band the gain should vary no more than 0.5%.
+
+ We want a cutoff frequency of 175 Hz, with a transition between the
+ pass band and the stop band of 24 Hz. That is, in the band [0, 163],
+ the gain varies no more than 0.5%, and in the band [187, 500], the
+ signal is attenuated by at least 65 dB.
+
+ >>> import numpy as np
+ >>> from scipy.signal import kaiserord, firwin, freqz
+ >>> import matplotlib.pyplot as plt
+ >>> fs = 1000.0
+ >>> cutoff = 175
+ >>> width = 24
+
+ The Kaiser method accepts just a single parameter to control the pass
+ band ripple and the stop band rejection, so we use the more restrictive
+ of the two. In this case, the pass band ripple is 0.005, or 46.02 dB,
+ so we will use 65 dB as the design parameter.
+
+ Use `kaiserord` to determine the length of the filter and the
+ parameter for the Kaiser window.
+
+ >>> numtaps, beta = kaiserord(65, width/(0.5*fs))
+ >>> numtaps
+ 167
+ >>> beta
+ 6.20426
+
+ Use `firwin` to create the FIR filter.
+
+ >>> taps = firwin(numtaps, cutoff, window=('kaiser', beta),
+ ... scale=False, fs=fs)
+
+ Compute the frequency response of the filter. ``w`` is the array of
+ frequencies, and ``h`` is the corresponding complex array of frequency
+ responses.
+
+ >>> w, h = freqz(taps, worN=8000)
+ >>> w *= 0.5*fs/np.pi # Convert w to Hz.
+
+ Compute the deviation of the magnitude of the filter's response from
+ that of the ideal lowpass filter. Values in the transition region are
+ set to ``nan``, so they won't appear in the plot.
+
+ >>> ideal = w < cutoff # The "ideal" frequency response.
+ >>> deviation = np.abs(np.abs(h) - ideal)
+ >>> deviation[(w > cutoff - 0.5*width) & (w < cutoff + 0.5*width)] = np.nan
+
+ Plot the deviation. A close look at the left end of the stop band shows
+ that the requirement for 65 dB attenuation is violated in the first lobe
+ by about 0.125 dB. This is not unusual for the Kaiser window method.
+
+ >>> plt.plot(w, 20*np.log10(np.abs(deviation)))
+ >>> plt.xlim(0, 0.5*fs)
+ >>> plt.ylim(-90, -60)
+ >>> plt.grid(alpha=0.25)
+ >>> plt.axhline(-65, color='r', ls='--', alpha=0.3)
+ >>> plt.xlabel('Frequency (Hz)')
+ >>> plt.ylabel('Deviation from ideal (dB)')
+ >>> plt.title('Lowpass Filter Frequency Response')
+ >>> plt.show()
+
+ """
+ A = abs(ripple) # in case somebody is confused as to what's meant
+ if A < 8:
+ # Formula for N is not valid in this range.
+ raise ValueError("Requested maximum ripple attenuation "
+ f"{A:f} is too small for the Kaiser formula.")
+ beta = kaiser_beta(A)
+
+ # Kaiser's formula (as given in Oppenheim and Schafer) is for the filter
+ # order, so we have to add 1 to get the number of taps.
+ numtaps = (A - 7.95) / 2.285 / (np.pi * width) + 1
+
+ return int(ceil(numtaps)), beta
+
+
+def firwin(numtaps, cutoff, *, width=None, window='hamming', pass_zero=True,
+ scale=True, fs=None):
+ r"""FIR filter design using the window method.
+
+ This function computes the coefficients of a finite impulse response
+ filter. The filter will have linear phase; it will be Type I if
+ `numtaps` is odd and Type II if `numtaps` is even.
+
+ Type II filters always have zero response at the Nyquist frequency, so a
+ ValueError exception is raised if firwin is called with `numtaps` even and
+ having a passband whose right end is at the Nyquist frequency.
+
+ Parameters
+ ----------
+ numtaps : int
+ Length of the filter (number of coefficients, i.e., the filter
+ order + 1). `numtaps` must be odd if a passband includes the
+ Nyquist frequency.
+ cutoff : float or 1-D array_like
+ Cutoff frequency of filter (expressed in the same units as `fs`)
+ or an array of cutoff frequencies (that is, band edges). In the
+ former case, as a float, the cutoff frequency should correspond
+ with the half-amplitude point, where the attenuation will be -6 dB.
+ In the latter case, the frequencies in `cutoff` should be positive
+ and monotonically increasing between 0 and `fs/2`. The values 0
+ and `fs/2` must not be included in `cutoff`. It should be noted
+ that this is different from the behavior of `~scipy.signal.iirdesign`,
+ where the cutoff is the half-power point (-3 dB).
+ width : float or None, optional
+ If not ``None``, then a `~scipy.signal.windows.kaiser` window is calculated
+ where `width` specifies the approximate width of the transition region
+ (expressed in the same unit as `fs`). This is achieved by utilizing
+ `~scipy.signal.kaiser_atten` to calculate an attenuation which is passed to
+ `~scipy.signal.kaiser_beta` for determining the β parameter for the kaiser
+ window. In this case, the `window` argument is ignored.
+ window : string or tuple of string and parameter values, optional
+ Desired window to use. Default is ``'hamming'``. The window will be symmetric,
+ unless a suffix ``'_periodic'`` is appended to the window name (e.g.,
+ ``'hamming_perodic'``) Consult `~scipy.signal.get_window` for a list of windows
+ and required parameters.
+ pass_zero : {True, False, 'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional
+ Toggles the zero frequency bin (or DC gain) to be in the passband (``True``) or
+ in the stopband (``False``). ``'bandstop'``, ``'lowpass'`` are synonyms for
+ ``True`` and ``'bandpass'``, ``'highpass'`` are synonyms for ``False``.
+ ``'lowpass'``, ``'highpass'`` additionally require `cutoff` to be a scalar
+ value or a length-one array. Default: ``True``.
+
+ .. versionadded:: 1.3.0
+ Support for string arguments.
+ scale : bool, optional
+ Set to ``True`` to scale the coefficients so that the frequency response is
+ exactly unity at a certain frequency. That frequency is either:
+
+ - 0 (DC) if the first passband starts at 0 (i.e., `pass_zero` is ``True``)
+ - `fs/2` (the Nyquist frequency) if the first passband ends at `fs/2`
+ (i.e., the filter is a single band highpass filter); center of first
+ passband otherwise
+
+ fs : float, optional
+ The sampling frequency of the signal. Each frequency in `cutoff`
+ must be between 0 and ``fs/2``. Default is 2.
+
+ Returns
+ -------
+ h : ndarray
+ FIR filter coefficients as 1d array with `numtaps` entries.
+
+ Raises
+ ------
+ ValueError
+ If any value in `cutoff` is less than or equal to 0 or greater
+ than or equal to ``fs/2``, if the values in `cutoff` are not strictly
+ monotonically increasing, or if `numtaps` is even but a passband
+ includes the Nyquist frequency.
+
+ See Also
+ --------
+ firwin2: Window method FIR filter design specifying gain-frequency pairs.
+ firwin_2d: 2D FIR filter design using the window method.
+ firls: FIR filter design using least-squares error minimization.
+ minimum_phase: Convert a FIR filter to minimum phase
+ remez: Calculate the minimax optimal filter using the Remez exchange algorithm.
+
+ Examples
+ --------
+ The following example calculates frequency responses of a 30 Hz low-pass filter
+ with various numbers of taps. The transition region width is 20 Hz. The upper plot
+ shows the gain and the lower plot the phase. The vertical dashed line marks the
+ corner frequency and the gray background the transition region.
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> import scipy.signal as signal
+ ...
+ >>> fs = 200 # sampling frequency and number of taps
+ >>> f_c, width = 30, 20 # corner frequency (-6 dB gain)
+ >>> taps = [20, 40, 60] # number of taps
+ ...
+ >>> fg, (ax0, ax1) = plt.subplots(2, 1, sharex='all', layout="constrained",
+ ... figsize=(5, 4))
+ >>> ax0.set_title(rf"Response of ${f_c}\,$Hz low-pass Filter with " +
+ ... rf"${width}\,$Hz transition region")
+ >>> ax0.set(ylabel="Gain in dB", xlim=(0, fs/2))
+ >>> ax1.set(xlabel=rf"Frequency $f\,$ in hertz (sampling frequency $f_S={fs}\,$Hz)",
+ ... ylabel="Phase in Degrees")
+ ...
+ >>> for n in taps: # calculate filter and plot response:
+ ... bb = signal.firwin(n, f_c, width=width, fs=fs)
+ ... f, H = signal.freqz(bb, fs=fs) # calculate frequency response
+ ... H_dB, H_ph = 20 * np.log10(abs(H)), np.rad2deg(np.unwrap(np.angle(H)))
+ ... H_ph[H_dB<-150] = np.nan
+ ... ax0.plot(f, H_dB, alpha=.5, label=rf"{n} taps")
+ ... ax1.plot(f, H_ph, alpha=.5, label=rf"{n} taps")
+ >>> for ax_ in (ax0, ax1):
+ ... ax_.axvspan(f_c-width/2, f_c+width/2,color='gray', alpha=.25)
+ ... ax_.axvline(f_c, color='gray', linestyle='--', alpha=.5)
+ ... ax_.grid()
+ ... ax_.legend()
+ >>> plt.show()
+
+ The plots show that with increasing number of taps, the suppression in the stopband
+ increases and the (negative) slope of the phase steepens, which signifies a longer
+ signal delay in the filter. Note that the plots contain numeric artifacts caused by
+ the limited frequency resolution: The phase jumps are not real---in reality the
+ phase is a straight line with a constant negative slope. Furthermore, the gains
+ contain zero values (i.e., -∞ dB), which are also not depicted.
+
+ The second example determines the frequency responses of a 30 Hz low-pass filter
+ with 40 taps. This time the width of the transition region varies:
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> import scipy.signal as signal
+ ...
+ >>> fs = 200 # sampling frequency and number of taps
+ >>> n, f_c = 40, 30 # number of taps and corner frequency (-6 dB gain)
+ >>> widths = (2, 10, 25) # width of transition region
+ ...
+ >>> fg, ax = plt.subplots(1, 1, layout="constrained",)
+ >>> ax.set(title=rf"Response of {n}-tap ${f_c}\,$Hz low-pass Filter",
+ ... xlabel=rf"Frequency $f\,$ in hertz (sampling frequency $f_S={fs}\,$Hz)",
+ ... ylabel="Gain in dB", xlim=(0, fs/2))
+ >>> ax.axvline(f_c, color='gray', linestyle='--', alpha=.7) # mark corner frequency
+ ...
+ >>> for width in widths: # calculate filter and plot response:
+ ... bb = signal.firwin(n, f_c, width=width, fs=fs)
+ ... f, H = signal.freqz(bb, fs=fs) # calculate frequency response
+ ... H_dB= 20 * np.log10(abs(H)) # convert to dB
+ ... ax.plot(f, H_dB, alpha=.5, label=rf"width$={width}\,$Hz")
+ ...
+ >>> ax.grid()
+ >>> ax.legend()
+ >>> plt.show()
+
+ It can be seen in the plot above that with increasing width of the transition
+ region the suppression in the stopband increases. Since the phase does not vary, it
+ is not depicted.
+
+ Instead of defining a transition region width, a window function can also be
+ specified. The plot below depicts the response of an 80 tap band-pass filter having
+ a passband ranging form 40 Hz to 60 Hz (denoted by a gray background) with
+ different windows:
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> import scipy.signal as signal
+ ...
+ >>> fs, n = 200, 80 # sampling frequency and number of taps
+ >>> cutoff = [40, 60] # corner frequencies (-6 dB gain)
+ >>> windows = ('boxcar', 'hamming', 'hann', 'blackman')
+ ...
+ >>> fg, ax = plt.subplots(1, 1, layout="constrained") # set up plotting
+ >>> ax.set(title=rf"Response of {n}-tap Filter with ${cutoff}\,$Hz passband",
+ ... xlabel=rf"Frequency $f\,$ in hertz (sampling frequency $f_S={fs}\,$Hz)",
+ ... ylabel="Gain in dB", xlim=(0, fs/2))
+ >>> ax.axvspan(*cutoff, color='gray', alpha=.25) # mark passband
+ ...
+ >>> for win in windows: # calculate filter and plot response:
+ ... bb = signal.firwin(n, cutoff, window=win, pass_zero=False, fs=fs)
+ ... f, H = signal.freqz(bb, fs=fs) # calculate frequency response
+ ... H_dB = 20 * np.log10(abs(H)) # convert to dB
+ ... ax.plot(f, H_dB, alpha=.5, label=win)
+ ...
+ >>> ax.grid()
+ >>> ax.legend()
+ >>> plt.show()
+
+ The plot shows that the choice of window mainly influences the balance of the
+ suppression in the stopband against the width of the transition region. Note that
+ utilizing the `~scipy.signal.windows.boxcar` window corresponds to just truncating
+ the ideal infinite impulse response to the length of `numtaps` samples.
+
+ The last example illustrates how to use the `cutoff` and `pass_zero` parameters to
+ create a low-pass, a high-pass, a band-stop and a band-pass filter. The desired
+ ideal frequency gain is drawn as a gray dashed line whereas the response of the FIR
+ filter is depicted as a blue continuous line:
+
+ >>> from itertools import product
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> import scipy.signal as signal
+ ...
+ >>> cutoffs = [0.5, (.25, .75)] # cutoff parameters
+ >>> fg, axx = plt.subplots(4, 1, sharex='all', layout="constrained",
+ ... figsize=(5, 4))
+ >>> for ax, (cutoff, pass_zero) in zip(axx, product(cutoffs, (True, False))):
+ ... ax.set(title=f"firwin(41, {cutoff=}, {pass_zero=}, fs=2)", ylabel="Gain")
+ ... ax.set_yticks([0.5], minor=True) # mark gain of 0.5 (= -6 dB)
+ ... ax.grid(which='minor', axis='y')
+ ...
+ ... bb = signal.firwin(41, cutoff, pass_zero=pass_zero, fs=2)
+ ... ff, HH = signal.freqz(bb, fs=2)
+ ... ax.plot(ff, abs(HH), 'C0-', label="FIR Response")
+ ...
+ ... f_d = np.hstack(([0], np.atleast_1d(cutoff), [1]))
+ ... H_d = np.tile([1, 0] if pass_zero else [0, 1], 2)[:len(f_d)]
+ ... H_d[-1] = H_d[-2] # account for symmetry at Nyquist frequency
+ ... ax.step(f_d, H_d, 'k--', where='post', alpha=.3, label="Desired Response")
+ >>> axx[-1].set(xlabel=r"Frequency $f\,$ in hertz (sampling frequency $f_S=2\,$Hz)",
+ ... xlim=(0, 1))
+ >>> plt.show()
+ """
+ # NB: scipy's version of array_namespace returns `np_compat` for int or floats
+ xp = array_namespace(cutoff)
+
+ # The major enhancements to this function added in November 2010 were
+ # developed by Tom Krauss (see ticket #902).
+ fs = _validate_fs(fs, allow_none=True)
+ fs = 2 if fs is None else fs
+
+ nyq = 0.5 * fs
+
+ cutoff = xp.asarray(cutoff, dtype=xp_default_dtype(xp))
+ cutoff = xpx.atleast_nd(cutoff, ndim=1, xp=xp) / float(nyq)
+
+ # Check for invalid input.
+ if cutoff.ndim > 1:
+ raise ValueError("The cutoff argument must be at most "
+ "one-dimensional.")
+ if xp_size(cutoff) == 0:
+ raise ValueError("At least one cutoff frequency must be given.")
+ if xp.min(cutoff) <= 0 or xp.max(cutoff) >= 1:
+ raise ValueError("Invalid cutoff frequency: frequencies must be "
+ "greater than 0 and less than fs/2.")
+ if xp.any(cutoff[1:] - cutoff[:-1] <= 0):
+ raise ValueError("Invalid cutoff frequencies: the frequencies "
+ "must be strictly increasing.")
+
+ if width is not None:
+ # A width was given. Find the beta parameter of the Kaiser window
+ # and set `window`. This overrides the value of `window` passed in.
+ atten = kaiser_atten(numtaps, float(width) / nyq)
+ beta = kaiser_beta(atten)
+ window = ('kaiser', beta)
+
+ if pass_zero in ('bandstop', 'lowpass'):
+ if pass_zero == 'lowpass':
+ if xp_size(cutoff) != 1:
+ raise ValueError('cutoff must have one element if '
+ f'pass_zero=="lowpass", got {cutoff.shape}')
+ elif xp_size(cutoff) <= 1:
+ raise ValueError('cutoff must have at least two elements if '
+ f'pass_zero=="bandstop", got {cutoff.shape}')
+ pass_zero = True
+ elif pass_zero in ('bandpass', 'highpass'):
+ if pass_zero == 'highpass':
+ if xp_size(cutoff) != 1:
+ raise ValueError('cutoff must have one element if '
+ f'pass_zero=="highpass", got {cutoff.shape}')
+ elif xp_size(cutoff) <= 1:
+ raise ValueError('cutoff must have at least two elements if '
+ f'pass_zero=="bandpass", got {cutoff.shape}')
+ pass_zero = False
+ elif not (pass_zero is True or pass_zero is False):
+ raise ValueError(f"Parameter {pass_zero=} not in (True, False, 'bandpass', " +
+ "'lowpass', 'highpass', 'bandstop')")
+
+ pass_nyquist = (xp_size(cutoff) % 2 == 0) == pass_zero
+ if pass_nyquist and numtaps % 2 == 0:
+ raise ValueError("A filter with an even number of coefficients must "
+ "have zero response at the Nyquist frequency.")
+
+ # Insert 0 and/or 1 at the ends of cutoff so that the length of cutoff
+ # is even, and each pair in cutoff corresponds to passband.
+ cutoff = xp.concat((xp.zeros(int(pass_zero)), cutoff, xp.ones(int(pass_nyquist))))
+
+
+ # `bands` is a 2-D array; each row gives the left and right edges of
+ # a passband.
+ bands = xp.reshape(cutoff, (-1, 2))
+
+ # Build up the coefficients.
+ alpha = 0.5 * (numtaps - 1)
+ m = xp.arange(0, numtaps, dtype=cutoff.dtype) - alpha
+ h = 0
+ for j in range(bands.shape[0]):
+ left, right = bands[j, 0], bands[j, 1]
+ h += right * xpx.sinc(right * m, xp=xp)
+ h -= left * xpx.sinc(left * m, xp=xp)
+
+ # Get and apply the window function.
+ win = get_window(window, numtaps, fftbins=False, xp=xp)
+ h *= win
+
+ # Now handle scaling if desired.
+ if scale:
+ # Get the first passband.
+ left, right = bands[0, ...]
+ if left == 0:
+ scale_frequency = 0.0
+ elif right == 1:
+ scale_frequency = 1.0
+ else:
+ scale_frequency = 0.5 * (left + right)
+ c = xp.cos(xp.pi * m * scale_frequency)
+ s = xp.sum(h * c)
+ h /= s
+
+ return h
+
+
+# Original version of firwin2 from scipy ticket #457, submitted by "tash".
+#
+# Rewritten by Warren Weckesser, 2010.
+def firwin2(numtaps, freq, gain, *, nfreqs=None, window='hamming',
+ antisymmetric=False, fs=None):
+ """
+ FIR filter design using the window method.
+
+ From the given frequencies `freq` and corresponding gains `gain`,
+ this function constructs an FIR filter with linear phase and
+ (approximately) the given frequency response.
+
+ Parameters
+ ----------
+ numtaps : int
+ The number of taps in the FIR filter. `numtaps` must be less than
+ `nfreqs`.
+ freq : array_like, 1-D
+ The frequency sampling points. Typically 0.0 to 1.0 with 1.0 being
+ Nyquist. The Nyquist frequency is half `fs`.
+ The values in `freq` must be nondecreasing. A value can be repeated
+ once to implement a discontinuity. The first value in `freq` must
+ be 0, and the last value must be ``fs/2``. Values 0 and ``fs/2`` must
+ not be repeated.
+ gain : array_like
+ The filter gains at the frequency sampling points. Certain
+ constraints to gain values, depending on the filter type, are applied,
+ see Notes for details.
+ nfreqs : int, optional
+ The size of the interpolation mesh used to construct the filter.
+ For most efficient behavior, this should be a power of 2 plus 1
+ (e.g, 129, 257, etc). The default is one more than the smallest
+ power of 2 that is not less than `numtaps`. `nfreqs` must be greater
+ than `numtaps`.
+ window : string or (string, float) or float, or None, optional
+ Desired window to use. Default is ``'hamming'``. The window will be symmetric,
+ unless a suffix ``'_periodic'`` is appended to the window name (e.g.,
+ ``'hamming_perodic'``) Consult `~scipy.signal.get_window` for a list of windows
+ and required parameters. If ``None``, no window function is applied.
+ antisymmetric : bool, optional
+ Whether resulting impulse response is symmetric/antisymmetric.
+ See Notes for more details.
+ fs : float, optional
+ The sampling frequency of the signal. Each frequency in `cutoff`
+ must be between 0 and ``fs/2``. Default is 2.
+
+ Returns
+ -------
+ taps : ndarray
+ The filter coefficients of the FIR filter, as a 1-D array of length
+ `numtaps`.
+
+ See Also
+ --------
+ firls
+ firwin
+ minimum_phase
+ remez
+
+ Notes
+ -----
+ From the given set of frequencies and gains, the desired response is
+ constructed in the frequency domain. The inverse FFT is applied to the
+ desired response to create the associated convolution kernel, and the
+ first `numtaps` coefficients of this kernel, scaled by `window`, are
+ returned.
+
+ The FIR filter will have linear phase. The type of filter is determined by
+ the value of 'numtaps` and `antisymmetric` flag.
+ There are four possible combinations:
+
+ - odd `numtaps`, `antisymmetric` is False, type I filter is produced
+ - even `numtaps`, `antisymmetric` is False, type II filter is produced
+ - odd `numtaps`, `antisymmetric` is True, type III filter is produced
+ - even `numtaps`, `antisymmetric` is True, type IV filter is produced
+
+ Magnitude response of all but type I filters are subjects to following
+ constraints:
+
+ - type II -- zero at the Nyquist frequency
+ - type III -- zero at zero and Nyquist frequencies
+ - type IV -- zero at zero frequency
+
+ .. versionadded:: 0.9.0
+
+ References
+ ----------
+ .. [1] Oppenheim, A. V. and Schafer, R. W., "Discrete-Time Signal
+ Processing", Prentice-Hall, Englewood Cliffs, New Jersey (1989).
+ (See, for example, Section 7.4.)
+
+ .. [2] Smith, Steven W., "The Scientist and Engineer's Guide to Digital
+ Signal Processing", Ch. 17. http://www.dspguide.com/ch17/1.htm
+
+ Examples
+ --------
+ A lowpass FIR filter with a response that is 1 on [0.0, 0.5], and
+ that decreases linearly on [0.5, 1.0] from 1 to 0:
+
+ >>> from scipy import signal
+ >>> taps = signal.firwin2(150, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0])
+ >>> print(taps[72:78])
+ [-0.02286961 -0.06362756 0.57310236 0.57310236 -0.06362756 -0.02286961]
+
+ """
+ xp = array_namespace(freq, gain)
+ freq, gain = xp.asarray(freq), xp.asarray(gain)
+
+ fs = _validate_fs(fs, allow_none=True)
+ fs = 2 if fs is None else fs
+ nyq = 0.5 * fs
+
+ if freq.shape[0] != gain.shape[0]:
+ raise ValueError('freq and gain must be of same length.')
+
+ if nfreqs is not None and numtaps >= nfreqs:
+ raise ValueError(
+ f'ntaps must be less than nfreqs, but firwin2 was called with '
+ f'ntaps={numtaps} and nfreqs={nfreqs}'
+ )
+
+ if freq[0] != 0 or freq[-1] != nyq:
+ raise ValueError('freq must start with 0 and end with fs/2.')
+ d = freq[1:] - freq[:-1]
+ if xp.any(d < 0):
+ raise ValueError('The values in freq must be nondecreasing.')
+ d2 = d[:-1] + d[1:]
+ if xp.any(d2 == 0):
+ raise ValueError('A value in freq must not occur more than twice.')
+ if freq[1] == 0:
+ raise ValueError('Value 0 must not be repeated in freq')
+ if freq[-2] == nyq:
+ raise ValueError('Value fs/2 must not be repeated in freq')
+
+ if antisymmetric:
+ if numtaps % 2 == 0:
+ ftype = 4
+ else:
+ ftype = 3
+ else:
+ if numtaps % 2 == 0:
+ ftype = 2
+ else:
+ ftype = 1
+
+ if ftype == 2 and gain[-1] != 0.0:
+ raise ValueError("A Type II filter must have zero gain at the "
+ "Nyquist frequency.")
+ elif ftype == 3 and (gain[0] != 0.0 or gain[-1] != 0.0):
+ raise ValueError("A Type III filter must have zero gain at zero "
+ "and Nyquist frequencies.")
+ elif ftype == 4 and gain[0] != 0.0:
+ raise ValueError("A Type IV filter must have zero gain at zero "
+ "frequency.")
+
+ if nfreqs is None:
+ nfreqs = 1 + 2 ** int(ceil(log(numtaps, 2)))
+
+ if xp.any(d == 0):
+ # Tweak any repeated values in freq so that interp works.
+ freq = xp.asarray(freq, copy=True)
+ eps = xp.finfo(xp_default_dtype(xp)).eps * nyq
+ for k in range(freq.shape[0] - 1):
+ if freq[k] == freq[k + 1]:
+ freq[k] = freq[k] - eps
+ freq[k + 1] = freq[k + 1] + eps
+ # Check if freq is strictly increasing after tweak
+ d = freq[1:] - freq[:-1]
+ if xp.any(d <= 0):
+ raise ValueError("freq cannot contain numbers that are too close "
+ "(within eps * (fs/2): "
+ f"{eps}) to a repeated value")
+
+ # Linearly interpolate the desired response on a uniform mesh `x`.
+ x = np.linspace(0.0, nyq, nfreqs)
+ fx = np.interp(x, np.asarray(freq), np.asarray(gain)) # XXX array-api-extra#193
+ x = xp.asarray(x)
+ fx = xp.asarray(fx)
+
+ # Adjust the phases of the coefficients so that the first `ntaps` of the
+ # inverse FFT are the desired filter coefficients.
+ shift = xp.exp(-(numtaps - 1) / 2. * 1j * xp.pi * x / nyq)
+ if ftype > 2:
+ shift *= 1j
+
+ fx2 = fx * shift
+
+ # Use irfft to compute the inverse FFT.
+ out_full = irfft(fx2)
+
+ if window is not None:
+ # Create the window to apply to the filter coefficients.
+ wind = get_window(window, numtaps, fftbins=False, xp=xp)
+ else:
+ wind = 1
+
+ # Keep only the first `numtaps` coefficients in `out`, and multiply by
+ # the window.
+ out = out_full[:numtaps] * wind
+
+ if ftype == 3:
+ out[xp_size(out) // 2] = 0.0
+
+ return out
+
+
+def remez(numtaps, bands, desired, *, weight=None, type='bandpass',
+ maxiter=25, grid_density=16, fs=None):
+ """
+ Calculate the minimax optimal filter using the Remez exchange algorithm.
+
+ Calculate the filter-coefficients for the finite impulse response
+ (FIR) filter whose transfer function minimizes the maximum error
+ between the desired gain and the realized gain in the specified
+ frequency bands using the Remez exchange algorithm.
+
+ Parameters
+ ----------
+ numtaps : int
+ The desired number of taps in the filter. The number of taps is
+ the number of terms in the filter, or the filter order plus one.
+ bands : array_like
+ A monotonic sequence containing the band edges.
+ All elements must be non-negative and less than half the sampling
+ frequency as given by `fs`.
+ desired : array_like
+ A sequence half the size of bands containing the desired gain
+ in each of the specified bands.
+ weight : array_like, optional
+ A relative weighting to give to each band region. The length of
+ `weight` has to be half the length of `bands`.
+ type : {'bandpass', 'differentiator', 'hilbert'}, optional
+ The type of filter:
+
+ * 'bandpass' : flat response in bands. This is the default.
+
+ * 'differentiator' : frequency proportional response in bands.
+
+ * 'hilbert' : filter with odd symmetry, that is, type III
+ (for even order) or type IV (for odd order)
+ linear phase filters.
+
+ maxiter : int, optional
+ Maximum number of iterations of the algorithm. Default is 25.
+ grid_density : int, optional
+ Grid density. The dense grid used in `remez` is of size
+ ``(numtaps + 1) * grid_density``. Default is 16.
+ fs : float, optional
+ The sampling frequency of the signal. Default is 1.
+
+ Returns
+ -------
+ out : ndarray
+ A rank-1 array containing the coefficients of the optimal
+ (in a minimax sense) filter.
+
+ See Also
+ --------
+ firls
+ firwin
+ firwin2
+ minimum_phase
+
+ References
+ ----------
+ .. [1] J. H. McClellan and T. W. Parks, "A unified approach to the
+ design of optimum FIR linear phase digital filters",
+ IEEE Trans. Circuit Theory, vol. CT-20, pp. 697-701, 1973.
+ .. [2] J. H. McClellan, T. W. Parks and L. R. Rabiner, "A Computer
+ Program for Designing Optimum FIR Linear Phase Digital
+ Filters", IEEE Trans. Audio Electroacoust., vol. AU-21,
+ pp. 506-525, 1973.
+
+ Examples
+ --------
+ In these examples, `remez` is used to design low-pass, high-pass,
+ band-pass and band-stop filters. The parameters that define each filter
+ are the filter order, the band boundaries, the transition widths of the
+ boundaries, the desired gains in each band, and the sampling frequency.
+
+ We'll use a sample frequency of 22050 Hz in all the examples. In each
+ example, the desired gain in each band is either 0 (for a stop band)
+ or 1 (for a pass band).
+
+ `freqz` is used to compute the frequency response of each filter, and
+ the utility function ``plot_response`` defined below is used to plot
+ the response.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> fs = 22050 # Sample rate, Hz
+
+ >>> def plot_response(w, h, title):
+ ... "Utility function to plot response functions"
+ ... fig = plt.figure()
+ ... ax = fig.add_subplot(111)
+ ... ax.plot(w, 20*np.log10(np.abs(h)))
+ ... ax.set_ylim(-40, 5)
+ ... ax.grid(True)
+ ... ax.set_xlabel('Frequency (Hz)')
+ ... ax.set_ylabel('Gain (dB)')
+ ... ax.set_title(title)
+
+ The first example is a low-pass filter, with cutoff frequency 8 kHz.
+ The filter length is 325, and the transition width from pass to stop
+ is 100 Hz.
+
+ >>> cutoff = 8000.0 # Desired cutoff frequency, Hz
+ >>> trans_width = 100 # Width of transition from pass to stop, Hz
+ >>> numtaps = 325 # Size of the FIR filter.
+ >>> taps = signal.remez(numtaps, [0, cutoff, cutoff + trans_width, 0.5*fs],
+ ... [1, 0], fs=fs)
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
+ >>> plot_response(w, h, "Low-pass Filter")
+ >>> plt.show()
+
+ This example shows a high-pass filter:
+
+ >>> cutoff = 2000.0 # Desired cutoff frequency, Hz
+ >>> trans_width = 250 # Width of transition from pass to stop, Hz
+ >>> numtaps = 125 # Size of the FIR filter.
+ >>> taps = signal.remez(numtaps, [0, cutoff - trans_width, cutoff, 0.5*fs],
+ ... [0, 1], fs=fs)
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
+ >>> plot_response(w, h, "High-pass Filter")
+ >>> plt.show()
+
+ This example shows a band-pass filter with a pass-band from 2 kHz to
+ 5 kHz. The transition width is 260 Hz and the length of the filter
+ is 63, which is smaller than in the other examples:
+
+ >>> band = [2000, 5000] # Desired pass band, Hz
+ >>> trans_width = 260 # Width of transition from pass to stop, Hz
+ >>> numtaps = 63 # Size of the FIR filter.
+ >>> edges = [0, band[0] - trans_width, band[0], band[1],
+ ... band[1] + trans_width, 0.5*fs]
+ >>> taps = signal.remez(numtaps, edges, [0, 1, 0], fs=fs)
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
+ >>> plot_response(w, h, "Band-pass Filter")
+ >>> plt.show()
+
+ The low order leads to higher ripple and less steep transitions.
+
+ The next example shows a band-stop filter.
+
+ >>> band = [6000, 8000] # Desired stop band, Hz
+ >>> trans_width = 200 # Width of transition from pass to stop, Hz
+ >>> numtaps = 175 # Size of the FIR filter.
+ >>> edges = [0, band[0] - trans_width, band[0], band[1],
+ ... band[1] + trans_width, 0.5*fs]
+ >>> taps = signal.remez(numtaps, edges, [1, 0, 1], fs=fs)
+ >>> w, h = signal.freqz(taps, [1], worN=2000, fs=fs)
+ >>> plot_response(w, h, "Band-stop Filter")
+ >>> plt.show()
+
+ """
+ xp = array_namespace(bands, desired, weight)
+ bands = np.asarray(bands)
+ desired = np.asarray(desired)
+ if weight is not None:
+ weight = np.asarray(weight)
+
+ fs = _validate_fs(fs, allow_none=True)
+ fs = 1.0 if fs is None else fs
+
+ # Convert type
+ try:
+ tnum = {'bandpass': 1, 'differentiator': 2, 'hilbert': 3}[type]
+ except KeyError as e:
+ raise ValueError("Type must be 'bandpass', 'differentiator', "
+ "or 'hilbert'") from e
+
+ # Convert weight
+ if weight is None:
+ weight = [1] * len(desired)
+
+ bands = np.asarray(bands).copy()
+ result = _sigtools._remez(numtaps, bands, desired, weight, tnum, fs,
+ maxiter, grid_density)
+ return xp.asarray(result)
+
+
+def firls(numtaps, bands, desired, *, weight=None, fs=None):
+ """
+ FIR filter design using least-squares error minimization.
+
+ Calculate the filter coefficients for the linear-phase finite
+ impulse response (FIR) filter which has the best approximation
+ to the desired frequency response described by `bands` and
+ `desired` in the least squares sense (i.e., the integral of the
+ weighted mean-squared error within the specified bands is
+ minimized).
+
+ Parameters
+ ----------
+ numtaps : int
+ The number of taps in the FIR filter. `numtaps` must be odd.
+ bands : array_like
+ A monotonic nondecreasing sequence containing the band edges in
+ Hz. All elements must be non-negative and less than or equal to
+ the Nyquist frequency given by `nyq`. The bands are specified as
+ frequency pairs, thus, if using a 1D array, its length must be
+ even, e.g., `np.array([0, 1, 2, 3, 4, 5])`. Alternatively, the
+ bands can be specified as an nx2 sized 2D array, where n is the
+ number of bands, e.g, `np.array([[0, 1], [2, 3], [4, 5]])`.
+ desired : array_like
+ A sequence the same size as `bands` containing the desired gain
+ at the start and end point of each band.
+ weight : array_like, optional
+ A relative weighting to give to each band region when solving
+ the least squares problem. `weight` has to be half the size of
+ `bands`.
+ fs : float, optional
+ The sampling frequency of the signal. Each frequency in `bands`
+ must be between 0 and ``fs/2`` (inclusive). Default is 2.
+
+ Returns
+ -------
+ coeffs : ndarray
+ Coefficients of the optimal (in a least squares sense) FIR filter.
+
+ See Also
+ --------
+ firwin
+ firwin2
+ minimum_phase
+ remez
+
+ Notes
+ -----
+ This implementation follows the algorithm given in [1]_.
+ As noted there, least squares design has multiple advantages:
+
+ 1. Optimal in a least-squares sense.
+ 2. Simple, non-iterative method.
+ 3. The general solution can obtained by solving a linear
+ system of equations.
+ 4. Allows the use of a frequency dependent weighting function.
+
+ This function constructs a Type I linear phase FIR filter, which
+ contains an odd number of `coeffs` satisfying for :math:`n < numtaps`:
+
+ .. math:: coeffs(n) = coeffs(numtaps - 1 - n)
+
+ The odd number of coefficients and filter symmetry avoid boundary
+ conditions that could otherwise occur at the Nyquist and 0 frequencies
+ (e.g., for Type II, III, or IV variants).
+
+ .. versionadded:: 0.18
+
+ References
+ ----------
+ .. [1] Ivan Selesnick, Linear-Phase Fir Filter Design By Least Squares.
+ OpenStax CNX. Aug 9, 2005.
+ https://eeweb.engineering.nyu.edu/iselesni/EL713/firls/firls.pdf
+
+ Examples
+ --------
+ We want to construct a band-pass filter. Note that the behavior in the
+ frequency ranges between our stop bands and pass bands is unspecified,
+ and thus may overshoot depending on the parameters of our filter:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> fig, axs = plt.subplots(2)
+ >>> fs = 10.0 # Hz
+ >>> desired = (0, 0, 1, 1, 0, 0)
+ >>> for bi, bands in enumerate(((0, 1, 2, 3, 4, 5), (0, 1, 2, 4, 4.5, 5))):
+ ... fir_firls = signal.firls(73, bands, desired, fs=fs)
+ ... fir_remez = signal.remez(73, bands, desired[::2], fs=fs)
+ ... fir_firwin2 = signal.firwin2(73, bands, desired, fs=fs)
+ ... hs = list()
+ ... ax = axs[bi]
+ ... for fir in (fir_firls, fir_remez, fir_firwin2):
+ ... freq, response = signal.freqz(fir)
+ ... hs.append(ax.semilogy(0.5*fs*freq/np.pi, np.abs(response))[0])
+ ... for band, gains in zip(zip(bands[::2], bands[1::2]),
+ ... zip(desired[::2], desired[1::2])):
+ ... ax.semilogy(band, np.maximum(gains, 1e-7), 'k--', linewidth=2)
+ ... if bi == 0:
+ ... ax.legend(hs, ('firls', 'remez', 'firwin2'),
+ ... loc='lower center', frameon=False)
+ ... else:
+ ... ax.set_xlabel('Frequency (Hz)')
+ ... ax.grid(True)
+ ... ax.set(title='Band-pass %d-%d Hz' % bands[2:4], ylabel='Magnitude')
+ ...
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ """
+ xp = array_namespace(bands, desired)
+ bands = np.asarray(bands)
+ desired = np.asarray(desired)
+
+ fs = _validate_fs(fs, allow_none=True)
+ fs = 2 if fs is None else fs
+ nyq = 0.5 * fs
+
+ numtaps = int(numtaps)
+ if numtaps % 2 == 0 or numtaps < 1:
+ raise ValueError("numtaps must be odd and >= 1")
+ M = (numtaps-1) // 2
+
+ # normalize bands 0->1 and make it 2 columns
+ nyq = float(nyq)
+ if nyq <= 0:
+ raise ValueError(f'nyq must be positive, got {nyq} <= 0.')
+ bands = np.asarray(bands).flatten() / nyq
+ if len(bands) % 2 != 0:
+ raise ValueError("bands must contain frequency pairs.")
+ if (bands < 0).any() or (bands > 1).any():
+ raise ValueError("bands must be between 0 and 1 relative to Nyquist")
+ bands = bands.reshape((-1, 2))
+
+ # check remaining params
+ desired = np.asarray(desired).flatten()
+ if bands.size != desired.size:
+ raise ValueError(
+ f"desired must have one entry per frequency, got {desired.size} "
+ f"gains for {bands.size} frequencies."
+ )
+ desired = desired.reshape((-1, 2))
+ if (np.diff(bands) <= 0).any() or (np.diff(bands[:, 0]) < 0).any():
+ raise ValueError("bands must be monotonically nondecreasing and have "
+ "width > 0.")
+ if (bands[:-1, 1] > bands[1:, 0]).any():
+ raise ValueError("bands must not overlap.")
+ if (desired < 0).any():
+ raise ValueError("desired must be non-negative.")
+ if weight is None:
+ weight = np.ones(len(desired))
+ weight = np.asarray(weight).flatten()
+ if len(weight) != len(desired):
+ raise ValueError("weight must be the same size as the number of "
+ f"band pairs ({len(bands)}).")
+ if (weight < 0).any():
+ raise ValueError("weight must be non-negative.")
+
+ # Set up the linear matrix equation to be solved, Qa = b
+
+ # We can express Q(k,n) = 0.5 Q1(k,n) + 0.5 Q2(k,n)
+ # where Q1(k,n)=q(k-n) and Q2(k,n)=q(k+n), i.e. a Toeplitz plus Hankel.
+
+ # We omit the factor of 0.5 above, instead adding it during coefficient
+ # calculation.
+
+ # We also omit the 1/Ï€ from both Q and b equations, as they cancel
+ # during solving.
+
+ # We have that:
+ # q(n) = 1/π ∫W(ω)cos(nω)dω (over 0->π)
+ # Using our normalization ω=πf and with a constant weight W over each
+ # interval f1->f2 we get:
+ # q(n) = W∫cos(πnf)df (0->1) = Wf sin(πnf)/πnf
+ # integrated over each f1->f2 pair (i.e., value at f2 - value at f1).
+ n = np.arange(numtaps)[:, np.newaxis, np.newaxis]
+ q = np.dot(np.diff(np.sinc(bands * n) * bands, axis=2)[:, :, 0], weight)
+
+ # Now we assemble our sum of Toeplitz and Hankel
+ Q1 = toeplitz(q[:M+1])
+ Q2 = hankel(q[:M+1], q[M:])
+ Q = Q1 + Q2
+
+ # Now for b(n) we have that:
+ # b(n) = 1/π ∫ W(ω)D(ω)cos(nω)dω (over 0->π)
+ # Using our normalization ω=πf and with a constant weight W over each
+ # interval and a linear term for D(ω) we get (over each f1->f2 interval):
+ # b(n) = W ∫ (mf+c)cos(πnf)df
+ # = f(mf+c)sin(πnf)/πnf + mf**2 cos(nπf)/(πnf)**2
+ # integrated over each f1->f2 pair (i.e., value at f2 - value at f1).
+ n = n[:M + 1] # only need this many coefficients here
+ # Choose m and c such that we are at the start and end weights
+ m = (np.diff(desired, axis=1) / np.diff(bands, axis=1))
+ c = desired[:, [0]] - bands[:, [0]] * m
+ b = bands * (m*bands + c) * np.sinc(bands * n)
+ # Use L'Hospital's rule here for cos(nπf)/(πnf)**2 @ n=0
+ b[0] -= m * bands * bands / 2.
+ b[1:] += m * np.cos(n[1:] * np.pi * bands) / (np.pi * n[1:]) ** 2
+ b = np.dot(np.diff(b, axis=2)[:, :, 0], weight)
+
+ # Now we can solve the equation
+ try: # try the fast way
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter('always')
+ a = solve(Q, b, assume_a="pos", check_finite=False)
+ for ww in w:
+ if (ww.category == LinAlgWarning and
+ str(ww.message).startswith('Ill-conditioned matrix')):
+ raise LinAlgError(str(ww.message))
+ except LinAlgError: # in case Q is rank deficient
+ # This is faster than pinvh, even though we don't explicitly use
+ # the symmetry here. gelsy was faster than gelsd and gelss in
+ # some non-exhaustive tests.
+ a = lstsq(Q, b, lapack_driver='gelsy')[0]
+
+ # make coefficients symmetric (linear phase)
+ coeffs = np.hstack((a[:0:-1], 2 * a[0], a[1:]))
+ return xp.asarray(coeffs)
+
+
+def _dhtm(mag, xp):
+ """Compute the modified 1-D discrete Hilbert transform
+
+ Parameters
+ ----------
+ mag : ndarray
+ The magnitude spectrum. Should be 1-D with an even length, and
+ preferably a fast length for FFT/IFFT.
+ """
+ # Adapted based on code by Niranjan Damera-Venkata,
+ # Brian L. Evans and Shawn R. McCaslin (see refs for `minimum_phase`)
+ sig = xp.zeros(mag.shape[0])
+ # Leave Nyquist and DC at 0, knowing np.abs(fftfreq(N)[midpt]) == 0.5
+ midpt = mag.shape[0] // 2
+ sig[1:midpt] = 1
+ sig[midpt+1:] = -1
+ # eventually if we want to support complex filters, we will need a
+ # np.abs() on the mag inside the log, and should remove the .real
+ recon = xp.real(ifft(mag * xp.exp(fft(sig * ifft(xp.log(mag))))))
+ return recon
+
+
+def minimum_phase(h,
+ method: Literal['homomorphic', 'hilbert'] = 'homomorphic',
+ n_fft: int | None = None, *, half: bool = True):
+ """Convert a linear-phase FIR filter to minimum phase
+
+ Parameters
+ ----------
+ h : array
+ Linear-phase FIR filter coefficients.
+ method : {'hilbert', 'homomorphic'}
+ The provided methods are:
+
+ 'homomorphic' (default)
+ This method [4]_ [5]_ works best with filters with an
+ odd number of taps, and the resulting minimum phase filter
+ will have a magnitude response that approximates the square
+ root of the original filter's magnitude response using half
+ the number of taps when ``half=True`` (default), or the
+ original magnitude spectrum using the same number of taps
+ when ``half=False``.
+
+ 'hilbert'
+ This method [1]_ is designed to be used with equiripple
+ filters (e.g., from `remez`) with unity or zero gain
+ regions.
+
+ n_fft : int
+ The number of points to use for the FFT. Should be at least a
+ few times larger than the signal length (see Notes).
+ half : bool
+ If ``True``, create a filter that is half the length of the original, with a
+ magnitude spectrum that is the square root of the original. If ``False``,
+ create a filter that is the same length as the original, with a magnitude
+ spectrum that is designed to match the original (only supported when
+ ``method='homomorphic'``).
+
+ .. versionadded:: 1.14.0
+
+ Returns
+ -------
+ h_minimum : array
+ The minimum-phase version of the filter, with length
+ ``(len(h) + 1) // 2`` when ``half is True`` or ``len(h)`` otherwise.
+
+ See Also
+ --------
+ firwin
+ firwin2
+ remez
+
+ Notes
+ -----
+ Both the Hilbert [1]_ or homomorphic [4]_ [5]_ methods require selection
+ of an FFT length to estimate the complex cepstrum of the filter.
+
+ In the case of the Hilbert method, the deviation from the ideal
+ spectrum ``epsilon`` is related to the number of stopband zeros
+ ``n_stop`` and FFT length ``n_fft`` as::
+
+ epsilon = 2. * n_stop / n_fft
+
+ For example, with 100 stopband zeros and a FFT length of 2048,
+ ``epsilon = 0.0976``. If we conservatively assume that the number of
+ stopband zeros is one less than the filter length, we can take the FFT
+ length to be the next power of 2 that satisfies ``epsilon=0.01`` as::
+
+ n_fft = 2 ** int(np.ceil(np.log2(2 * (len(h) - 1) / 0.01)))
+
+ This gives reasonable results for both the Hilbert and homomorphic
+ methods, and gives the value used when ``n_fft=None``.
+
+ Alternative implementations exist for creating minimum-phase filters,
+ including zero inversion [2]_ and spectral factorization [3]_ [4]_.
+ For more information, see `this DSPGuru page
+ `__.
+
+ References
+ ----------
+ .. [1] N. Damera-Venkata and B. L. Evans, "Optimal design of real and
+ complex minimum phase digital FIR filters," Acoustics, Speech,
+ and Signal Processing, 1999. Proceedings., 1999 IEEE International
+ Conference on, Phoenix, AZ, 1999, pp. 1145-1148 vol.3.
+ :doi:`10.1109/ICASSP.1999.756179`
+ .. [2] X. Chen and T. W. Parks, "Design of optimal minimum phase FIR
+ filters by direct factorization," Signal Processing,
+ vol. 10, no. 4, pp. 369-383, Jun. 1986.
+ .. [3] T. Saramaki, "Finite Impulse Response Filter Design," in
+ Handbook for Digital Signal Processing, chapter 4,
+ New York: Wiley-Interscience, 1993.
+ .. [4] J. S. Lim, Advanced Topics in Signal Processing.
+ Englewood Cliffs, N.J.: Prentice Hall, 1988.
+ .. [5] A. V. Oppenheim, R. W. Schafer, and J. R. Buck,
+ "Discrete-Time Signal Processing," 3rd edition.
+ Upper Saddle River, N.J.: Pearson, 2009.
+
+ Examples
+ --------
+ Create an optimal linear-phase low-pass filter `h` with a transition band of
+ [0.2, 0.3] (assuming a Nyquist frequency of 1):
+
+ >>> import numpy as np
+ >>> from scipy.signal import remez, minimum_phase, freqz, group_delay
+ >>> import matplotlib.pyplot as plt
+ >>> freq = [0, 0.2, 0.3, 1.0]
+ >>> desired = [1, 0]
+ >>> h_linear = remez(151, freq, desired, fs=2)
+
+ Convert it to minimum phase:
+
+ >>> h_hil = minimum_phase(h_linear, method='hilbert')
+ >>> h_hom = minimum_phase(h_linear, method='homomorphic')
+ >>> h_hom_full = minimum_phase(h_linear, method='homomorphic', half=False)
+
+ Compare the impulse and frequency response of the four filters:
+
+ >>> fig0, ax0 = plt.subplots(figsize=(6, 3), tight_layout=True)
+ >>> fig1, axs = plt.subplots(3, sharex='all', figsize=(6, 6), tight_layout=True)
+ >>> ax0.set_title("Impulse response")
+ >>> ax0.set(xlabel='Samples', ylabel='Amplitude', xlim=(0, len(h_linear) - 1))
+ >>> axs[0].set_title("Frequency Response")
+ >>> axs[0].set(xlim=(0, .65), ylabel="Magnitude / dB")
+ >>> axs[1].set(ylabel="Phase / rad")
+ >>> axs[2].set(ylabel="Group Delay / samples", ylim=(-31, 81),
+ ... xlabel='Normalized Frequency (Nyqist frequency: 1)')
+ >>> for h, lb in ((h_linear, f'Linear ({len(h_linear)})'),
+ ... (h_hil, f'Min-Hilbert ({len(h_hil)})'),
+ ... (h_hom, f'Min-Homomorphic ({len(h_hom)})'),
+ ... (h_hom_full, f'Min-Homom. Full ({len(h_hom_full)})')):
+ ... w_H, H = freqz(h, fs=2)
+ ... w_gd, gd = group_delay((h, 1), fs=2)
+ ...
+ ... alpha = 1.0 if lb == 'linear' else 0.5 # full opacity for 'linear' line
+ ... ax0.plot(h, '.-', alpha=alpha, label=lb)
+ ... axs[0].plot(w_H, 20 * np.log10(np.abs(H)), alpha=alpha)
+ ... axs[1].plot(w_H, np.unwrap(np.angle(H)), alpha=alpha, label=lb)
+ ... axs[2].plot(w_gd, gd, alpha=alpha)
+ >>> ax0.grid(True)
+ >>> ax0.legend(title='Filter Phase (Order)')
+ >>> axs[1].legend(title='Filter Phase (Order)', loc='lower right')
+ >>> for ax_ in axs: # shade transition band:
+ ... ax_.axvspan(freq[1], freq[2], color='y', alpha=.25)
+ ... ax_.grid(True)
+ >>> plt.show()
+
+ The impulse response and group delay plot depict the 75 sample delay of the linear
+ phase filter `h`. The phase should also be linear in the stop band--due to the small
+ magnitude, numeric noise dominates there. Furthermore, the plots show that the
+ minimum phase filters clearly show a reduced (negative) phase slope in the pass and
+ transition band. The plots also illustrate that the filter with parameters
+ ``method='homomorphic', half=False`` has same order and magnitude response as the
+ linear filter `h` whereas the other minimum phase filters have only half the order
+ and the square root of the magnitude response.
+ """
+ xp = array_namespace(h)
+
+ h = xp.asarray(h)
+ if xp.isdtype(h.dtype, "complex floating"):
+ raise ValueError('Complex filters not supported')
+ if h.ndim != 1 or h.shape[0] <= 2:
+ raise ValueError('h must be 1-D and at least 2 samples long')
+ n_half = h.shape[0] // 2
+
+ if not xp.any(xp.flip(h[-n_half:]) - h[:n_half] <= 1e-8 + 1e-6*abs(h[:n_half])):
+ warnings.warn('h does not appear to by symmetric, conversion may fail',
+ RuntimeWarning, stacklevel=2)
+ if not isinstance(method, str) or method not in \
+ ('homomorphic', 'hilbert',):
+ raise ValueError(f'method must be "homomorphic" or "hilbert", got {method!r}')
+ if method == "hilbert" and not half:
+ raise ValueError("`half=False` is only supported when `method='homomorphic'`")
+ if n_fft is None:
+ n_fft = 2 ** int(ceil(log2(2 * (h.shape[0] - 1) / 0.01)))
+ n_fft = int(n_fft)
+ if n_fft < h.shape[0]:
+ raise ValueError(f'n_fft must be at least len(h)=={len(h)}')
+
+ if method == 'hilbert':
+ w = xp.arange(n_fft, dtype=xp.float64) * (2 * xp.pi / n_fft * n_half)
+ H = xp.real(fft(h, n_fft) * xp.exp(1j * w))
+ dp = max(H) - 1
+ ds = 0 - min(H)
+ S = 4. / (xp.sqrt(1+dp+ds) + xp.sqrt(1-dp+ds)) ** 2
+ H += ds
+ H *= S
+ H = xp.sqrt(H)
+ H += 1e-10 # ensure that the log does not explode
+ h_minimum = _dhtm(H, xp)
+ else: # method == 'homomorphic'
+ # zero-pad; calculate the DFT
+ h_temp = xp.abs(fft(h, n_fft))
+ # take 0.25*log(|H|**2) = 0.5*log(|H|)
+ h_temp += 1e-7 * xp.min(h_temp[h_temp > 0]) # don't let log blow up
+ h_temp = xp.log(h_temp)
+ if half: # halving of magnitude spectrum optional
+ h_temp *= 0.5
+ # IDFT
+ h_temp = xp.real(ifft(h_temp))
+ # multiply pointwise by the homomorphic filter
+ # lmin[n] = 2u[n] - d[n]
+ # i.e., double the positive frequencies and zero out the negative ones;
+ # Oppenheim+Shafer 3rd ed p991 eq13.42b and p1004 fig13.7
+ win = xp.zeros(n_fft)
+ win[0] = 1
+ stop = n_fft // 2
+ win[1:stop] = 2
+ if n_fft % 2:
+ win[stop] = 1
+ h_temp *= win
+ h_temp = ifft(xp.exp(fft(h_temp)))
+ h_minimum = h_temp.real
+ n_out = (n_half + h.shape[0] % 2) if half else h.shape[0]
+ return h_minimum[:n_out]
+
+
+def firwin_2d(hsize, window, *, fc=None, fs=2, circular=False,
+ pass_zero=True, scale=True):
+ """
+ 2D FIR filter design using the window method.
+
+ This function computes the coefficients of a 2D finite impulse response
+ filter. The filter is separable with linear phase; it will be designed
+ as a product of two 1D filters with dimensions defined by `hsize`.
+ Additionally, it can create approximately circularly symmetric 2-D windows.
+
+ Parameters
+ ----------
+ hsize : tuple or list of length 2
+ Lengths of the filter in each dimension. `hsize[0]` specifies the
+ number of coefficients in the row direction and `hsize[1]` specifies
+ the number of coefficients in the column direction.
+ window : tuple or list of length 2 or string
+ Desired window to use for each 1D filter or a single window type for creating
+ circularly symmetric 2-D windows. Each element should be a string or tuple of
+ string and parameter values. The generated windows will be symmetric, unless a
+ suffix ``'_periodic'`` is appended to the window name (e.g.,
+ ``'hamming_perodic'``). Consult `~scipy.signal.get_window` for a list of windows
+ and required parameters.
+ fc : float or 1-D array_like, optional
+ Cutoff frequency of the filter in the same units as `fs`. This defines
+ the frequency at which the filter's gain drops to approximately -6 dB
+ (half power) in a low-pass or high-pass filter. For multi-band filters,
+ `fc` can be an array of cutoff frequencies (i.e., band edges) in the
+ range [0, fs/2], with each band specified in pairs. Required if
+ `circular` is False.
+ fs : float, optional
+ The sampling frequency of the signal. Default is 2.
+ circular : bool, optional
+ Whether to create a circularly symmetric 2-D window. Default is ``False``.
+ pass_zero : {True, False, 'bandpass', 'lowpass', 'highpass', 'bandstop'}, optional
+ This parameter is directly passed to `firwin` for each scalar frequency axis.
+ Hence, if ``True``, the DC gain, i.e., the gain at frequency (0, 0), is 1.
+ If ``False``, the DC gain is 0 at frequency (0, 0) if `circular` is ``True``.
+ If `circular` is ``False`` the frequencies (0, f1) and (f0, 0) will
+ have gain 0.
+ It can also be a string argument for the desired filter type
+ (equivalent to ``btype`` in IIR design functions).
+ scale : bool, optional
+ This parameter is directly passed to `firwin` for each scalar frequency axis.
+ Set to ``True`` to scale the coefficients so that the frequency
+ response is exactly unity at a certain frequency on one frequency axis.
+ That frequency is either:
+
+ - 0 (DC) if the first passband starts at 0 (i.e. pass_zero is ``True``)
+ - `fs`/2 (the Nyquist frequency) if the first passband ends at `fs`/2
+ (i.e., the filter is a single band highpass filter);
+ center of first passband otherwise
+
+ Returns
+ -------
+ filter_2d : (hsize[0], hsize[1]) ndarray
+ Coefficients of 2D FIR filter.
+
+ Raises
+ ------
+ ValueError
+ - If `hsize` and `window` are not 2-element tuples or lists.
+ - If `cutoff` is None when `circular` is True.
+ - If `cutoff` is outside the range [0, `fs`/2] and `circular` is ``False``.
+ - If any of the elements in `window` are not recognized.
+ RuntimeError
+ If `firwin` fails to converge when designing the filter.
+
+ See Also
+ --------
+ firwin: FIR filter design using the window method for 1d arrays.
+ get_window: Return a window of a given length and type.
+
+ Examples
+ --------
+ Generate a 5x5 low-pass filter with cutoff frequency 0.1:
+
+ >>> import numpy as np
+ >>> from scipy.signal import get_window
+ >>> from scipy.signal import firwin_2d
+ >>> hsize = (5, 5)
+ >>> window = (("kaiser", 5.0), ("kaiser", 5.0))
+ >>> fc = 0.1
+ >>> filter_2d = firwin_2d(hsize, window, fc=fc)
+ >>> filter_2d
+ array([[0.00025366, 0.00401662, 0.00738617, 0.00401662, 0.00025366],
+ [0.00401662, 0.06360159, 0.11695714, 0.06360159, 0.00401662],
+ [0.00738617, 0.11695714, 0.21507283, 0.11695714, 0.00738617],
+ [0.00401662, 0.06360159, 0.11695714, 0.06360159, 0.00401662],
+ [0.00025366, 0.00401662, 0.00738617, 0.00401662, 0.00025366]])
+
+ Generate a circularly symmetric 5x5 low-pass filter with Hamming window:
+
+ >>> filter_2d = firwin_2d((5, 5), 'hamming', fc=fc, circular=True)
+ >>> filter_2d
+ array([[-0.00020354, -0.00020354, -0.00020354, -0.00020354, -0.00020354],
+ [-0.00020354, 0.01506844, 0.09907658, 0.01506844, -0.00020354],
+ [-0.00020354, 0.09907658, -0.00020354, 0.09907658, -0.00020354],
+ [-0.00020354, 0.01506844, 0.09907658, 0.01506844, -0.00020354],
+ [-0.00020354, -0.00020354, -0.00020354, -0.00020354, -0.00020354]])
+
+ Generate Plots comparing the product of two 1d filters with a circular
+ symmetric filter:
+
+ >>> import matplotlib.pyplot as plt
+ >>> hsize, fc = (50, 50), 0.05
+ >>> window = (("kaiser", 5.0), ("kaiser", 5.0))
+ >>> filter0_2d = firwin_2d(hsize, window, fc=fc)
+ >>> filter1_2d = firwin_2d((50, 50), 'hamming', fc=fc, circular=True)
+ ...
+ >>> fg, (ax0, ax1) = plt.subplots(1, 2, tight_layout=True, figsize=(6.5, 3.5))
+ >>> ax0.set_title("Product of 2 Windows")
+ >>> im0 = ax0.imshow(filter0_2d, cmap='viridis', origin='lower', aspect='equal')
+ >>> fg.colorbar(im0, ax=ax0, shrink=0.7)
+ >>> ax1.set_title("Circular Window")
+ >>> im1 = ax1.imshow(filter1_2d, cmap='plasma', origin='lower', aspect='equal')
+ >>> fg.colorbar(im1, ax=ax1, shrink=0.7)
+ >>> plt.show()
+ """
+ if len(hsize) != 2:
+ raise ValueError("hsize must be a 2-element tuple or list")
+
+ if circular:
+ if fc is None:
+ raise ValueError("Cutoff frequency `fc` must be "
+ "provided when `circular` is True")
+
+ n_r = max(hsize[0], hsize[1]) * 8 # oversample 1d window by factor 8
+
+ win_r = firwin(n_r, cutoff=fc, window=window, fs=fs)
+
+ f1, f2 = np.meshgrid(np.linspace(-1, 1, hsize[0]), np.linspace(-1, 1, hsize[1]))
+ r = np.sqrt(f1**2 + f2**2)
+
+ win_2d = np.interp(r, np.linspace(0, 1, n_r), win_r)
+ return win_2d
+
+ if len(window) != 2:
+ raise ValueError("window must be a 2-element tuple or list")
+
+ row_filter = firwin(hsize[0], cutoff=fc, window=window[0], fs=fs)
+ col_filter = firwin(hsize[1], cutoff=fc, window=window[1], fs=fs)
+
+ return np.outer(row_filter, col_filter)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_lti_conversion.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_lti_conversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..6a42e320420d7f3025f3bbc358f1c866cdb568b1
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_lti_conversion.py
@@ -0,0 +1,555 @@
+"""
+ltisys -- a collection of functions to convert linear time invariant systems
+from one representation to another.
+"""
+
+import numpy as np
+from numpy import (r_, eye, atleast_2d, poly, dot,
+ asarray, zeros, array, outer)
+from scipy import linalg
+
+from scipy._lib._array_api import array_namespace, xp_size
+import scipy._lib.array_api_extra as xpx
+from ._filter_design import tf2zpk, zpk2tf, normalize
+
+
+__all__ = ['tf2ss', 'abcd_normalize', 'ss2tf', 'zpk2ss', 'ss2zpk',
+ 'cont2discrete']
+
+
+def tf2ss(num, den):
+ r"""Transfer function to state-space representation.
+
+ Parameters
+ ----------
+ num, den : array_like
+ Sequences representing the coefficients of the numerator and
+ denominator polynomials, in order of descending degree. The
+ denominator needs to be at least as long as the numerator.
+
+ Returns
+ -------
+ A, B, C, D : ndarray
+ State space representation of the system, in controller canonical
+ form.
+
+ Examples
+ --------
+ Convert the transfer function:
+
+ .. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}
+
+ >>> num = [1, 3, 3]
+ >>> den = [1, 2, 1]
+
+ to the state-space representation:
+
+ .. math::
+
+ \dot{\textbf{x}}(t) =
+ \begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) +
+ \begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\
+
+ \textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) +
+ \begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t)
+
+ >>> from scipy.signal import tf2ss
+ >>> A, B, C, D = tf2ss(num, den)
+ >>> A
+ array([[-2., -1.],
+ [ 1., 0.]])
+ >>> B
+ array([[ 1.],
+ [ 0.]])
+ >>> C
+ array([[ 1., 2.]])
+ >>> D
+ array([[ 1.]])
+ """
+ # Controller canonical state-space representation.
+ # if M+1 = len(num) and K+1 = len(den) then we must have M <= K
+ # states are found by asserting that X(s) = U(s) / D(s)
+ # then Y(s) = N(s) * X(s)
+ #
+ # A, B, C, and D follow quite naturally.
+ #
+ num, den = normalize(num, den) # Strips zeros, checks arrays
+ nn = len(num.shape)
+ if nn == 1:
+ num = asarray([num], num.dtype)
+ M = num.shape[1]
+ K = len(den)
+ if M > K:
+ msg = "Improper transfer function. `num` is longer than `den`."
+ raise ValueError(msg)
+ if M == 0 or K == 0: # Null system
+ return (array([], float), array([], float), array([], float),
+ array([], float))
+
+ # pad numerator to have same number of columns has denominator
+ num = np.hstack((np.zeros((num.shape[0], K - M), dtype=num.dtype), num))
+
+ if num.shape[-1] > 0:
+ D = atleast_2d(num[:, 0])
+
+ else:
+ # We don't assign it an empty array because this system
+ # is not 'null'. It just doesn't have a non-zero D
+ # matrix. Thus, it should have a non-zero shape so that
+ # it can be operated on by functions like 'ss2tf'
+ D = array([[0]], float)
+
+ if K == 1:
+ D = D.reshape(num.shape)
+
+ return (zeros((1, 1)), zeros((1, D.shape[1])),
+ zeros((D.shape[0], 1)), D)
+
+ frow = -array([den[1:]])
+ A = r_[frow, eye(K - 2, K - 1)]
+ B = eye(K - 1, 1)
+ C = num[:, 1:] - outer(num[:, 0], den[1:])
+ D = D.reshape((C.shape[0], B.shape[1]))
+
+ return A, B, C, D
+
+
+def abcd_normalize(A=None, B=None, C=None, D=None):
+ """Check state-space matrices compatibility and ensure they are 2d arrays.
+
+ Converts input matrices into two-dimensional arrays as needed. Then the dimensions
+ n, q, p are determined by investigating the non-zero entries of the array shapes.
+ If a parameter is ``None``, or has shape (0, 0), it is set to a
+ zero-array of compatible shape. Finally, it is verified that all parameter shapes
+ are compatible to each other. If that fails, a ``ValueError`` is raised. Note that
+ the dimensions n, q, p are allowed to be zero.
+
+ Parameters
+ ----------
+ A: array_like, optional
+ Two-dimensional array of shape (n, n).
+ B: array_like, optional
+ Two-dimensional array of shape (n, p).
+ C: array_like, optional
+ Two-dimensional array of shape (q, n).
+ D: array_like, optional
+ Two-dimensional array of shape (q, p).
+
+ Returns
+ -------
+ A, B, C, D : array
+ State-space matrices as two-dimensional arrays.
+
+ Notes
+ -----
+ The :ref:`tutorial_signal_state_space_representation` section of the
+ :ref:`user_guide` presents the corresponding definitions of continuous-time and
+ disrcete time state space systems.
+
+ Raises
+ ------
+ ValueError
+ If the dimensions n, q, or p could not be determined or if the shapes are
+ incompatible with each other.
+
+ See Also
+ --------
+ StateSpace: Linear Time Invariant system in state-space form.
+ dlti: Discrete-time linear time invariant system base class.
+ tf2ss: Transfer function to state-space representation.
+ ss2tf: State-space to transfer function.
+ ss2zpk: State-space representation to zero-pole-gain representation.
+ cont2discrete: Transform a continuous to a discrete state-space system.
+
+ Examples
+ --------
+ The following example demonstrates that the passed lists are converted into
+ two-dimensional arrays:
+
+ >>> from scipy.signal import abcd_normalize
+ >>> AA, BB, CC, DD = abcd_normalize(A=[[1, 2], [3, 4]], B=[[-1], [5]],
+ ... C=[[4, 5]], D=2.5)
+ >>> AA.shape, BB.shape, CC.shape, DD.shape
+ ((2, 2), (2, 1), (1, 2), (1, 1))
+
+ In the following, the missing parameter C is assumed to be an array of zeros
+ with shape (1, 2):
+
+ >>> from scipy.signal import abcd_normalize
+ >>> AA, BB, CC, DD = abcd_normalize(A=[[1, 2], [3, 4]], B=[[-1], [5]], D=2.5)
+ >>> AA.shape, BB.shape, CC.shape, DD.shape
+ ((2, 2), (2, 1), (1, 2), (1, 1))
+ >>> CC
+ array([[0., 0.]])
+ """
+ if A is None and B is None and C is None:
+ raise ValueError("Dimension n is undefined for parameters A = B = C = None!")
+ if B is None and D is None:
+ raise ValueError("Dimension p is undefined for parameters B = D = None!")
+ if C is None and D is None:
+ raise ValueError("Dimension q is undefined for parameters C = D = None!")
+
+ xp = array_namespace(A, B, C, D)
+ A, B, C, D = (xpx.atleast_nd(xp.asarray(M_), ndim=2) if M_ is not None else
+ xp.zeros((0, 0)) for M_ in (A, B, C, D))
+
+ n = A.shape[0] or B.shape[0] or C.shape[1] or 0 # try finding non-zero dimensions
+ p = B.shape[1] or D.shape[1] or 0
+ q = C.shape[0] or D.shape[0] or 0
+
+ A = xp.zeros((n, n)) if xp_size(A) == 0 else A # Create zero-matrices if needed
+ B = xp.zeros((n, p)) if xp_size(B) == 0 else B
+ C = xp.zeros((q, n)) if xp_size(C) == 0 else C
+ D = xp.zeros((q, p)) if xp_size(D) == 0 else D
+
+ if A.shape != (n, n):
+ raise ValueError(f"Parameter A has shape {A.shape} but should be ({n}, {n})!")
+ if B.shape != (n, p):
+ raise ValueError(f"Parameter B has shape {B.shape} but should be ({n}, {p})!")
+ if C.shape != (q, n):
+ raise ValueError(f"Parameter C has shape {C.shape} but should be ({q}, {n})!")
+ if D.shape != (q, p):
+ raise ValueError(f"Parameter D has shape {D.shape} but should be ({q}, {p})!")
+
+ return A, B, C, D
+
+
+def ss2tf(A, B, C, D, input=0):
+ r"""State-space to transfer function.
+
+ A, B, C, D defines a linear state-space system with `p` inputs,
+ `q` outputs, and `n` state variables.
+
+ Parameters
+ ----------
+ A : array_like
+ State (or system) matrix of shape ``(n, n)``
+ B : array_like
+ Input matrix of shape ``(n, p)``
+ C : array_like
+ Output matrix of shape ``(q, n)``
+ D : array_like
+ Feedthrough (or feedforward) matrix of shape ``(q, p)``
+ input : int, optional
+ For multiple-input systems, the index of the input to use.
+
+ Returns
+ -------
+ num : 2-D ndarray
+ Numerator(s) of the resulting transfer function(s). `num` has one row
+ for each of the system's outputs. Each row is a sequence representation
+ of the numerator polynomial.
+ den : 1-D ndarray
+ Denominator of the resulting transfer function(s). `den` is a sequence
+ representation of the denominator polynomial.
+
+ Examples
+ --------
+ Convert the state-space representation:
+
+ .. math::
+
+ \dot{\textbf{x}}(t) =
+ \begin{bmatrix} -2 & -1 \\ 1 & 0 \end{bmatrix} \textbf{x}(t) +
+ \begin{bmatrix} 1 \\ 0 \end{bmatrix} \textbf{u}(t) \\
+
+ \textbf{y}(t) = \begin{bmatrix} 1 & 2 \end{bmatrix} \textbf{x}(t) +
+ \begin{bmatrix} 1 \end{bmatrix} \textbf{u}(t)
+
+ >>> A = [[-2, -1], [1, 0]]
+ >>> B = [[1], [0]] # 2-D column vector
+ >>> C = [[1, 2]] # 2-D row vector
+ >>> D = 1
+
+ to the transfer function:
+
+ .. math:: H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}
+
+ >>> from scipy.signal import ss2tf
+ >>> ss2tf(A, B, C, D)
+ (array([[1., 3., 3.]]), array([ 1., 2., 1.]))
+ """
+ # transfer function is C (sI - A)**(-1) B + D
+
+ # Check consistency and make them all rank-2 arrays
+ A, B, C, D = abcd_normalize(A, B, C, D)
+
+ nout, nin = D.shape
+ if input >= nin:
+ raise ValueError("System does not have the input specified.")
+
+ # make SIMO from possibly MIMO system.
+ B = B[:, input:input + 1]
+ D = D[:, input:input + 1]
+
+ try:
+ den = poly(A)
+ except ValueError:
+ den = 1
+
+ if (B.size == 0) and (C.size == 0):
+ num = np.ravel(D)
+ if (D.size == 0) and (A.size == 0):
+ den = []
+ return num, den
+
+ num_states = A.shape[0]
+ type_test = A[:, 0] + B[:, 0] + C[0, :] + D + 0.0
+ num = np.empty((nout, num_states + 1), type_test.dtype)
+ for k in range(nout):
+ Ck = atleast_2d(C[k, :])
+ num[k] = poly(A - dot(B, Ck)) + (D[k] - 1) * den
+
+ return num, den
+
+
+def zpk2ss(z, p, k):
+ """Zero-pole-gain representation to state-space representation
+
+ Parameters
+ ----------
+ z, p : sequence
+ Zeros and poles.
+ k : float
+ System gain.
+
+ Returns
+ -------
+ A, B, C, D : ndarray
+ State space representation of the system, in controller canonical
+ form.
+
+ """
+ return tf2ss(*zpk2tf(z, p, k))
+
+
+def ss2zpk(A, B, C, D, input=0):
+ """State-space representation to zero-pole-gain representation.
+
+ A, B, C, D defines a linear state-space system with `p` inputs,
+ `q` outputs, and `n` state variables.
+
+ Parameters
+ ----------
+ A : array_like
+ State (or system) matrix of shape ``(n, n)``
+ B : array_like
+ Input matrix of shape ``(n, p)``
+ C : array_like
+ Output matrix of shape ``(q, n)``
+ D : array_like
+ Feedthrough (or feedforward) matrix of shape ``(q, p)``
+ input : int, optional
+ For multiple-input systems, the index of the input to use.
+
+ Returns
+ -------
+ z, p : sequence
+ Zeros and poles.
+ k : float
+ System gain.
+
+ """
+ return tf2zpk(*ss2tf(A, B, C, D, input=input))
+
+
+def cont2discrete(system, dt, method="zoh", alpha=None):
+ """
+ Transform a continuous to a discrete state-space system.
+
+ Parameters
+ ----------
+ system : a tuple describing the system or an instance of `lti`
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1: (instance of `lti`)
+ * 2: (num, den)
+ * 3: (zeros, poles, gain)
+ * 4: (A, B, C, D)
+
+ dt : float
+ The discretization time step.
+ method : str, optional
+ Which method to use:
+
+ * gbt: generalized bilinear transformation
+ * bilinear: Tustin's approximation ("gbt" with alpha=0.5)
+ * euler: Euler (or forward differencing) method ("gbt" with alpha=0)
+ * backward_diff: Backwards differencing ("gbt" with alpha=1.0)
+ * zoh: zero-order hold (default)
+ * foh: first-order hold (*versionadded: 1.3.0*)
+ * impulse: equivalent impulse response (*versionadded: 1.3.0*)
+
+ alpha : float within [0, 1], optional
+ The generalized bilinear transformation weighting parameter, which
+ should only be specified with method="gbt", and is ignored otherwise
+
+ Returns
+ -------
+ sysd : tuple containing the discrete system
+ Based on the input type, the output will be of the form
+
+ * (num, den, dt) for transfer function input
+ * (zeros, poles, gain, dt) for zeros-poles-gain input
+ * (A, B, C, D, dt) for state-space system input
+
+ Notes
+ -----
+ By default, the routine uses a Zero-Order Hold (zoh) method to perform
+ the transformation. Alternatively, a generalized bilinear transformation
+ may be used, which includes the common Tustin's bilinear approximation,
+ an Euler's method technique, or a backwards differencing technique.
+
+ The Zero-Order Hold (zoh) method is based on [1]_, the generalized bilinear
+ approximation is based on [2]_ and [3]_, the First-Order Hold (foh) method
+ is based on [4]_.
+
+ References
+ ----------
+ .. [1] https://en.wikipedia.org/wiki/Discretization#Discretization_of_linear_state_space_models
+
+ .. [2] http://techteach.no/publications/discretetime_signals_systems/discrete.pdf
+
+ .. [3] G. Zhang, X. Chen, and T. Chen, Digital redesign via the generalized
+ bilinear transformation, Int. J. Control, vol. 82, no. 4, pp. 741-754,
+ 2009.
+ (https://www.mypolyuweb.hk/~magzhang/Research/ZCC09_IJC.pdf)
+
+ .. [4] G. F. Franklin, J. D. Powell, and M. L. Workman, Digital control
+ of dynamic systems, 3rd ed. Menlo Park, Calif: Addison-Wesley,
+ pp. 204-206, 1998.
+
+ Examples
+ --------
+ We can transform a continuous state-space system to a discrete one:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import cont2discrete, lti, dlti, dstep
+
+ Define a continuous state-space system.
+
+ >>> A = np.array([[0, 1],[-10., -3]])
+ >>> B = np.array([[0],[10.]])
+ >>> C = np.array([[1., 0]])
+ >>> D = np.array([[0.]])
+ >>> l_system = lti(A, B, C, D)
+ >>> t, x = l_system.step(T=np.linspace(0, 5, 100))
+ >>> fig, ax = plt.subplots()
+ >>> ax.plot(t, x, label='Continuous', linewidth=3)
+
+ Transform it to a discrete state-space system using several methods.
+
+ >>> dt = 0.1
+ >>> for method in ['zoh', 'bilinear', 'euler', 'backward_diff', 'foh', 'impulse']:
+ ... d_system = cont2discrete((A, B, C, D), dt, method=method)
+ ... s, x_d = dstep(d_system)
+ ... ax.step(s, np.squeeze(x_d), label=method, where='post')
+ >>> ax.axis([t[0], t[-1], x[0], 1.4])
+ >>> ax.legend(loc='best')
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ """
+ if hasattr(system, 'to_discrete') and callable(system.to_discrete):
+ return system.to_discrete(dt=dt, method=method, alpha=alpha)
+
+ if len(system) == 2:
+ sysd = cont2discrete(tf2ss(system[0], system[1]), dt, method=method,
+ alpha=alpha)
+ return ss2tf(sysd[0], sysd[1], sysd[2], sysd[3]) + (dt,)
+ elif len(system) == 3:
+ sysd = cont2discrete(zpk2ss(system[0], system[1], system[2]), dt,
+ method=method, alpha=alpha)
+ return ss2zpk(sysd[0], sysd[1], sysd[2], sysd[3]) + (dt,)
+ elif len(system) == 4:
+ a, b, c, d = system
+ else:
+ raise ValueError("First argument must either be a tuple of 2 (tf), "
+ "3 (zpk), or 4 (ss) arrays.")
+
+ if method == 'gbt':
+ if alpha is None:
+ raise ValueError("Alpha parameter must be specified for the "
+ "generalized bilinear transform (gbt) method")
+ elif alpha < 0 or alpha > 1:
+ raise ValueError("Alpha parameter must be within the interval "
+ "[0,1] for the gbt method")
+
+ if method == 'gbt':
+ # This parameter is used repeatedly - compute once here
+ ima = np.eye(a.shape[0]) - alpha*dt*a
+ ad = linalg.solve(ima, np.eye(a.shape[0]) + (1.0-alpha)*dt*a)
+ bd = linalg.solve(ima, dt*b)
+
+ # Similarly solve for the output equation matrices
+ cd = linalg.solve(ima.transpose(), c.transpose())
+ cd = cd.transpose()
+ dd = d + alpha*np.dot(c, bd)
+
+ elif method == 'bilinear' or method == 'tustin':
+ return cont2discrete(system, dt, method="gbt", alpha=0.5)
+
+ elif method == 'euler' or method == 'forward_diff':
+ return cont2discrete(system, dt, method="gbt", alpha=0.0)
+
+ elif method == 'backward_diff':
+ return cont2discrete(system, dt, method="gbt", alpha=1.0)
+
+ elif method == 'zoh':
+ # Build an exponential matrix
+ em_upper = np.hstack((a, b))
+
+ # Need to stack zeros under the a and b matrices
+ em_lower = np.hstack((np.zeros((b.shape[1], a.shape[0])),
+ np.zeros((b.shape[1], b.shape[1]))))
+
+ em = np.vstack((em_upper, em_lower))
+ ms = linalg.expm(dt * em)
+
+ # Dispose of the lower rows
+ ms = ms[:a.shape[0], :]
+
+ ad = ms[:, 0:a.shape[1]]
+ bd = ms[:, a.shape[1]:]
+
+ cd = c
+ dd = d
+
+ elif method == 'foh':
+ # Size parameters for convenience
+ n = a.shape[0]
+ m = b.shape[1]
+
+ # Build an exponential matrix similar to 'zoh' method
+ em_upper = linalg.block_diag(np.block([a, b]) * dt, np.eye(m))
+ em_lower = zeros((m, n + 2 * m))
+ em = np.block([[em_upper], [em_lower]])
+
+ ms = linalg.expm(em)
+
+ # Get the three blocks from upper rows
+ ms11 = ms[:n, 0:n]
+ ms12 = ms[:n, n:n + m]
+ ms13 = ms[:n, n + m:]
+
+ ad = ms11
+ bd = ms12 - ms13 + ms11 @ ms13
+ cd = c
+ dd = d + c @ ms13
+
+ elif method == 'impulse':
+ if not np.allclose(d, 0):
+ raise ValueError("Impulse method is only applicable "
+ "to strictly proper systems")
+
+ ad = linalg.expm(a * dt)
+ bd = ad @ b * dt
+ cd = c
+ dd = c @ b * dt
+
+ else:
+ raise ValueError(f"Unknown transformation method '{method}'")
+
+ return ad, bd, cd, dd, dt
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_ltisys.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_ltisys.py
new file mode 100644
index 0000000000000000000000000000000000000000..8692dd945c7e08e50dadabb590d65dfea5429568
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_ltisys.py
@@ -0,0 +1,3550 @@
+"""
+ltisys -- a collection of classes and functions for modeling linear
+time invariant systems.
+"""
+#
+# Author: Travis Oliphant 2001
+#
+# Feb 2010: Warren Weckesser
+# Rewrote lsim2 and added impulse2.
+# Apr 2011: Jeffrey Armstrong
+# Added dlsim, dstep, dimpulse, cont2discrete
+# Aug 2013: Juan Luis Cano
+# Rewrote abcd_normalize.
+# Jan 2015: Irvin Probst irvin DOT probst AT ensta-bretagne DOT fr
+# Added pole placement
+# Mar 2015: Clancy Rowley
+# Rewrote lsim
+# May 2015: Felix Berkenkamp
+# Split lti class into subclasses
+# Merged discrete systems and added dlti
+
+import warnings
+from types import GenericAlias
+
+# np.linalg.qr fails on some tests with LinAlgError: zgeqrf returns -7
+# use scipy's qr until this is solved
+
+from scipy.linalg import qr as s_qr
+from scipy import linalg
+from scipy.interpolate import make_interp_spline
+from ._filter_design import (tf2zpk, zpk2tf, normalize, freqs, freqz, freqs_zpk,
+ freqz_zpk)
+from ._lti_conversion import (tf2ss, abcd_normalize, ss2tf, zpk2ss, ss2zpk,
+ cont2discrete)
+
+import numpy as np
+from numpy import (real, atleast_1d, squeeze, asarray, zeros,
+ dot, transpose, ones, linspace)
+import copy
+
+__all__ = ['lti', 'dlti', 'TransferFunction', 'ZerosPolesGain', 'StateSpace',
+ 'lsim', 'impulse', 'step', 'bode',
+ 'freqresp', 'place_poles', 'dlsim', 'dstep', 'dimpulse',
+ 'dfreqresp', 'dbode']
+
+
+class LinearTimeInvariant:
+ # generic type compatibility with scipy-stubs
+ __class_getitem__ = classmethod(GenericAlias)
+
+ def __new__(cls, *system, **kwargs):
+ """Create a new object, don't allow direct instances."""
+ if cls is LinearTimeInvariant:
+ raise NotImplementedError('The LinearTimeInvariant class is not '
+ 'meant to be used directly, use `lti` '
+ 'or `dlti` instead.')
+ return super().__new__(cls)
+
+ def __init__(self):
+ """
+ Initialize the `lti` baseclass.
+
+ The heavy lifting is done by the subclasses.
+ """
+ super().__init__()
+
+ self.inputs = None
+ self.outputs = None
+ self._dt = None
+
+ @property
+ def dt(self):
+ """Return the sampling time of the system, `None` for `lti` systems."""
+ return self._dt
+
+ @property
+ def _dt_dict(self):
+ if self.dt is None:
+ return {}
+ else:
+ return {'dt': self.dt}
+
+ @property
+ def zeros(self):
+ """Zeros of the system."""
+ return self.to_zpk().zeros
+
+ @property
+ def poles(self):
+ """Poles of the system."""
+ return self.to_zpk().poles
+
+ def _as_ss(self):
+ """Convert to `StateSpace` system, without copying.
+
+ Returns
+ -------
+ sys: StateSpace
+ The `StateSpace` system. If the class is already an instance of
+ `StateSpace` then this instance is returned.
+ """
+ if isinstance(self, StateSpace):
+ return self
+ else:
+ return self.to_ss()
+
+ def _as_zpk(self):
+ """Convert to `ZerosPolesGain` system, without copying.
+
+ Returns
+ -------
+ sys: ZerosPolesGain
+ The `ZerosPolesGain` system. If the class is already an instance of
+ `ZerosPolesGain` then this instance is returned.
+ """
+ if isinstance(self, ZerosPolesGain):
+ return self
+ else:
+ return self.to_zpk()
+
+ def _as_tf(self):
+ """Convert to `TransferFunction` system, without copying.
+
+ Returns
+ -------
+ sys: ZerosPolesGain
+ The `TransferFunction` system. If the class is already an instance of
+ `TransferFunction` then this instance is returned.
+ """
+ if isinstance(self, TransferFunction):
+ return self
+ else:
+ return self.to_tf()
+
+
+class lti(LinearTimeInvariant):
+ r"""
+ Continuous-time linear time invariant system base class.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `lti` class can be instantiated with either 2, 3 or 4 arguments.
+ The following gives the number of arguments and the corresponding
+ continuous-time subclass that is created:
+
+ * 2: `TransferFunction`: (numerator, denominator)
+ * 3: `ZerosPolesGain`: (zeros, poles, gain)
+ * 4: `StateSpace`: (A, B, C, D)
+
+ Each argument can be an array or a sequence.
+
+ See Also
+ --------
+ ZerosPolesGain, StateSpace, TransferFunction, dlti
+
+ Notes
+ -----
+ `lti` instances do not exist directly. Instead, `lti` creates an instance
+ of one of its subclasses: `StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`.
+
+ If (numerator, denominator) is passed in for ``*system``, coefficients for
+ both the numerator and denominator should be specified in descending
+ exponent order (e.g., ``s^2 + 3s + 5`` would be represented as ``[1, 3,
+ 5]``).
+
+ Changing the value of properties that are not directly part of the current
+ system representation (such as the `zeros` of a `StateSpace` system) is
+ very inefficient and may lead to numerical inaccuracies. It is better to
+ convert to the specific system representation first. For example, call
+ ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain.
+
+ Examples
+ --------
+ >>> from scipy import signal
+
+ >>> signal.lti(1, 2, 3, 4)
+ StateSpaceContinuous(
+ array([[1]]),
+ array([[2]]),
+ array([[3]]),
+ array([[4]]),
+ dt: None
+ )
+
+ Construct the transfer function
+ :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`:
+
+ >>> signal.lti([1, 2], [3, 4], 5)
+ ZerosPolesGainContinuous(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: None
+ )
+
+ Construct the transfer function :math:`H(s) = \frac{3s + 4}{1s + 2}`:
+
+ >>> signal.lti([3, 4], [1, 2])
+ TransferFunctionContinuous(
+ array([3., 4.]),
+ array([1., 2.]),
+ dt: None
+ )
+
+ """
+ def __new__(cls, *system):
+ """Create an instance of the appropriate subclass."""
+ if cls is lti:
+ N = len(system)
+ if N == 2:
+ return TransferFunctionContinuous.__new__(
+ TransferFunctionContinuous, *system)
+ elif N == 3:
+ return ZerosPolesGainContinuous.__new__(
+ ZerosPolesGainContinuous, *system)
+ elif N == 4:
+ return StateSpaceContinuous.__new__(StateSpaceContinuous,
+ *system)
+ else:
+ raise ValueError("`system` needs to be an instance of `lti` "
+ "or have 2, 3 or 4 arguments.")
+ # __new__ was called from a subclass, let it call its own functions
+ return super().__new__(cls)
+
+ def __init__(self, *system):
+ """
+ Initialize the `lti` baseclass.
+
+ The heavy lifting is done by the subclasses.
+ """
+ super().__init__(*system)
+
+ def impulse(self, X0=None, T=None, N=None):
+ """
+ Return the impulse response of a continuous-time system.
+ See `impulse` for details.
+ """
+ return impulse(self, X0=X0, T=T, N=N)
+
+ def step(self, X0=None, T=None, N=None):
+ """
+ Return the step response of a continuous-time system.
+ See `step` for details.
+ """
+ return step(self, X0=X0, T=T, N=N)
+
+ def output(self, U, T, X0=None):
+ """
+ Return the response of a continuous-time system to input `U`.
+ See `lsim` for details.
+ """
+ return lsim(self, U, T, X0=X0)
+
+ def bode(self, w=None, n=100):
+ """
+ Calculate Bode magnitude and phase data of a continuous-time system.
+
+ Returns a 3-tuple containing arrays of frequencies [rad/s], magnitude
+ [dB] and phase [deg]. See `bode` for details.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> sys = signal.TransferFunction([1], [1, 1])
+ >>> w, mag, phase = sys.bode()
+
+ >>> plt.figure()
+ >>> plt.semilogx(w, mag) # Bode magnitude plot
+ >>> plt.figure()
+ >>> plt.semilogx(w, phase) # Bode phase plot
+ >>> plt.show()
+
+ """
+ return bode(self, w=w, n=n)
+
+ def freqresp(self, w=None, n=10000):
+ """
+ Calculate the frequency response of a continuous-time system.
+
+ Returns a 2-tuple containing arrays of frequencies [rad/s] and
+ complex magnitude.
+ See `freqresp` for details.
+ """
+ return freqresp(self, w=w, n=n)
+
+ def to_discrete(self, dt, method='zoh', alpha=None):
+ """Return a discretized version of the current system.
+
+ Parameters: See `cont2discrete` for details.
+
+ Returns
+ -------
+ sys: instance of `dlti`
+ """
+ raise NotImplementedError('to_discrete is not implemented for this '
+ 'system class.')
+
+
+class dlti(LinearTimeInvariant):
+ r"""
+ Discrete-time linear time invariant system base class.
+
+ Parameters
+ ----------
+ *system: arguments
+ The `dlti` class can be instantiated with either 2, 3 or 4 arguments.
+ The following gives the number of arguments and the corresponding
+ discrete-time subclass that is created:
+
+ * 2: `TransferFunction`: (numerator, denominator)
+ * 3: `ZerosPolesGain`: (zeros, poles, gain)
+ * 4: `StateSpace`: (A, B, C, D)
+
+ Each argument can be an array or a sequence.
+ dt: float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to ``True``
+ (unspecified sampling time). Must be specified as a keyword argument,
+ for example, ``dt=0.1``.
+
+ See Also
+ --------
+ ZerosPolesGain, StateSpace, TransferFunction, lti
+
+ Notes
+ -----
+ `dlti` instances do not exist directly. Instead, `dlti` creates an instance
+ of one of its subclasses: `StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`.
+
+ Changing the value of properties that are not directly part of the current
+ system representation (such as the `zeros` of a `StateSpace` system) is
+ very inefficient and may lead to numerical inaccuracies. It is better to
+ convert to the specific system representation first. For example, call
+ ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain.
+
+ If (numerator, denominator) is passed in for ``*system``, coefficients for
+ both the numerator and denominator should be specified in descending
+ exponent order (e.g., ``z^2 + 3z + 5`` would be represented as ``[1, 3,
+ 5]``).
+
+ .. versionadded:: 0.18.0
+
+ Examples
+ --------
+ >>> from scipy import signal
+
+ >>> signal.dlti(1, 2, 3, 4)
+ StateSpaceDiscrete(
+ array([[1]]),
+ array([[2]]),
+ array([[3]]),
+ array([[4]]),
+ dt: True
+ )
+
+ >>> signal.dlti(1, 2, 3, 4, dt=0.1)
+ StateSpaceDiscrete(
+ array([[1]]),
+ array([[2]]),
+ array([[3]]),
+ array([[4]]),
+ dt: 0.1
+ )
+
+ Construct the transfer function
+ :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time
+ of 0.1 seconds:
+
+ >>> signal.dlti([1, 2], [3, 4], 5, dt=0.1)
+ ZerosPolesGainDiscrete(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: 0.1
+ )
+
+ Construct the transfer function :math:`H(z) = \frac{3z + 4}{1z + 2}` with
+ a sampling time of 0.1 seconds:
+
+ >>> signal.dlti([3, 4], [1, 2], dt=0.1)
+ TransferFunctionDiscrete(
+ array([3., 4.]),
+ array([1., 2.]),
+ dt: 0.1
+ )
+
+ """
+ def __new__(cls, *system, **kwargs):
+ """Create an instance of the appropriate subclass."""
+ if cls is dlti:
+ N = len(system)
+ if N == 2:
+ return TransferFunctionDiscrete.__new__(
+ TransferFunctionDiscrete, *system, **kwargs)
+ elif N == 3:
+ return ZerosPolesGainDiscrete.__new__(ZerosPolesGainDiscrete,
+ *system, **kwargs)
+ elif N == 4:
+ return StateSpaceDiscrete.__new__(StateSpaceDiscrete, *system,
+ **kwargs)
+ else:
+ raise ValueError("`system` needs to be an instance of `dlti` "
+ "or have 2, 3 or 4 arguments.")
+ # __new__ was called from a subclass, let it call its own functions
+ return super().__new__(cls)
+
+ def __init__(self, *system, **kwargs):
+ """
+ Initialize the `lti` baseclass.
+
+ The heavy lifting is done by the subclasses.
+ """
+ dt = kwargs.pop('dt', True)
+ super().__init__(*system, **kwargs)
+
+ self.dt = dt
+
+ @property
+ def dt(self):
+ """Return the sampling time of the system."""
+ return self._dt
+
+ @dt.setter
+ def dt(self, dt):
+ self._dt = dt
+
+ def impulse(self, x0=None, t=None, n=None):
+ """
+ Return the impulse response of the discrete-time `dlti` system.
+ See `dimpulse` for details.
+ """
+ return dimpulse(self, x0=x0, t=t, n=n)
+
+ def step(self, x0=None, t=None, n=None):
+ """
+ Return the step response of the discrete-time `dlti` system.
+ See `dstep` for details.
+ """
+ return dstep(self, x0=x0, t=t, n=n)
+
+ def output(self, u, t, x0=None):
+ """
+ Return the response of the discrete-time system to input `u`.
+ See `dlsim` for details.
+ """
+ return dlsim(self, u, t, x0=x0)
+
+ def bode(self, w=None, n=100):
+ r"""
+ Calculate Bode magnitude and phase data of a discrete-time system.
+
+ Returns a 3-tuple containing arrays of frequencies [rad/s], magnitude
+ [dB] and phase [deg]. See `dbode` for details.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ Construct the transfer function :math:`H(z) = \frac{1}{z^2 + 2z + 3}`
+ with sampling time 0.5s:
+
+ >>> sys = signal.TransferFunction([1], [1, 2, 3], dt=0.5)
+
+ Equivalent: signal.dbode(sys)
+
+ >>> w, mag, phase = sys.bode()
+
+ >>> plt.figure()
+ >>> plt.semilogx(w, mag) # Bode magnitude plot
+ >>> plt.figure()
+ >>> plt.semilogx(w, phase) # Bode phase plot
+ >>> plt.show()
+
+ """
+ return dbode(self, w=w, n=n)
+
+ def freqresp(self, w=None, n=10000, whole=False):
+ """
+ Calculate the frequency response of a discrete-time system.
+
+ Returns a 2-tuple containing arrays of frequencies [rad/s] and
+ complex magnitude.
+ See `dfreqresp` for details.
+
+ """
+ return dfreqresp(self, w=w, n=n, whole=whole)
+
+
+class TransferFunction(LinearTimeInvariant):
+ r"""Linear Time Invariant system class in transfer function form.
+
+ Represents the system as the continuous-time transfer function
+ :math:`H(s)=\sum_{i=0}^N b[N-i] s^i / \sum_{j=0}^M a[M-j] s^j` or the
+ discrete-time transfer function
+ :math:`H(z)=\sum_{i=0}^N b[N-i] z^i / \sum_{j=0}^M a[M-j] z^j`, where
+ :math:`b` are elements of the numerator `num`, :math:`a` are elements of
+ the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``.
+ `TransferFunction` systems inherit additional
+ functionality from the `lti`, respectively the `dlti` classes, depending on
+ which system representation is used.
+
+ Parameters
+ ----------
+ *system: arguments
+ The `TransferFunction` class can be instantiated with 1 or 2
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 2: array_like: (numerator, denominator)
+ dt: float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `None`
+ (continuous-time). Must be specified as a keyword argument, for
+ example, ``dt=0.1``.
+
+ See Also
+ --------
+ ZerosPolesGain, StateSpace, lti, dlti
+ tf2ss, tf2zpk, tf2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `TransferFunction` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies. It is better to convert to the specific system
+ representation first. For example, call ``sys = sys.to_ss()`` before
+ accessing/changing the A, B, C, D system matrices.
+
+ If (numerator, denominator) is passed in for ``*system``, coefficients
+ for both the numerator and denominator should be specified in descending
+ exponent order (e.g. ``s^2 + 3s + 5`` or ``z^2 + 3z + 5`` would be
+ represented as ``[1, 3, 5]``)
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}`:
+
+ >>> from scipy import signal
+
+ >>> num = [1, 3, 3]
+ >>> den = [1, 2, 1]
+
+ >>> signal.TransferFunction(num, den)
+ TransferFunctionContinuous(
+ array([1., 3., 3.]),
+ array([1., 2., 1.]),
+ dt: None
+ )
+
+ Construct the transfer function
+ :math:`H(z) = \frac{z^2 + 3z + 3}{z^2 + 2z + 1}` with a sampling time of
+ 0.1 seconds:
+
+ >>> signal.TransferFunction(num, den, dt=0.1)
+ TransferFunctionDiscrete(
+ array([1., 3., 3.]),
+ array([1., 2., 1.]),
+ dt: 0.1
+ )
+
+ """
+ def __new__(cls, *system, **kwargs):
+ """Handle object conversion if input is an instance of lti."""
+ if len(system) == 1 and isinstance(system[0], LinearTimeInvariant):
+ return system[0].to_tf()
+
+ # Choose whether to inherit from `lti` or from `dlti`
+ if cls is TransferFunction:
+ if kwargs.get('dt') is None:
+ return TransferFunctionContinuous.__new__(
+ TransferFunctionContinuous,
+ *system,
+ **kwargs)
+ else:
+ return TransferFunctionDiscrete.__new__(
+ TransferFunctionDiscrete,
+ *system,
+ **kwargs)
+
+ # No special conversion needed
+ return super().__new__(cls)
+
+ def __init__(self, *system, **kwargs):
+ """Initialize the state space LTI system."""
+ # Conversion of lti instances is handled in __new__
+ if isinstance(system[0], LinearTimeInvariant):
+ return
+
+ # Remove system arguments, not needed by parents anymore
+ super().__init__(**kwargs)
+
+ self._num = None
+ self._den = None
+
+ self.num, self.den = normalize(*system)
+
+ def __repr__(self):
+ """Return representation of the system's transfer function"""
+ return (
+ f'{self.__class__.__name__}(\n'
+ f'{repr(self.num)},\n'
+ f'{repr(self.den)},\n'
+ f'dt: {repr(self.dt)}\n)'
+ )
+
+ @property
+ def num(self):
+ """Numerator of the `TransferFunction` system."""
+ return self._num
+
+ @num.setter
+ def num(self, num):
+ self._num = atleast_1d(num)
+
+ # Update dimensions
+ if len(self.num.shape) > 1:
+ self.outputs, self.inputs = self.num.shape
+ else:
+ self.outputs = 1
+ self.inputs = 1
+
+ @property
+ def den(self):
+ """Denominator of the `TransferFunction` system."""
+ return self._den
+
+ @den.setter
+ def den(self, den):
+ self._den = atleast_1d(den)
+
+ def _copy(self, system):
+ """
+ Copy the parameters of another `TransferFunction` object
+
+ Parameters
+ ----------
+ system : `TransferFunction`
+ The `StateSpace` system that is to be copied
+
+ """
+ self.num = system.num
+ self.den = system.den
+
+ def to_tf(self):
+ """
+ Return a copy of the current `TransferFunction` system.
+
+ Returns
+ -------
+ sys : instance of `TransferFunction`
+ The current system (copy)
+
+ """
+ return copy.deepcopy(self)
+
+ def to_zpk(self):
+ """
+ Convert system representation to `ZerosPolesGain`.
+
+ Returns
+ -------
+ sys : instance of `ZerosPolesGain`
+ Zeros, poles, gain representation of the current system
+
+ """
+ return ZerosPolesGain(*tf2zpk(self.num, self.den),
+ **self._dt_dict)
+
+ def to_ss(self):
+ """
+ Convert system representation to `StateSpace`.
+
+ Returns
+ -------
+ sys : instance of `StateSpace`
+ State space model of the current system
+
+ """
+ return StateSpace(*tf2ss(self.num, self.den),
+ **self._dt_dict)
+
+ @staticmethod
+ def _z_to_zinv(num, den):
+ """Change a transfer function from the variable `z` to `z**-1`.
+
+ Parameters
+ ----------
+ num, den: 1d array_like
+ Sequences representing the coefficients of the numerator and
+ denominator polynomials, in order of descending degree of 'z'.
+ That is, ``5z**2 + 3z + 2`` is presented as ``[5, 3, 2]``.
+
+ Returns
+ -------
+ num, den: 1d array_like
+ Sequences representing the coefficients of the numerator and
+ denominator polynomials, in order of ascending degree of 'z**-1'.
+ That is, ``5 + 3 z**-1 + 2 z**-2`` is presented as ``[5, 3, 2]``.
+ """
+ diff = len(num) - len(den)
+ if diff > 0:
+ den = np.hstack((np.zeros(diff), den))
+ elif diff < 0:
+ num = np.hstack((np.zeros(-diff), num))
+ return num, den
+
+ @staticmethod
+ def _zinv_to_z(num, den):
+ """Change a transfer function from the variable `z` to `z**-1`.
+
+ Parameters
+ ----------
+ num, den: 1d array_like
+ Sequences representing the coefficients of the numerator and
+ denominator polynomials, in order of ascending degree of 'z**-1'.
+ That is, ``5 + 3 z**-1 + 2 z**-2`` is presented as ``[5, 3, 2]``.
+
+ Returns
+ -------
+ num, den: 1d array_like
+ Sequences representing the coefficients of the numerator and
+ denominator polynomials, in order of descending degree of 'z'.
+ That is, ``5z**2 + 3z + 2`` is presented as ``[5, 3, 2]``.
+ """
+ diff = len(num) - len(den)
+ if diff > 0:
+ den = np.hstack((den, np.zeros(diff)))
+ elif diff < 0:
+ num = np.hstack((num, np.zeros(-diff)))
+ return num, den
+
+
+class TransferFunctionContinuous(TransferFunction, lti):
+ r"""
+ Continuous-time Linear Time Invariant system in transfer function form.
+
+ Represents the system as the transfer function
+ :math:`H(s)=\sum_{i=0}^N b[N-i] s^i / \sum_{j=0}^M a[M-j] s^j`, where
+ :math:`b` are elements of the numerator `num`, :math:`a` are elements of
+ the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``.
+ Continuous-time `TransferFunction` systems inherit additional
+ functionality from the `lti` class.
+
+ Parameters
+ ----------
+ *system: arguments
+ The `TransferFunction` class can be instantiated with 1 or 2
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 2: array_like: (numerator, denominator)
+
+ See Also
+ --------
+ ZerosPolesGain, StateSpace, lti
+ tf2ss, tf2zpk, tf2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `TransferFunction` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies. It is better to convert to the specific system
+ representation first. For example, call ``sys = sys.to_ss()`` before
+ accessing/changing the A, B, C, D system matrices.
+
+ If (numerator, denominator) is passed in for ``*system``, coefficients
+ for both the numerator and denominator should be specified in descending
+ exponent order (e.g. ``s^2 + 3s + 5`` would be represented as
+ ``[1, 3, 5]``)
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(s) = \frac{s^2 + 3s + 3}{s^2 + 2s + 1}`:
+
+ >>> from scipy import signal
+
+ >>> num = [1, 3, 3]
+ >>> den = [1, 2, 1]
+
+ >>> signal.TransferFunction(num, den)
+ TransferFunctionContinuous(
+ array([ 1., 3., 3.]),
+ array([ 1., 2., 1.]),
+ dt: None
+ )
+
+ """
+
+ def to_discrete(self, dt, method='zoh', alpha=None):
+ """
+ Returns the discretized `TransferFunction` system.
+
+ Parameters: See `cont2discrete` for details.
+
+ Returns
+ -------
+ sys: instance of `dlti` and `StateSpace`
+ """
+ return TransferFunction(*cont2discrete((self.num, self.den),
+ dt,
+ method=method,
+ alpha=alpha)[:-1],
+ dt=dt)
+
+
+class TransferFunctionDiscrete(TransferFunction, dlti):
+ r"""
+ Discrete-time Linear Time Invariant system in transfer function form.
+
+ Represents the system as the transfer function
+ :math:`H(z)=\sum_{i=0}^N b[N-i] z^i / \sum_{j=0}^M a[M-j] z^j`, where
+ :math:`b` are elements of the numerator `num`, :math:`a` are elements of
+ the denominator `den`, and ``N == len(b) - 1``, ``M == len(a) - 1``.
+ Discrete-time `TransferFunction` systems inherit additional functionality
+ from the `dlti` class.
+
+ Parameters
+ ----------
+ *system: arguments
+ The `TransferFunction` class can be instantiated with 1 or 2
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `dlti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 2: array_like: (numerator, denominator)
+ dt: float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `True`
+ (unspecified sampling time). Must be specified as a keyword argument,
+ for example, ``dt=0.1``.
+
+ See Also
+ --------
+ ZerosPolesGain, StateSpace, dlti
+ tf2ss, tf2zpk, tf2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `TransferFunction` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies.
+
+ If (numerator, denominator) is passed in for ``*system``, coefficients
+ for both the numerator and denominator should be specified in descending
+ exponent order (e.g., ``z^2 + 3z + 5`` would be represented as
+ ``[1, 3, 5]``).
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(z) = \frac{z^2 + 3z + 3}{z^2 + 2z + 1}` with a sampling time of
+ 0.5 seconds:
+
+ >>> from scipy import signal
+
+ >>> num = [1, 3, 3]
+ >>> den = [1, 2, 1]
+
+ >>> signal.TransferFunction(num, den, dt=0.5)
+ TransferFunctionDiscrete(
+ array([ 1., 3., 3.]),
+ array([ 1., 2., 1.]),
+ dt: 0.5
+ )
+
+ """
+ pass
+
+
+class ZerosPolesGain(LinearTimeInvariant):
+ r"""
+ Linear Time Invariant system class in zeros, poles, gain form.
+
+ Represents the system as the continuous- or discrete-time transfer function
+ :math:`H(s)=k \prod_i (s - z[i]) / \prod_j (s - p[j])`, where :math:`k` is
+ the `gain`, :math:`z` are the `zeros` and :math:`p` are the `poles`.
+ `ZerosPolesGain` systems inherit additional functionality from the `lti`,
+ respectively the `dlti` classes, depending on which system representation
+ is used.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `ZerosPolesGain` class can be instantiated with 1 or 3
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 3: array_like: (zeros, poles, gain)
+ dt: float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `None`
+ (continuous-time). Must be specified as a keyword argument, for
+ example, ``dt=0.1``.
+
+
+ See Also
+ --------
+ TransferFunction, StateSpace, lti, dlti
+ zpk2ss, zpk2tf, zpk2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies. It is better to convert to the specific system
+ representation first. For example, call ``sys = sys.to_ss()`` before
+ accessing/changing the A, B, C, D system matrices.
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`:
+
+ >>> from scipy import signal
+
+ >>> signal.ZerosPolesGain([1, 2], [3, 4], 5)
+ ZerosPolesGainContinuous(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: None
+ )
+
+ Construct the transfer function
+ :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time
+ of 0.1 seconds:
+
+ >>> signal.ZerosPolesGain([1, 2], [3, 4], 5, dt=0.1)
+ ZerosPolesGainDiscrete(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: 0.1
+ )
+
+ """
+ def __new__(cls, *system, **kwargs):
+ """Handle object conversion if input is an instance of `lti`"""
+ if len(system) == 1 and isinstance(system[0], LinearTimeInvariant):
+ return system[0].to_zpk()
+
+ # Choose whether to inherit from `lti` or from `dlti`
+ if cls is ZerosPolesGain:
+ if kwargs.get('dt') is None:
+ return ZerosPolesGainContinuous.__new__(
+ ZerosPolesGainContinuous,
+ *system,
+ **kwargs)
+ else:
+ return ZerosPolesGainDiscrete.__new__(
+ ZerosPolesGainDiscrete,
+ *system,
+ **kwargs
+ )
+
+ # No special conversion needed
+ return super().__new__(cls)
+
+ def __init__(self, *system, **kwargs):
+ """Initialize the zeros, poles, gain system."""
+ # Conversion of lti instances is handled in __new__
+ if isinstance(system[0], LinearTimeInvariant):
+ return
+
+ super().__init__(**kwargs)
+
+ self._zeros = None
+ self._poles = None
+ self._gain = None
+
+ self.zeros, self.poles, self.gain = system
+
+ def __repr__(self):
+ """Return representation of the `ZerosPolesGain` system."""
+ return (
+ f'{self.__class__.__name__}(\n'
+ f'{repr(self.zeros)},\n'
+ f'{repr(self.poles)},\n'
+ f'{repr(self.gain)},\n'
+ f'dt: {repr(self.dt)}\n)'
+ )
+
+ @property
+ def zeros(self):
+ """Zeros of the `ZerosPolesGain` system."""
+ return self._zeros
+
+ @zeros.setter
+ def zeros(self, zeros):
+ self._zeros = atleast_1d(zeros)
+
+ # Update dimensions
+ if len(self.zeros.shape) > 1:
+ self.outputs, self.inputs = self.zeros.shape
+ else:
+ self.outputs = 1
+ self.inputs = 1
+
+ @property
+ def poles(self):
+ """Poles of the `ZerosPolesGain` system."""
+ return self._poles
+
+ @poles.setter
+ def poles(self, poles):
+ self._poles = atleast_1d(poles)
+
+ @property
+ def gain(self):
+ """Gain of the `ZerosPolesGain` system."""
+ return self._gain
+
+ @gain.setter
+ def gain(self, gain):
+ self._gain = gain
+
+ def _copy(self, system):
+ """
+ Copy the parameters of another `ZerosPolesGain` system.
+
+ Parameters
+ ----------
+ system : instance of `ZerosPolesGain`
+ The zeros, poles gain system that is to be copied
+
+ """
+ self.poles = system.poles
+ self.zeros = system.zeros
+ self.gain = system.gain
+
+ def to_tf(self):
+ """
+ Convert system representation to `TransferFunction`.
+
+ Returns
+ -------
+ sys : instance of `TransferFunction`
+ Transfer function of the current system
+
+ """
+ return TransferFunction(*zpk2tf(self.zeros, self.poles, self.gain),
+ **self._dt_dict)
+
+ def to_zpk(self):
+ """
+ Return a copy of the current 'ZerosPolesGain' system.
+
+ Returns
+ -------
+ sys : instance of `ZerosPolesGain`
+ The current system (copy)
+
+ """
+ return copy.deepcopy(self)
+
+ def to_ss(self):
+ """
+ Convert system representation to `StateSpace`.
+
+ Returns
+ -------
+ sys : instance of `StateSpace`
+ State space model of the current system
+
+ """
+ return StateSpace(*zpk2ss(self.zeros, self.poles, self.gain),
+ **self._dt_dict)
+
+
+class ZerosPolesGainContinuous(ZerosPolesGain, lti):
+ r"""
+ Continuous-time Linear Time Invariant system in zeros, poles, gain form.
+
+ Represents the system as the continuous time transfer function
+ :math:`H(s)=k \prod_i (s - z[i]) / \prod_j (s - p[j])`, where :math:`k` is
+ the `gain`, :math:`z` are the `zeros` and :math:`p` are the `poles`.
+ Continuous-time `ZerosPolesGain` systems inherit additional functionality
+ from the `lti` class.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `ZerosPolesGain` class can be instantiated with 1 or 3
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 3: array_like: (zeros, poles, gain)
+
+ See Also
+ --------
+ TransferFunction, StateSpace, lti
+ zpk2ss, zpk2tf, zpk2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies. It is better to convert to the specific system
+ representation first. For example, call ``sys = sys.to_ss()`` before
+ accessing/changing the A, B, C, D system matrices.
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(s)=\frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`:
+
+ >>> from scipy import signal
+
+ >>> signal.ZerosPolesGain([1, 2], [3, 4], 5)
+ ZerosPolesGainContinuous(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: None
+ )
+
+ """
+
+ def to_discrete(self, dt, method='zoh', alpha=None):
+ """
+ Returns the discretized `ZerosPolesGain` system.
+
+ Parameters: See `cont2discrete` for details.
+
+ Returns
+ -------
+ sys: instance of `dlti` and `ZerosPolesGain`
+ """
+ return ZerosPolesGain(
+ *cont2discrete((self.zeros, self.poles, self.gain),
+ dt,
+ method=method,
+ alpha=alpha)[:-1],
+ dt=dt)
+
+
+class ZerosPolesGainDiscrete(ZerosPolesGain, dlti):
+ r"""
+ Discrete-time Linear Time Invariant system in zeros, poles, gain form.
+
+ Represents the system as the discrete-time transfer function
+ :math:`H(z)=k \prod_i (z - q[i]) / \prod_j (z - p[j])`, where :math:`k` is
+ the `gain`, :math:`q` are the `zeros` and :math:`p` are the `poles`.
+ Discrete-time `ZerosPolesGain` systems inherit additional functionality
+ from the `dlti` class.
+
+ Parameters
+ ----------
+ *system : arguments
+ The `ZerosPolesGain` class can be instantiated with 1 or 3
+ arguments. The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `dlti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 3: array_like: (zeros, poles, gain)
+ dt: float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `True`
+ (unspecified sampling time). Must be specified as a keyword argument,
+ for example, ``dt=0.1``.
+
+ See Also
+ --------
+ TransferFunction, StateSpace, dlti
+ zpk2ss, zpk2tf, zpk2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `ZerosPolesGain` system representation (such as the `A`, `B`, `C`, `D`
+ state-space matrices) is very inefficient and may lead to numerical
+ inaccuracies. It is better to convert to the specific system
+ representation first. For example, call ``sys = sys.to_ss()`` before
+ accessing/changing the A, B, C, D system matrices.
+
+ Examples
+ --------
+ Construct the transfer function
+ :math:`H(s) = \frac{5(s - 1)(s - 2)}{(s - 3)(s - 4)}`:
+
+ >>> from scipy import signal
+
+ >>> signal.ZerosPolesGain([1, 2], [3, 4], 5)
+ ZerosPolesGainContinuous(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: None
+ )
+
+ Construct the transfer function
+ :math:`H(z) = \frac{5(z - 1)(z - 2)}{(z - 3)(z - 4)}` with a sampling time
+ of 0.1 seconds:
+
+ >>> signal.ZerosPolesGain([1, 2], [3, 4], 5, dt=0.1)
+ ZerosPolesGainDiscrete(
+ array([1, 2]),
+ array([3, 4]),
+ 5,
+ dt: 0.1
+ )
+
+ """
+ pass
+
+
+class StateSpace(LinearTimeInvariant):
+ r"""
+ Linear Time Invariant system in state-space form.
+
+ Represents the system as the continuous-time, first order differential
+ equation :math:`\dot{x} = A x + B u` or the discrete-time difference
+ equation :math:`x[k+1] = A x[k] + B u[k]`. `StateSpace` systems
+ inherit additional functionality from the `lti`, respectively the `dlti`
+ classes, depending on which system representation is used.
+
+ Parameters
+ ----------
+ *system: arguments
+ The `StateSpace` class can be instantiated with 1 or 4 arguments.
+ The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` or `dlti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 4: array_like: (A, B, C, D)
+ dt: float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `None`
+ (continuous-time). Must be specified as a keyword argument, for
+ example, ``dt=0.1``.
+
+ See Also
+ --------
+ TransferFunction, ZerosPolesGain, lti, dlti
+ ss2zpk, ss2tf, zpk2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `StateSpace` system representation (such as `zeros` or `poles`) is very
+ inefficient and may lead to numerical inaccuracies. It is better to
+ convert to the specific system representation first. For example, call
+ ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import numpy as np
+ >>> a = np.array([[0, 1], [0, 0]])
+ >>> b = np.array([[0], [1]])
+ >>> c = np.array([[1, 0]])
+ >>> d = np.array([[0]])
+
+ >>> sys = signal.StateSpace(a, b, c, d)
+ >>> print(sys)
+ StateSpaceContinuous(
+ array([[0, 1],
+ [0, 0]]),
+ array([[0],
+ [1]]),
+ array([[1, 0]]),
+ array([[0]]),
+ dt: None
+ )
+
+ >>> sys.to_discrete(0.1)
+ StateSpaceDiscrete(
+ array([[1. , 0.1],
+ [0. , 1. ]]),
+ array([[0.005],
+ [0.1 ]]),
+ array([[1, 0]]),
+ array([[0]]),
+ dt: 0.1
+ )
+
+ >>> a = np.array([[1, 0.1], [0, 1]])
+ >>> b = np.array([[0.005], [0.1]])
+
+ >>> signal.StateSpace(a, b, c, d, dt=0.1)
+ StateSpaceDiscrete(
+ array([[1. , 0.1],
+ [0. , 1. ]]),
+ array([[0.005],
+ [0.1 ]]),
+ array([[1, 0]]),
+ array([[0]]),
+ dt: 0.1
+ )
+
+ """
+
+ # Override NumPy binary operations and ufuncs
+ __array_priority__ = 100.0
+ __array_ufunc__ = None
+
+ def __new__(cls, *system, **kwargs):
+ """Create new StateSpace object and settle inheritance."""
+ # Handle object conversion if input is an instance of `lti`
+ if len(system) == 1 and isinstance(system[0], LinearTimeInvariant):
+ return system[0].to_ss()
+
+ # Choose whether to inherit from `lti` or from `dlti`
+ if cls is StateSpace:
+ if kwargs.get('dt') is None:
+ return StateSpaceContinuous.__new__(StateSpaceContinuous,
+ *system, **kwargs)
+ else:
+ return StateSpaceDiscrete.__new__(StateSpaceDiscrete,
+ *system, **kwargs)
+
+ # No special conversion needed
+ return super().__new__(cls)
+
+ def __init__(self, *system, **kwargs):
+ """Initialize the state space lti/dlti system."""
+ # Conversion of lti instances is handled in __new__
+ if isinstance(system[0], LinearTimeInvariant):
+ return
+
+ # Remove system arguments, not needed by parents anymore
+ super().__init__(**kwargs)
+
+ self._A = None
+ self._B = None
+ self._C = None
+ self._D = None
+
+ self.A, self.B, self.C, self.D = abcd_normalize(*system)
+
+ def __repr__(self):
+ """Return representation of the `StateSpace` system."""
+ return (
+ f'{self.__class__.__name__}(\n'
+ f'{repr(self.A)},\n'
+ f'{repr(self.B)},\n'
+ f'{repr(self.C)},\n'
+ f'{repr(self.D)},\n'
+ f'dt: {repr(self.dt)}\n)'
+ )
+
+ def _check_binop_other(self, other):
+ return isinstance(other, StateSpace | np.ndarray | float | complex |
+ np.number | int)
+
+ def __mul__(self, other):
+ """
+ Post-multiply another system or a scalar
+
+ Handles multiplication of systems in the sense of a frequency domain
+ multiplication. That means, given two systems E1(s) and E2(s), their
+ multiplication, H(s) = E1(s) * E2(s), means that applying H(s) to U(s)
+ is equivalent to first applying E2(s), and then E1(s).
+
+ Notes
+ -----
+ For SISO systems the order of system application does not matter.
+ However, for MIMO systems, where the two systems are matrices, the
+ order above ensures standard Matrix multiplication rules apply.
+ """
+ if not self._check_binop_other(other):
+ return NotImplemented
+
+ if isinstance(other, StateSpace):
+ # Disallow mix of discrete and continuous systems.
+ if type(other) is not type(self):
+ return NotImplemented
+
+ if self.dt != other.dt:
+ raise TypeError('Cannot multiply systems with different `dt`.')
+
+ n1 = self.A.shape[0]
+ n2 = other.A.shape[0]
+
+ # Interconnection of systems
+ # x1' = A1 x1 + B1 u1
+ # y1 = C1 x1 + D1 u1
+ # x2' = A2 x2 + B2 y1
+ # y2 = C2 x2 + D2 y1
+ #
+ # Plugging in with u1 = y2 yields
+ # [x1'] [A1 B1*C2 ] [x1] [B1*D2]
+ # [x2'] = [0 A2 ] [x2] + [B2 ] u2
+ # [x1]
+ # y2 = [C1 D1*C2] [x2] + D1*D2 u2
+ a = np.vstack((np.hstack((self.A, np.dot(self.B, other.C))),
+ np.hstack((zeros((n2, n1)), other.A))))
+ b = np.vstack((np.dot(self.B, other.D), other.B))
+ c = np.hstack((self.C, np.dot(self.D, other.C)))
+ d = np.dot(self.D, other.D)
+ else:
+ # Assume that other is a scalar / matrix
+ # For post multiplication the input gets scaled
+ a = self.A
+ b = np.dot(self.B, other)
+ c = self.C
+ d = np.dot(self.D, other)
+
+ common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype)
+ return StateSpace(np.asarray(a, dtype=common_dtype),
+ np.asarray(b, dtype=common_dtype),
+ np.asarray(c, dtype=common_dtype),
+ np.asarray(d, dtype=common_dtype),
+ **self._dt_dict)
+
+ def __rmul__(self, other):
+ """Pre-multiply a scalar or matrix (but not StateSpace)"""
+ if not self._check_binop_other(other) or isinstance(other, StateSpace):
+ return NotImplemented
+
+ # For pre-multiplication only the output gets scaled
+ a = self.A
+ b = self.B
+ c = np.dot(other, self.C)
+ d = np.dot(other, self.D)
+
+ common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype)
+ return StateSpace(np.asarray(a, dtype=common_dtype),
+ np.asarray(b, dtype=common_dtype),
+ np.asarray(c, dtype=common_dtype),
+ np.asarray(d, dtype=common_dtype),
+ **self._dt_dict)
+
+ def __neg__(self):
+ """Negate the system (equivalent to pre-multiplying by -1)."""
+ return StateSpace(self.A, self.B, -self.C, -self.D, **self._dt_dict)
+
+ def __add__(self, other):
+ """
+ Adds two systems in the sense of frequency domain addition.
+ """
+ if not self._check_binop_other(other):
+ return NotImplemented
+
+ if isinstance(other, StateSpace):
+ # Disallow mix of discrete and continuous systems.
+ if type(other) is not type(self):
+ raise TypeError(f'Cannot add {type(self)} and {type(other)}')
+
+ if self.dt != other.dt:
+ raise TypeError('Cannot add systems with different `dt`.')
+ # Interconnection of systems
+ # x1' = A1 x1 + B1 u
+ # y1 = C1 x1 + D1 u
+ # x2' = A2 x2 + B2 u
+ # y2 = C2 x2 + D2 u
+ # y = y1 + y2
+ #
+ # Plugging in yields
+ # [x1'] [A1 0 ] [x1] [B1]
+ # [x2'] = [0 A2] [x2] + [B2] u
+ # [x1]
+ # y = [C1 C2] [x2] + [D1 + D2] u
+ a = linalg.block_diag(self.A, other.A)
+ b = np.vstack((self.B, other.B))
+ c = np.hstack((self.C, other.C))
+ d = self.D + other.D
+ else:
+ other = np.atleast_2d(other)
+ if self.D.shape == other.shape:
+ # A scalar/matrix is really just a static system (A=0, B=0, C=0)
+ a = self.A
+ b = self.B
+ c = self.C
+ d = self.D + other
+ else:
+ raise ValueError("Cannot add systems with incompatible "
+ f"dimensions ({self.D.shape} and {other.shape})")
+
+ common_dtype = np.result_type(a.dtype, b.dtype, c.dtype, d.dtype)
+ return StateSpace(np.asarray(a, dtype=common_dtype),
+ np.asarray(b, dtype=common_dtype),
+ np.asarray(c, dtype=common_dtype),
+ np.asarray(d, dtype=common_dtype),
+ **self._dt_dict)
+
+ def __sub__(self, other):
+ if not self._check_binop_other(other):
+ return NotImplemented
+
+ return self.__add__(-other)
+
+ def __radd__(self, other):
+ if not self._check_binop_other(other):
+ return NotImplemented
+
+ return self.__add__(other)
+
+ def __rsub__(self, other):
+ if not self._check_binop_other(other):
+ return NotImplemented
+
+ return (-self).__add__(other)
+
+ def __truediv__(self, other):
+ """
+ Divide by a scalar
+ """
+ # Division by non-StateSpace scalars
+ if not self._check_binop_other(other) or isinstance(other, StateSpace):
+ return NotImplemented
+
+ if isinstance(other, np.ndarray) and other.ndim > 0:
+ # It's ambiguous what this means, so disallow it
+ raise ValueError("Cannot divide StateSpace by non-scalar numpy arrays")
+
+ return self.__mul__(1/other)
+
+ @property
+ def A(self):
+ """State matrix of the `StateSpace` system."""
+ return self._A
+
+ @A.setter
+ def A(self, A):
+ self._A = np.atleast_2d(A) if A is not None else None
+
+ @property
+ def B(self):
+ """Input matrix of the `StateSpace` system."""
+ return self._B
+
+ @B.setter
+ def B(self, B):
+ self._B = np.atleast_2d(B) if B is not None else None
+ self.inputs = self.B.shape[-1]
+
+ @property
+ def C(self):
+ """Output matrix of the `StateSpace` system."""
+ return self._C
+
+ @C.setter
+ def C(self, C):
+ self._C = np.atleast_2d(C) if C is not None else None
+ self.outputs = self.C.shape[0]
+
+ @property
+ def D(self):
+ """Feedthrough matrix of the `StateSpace` system."""
+ return self._D
+
+ @D.setter
+ def D(self, D):
+ self._D = np.atleast_2d(D) if D is not None else None
+
+ def _copy(self, system):
+ """
+ Copy the parameters of another `StateSpace` system.
+
+ Parameters
+ ----------
+ system : instance of `StateSpace`
+ The state-space system that is to be copied
+
+ """
+ self.A = system.A
+ self.B = system.B
+ self.C = system.C
+ self.D = system.D
+
+ def to_tf(self, **kwargs):
+ """
+ Convert system representation to `TransferFunction`.
+
+ Parameters
+ ----------
+ kwargs : dict, optional
+ Additional keywords passed to `ss2zpk`
+
+ Returns
+ -------
+ sys : instance of `TransferFunction`
+ Transfer function of the current system
+
+ """
+ return TransferFunction(*ss2tf(self._A, self._B, self._C, self._D,
+ **kwargs), **self._dt_dict)
+
+ def to_zpk(self, **kwargs):
+ """
+ Convert system representation to `ZerosPolesGain`.
+
+ Parameters
+ ----------
+ kwargs : dict, optional
+ Additional keywords passed to `ss2zpk`
+
+ Returns
+ -------
+ sys : instance of `ZerosPolesGain`
+ Zeros, poles, gain representation of the current system
+
+ """
+ return ZerosPolesGain(*ss2zpk(self._A, self._B, self._C, self._D,
+ **kwargs), **self._dt_dict)
+
+ def to_ss(self):
+ """
+ Return a copy of the current `StateSpace` system.
+
+ Returns
+ -------
+ sys : instance of `StateSpace`
+ The current system (copy)
+
+ """
+ return copy.deepcopy(self)
+
+
+class StateSpaceContinuous(StateSpace, lti):
+ r"""
+ Continuous-time Linear Time Invariant system in state-space form.
+
+ Represents the system as the continuous-time, first order differential
+ equation :math:`\dot{x} = A x + B u`.
+ Continuous-time `StateSpace` systems inherit additional functionality
+ from the `lti` class.
+
+ Parameters
+ ----------
+ *system: arguments
+ The `StateSpace` class can be instantiated with 1 or 3 arguments.
+ The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `lti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 4: array_like: (A, B, C, D)
+
+ See Also
+ --------
+ TransferFunction, ZerosPolesGain, lti
+ ss2zpk, ss2tf, zpk2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `StateSpace` system representation (such as `zeros` or `poles`) is very
+ inefficient and may lead to numerical inaccuracies. It is better to
+ convert to the specific system representation first. For example, call
+ ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+
+ >>> a = np.array([[0, 1], [0, 0]])
+ >>> b = np.array([[0], [1]])
+ >>> c = np.array([[1, 0]])
+ >>> d = np.array([[0]])
+
+ >>> sys = signal.StateSpace(a, b, c, d)
+ >>> print(sys)
+ StateSpaceContinuous(
+ array([[0, 1],
+ [0, 0]]),
+ array([[0],
+ [1]]),
+ array([[1, 0]]),
+ array([[0]]),
+ dt: None
+ )
+
+ """
+
+ def to_discrete(self, dt, method='zoh', alpha=None):
+ """
+ Returns the discretized `StateSpace` system.
+
+ Parameters: See `cont2discrete` for details.
+
+ Returns
+ -------
+ sys: instance of `dlti` and `StateSpace`
+ """
+ return StateSpace(*cont2discrete((self.A, self.B, self.C, self.D),
+ dt,
+ method=method,
+ alpha=alpha)[:-1],
+ dt=dt)
+
+
+class StateSpaceDiscrete(StateSpace, dlti):
+ r"""
+ Discrete-time Linear Time Invariant system in state-space form.
+
+ Represents the system as the discrete-time difference equation
+ :math:`x[k+1] = A x[k] + B u[k]`.
+ `StateSpace` systems inherit additional functionality from the `dlti`
+ class.
+
+ Parameters
+ ----------
+ *system: arguments
+ The `StateSpace` class can be instantiated with 1 or 3 arguments.
+ The following gives the number of input arguments and their
+ interpretation:
+
+ * 1: `dlti` system: (`StateSpace`, `TransferFunction` or
+ `ZerosPolesGain`)
+ * 4: array_like: (A, B, C, D)
+ dt: float, optional
+ Sampling time [s] of the discrete-time systems. Defaults to `True`
+ (unspecified sampling time). Must be specified as a keyword argument,
+ for example, ``dt=0.1``.
+
+ See Also
+ --------
+ TransferFunction, ZerosPolesGain, dlti
+ ss2zpk, ss2tf, zpk2sos
+
+ Notes
+ -----
+ Changing the value of properties that are not part of the
+ `StateSpace` system representation (such as `zeros` or `poles`) is very
+ inefficient and may lead to numerical inaccuracies. It is better to
+ convert to the specific system representation first. For example, call
+ ``sys = sys.to_zpk()`` before accessing/changing the zeros, poles or gain.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+
+ >>> a = np.array([[1, 0.1], [0, 1]])
+ >>> b = np.array([[0.005], [0.1]])
+ >>> c = np.array([[1, 0]])
+ >>> d = np.array([[0]])
+
+ >>> signal.StateSpace(a, b, c, d, dt=0.1)
+ StateSpaceDiscrete(
+ array([[ 1. , 0.1],
+ [ 0. , 1. ]]),
+ array([[ 0.005],
+ [ 0.1 ]]),
+ array([[1, 0]]),
+ array([[0]]),
+ dt: 0.1
+ )
+
+ """
+ pass
+
+
+def lsim(system, U, T, X0=None, interp=True):
+ """
+ Simulate output of a continuous-time linear system.
+
+ Parameters
+ ----------
+ system : an instance of the LTI class or a tuple describing the system.
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1: (instance of `lti`)
+ * 2: (num, den)
+ * 3: (zeros, poles, gain)
+ * 4: (A, B, C, D)
+
+ U : array_like
+ An input array describing the input at each time `T`
+ (interpolation is assumed between given times). If there are
+ multiple inputs, then each column of the rank-2 array
+ represents an input. If U = 0 or None, a zero input is used.
+ T : array_like
+ The time steps at which the input is defined and at which the
+ output is desired. Must be nonnegative, increasing, and equally spaced.
+ X0 : array_like, optional
+ The initial conditions on the state vector (zero by default).
+ interp : bool, optional
+ Whether to use linear (True, the default) or zero-order-hold (False)
+ interpolation for the input array.
+
+ Returns
+ -------
+ T : 1D ndarray
+ Time values for the output.
+ yout : 1D ndarray
+ System response.
+ xout : ndarray
+ Time evolution of the state vector.
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``).
+
+ Examples
+ --------
+ We'll use `lsim` to simulate an analog Bessel filter applied to
+ a signal.
+
+ >>> import numpy as np
+ >>> from scipy.signal import bessel, lsim
+ >>> import matplotlib.pyplot as plt
+
+ Create a low-pass Bessel filter with a cutoff of 12 Hz.
+
+ >>> b, a = bessel(N=5, Wn=2*np.pi*12, btype='lowpass', analog=True)
+
+ Generate data to which the filter is applied.
+
+ >>> t = np.linspace(0, 1.25, 500, endpoint=False)
+
+ The input signal is the sum of three sinusoidal curves, with
+ frequencies 4 Hz, 40 Hz, and 80 Hz. The filter should mostly
+ eliminate the 40 Hz and 80 Hz components, leaving just the 4 Hz signal.
+
+ >>> u = (np.cos(2*np.pi*4*t) + 0.6*np.sin(2*np.pi*40*t) +
+ ... 0.5*np.cos(2*np.pi*80*t))
+
+ Simulate the filter with `lsim`.
+
+ >>> tout, yout, xout = lsim((b, a), U=u, T=t)
+
+ Plot the result.
+
+ >>> plt.plot(t, u, 'r', alpha=0.5, linewidth=1, label='input')
+ >>> plt.plot(tout, yout, 'k', linewidth=1.5, label='output')
+ >>> plt.legend(loc='best', shadow=True, framealpha=1)
+ >>> plt.grid(alpha=0.3)
+ >>> plt.xlabel('t')
+ >>> plt.show()
+
+ In a second example, we simulate a double integrator ``y'' = u``, with
+ a constant input ``u = 1``. We'll use the state space representation
+ of the integrator.
+
+ >>> from scipy.signal import lti
+ >>> A = np.array([[0.0, 1.0], [0.0, 0.0]])
+ >>> B = np.array([[0.0], [1.0]])
+ >>> C = np.array([[1.0, 0.0]])
+ >>> D = 0.0
+ >>> system = lti(A, B, C, D)
+
+ `t` and `u` define the time and input signal for the system to
+ be simulated.
+
+ >>> t = np.linspace(0, 5, num=50)
+ >>> u = np.ones_like(t)
+
+ Compute the simulation, and then plot `y`. As expected, the plot shows
+ the curve ``y = 0.5*t**2``.
+
+ >>> tout, y, x = lsim(system, u, t)
+ >>> plt.plot(t, y)
+ >>> plt.grid(alpha=0.3)
+ >>> plt.xlabel('t')
+ >>> plt.show()
+
+ """
+ if isinstance(system, lti):
+ sys = system._as_ss()
+ elif isinstance(system, dlti):
+ raise AttributeError('lsim can only be used with continuous-time '
+ 'systems.')
+ else:
+ sys = lti(*system)._as_ss()
+ T = atleast_1d(T)
+ if len(T.shape) != 1:
+ raise ValueError("T must be a rank-1 array.")
+
+ A, B, C, D = map(np.asarray, (sys.A, sys.B, sys.C, sys.D))
+ n_states = A.shape[0]
+ n_inputs = B.shape[1]
+
+ n_steps = T.size
+ if X0 is None:
+ X0 = zeros(n_states, sys.A.dtype)
+ xout = np.empty((n_steps, n_states), sys.A.dtype)
+
+ if T[0] == 0:
+ xout[0] = X0
+ elif T[0] > 0:
+ # step forward to initial time, with zero input
+ xout[0] = dot(X0, linalg.expm(transpose(A) * T[0]))
+ else:
+ raise ValueError("Initial time must be nonnegative")
+
+ no_input = (U is None or
+ (isinstance(U, int | float) and U == 0.) or
+ not np.any(U))
+
+ if n_steps == 1:
+ yout = squeeze(xout @ C.T)
+ if not no_input:
+ yout += squeeze(U @ D.T)
+ return T, yout, squeeze(xout)
+
+ dt = T[1] - T[0]
+ if not np.allclose(np.diff(T), dt):
+ raise ValueError("Time steps are not equally spaced.")
+
+ if no_input:
+ # Zero input: just use matrix exponential
+ # take transpose because state is a row vector
+ expAT_dt = linalg.expm(A.T * dt)
+ for i in range(1, n_steps):
+ xout[i] = xout[i-1] @ expAT_dt
+ yout = squeeze(xout @ C.T)
+ return T, yout, squeeze(xout)
+
+ # Nonzero input
+ U = atleast_1d(U)
+ if U.ndim == 1:
+ U = U[:, np.newaxis]
+
+ if U.shape[0] != n_steps:
+ raise ValueError("U must have the same number of rows "
+ "as elements in T.")
+
+ if U.shape[1] != n_inputs:
+ raise ValueError("System does not define that many inputs.")
+
+ if not interp:
+ # Zero-order hold
+ # Algorithm: to integrate from time 0 to time dt, we solve
+ # xdot = A x + B u, x(0) = x0
+ # udot = 0, u(0) = u0.
+ #
+ # Solution is
+ # [ x(dt) ] [ A*dt B*dt ] [ x0 ]
+ # [ u(dt) ] = exp [ 0 0 ] [ u0 ]
+ M = np.vstack([np.hstack([A * dt, B * dt]),
+ np.zeros((n_inputs, n_states + n_inputs))])
+ # transpose everything because the state and input are row vectors
+ expMT = linalg.expm(M.T)
+ Ad = expMT[:n_states, :n_states]
+ Bd = expMT[n_states:, :n_states]
+ for i in range(1, n_steps):
+ xout[i] = xout[i-1] @ Ad + U[i-1] @ Bd
+ else:
+ # Linear interpolation between steps
+ # Algorithm: to integrate from time 0 to time dt, with linear
+ # interpolation between inputs u(0) = u0 and u(dt) = u1, we solve
+ # xdot = A x + B u, x(0) = x0
+ # udot = (u1 - u0) / dt, u(0) = u0.
+ #
+ # Solution is
+ # [ x(dt) ] [ A*dt B*dt 0 ] [ x0 ]
+ # [ u(dt) ] = exp [ 0 0 I ] [ u0 ]
+ # [u1 - u0] [ 0 0 0 ] [u1 - u0]
+ M = np.vstack([np.hstack([A * dt, B * dt,
+ np.zeros((n_states, n_inputs))]),
+ np.hstack([np.zeros((n_inputs, n_states + n_inputs)),
+ np.identity(n_inputs)]),
+ np.zeros((n_inputs, n_states + 2 * n_inputs))])
+ expMT = linalg.expm(M.T)
+ Ad = expMT[:n_states, :n_states]
+ Bd1 = expMT[n_states+n_inputs:, :n_states]
+ Bd0 = expMT[n_states:n_states + n_inputs, :n_states] - Bd1
+ for i in range(1, n_steps):
+ xout[i] = xout[i-1] @ Ad + U[i-1] @ Bd0 + U[i] @ Bd1
+
+ yout = squeeze(xout @ C.T) + squeeze(U @ D.T)
+ return T, yout, squeeze(xout)
+
+
+def _default_response_times(A, n):
+ """Compute a reasonable set of time samples for the response time.
+
+ This function is used by `impulse` and `step` to compute the response time
+ when the `T` argument to the function is None.
+
+ Parameters
+ ----------
+ A : array_like
+ The system matrix, which is square.
+ n : int
+ The number of time samples to generate.
+
+ Returns
+ -------
+ t : ndarray
+ The 1-D array of length `n` of time samples at which the response
+ is to be computed.
+ """
+ # Create a reasonable time interval.
+ # TODO: This could use some more work.
+ # For example, what is expected when the system is unstable?
+ vals = linalg.eigvals(A)
+ r = min(abs(real(vals)))
+ if r == 0.0:
+ r = 1.0
+ tc = 1.0 / r
+ t = linspace(0.0, 7 * tc, n)
+ return t
+
+
+def impulse(system, X0=None, T=None, N=None):
+ """Impulse response of continuous-time system.
+
+ Parameters
+ ----------
+ system : an instance of the LTI class or a tuple of array_like
+ describing the system.
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1 (instance of `lti`)
+ * 2 (num, den)
+ * 3 (zeros, poles, gain)
+ * 4 (A, B, C, D)
+
+ X0 : array_like, optional
+ Initial state-vector. Defaults to zero.
+ T : array_like, optional
+ Time points. Computed if not given.
+ N : int, optional
+ The number of time points to compute (if `T` is not given).
+
+ Returns
+ -------
+ T : ndarray
+ A 1-D array of time points.
+ yout : ndarray
+ A 1-D array containing the impulse response of the system (except for
+ singularities at zero).
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``).
+
+ Examples
+ --------
+ Compute the impulse response of a second order system with a repeated
+ root: ``x''(t) + 2*x'(t) + x(t) = u(t)``
+
+ >>> from scipy import signal
+ >>> system = ([1.0], [1.0, 2.0, 1.0])
+ >>> t, y = signal.impulse(system)
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(t, y)
+
+ """
+ if isinstance(system, lti):
+ sys = system._as_ss()
+ elif isinstance(system, dlti):
+ raise AttributeError('impulse can only be used with continuous-time '
+ 'systems.')
+ else:
+ sys = lti(*system)._as_ss()
+ if X0 is None:
+ X = squeeze(sys.B)
+ else:
+ X = squeeze(sys.B + X0)
+ if N is None:
+ N = 100
+ if T is None:
+ T = _default_response_times(sys.A, N)
+ else:
+ T = asarray(T)
+
+ _, h, _ = lsim(sys, 0., T, X, interp=False)
+ return T, h
+
+
+def step(system, X0=None, T=None, N=None):
+ """Step response of continuous-time system.
+
+ Parameters
+ ----------
+ system : an instance of the LTI class or a tuple of array_like
+ describing the system.
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1 (instance of `lti`)
+ * 2 (num, den)
+ * 3 (zeros, poles, gain)
+ * 4 (A, B, C, D)
+
+ X0 : array_like, optional
+ Initial state-vector (default is zero).
+ T : array_like, optional
+ Time points (computed if not given).
+ N : int, optional
+ Number of time points to compute if `T` is not given.
+
+ Returns
+ -------
+ T : 1D ndarray
+ Output time points.
+ yout : 1D ndarray
+ Step response of system.
+
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``).
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> lti = signal.lti([1.0], [1.0, 1.0])
+ >>> t, y = signal.step(lti)
+ >>> plt.plot(t, y)
+ >>> plt.xlabel('Time [s]')
+ >>> plt.ylabel('Amplitude')
+ >>> plt.title('Step response for 1. Order Lowpass')
+ >>> plt.grid()
+
+ """
+ if isinstance(system, lti):
+ sys = system._as_ss()
+ elif isinstance(system, dlti):
+ raise AttributeError('step can only be used with continuous-time '
+ 'systems.')
+ else:
+ sys = lti(*system)._as_ss()
+ if N is None:
+ N = 100
+ if T is None:
+ T = _default_response_times(sys.A, N)
+ else:
+ T = asarray(T)
+ U = ones(T.shape, sys.A.dtype)
+ vals = lsim(sys, U, T, X0=X0, interp=False)
+ return vals[0], vals[1]
+
+
+def bode(system, w=None, n=100):
+ """
+ Calculate Bode magnitude and phase data of a continuous-time system.
+
+ Parameters
+ ----------
+ system : an instance of the LTI class or a tuple describing the system.
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1 (instance of `lti`)
+ * 2 (num, den)
+ * 3 (zeros, poles, gain)
+ * 4 (A, B, C, D)
+
+ w : array_like, optional
+ Array of frequencies (in rad/s). Magnitude and phase data is calculated
+ for every value in this array. If not given a reasonable set will be
+ calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Frequency array [rad/s]
+ mag : 1D ndarray
+ Magnitude array [dB]
+ phase : 1D ndarray
+ Phase array [deg]
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``).
+
+ .. versionadded:: 0.11.0
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> sys = signal.TransferFunction([1], [1, 1])
+ >>> w, mag, phase = signal.bode(sys)
+
+ >>> plt.figure()
+ >>> plt.semilogx(w, mag) # Bode magnitude plot
+ >>> plt.figure()
+ >>> plt.semilogx(w, phase) # Bode phase plot
+ >>> plt.show()
+
+ """
+ w, y = freqresp(system, w=w, n=n)
+
+ mag = 20.0 * np.log10(abs(y))
+ phase = np.unwrap(np.arctan2(y.imag, y.real)) * 180.0 / np.pi
+
+ return w, mag, phase
+
+
+def freqresp(system, w=None, n=10000):
+ r"""Calculate the frequency response of a continuous-time system.
+
+ Parameters
+ ----------
+ system : an instance of the `lti` class or a tuple describing the system.
+ The following gives the number of elements in the tuple and
+ the interpretation:
+
+ * 1 (instance of `lti`)
+ * 2 (num, den)
+ * 3 (zeros, poles, gain)
+ * 4 (A, B, C, D)
+
+ w : array_like, optional
+ Array of frequencies (in rad/s). Magnitude and phase data is
+ calculated for every value in this array. If not given, a reasonable
+ set will be calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Frequency array [rad/s]
+ H : 1D ndarray
+ Array of complex magnitude values
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``s^2 + 3s + 5`` would be represented as ``[1, 3, 5]``).
+
+ Examples
+ --------
+ Generating the Nyquist plot of a transfer function
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ Construct the transfer function :math:`H(s) = \frac{5}{(s-1)^3}`:
+
+ >>> s1 = signal.ZerosPolesGain([], [1, 1, 1], [5])
+
+ >>> w, H = signal.freqresp(s1)
+
+ >>> plt.figure()
+ >>> plt.plot(H.real, H.imag, "b")
+ >>> plt.plot(H.real, -H.imag, "r")
+ >>> plt.show()
+ """
+ if isinstance(system, lti):
+ if isinstance(system, TransferFunction | ZerosPolesGain):
+ sys = system
+ else:
+ sys = system._as_zpk()
+ elif isinstance(system, dlti):
+ raise AttributeError('freqresp can only be used with continuous-time '
+ 'systems.')
+ else:
+ sys = lti(*system)._as_zpk()
+
+ if sys.inputs != 1 or sys.outputs != 1:
+ raise ValueError("freqresp() requires a SISO (single input, single "
+ "output) system.")
+
+ if w is not None:
+ worN = w
+ else:
+ worN = n
+
+ if isinstance(sys, TransferFunction):
+ # In the call to freqs(), sys.num.ravel() is used because there are
+ # cases where sys.num is a 2-D array with a single row.
+ w, h = freqs(sys.num.ravel(), sys.den, worN=worN)
+
+ elif isinstance(sys, ZerosPolesGain):
+ w, h = freqs_zpk(sys.zeros, sys.poles, sys.gain, worN=worN)
+
+ return w, h
+
+
+# This class will be used by place_poles to return its results
+# see https://code.activestate.com/recipes/52308/
+class Bunch:
+ def __init__(self, **kwds):
+ self.__dict__.update(kwds)
+
+
+def _valid_inputs(A, B, poles, method, rtol, maxiter):
+ """
+ Check the poles come in complex conjugate pairs
+ Check shapes of A, B and poles are compatible.
+ Check the method chosen is compatible with provided poles
+ Return update method to use and ordered poles
+
+ """
+ poles = np.asarray(poles)
+ if poles.ndim > 1:
+ raise ValueError("Poles must be a 1D array like.")
+ # Will raise ValueError if poles do not come in complex conjugates pairs
+ poles = _order_complex_poles(poles)
+ if A.ndim > 2:
+ raise ValueError("A must be a 2D array/matrix.")
+ if B.ndim > 2:
+ raise ValueError("B must be a 2D array/matrix")
+ if A.shape[0] != A.shape[1]:
+ raise ValueError("A must be square")
+ if len(poles) > A.shape[0]:
+ raise ValueError(
+ f"maximum number of poles is {A.shape[0]} but you asked for {len(poles)}"
+ )
+ if len(poles) < A.shape[0]:
+ raise ValueError(
+ f"number of poles is {len(poles)} but you should provide {A.shape[0]}"
+ )
+ r = np.linalg.matrix_rank(B)
+ for p in poles:
+ if sum(p == poles) > r:
+ raise ValueError("at least one of the requested pole is repeated "
+ "more than rank(B) times")
+ # Choose update method
+ update_loop = _YT_loop
+ if method not in ('KNV0','YT'):
+ raise ValueError("The method keyword must be one of 'YT' or 'KNV0'")
+
+ if method == "KNV0":
+ update_loop = _KNV0_loop
+ if not all(np.isreal(poles)):
+ raise ValueError("Complex poles are not supported by KNV0")
+
+ if maxiter < 1:
+ raise ValueError("maxiter must be at least equal to 1")
+
+ # We do not check rtol <= 0 as the user can use a negative rtol to
+ # force maxiter iterations
+ if rtol > 1:
+ raise ValueError("rtol can not be greater than 1")
+
+ return update_loop, poles
+
+
+def _order_complex_poles(poles):
+ """
+ Check we have complex conjugates pairs and reorder P according to YT, ie
+ real_poles, complex_i, conjugate complex_i, ....
+ The lexicographic sort on the complex poles is added to help the user to
+ compare sets of poles.
+ """
+ ordered_poles = np.sort(poles[np.isreal(poles)])
+ im_poles = []
+ for p in np.sort(poles[np.imag(poles) < 0]):
+ if np.conj(p) in poles:
+ im_poles.extend((p, np.conj(p)))
+
+ ordered_poles = np.hstack((ordered_poles, im_poles))
+
+ if poles.shape[0] != len(ordered_poles):
+ raise ValueError("Complex poles must come with their conjugates")
+ return ordered_poles
+
+
+def _KNV0(B, ker_pole, transfer_matrix, j, poles):
+ """
+ Algorithm "KNV0" Kautsky et Al. Robust pole
+ assignment in linear state feedback, Int journal of Control
+ 1985, vol 41 p 1129->1155
+ https://la.epfl.ch/files/content/sites/la/files/
+ users/105941/public/KautskyNicholsDooren
+
+ """
+ # Remove xj form the base
+ transfer_matrix_not_j = np.delete(transfer_matrix, j, axis=1)
+ # If we QR this matrix in full mode Q=Q0|Q1
+ # then Q1 will be a single column orthogonal to
+ # Q0, that's what we are looking for !
+
+ # After merge of gh-4249 great speed improvements could be achieved
+ # using QR updates instead of full QR in the line below
+
+ # To debug with numpy qr uncomment the line below
+ # Q, R = np.linalg.qr(transfer_matrix_not_j, mode="complete")
+ Q, R = s_qr(transfer_matrix_not_j, mode="full")
+
+ mat_ker_pj = np.dot(ker_pole[j], ker_pole[j].T)
+ yj = np.dot(mat_ker_pj, Q[:, -1])
+
+ # If Q[:, -1] is "almost" orthogonal to ker_pole[j] its
+ # projection into ker_pole[j] will yield a vector
+ # close to 0. As we are looking for a vector in ker_pole[j]
+ # simply stick with transfer_matrix[:, j] (unless someone provides me with
+ # a better choice ?)
+
+ if not np.allclose(yj, 0):
+ xj = yj/np.linalg.norm(yj)
+ transfer_matrix[:, j] = xj
+
+ # KNV does not support complex poles, using YT technique the two lines
+ # below seem to work 9 out of 10 times but it is not reliable enough:
+ # transfer_matrix[:, j]=real(xj)
+ # transfer_matrix[:, j+1]=imag(xj)
+
+ # Add this at the beginning of this function if you wish to test
+ # complex support:
+ # if ~np.isreal(P[j]) and (j>=B.shape[0]-1 or P[j]!=np.conj(P[j+1])):
+ # return
+ # Problems arise when imag(xj)=>0 I have no idea on how to fix this
+
+
+def _YT_real(ker_pole, Q, transfer_matrix, i, j):
+ """
+ Applies algorithm from YT section 6.1 page 19 related to real pairs
+ """
+ # step 1 page 19
+ u = Q[:, -2, np.newaxis]
+ v = Q[:, -1, np.newaxis]
+
+ # step 2 page 19
+ m = np.dot(np.dot(ker_pole[i].T, np.dot(u, v.T) -
+ np.dot(v, u.T)), ker_pole[j])
+
+ # step 3 page 19
+ um, sm, vm = np.linalg.svd(m)
+ # mu1, mu2 two first columns of U => 2 first lines of U.T
+ mu1, mu2 = um.T[:2, :, np.newaxis]
+ # VM is V.T with numpy we want the first two lines of V.T
+ nu1, nu2 = vm[:2, :, np.newaxis]
+
+ # what follows is a rough python translation of the formulas
+ # in section 6.2 page 20 (step 4)
+ transfer_matrix_j_mo_transfer_matrix_j = np.vstack((
+ transfer_matrix[:, i, np.newaxis],
+ transfer_matrix[:, j, np.newaxis]))
+
+ if not np.allclose(sm[0], sm[1]):
+ ker_pole_imo_mu1 = np.dot(ker_pole[i], mu1)
+ ker_pole_i_nu1 = np.dot(ker_pole[j], nu1)
+ ker_pole_mu_nu = np.vstack((ker_pole_imo_mu1, ker_pole_i_nu1))
+ else:
+ ker_pole_ij = np.vstack((
+ np.hstack((ker_pole[i],
+ np.zeros(ker_pole[i].shape))),
+ np.hstack((np.zeros(ker_pole[j].shape),
+ ker_pole[j]))
+ ))
+ mu_nu_matrix = np.vstack(
+ (np.hstack((mu1, mu2)), np.hstack((nu1, nu2)))
+ )
+ ker_pole_mu_nu = np.dot(ker_pole_ij, mu_nu_matrix)
+ transfer_matrix_ij = np.dot(np.dot(ker_pole_mu_nu, ker_pole_mu_nu.T),
+ transfer_matrix_j_mo_transfer_matrix_j)
+ if not np.allclose(transfer_matrix_ij, 0):
+ transfer_matrix_ij = (np.sqrt(2)*transfer_matrix_ij /
+ np.linalg.norm(transfer_matrix_ij))
+ transfer_matrix[:, i] = transfer_matrix_ij[
+ :transfer_matrix[:, i].shape[0], 0
+ ]
+ transfer_matrix[:, j] = transfer_matrix_ij[
+ transfer_matrix[:, i].shape[0]:, 0
+ ]
+ else:
+ # As in knv0 if transfer_matrix_j_mo_transfer_matrix_j is orthogonal to
+ # Vect{ker_pole_mu_nu} assign transfer_matrixi/transfer_matrix_j to
+ # ker_pole_mu_nu and iterate. As we are looking for a vector in
+ # Vect{Matker_pole_MU_NU} (see section 6.1 page 19) this might help
+ # (that's a guess, not a claim !)
+ transfer_matrix[:, i] = ker_pole_mu_nu[
+ :transfer_matrix[:, i].shape[0], 0
+ ]
+ transfer_matrix[:, j] = ker_pole_mu_nu[
+ transfer_matrix[:, i].shape[0]:, 0
+ ]
+
+
+def _YT_complex(ker_pole, Q, transfer_matrix, i, j):
+ """
+ Applies algorithm from YT section 6.2 page 20 related to complex pairs
+ """
+ # step 1 page 20
+ ur = np.sqrt(2)*Q[:, -2, np.newaxis]
+ ui = np.sqrt(2)*Q[:, -1, np.newaxis]
+ u = ur + 1j*ui
+
+ # step 2 page 20
+ ker_pole_ij = ker_pole[i]
+ m = np.dot(np.dot(np.conj(ker_pole_ij.T), np.dot(u, np.conj(u).T) -
+ np.dot(np.conj(u), u.T)), ker_pole_ij)
+
+ # step 3 page 20
+ e_val, e_vec = np.linalg.eig(m)
+ # sort eigenvalues according to their module
+ e_val_idx = np.argsort(np.abs(e_val))
+ mu1 = e_vec[:, e_val_idx[-1], np.newaxis]
+ mu2 = e_vec[:, e_val_idx[-2], np.newaxis]
+
+ # what follows is a rough python translation of the formulas
+ # in section 6.2 page 20 (step 4)
+
+ # remember transfer_matrix_i has been split as
+ # transfer_matrix[i]=real(transfer_matrix_i) and
+ # transfer_matrix[j]=imag(transfer_matrix_i)
+ transfer_matrix_j_mo_transfer_matrix_j = (
+ transfer_matrix[:, i, np.newaxis] +
+ 1j*transfer_matrix[:, j, np.newaxis]
+ )
+ if not np.allclose(np.abs(e_val[e_val_idx[-1]]),
+ np.abs(e_val[e_val_idx[-2]])):
+ ker_pole_mu = np.dot(ker_pole_ij, mu1)
+ else:
+ mu1_mu2_matrix = np.hstack((mu1, mu2))
+ ker_pole_mu = np.dot(ker_pole_ij, mu1_mu2_matrix)
+ transfer_matrix_i_j = np.dot(np.dot(ker_pole_mu, np.conj(ker_pole_mu.T)),
+ transfer_matrix_j_mo_transfer_matrix_j)
+
+ if not np.allclose(transfer_matrix_i_j, 0):
+ transfer_matrix_i_j = (transfer_matrix_i_j /
+ np.linalg.norm(transfer_matrix_i_j))
+ transfer_matrix[:, i] = np.real(transfer_matrix_i_j[:, 0])
+ transfer_matrix[:, j] = np.imag(transfer_matrix_i_j[:, 0])
+ else:
+ # same idea as in YT_real
+ transfer_matrix[:, i] = np.real(ker_pole_mu[:, 0])
+ transfer_matrix[:, j] = np.imag(ker_pole_mu[:, 0])
+
+
+def _YT_loop(ker_pole, transfer_matrix, poles, B, maxiter, rtol):
+ """
+ Algorithm "YT" Tits, Yang. Globally Convergent
+ Algorithms for Robust Pole Assignment by State Feedback
+ https://hdl.handle.net/1903/5598
+ The poles P have to be sorted accordingly to section 6.2 page 20
+
+ """
+ # The IEEE edition of the YT paper gives useful information on the
+ # optimal update order for the real poles in order to minimize the number
+ # of times we have to loop over all poles, see page 1442
+ nb_real = poles[np.isreal(poles)].shape[0]
+ # hnb => Half Nb Real
+ hnb = nb_real // 2
+
+ # Stick to the indices in the paper and then remove one to get numpy array
+ # index it is a bit easier to link the code to the paper this way even if it
+ # is not very clean. The paper is unclear about what should be done when
+ # there is only one real pole => use KNV0 on this real pole seem to work
+ if nb_real > 0:
+ #update the biggest real pole with the smallest one
+ update_order = [[nb_real], [1]]
+ else:
+ update_order = [[],[]]
+
+ r_comp = np.arange(nb_real+1, len(poles)+1, 2)
+ # step 1.a
+ r_p = np.arange(1, hnb+nb_real % 2)
+ update_order[0].extend(2*r_p)
+ update_order[1].extend(2*r_p+1)
+ # step 1.b
+ update_order[0].extend(r_comp)
+ update_order[1].extend(r_comp+1)
+ # step 1.c
+ r_p = np.arange(1, hnb+1)
+ update_order[0].extend(2*r_p-1)
+ update_order[1].extend(2*r_p)
+ # step 1.d
+ if hnb == 0 and np.isreal(poles[0]):
+ update_order[0].append(1)
+ update_order[1].append(1)
+ update_order[0].extend(r_comp)
+ update_order[1].extend(r_comp+1)
+ # step 2.a
+ r_j = np.arange(2, hnb+nb_real % 2)
+ for j in r_j:
+ for i in range(1, hnb+1):
+ update_order[0].append(i)
+ update_order[1].append(i+j)
+ # step 2.b
+ if hnb == 0 and np.isreal(poles[0]):
+ update_order[0].append(1)
+ update_order[1].append(1)
+ update_order[0].extend(r_comp)
+ update_order[1].extend(r_comp+1)
+ # step 2.c
+ r_j = np.arange(2, hnb+nb_real % 2)
+ for j in r_j:
+ for i in range(hnb+1, nb_real+1):
+ idx_1 = i+j
+ if idx_1 > nb_real:
+ idx_1 = i+j-nb_real
+ update_order[0].append(i)
+ update_order[1].append(idx_1)
+ # step 2.d
+ if hnb == 0 and np.isreal(poles[0]):
+ update_order[0].append(1)
+ update_order[1].append(1)
+ update_order[0].extend(r_comp)
+ update_order[1].extend(r_comp+1)
+ # step 3.a
+ for i in range(1, hnb+1):
+ update_order[0].append(i)
+ update_order[1].append(i+hnb)
+ # step 3.b
+ if hnb == 0 and np.isreal(poles[0]):
+ update_order[0].append(1)
+ update_order[1].append(1)
+ update_order[0].extend(r_comp)
+ update_order[1].extend(r_comp+1)
+
+ update_order = np.array(update_order).T-1
+ stop = False
+ nb_try = 0
+ while nb_try < maxiter and not stop:
+ det_transfer_matrixb = np.abs(np.linalg.det(transfer_matrix))
+ for i, j in update_order:
+ if i == j:
+ assert i == 0, "i!=0 for KNV call in YT"
+ assert np.isreal(poles[i]), "calling KNV on a complex pole"
+ _KNV0(B, ker_pole, transfer_matrix, i, poles)
+ else:
+ transfer_matrix_not_i_j = np.delete(transfer_matrix, (i, j),
+ axis=1)
+ # after merge of gh-4249 great speed improvements could be
+ # achieved using QR updates instead of full QR in the line below
+
+ #to debug with numpy qr uncomment the line below
+ #Q, _ = np.linalg.qr(transfer_matrix_not_i_j, mode="complete")
+ Q, _ = s_qr(transfer_matrix_not_i_j, mode="full")
+
+ if np.isreal(poles[i]):
+ assert np.isreal(poles[j]), "mixing real and complex " + \
+ "in YT_real" + str(poles)
+ _YT_real(ker_pole, Q, transfer_matrix, i, j)
+ else:
+ assert ~np.isreal(poles[i]), "mixing real and complex " + \
+ "in YT_real" + str(poles)
+ _YT_complex(ker_pole, Q, transfer_matrix, i, j)
+
+ det_transfer_matrix = np.max((np.sqrt(np.spacing(1)),
+ np.abs(np.linalg.det(transfer_matrix))))
+ cur_rtol = np.abs(
+ (det_transfer_matrix -
+ det_transfer_matrixb) /
+ det_transfer_matrix)
+ if cur_rtol < rtol and det_transfer_matrix > np.sqrt(np.spacing(1)):
+ # Convergence test from YT page 21
+ stop = True
+ nb_try += 1
+ return stop, cur_rtol, nb_try
+
+
+def _KNV0_loop(ker_pole, transfer_matrix, poles, B, maxiter, rtol):
+ """
+ Loop over all poles one by one and apply KNV method 0 algorithm
+ """
+ # This method is useful only because we need to be able to call
+ # _KNV0 from YT without looping over all poles, otherwise it would
+ # have been fine to mix _KNV0_loop and _KNV0 in a single function
+ stop = False
+ nb_try = 0
+ while nb_try < maxiter and not stop:
+ det_transfer_matrixb = np.abs(np.linalg.det(transfer_matrix))
+ for j in range(B.shape[0]):
+ _KNV0(B, ker_pole, transfer_matrix, j, poles)
+
+ det_transfer_matrix = np.max((np.sqrt(np.spacing(1)),
+ np.abs(np.linalg.det(transfer_matrix))))
+ cur_rtol = np.abs((det_transfer_matrix - det_transfer_matrixb) /
+ det_transfer_matrix)
+ if cur_rtol < rtol and det_transfer_matrix > np.sqrt(np.spacing(1)):
+ # Convergence test from YT page 21
+ stop = True
+
+ nb_try += 1
+ return stop, cur_rtol, nb_try
+
+
+def place_poles(A, B, poles, method="YT", rtol=1e-3, maxiter=30):
+ """
+ Compute K such that eigenvalues (A - dot(B, K))=poles.
+
+ K is the gain matrix such as the plant described by the linear system
+ ``AX+BU`` will have its closed-loop poles, i.e the eigenvalues ``A - B*K``,
+ as close as possible to those asked for in poles.
+
+ SISO, MISO and MIMO systems are supported.
+
+ Parameters
+ ----------
+ A, B : ndarray
+ State-space representation of linear system ``AX + BU``.
+ poles : array_like
+ Desired real poles and/or complex conjugates poles.
+ Complex poles are only supported with ``method="YT"`` (default).
+ method: {'YT', 'KNV0'}, optional
+ Which method to choose to find the gain matrix K. One of:
+
+ - 'YT': Yang Tits
+ - 'KNV0': Kautsky, Nichols, Van Dooren update method 0
+
+ See References and Notes for details on the algorithms.
+ rtol: float, optional
+ After each iteration the determinant of the eigenvectors of
+ ``A - B*K`` is compared to its previous value, when the relative
+ error between these two values becomes lower than `rtol` the algorithm
+ stops. Default is 1e-3.
+ maxiter: int, optional
+ Maximum number of iterations to compute the gain matrix.
+ Default is 30.
+
+ Returns
+ -------
+ full_state_feedback : Bunch object
+ full_state_feedback is composed of:
+ gain_matrix : 1-D ndarray
+ The closed loop matrix K such as the eigenvalues of ``A-BK``
+ are as close as possible to the requested poles.
+ computed_poles : 1-D ndarray
+ The poles corresponding to ``A-BK`` sorted as first the real
+ poles in increasing order, then the complex conjugates in
+ lexicographic order.
+ requested_poles : 1-D ndarray
+ The poles the algorithm was asked to place sorted as above,
+ they may differ from what was achieved.
+ X : 2-D ndarray
+ The transfer matrix such as ``X * diag(poles) = (A - B*K)*X``
+ (see Notes)
+ rtol : float
+ The relative tolerance achieved on ``det(X)`` (see Notes).
+ `rtol` will be NaN if it is possible to solve the system
+ ``diag(poles) = (A - B*K)``, or 0 when the optimization
+ algorithms can't do anything i.e when ``B.shape[1] == 1``.
+ nb_iter : int
+ The number of iterations performed before converging.
+ `nb_iter` will be NaN if it is possible to solve the system
+ ``diag(poles) = (A - B*K)``, or 0 when the optimization
+ algorithms can't do anything i.e when ``B.shape[1] == 1``.
+
+ Notes
+ -----
+ The Tits and Yang (YT), [2]_ paper is an update of the original Kautsky et
+ al. (KNV) paper [1]_. KNV relies on rank-1 updates to find the transfer
+ matrix X such that ``X * diag(poles) = (A - B*K)*X``, whereas YT uses
+ rank-2 updates. This yields on average more robust solutions (see [2]_
+ pp 21-22), furthermore the YT algorithm supports complex poles whereas KNV
+ does not in its original version. Only update method 0 proposed by KNV has
+ been implemented here, hence the name ``'KNV0'``.
+
+ KNV extended to complex poles is used in Matlab's ``place`` function, YT is
+ distributed under a non-free licence by Slicot under the name ``robpole``.
+ It is unclear and undocumented how KNV0 has been extended to complex poles
+ (Tits and Yang claim on page 14 of their paper that their method can not be
+ used to extend KNV to complex poles), therefore only YT supports them in
+ this implementation.
+
+ As the solution to the problem of pole placement is not unique for MIMO
+ systems, both methods start with a tentative transfer matrix which is
+ altered in various way to increase its determinant. Both methods have been
+ proven to converge to a stable solution, however depending on the way the
+ initial transfer matrix is chosen they will converge to different
+ solutions and therefore there is absolutely no guarantee that using
+ ``'KNV0'`` will yield results similar to Matlab's or any other
+ implementation of these algorithms.
+
+ Using the default method ``'YT'`` should be fine in most cases; ``'KNV0'``
+ is only provided because it is needed by ``'YT'`` in some specific cases.
+ Furthermore ``'YT'`` gives on average more robust results than ``'KNV0'``
+ when ``abs(det(X))`` is used as a robustness indicator.
+
+ [2]_ is available as a technical report on the following URL:
+ https://hdl.handle.net/1903/5598
+
+ References
+ ----------
+ .. [1] J. Kautsky, N.K. Nichols and P. van Dooren, "Robust pole assignment
+ in linear state feedback", International Journal of Control, Vol. 41
+ pp. 1129-1155, 1985.
+ .. [2] A.L. Tits and Y. Yang, "Globally convergent algorithms for robust
+ pole assignment by state feedback", IEEE Transactions on Automatic
+ Control, Vol. 41, pp. 1432-1452, 1996.
+
+ Examples
+ --------
+ A simple example demonstrating real pole placement using both KNV and YT
+ algorithms. This is example number 1 from section 4 of the reference KNV
+ publication ([1]_):
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> A = np.array([[ 1.380, -0.2077, 6.715, -5.676 ],
+ ... [-0.5814, -4.290, 0, 0.6750 ],
+ ... [ 1.067, 4.273, -6.654, 5.893 ],
+ ... [ 0.0480, 4.273, 1.343, -2.104 ]])
+ >>> B = np.array([[ 0, 5.679 ],
+ ... [ 1.136, 1.136 ],
+ ... [ 0, 0, ],
+ ... [-3.146, 0 ]])
+ >>> P = np.array([-0.2, -0.5, -5.0566, -8.6659])
+
+ Now compute K with KNV method 0, with the default YT method and with the YT
+ method while forcing 100 iterations of the algorithm and print some results
+ after each call.
+
+ >>> fsf1 = signal.place_poles(A, B, P, method='KNV0')
+ >>> fsf1.gain_matrix
+ array([[ 0.20071427, -0.96665799, 0.24066128, -0.10279785],
+ [ 0.50587268, 0.57779091, 0.51795763, -0.41991442]])
+
+ >>> fsf2 = signal.place_poles(A, B, P) # uses YT method
+ >>> fsf2.computed_poles
+ array([-8.6659, -5.0566, -0.5 , -0.2 ])
+
+ >>> fsf3 = signal.place_poles(A, B, P, rtol=-1, maxiter=100)
+ >>> fsf3.X
+ array([[ 0.52072442+0.j, -0.08409372+0.j, -0.56847937+0.j, 0.74823657+0.j],
+ [-0.04977751+0.j, -0.80872954+0.j, 0.13566234+0.j, -0.29322906+0.j],
+ [-0.82266932+0.j, -0.19168026+0.j, -0.56348322+0.j, -0.43815060+0.j],
+ [ 0.22267347+0.j, 0.54967577+0.j, -0.58387806+0.j, -0.40271926+0.j]])
+
+ The absolute value of the determinant of X is a good indicator to check the
+ robustness of the results, both ``'KNV0'`` and ``'YT'`` aim at maximizing
+ it. Below a comparison of the robustness of the results above:
+
+ >>> abs(np.linalg.det(fsf1.X)) < abs(np.linalg.det(fsf2.X))
+ True
+ >>> abs(np.linalg.det(fsf2.X)) < abs(np.linalg.det(fsf3.X))
+ True
+
+ Now a simple example for complex poles:
+
+ >>> A = np.array([[ 0, 7/3., 0, 0 ],
+ ... [ 0, 0, 0, 7/9. ],
+ ... [ 0, 0, 0, 0 ],
+ ... [ 0, 0, 0, 0 ]])
+ >>> B = np.array([[ 0, 0 ],
+ ... [ 0, 0 ],
+ ... [ 1, 0 ],
+ ... [ 0, 1 ]])
+ >>> P = np.array([-3, -1, -2-1j, -2+1j]) / 3.
+ >>> fsf = signal.place_poles(A, B, P, method='YT')
+
+ We can plot the desired and computed poles in the complex plane:
+
+ >>> t = np.linspace(0, 2*np.pi, 401)
+ >>> plt.plot(np.cos(t), np.sin(t), 'k--') # unit circle
+ >>> plt.plot(fsf.requested_poles.real, fsf.requested_poles.imag,
+ ... 'wo', label='Desired')
+ >>> plt.plot(fsf.computed_poles.real, fsf.computed_poles.imag, 'bx',
+ ... label='Placed')
+ >>> plt.grid()
+ >>> plt.axis('image')
+ >>> plt.axis([-1.1, 1.1, -1.1, 1.1])
+ >>> plt.legend(bbox_to_anchor=(1.05, 1), loc=2, numpoints=1)
+
+ """
+ # Move away all the inputs checking, it only adds noise to the code
+ update_loop, poles = _valid_inputs(A, B, poles, method, rtol, maxiter)
+
+ # The current value of the relative tolerance we achieved
+ cur_rtol = 0
+ # The number of iterations needed before converging
+ nb_iter = 0
+
+ # Step A: QR decomposition of B page 1132 KN
+ # to debug with numpy qr uncomment the line below
+ # u, z = np.linalg.qr(B, mode="complete")
+ u, z = s_qr(B, mode="full")
+ rankB = np.linalg.matrix_rank(B)
+ u0 = u[:, :rankB]
+ u1 = u[:, rankB:]
+ z = z[:rankB, :]
+
+ # If we can use the identity matrix as X the solution is obvious
+ if B.shape[0] == rankB:
+ # if B is square and full rank there is only one solution
+ # such as (A+BK)=inv(X)*diag(P)*X with X=eye(A.shape[0])
+ # i.e K=inv(B)*(diag(P)-A)
+ # if B has as many lines as its rank (but not square) there are many
+ # solutions and we can choose one using least squares
+ # => use lstsq in both cases.
+ # In both cases the transfer matrix X will be eye(A.shape[0]) and I
+ # can hardly think of a better one so there is nothing to optimize
+ #
+ # for complex poles we use the following trick
+ #
+ # |a -b| has for eigenvalues a+b and a-b
+ # |b a|
+ #
+ # |a+bi 0| has the obvious eigenvalues a+bi and a-bi
+ # |0 a-bi|
+ #
+ # e.g solving the first one in R gives the solution
+ # for the second one in C
+ diag_poles = np.zeros(A.shape)
+ idx = 0
+ while idx < poles.shape[0]:
+ p = poles[idx]
+ diag_poles[idx, idx] = np.real(p)
+ if ~np.isreal(p):
+ diag_poles[idx, idx+1] = -np.imag(p)
+ diag_poles[idx+1, idx+1] = np.real(p)
+ diag_poles[idx+1, idx] = np.imag(p)
+ idx += 1 # skip next one
+ idx += 1
+ gain_matrix = np.linalg.lstsq(B, diag_poles-A, rcond=-1)[0]
+ transfer_matrix = np.eye(A.shape[0])
+ cur_rtol = np.nan
+ nb_iter = np.nan
+ else:
+ # step A (p1144 KNV) and beginning of step F: decompose
+ # dot(U1.T, A-P[i]*I).T and build our set of transfer_matrix vectors
+ # in the same loop
+ ker_pole = []
+
+ # flag to skip the conjugate of a complex pole
+ skip_conjugate = False
+ # select orthonormal base ker_pole for each Pole and vectors for
+ # transfer_matrix
+ for j in range(B.shape[0]):
+ if skip_conjugate:
+ skip_conjugate = False
+ continue
+ pole_space_j = np.dot(u1.T, A-poles[j]*np.eye(B.shape[0])).T
+
+ # after QR Q=Q0|Q1
+ # only Q0 is used to reconstruct the qr'ed (dot Q, R) matrix.
+ # Q1 is orthogonal to Q0 and will be multiplied by the zeros in
+ # R when using mode "complete". In default mode Q1 and the zeros
+ # in R are not computed
+
+ # To debug with numpy qr uncomment the line below
+ # Q, _ = np.linalg.qr(pole_space_j, mode="complete")
+ Q, _ = s_qr(pole_space_j, mode="full")
+
+ ker_pole_j = Q[:, pole_space_j.shape[1]:]
+
+ # We want to select one vector in ker_pole_j to build the transfer
+ # matrix, however qr returns sometimes vectors with zeros on the
+ # same line for each pole and this yields very long convergence
+ # times.
+ # Or some other times a set of vectors, one with zero imaginary
+ # part and one (or several) with imaginary parts. After trying
+ # many ways to select the best possible one (eg ditch vectors
+ # with zero imaginary part for complex poles) I ended up summing
+ # all vectors in ker_pole_j, this solves 100% of the problems and
+ # is a valid choice for transfer_matrix.
+ # This way for complex poles we are sure to have a non zero
+ # imaginary part that way, and the problem of lines full of zeros
+ # in transfer_matrix is solved too as when a vector from
+ # ker_pole_j has a zero the other one(s) when
+ # ker_pole_j.shape[1]>1) for sure won't have a zero there.
+
+ transfer_matrix_j = np.sum(ker_pole_j, axis=1)[:, np.newaxis]
+ transfer_matrix_j = (transfer_matrix_j /
+ np.linalg.norm(transfer_matrix_j))
+ if ~np.isreal(poles[j]): # complex pole
+ transfer_matrix_j = np.hstack([np.real(transfer_matrix_j),
+ np.imag(transfer_matrix_j)])
+ ker_pole.extend([ker_pole_j, ker_pole_j])
+
+ # Skip next pole as it is the conjugate
+ skip_conjugate = True
+ else: # real pole, nothing to do
+ ker_pole.append(ker_pole_j)
+
+ if j == 0:
+ transfer_matrix = transfer_matrix_j
+ else:
+ transfer_matrix = np.hstack((transfer_matrix, transfer_matrix_j))
+
+ if rankB > 1: # otherwise there is nothing we can optimize
+ stop, cur_rtol, nb_iter = update_loop(ker_pole, transfer_matrix,
+ poles, B, maxiter, rtol)
+ if not stop and rtol > 0:
+ # if rtol<=0 the user has probably done that on purpose,
+ # don't annoy them
+ err_msg = (
+ "Convergence was not reached after maxiter iterations.\n"
+ f"You asked for a tolerance of {rtol}, we got {cur_rtol}."
+ )
+ warnings.warn(err_msg, stacklevel=2)
+
+ # reconstruct transfer_matrix to match complex conjugate pairs,
+ # ie transfer_matrix_j/transfer_matrix_j+1 are
+ # Re(Complex_pole), Im(Complex_pole) now and will be Re-Im/Re+Im after
+ transfer_matrix = transfer_matrix.astype(complex)
+ idx = 0
+ while idx < poles.shape[0]-1:
+ if ~np.isreal(poles[idx]):
+ rel = transfer_matrix[:, idx].copy()
+ img = transfer_matrix[:, idx+1]
+ # rel will be an array referencing a column of transfer_matrix
+ # if we don't copy() it will changer after the next line and
+ # and the line after will not yield the correct value
+ transfer_matrix[:, idx] = rel-1j*img
+ transfer_matrix[:, idx+1] = rel+1j*img
+ idx += 1 # skip next one
+ idx += 1
+
+ try:
+ m = np.linalg.solve(transfer_matrix.T, np.dot(np.diag(poles),
+ transfer_matrix.T)).T
+ gain_matrix = np.linalg.solve(z, np.dot(u0.T, m-A))
+ except np.linalg.LinAlgError as e:
+ raise ValueError("The poles you've chosen can't be placed. "
+ "Check the controllability matrix and try "
+ "another set of poles") from e
+
+ # Beware: Kautsky solves A+BK but the usual form is A-BK
+ gain_matrix = -gain_matrix
+ # K still contains complex with ~=0j imaginary parts, get rid of them
+ gain_matrix = np.real(gain_matrix)
+
+ full_state_feedback = Bunch()
+ full_state_feedback.gain_matrix = gain_matrix
+ full_state_feedback.computed_poles = _order_complex_poles(
+ np.linalg.eig(A - np.dot(B, gain_matrix))[0]
+ )
+ full_state_feedback.requested_poles = poles
+ full_state_feedback.X = transfer_matrix
+ full_state_feedback.rtol = cur_rtol
+ full_state_feedback.nb_iter = nb_iter
+
+ return full_state_feedback
+
+
+def dlsim(system, u, t=None, x0=None):
+ r"""Simulate output of a discrete-time linear system.
+
+ Parameters
+ ----------
+ system : dlti | tuple
+ An instance of the LTI class `dlti` or a tuple describing the system.
+ The number of elements in the tuple determine the interpretation. I.e.:
+
+ * ``system``: Instance of LTI class `dlti`. Note that derived instances, such
+ as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, are
+ allowed as well.
+ * ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`.
+ The coefficients of the polynomials should be specified in descending
+ exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``.
+ * ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described
+ in `ZerosPolesGain`.
+ * ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`.
+
+
+ u : array_like
+ An input array describing the input at each time `t` (interpolation is
+ assumed between given times). If there are multiple inputs, then each
+ column of the rank-2 array represents an input.
+ t : array_like, optional
+ The time steps at which the input is defined. If `t` is given, it
+ must be the same length as `u`, and the final value in `t` determines
+ the number of steps returned in the output.
+ x0 : array_like, optional
+ The initial conditions on the state vector (zero by default).
+
+ Returns
+ -------
+ tout : ndarray
+ Time values for the output, as a 1-D array.
+ yout : ndarray
+ System response, as a 1-D array.
+ xout : ndarray, optional
+ Time-evolution of the state-vector. Only generated if the input is a
+ `StateSpace` system.
+
+ See Also
+ --------
+ lsim, dstep, dimpulse, cont2discrete
+
+ Examples
+ --------
+ A simple integrator transfer function with a discrete time step of 1.0
+ could be implemented as:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> tf = ([1.0,], [1.0, -1.0], 1.0)
+ >>> t_in = [0.0, 1.0, 2.0, 3.0]
+ >>> u = np.asarray([0.0, 0.0, 1.0, 1.0])
+ >>> t_out, y = signal.dlsim(tf, u, t=t_in)
+ >>> y.T
+ array([[ 0., 0., 0., 1.]])
+
+ """
+ # Convert system to dlti-StateSpace
+ if isinstance(system, lti):
+ raise AttributeError('dlsim can only be used with discrete-time dlti '
+ 'systems.')
+ elif not isinstance(system, dlti):
+ system = dlti(*system[:-1], dt=system[-1])
+
+ # Condition needed to ensure output remains compatible
+ is_ss_input = isinstance(system, StateSpace)
+ system = system._as_ss()
+
+ u = np.atleast_1d(u)
+
+ if u.ndim == 1:
+ u = np.atleast_2d(u).T
+
+ if t is None:
+ out_samples = len(u)
+ stoptime = (out_samples - 1) * system.dt
+ else:
+ stoptime = t[-1]
+ out_samples = int(np.floor(stoptime / system.dt)) + 1
+
+ # Pre-build output arrays
+ xout = np.zeros((out_samples, system.A.shape[0]))
+ yout = np.zeros((out_samples, system.C.shape[0]))
+ tout = np.linspace(0.0, stoptime, num=out_samples)
+
+ # Check initial condition
+ if x0 is None:
+ xout[0, :] = np.zeros((system.A.shape[1],))
+ else:
+ xout[0, :] = np.asarray(x0)
+
+ # Pre-interpolate inputs into the desired time steps
+ if t is None:
+ u_dt = u
+ else:
+ if len(u.shape) == 1:
+ u = u[:, np.newaxis]
+
+ u_dt = make_interp_spline(t, u, k=1)(tout)
+
+ # Simulate the system
+ for i in range(0, out_samples - 1):
+ xout[i+1, :] = (np.dot(system.A, xout[i, :]) +
+ np.dot(system.B, u_dt[i, :]))
+ yout[i, :] = (np.dot(system.C, xout[i, :]) +
+ np.dot(system.D, u_dt[i, :]))
+
+ # Last point
+ yout[out_samples-1, :] = (np.dot(system.C, xout[out_samples-1, :]) +
+ np.dot(system.D, u_dt[out_samples-1, :]))
+
+ if is_ss_input:
+ return tout, yout, xout
+ else:
+ return tout, yout
+
+
+def dimpulse(system, x0=None, t=None, n=None):
+ r"""Impulse response of discrete-time system.
+
+ Parameters
+ ----------
+ system : dlti | tuple
+ An instance of the LTI class `dlti` or a tuple describing the system.
+ The number of elements in the tuple determine the interpretation. I.e.:
+
+ * ``system``: Instance of LTI class `dlti`. Note that derived instances, such
+ as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, are
+ allowed as well.
+ * ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`.
+ The coefficients of the polynomials should be specified in descending
+ exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``.
+ * ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described
+ in `ZerosPolesGain`.
+ * ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`.
+
+ x0 : array_like, optional
+ Initial state-vector. Defaults to zero.
+ t : array_like, optional
+ Time points. Computed if not given.
+ n : int, optional
+ The number of time points to compute (if `t` is not given).
+
+ Returns
+ -------
+ tout : ndarray
+ Time values for the output, as a 1-D array.
+ yout : tuple of ndarray
+ Impulse response of system. Each element of the tuple represents
+ the output of the system based on an impulse in each input.
+
+ See Also
+ --------
+ impulse, dstep, dlsim, cont2discrete
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ ...
+ >>> dt = 1 # sampling interval is one => time unit is sample number
+ >>> bb, aa = signal.butter(3, 0.25, fs=1/dt)
+ >>> t, y = signal.dimpulse((bb, aa, dt), n=25)
+ ...
+ >>> fig0, ax0 = plt.subplots()
+ >>> ax0.step(t, np.squeeze(y), '.-', where='post')
+ >>> ax0.set_title(r"Impulse Response of a $3^\text{rd}$ Order Butterworth Filter")
+ >>> ax0.set(xlabel='Sample number', ylabel='Amplitude')
+ >>> ax0.grid()
+ >>> plt.show()
+ """
+ # Convert system to dlti-StateSpace
+ if isinstance(system, dlti):
+ system = system._as_ss()
+ elif isinstance(system, lti):
+ raise AttributeError('dimpulse can only be used with discrete-time '
+ 'dlti systems.')
+ else:
+ system = dlti(*system[:-1], dt=system[-1])._as_ss()
+
+ # Default to 100 samples if unspecified
+ if n is None:
+ n = 100
+
+ # If time is not specified, use the number of samples
+ # and system dt
+ if t is None:
+ t = np.linspace(0, n * system.dt, n, endpoint=False)
+ else:
+ t = np.asarray(t)
+
+ # For each input, implement a step change
+ yout = None
+ for i in range(0, system.inputs):
+ u = np.zeros((t.shape[0], system.inputs))
+ u[0, i] = 1.0
+
+ one_output = dlsim(system, u, t=t, x0=x0)
+
+ if yout is None:
+ yout = (one_output[1],)
+ else:
+ yout = yout + (one_output[1],)
+
+ tout = one_output[0]
+
+ return tout, yout
+
+
+def dstep(system, x0=None, t=None, n=None):
+ r"""Step response of discrete-time system.
+
+ Parameters
+ ----------
+ system : dlti | tuple
+ An instance of the LTI class `dlti` or a tuple describing the system.
+ The number of elements in the tuple determine the interpretation. I.e.:
+
+ * ``system``: Instance of LTI class `dlti`. Note that derived instances, such
+ as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, are
+ allowed as well.
+ * ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`.
+ The coefficients of the polynomials should be specified in descending
+ exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``.
+ * ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described
+ in `ZerosPolesGain`.
+ * ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`.
+
+ x0 : array_like, optional
+ Initial state-vector. Defaults to zero.
+ t : array_like, optional
+ Time points. Computed if not given.
+ n : int, optional
+ The number of time points to compute (if `t` is not given).
+
+ Returns
+ -------
+ tout : ndarray
+ Output time points, as a 1-D array.
+ yout : tuple of ndarray
+ Step response of system. Each element of the tuple represents
+ the output of the system based on a step response to each input.
+
+ See Also
+ --------
+ step, dimpulse, dlsim, cont2discrete
+
+ Examples
+ --------
+ The following example illustrates how to create a digital Butterworth filer and
+ plot its step response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ ...
+ >>> dt = 1 # sampling interval is one => time unit is sample number
+ >>> bb, aa = signal.butter(3, 0.25, fs=1/dt)
+ >>> t, y = signal.dstep((bb, aa, dt), n=25)
+ ...
+ >>> fig0, ax0 = plt.subplots()
+ >>> ax0.step(t, np.squeeze(y), '.-', where='post')
+ >>> ax0.set_title(r"Step Response of a $3^\text{rd}$ Order Butterworth Filter")
+ >>> ax0.set(xlabel='Sample number', ylabel='Amplitude', ylim=(0, 1.1*np.max(y)))
+ >>> ax0.grid()
+ >>> plt.show()
+ """
+ # Convert system to dlti-StateSpace
+ if isinstance(system, dlti):
+ system = system._as_ss()
+ elif isinstance(system, lti):
+ raise AttributeError('dstep can only be used with discrete-time dlti '
+ 'systems.')
+ else:
+ system = dlti(*system[:-1], dt=system[-1])._as_ss()
+
+ # Default to 100 samples if unspecified
+ if n is None:
+ n = 100
+
+ # If time is not specified, use the number of samples
+ # and system dt
+ if t is None:
+ t = np.linspace(0, n * system.dt, n, endpoint=False)
+ else:
+ t = np.asarray(t)
+
+ # For each input, implement a step change
+ yout = None
+ for i in range(0, system.inputs):
+ u = np.zeros((t.shape[0], system.inputs))
+ u[:, i] = np.ones((t.shape[0],))
+
+ one_output = dlsim(system, u, t=t, x0=x0)
+
+ if yout is None:
+ yout = (one_output[1],)
+ else:
+ yout = yout + (one_output[1],)
+
+ tout = one_output[0]
+
+ return tout, yout
+
+
+def dfreqresp(system, w=None, n=10000, whole=False):
+ r"""
+ Calculate the frequency response of a discrete-time system.
+
+ Parameters
+ ----------
+ system : dlti | tuple
+ An instance of the LTI class `dlti` or a tuple describing the system.
+ The number of elements in the tuple determine the interpretation. I.e.:
+
+ * ``system``: Instance of LTI class `dlti`. Note that derived instances, such
+ as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, are
+ allowed as well.
+ * ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`.
+ The coefficients of the polynomials should be specified in descending
+ exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``.
+ * ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described
+ in `ZerosPolesGain`.
+ * ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`.
+
+ w : array_like, optional
+ Array of frequencies (in radians/sample). Magnitude and phase data is
+ calculated for every value in this array. If not given a reasonable
+ set will be calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+ whole : bool, optional
+ Normally, if 'w' is not given, frequencies are computed from 0 to the
+ Nyquist frequency, pi radians/sample (upper-half of unit-circle). If
+ `whole` is True, compute frequencies from 0 to 2*pi radians/sample.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Frequency array [radians/sample]
+ H : 1D ndarray
+ Array of complex magnitude values
+
+ Notes
+ -----
+ If (num, den) is passed in for ``system``, coefficients for both the
+ numerator and denominator should be specified in descending exponent
+ order (e.g. ``z^2 + 3z + 5`` would be represented as ``[1, 3, 5]``).
+
+ .. versionadded:: 0.18.0
+
+ Examples
+ --------
+ The following example generates the Nyquist plot of the transfer function
+ :math:`H(z) = \frac{1}{z^2 + 2z + 3}` with a sampling time of 0.05 seconds:
+
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> sys = signal.TransferFunction([1], [1, 2, 3], dt=0.05) # construct H(z)
+ >>> w, H = signal.dfreqresp(sys)
+ ...
+ >>> fig0, ax0 = plt.subplots()
+ >>> ax0.plot(H.real, H.imag, label=r"$H(z=e^{+j\omega})$")
+ >>> ax0.plot(H.real, -H.imag, label=r"$H(z=e^{-j\omega})$")
+ >>> ax0.set_title(r"Nyquist Plot of $H(z) = 1 / (z^2 + 2z + 3)$")
+ >>> ax0.set(xlabel=r"$\text{Re}\{z\}$", ylabel=r"$\text{Im}\{z\}$",
+ ... xlim=(-0.2, 0.65), aspect='equal')
+ >>> ax0.plot(H[0].real, H[0].imag, 'k.') # mark H(exp(1j*w[0]))
+ >>> ax0.text(0.2, 0, r"$H(e^{j0})$")
+ >>> ax0.grid(True)
+ >>> ax0.legend()
+ >>> plt.show()
+ """
+ if not isinstance(system, dlti):
+ if isinstance(system, lti):
+ raise AttributeError('dfreqresp can only be used with '
+ 'discrete-time systems.')
+
+ system = dlti(*system[:-1], dt=system[-1])
+
+ if isinstance(system, StateSpace):
+ # No SS->ZPK code exists right now, just SS->TF->ZPK
+ system = system._as_tf()
+
+ if not isinstance(system, TransferFunction | ZerosPolesGain):
+ raise ValueError('Unknown system type')
+
+ if system.inputs != 1 or system.outputs != 1:
+ raise ValueError("dfreqresp requires a SISO (single input, single "
+ "output) system.")
+
+ if w is not None:
+ worN = w
+ else:
+ worN = n
+
+ if isinstance(system, TransferFunction):
+ # Convert numerator and denominator from polynomials in the variable
+ # 'z' to polynomials in the variable 'z^-1', as freqz expects.
+ num, den = TransferFunction._z_to_zinv(system.num.ravel(), system.den)
+ w, h = freqz(num, den, worN=worN, whole=whole)
+
+ elif isinstance(system, ZerosPolesGain):
+ w, h = freqz_zpk(system.zeros, system.poles, system.gain, worN=worN,
+ whole=whole)
+
+ return w, h
+
+
+def dbode(system, w=None, n=100):
+ r"""Calculate Bode magnitude and phase data of a discrete-time system.
+
+ Parameters
+ ----------
+ system : dlti | tuple
+ An instance of the LTI class `dlti` or a tuple describing the system.
+ The number of elements in the tuple determine the interpretation. I.e.:
+
+ * ``system``: Instance of LTI class `dlti`. Note that derived instances, such
+ as instances of `TransferFunction`, `ZerosPolesGain`, or `StateSpace`, are
+ allowed as well.
+ * ``(num, den, dt)``: Rational polynomial as described in `TransferFunction`.
+ The coefficients of the polynomials should be specified in descending
+ exponent order, e.g., z² + 3z + 5 would be represented as ``[1, 3, 5]``.
+ * ``(zeros, poles, gain, dt)``: Zeros, poles, gain form as described
+ in `ZerosPolesGain`.
+ * ``(A, B, C, D, dt)``: State-space form as described in `StateSpace`.
+
+ w : array_like, optional
+ Array of frequencies normalized to the Nyquist frequency being π, i.e.,
+ having unit radiant / sample. Magnitude and phase data is calculated for every
+ value in this array. If not given, a reasonable set will be calculated.
+ n : int, optional
+ Number of frequency points to compute if `w` is not given. The `n`
+ frequencies are logarithmically spaced in an interval chosen to
+ include the influence of the poles and zeros of the system.
+
+ Returns
+ -------
+ w : 1D ndarray
+ Array of frequencies normalized to the Nyquist frequency being ``np.pi/dt``
+ with ``dt`` being the sampling interval of the `system` parameter.
+ The unit is rad/s assuming ``dt`` is in seconds.
+ mag : 1D ndarray
+ Magnitude array in dB
+ phase : 1D ndarray
+ Phase array in degrees
+
+ Notes
+ -----
+ This function is a convenience wrapper around `dfreqresp` for extracting
+ magnitude and phase from the calculated complex-valued amplitude of the
+ frequency response.
+
+ .. versionadded:: 0.18.0
+
+ See Also
+ --------
+ dfreqresp, dlti, TransferFunction, ZerosPolesGain, StateSpace
+
+
+ Examples
+ --------
+ The following example shows how to create a Bode plot of a 5-th order
+ Butterworth lowpass filter with a corner frequency of 100 Hz:
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy import signal
+ ...
+ >>> T = 1e-4 # sampling interval in s
+ >>> f_c, o = 1e2, 5 # corner frequency in Hz (i.e., -3 dB value) and filter order
+ >>> bb, aa = signal.butter(o, f_c, 'lowpass', fs=1/T)
+ ...
+ >>> w, mag, phase = signal.dbode((bb, aa, T))
+ >>> w /= 2*np.pi # convert unit of frequency into Hertz
+ ...
+ >>> fg, (ax0, ax1) = plt.subplots(2, 1, sharex='all', figsize=(5, 4),
+ ... tight_layout=True)
+ >>> ax0.set_title("Bode Plot of Butterworth Lowpass Filter " +
+ ... rf"($f_c={f_c:g}\,$Hz, order={o})")
+ >>> ax0.set_ylabel(r"Magnitude in dB")
+ >>> ax1.set(ylabel=r"Phase in Degrees",
+ ... xlabel="Frequency $f$ in Hertz", xlim=(w[1], w[-1]))
+ >>> ax0.semilogx(w, mag, 'C0-', label=r"$20\,\log_{10}|G(f)|$") # Magnitude plot
+ >>> ax1.semilogx(w, phase, 'C1-', label=r"$\angle G(f)$") # Phase plot
+ ...
+ >>> for ax_ in (ax0, ax1):
+ ... ax_.axvline(f_c, color='m', alpha=0.25, label=rf"${f_c=:g}\,$Hz")
+ ... ax_.grid(which='both', axis='x') # plot major & minor vertical grid lines
+ ... ax_.grid(which='major', axis='y')
+ ... ax_.legend()
+ >>> plt.show()
+ """
+ w, y = dfreqresp(system, w=w, n=n)
+
+ if isinstance(system, dlti):
+ dt = system.dt
+ else:
+ dt = system[-1]
+
+ mag = 20.0 * np.log10(abs(y))
+ phase = np.rad2deg(np.unwrap(np.angle(y)))
+
+ return w / dt, mag, phase
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_max_len_seq.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_max_len_seq.py
new file mode 100644
index 0000000000000000000000000000000000000000..4d64beaca86d1da50b563668679b6fc52c954ab0
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_max_len_seq.py
@@ -0,0 +1,139 @@
+# Author: Eric Larson
+# 2014
+
+"""Tools for MLS generation"""
+
+import numpy as np
+
+from ._max_len_seq_inner import _max_len_seq_inner
+
+__all__ = ['max_len_seq']
+
+
+# These are definitions of linear shift register taps for use in max_len_seq()
+_mls_taps = {2: [1], 3: [2], 4: [3], 5: [3], 6: [5], 7: [6], 8: [7, 6, 1],
+ 9: [5], 10: [7], 11: [9], 12: [11, 10, 4], 13: [12, 11, 8],
+ 14: [13, 12, 2], 15: [14], 16: [15, 13, 4], 17: [14],
+ 18: [11], 19: [18, 17, 14], 20: [17], 21: [19], 22: [21],
+ 23: [18], 24: [23, 22, 17], 25: [22], 26: [25, 24, 20],
+ 27: [26, 25, 22], 28: [25], 29: [27], 30: [29, 28, 7],
+ 31: [28], 32: [31, 30, 10]}
+
+def max_len_seq(nbits, state=None, length=None, taps=None):
+ """
+ Maximum length sequence (MLS) generator.
+
+ Parameters
+ ----------
+ nbits : int
+ Number of bits to use. Length of the resulting sequence will
+ be ``(2**nbits) - 1``. Note that generating long sequences
+ (e.g., greater than ``nbits == 16``) can take a long time.
+ state : array_like, optional
+ If array, must be of length ``nbits``, and will be cast to binary
+ (bool) representation. If None, a seed of ones will be used,
+ producing a repeatable representation. If ``state`` is all
+ zeros, an error is raised as this is invalid. Default: None.
+ length : int, optional
+ Number of samples to compute. If None, the entire length
+ ``(2**nbits) - 1`` is computed.
+ taps : array_like, optional
+ Polynomial taps to use (e.g., ``[7, 6, 1]`` for an 8-bit sequence).
+ If None, taps will be automatically selected (for up to
+ ``nbits == 32``).
+
+ Returns
+ -------
+ seq : array
+ Resulting MLS sequence of 0's and 1's.
+ state : array
+ The final state of the shift register.
+
+ Notes
+ -----
+ The algorithm for MLS generation is generically described in:
+
+ https://en.wikipedia.org/wiki/Maximum_length_sequence
+
+ The default values for taps are specifically taken from the first
+ option listed for each value of ``nbits`` in:
+
+ https://web.archive.org/web/20181001062252/http://www.newwaveinstruments.com/resources/articles/m_sequence_linear_feedback_shift_register_lfsr.htm
+
+ .. versionadded:: 0.15.0
+
+ Examples
+ --------
+ MLS uses binary convention:
+
+ >>> from scipy.signal import max_len_seq
+ >>> max_len_seq(4)[0]
+ array([1, 1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0, 0], dtype=int8)
+
+ MLS has a white spectrum (except for DC):
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from numpy.fft import fft, ifft, fftshift, fftfreq
+ >>> seq = max_len_seq(6)[0]*2-1 # +1 and -1
+ >>> spec = fft(seq)
+ >>> N = len(seq)
+ >>> plt.plot(fftshift(fftfreq(N)), fftshift(np.abs(spec)), '.-')
+ >>> plt.margins(0.1, 0.1)
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ Circular autocorrelation of MLS is an impulse:
+
+ >>> acorrcirc = ifft(spec * np.conj(spec)).real
+ >>> plt.figure()
+ >>> plt.plot(np.arange(-N/2+1, N/2+1), fftshift(acorrcirc), '.-')
+ >>> plt.margins(0.1, 0.1)
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ Linear autocorrelation of MLS is approximately an impulse:
+
+ >>> acorr = np.correlate(seq, seq, 'full')
+ >>> plt.figure()
+ >>> plt.plot(np.arange(-N+1, N), acorr, '.-')
+ >>> plt.margins(0.1, 0.1)
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ """
+ taps_dtype = np.int32 if np.intp().itemsize == 4 else np.int64
+ if taps is None:
+ if nbits not in _mls_taps:
+ known_taps = np.array(list(_mls_taps.keys()))
+ raise ValueError(f'nbits must be between {known_taps.min()} and '
+ f'{known_taps.max()} if taps is None')
+ taps = np.array(_mls_taps[nbits], taps_dtype)
+ else:
+ taps = np.unique(np.array(taps, taps_dtype))[::-1]
+ if np.any(taps < 0) or np.any(taps > nbits) or taps.size < 1:
+ raise ValueError('taps must be non-empty with values between '
+ 'zero and nbits (inclusive)')
+ taps = np.array(taps) # needed for Cython and Pythran
+ n_max = (2**nbits) - 1
+ if length is None:
+ length = n_max
+ else:
+ length = int(length)
+ if length < 0:
+ raise ValueError('length must be greater than or equal to 0')
+ # We use int8 instead of bool here because NumPy arrays of bools
+ # don't seem to work nicely with Cython
+ if state is None:
+ state = np.ones(nbits, dtype=np.int8, order='c')
+ else:
+ # makes a copy if need be, ensuring it's 0's and 1's
+ state = np.array(state, dtype=bool, order='c').astype(np.int8)
+ if state.ndim != 1 or state.size != nbits:
+ raise ValueError('state must be a 1-D array of size nbits')
+ if np.all(state == 0):
+ raise ValueError('state must not be all zeros')
+
+ seq = np.empty(length, dtype=np.int8, order='c')
+ state = _max_len_seq_inner(taps, state, nbits, length, seq)
+ return seq, state
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_max_len_seq_inner.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_max_len_seq_inner.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..eff71d342a65520c087a316b2c3baa718fbd9ae9
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_max_len_seq_inner.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_peak_finding.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_peak_finding.py
new file mode 100644
index 0000000000000000000000000000000000000000..ccbeca5b7a4839bbc28e9c1cfd1ebd1d028a82cf
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_peak_finding.py
@@ -0,0 +1,1310 @@
+"""
+Functions for identifying peaks in signals.
+"""
+import math
+import numpy as np
+
+from scipy.signal._wavelets import _cwt, _ricker
+from scipy.stats import scoreatpercentile
+
+from ._peak_finding_utils import (
+ _local_maxima_1d,
+ _select_by_peak_distance,
+ _peak_prominences,
+ _peak_widths
+)
+
+
+__all__ = ['argrelmin', 'argrelmax', 'argrelextrema', 'peak_prominences',
+ 'peak_widths', 'find_peaks', 'find_peaks_cwt']
+
+
+def _boolrelextrema(data, comparator, axis=0, order=1, mode='clip'):
+ """
+ Calculate the relative extrema of `data`.
+
+ Relative extrema are calculated by finding locations where
+ ``comparator(data[n], data[n+1:n+order+1])`` is True.
+
+ Parameters
+ ----------
+ data : ndarray
+ Array in which to find the relative extrema.
+ comparator : callable
+ Function to use to compare two data points.
+ Should take two arrays as arguments.
+ axis : int, optional
+ Axis over which to select from `data`. Default is 0.
+ order : int, optional
+ How many points on each side to use for the comparison
+ to consider ``comparator(n,n+x)`` to be True.
+ mode : str, optional
+ How the edges of the vector are treated. 'wrap' (wrap around) or
+ 'clip' (treat overflow as the same as the last (or first) element).
+ Default 'clip'. See numpy.take.
+
+ Returns
+ -------
+ extrema : ndarray
+ Boolean array of the same shape as `data` that is True at an extrema,
+ False otherwise.
+
+ See also
+ --------
+ argrelmax, argrelmin
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._peak_finding import _boolrelextrema
+ >>> testdata = np.array([1,2,3,2,1])
+ >>> _boolrelextrema(testdata, np.greater, axis=0)
+ array([False, False, True, False, False], dtype=bool)
+
+ """
+ if (int(order) != order) or (order < 1):
+ raise ValueError('Order must be an int >= 1')
+
+ datalen = data.shape[axis]
+ locs = np.arange(0, datalen)
+
+ results = np.ones(data.shape, dtype=bool)
+ main = data.take(locs, axis=axis, mode=mode)
+ for shift in range(1, order + 1):
+ plus = data.take(locs + shift, axis=axis, mode=mode)
+ minus = data.take(locs - shift, axis=axis, mode=mode)
+ results &= comparator(main, plus)
+ results &= comparator(main, minus)
+ if ~results.any():
+ return results
+ return results
+
+
+def argrelmin(data, axis=0, order=1, mode='clip'):
+ """
+ Calculate the relative minima of `data`.
+
+ Parameters
+ ----------
+ data : ndarray
+ Array in which to find the relative minima.
+ axis : int, optional
+ Axis over which to select from `data`. Default is 0.
+ order : int, optional
+ How many points on each side to use for the comparison
+ to consider ``comparator(n, n+x)`` to be True.
+ mode : str, optional
+ How the edges of the vector are treated.
+ Available options are 'wrap' (wrap around) or 'clip' (treat overflow
+ as the same as the last (or first) element).
+ Default 'clip'. See numpy.take.
+
+ Returns
+ -------
+ extrema : tuple of ndarrays
+ Indices of the minima in arrays of integers. ``extrema[k]`` is
+ the array of indices of axis `k` of `data`. Note that the
+ return value is a tuple even when `data` is 1-D.
+
+ See Also
+ --------
+ argrelextrema, argrelmax, find_peaks
+
+ Notes
+ -----
+ This function uses `argrelextrema` with np.less as comparator. Therefore, it
+ requires a strict inequality on both sides of a value to consider it a
+ minimum. This means flat minima (more than one sample wide) are not detected.
+ In case of 1-D `data` `find_peaks` can be used to detect all
+ local minima, including flat ones, by calling it with negated `data`.
+
+ .. versionadded:: 0.11.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import argrelmin
+ >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
+ >>> argrelmin(x)
+ (array([1, 5]),)
+ >>> y = np.array([[1, 2, 1, 2],
+ ... [2, 2, 0, 0],
+ ... [5, 3, 4, 4]])
+ ...
+ >>> argrelmin(y, axis=1)
+ (array([0, 2]), array([2, 1]))
+
+ """
+ return argrelextrema(data, np.less, axis, order, mode)
+
+
+def argrelmax(data, axis=0, order=1, mode='clip'):
+ """
+ Calculate the relative maxima of `data`.
+
+ Parameters
+ ----------
+ data : ndarray
+ Array in which to find the relative maxima.
+ axis : int, optional
+ Axis over which to select from `data`. Default is 0.
+ order : int, optional
+ How many points on each side to use for the comparison
+ to consider ``comparator(n, n+x)`` to be True.
+ mode : str, optional
+ How the edges of the vector are treated.
+ Available options are 'wrap' (wrap around) or 'clip' (treat overflow
+ as the same as the last (or first) element).
+ Default 'clip'. See `numpy.take`.
+
+ Returns
+ -------
+ extrema : tuple of ndarrays
+ Indices of the maxima in arrays of integers. ``extrema[k]`` is
+ the array of indices of axis `k` of `data`. Note that the
+ return value is a tuple even when `data` is 1-D.
+
+ See Also
+ --------
+ argrelextrema, argrelmin, find_peaks
+
+ Notes
+ -----
+ This function uses `argrelextrema` with np.greater as comparator. Therefore,
+ it requires a strict inequality on both sides of a value to consider it a
+ maximum. This means flat maxima (more than one sample wide) are not detected.
+ In case of 1-D `data` `find_peaks` can be used to detect all
+ local maxima, including flat ones.
+
+ .. versionadded:: 0.11.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import argrelmax
+ >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
+ >>> argrelmax(x)
+ (array([3, 6]),)
+ >>> y = np.array([[1, 2, 1, 2],
+ ... [2, 2, 0, 0],
+ ... [5, 3, 4, 4]])
+ ...
+ >>> argrelmax(y, axis=1)
+ (array([0]), array([1]))
+ """
+ return argrelextrema(data, np.greater, axis, order, mode)
+
+
+def argrelextrema(data, comparator, axis=0, order=1, mode='clip'):
+ """
+ Calculate the relative extrema of `data`.
+
+ Parameters
+ ----------
+ data : ndarray
+ Array in which to find the relative extrema.
+ comparator : callable
+ Function to use to compare two data points.
+ Should take two arrays as arguments.
+ axis : int, optional
+ Axis over which to select from `data`. Default is 0.
+ order : int, optional
+ How many points on each side to use for the comparison
+ to consider ``comparator(n, n+x)`` to be True.
+ mode : str, optional
+ How the edges of the vector are treated. 'wrap' (wrap around) or
+ 'clip' (treat overflow as the same as the last (or first) element).
+ Default is 'clip'. See `numpy.take`.
+
+ Returns
+ -------
+ extrema : tuple of ndarrays
+ Indices of the maxima in arrays of integers. ``extrema[k]`` is
+ the array of indices of axis `k` of `data`. Note that the
+ return value is a tuple even when `data` is 1-D.
+
+ See Also
+ --------
+ argrelmin, argrelmax
+
+ Notes
+ -----
+
+ .. versionadded:: 0.11.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import argrelextrema
+ >>> x = np.array([2, 1, 2, 3, 2, 0, 1, 0])
+ >>> argrelextrema(x, np.greater)
+ (array([3, 6]),)
+ >>> y = np.array([[1, 2, 1, 2],
+ ... [2, 2, 0, 0],
+ ... [5, 3, 4, 4]])
+ ...
+ >>> argrelextrema(y, np.less, axis=1)
+ (array([0, 2]), array([2, 1]))
+
+ """
+ results = _boolrelextrema(data, comparator,
+ axis, order, mode)
+ return np.nonzero(results)
+
+
+def _arg_x_as_expected(value):
+ """Ensure argument `x` is a 1-D C-contiguous array of dtype('float64').
+
+ Used in `find_peaks`, `peak_prominences` and `peak_widths` to make `x`
+ compatible with the signature of the wrapped Cython functions.
+
+ Returns
+ -------
+ value : ndarray
+ A 1-D C-contiguous array with dtype('float64').
+ """
+ value = np.asarray(value, order='C', dtype=np.float64)
+ if value.ndim != 1:
+ raise ValueError('`x` must be a 1-D array')
+ return value
+
+
+def _arg_peaks_as_expected(value):
+ """Ensure argument `peaks` is a 1-D C-contiguous array of dtype('intp').
+
+ Used in `peak_prominences` and `peak_widths` to make `peaks` compatible
+ with the signature of the wrapped Cython functions.
+
+ Returns
+ -------
+ value : ndarray
+ A 1-D C-contiguous array with dtype('intp').
+ """
+ value = np.asarray(value)
+ if value.size == 0:
+ # Empty arrays default to np.float64 but are valid input
+ value = np.array([], dtype=np.intp)
+ try:
+ # Safely convert to C-contiguous array of type np.intp
+ value = value.astype(np.intp, order='C', casting='safe',
+ subok=False, copy=False)
+ except TypeError as e:
+ raise TypeError("cannot safely cast `peaks` to dtype('intp')") from e
+ if value.ndim != 1:
+ raise ValueError('`peaks` must be a 1-D array')
+ return value
+
+
+def _arg_wlen_as_expected(value):
+ """Ensure argument `wlen` is of type `np.intp` and larger than 1.
+
+ Used in `peak_prominences` and `peak_widths`.
+
+ Returns
+ -------
+ value : np.intp
+ The original `value` rounded up to an integer or -1 if `value` was
+ None.
+ """
+ if value is None:
+ # _peak_prominences expects an intp; -1 signals that no value was
+ # supplied by the user
+ value = -1
+ elif 1 < value:
+ # Round up to a positive integer
+ if isinstance(value, float):
+ value = math.ceil(value)
+ value = np.intp(value)
+ else:
+ raise ValueError(f'`wlen` must be larger than 1, was {value}')
+ return value
+
+
+def peak_prominences(x, peaks, wlen=None):
+ """
+ Calculate the prominence of each peak in a signal.
+
+ The prominence of a peak measures how much a peak stands out from the
+ surrounding baseline of the signal and is defined as the vertical distance
+ between the peak and its lowest contour line.
+
+ Parameters
+ ----------
+ x : sequence
+ A signal with peaks.
+ peaks : sequence
+ Indices of peaks in `x`.
+ wlen : int, optional
+ A window length in samples that optionally limits the evaluated area for
+ each peak to a subset of `x`. The peak is always placed in the middle of
+ the window therefore the given length is rounded up to the next odd
+ integer. This parameter can speed up the calculation (see Notes).
+
+ Returns
+ -------
+ prominences : ndarray
+ The calculated prominences for each peak in `peaks`.
+ left_bases, right_bases : ndarray
+ The peaks' bases as indices in `x` to the left and right of each peak.
+ The higher base of each pair is a peak's lowest contour line.
+
+ Raises
+ ------
+ ValueError
+ If a value in `peaks` is an invalid index for `x`.
+
+ Warns
+ -----
+ PeakPropertyWarning
+ For indices in `peaks` that don't point to valid local maxima in `x`,
+ the returned prominence will be 0 and this warning is raised. This
+ also happens if `wlen` is smaller than the plateau size of a peak.
+
+ Warnings
+ --------
+ This function may return unexpected results for data containing NaNs. To
+ avoid this, NaNs should either be removed or replaced.
+
+ See Also
+ --------
+ find_peaks
+ Find peaks inside a signal based on peak properties.
+ peak_widths
+ Calculate the width of peaks.
+
+ Notes
+ -----
+ Strategy to compute a peak's prominence:
+
+ 1. Extend a horizontal line from the current peak to the left and right
+ until the line either reaches the window border (see `wlen`) or
+ intersects the signal again at the slope of a higher peak. An
+ intersection with a peak of the same height is ignored.
+ 2. On each side find the minimal signal value within the interval defined
+ above. These points are the peak's bases.
+ 3. The higher one of the two bases marks the peak's lowest contour line. The
+ prominence can then be calculated as the vertical difference between the
+ peaks height itself and its lowest contour line.
+
+ Searching for the peak's bases can be slow for large `x` with periodic
+ behavior because large chunks or even the full signal need to be evaluated
+ for the first algorithmic step. This evaluation area can be limited with the
+ parameter `wlen` which restricts the algorithm to a window around the
+ current peak and can shorten the calculation time if the window length is
+ short in relation to `x`.
+ However, this may stop the algorithm from finding the true global contour
+ line if the peak's true bases are outside this window. Instead, a higher
+ contour line is found within the restricted window leading to a smaller
+ calculated prominence. In practice, this is only relevant for the highest set
+ of peaks in `x`. This behavior may even be used intentionally to calculate
+ "local" prominences.
+
+ .. versionadded:: 1.1.0
+
+ References
+ ----------
+ .. [1] Wikipedia Article for Topographic Prominence:
+ https://en.wikipedia.org/wiki/Topographic_prominence
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import find_peaks, peak_prominences
+ >>> import matplotlib.pyplot as plt
+
+ Create a test signal with two overlaid harmonics
+
+ >>> x = np.linspace(0, 6 * np.pi, 1000)
+ >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x)
+
+ Find all peaks and calculate prominences
+
+ >>> peaks, _ = find_peaks(x)
+ >>> prominences = peak_prominences(x, peaks)[0]
+ >>> prominences
+ array([1.24159486, 0.47840168, 0.28470524, 3.10716793, 0.284603 ,
+ 0.47822491, 2.48340261, 0.47822491])
+
+ Calculate the height of each peak's contour line and plot the results
+
+ >>> contour_heights = x[peaks] - prominences
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.vlines(x=peaks, ymin=contour_heights, ymax=x[peaks])
+ >>> plt.show()
+
+ Let's evaluate a second example that demonstrates several edge cases for
+ one peak at index 5.
+
+ >>> x = np.array([0, 1, 0, 3, 1, 3, 0, 4, 0])
+ >>> peaks = np.array([5])
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.show()
+ >>> peak_prominences(x, peaks) # -> (prominences, left_bases, right_bases)
+ (array([3.]), array([2]), array([6]))
+
+ Note how the peak at index 3 of the same height is not considered as a
+ border while searching for the left base. Instead, two minima at 0 and 2
+ are found in which case the one closer to the evaluated peak is always
+ chosen. On the right side, however, the base must be placed at 6 because the
+ higher peak represents the right border to the evaluated area.
+
+ >>> peak_prominences(x, peaks, wlen=3.1)
+ (array([2.]), array([4]), array([6]))
+
+ Here, we restricted the algorithm to a window from 3 to 7 (the length is 5
+ samples because `wlen` was rounded up to the next odd integer). Thus, the
+ only two candidates in the evaluated area are the two neighboring samples
+ and a smaller prominence is calculated.
+ """
+ x = _arg_x_as_expected(x)
+ peaks = _arg_peaks_as_expected(peaks)
+ wlen = _arg_wlen_as_expected(wlen)
+ return _peak_prominences(x, peaks, wlen)
+
+
+def peak_widths(x, peaks, rel_height=0.5, prominence_data=None, wlen=None):
+ """
+ Calculate the width of each peak in a signal.
+
+ This function calculates the width of a peak in samples at a relative
+ distance to the peak's height and prominence.
+
+ Parameters
+ ----------
+ x : sequence
+ A signal with peaks.
+ peaks : sequence
+ Indices of peaks in `x`.
+ rel_height : float, optional
+ Chooses the relative height at which the peak width is measured as a
+ percentage of its prominence. 1.0 calculates the width of the peak at
+ its lowest contour line while 0.5 evaluates at half the prominence
+ height. Must be at least 0. See notes for further explanation.
+ prominence_data : tuple, optional
+ A tuple of three arrays matching the output of `peak_prominences` when
+ called with the same arguments `x` and `peaks`. This data are calculated
+ internally if not provided.
+ wlen : int, optional
+ A window length in samples passed to `peak_prominences` as an optional
+ argument for internal calculation of `prominence_data`. This argument
+ is ignored if `prominence_data` is given.
+
+ Returns
+ -------
+ widths : ndarray
+ The widths for each peak in samples.
+ width_heights : ndarray
+ The height of the contour lines at which the `widths` where evaluated.
+ left_ips, right_ips : ndarray
+ Interpolated positions of left and right intersection points of a
+ horizontal line at the respective evaluation height.
+
+ Raises
+ ------
+ ValueError
+ If `prominence_data` is supplied but doesn't satisfy the condition
+ ``0 <= left_base <= peak <= right_base < x.shape[0]`` for each peak,
+ has the wrong dtype, is not C-contiguous or does not have the same
+ shape.
+
+ Warns
+ -----
+ PeakPropertyWarning
+ Raised if any calculated width is 0. This may stem from the supplied
+ `prominence_data` or if `rel_height` is set to 0.
+
+ Warnings
+ --------
+ This function may return unexpected results for data containing NaNs. To
+ avoid this, NaNs should either be removed or replaced.
+
+ See Also
+ --------
+ find_peaks
+ Find peaks inside a signal based on peak properties.
+ peak_prominences
+ Calculate the prominence of peaks.
+
+ Notes
+ -----
+ The basic algorithm to calculate a peak's width is as follows:
+
+ * Calculate the evaluation height :math:`h_{eval}` with the formula
+ :math:`h_{eval} = h_{Peak} - P \\cdot R`, where :math:`h_{Peak}` is the
+ height of the peak itself, :math:`P` is the peak's prominence and
+ :math:`R` a positive ratio specified with the argument `rel_height`.
+ * Draw a horizontal line at the evaluation height to both sides, starting at
+ the peak's current vertical position until the lines either intersect a
+ slope, the signal border or cross the vertical position of the peak's
+ base (see `peak_prominences` for an definition). For the first case,
+ intersection with the signal, the true intersection point is estimated
+ with linear interpolation.
+ * Calculate the width as the horizontal distance between the chosen
+ endpoints on both sides. As a consequence of this the maximal possible
+ width for each peak is the horizontal distance between its bases.
+
+ As shown above to calculate a peak's width its prominence and bases must be
+ known. You can supply these yourself with the argument `prominence_data`.
+ Otherwise, they are internally calculated (see `peak_prominences`).
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import chirp, find_peaks, peak_widths
+ >>> import matplotlib.pyplot as plt
+
+ Create a test signal with two overlaid harmonics
+
+ >>> x = np.linspace(0, 6 * np.pi, 1000)
+ >>> x = np.sin(x) + 0.6 * np.sin(2.6 * x)
+
+ Find all peaks and calculate their widths at the relative height of 0.5
+ (contour line at half the prominence height) and 1 (at the lowest contour
+ line at full prominence height).
+
+ >>> peaks, _ = find_peaks(x)
+ >>> results_half = peak_widths(x, peaks, rel_height=0.5)
+ >>> results_half[0] # widths
+ array([ 64.25172825, 41.29465463, 35.46943289, 104.71586081,
+ 35.46729324, 41.30429622, 181.93835853, 45.37078546])
+ >>> results_full = peak_widths(x, peaks, rel_height=1)
+ >>> results_full[0] # widths
+ array([181.9396084 , 72.99284945, 61.28657872, 373.84622694,
+ 61.78404617, 72.48822812, 253.09161876, 79.36860878])
+
+ Plot signal, peaks and contour lines at which the widths where calculated
+
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.hlines(*results_half[1:], color="C2")
+ >>> plt.hlines(*results_full[1:], color="C3")
+ >>> plt.show()
+ """
+ x = _arg_x_as_expected(x)
+ peaks = _arg_peaks_as_expected(peaks)
+ if prominence_data is None:
+ # Calculate prominence if not supplied and use wlen if supplied.
+ wlen = _arg_wlen_as_expected(wlen)
+ prominence_data = _peak_prominences(x, peaks, wlen)
+ return _peak_widths(x, peaks, rel_height, *prominence_data)
+
+
+def _unpack_condition_args(interval, x, peaks):
+ """
+ Parse condition arguments for `find_peaks`.
+
+ Parameters
+ ----------
+ interval : number or ndarray or sequence
+ Either a number or ndarray or a 2-element sequence of the former. The
+ first value is always interpreted as `imin` and the second, if supplied,
+ as `imax`.
+ x : ndarray
+ The signal with `peaks`.
+ peaks : ndarray
+ An array with indices used to reduce `imin` and / or `imax` if those are
+ arrays.
+
+ Returns
+ -------
+ imin, imax : number or ndarray or None
+ Minimal and maximal value in `argument`.
+
+ Raises
+ ------
+ ValueError :
+ If interval border is given as array and its size does not match the size
+ of `x`.
+
+ Notes
+ -----
+
+ .. versionadded:: 1.1.0
+ """
+ try:
+ imin, imax = interval
+ except (TypeError, ValueError):
+ imin, imax = (interval, None)
+
+ # Reduce arrays if arrays
+ if isinstance(imin, np.ndarray):
+ if imin.size != x.size:
+ raise ValueError('array size of lower interval border must match x')
+ imin = imin[peaks]
+ if isinstance(imax, np.ndarray):
+ if imax.size != x.size:
+ raise ValueError('array size of upper interval border must match x')
+ imax = imax[peaks]
+
+ return imin, imax
+
+
+def _select_by_property(peak_properties, pmin, pmax):
+ """
+ Evaluate where the generic property of peaks confirms to an interval.
+
+ Parameters
+ ----------
+ peak_properties : ndarray
+ An array with properties for each peak.
+ pmin : None or number or ndarray
+ Lower interval boundary for `peak_properties`. ``None`` is interpreted as
+ an open border.
+ pmax : None or number or ndarray
+ Upper interval boundary for `peak_properties`. ``None`` is interpreted as
+ an open border.
+
+ Returns
+ -------
+ keep : bool
+ A boolean mask evaluating to true where `peak_properties` confirms to the
+ interval.
+
+ See Also
+ --------
+ find_peaks
+
+ Notes
+ -----
+
+ .. versionadded:: 1.1.0
+ """
+ keep = np.ones(peak_properties.size, dtype=bool)
+ if pmin is not None:
+ keep &= (pmin <= peak_properties)
+ if pmax is not None:
+ keep &= (peak_properties <= pmax)
+ return keep
+
+
+def _select_by_peak_threshold(x, peaks, tmin, tmax):
+ """
+ Evaluate which peaks fulfill the threshold condition.
+
+ Parameters
+ ----------
+ x : ndarray
+ A 1-D array which is indexable by `peaks`.
+ peaks : ndarray
+ Indices of peaks in `x`.
+ tmin, tmax : scalar or ndarray or None
+ Minimal and / or maximal required thresholds. If supplied as ndarrays
+ their size must match `peaks`. ``None`` is interpreted as an open
+ border.
+
+ Returns
+ -------
+ keep : bool
+ A boolean mask evaluating to true where `peaks` fulfill the threshold
+ condition.
+ left_thresholds, right_thresholds : ndarray
+ Array matching `peak` containing the thresholds of each peak on
+ both sides.
+
+ Notes
+ -----
+
+ .. versionadded:: 1.1.0
+ """
+ # Stack thresholds on both sides to make min / max operations easier:
+ # tmin is compared with the smaller, and tmax with the greater threshold to
+ # each peak's side
+ stacked_thresholds = np.vstack([x[peaks] - x[peaks - 1],
+ x[peaks] - x[peaks + 1]])
+ keep = np.ones(peaks.size, dtype=bool)
+ if tmin is not None:
+ min_thresholds = np.min(stacked_thresholds, axis=0)
+ keep &= (tmin <= min_thresholds)
+ if tmax is not None:
+ max_thresholds = np.max(stacked_thresholds, axis=0)
+ keep &= (max_thresholds <= tmax)
+
+ return keep, stacked_thresholds[0], stacked_thresholds[1]
+
+
+def find_peaks(x, height=None, threshold=None, distance=None,
+ prominence=None, width=None, wlen=None, rel_height=0.5,
+ plateau_size=None):
+ """
+ Find peaks inside a signal based on peak properties.
+
+ This function takes a 1-D array and finds all local maxima by
+ simple comparison of neighboring values. Optionally, a subset of these
+ peaks can be selected by specifying conditions for a peak's properties.
+
+ Parameters
+ ----------
+ x : sequence
+ A signal with peaks.
+ height : number or ndarray or sequence, optional
+ Required height of peaks. Either a number, ``None``, an array matching
+ `x` or a 2-element sequence of the former. The first element is
+ always interpreted as the minimal and the second, if supplied, as the
+ maximal required height.
+ threshold : number or ndarray or sequence, optional
+ Required threshold of peaks, the vertical distance to its neighboring
+ samples. Either a number, ``None``, an array matching `x` or a
+ 2-element sequence of the former. The first element is always
+ interpreted as the minimal and the second, if supplied, as the maximal
+ required threshold.
+ distance : number, optional
+ Required minimal horizontal distance (>= 1) in samples between
+ neighbouring peaks. Smaller peaks are removed first until the condition
+ is fulfilled for all remaining peaks.
+ prominence : number or ndarray or sequence, optional
+ Required prominence of peaks. Either a number, ``None``, an array
+ matching `x` or a 2-element sequence of the former. The first
+ element is always interpreted as the minimal and the second, if
+ supplied, as the maximal required prominence.
+ width : number or ndarray or sequence, optional
+ Required width of peaks in samples. Either a number, ``None``, an array
+ matching `x` or a 2-element sequence of the former. The first
+ element is always interpreted as the minimal and the second, if
+ supplied, as the maximal required width.
+ wlen : int, optional
+ Used for calculation of the peaks prominences, thus it is only used if
+ one of the arguments `prominence` or `width` is given. See argument
+ `wlen` in `peak_prominences` for a full description of its effects.
+ rel_height : float, optional
+ Used for calculation of the peaks width, thus it is only used if `width`
+ is given. See argument `rel_height` in `peak_widths` for a full
+ description of its effects.
+ plateau_size : number or ndarray or sequence, optional
+ Required size of the flat top of peaks in samples. Either a number,
+ ``None``, an array matching `x` or a 2-element sequence of the former.
+ The first element is always interpreted as the minimal and the second,
+ if supplied as the maximal required plateau size.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ peaks : ndarray
+ Indices of peaks in `x` that satisfy all given conditions.
+ properties : dict
+ A dictionary containing properties of the returned peaks which were
+ calculated as intermediate results during evaluation of the specified
+ conditions:
+
+ * 'peak_heights'
+ If `height` is given, the height of each peak in `x`.
+ * 'left_thresholds', 'right_thresholds'
+ If `threshold` is given, these keys contain a peaks vertical
+ distance to its neighbouring samples.
+ * 'prominences', 'right_bases', 'left_bases'
+ If `prominence` is given, these keys are accessible. See
+ `peak_prominences` for a description of their content.
+ * 'widths', 'width_heights', 'left_ips', 'right_ips'
+ If `width` is given, these keys are accessible. See `peak_widths`
+ for a description of their content.
+ * 'plateau_sizes', left_edges', 'right_edges'
+ If `plateau_size` is given, these keys are accessible and contain
+ the indices of a peak's edges (edges are still part of the
+ plateau) and the calculated plateau sizes.
+
+ .. versionadded:: 1.2.0
+
+ To calculate and return properties without excluding peaks, provide the
+ open interval ``(None, None)`` as a value to the appropriate argument
+ (excluding `distance`).
+
+ Warns
+ -----
+ PeakPropertyWarning
+ Raised if a peak's properties have unexpected values (see
+ `peak_prominences` and `peak_widths`).
+
+ Warnings
+ --------
+ This function may return unexpected results for data containing NaNs. To
+ avoid this, NaNs should either be removed or replaced.
+
+ See Also
+ --------
+ find_peaks_cwt
+ Find peaks using the wavelet transformation.
+ peak_prominences
+ Directly calculate the prominence of peaks.
+ peak_widths
+ Directly calculate the width of peaks.
+
+ Notes
+ -----
+ In the context of this function, a peak or local maximum is defined as any
+ sample whose two direct neighbours have a smaller amplitude. For flat peaks
+ (more than one sample of equal amplitude wide) the index of the middle
+ sample is returned (rounded down in case the number of samples is even).
+ For noisy signals the peak locations can be off because the noise might
+ change the position of local maxima. In those cases consider smoothing the
+ signal before searching for peaks or use other peak finding and fitting
+ methods (like `find_peaks_cwt`).
+
+ Some additional comments on specifying conditions:
+
+ * Almost all conditions (excluding `distance`) can be given as half-open or
+ closed intervals, e.g., ``1`` or ``(1, None)`` defines the half-open
+ interval :math:`[1, \\infty]` while ``(None, 1)`` defines the interval
+ :math:`[-\\infty, 1]`. The open interval ``(None, None)`` can be specified
+ as well, which returns the matching properties without exclusion of peaks.
+ * The border is always included in the interval used to select valid peaks.
+ * For several conditions the interval borders can be specified with
+ arrays matching `x` in shape which enables dynamic constrains based on
+ the sample position.
+ * The conditions are evaluated in the following order: `plateau_size`,
+ `height`, `threshold`, `distance`, `prominence`, `width`. In most cases
+ this order is the fastest one because faster operations are applied first
+ to reduce the number of peaks that need to be evaluated later.
+ * While indices in `peaks` are guaranteed to be at least `distance` samples
+ apart, edges of flat peaks may be closer than the allowed `distance`.
+ * Use `wlen` to reduce the time it takes to evaluate the conditions for
+ `prominence` or `width` if `x` is large or has many local maxima
+ (see `peak_prominences`).
+
+ .. versionadded:: 1.1.0
+
+ Examples
+ --------
+ To demonstrate this function's usage we use a signal `x` supplied with
+ SciPy (see `scipy.datasets.electrocardiogram`). Let's find all peaks (local
+ maxima) in `x` whose amplitude lies above 0.
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.datasets import electrocardiogram
+ >>> from scipy.signal import find_peaks
+ >>> x = electrocardiogram()[2000:4000]
+ >>> peaks, _ = find_peaks(x, height=0)
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.plot(np.zeros_like(x), "--", color="gray")
+ >>> plt.show()
+
+ We can select peaks below 0 with ``height=(None, 0)`` or use arrays matching
+ `x` in size to reflect a changing condition for different parts of the
+ signal.
+
+ >>> border = np.sin(np.linspace(0, 3 * np.pi, x.size))
+ >>> peaks, _ = find_peaks(x, height=(-border, border))
+ >>> plt.plot(x)
+ >>> plt.plot(-border, "--", color="gray")
+ >>> plt.plot(border, ":", color="gray")
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.show()
+
+ Another useful condition for periodic signals can be given with the
+ `distance` argument. In this case, we can easily select the positions of
+ QRS complexes within the electrocardiogram (ECG) by demanding a distance of
+ at least 150 samples.
+
+ >>> peaks, _ = find_peaks(x, distance=150)
+ >>> np.diff(peaks)
+ array([186, 180, 177, 171, 177, 169, 167, 164, 158, 162, 172])
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.show()
+
+ Especially for noisy signals peaks can be easily grouped by their
+ prominence (see `peak_prominences`). E.g., we can select all peaks except
+ for the mentioned QRS complexes by limiting the allowed prominence to 0.6.
+
+ >>> peaks, properties = find_peaks(x, prominence=(None, 0.6))
+ >>> properties["prominences"].max()
+ 0.5049999999999999
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.show()
+
+ And, finally, let's examine a different section of the ECG which contains
+ beat forms of different shape. To select only the atypical heart beats, we
+ combine two conditions: a minimal prominence of 1 and width of at least 20
+ samples.
+
+ >>> x = electrocardiogram()[17000:18000]
+ >>> peaks, properties = find_peaks(x, prominence=1, width=20)
+ >>> properties["prominences"], properties["widths"]
+ (array([1.495, 2.3 ]), array([36.93773946, 39.32723577]))
+ >>> plt.plot(x)
+ >>> plt.plot(peaks, x[peaks], "x")
+ >>> plt.vlines(x=peaks, ymin=x[peaks] - properties["prominences"],
+ ... ymax = x[peaks], color = "C1")
+ >>> plt.hlines(y=properties["width_heights"], xmin=properties["left_ips"],
+ ... xmax=properties["right_ips"], color = "C1")
+ >>> plt.show()
+ """
+ # _argmaxima1d expects array of dtype 'float64'
+ x = _arg_x_as_expected(x)
+ if distance is not None and distance < 1:
+ raise ValueError('`distance` must be greater or equal to 1')
+
+ peaks, left_edges, right_edges = _local_maxima_1d(x)
+ properties = {}
+
+ if plateau_size is not None:
+ # Evaluate plateau size
+ plateau_sizes = right_edges - left_edges + 1
+ pmin, pmax = _unpack_condition_args(plateau_size, x, peaks)
+ keep = _select_by_property(plateau_sizes, pmin, pmax)
+ peaks = peaks[keep]
+ properties["plateau_sizes"] = plateau_sizes
+ properties["left_edges"] = left_edges
+ properties["right_edges"] = right_edges
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ if height is not None:
+ # Evaluate height condition
+ peak_heights = x[peaks]
+ hmin, hmax = _unpack_condition_args(height, x, peaks)
+ keep = _select_by_property(peak_heights, hmin, hmax)
+ peaks = peaks[keep]
+ properties["peak_heights"] = peak_heights
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ if threshold is not None:
+ # Evaluate threshold condition
+ tmin, tmax = _unpack_condition_args(threshold, x, peaks)
+ keep, left_thresholds, right_thresholds = _select_by_peak_threshold(
+ x, peaks, tmin, tmax)
+ peaks = peaks[keep]
+ properties["left_thresholds"] = left_thresholds
+ properties["right_thresholds"] = right_thresholds
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ if distance is not None:
+ # Evaluate distance condition
+ keep = _select_by_peak_distance(peaks, x[peaks], distance)
+ peaks = peaks[keep]
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ if prominence is not None or width is not None:
+ # Calculate prominence (required for both conditions)
+ wlen = _arg_wlen_as_expected(wlen)
+ properties.update(zip(
+ ['prominences', 'left_bases', 'right_bases'],
+ _peak_prominences(x, peaks, wlen=wlen)
+ ))
+
+ if prominence is not None:
+ # Evaluate prominence condition
+ pmin, pmax = _unpack_condition_args(prominence, x, peaks)
+ keep = _select_by_property(properties['prominences'], pmin, pmax)
+ peaks = peaks[keep]
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ if width is not None:
+ # Calculate widths
+ properties.update(zip(
+ ['widths', 'width_heights', 'left_ips', 'right_ips'],
+ _peak_widths(x, peaks, rel_height, properties['prominences'],
+ properties['left_bases'], properties['right_bases'])
+ ))
+ # Evaluate width condition
+ wmin, wmax = _unpack_condition_args(width, x, peaks)
+ keep = _select_by_property(properties['widths'], wmin, wmax)
+ peaks = peaks[keep]
+ properties = {key: array[keep] for key, array in properties.items()}
+
+ return peaks, properties
+
+
+def _identify_ridge_lines(matr, max_distances, gap_thresh):
+ """
+ Identify ridges in the 2-D matrix.
+
+ Expect that the width of the wavelet feature increases with increasing row
+ number.
+
+ Parameters
+ ----------
+ matr : 2-D ndarray
+ Matrix in which to identify ridge lines.
+ max_distances : 1-D sequence
+ At each row, a ridge line is only connected
+ if the relative max at row[n] is within
+ `max_distances`[n] from the relative max at row[n+1].
+ gap_thresh : int
+ If a relative maximum is not found within `max_distances`,
+ there will be a gap. A ridge line is discontinued if
+ there are more than `gap_thresh` points without connecting
+ a new relative maximum.
+
+ Returns
+ -------
+ ridge_lines : tuple
+ Tuple of 2 1-D sequences. `ridge_lines`[ii][0] are the rows of the
+ ii-th ridge-line, `ridge_lines`[ii][1] are the columns. Empty if none
+ found. Each ridge-line will be sorted by row (increasing), but the
+ order of the ridge lines is not specified.
+
+ References
+ ----------
+ .. [1] Bioinformatics (2006) 22 (17): 2059-2065.
+ :doi:`10.1093/bioinformatics/btl355`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal._peak_finding import _identify_ridge_lines
+ >>> rng = np.random.default_rng()
+ >>> data = rng.random((5,5))
+ >>> max_dist = 3
+ >>> max_distances = np.full(20, max_dist)
+ >>> ridge_lines = _identify_ridge_lines(data, max_distances, 1)
+
+ Notes
+ -----
+ This function is intended to be used in conjunction with `cwt`
+ as part of `find_peaks_cwt`.
+
+ """
+ if len(max_distances) < matr.shape[0]:
+ raise ValueError('Max_distances must have at least as many rows '
+ 'as matr')
+
+ all_max_cols = _boolrelextrema(matr, np.greater, axis=1, order=1)
+ # Highest row for which there are any relative maxima
+ has_relmax = np.nonzero(all_max_cols.any(axis=1))[0]
+ if len(has_relmax) == 0:
+ return []
+ start_row = has_relmax[-1]
+ # Each ridge line is a 3-tuple:
+ # rows, cols,Gap number
+ ridge_lines = [[[start_row],
+ [col],
+ 0] for col in np.nonzero(all_max_cols[start_row])[0]]
+ final_lines = []
+ rows = np.arange(start_row - 1, -1, -1)
+ cols = np.arange(0, matr.shape[1])
+ for row in rows:
+ this_max_cols = cols[all_max_cols[row]]
+
+ # Increment gap number of each line,
+ # set it to zero later if appropriate
+ for line in ridge_lines:
+ line[2] += 1
+
+ # XXX These should always be all_max_cols[row]
+ # But the order might be different. Might be an efficiency gain
+ # to make sure the order is the same and avoid this iteration
+ prev_ridge_cols = np.array([line[1][-1] for line in ridge_lines])
+ # Look through every relative maximum found at current row
+ # Attempt to connect them with existing ridge lines.
+ for ind, col in enumerate(this_max_cols):
+ # If there is a previous ridge line within
+ # the max_distance to connect to, do so.
+ # Otherwise start a new one.
+ line = None
+ if len(prev_ridge_cols) > 0:
+ diffs = np.abs(col - prev_ridge_cols)
+ closest = np.argmin(diffs)
+ if diffs[closest] <= max_distances[row]:
+ line = ridge_lines[closest]
+ if line is not None:
+ # Found a point close enough, extend current ridge line
+ line[1].append(col)
+ line[0].append(row)
+ line[2] = 0
+ else:
+ new_line = [[row],
+ [col],
+ 0]
+ ridge_lines.append(new_line)
+
+ # Remove the ridge lines with gap_number too high
+ # XXX Modifying a list while iterating over it.
+ # Should be safe, since we iterate backwards, but
+ # still tacky.
+ for ind in range(len(ridge_lines) - 1, -1, -1):
+ line = ridge_lines[ind]
+ if line[2] > gap_thresh:
+ final_lines.append(line)
+ del ridge_lines[ind]
+
+ out_lines = []
+ for line in (final_lines + ridge_lines):
+ sortargs = np.array(np.argsort(line[0]))
+ rows, cols = np.zeros_like(sortargs), np.zeros_like(sortargs)
+ rows[sortargs] = line[0]
+ cols[sortargs] = line[1]
+ out_lines.append([rows, cols])
+
+ return out_lines
+
+
+def _filter_ridge_lines(cwt, ridge_lines, window_size=None, min_length=None,
+ min_snr=1, noise_perc=10):
+ """
+ Filter ridge lines according to prescribed criteria. Intended
+ to be used for finding relative maxima.
+
+ Parameters
+ ----------
+ cwt : 2-D ndarray
+ Continuous wavelet transform from which the `ridge_lines` were defined.
+ ridge_lines : 1-D sequence
+ Each element should contain 2 sequences, the rows and columns
+ of the ridge line (respectively).
+ window_size : int, optional
+ Size of window to use to calculate noise floor.
+ Default is ``cwt.shape[1] / 20``.
+ min_length : int, optional
+ Minimum length a ridge line needs to be acceptable.
+ Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths.
+ min_snr : float, optional
+ Minimum SNR ratio. Default 1. The signal is the value of
+ the cwt matrix at the shortest length scale (``cwt[0, loc]``), the
+ noise is the `noise_perc`\\ th percentile of datapoints contained within a
+ window of `window_size` around ``cwt[0, loc]``.
+ noise_perc : float, optional
+ When calculating the noise floor, percentile of data points
+ examined below which to consider noise. Calculated using
+ scipy.stats.scoreatpercentile.
+
+ References
+ ----------
+ .. [1] Bioinformatics (2006) 22 (17): 2059-2065.
+ :doi:`10.1093/bioinformatics/btl355`
+
+ """
+ num_points = cwt.shape[1]
+ if min_length is None:
+ min_length = np.ceil(cwt.shape[0] / 4)
+ if window_size is None:
+ window_size = np.ceil(num_points / 20)
+
+ window_size = int(window_size)
+ hf_window, odd = divmod(window_size, 2)
+
+ # Filter based on SNR
+ row_one = cwt[0, :]
+ noises = np.empty_like(row_one)
+ for ind, val in enumerate(row_one):
+ window_start = max(ind - hf_window, 0)
+ window_end = min(ind + hf_window + odd, num_points)
+ noises[ind] = scoreatpercentile(row_one[window_start:window_end],
+ per=noise_perc)
+
+ def filt_func(line):
+ if len(line[0]) < min_length:
+ return False
+ snr = abs(cwt[line[0][0], line[1][0]] / noises[line[1][0]])
+ if snr < min_snr:
+ return False
+ return True
+
+ return list(filter(filt_func, ridge_lines))
+
+
+def find_peaks_cwt(vector, widths, wavelet=None, max_distances=None,
+ gap_thresh=None, min_length=None,
+ min_snr=1, noise_perc=10, window_size=None):
+ """
+ Find peaks in a 1-D array with wavelet transformation.
+
+ The general approach is to smooth `vector` by convolving it with
+ `wavelet(width)` for each width in `widths`. Relative maxima which
+ appear at enough length scales, and with sufficiently high SNR, are
+ accepted.
+
+ Parameters
+ ----------
+ vector : ndarray
+ 1-D array in which to find the peaks.
+ widths : float or sequence
+ Single width or 1-D array-like of widths to use for calculating
+ the CWT matrix. In general,
+ this range should cover the expected width of peaks of interest.
+ wavelet : callable, optional
+ Should take two parameters and return a 1-D array to convolve
+ with `vector`. The first parameter determines the number of points
+ of the returned wavelet array, the second parameter is the scale
+ (`width`) of the wavelet. Should be normalized and symmetric.
+ Default is the ricker wavelet.
+ max_distances : ndarray, optional
+ At each row, a ridge line is only connected if the relative max at
+ row[n] is within ``max_distances[n]`` from the relative max at
+ ``row[n+1]``. Default value is ``widths/4``.
+ gap_thresh : float, optional
+ If a relative maximum is not found within `max_distances`,
+ there will be a gap. A ridge line is discontinued if there are more
+ than `gap_thresh` points without connecting a new relative maximum.
+ Default is the first value of the widths array i.e. widths[0].
+ min_length : int, optional
+ Minimum length a ridge line needs to be acceptable.
+ Default is ``cwt.shape[0] / 4``, ie 1/4-th the number of widths.
+ min_snr : float, optional
+ Minimum SNR ratio. Default 1. The signal is the maximum CWT coefficient
+ on the largest ridge line. The noise is `noise_perc` th percentile of
+ datapoints contained within the same ridge line.
+ noise_perc : float, optional
+ When calculating the noise floor, percentile of data points
+ examined below which to consider noise. Calculated using
+ `stats.scoreatpercentile`. Default is 10.
+ window_size : int, optional
+ Size of window to use to calculate noise floor.
+ Default is ``cwt.shape[1] / 20``.
+
+ Returns
+ -------
+ peaks_indices : ndarray
+ Indices of the locations in the `vector` where peaks were found.
+ The list is sorted.
+
+ See Also
+ --------
+ find_peaks
+ Find peaks inside a signal based on peak properties.
+
+ Notes
+ -----
+ This approach was designed for finding sharp peaks among noisy data,
+ however with proper parameter selection it should function well for
+ different peak shapes.
+
+ The algorithm is as follows:
+ 1. Perform a continuous wavelet transform on `vector`, for the supplied
+ `widths`. This is a convolution of `vector` with `wavelet(width)` for
+ each width in `widths`. See `cwt`.
+ 2. Identify "ridge lines" in the cwt matrix. These are relative maxima
+ at each row, connected across adjacent rows. See identify_ridge_lines
+ 3. Filter the ridge_lines using filter_ridge_lines.
+
+ .. versionadded:: 0.11.0
+
+ References
+ ----------
+ .. [1] Bioinformatics (2006) 22 (17): 2059-2065.
+ :doi:`10.1093/bioinformatics/btl355`
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> xs = np.arange(0, np.pi, 0.05)
+ >>> data = np.sin(xs)
+ >>> peakind = signal.find_peaks_cwt(data, np.arange(1,10))
+ >>> peakind, xs[peakind], data[peakind]
+ ([32], array([ 1.6]), array([ 0.9995736]))
+
+ """
+ widths = np.atleast_1d(np.asarray(widths))
+
+ if gap_thresh is None:
+ gap_thresh = np.ceil(widths[0])
+ if max_distances is None:
+ max_distances = widths / 4.0
+ if wavelet is None:
+ wavelet = _ricker
+
+ cwt_dat = _cwt(vector, wavelet, widths)
+ ridge_lines = _identify_ridge_lines(cwt_dat, max_distances, gap_thresh)
+ filtered = _filter_ridge_lines(cwt_dat, ridge_lines, min_length=min_length,
+ window_size=window_size, min_snr=min_snr,
+ noise_perc=noise_perc)
+ max_locs = np.asarray([x[1][0] for x in filtered])
+ max_locs.sort()
+
+ return max_locs
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..cc39a03e4738736c56a769691478be38dacaf8f7
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_peak_finding_utils.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:af31b05a73b1a4335970227c3c8f2f58eecd623b89e1b267df8f93e757fa9c4b
+size 131336
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_polyutils.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_polyutils.py
new file mode 100644
index 0000000000000000000000000000000000000000..c85f161e0eae7607a48ff819d3c97906e38fa8b2
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_polyutils.py
@@ -0,0 +1,261 @@
+"""Partial replacements for numpy polynomial routines, with Array API compatibility.
+
+This module contains both "old-style", np.poly1d, routines from the main numpy
+namespace, and "new-style", np.polynomial.polynomial, routines.
+
+To distinguish the two sets, the "new-style" routine names start with `npp_`
+"""
+import warnings
+import scipy._lib.array_api_extra as xpx
+from scipy._lib._array_api import (
+ xp_promote, xp_default_dtype, xp_size, xp_device, is_numpy
+)
+
+try:
+ from numpy.exceptions import RankWarning
+except ImportError:
+ # numpy 1.x
+ from numpy import RankWarning
+
+
+def _sort_cmplx(arr, xp):
+ # xp.sort is undefined for complex dtypes. Here we only need some
+ # consistent way to sort a complex array, including equal magnitude elements.
+ arr = xp.asarray(arr)
+ if xp.isdtype(arr.dtype, 'complex floating'):
+ sorter = abs(arr) + xp.real(arr) + xp.imag(arr)**3
+ else:
+ sorter = arr
+
+ idxs = xp.argsort(sorter)
+ return arr[idxs]
+
+
+def polyroots(coef, *, xp):
+ """numpy.roots, best-effor replacement
+ """
+ if coef.shape[0] < 2:
+ return xp.asarray([], dtype=coef.dtype)
+
+ root_func = getattr(xp, 'roots', None)
+ if root_func:
+ # NB: cupy.roots is broken in CuPy 13.x, but CuPy is handled via delegation
+ # so we never hit this code path with xp being cupy
+ return root_func(coef)
+
+ # companion matrix
+ n = coef.shape[0]
+ a = xp.eye(n - 1, n - 1, k=-1, dtype=coef.dtype)
+ a[:, -1] = -xp.flip(coef[1:]) / coef[0]
+
+ # non-symmetric eigenvalue problem is not in the spec but is available on e.g. torch
+ if hasattr(xp.linalg, 'eigvals'):
+ return xp.linalg.eigvals(a)
+ else:
+ import numpy as np
+ return xp.asarray(np.linalg.eigvals(np.asarray(a)))
+
+
+# https://github.com/numpy/numpy/blob/v2.1.0/numpy/lib/_function_base_impl.py#L1874-L1925
+def _trim_zeros(filt, trim='fb'):
+ first = 0
+ trim = trim.upper()
+ if 'F' in trim:
+ for i in filt:
+ if i != 0.:
+ break
+ else:
+ first = first + 1
+ last = filt.shape[0]
+ if 'B' in trim:
+ for i in filt[::-1]:
+ if i != 0.:
+ break
+ else:
+ last = last - 1
+ return filt[first:last]
+
+
+# For numpy arrays, use scipy.linalg.lstsq;
+# For other backends,
+# - use xp.linalg.lstsq, if available (cupy, torch, jax.numpy);
+# - otherwise manually compute pseudoinverse via SVD factorization
+def _lstsq(a, b, xp=None, rcond=None):
+ a, b = xp_promote(a, b, force_floating=True, xp=xp)
+
+ if rcond is None:
+ rcond = xp.finfo(a.dtype).eps * max(a.shape[-1], a.shape[-2])
+
+ if is_numpy(xp):
+ from scipy.linalg import lstsq as s_lstsq
+ return s_lstsq(a, b, cond=rcond)
+ elif lstsq_func := getattr(xp.linalg, "lstsq", None):
+ # cupy, torch, jax.numpy all have xp.linalg.lstsq
+ return lstsq_func(a, b, rcond=rcond)
+ else:
+ # unknown array library: LSQ solve via pseudoinverse
+ u, s, vt = xp.linalg.svd(a, full_matrices=False)
+
+ sing_val_mask = s > rcond
+ s = xpx.apply_where(sing_val_mask, (s,), lambda x: 1. / x, fill_value=0.)
+
+ sigma = xp.eye(s.shape[0]) * s # == np.diag(s)
+ x = vt.T @ sigma @ u.T @ b
+
+ rank = xp.count_nonzero(sing_val_mask)
+
+ # XXX actually compute residuals, when there's a use case
+ residuals = xp.asarray([])
+ return x, residuals, rank, s
+
+
+# ### Old-style routines ###
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/lib/_polynomial_impl.py#L1232
+def _poly1d(c_or_r, *, xp):
+ """ Constructor of np.poly1d object from an array of coefficients (r=False)
+ """
+ c_or_r = xpx.atleast_nd(c_or_r, ndim=1, xp=xp)
+ if c_or_r.ndim > 1:
+ raise ValueError("Polynomial must be 1d only.")
+ c_or_r = _trim_zeros(c_or_r, trim='f')
+ if c_or_r.shape[0] == 0:
+ c_or_r = xp.asarray([0], dtype=c_or_r.dtype)
+ return c_or_r
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/lib/_polynomial_impl.py#L702-L779
+def polyval(p, x, *, xp):
+ """ Old-style polynomial, `np.polyval`
+ """
+ p = xp.asarray(p)
+ x = xp.asarray(x)
+ y = xp.zeros_like(x)
+
+ # NB: cannot do `for pv in p` since array API iteration
+ # is only defined for 1D arrays.
+ for j in range(p.shape[0]):
+ y = y * x + p[j, ...]
+ return y
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/lib/_polynomial_impl.py#L34-L157
+def poly(seq_of_zeros, *, xp):
+ # Only reproduce the 1D variant of np.poly
+ seq_of_zeros = xp.asarray(seq_of_zeros)
+ seq_of_zeros = xpx.atleast_nd(seq_of_zeros, ndim=1, xp=xp)
+
+ if seq_of_zeros.shape[0] == 0:
+ return xp.asarray(1.0, dtype=xp.real(seq_of_zeros).dtype)
+
+ # prefer np.convolve etc, if available
+ convolve_func = getattr(xp, 'convolve', None)
+ if convolve_func is None:
+ from scipy.signal import convolve as convolve_func
+
+ dt = seq_of_zeros.dtype
+ a = xp.ones((1,), dtype=dt)
+ one = xp.ones_like(seq_of_zeros[0])
+ for zero in seq_of_zeros:
+ a = convolve_func(a, xp.stack((one, -zero)), mode='full')
+
+ if xp.isdtype(a.dtype, 'complex floating'):
+ # if complex roots are all complex conjugates, the roots are real.
+ roots = xp.asarray(seq_of_zeros, dtype=xp.complex128)
+ if xp.all(xp.sort(xp.imag(roots)) == xp.sort(xp.imag(xp.conj(roots)))):
+ a = xp.asarray(xp.real(a), copy=True)
+
+ return a
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/lib/_polynomial_impl.py#L912
+def polymul(a1, a2, *, xp):
+ a1, a2 = _poly1d(a1, xp=xp), _poly1d(a2, xp=xp)
+
+ # prefer np.convolve etc, if available
+ convolve_func = getattr(xp, 'convolve', None)
+ if convolve_func is None:
+ from scipy.signal import convolve as convolve_func
+
+ val = convolve_func(a1, a2)
+ return val
+
+
+# https://github.com/numpy/numpy/blob/v2.3.3/numpy/lib/_polynomial_impl.py#L459
+def polyfit(x, y, deg, *, xp, rcond=None):
+ # only reproduce the variant with full=False, w=None, cov=False
+ order = int(deg) + 1
+ x = xp.asarray(x)
+ y = xp.asarray(y)
+ x, y = xp_promote(x, y, force_floating=True, xp=xp)
+
+ # check arguments.
+ if deg < 0:
+ raise ValueError("expected deg >= 0")
+ if x.ndim != 1:
+ raise TypeError("expected 1D vector for x")
+ if xp_size(x) == 0:
+ raise TypeError("expected non-empty vector for x")
+ if y.ndim < 1 or y.ndim > 2:
+ raise TypeError("expected 1D or 2D array for y")
+ if x.shape[0] != y.shape[0]:
+ raise TypeError("expected x and y to have same length")
+
+ # set rcond
+ if rcond is None:
+ rcond = x.shape[0] * xp.finfo(x.dtype).eps
+
+ # set up least squares equation for powers of x: lhs = vander(x, order)
+ powers = xp.flip(xp.arange(order, dtype=x.dtype, device=xp_device(x)))
+ lhs = x[:, None] ** powers[None, :]
+
+ # scale lhs to improve condition number and solve
+ scale = xp.sqrt(xp.sum(lhs * lhs, axis=0))
+ lhs /= scale
+
+ c, _, rank, _ = _lstsq(lhs, y, rcond=rcond, xp=xp)
+ c = (c.T / scale).T # broadcast scale coefficients
+
+ # warn on rank reduction, which indicates an ill conditioned matrix
+ if rank != order:
+ msg = "Polyfit may be poorly conditioned"
+ warnings.warn(msg, RankWarning, stacklevel=2)
+
+ return c
+
+
+# ### New-style routines ###
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/polynomial/polynomial.py#L663
+def npp_polyval(x, c, *, xp, tensor=True):
+ if xp.isdtype(c.dtype, 'integral'):
+ c = xp.astype(c, xp_default_dtype(xp))
+
+ c = xpx.atleast_nd(c, ndim=1, xp=xp)
+ if isinstance(x, tuple | list):
+ x = xp.asarray(x)
+ if tensor:
+ c = xp.reshape(c, (c.shape + (1,)*x.ndim))
+
+ c0, _ = xp_promote(c[-1, ...], x, broadcast=True, xp=xp)
+ for i in range(2, c.shape[0] + 1):
+ c0 = c[-i, ...] + c0*x
+ return c0
+
+
+# https://github.com/numpy/numpy/blob/v2.2.0/numpy/polynomial/polynomial.py#L758-L842
+def npp_polyvalfromroots(x, r, *, xp, tensor=True):
+ r = xpx.atleast_nd(r, ndim=1, xp=xp)
+ # if r.dtype.char in '?bBhHiIlLqQpP':
+ # r = r.astype(np.double)
+
+ if isinstance(x, tuple | list):
+ x = xp.asarray(x)
+
+ if tensor:
+ r = xp.reshape(r, r.shape + (1,) * x.ndim)
+ elif x.ndim >= r.ndim:
+ raise ValueError("x.ndim must be < r.ndim when tensor == False")
+ return xp.prod(x - r, axis=0)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_savitzky_golay.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_savitzky_golay.py
new file mode 100644
index 0000000000000000000000000000000000000000..801587b17f859eae91544ba2c1eb026997d0ab0d
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_savitzky_golay.py
@@ -0,0 +1,383 @@
+from scipy._lib._util import float_factorial
+from scipy._lib.array_api_compat import numpy as np_compat
+from scipy._lib._array_api import array_namespace, xp_swapaxes, xp_device
+import scipy._lib.array_api_extra as xpx
+
+from scipy.ndimage import convolve1d # type: ignore[attr-defined]
+from scipy.signal import _polyutils as _pu
+from ._arraytools import axis_slice
+
+
+def savgol_coeffs(window_length, polyorder, deriv=0, delta=1.0, pos=None,
+ use="conv", *, xp=None, device=None):
+ """Compute the coefficients for a 1-D Savitzky-Golay FIR filter.
+
+ Parameters
+ ----------
+ window_length : int
+ The length of the filter window (i.e., the number of coefficients).
+ polyorder : int
+ The order of the polynomial used to fit the samples.
+ `polyorder` must be less than `window_length`.
+ deriv : int, optional
+ The order of the derivative to compute. This must be a
+ nonnegative integer. The default is 0, which means to filter
+ the data without differentiating.
+ delta : float, optional
+ The spacing of the samples to which the filter will be applied.
+ This is only used if deriv > 0.
+ pos : int or None, optional
+ If pos is not None, it specifies evaluation position within the
+ window. The default is the middle of the window.
+ use : str, optional
+ Either 'conv' or 'dot'. This argument chooses the order of the
+ coefficients. The default is 'conv', which means that the
+ coefficients are ordered to be used in a convolution. With
+ use='dot', the order is reversed, so the filter is applied by
+ dotting the coefficients with the data set.
+
+ Returns
+ -------
+ coeffs : 1-D ndarray
+ The filter coefficients.
+
+ See Also
+ --------
+ savgol_filter
+
+ Notes
+ -----
+ .. versionadded:: 0.14.0
+
+ References
+ ----------
+ A. Savitzky, M. J. E. Golay, Smoothing and Differentiation of Data by
+ Simplified Least Squares Procedures. Analytical Chemistry, 1964, 36 (8),
+ pp 1627-1639.
+ Jianwen Luo, Kui Ying, and Jing Bai. 2005. Savitzky-Golay smoothing and
+ differentiation filter for even number data. Signal Process.
+ 85, 7 (July 2005), 1429-1434.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import savgol_coeffs
+ >>> savgol_coeffs(5, 2)
+ array([-0.08571429, 0.34285714, 0.48571429, 0.34285714, -0.08571429])
+ >>> savgol_coeffs(5, 2, deriv=1)
+ array([ 2.00000000e-01, 1.00000000e-01, 2.07548111e-16, -1.00000000e-01,
+ -2.00000000e-01])
+
+ Note that use='dot' simply reverses the coefficients.
+
+ >>> savgol_coeffs(5, 2, pos=3)
+ array([ 0.25714286, 0.37142857, 0.34285714, 0.17142857, -0.14285714])
+ >>> savgol_coeffs(5, 2, pos=3, use='dot')
+ array([-0.14285714, 0.17142857, 0.34285714, 0.37142857, 0.25714286])
+ >>> savgol_coeffs(4, 2, pos=3, deriv=1, use='dot')
+ array([0.45, -0.85, -0.65, 1.05])
+
+ `x` contains data from the parabola x = t**2, sampled at
+ t = -1, 0, 1, 2, 3. `c` holds the coefficients that will compute the
+ derivative at the last position. When dotted with `x` the result should
+ be 6.
+
+ >>> x = np.array([1, 0, 1, 4, 9])
+ >>> c = savgol_coeffs(5, 2, pos=4, deriv=1, use='dot')
+ >>> c.dot(x)
+ 6.0
+ """
+
+ # An alternative method for finding the coefficients when deriv=0 is
+ # t = np.arange(window_length)
+ # unit = (t == pos).astype(int)
+ # coeffs = np.polyval(np.polyfit(t, unit, polyorder), t)
+ # The method implemented here is faster.
+
+ # To recreate the table of sample coefficients shown in the chapter on
+ # the Savitzy-Golay filter in the Numerical Recipes book, use
+ # window_length = nL + nR + 1
+ # pos = nL + 1
+ # c = savgol_coeffs(window_length, M, pos=pos, use='dot')
+
+ if polyorder >= window_length:
+ raise ValueError("polyorder must be less than window_length.")
+
+ halflen, rem = divmod(window_length, 2)
+
+ if pos is None:
+ if rem == 0:
+ pos = halflen - 0.5
+ else:
+ pos = halflen
+
+ if not (0 <= pos < window_length):
+ raise ValueError("pos must be nonnegative and less than "
+ "window_length.")
+
+ if use not in ['conv', 'dot']:
+ raise ValueError("`use` must be 'conv' or 'dot'")
+
+ # cf windows/_windows.py
+ xp = np_compat if xp is None else array_namespace(xp.empty(0))
+
+ if deriv > polyorder:
+ coeffs = xp.zeros(window_length, dtype=xp.float64, device=device)
+ return coeffs
+
+ # Form the design matrix A. The columns of A are powers of the integers
+ # from -pos to window_length - pos - 1. The powers (i.e., rows) range
+ # from 0 to polyorder. (That is, A is a vandermonde matrix, but not
+ # necessarily square.)
+ x = xp.arange(-pos, window_length - pos, dtype=xp.float64, device=device)
+
+ if use == "conv":
+ # Reverse so that result can be used in a convolution.
+ x = xp.flip(x)
+
+ order = xp.reshape(
+ xp.arange(polyorder + 1, dtype=xp.float64, device=device), (-1, 1)
+ )
+ A = x ** order
+
+ # y determines which order derivative is returned.
+ y = xp.zeros(polyorder + 1, dtype=xp.float64, device=device)
+ # The coefficient assigned to y[deriv] scales the result to take into
+ # account the order of the derivative and the sample spacing.
+ y = xpx.at(y, deriv).set(float_factorial(deriv) / (delta ** deriv))
+
+ # Find the least-squares solution of A*c = y
+ coeffs, _, _, _ = _pu._lstsq(A, y, xp=xp)
+
+ return coeffs
+
+
+def _polyder(p, m, *, xp):
+ """Differentiate polynomials represented with coefficients.
+
+ p must be a 1-D or 2-D array. In the 2-D case, each column gives
+ the coefficients of a polynomial; the first row holds the coefficients
+ associated with the highest power. m must be a nonnegative integer.
+ (numpy.polyder doesn't handle the 2-D case.)
+ """
+
+ if m == 0:
+ result = p
+ else:
+ n = p.shape[0]
+ if n <= m:
+ result = xp.zeros_like(p[:1, ...])
+ else:
+ dp = xp.asarray(p[:-m, ...], copy=True)
+ for k in range(m):
+ rng = xp.arange(
+ n - k - 1, m - k - 1, -1, dtype=p.dtype, device=xp_device(p)
+ )
+ dp *= xp.reshape(rng, (n - m,) + (1,) * (p.ndim - 1))
+ result = dp
+ return result
+
+
+def _fit_edge(x, window_start, window_stop, interp_start, interp_stop,
+ axis, polyorder, deriv, delta, y):
+ """
+ Given an N-d array `x` and the specification of a slice of `x` from
+ `window_start` to `window_stop` along `axis`, create an interpolating
+ polynomial of each 1-D slice, and evaluate that polynomial in the slice
+ from `interp_start` to `interp_stop`. Put the result into the
+ corresponding slice of `y`.
+ """
+ xp = array_namespace(x)
+
+ # Get the edge into a (window_length, -1) array.
+ x_edge = axis_slice(x, start=window_start, stop=window_stop, axis=axis)
+ if axis == 0 or axis == -x.ndim:
+ xx_edge = x_edge
+ swapped = False
+ else:
+ xx_edge = xp_swapaxes(x_edge, axis, 0, xp)
+ swapped = True
+ xx_edge = xp.reshape(xx_edge, (xx_edge.shape[0], -1))
+
+ # Fit the edges. poly_coeffs has shape (polyorder + 1, -1),
+ # where '-1' is the same as in xx_edge.
+ poly_coeffs = _pu.polyfit(
+ xp.arange(
+ 0, window_stop - window_start, dtype=x.dtype, device=xp_device(x)
+ ), xx_edge, polyorder, xp=xp
+ )
+
+ if deriv > 0:
+ poly_coeffs = _polyder(poly_coeffs, deriv, xp=xp)
+
+ # Compute the interpolated values for the edge.
+ i = xp.arange(
+ interp_start - window_start, interp_stop - window_start,
+ dtype=poly_coeffs.dtype, device=xp_device(poly_coeffs)
+ )
+ values = _pu.polyval(poly_coeffs, xp.reshape(i, (-1, 1)), xp=xp) / (delta ** deriv)
+
+ # Now put the values into the appropriate slice of y.
+ # First reshape values to match y.
+ shp = list(y.shape)
+ shp[0], shp[axis] = shp[axis], shp[0]
+ values = xp.reshape(values, (interp_stop - interp_start, *shp[1:]))
+ if swapped:
+ values = xp_swapaxes(values, 0, axis, xp)
+ # Get a view of the data to be replaced by values.
+ y_slice = [slice(None)] * y.ndim
+ y_slice[axis] = slice(interp_start, interp_stop)
+ y = xpx.at(y, tuple(y_slice)).set(values)
+
+ return y
+
+
+
+def _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y):
+ """
+ Use polynomial interpolation of x at the low and high ends of the axis
+ to fill in the halflen values in y.
+
+ This function just calls _fit_edge twice, once for each end of the axis.
+ """
+ halflen = window_length // 2
+ y = _fit_edge(x, 0, window_length, 0, halflen, axis,
+ polyorder, deriv, delta, y)
+ n = x.shape[axis]
+ y = _fit_edge(x, n - window_length, n, n - halflen, n, axis,
+ polyorder, deriv, delta, y)
+
+ return y
+
+
+def savgol_filter(x, window_length, polyorder, deriv=0, delta=1.0,
+ axis=-1, mode='interp', cval=0.0):
+ """ Apply a Savitzky-Golay filter to an array.
+
+ This is a 1-D filter. If `x` has dimension greater than 1, `axis`
+ determines the axis along which the filter is applied.
+
+ Parameters
+ ----------
+ x : array_like
+ The data to be filtered. If `x` is not a single or double precision
+ floating point array, it will be converted to type ``numpy.float64``
+ before filtering.
+ window_length : int
+ The length of the filter window (i.e., the number of coefficients).
+ If `mode` is 'interp', `window_length` must be less than or equal
+ to the size of `x`.
+ polyorder : int
+ The order of the polynomial used to fit the samples.
+ `polyorder` must be less than `window_length`.
+ deriv : int, optional
+ The order of the derivative to compute. This must be a
+ nonnegative integer. The default is 0, which means to filter
+ the data without differentiating.
+ delta : float, optional
+ The spacing of the samples to which the filter will be applied.
+ This is only used if deriv > 0. Default is 1.0.
+ axis : int, optional
+ The axis of the array `x` along which the filter is to be applied.
+ Default is -1.
+ mode : str, optional
+ Must be 'mirror', 'constant', 'nearest', 'wrap' or 'interp'. This
+ determines the type of extension to use for the padded signal to
+ which the filter is applied. When `mode` is 'constant', the padding
+ value is given by `cval`. See the Notes for more details on 'mirror',
+ 'constant', 'wrap', and 'nearest'.
+ When the 'interp' mode is selected (the default), no extension
+ is used. Instead, a degree `polyorder` polynomial is fit to the
+ last `window_length` values of the edges, and this polynomial is
+ used to evaluate the last `window_length // 2` output values.
+ cval : scalar, optional
+ Value to fill past the edges of the input if `mode` is 'constant'.
+ Default is 0.0.
+
+ Returns
+ -------
+ y : ndarray, same shape as `x`
+ The filtered data.
+
+ See Also
+ --------
+ savgol_coeffs
+
+ Notes
+ -----
+ Details on the `mode` options:
+
+ 'mirror':
+ Repeats the values at the edges in reverse order. The value
+ closest to the edge is not included.
+ 'nearest':
+ The extension contains the nearest input value.
+ 'constant':
+ The extension contains the value given by the `cval` argument.
+ 'wrap':
+ The extension contains the values from the other end of the array.
+
+ For example, if the input is [1, 2, 3, 4, 5, 6, 7, 8], and
+ `window_length` is 7, the following shows the extended data for
+ the various `mode` options (assuming `cval` is 0)::
+
+ mode | Ext | Input | Ext
+ -----------+---------+------------------------+---------
+ 'mirror' | 4 3 2 | 1 2 3 4 5 6 7 8 | 7 6 5
+ 'nearest' | 1 1 1 | 1 2 3 4 5 6 7 8 | 8 8 8
+ 'constant' | 0 0 0 | 1 2 3 4 5 6 7 8 | 0 0 0
+ 'wrap' | 6 7 8 | 1 2 3 4 5 6 7 8 | 1 2 3
+
+ .. versionadded:: 0.14.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import savgol_filter
+ >>> np.set_printoptions(precision=2) # For compact display.
+ >>> x = np.array([2, 2, 5, 2, 1, 0, 1, 4, 9])
+
+ Filter with a window length of 5 and a degree 2 polynomial. Use
+ the defaults for all other parameters.
+
+ >>> savgol_filter(x, 5, 2)
+ array([1.66, 3.17, 3.54, 2.86, 0.66, 0.17, 1. , 4. , 9. ])
+
+ Note that the last five values in x are samples of a parabola, so
+ when mode='interp' (the default) is used with polyorder=2, the last
+ three values are unchanged. Compare that to, for example,
+ `mode='nearest'`:
+
+ >>> savgol_filter(x, 5, 2, mode='nearest')
+ array([1.74, 3.03, 3.54, 2.86, 0.66, 0.17, 1. , 4.6 , 7.97])
+
+ """
+ if mode not in ["mirror", "constant", "nearest", "interp", "wrap"]:
+ raise ValueError("mode must be 'mirror', 'constant', 'nearest' "
+ "'wrap' or 'interp'.")
+
+ xp = array_namespace(x)
+ x = xp.asarray(x)
+ # Ensure that x is either single or double precision floating point.
+ if x.dtype != xp.float64 and x.dtype != xp.float32:
+ x = xp.astype(x, xp.float64)
+
+ coeffs = savgol_coeffs(
+ window_length, polyorder, deriv=deriv, delta=delta, xp=xp, device=xp_device(x)
+ )
+
+ if mode == "interp":
+ if window_length > x.shape[axis]:
+ raise ValueError("If mode is 'interp', window_length must be less "
+ "than or equal to the size of x.")
+
+ # Do not pad. Instead, for the elements within `window_length // 2`
+ # of the ends of the sequence, use the polynomial that is fitted to
+ # the last `window_length` elements.
+ y = convolve1d(x, coeffs, axis=axis, mode="constant")
+ y = _fit_edges_polyfit(x, window_length, polyorder, deriv, delta, axis, y)
+ else:
+ # Any mode other than 'interp' is passed on to ndimage.convolve1d.
+ y = convolve1d(x, coeffs, axis=axis, mode=mode, cval=cval)
+
+ return y
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_short_time_fft.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_short_time_fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..b83c1963ec10b0c21b4bb5028a0529ae62b40fd8
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_short_time_fft.py
@@ -0,0 +1,2234 @@
+"""Implementation of an FFT-based Short-time Fourier Transform. """
+
+# Implementation Notes for this file (as of 2025-08)
+# --------------------------------------------------
+# * Since the method `stft` and `istft` have identical names as the legacy
+# functions in the signal module, referencing them as HTML link in the
+# docstrings has to be done by an explicit `~ShortTimeFFT.stft` instead of an
+# ambiguous `stft` (The ``~`` hides the class / module name).
+# * The HTML documentation currently renders each method/property on a separate
+# page without reference to the parent class. Thus, a link to `ShortTimeFFT`
+# was added to the "See Also" section of each method/property. These links
+# can be removed, when SciPy updates ``pydata-sphinx-theme`` to >= 0.13.3
+# (currently 0.9). Consult Issue 18512 and PR 16660 for further details.
+
+
+# Linter does not allow to import ``Generator`` from ``typing`` module:
+from collections.abc import Generator, Callable
+from functools import partial, cached_property
+from types import GenericAlias
+from typing import get_args, Literal
+
+import numpy as np
+
+import scipy.fft as fft_lib
+from scipy.signal._signaltools import detrend
+from scipy.signal.windows import get_window
+
+__all__ = ['closest_STFT_dual_window', 'ShortTimeFFT']
+
+
+#: Allowed values for parameter `padding` of method `ShortTimeFFT.stft()`:
+PAD_TYPE = Literal['zeros', 'edge', 'even', 'odd']
+
+#: Allowed values for property `ShortTimeFFT.fft_mode`:
+FFT_MODE_TYPE = Literal['twosided', 'centered', 'onesided', 'onesided2X']
+
+
+def _calc_dual_canonical_window(win: np.ndarray, hop: int) -> np.ndarray:
+ """Calculate canonical dual window for 1d window `win` and a time step
+ of `hop` samples.
+
+ A ``ValueError`` is raised if the inversion fails.
+
+ This is a separate function not a method, since it is also used in the
+ class method ``ShortTimeFFT.from_dual()``.
+ """
+ if hop > len(win):
+ raise ValueError(f"{hop=} is larger than window length of {len(win)}" +
+ " => STFT not invertible!")
+ if issubclass(win.dtype.type, np.integer):
+ raise ValueError("Parameter 'win' cannot be of integer type, but " +
+ f"{win.dtype=} => STFT not invertible!")
+ # The calculation of `relative_resolution` does not work for ints.
+ # Furthermore, `win / DD` casts the integers away, thus an implicit
+ # cast is avoided, which can always cause confusion when using 32-Bit
+ # floats.
+
+ w2 = win.real**2 + win.imag**2 # win*win.conj() does not ensure w2 is real
+ DD = w2.copy()
+ for k_ in range(hop, len(win), hop):
+ DD[k_:] += w2[:-k_]
+ DD[:-k_] += w2[k_:]
+
+ # check DD > 0:
+ relative_resolution = np.finfo(win.dtype).resolution * max(DD)
+ if not np.all(DD >= relative_resolution):
+ raise ValueError("Short-time Fourier Transform not invertible!")
+
+ return win / DD
+
+
+def closest_STFT_dual_window(win: np.ndarray, hop: int,
+ desired_dual: np.ndarray | None = None, *,
+ scaled: bool = True) \
+ -> tuple[np.ndarray, float | complex]:
+ r"""Calculate the STFT dual window of a given window closest to a desired dual
+ window.
+
+ For a given short-time Fourier transform window `win` incremented by `hop`
+ samples, the dual window is calculated, which minimizes
+ ``abs(dual_win - desired_dual)**2`` when `scaled` is ``False``. For `scaled`
+ set to ``True``, ``abs(alpha*dual_win - desired_dual)**2`` is minimized with
+ `alpha` being the optimal scaling factor.
+ A ``ValueError`` is raised if no valid dual window can be determined.
+
+
+ Parameters
+ ----------
+ win : np.ndarray
+ The window must be a real- or complex-valued 1d array.
+ hop : int
+ The increment in samples by which the window is shifted in each step.
+ desired_dual: np.ndarray | None
+ The desired dual window must be a 1d array of the same length as `win`.
+ If set to ``None`` (default), then `desired_dual` is assumed to be the
+ rectangular window, i.e., ``np.ones_like(win)``.
+ scaled : bool
+ If set (default), the closest scaled version instead of closest dual window
+ is calculated.
+
+ Returns
+ -------
+ dual_win : np.ndarray
+ A dual window of ``alpha*win`` (with hop interval `hop`), which is closest
+ to `desired_dual`. Note that the dual window of `win` is `dual_win/alpha`
+ and that the dual window of `dual_win` is `alpha*win`.
+ `dual_win` has the same shape as `win` and `desired_win`.
+ alpha : float | complex
+ Scale factor for `win`. It is always one if `scaled` is set to ``False``.
+
+ Notes
+ -----
+ For a given window and `hop` interval, all possible dual windows are expressed
+ by the `hop` linear conditions of Eq. :math:numref:`eq_STFT_AllDualWinsCond` in
+ the :ref:`tutorial_stft` section of the :ref:`user_guide`. Hence, decreasing
+ `hop`, increases the number of degrees of freedom of the set of all possible
+ dual windows, improving the ability to better approximate a `desired_dual`.
+
+ This function can also be used to determine windows which fulfill the
+ so-called "Constant OverLap Add" (COLA) condition [1]_. It states that summing
+ all touching window values at any given sample position results in the same
+ constant :math:`\alpha`. Eq. :math:numref:`eq_STFT_AllDualWinsCond` shows that
+ this is equal to having a rectangular dual window, i.e., the dual being
+ ``alpha*np.ones(m)``.
+
+ Some examples of windows that satisfy COLA (taken from [2]_):
+
+ - Rectangular window at overlap of 0, 1/2, 2/3, 3/4, ...
+ - Bartlett window at overlap of 1/2, 3/4, 5/6, ...
+ - Hann window at 1/2, 2/3, 3/4, ...
+ - Any Blackman family window at 2/3 overlap
+ - Any window with ``hop=1``
+
+ References
+ ----------
+ .. [1] Julius O. Smith III, "Spectral Audio Signal Processing",
+ online book, 2011, https://www.dsprelated.com/freebooks/sasp/
+ .. [2] G. Heinzel, A. Ruediger and R. Schilling, "Spectrum and spectral density
+ estimation by the Discrete Fourier transform (DFT), including a
+ comprehensive list of window functions and some new at-top windows",
+ 2002, http://hdl.handle.net/11858/00-001M-0000-0013-557A-5
+
+ Examples
+ --------
+ Let's show that a Bartlett window with 75% overlap fulfills the COLA condition:
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.signal import closest_STFT_dual_window, windows
+ ...
+ >>> m = 24
+ >>> win, w_rect = windows.bartlett(m, sym=False), np.ones(m)
+ >>> d_win, alpha = closest_STFT_dual_window(win, m//4, w_rect, scaled=True)
+ >>> print(f"COLA: {np.allclose(d_win, w_rect*alpha)}, {alpha = :g}")
+ COLA: True, alpha = 0.5
+
+ We can also determine for which hop intervals the COLA condition is fulfilled:
+
+ >>> hops, deviations, alphas = np.arange(1, 16, dtype=int), [], []
+ >>> for h_ in hops:
+ ... w_cola, alpha = closest_STFT_dual_window(w_rect, h_, win, scaled=True)
+ ... deviations.append(np.linalg.norm(w_cola - win*alpha))
+ ... alphas.append(alpha)
+ ...
+ >>> fg0, (ax0, ax1) = plt.subplots(2, 1, sharex='all', tight_layout=True)
+ >>> ax0.set_title(f"COLA Window closest to a {m}-Sample Bartlett Window")
+ >>> ax0.set(ylabel=r"$||w_\text{cola}-\alpha w||$", xlim=(0, hops[-1]-.5))
+ >>> ax1.set(xlabel="Hop Interval", ylabel=r"Scaling factor $\alpha$",
+ ... ylim=(0, 1.25))
+ >>> ax0.plot(hops, deviations, 'C0.-')
+ >>> ax1.plot(hops, alphas, 'C1.-')
+ >>> for ax_ in (ax0, ax1):
+ ... ax_.grid()
+ >>> plt.show()
+
+ The lower plot shows the calculated scaling factor :math:`\alpha` for different
+ `hops` whereas the upper displays the :math:`L^2`-norm of the difference
+ between the scaled Bartlett window and the calculated window. Since for `hops`
+ 1 to 4 as well as for 6 and 12 the :math:`L^2`-norm of the difference is
+ practically zero, the COLA condition is fulfilled for those.
+
+ See Also
+ --------
+ ShortTimeFFT: Short-time Fourier transform which is able to utilize a dual
+ window for calculating the inverse.
+ ShortTimeFFT.from_win_equals_dual: Create instance where the window and its
+ dual are equal.
+
+ """
+ if desired_dual is None: # default is rectangular window
+ desired_dual = np.ones_like(win)
+ if not (win.ndim == 1 and win.shape == desired_dual.shape):
+ raise ValueError("Parameters `win` and `desired_dual` are not 1d arrays of " +
+ f"equal length ({win.shape=}, {desired_dual.shape=})!")
+ if not all(np.isfinite(win)):
+ raise ValueError("Parameter win must have finite entries!")
+ if not all(np.isfinite(desired_dual)):
+ raise ValueError("Parameter desired_dual must have finite entries!")
+ if not (1 <= hop <= len(win) and isinstance(hop, int | np.integer)):
+ raise ValueError(f"Parameter {hop=} is not an integer between 1 and " +
+ f"{len(win)=}!")
+
+ w_d = _calc_dual_canonical_window(win, hop)
+ wdd = win.conjugate() * desired_dual
+ q_d = wdd.copy()
+ for k_ in range(hop, len(win), hop):
+ q_d[k_:] += wdd[:-k_]
+ q_d[:-k_] += wdd[k_:]
+ q_d = w_d * q_d
+
+ if not scaled:
+ return w_d + desired_dual - q_d, 1.
+
+ numerator = q_d.conjugate().T @ w_d
+ denominator = q_d.T.real @ q_d.real + q_d.T.imag @ q_d.imag # always >= 0
+ if not (abs(numerator) > 0 and denominator > np.finfo(w_d.dtype).resolution):
+ raise ValueError(
+ "Unable to calculate scaled closest dual window due to numerically " +
+ "unstable scaling factor! Try setting parameter `scaled` to False.")
+ alpha = numerator / denominator
+ return w_d + alpha * (desired_dual - q_d), alpha
+
+
+# noinspection PyShadowingNames
+class ShortTimeFFT:
+ r"""Provide a parametrized discrete Short-time Fourier transform (stft)
+ and its inverse (istft).
+
+ .. currentmodule:: scipy.signal.ShortTimeFFT
+
+ The `~ShortTimeFFT.stft` calculates sequential FFTs by sliding a
+ window (`win`) over an input signal by `hop` increments. It can be used to
+ quantify the change of the spectrum over time.
+
+ The `~ShortTimeFFT.stft` is represented by a complex-valued matrix S[q,p]
+ where the p-th column represents an FFT with the window centered at the
+ time t[p] = p * `delta_t` = p * `hop` * `T` where `T` is the sampling
+ interval of the input signal. The q-th row represents the values at the
+ frequency f[q] = q * `delta_f` with `delta_f` = 1 / (`mfft` * `T`) being
+ the bin width of the FFT.
+
+ The inverse STFT `~ShortTimeFFT.istft` is calculated by reversing the steps
+ of the STFT: Take the IFFT of the p-th slice of S[q,p] and multiply the
+ result with the so-called dual window (see `dual_win`). Shift the result by
+ p * `delta_t` and add the result to previous shifted results to reconstruct
+ the signal. If only the dual window is known and the STFT is invertible,
+ `from_dual` can be used to instantiate this class.
+
+ By default, the so-called canonical dual window is used. It is the window with
+ minimal energy among all possible dual windows. `from_win_equals_dual` and
+ `~scipy.signal.closest_STFT_dual_window` provide means for utilizing alterantive
+ dual windows. Note that `win` is also always a dual window of `dual_win`.
+
+ Due to the convention of time t = 0 being at the first sample of the input
+ signal, the STFT values typically have negative time slots. Hence,
+ negative indexes like `p_min` or `k_min` do not indicate counting
+ backwards from an array's end like in standard Python indexing but being
+ left of t = 0.
+
+ More detailed information can be found in the :ref:`tutorial_stft`
+ section of the :ref:`user_guide`.
+
+ Note that all parameters of the initializer, except `scale_to` (which uses
+ `scaling`) have identical named attributes.
+
+ Parameters
+ ----------
+ win : np.ndarray
+ The window must be a real- or complex-valued 1d array.
+ hop : int
+ The increment in samples, by which the window is shifted in each step.
+ fs : float
+ Sampling frequency of input signal and window. Its relation to the
+ sampling interval `T` is ``T = 1 / fs``.
+ fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X'
+ Mode of FFT to be used (default 'onesided').
+ See property `fft_mode` for details.
+ mfft: int | None
+ Length of the FFT used, if a zero padded FFT is desired.
+ If ``None`` (default), the length of the window `win` is used.
+ dual_win : np.ndarray | None
+ The dual window of `win`. If set to ``None``, it is calculated if
+ needed.
+ scale_to : 'magnitude', 'psd' | None
+ If not ``None`` (default) the window function is scaled, so each STFT
+ column represents either a 'magnitude' or a power spectral density
+ ('psd') spectrum. This parameter sets the property `scaling` to the
+ same value. See method `scale_to` for details.
+ phase_shift : int | None
+ If set, add a linear phase `phase_shift` / `mfft` * `f` to each
+ frequency `f`. The default value of 0 ensures that there is no phase shift
+ on the zeroth slice (in which t=0 is centered). See property
+ `phase_shift` for more details.
+
+ Notes
+ -----
+ A typical STFT application is the creation of various types of time-frequency
+ plots, often subsumed under the term "spectrogram". Note that this term is also
+ used to explecitly refer to the absolute square of a STFT [11]_, as done in
+ :meth:`spectrogram`.
+
+ The STFT can also be used for filtering and filter banks as discussed in [12]_.
+
+
+ References
+ ----------
+ .. [11] Karlheinz Gröchenig: "Foundations of Time-Frequency Analysis",
+ Birkhäuser Boston 2001, `10.1007/978-1-4612-0003-1`
+ .. [12] Julius O. Smith III, "Spectral Audio Signal Processing", online book, 2011,
+ https://www.dsprelated.com/freebooks/sasp/
+
+
+ Examples
+ --------
+ The following example shows the magnitude of the STFT of a sine with
+ varying frequency :math:`f_i(t)` (marked by a red dashed line in the plot):
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import ShortTimeFFT
+ >>> from scipy.signal.windows import gaussian
+ ...
+ >>> T_x, N = 1 / 20, 1000 # 20 Hz sampling rate for 50 s signal
+ >>> t_x = np.arange(N) * T_x # time indexes for signal
+ >>> f_i = 1 * np.arctan((t_x - t_x[N // 2]) / 2) + 5 # varying frequency
+ >>> x = np.sin(2*np.pi*np.cumsum(f_i)*T_x) # the signal
+
+ The utilized Gaussian window is 50 samples or 2.5 s long. The parameter
+ ``mfft=200`` in `ShortTimeFFT` causes the spectrum to be oversampled
+ by a factor of 4:
+
+ >>> g_std = 8 # standard deviation for Gaussian window in samples
+ >>> w = gaussian(50, std=g_std, sym=True) # symmetric Gaussian window
+ >>> SFT = ShortTimeFFT(w, hop=10, fs=1/T_x, mfft=200, scale_to='magnitude')
+ >>> Sx = SFT.stft(x) # perform the STFT
+
+ In the plot, the time extent of the signal `x` is marked by vertical dashed
+ lines. Note that the SFT produces values outside the time range of `x`. The
+ shaded areas on the left and the right indicate border effects caused
+ by the window slices in that area not fully being inside time range of
+ `x`:
+
+ >>> fig1, ax1 = plt.subplots(figsize=(6., 4.)) # enlarge plot a bit
+ >>> t_lo, t_hi = SFT.extent(N)[:2] # time range of plot
+ >>> ax1.set_title(rf"STFT ({SFT.m_num*SFT.T:g}$\,s$ Gaussian window, " +
+ ... rf"$\sigma_t={g_std*SFT.T}\,$s)")
+ >>> ax1.set(xlabel=f"Time $t$ in seconds ({SFT.p_num(N)} slices, " +
+ ... rf"$\Delta t = {SFT.delta_t:g}\,$s)",
+ ... ylabel=f"Freq. $f$ in Hz ({SFT.f_pts} bins, " +
+ ... rf"$\Delta f = {SFT.delta_f:g}\,$Hz)",
+ ... xlim=(t_lo, t_hi))
+ ...
+ >>> im1 = ax1.imshow(abs(Sx), origin='lower', aspect='auto',
+ ... extent=SFT.extent(N), cmap='viridis')
+ >>> ax1.plot(t_x, f_i, 'r--', alpha=.5, label='$f_i(t)$')
+ >>> fig1.colorbar(im1, label="Magnitude $|S_x(t, f)|$")
+ ...
+ >>> # Shade areas where window slices stick out to the side:
+ >>> for t0_, t1_ in [(t_lo, SFT.lower_border_end[0] * SFT.T),
+ ... (SFT.upper_border_begin(N)[0] * SFT.T, t_hi)]:
+ ... ax1.axvspan(t0_, t1_, color='w', linewidth=0, alpha=.2)
+ >>> for t_ in [0, N * SFT.T]: # mark signal borders with vertical line:
+ ... ax1.axvline(t_, color='y', linestyle='--', alpha=0.5)
+ >>> ax1.legend()
+ >>> fig1.tight_layout()
+ >>> plt.show()
+
+ Reconstructing the signal with the `~ShortTimeFFT.istft` is
+ straightforward, but note that the length of `x1` should be specified,
+ since the STFT length increases in `hop` steps:
+
+ >>> SFT.invertible # check if invertible
+ True
+ >>> x1 = SFT.istft(Sx, k1=N)
+ >>> np.allclose(x, x1)
+ True
+
+ It is possible to calculate the STFT of signal parts:
+
+ >>> N2 = SFT.nearest_k_p(N // 2)
+ >>> Sx0 = SFT.stft(x[:N2])
+ >>> Sx1 = SFT.stft(x[N2:])
+
+ When assembling sequential STFT parts together, the overlap needs to be
+ considered:
+
+ >>> p0_ub = SFT.upper_border_begin(N2)[1] - SFT.p_min
+ >>> p1_le = SFT.lower_border_end[1] - SFT.p_min
+ >>> Sx01 = np.hstack((Sx0[:, :p0_ub],
+ ... Sx0[:, p0_ub:] + Sx1[:, :p1_le],
+ ... Sx1[:, p1_le:]))
+ >>> np.allclose(Sx01, Sx) # Compare with SFT of complete signal
+ True
+
+ It is also possible to calculate the `itsft` for signal parts:
+
+ >>> y_p = SFT.istft(Sx, N//3, N//2)
+ >>> np.allclose(y_p, x[N//3:N//2])
+ True
+
+ """
+ # immutable attributes (only have getters but no setters):
+ _win: np.ndarray # window
+ _dual_win: np.ndarray | None = None # canonical dual window
+ _hop: int # Step of STFT in number of samples
+
+ # mutable attributes:
+ _fs: float # sampling frequency of input signal and window
+ _fft_mode: FFT_MODE_TYPE = 'onesided' # Mode of FFT to use
+ _mfft: int # length of FFT used - defaults to len(win)
+ _scaling: Literal['magnitude', 'psd', 'unitary'] | None = None # Scaling of _win
+ _phase_shift: int | None # amount to shift phase of FFT in samples
+
+ # attributes for caching calculated values:
+ _fac_mag: float | None = None
+ _fac_psd: float | None = None
+ _lower_border_end: tuple[int, int] | None = None
+ # The following tuples store parameter(s) and return value(s) of methods for caching
+ # (initialized with invalid parameters; should only be accessed by atomic
+ # read/writes to alleviate potential multithreading issues):
+ _cache_post_padding: tuple[int, tuple[int, int]] = -1, (0, 0)
+ _cache_upper_border_begin: tuple[int, tuple[int, int]] = -1, (0, 0)
+ _cache_t: tuple[tuple[int, int | None, int | None, int, float], np.ndarray] = \
+ (-1, None, None, 0, 0.), np.ndarray([])
+ _cache_f: tuple[tuple[FFT_MODE_TYPE, int, float], np.ndarray] = \
+ ('onesided', -1, 1.), np.ndarray([])
+
+ # generic type compatibility with scipy-stubs
+ __class_getitem__ = classmethod(GenericAlias)
+
+ def __init__(self, win: np.ndarray, hop: int, fs: float, *,
+ fft_mode: FFT_MODE_TYPE = 'onesided',
+ mfft: int | None = None,
+ dual_win: np.ndarray | None = None,
+ scale_to: Literal['magnitude', 'psd'] | None = None,
+ phase_shift: int | None = 0):
+ if not (win.ndim == 1 and win.size > 0):
+ raise ValueError(f"Parameter win must be 1d, but {win.shape=}!")
+ if not all(np.isfinite(win)):
+ raise ValueError("Parameter win must have finite entries!")
+ if not (hop >= 1 and isinstance(hop, int | np.integer)):
+ raise ValueError(f"Parameter {hop=} is not an integer >= 1!")
+
+ self._win, self._hop, self.fs = win, hop, fs
+ self.win.setflags(write=False)
+ self.mfft = len(win) if mfft is None else mfft
+
+ if dual_win is not None:
+ if dual_win.shape != win.shape:
+ raise ValueError(f"{dual_win.shape=} must equal {win.shape=}!")
+ if not all(np.isfinite(dual_win)):
+ raise ValueError("Parameter dual_win must be a finite array!")
+ dual_win.setflags(write=False)
+ self._dual_win = dual_win # needs to be set before scaling
+
+ if scale_to is not None: # needs to be set before fft_mode
+ self.scale_to(scale_to)
+
+ self.fft_mode, self.phase_shift = fft_mode, phase_shift
+
+ @classmethod
+ def from_dual(cls, dual_win: np.ndarray, hop: int, fs: float, *,
+ fft_mode: FFT_MODE_TYPE = 'onesided',
+ mfft: int | None = None,
+ scale_to: Literal['magnitude', 'psd'] | None = None,
+ phase_shift: int | None = 0):
+ r"""Instantiate a `ShortTimeFFT` by only providing a dual window.
+
+ If an STFT is invertible, it is possible to calculate the window `win`
+ from a given dual window `dual_win`. All other parameters have the
+ same meaning as in the initializer of `ShortTimeFFT`.
+
+ As explained in the :ref:`tutorial_stft` section of the
+ :ref:`user_guide`, an invertible STFT can be interpreted as series
+ expansion of time-shifted and frequency modulated dual windows. E.g.,
+ the series coefficient S[q,p] belongs to the term, which shifted
+ `dual_win` by p * `delta_t` and multiplied it by
+ exp( 2 * j * pi * t * q * `delta_f`).
+
+
+ Examples
+ --------
+ The following example discusses decomposing a signal into time- and
+ frequency-shifted Gaussians. A Gaussian with standard deviation of
+ one made up of 51 samples will be used:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import ShortTimeFFT
+ >>> from scipy.signal.windows import gaussian
+ ...
+ >>> T, N = 0.1, 51
+ >>> d_win = gaussian(N, std=1/T, sym=True) # symmetric Gaussian window
+ >>> t = T * (np.arange(N) - N//2)
+ ...
+ >>> fg1, ax1 = plt.subplots()
+ >>> ax1.set_title(r"Dual Window: Gaussian with $\sigma_t=1$")
+ >>> ax1.set(xlabel=f"Time $t$ in seconds ({N} samples, $T={T}$ s)",
+ ... xlim=(t[0], t[-1]), ylim=(0, 1.1*np.max(d_win)))
+ >>> ax1.plot(t, d_win, 'C0-')
+
+ The following plot with the overlap of 41, 11 and 2 samples show how
+ the `hop` interval affects the shape of the window `win`:
+
+ >>> fig2, axx = plt.subplots(3, 1, sharex='all')
+ ...
+ >>> axx[0].set_title(r"Windows for hop$\in\{10, 40, 49\}$")
+ >>> for c_, h_ in enumerate([10, 40, 49]):
+ ... SFT = ShortTimeFFT.from_dual(d_win, h_, 1/T)
+ ... axx[c_].plot(t + h_ * T, SFT.win, 'k--', alpha=.3, label=None)
+ ... axx[c_].plot(t - h_ * T, SFT.win, 'k:', alpha=.3, label=None)
+ ... axx[c_].plot(t, SFT.win, f'C{c_+1}',
+ ... label=r"$\Delta t=%0.1f\,$s" % SFT.delta_t)
+ ... axx[c_].set_ylim(0, 1.1*max(SFT.win))
+ ... axx[c_].legend(loc='center')
+ >>> axx[-1].set(xlabel=f"Time $t$ in seconds ({N} samples, $T={T}$ s)",
+ ... xlim=(t[0], t[-1]))
+ >>> plt.show()
+
+ Beside the window `win` centered at t = 0 the previous (t = -`delta_t`)
+ and following window (t = `delta_t`) are depicted. It can be seen that
+ for small `hop` intervals, the window is compact and smooth, having a
+ good time-frequency concentration in the STFT. For the large `hop`
+ interval of 4.9 s, the window has small values around t = 0, which are
+ not covered by the overlap of the adjacent windows, which could lead to
+ numeric inaccuracies. Furthermore, the peaky shape at the beginning and
+ the end of the window points to a higher bandwidth, resulting in a
+ poorer time-frequency resolution of the STFT.
+ Hence, the choice of the `hop` interval will be a compromise between
+ a time-frequency resolution and memory requirements demanded by small
+ `hop` sizes.
+
+ See Also
+ --------
+ from_window: Create instance by wrapping `get_window`.
+ ShortTimeFFT: Create instance using standard initializer.
+ """
+ win = _calc_dual_canonical_window(dual_win, hop)
+ return cls(win=win, hop=hop, fs=fs, fft_mode=fft_mode, mfft=mfft,
+ dual_win=dual_win, scale_to=scale_to,
+ phase_shift=phase_shift)
+
+ @classmethod
+ def from_window(cls, win_param: str | tuple | float,
+ fs: float, nperseg: int, noverlap: int, *,
+ symmetric_win: bool = False,
+ fft_mode: FFT_MODE_TYPE = 'onesided',
+ mfft: int | None = None,
+ scale_to: Literal['magnitude', 'psd'] | None = None,
+ phase_shift: int | None = 0):
+ """Instantiate `ShortTimeFFT` by using `get_window`.
+
+ The method `get_window` is used to create a window of length
+ `nperseg`. The parameter names `noverlap`, and `nperseg` are used here,
+ since they more inline with other classical STFT libraries.
+
+ Parameters
+ ----------
+ win_param: Union[str, tuple, float],
+ Parameters passed to `get_window`. For windows with no parameters,
+ it may be a string (e.g., ``'hann'``), for parametrized windows a
+ tuple, (e.g., ``('gaussian', 2.)``) or a single float specifying
+ the shape parameter of a kaiser window (i.e. ``4.`` and
+ ``('kaiser', 4.)`` are equal. See `get_window` for more details.
+ fs : float
+ Sampling frequency of input signal. Its relation to the
+ sampling interval `T` is ``T = 1 / fs``.
+ nperseg: int
+ Window length in samples, which corresponds to the `m_num`.
+ noverlap: int
+ Window overlap in samples. It relates to the `hop` increment by
+ ``hop = npsereg - noverlap``.
+ symmetric_win: bool
+ If ``True`` then a symmetric window is generated, else a periodic window is
+ generated (default). Though symmetric windows seem for most applications to
+ be more sensible, the default of a periodic windows was chosen to
+ correspond to the default of `get_window`. This parameter is ignored, if
+ the window name in the `window` parameter has a suffix ``'_periodic'`` or
+ ``'_symmetric'`` appended to it (e.g., ``'hann_symmetric'``).
+ fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X'
+ Mode of FFT to be used (default 'onesided').
+ See property `fft_mode` for details.
+ mfft: int | None
+ Length of the FFT used, if a zero padded FFT is desired.
+ If ``None`` (default), the length of the window `win` is used.
+ scale_to : 'magnitude', 'psd' | None
+ If not ``None`` (default) the window function is scaled, so each
+ STFT column represents either a 'magnitude' or a power spectral
+ density ('psd') spectrum. This parameter sets the property
+ `scaling` to the same value. See method `scale_to` for details.
+ phase_shift : int | None
+ If set, add a linear phase `phase_shift` / `mfft` * `f` to each
+ frequency `f`. The default value 0 ensures that there is no phase
+ shift on the zeroth slice (in which t=0 is centered). See property
+ `phase_shift` for more details.
+
+ Examples
+ --------
+ The following instances ``SFT0`` and ``SFT1`` are equivalent:
+
+ >>> from scipy.signal import ShortTimeFFT, get_window
+ >>> nperseg = 9 # window length
+ >>> w = get_window(('gaussian_periodic', 2.), nperseg)
+ >>> fs = 128 # sampling frequency
+ >>> hop = 3 # increment of STFT time slice
+ >>> SFT0 = ShortTimeFFT(w, hop, fs=fs)
+ >>> SFT1 = ShortTimeFFT.from_window(('gaussian', 2.), fs, nperseg,
+ ... noverlap=nperseg-hop)
+
+ See Also
+ --------
+ scipy.signal.get_window: Return a window of a given length and type.
+ from_dual: Create instance using dual window.
+ ShortTimeFFT: Create instance using standard initializer.
+ """
+ win = get_window(win_param, nperseg, fftbins=not symmetric_win)
+ return cls(win, hop=nperseg-noverlap, fs=fs, fft_mode=fft_mode,
+ mfft=mfft, scale_to=scale_to, phase_shift=phase_shift)
+
+ @classmethod
+ def from_win_equals_dual(
+ cls, desired_win: np.ndarray, hop: int, fs: float, *,
+ fft_mode: FFT_MODE_TYPE = 'onesided', mfft: int | None = None,
+ scale_to: Literal['magnitude', 'psd', 'unitary'] | None = None,
+ phase_shift: int | None = 0):
+ r"""Create instance where the window and its dual are equal up to a
+ scaling factor.
+
+ An instance is created were window and dual window are equal as well as being
+ closest to the parameter `desired_win` in the least-squares sense, i.e.,
+ minimizing ``abs(win-desired_win)**2``. Hence, `win` has the same length as
+ `desired_win`. Then a scaling factor is applied accoring to the `scale_to`
+ parameter.
+
+ All other parameters have the identical meaning as in the initializer.
+
+ To be able to calculate a valid window, `desired_win` needs to have a valid
+ dual STFT window for the given `hop` interval.
+ If this is not the case, a ``ValueError`` is raised.
+
+ Parameters
+ ----------
+ desired_win : np.ndarray
+ A real-valued or complex-valued 1d array containing the sample of the
+ desired window.
+ hop : int
+ The increment in samples, by which the window is shifted in each step.
+ fs : float
+ Sampling frequency of input signal and window. Its relation to the
+ sampling interval `T` is ``T = 1 / fs``.
+ fft_mode : 'twosided', 'centered', 'onesided', 'onesided2X'
+ Mode of FFT to be used (default 'onesided').
+ See property `fft_mode` for details.
+ mfft: int | None
+ Length of the FFT used, if a zero padded FFT is desired.
+ If ``None`` (default), the length of the window `win` is used.
+ scale_to : 'magnitude' | 'psd' | 'unitary' | None
+ If not ``None`` (default) the window function is scaled, so each STFT
+ column represents either a 'magnitude' or a power spectral density ('psd')
+ spectrum, Alternatively, the STFT can be scaled to a`unitary` mapping,
+ i.e., dividing the window by ``np.sqrt(mfft)`` and multiplying the dual
+ window by the same amount.
+ phase_shift : int | None
+ If set, add a linear phase `phase_shift` / `mfft` * `f` to each
+ frequency `f`. The default value of 0 ensures that there is no phase shift
+ on the zeroth slice (in which t=0 is centered). See property
+ `phase_shift` for more details.
+
+
+ Notes
+ -----
+ The set of all possible windows with identical dual is defined by the set of
+ linear constraints of Eq. :math:numref:`eq_STFT_AllDualWinsCond` in the
+ :ref:`tutorial_stft` section of the :ref:`user_guide`. There it is also
+ derived that ``ShortTimeFFT.dual_win == ShortTimeFFT.m_pts * ShortTimeFFT.win``
+ needs to hold for an STFT to be a unitary mapping.
+
+ A unitary mapping preserves the value of the scalar product, i.e.,
+
+ .. math::
+
+ \langle x, y\rangle = \sum_k x[k]\, \overline{y[k]}
+ \stackrel{\stackrel{\text{unitary}}{\downarrow}}{=}
+ \sum_{q,p} S_x[q,p]\, \overline{S_y[q,p]}
+ = \langle S_x[q,p], S_y[q,p]\rangle\ ,
+
+ with :math:`S_{x,y}` being the STFT of :math:`x,y`. Hence, the energy
+ :math:`E_x=T\sum_k |x[k]|^2` of a signal is also preserved. This is also
+ illustrated in the example below.
+
+ Thie reason of distinguishing between no scaling (i.e., parameter `scale_to` is
+ ``None``) and unitary scaling (i.e., ``scale_to = 'unitary'``) is due to the
+ utilized FFT function not being unitary (i.e., using the default value
+ ``'backward'`` for the `~scipy.fft.fft` parameter `norm`).
+
+
+ See Also
+ --------
+ closest_STFT_dual_window: Calculate the STFT dual window of a given window
+ closest to a desired dual window.
+ ShortTimeFFT.spectrogram: Calculate squared STFTs
+ ShortTimeFFT: Class this property belongs to.
+
+ Examples
+ --------
+ The following example shows that an STFT can be indeed unitary:
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.signal import ShortTimeFFT, windows
+ ...
+ >>> m, hop, std = 36, 8, 5
+ >>> desired_win = windows.gaussian(m, std, sym=True)
+ >>> SFT = ShortTimeFFT.from_win_equals_dual(desired_win, hop, fs=1/m,
+ ... fft_mode='twosided',
+ ... scale_to='unitary')
+ >>> np.allclose(SFT.dual_win, SFT.win * SFT.m_num) # check if STFT is unitary
+ True
+ >>> x1, x2 = np.tile([-1, -1, 1, 1], 5), np.tile([1, -1, -1, 1], 5)
+ >>> np.sum(x1*x2) # scalar product is zero -> orthogonal signals
+ 0
+ >>> np.sum(x1**2) # scalar product of x1 with itself
+ 20
+ >>> Sx11, Sx12 = SFT.spectrogram(x1), SFT.spectrogram(x1, x2)
+ >>> np.sum(Sx12) # STFT scalar product is also zero
+ -4.163336342344337e-16+0j # may vary
+ >>> np.sum(Sx11) # == np.sum(x1**2)
+ 19.999999999999996 # may vary
+ ...
+ ... # Do the plotting:
+ >>> fg1, (ax11, ax12) = plt.subplots(1, 2, tight_layout=True, figsize=(8, 4))
+ >>> s_fac = np.sqrt(SFT.mfft)
+ >>> _ = fg1.suptitle(f"Scaled Unitary Window of {m} Sample Gaussian with " +
+ ... rf"{hop=}, $\sigma={std}$, Scale factor: {s_fac}")
+ >>> ax11.set(ylabel="Amplitude", xlabel="Samples", xlim=(0, m))
+ >>> ax12.set(xlabel="Frequency Bins", ylabel="Magnitude Spectrum",
+ ... xlim=(0, 15), ylim=(1e-5, 1.5))
+ >>> u_win_str = rf"Unitary $\times{s_fac:g}$"
+ >>> for x_, n_ in zip((desired_win, SFT.win*s_fac), ('Desired', u_win_str)):
+ ... ax11.plot(x_, '.-', alpha=0.5, label=n_)
+ ... X_ = np.fft.rfft(x_) / np.sum(abs(x_))
+ ... ax12.semilogy(abs(X_), '.-', alpha=0.5, label=n_)
+ >>> for ax_ in (ax11, ax12):
+ ... ax_.grid(True)
+ ... ax_.legend()
+ >>> plt.show()
+
+ Note that ``fftmode='twosided'`` is used, since we need sum over the complete
+ time frequency plane. Due to passing ``scale_to='unitary'`` the window
+ ``SFT.win`` is scaled by ``1/np.sqrt(SFT.mfft)``. Hence, ``SFT.win`` needs to
+ be scaled by `s_fac` in the plot above.
+ """
+ if not (desired_win.ndim == 1 and desired_win.size > 0):
+ raise ValueError(f"Parameter desired_win is not 1d, but "
+ f"{desired_win.shape=}!")
+ if issubclass(desired_win.dtype.type, np.integer):
+ raise ValueError("Parameter desired_win cannot be of integer type, " +
+ f"but {desired_win.dtype=} => cast to float | complex ")
+ if not all(np.isfinite(desired_win)):
+ raise ValueError("Parameter desired_win must have finite entries!")
+ if not (1 <= hop <= len(desired_win) and isinstance(hop, int | np.integer)):
+ raise ValueError(f"Parameter {hop=} is not an integer between 1 and " +
+ f"{len(desired_win)=}!")
+ if scale_to not in ['magnitude', 'psd', 'unitary', None]:
+ raise ValueError(f"Parameter {scale_to=} not in " +
+ "['magnitude', 'psd', 'unitary', None]!")
+
+ mfft = len(desired_win) if mfft is None else mfft
+ s_fac = np.sqrt(mfft) if scale_to == 'unitary' else 1
+
+ win = desired_win.copy() # we do not want to modify input parameters
+ relative_resolution = np.finfo(win.dtype).resolution * max(win)
+ for m in range(hop):
+ a = np.linalg.norm(desired_win[m::hop])
+ if not (a > relative_resolution):
+ raise ValueError("Parameter desired_win does not have valid STFT dual "
+ f"window for {hop=}!")
+ win[m::hop] /= a
+
+ SFT = cls(win=win/s_fac, hop=hop, fs=fs, fft_mode=fft_mode, mfft=mfft,
+ dual_win=win*s_fac, phase_shift=phase_shift,
+ scale_to=None if scale_to=='unitary' else scale_to)
+
+ if scale_to == 'unitary':
+ SFT._scaling = scale_to
+ return SFT
+
+
+ @property
+ def win(self) -> np.ndarray:
+ """Window function as real- or complex-valued 1d array.
+
+ This attribute is read-only, since `dual_win` depends on it.
+ To make this array immutable, its WRITEABLE flag is set to ``FALSE``.
+
+ See Also
+ --------
+ dual_win: Dual window.
+ m_num: Number of samples in window `win`.
+ m_num_mid: Center index of window `win`.
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
+ hop: ime increment in signal samples for sliding window.
+ win: Window function as real- or complex-valued 1d array.
+ numpy.ndarray.setflags: Modify array flags.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._win
+
+ @property
+ def hop(self) -> int:
+ """Time increment in signal samples for sliding window.
+
+ This attribute is read only, since `dual_win` depends on it.
+
+ See Also
+ --------
+ delta_t: Time increment of STFT (``hop*T``)
+ m_num: Number of samples in window `win`.
+ m_num_mid: Center index of window `win`.
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
+ T: Sampling interval of input signal and of the window.
+ win: Window function as real- or complex-valued 1d array.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._hop
+
+ @property
+ def T(self) -> float:
+ """Sampling interval of input signal and of the window.
+
+ A ``ValueError`` is raised if it is set to a non-positive value.
+
+ See Also
+ --------
+ delta_t: Time increment of STFT (``hop*T``)
+ hop: Time increment in signal samples for sliding window.
+ fs: Sampling frequency (being ``1/T``)
+ t: Times of STFT for an input signal with `n` samples.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return 1 / self._fs
+
+ @T.setter
+ def T(self, v: float):
+ """Sampling interval of input signal and of the window.
+
+ A ``ValueError`` is raised if it is set to a non-positive value.
+ """
+ if not (v > 0):
+ raise ValueError(f"Sampling interval T={v} must be positive!")
+ self._fs = 1 / v
+
+ @property
+ def fs(self) -> float:
+ """Sampling frequency of input signal and of the window.
+
+ The sampling frequency is the inverse of the sampling interval `T`.
+ A ``ValueError`` is raised if it is set to a non-positive value.
+
+ See Also
+ --------
+ delta_t: Time increment of STFT (``hop*T``)
+ hop: Time increment in signal samples for sliding window.
+ T: Sampling interval of input signal and of the window (``1/fs``).
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._fs
+
+ @fs.setter
+ def fs(self, v: float):
+ """Sampling frequency of input signal and of the window.
+
+ The sampling frequency is the inverse of the sampling interval `T`.
+ A ``ValueError`` is raised if it is set to a non-positive value.
+ """
+ if not (v > 0):
+ raise ValueError(f"Sampling frequency fs={v} must be positive!")
+ self._fs = v
+
+ @property
+ def fft_mode(self) -> FFT_MODE_TYPE:
+ """Mode of utilized FFT ('twosided', 'centered', 'onesided' or
+ 'onesided2X').
+
+ It can have the following values:
+
+ 'twosided':
+ Two-sided FFT, where values for the negative frequencies are in
+ upper half of the array. Corresponds to :func:`~scipy.fft.fft()`.
+ 'centered':
+ Two-sided FFT with the values being ordered along monotonically
+ increasing frequencies. Corresponds to applying
+ :func:`~scipy.fft.fftshift()` to :func:`~scipy.fft.fft()`.
+ 'onesided':
+ Calculates only values for non-negative frequency values.
+ Corresponds to :func:`~scipy.fft.rfft()`.
+ 'onesided2X':
+ Like `onesided`, but the non-zero frequencies are doubled if
+ `scaling` is set to 'magnitude' or multiplied by ``sqrt(2)`` if
+ set to 'psd'. If `scaling` is ``None``, setting `fft_mode` to
+ `onesided2X` is not allowed.
+ If the FFT length `mfft` is even, the last FFT value is not paired,
+ and thus it is not scaled.
+
+ Note that `onesided` and `onesided2X` do not work for complex-valued signals or
+ complex-valued windows. Furthermore, the frequency values can be obtained by
+ reading the `f` property, and the number of samples by accessing the `f_pts`
+ property.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ f: Frequencies values of the STFT.
+ f_pts: Width of the frequency bins of the STFT.
+ onesided_fft: True if a one-sided FFT is used.
+ scaling: Normalization applied to the window function
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._fft_mode
+
+ @fft_mode.setter
+ def fft_mode(self, t: FFT_MODE_TYPE):
+ """Set mode of FFT.
+
+ Allowed values are 'twosided', 'centered', 'onesided', 'onesided2X'.
+ See the property `fft_mode` for more details.
+ """
+ if t not in (fft_mode_types := get_args(FFT_MODE_TYPE)):
+ raise ValueError(f"fft_mode='{t}' not in {fft_mode_types}!")
+
+ if t in {'onesided', 'onesided2X'} and np.iscomplexobj(self.win):
+ raise ValueError(f"One-sided spectra, i.e., fft_mode='{t}', " +
+ "are not allowed for complex-valued windows!")
+
+ if t == 'onesided2X' and self.scaling is None:
+ raise ValueError(f"For scaling is None, fft_mode='{t}' is invalid!"
+ "Do scale_to('psd') or scale_to('magnitude')!")
+ self._fft_mode = t
+
+ @property
+ def mfft(self) -> int:
+ """Length of input for the FFT used - may be larger than window
+ length `m_num`.
+
+ If not set, `mfft` defaults to the window length `m_num`.
+
+ See Also
+ --------
+ f_pts: Number of points along the frequency axis.
+ f: Frequencies values of the STFT.
+ m_num: Number of samples in window `win`.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._mfft
+
+ @mfft.setter
+ def mfft(self, n_: int):
+ """Setter for the length of FFT utilized.
+
+ See the property `mfft` for further details.
+ """
+ if not (n_ >= self.m_num):
+ raise ValueError(f"Attribute mfft={n_} needs to be at least the " +
+ f"window length m_num={self.m_num}!")
+ self._mfft = n_
+
+ @property
+ def scaling(self) -> Literal['magnitude', 'psd', 'unitary'] | None:
+ """Normalization applied to the window function
+ ('magnitude', 'psd', 'unitary', or ``None``).
+
+ If not ``None``, the FFT slices may be either interpreted as a `magnitude` or
+ a power spectral density spectrum (`psd`). If set to `unitary`, the STFT may be
+ interpreted as a unitary mapping, i.e., preserving the value of the scalar
+ product.
+
+ The window function can be scaled by calling the `scale_to` method,
+ or it is set by the initializer parameter ``scale_to``. Note that a
+ window cannot to be scaled to be `unitary`. Use `from_win_equals_dual`
+ to create a unitary `ShortTimeFFT` instance.
+
+ See Also
+ --------
+ fac_magnitude: Scaling factor for to a magnitude spectrum.
+ fac_psd: Scaling factor for to a power spectral density spectrum.
+ fft_mode: Mode of utilized FFT
+ scale_to: Scale window to obtain 'magnitude' or 'psd' scaling.
+ from_win_equals_dual: Class-method for creating a unitary instance.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._scaling
+
+ def scale_to(self, scaling: Literal['magnitude', 'psd']):
+ """Scale window to obtain 'magnitude' or 'psd' scaling for the STFT.
+
+ The window of a 'magnitude' spectrum has an integral of one, i.e., unit
+ area for non-negative windows. This ensures that absolute the values of
+ spectrum does not change if the length of the window changes (given
+ the input signal is stationary).
+
+ To represent the power spectral density ('psd') for varying length
+ windows the area of the absolute square of the window needs to be
+ unity.
+
+ The `scaling` property shows the current scaling. The properties
+ `fac_magnitude` and `fac_psd` show the scaling factors required to
+ scale the STFT values to a magnitude or a psd spectrum.
+
+ Note that a window cannot to be scaled to be `unitary`. Use
+ `from_win_equals_dual` to create a unitary `ShortTimeFFT` instance.
+
+ This method is called, if the initializer parameter `scale_to` is set.
+
+ See Also
+ --------
+ fac_magnitude: Scaling factor for to a magnitude spectrum.
+ fac_psd: Scaling factor for to a power spectral density spectrum.
+ fft_mode: Mode of utilized FFT
+ scaling: Normalization applied to the window function.
+ ShortTimeFFT: Class this method belongs to.
+ """
+ if scaling not in (scaling_values := {'magnitude', 'psd'}):
+ raise ValueError(f"{scaling=} not in {scaling_values}!")
+ if self._scaling == scaling: # do nothing
+ return
+
+ s_fac = self.fac_psd if scaling == 'psd' else self.fac_magnitude
+ self._win = self._win * s_fac
+ self.win.setflags(write=False)
+ if self._dual_win is not None:
+ self._dual_win = self._dual_win / s_fac
+ self.dual_win.setflags(write=False)
+ self._fac_mag, self._fac_psd = None, None # reset scaling factors
+ self._scaling = scaling
+
+ @property
+ def phase_shift(self) -> int | None:
+ """If set, add linear phase `phase_shift` / `mfft` * `f` to each FFT
+ slice of frequency `f`.
+
+ Shifting (more precisely `rolling`) an `mfft`-point FFT input by
+ `phase_shift` samples results in a multiplication of the output by
+ ``np.exp(2j*np.pi*q*phase_shift/mfft)`` at the frequency q * `delta_f`.
+
+ The default value 0 ensures that there is no phase shift on the
+ zeroth slice (in which t=0 is centered).
+ No phase shift (``phase_shift is None``) is equivalent to
+ ``phase_shift = -mfft//2``. In this case slices are not shifted
+ before calculating the FFT.
+
+ The absolute value of `phase_shift` is limited to be less than `mfft`.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ f: Frequencies values of the STFT.
+ mfft: Length of input for the FFT used
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._phase_shift
+
+ @phase_shift.setter
+ def phase_shift(self, v: int | None):
+ """The absolute value of the phase shift needs to be less than mfft
+ samples.
+
+ See the `phase_shift` getter method for more details.
+ """
+ if v is None:
+ self._phase_shift = v
+ return
+ if not isinstance(v, int | np.integer):
+ raise ValueError(f"phase_shift={v} has the unit samples. Hence " +
+ "it needs to be an int or it may be None!")
+ if not (-self.mfft < v < self.mfft):
+ raise ValueError("-mfft < phase_shift < mfft does not hold " +
+ f"for mfft={self.mfft}, phase_shift={v}!")
+ self._phase_shift = v
+
+ def _x_slices(self, x: np.ndarray, k_off: int, p0: int, p1: int,
+ padding: PAD_TYPE) -> Generator[np.ndarray, None, None]:
+ """Generate signal slices along last axis of `x`.
+
+ This method is only used by `stft_detrend`. The parameters are
+ described in `~ShortTimeFFT.stft`.
+ """
+ if padding not in (padding_types := get_args(PAD_TYPE)):
+ raise ValueError(f"Parameter {padding=} not in {padding_types}!")
+ pad_kws: dict[str, dict] = { # possible keywords to pass to np.pad:
+ 'zeros': dict(mode='constant', constant_values=(0, 0)),
+ 'edge': dict(mode='edge'),
+ 'even': dict(mode='reflect', reflect_type='even'),
+ 'odd': dict(mode='reflect', reflect_type='odd'),
+ } # typing of pad_kws is needed to make mypy happy
+
+ n, n1 = x.shape[-1], (p1 - p0) * self.hop
+ k0 = p0 * self.hop - self.m_num_mid + k_off # start sample
+ k1 = k0 + n1 + self.m_num # end sample
+
+ i0, i1 = max(k0, 0), min(k1, n) # indexes to shorten x
+ # dimensions for padding x:
+ pad_width = [(0, 0)] * (x.ndim-1) + [(-min(k0, 0), max(k1 - n, 0))]
+
+ x1 = np.pad(x[..., i0:i1], pad_width, **pad_kws[padding])
+ for k_ in range(0, n1, self.hop):
+ yield x1[..., k_:k_ + self.m_num]
+
+ def stft(self, x: np.ndarray, p0: int | None = None,
+ p1: int | None = None, *, k_offset: int = 0,
+ padding: PAD_TYPE = 'zeros', axis: int = -1) \
+ -> np.ndarray:
+ """Perform the short-time Fourier transform.
+
+ A two-dimensional matrix with ``p1-p0`` columns is calculated.
+ The `f_pts` rows represent value at the frequencies `f`. The q-th
+ column of the windowed FFT with the window `win` is centered at t[q].
+ The columns represent the values at the frequencies `f`.
+
+ Parameters
+ ----------
+ x : np.ndarray
+ The input signal as real or complex valued array. For complex values, the
+ property `fft_mode` must be set to 'twosided' or 'centered'.
+ p0 : int | None
+ The first element of the range of slices to calculate. If ``None``
+ then it is set to :attr:`p_min`, which is the smallest possible
+ slice.
+ p1 : int | None
+ The end of the array. If ``None`` then `p_max(n)` is used.
+ k_offset : int
+ Index of first sample (t = 0) in `x`.
+ padding : 'zeros' | 'edge' | 'even' | 'odd'
+ Kind of values which are added, when the sliding window sticks out
+ on either the lower or upper end of the input `x`. Zeros are added
+ if the default 'zeros' is set. For 'edge' either the first or the
+ last value of `x` is used. 'even' pads by reflecting the
+ signal on the first or last sample and 'odd' additionally
+ multiplies it with -1.
+ axis : int
+ The axis of `x` over which to compute the STFT.
+ If not given, the last axis is used.
+
+ Returns
+ -------
+ S : np.ndarray
+ A complex array is returned with the dimension always being larger
+ by one than of `x`. The last axis always represents the time slices
+ of the STFT. `axis` defines the frequency axis (default second to
+ last). E.g., for a one-dimensional `x`, a complex 2d array is
+ returned, with axis 0 representing frequency and axis 1 the time
+ slices.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ delta_t: Time increment of STFT
+ f: Frequencies values of the STFT.
+ invertible: Check if STFT is invertible.
+ :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform.
+ p_range: Determine and validate slice index range.
+ stft_detrend: STFT with detrended segments.
+ t: Times of STFT for an input signal with `n` samples.
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
+ """
+ return self.stft_detrend(x, None, p0, p1, k_offset=k_offset,
+ padding=padding, axis=axis)
+
+ def stft_detrend(self, x: np.ndarray,
+ detr: Callable[[np.ndarray], np.ndarray] | Literal['linear', 'constant'] | None, # noqa: E501
+ p0: int | None = None, p1: int | None = None, *,
+ k_offset: int = 0, padding: PAD_TYPE = 'zeros',
+ axis: int = -1) \
+ -> np.ndarray:
+ """Calculate short-time Fourier transform with a trend being subtracted from
+ each segment beforehand.
+
+ When the parameter `detr` is ``None``, this method's behavior is identical to
+ the `~ShortTimeFFT.stft` method. Note that due to the detrending, the original
+ signal cannot be reconstructed by the `~ShortTimeFFT.istft`.
+
+ Parameters
+ ----------
+ x : np.ndarray
+ The input signal as real or complex valued array. For complex values, the
+ property `fft_mode` must be set to 'twosided' or 'centered'.
+ detr : 'linear' | 'constant' | Callable[[np.ndarray], np.ndarray] | None
+ If 'constant', the mean is subtracted, if set to "linear", the linear
+ trend is removed from each segment. This is achieved by calling
+ `~scipy.signal.detrend`. If `detr` is a function with one parameter, `detr`
+ is applied to each segment.
+ p0 : int | None
+ The first element of the range of slices to calculate. If ``None``
+ then it is set to :attr:`p_min`, which is the smallest possible
+ slice.
+ p1 : int | None
+ The end of the array. If ``None`` then `p_max(n)` is used.
+ k_offset : int
+ Index of first sample (t = 0) in `x`.
+ padding : 'zeros' | 'edge' | 'even' | 'odd'
+ Kind of values which are added, when the sliding window sticks out
+ on either the lower or upper end of the input `x`. Zeros are added
+ if the default 'zeros' is set. For 'edge' either the first or the
+ last value of `x` is used. 'even' pads by reflecting the
+ signal on the first or last sample and 'odd' additionally
+ multiplies it with -1.
+ axis: int
+ The axis of `x` over which to compute the STFT.
+ If not given, the last axis is used.
+
+ Returns
+ -------
+ S : np.ndarray
+ A complex array is returned with the dimension always being larger
+ by one than of `x`. The last axis always represents the time slices
+ of the STFT. `axis` defines the frequency axis (default second to
+ last). E.g., for a one-dimensional `x`, a complex 2d array is
+ returned, with axis 0 representing frequency and axis 1 the time
+ slices.
+
+ See Also
+ --------
+ invertible: Check if STFT is invertible.
+ :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform.
+ :meth:`~ShortTimeFFT.stft`: Short-time Fourier transform
+ (without detrending).
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
+ """
+ if self.onesided_fft and np.iscomplexobj(x):
+ raise ValueError(f"Complex-valued `x` not allowed for {self.fft_mode=}'! "
+ "Set property `fft_mode` to 'twosided' or 'centered'.")
+ if isinstance(detr, str):
+ detr = partial(detrend, type=detr)
+ elif not (detr is None or callable(detr)):
+ raise ValueError(f"Parameter {detr=} is not a str, function or " +
+ "None!")
+ n = x.shape[axis]
+ if not (n >= (m2p := self.m_num-self.m_num_mid)):
+ e_str = f'{len(x)=}' if x.ndim == 1 else f'of {axis=} of {x.shape}'
+ raise ValueError(f"{e_str} must be >= ceil(m_num/2) = {m2p}!")
+
+ if x.ndim > 1: # motivated by the NumPy broadcasting mechanisms:
+ x = np.moveaxis(x, axis, -1)
+ # determine slice index range:
+ p0, p1 = self.p_range(n, p0, p1)
+ S_shape_1d = (self.f_pts, p1 - p0)
+ S_shape = x.shape[:-1] + S_shape_1d if x.ndim > 1 else S_shape_1d
+ S = np.zeros(S_shape, dtype=complex)
+ for p_, x_ in enumerate(self._x_slices(x, k_offset, p0, p1, padding)):
+ if detr is not None:
+ x_ = detr(x_)
+ S[..., :, p_] = self._fft_func(x_ * self.win.conj())
+ if x.ndim > 1:
+ return np.moveaxis(S, -2, axis if axis >= 0 else axis-1)
+ return S
+
+ def spectrogram(self, x: np.ndarray, y: np.ndarray | None = None,
+ detr: Callable[[np.ndarray], np.ndarray] | Literal['linear', 'constant'] | None = None, # noqa: E501
+ *,
+ p0: int | None = None, p1: int | None = None,
+ k_offset: int = 0, padding: PAD_TYPE = 'zeros',
+ axis: int = -1) \
+ -> np.ndarray:
+ r"""Calculate spectrogram or cross-spectrogram.
+
+ The spectrogram is the absolute square of the STFT, i.e., it is
+ ``abs(S[q,p])**2`` for given ``S[q,p]`` and thus is always
+ non-negative.
+ For two STFTs ``Sx[q,p], Sy[q,p]``, the cross-spectrogram is defined
+ as ``Sx[q,p] * np.conj(Sy[q,p])`` and is complex-valued.
+ This is a convenience function for calling `~ShortTimeFFT.stft` /
+ `stft_detrend`, hence all parameters are discussed there.
+
+ Parameters
+ ----------
+ x : np.ndarray
+ The input signal as real or complex valued array. For complex values, the
+ property `fft_mode` must be set to 'twosided' or 'centered'.
+ y : np.ndarray
+ The second input signal of the same shape as `x`. If ``None``, it is
+ assumed to be `x`. For complex values, the property `fft_mode` must be
+ set to 'twosided' or 'centered'.
+ detr : 'linear' | 'constant' | Callable[[np.ndarray], np.ndarray] | None
+ If 'constant', the mean is subtracted, if set to "linear", the linear
+ trend is removed from each segment. This is achieved by calling
+ `~scipy.signal.detrend`. If `detr` is a function with one parameter, `detr`
+ is applied to each segment. For ``None`` (default), no trends are removed.
+ p0 : int | None
+ The first element of the range of slices to calculate. If ``None``
+ then it is set to :attr:`p_min`, which is the smallest possible
+ slice.
+ p1 : int | None
+ The end of the array. If ``None`` then `p_max(n)` is used.
+ k_offset : int
+ Index of first sample (t = 0) in `x`.
+ padding : 'zeros' | 'edge' | 'even' | 'odd'
+ Kind of values which are added, when the sliding window sticks out
+ on either the lower or upper end of the input `x`. Zeros are added
+ if the default 'zeros' is set. For 'edge' either the first or the
+ last value of `x` is used. 'even' pads by reflecting the
+ signal on the first or last sample and 'odd' additionally
+ multiplies it with -1.
+ axis : int
+ The axis of `x` over which to compute the STFT.
+ If not given, the last axis is used.
+
+ Returns
+ -------
+ S_xy : np.ndarray
+ A real-valued array with non-negative values is returned, if ``x is y`` or
+ `y` is ``None``. The dimension is always by one larger than of `x`. The
+ last axis always represents the time slices of the spectrogram. `axis`
+ defines the frequency axis (default second to last). E.g., for a
+ one-dimensional `x`, a complex 2d array is returned, with axis 0
+ representing frequency and axis 1 the time slices.
+
+ Notes
+ -----
+ The cross-spectrogram may be interpreted as the time-frequency analogon of the
+ cross-spectral density (consult `csd`). The absolute square `|Sxy|²` of a
+ cross-spectrogram `Sxy` divided by the spectrograms `Sxx` and `Syy` can be
+ interpreted as a coherence spectrogram ``Cxy := abs(Sxy)**2 / (Sxx*Syy)``,
+ which is the time-frequency analogon to `~coherence`.
+
+ If the STFT is parametrized to be a unitary transform, i.e., utilitzing
+ `~from_win_equals_dual`, then the value of the scalar product, hence also the
+ energy, is preserved.
+
+ Examples
+ --------
+ The following example shows the spectrogram of a square wave with varying
+ frequency :math:`f_i(t)` (marked by a green dashed line in the plot) sampled
+ with 20 Hz. The utilized Gaussian window is 50 samples or 2.5 s long. For the
+ `ShortTimeFFT`, the parameter ``mfft=800`` (oversampling factor 16) and the
+ `hop` interval of 2 in was chosen to produce a sufficient number of points.
+
+ The plot's colormap is logarithmically scaled as the power spectral
+ density is in dB. The time extent of the signal `x` is marked by
+ vertical dashed lines, and the shaded areas mark the presence of border
+ effects.
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.signal import square, ShortTimeFFT
+ >>> from scipy.signal.windows import gaussian
+ ...
+ >>> T_x, N = 1 / 20, 1000 # 20 Hz sampling rate for 50 s signal
+ >>> t_x = np.arange(N) * T_x # time indexes for signal
+ >>> f_i = 5e-3*(t_x - t_x[N // 3])**2 + 1 # varying frequency
+ >>> x = square(2*np.pi*np.cumsum(f_i)*T_x) # the signal
+ ...
+ >>> g_std = 12 # standard deviation for Gaussian window in samples
+ >>> win = gaussian(50, std=g_std, sym=True) # symmetric Gaussian wind.
+ >>> SFT = ShortTimeFFT(win, hop=2, fs=1/T_x, mfft=800, scale_to='psd')
+ >>> Sx2 = SFT.spectrogram(x) # calculate absolute square of STFT
+ ...
+ >>> fig1, ax1 = plt.subplots(figsize=(6., 4.)) # enlarge plot a bit
+ >>> t_lo, t_hi = SFT.extent(N)[:2] # time range of plot
+ >>> ax1.set_title(rf"Spectrogram ({SFT.m_num*SFT.T:g}$\,s$ Gaussian " +
+ ... rf"window, $\sigma_t={g_std*SFT.T:g}\,$s)")
+ >>> ax1.set(xlabel=f"Time $t$ in seconds ({SFT.p_num(N)} slices, " +
+ ... rf"$\Delta t = {SFT.delta_t:g}\,$s)",
+ ... ylabel=f"Freq. $f$ in Hz ({SFT.f_pts} bins, " +
+ ... rf"$\Delta f = {SFT.delta_f:g}\,$Hz)",
+ ... xlim=(t_lo, t_hi))
+ >>> Sx_dB = 10 * np.log10(np.fmax(Sx2, 1e-4)) # limit range to -40 dB
+ >>> im1 = ax1.imshow(Sx_dB, origin='lower', aspect='auto',
+ ... extent=SFT.extent(N), cmap='magma')
+ >>> ax1.plot(t_x, f_i, 'g--', alpha=.5, label='$f_i(t)$')
+ >>> fig1.colorbar(im1, label='Power Spectral Density ' +
+ ... r"$20\,\log_{10}|S_x(t, f)|$ in dB")
+ ...
+ >>> # Shade areas where window slices stick out to the side:
+ >>> for t0_, t1_ in [(t_lo, SFT.lower_border_end[0] * SFT.T),
+ ... (SFT.upper_border_begin(N)[0] * SFT.T, t_hi)]:
+ ... ax1.axvspan(t0_, t1_, color='w', linewidth=0, alpha=.3)
+ >>> for t_ in [0, N * SFT.T]: # mark signal borders with vertical line
+ ... ax1.axvline(t_, color='c', linestyle='--', alpha=0.5)
+ >>> ax1.legend()
+ >>> fig1.tight_layout()
+ >>> plt.show()
+
+ The logarithmic scaling reveals the odd harmonics of the square wave,
+ which are reflected at the Nyquist frequency of 10 Hz. This aliasing
+ is also the main source of the noise artifacts in the plot.
+
+ See Also
+ --------
+ :meth:`~ShortTimeFFT.stft`: Perform the short-time Fourier transform.
+ stft_detrend: STFT with a trend subtracted from each segment.
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
+ """
+ Sx = self.stft_detrend(x, detr, p0, p1, k_offset=k_offset,
+ padding=padding, axis=axis)
+ if y is None or y is x: # do spectrogram:
+ return Sx.real**2 + Sx.imag**2
+ # Cross-spectrogram:
+ Sy = self.stft_detrend(y, detr, p0, p1, k_offset=k_offset,
+ padding=padding, axis=axis)
+ return Sx * Sy.conj()
+
+ @property
+ def dual_win(self) -> np.ndarray:
+ """Dual window (canonical dual window by default).
+
+ A STFT can be interpreted as the input signal being expressed as a
+ weighted sum of modulated and time-shifted dual windows. If no dual window is
+ given on instantiation, the canonical dual window, i.e., the window with the
+ minimal energy (i.e., minimal L²-norm) is calculated. Alternative means for
+ determining dual windows are provided by `closest_STFT_dual_window` and the
+ `from_win_equals_dual` class-method. Note that `win` is also always a
+ dual window of `dual_win`.
+
+ `dual_win` has same length as `win`, namely `m_num` samples.
+
+ If the dual window cannot be calculated a ``ValueError`` is raised.
+ This attribute is read only and calculated lazily.
+ To make this array immutable, its WRITEABLE flag is set to ``FALSE``.
+
+ See Also
+ --------
+ m_num: Number of samples in window `win` and `dual_win`.
+ win: Window function as real- or complex-valued 1d array.
+ from_win_equals_dual: Create instance where `win` and `dual_win` are equal.
+ closest_STFT_dual_window: Calculate dual window closest to a desired window.
+ numpy.ndarray.setflags: Modify array flags.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ if self._dual_win is None:
+ self._dual_win = _calc_dual_canonical_window(self.win, self.hop)
+ self.dual_win.setflags(write=False)
+ return self._dual_win
+
+ @property
+ def invertible(self) -> bool:
+ """Check if STFT is invertible.
+
+ This is achieved by trying to calculate the canonical dual window.
+
+ See Also
+ --------
+ :meth:`~ShortTimeFFT.istft`: Inverse short-time Fourier transform.
+ m_num: Number of samples in window `win` and `dual_win`.
+ dual_win: Dual window.
+ win: Window for STFT.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ try:
+ return len(self.dual_win) > 0 # call self.dual_win()
+ except ValueError:
+ return False
+
+ def istft(self, S: np.ndarray, k0: int = 0, k1: int | None = None, *,
+ f_axis: int = -2, t_axis: int = -1) \
+ -> np.ndarray:
+ """Inverse short-time Fourier transform.
+
+ It returns an array of dimension ``S.ndim - 1`` which is real
+ if `onesided_fft` is set, else complex. If the STFT is not
+ `invertible`, or the parameters are out of bounds a ``ValueError`` is
+ raised.
+
+ Parameters
+ ----------
+ S
+ A complex valued array where `f_axis` denotes the frequency
+ values and the `t-axis` dimension the temporal values of the
+ STFT values.
+ k0, k1
+ The start and the end index of the reconstructed signal. The
+ default (``k0 = 0``, ``k1 = None``) assumes that the maximum length
+ signal should be reconstructed.
+ f_axis, t_axis
+ The axes in `S` denoting the frequency and the time dimension.
+
+ Notes
+ -----
+ It is required that `S` has `f_pts` entries along the `f_axis`. For
+ the `t_axis` it is assumed that the first entry corresponds to
+ `p_min` * `delta_t` (being <= 0). The length of `t_axis` needs to be
+ compatible with `k1`. I.e., ``S.shape[t_axis] >= self.p_max(k1)`` must
+ hold, if `k1` is not ``None``. Else `k1` is set to `k_max` with::
+
+ q_max = S.shape[t_range] + self.p_min
+ k_max = (q_max - 1) * self.hop + self.m_num - self.m_num_mid
+
+ The :ref:`tutorial_stft` section of the :ref:`user_guide` discussed the
+ slicing behavior by means of an example.
+
+ See Also
+ --------
+ invertible: Check if STFT is invertible.
+ :meth:`~ShortTimeFFT.stft`: Perform Short-time Fourier transform.
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
+ """
+ if f_axis == t_axis:
+ raise ValueError(f"{f_axis=} may not be equal to {t_axis=}!")
+ if S.shape[f_axis] != self.f_pts:
+ raise ValueError(f"{S.shape[f_axis]=} must be equal to " +
+ f"{self.f_pts=} ({S.shape=})!")
+ n_min = self.m_num-self.m_num_mid # minimum signal length
+ if not (S.shape[t_axis] >= (q_num := self.p_num(n_min))):
+ raise ValueError(f"{S.shape[t_axis]=} needs to have at least " +
+ f"{q_num} slices ({S.shape=})!")
+ if t_axis != S.ndim - 1 or f_axis != S.ndim - 2:
+ t_axis = S.ndim + t_axis if t_axis < 0 else t_axis
+ f_axis = S.ndim + f_axis if f_axis < 0 else f_axis
+ S = np.moveaxis(S, (f_axis, t_axis), (-2, -1))
+
+ q_max = S.shape[-1] + self.p_min
+ k_max = (q_max - 1) * self.hop + self.m_num - self.m_num_mid
+
+ k1 = k_max if k1 is None else k1
+ if not (self.k_min <= k0 < k1 <= k_max):
+ raise ValueError(f"({self.k_min=}) <= ({k0=}) < ({k1=}) <= " +
+ f"({k_max=}) is false!")
+ if not (num_pts := k1 - k0) >= n_min:
+ raise ValueError(f"({k1=}) - ({k0=}) = {num_pts} has to be at " +
+ f"least the half the window length {n_min}!")
+
+ q0 = (k0 // self.hop + self.p_min if k0 >= 0 else # p_min always <= 0
+ k0 // self.hop)
+ q1 = min(self.p_max(k1), q_max)
+ k_q0, k_q1 = self.nearest_k_p(k0), self.nearest_k_p(k1, left=False)
+ n_pts = k_q1 - k_q0 + self.m_num - self.m_num_mid
+ x = np.zeros(S.shape[:-2] + (n_pts,),
+ dtype=float if self.onesided_fft else complex)
+ for q_ in range(q0, q1):
+ xs = self._ifft_func(S[..., :, q_ - self.p_min]) * self.dual_win
+ i0 = q_ * self.hop - self.m_num_mid
+ i1 = min(i0 + self.m_num, n_pts+k0)
+ j0, j1 = 0, i1 - i0
+ if i0 < k0: # xs sticks out to the left on x:
+ j0 += k0 - i0
+ i0 = k0
+ x[..., i0-k0:i1-k0] += xs[..., j0:j1]
+ x = x[..., :k1-k0]
+ if x.ndim > 1:
+ x = np.moveaxis(x, -1, f_axis if f_axis < x.ndim else t_axis)
+ return x
+
+ @property
+ def fac_magnitude(self) -> float:
+ """Factor to multiply the STFT values by to scale each frequency slice
+ to a magnitude spectrum.
+
+ It is 1 if attribute ``scaling == 'magnitude'``.
+ The window can be scaled to a magnitude spectrum by using the method
+ `scale_to`.
+
+ See Also
+ --------
+ fac_psd: Scaling factor for to a power spectral density spectrum.
+ scale_to: Scale window to obtain 'magnitude' or 'psd' scaling.
+ scaling: Normalization applied to the window function.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ if self.scaling == 'magnitude':
+ return 1
+ if self._fac_mag is None:
+ self._fac_mag = 1 / abs(sum(self.win))
+ return self._fac_mag
+
+ @property
+ def fac_psd(self) -> float:
+ """Factor to multiply the STFT values by to scale each frequency slice
+ to a power spectral density (PSD).
+
+ It is 1 if attribute ``scaling == 'psd'``.
+ The window can be scaled to a psd spectrum by using the method
+ `scale_to`.
+
+ See Also
+ --------
+ fac_magnitude: Scaling factor for to a magnitude spectrum.
+ scale_to: Scale window to obtain 'magnitude' or 'psd' scaling.
+ scaling: Normalization applied to the window function.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ if self.scaling == 'psd':
+ return 1
+ if self._fac_psd is None:
+ self._fac_psd = 1 / np.sqrt(
+ sum(self.win.real**2+self.win.imag**2) / self.T)
+ return self._fac_psd
+
+ @property
+ def m_num(self) -> int:
+ """Number of samples in window `win`.
+
+ Note that the FFT can be oversampled by zero-padding. This is achieved
+ by setting the `mfft` property.
+
+ See Also
+ --------
+ m_num_mid: Center index of window `win`.
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
+ hop: Time increment in signal samples for sliding window.
+ win: Window function as real- or complex-valued 1d array.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return len(self.win)
+
+ @property
+ def m_num_mid(self) -> int:
+ """Center index of window `win`.
+
+ For odd `m_num`, ``(m_num - 1) / 2`` is returned and
+ for even `m_num` (per definition) ``m_num / 2`` is returned.
+
+ See Also
+ --------
+ m_num: Number of samples in window `win`.
+ mfft: Length of input for the FFT used - may be larger than `m_num`.
+ hop: ime increment in signal samples for sliding window.
+ win: Window function as real- or complex-valued 1d array.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self.m_num // 2
+
+ @cached_property
+ def _pre_padding(self) -> tuple[int, int]:
+ """Smallest signal index and slice index due to padding.
+
+ Since, per convention, for time t=0, n,q is zero, the returned values
+ are negative or zero.
+ """
+ w2 = self.win.real**2 + self.win.imag**2
+ # move window to the left until the overlap with t >= 0 vanishes:
+ n0 = -self.m_num_mid
+ for p_, n_ in enumerate(range(n0, n0-self.m_num-1, -self.hop)):
+ n_next = n_ - self.hop
+ if n_next + self.m_num <= 0 or all(w2[n_next:] == 0):
+ return n_, -p_
+ # Make the linter happy:
+ raise RuntimeError("This code line should never run! Please file a bug.")
+
+ @property
+ def k_min(self) -> int:
+ """The smallest possible signal index of the STFT.
+
+ `k_min` is the index of the left-most non-zero value of the lowest
+ slice `p_min`. Since the zeroth slice is centered over the zeroth
+ sample of the input signal, `k_min` is never positive.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ See Also
+ --------
+ k_max: First sample index after signal end not touched by a time slice.
+ lower_border_end: Where pre-padding effects end.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ upper_border_begin: Where post-padding effects start.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._pre_padding[0]
+
+ @property
+ def p_min(self) -> int:
+ """The smallest possible slice index.
+
+ `p_min` is the index of the left-most slice, where the window still
+ sticks into the signal, i.e., has non-zero part for t >= 0.
+ `k_min` is the smallest index where the window function of the slice
+ `p_min` is non-zero.
+
+ Since, per convention the zeroth slice is centered at t=0,
+ `p_min` <= 0 always holds.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self._pre_padding[1]
+
+ def _post_padding(self, n: int) -> tuple[int, int]:
+ """Largest signal index and slice index due to padding.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples of input signal (must be ≥ half of the window length).
+
+ Notes
+ -----
+ Note that the return values are cached together with the parameter `n` to avoid
+ unnecessary recalculations.
+ """
+ if not (n >= (m2p := self.m_num - self.m_num_mid)):
+ raise ValueError(f"Parameter n must be >= ceil(m_num/2) = {m2p}!")
+ last_arg, last_return_value = self._cache_post_padding
+ if n == last_arg: # use cached value:
+ return last_return_value
+ w2 = self.win.real**2 + self.win.imag**2
+ # move window to the right until the overlap for t < t[n] vanishes:
+ q1 = n // self.hop # last slice index with t[p1] <= t[n]
+ k1 = q1 * self.hop - self.m_num_mid
+ for q_, k_ in enumerate(range(k1, n+self.m_num, self.hop), start=q1):
+ n_next = k_ + self.hop
+ if n_next >= n or all(w2[:n-n_next] == 0):
+ return_value = k_ + self.m_num, q_ + 1
+ self._cache_post_padding = n, return_value
+ return return_value
+ raise RuntimeError("This code line should never run! Please file a bug.")
+ # If this case is reached, it probably means the last slice should be
+ # returned, i.e.: return k1 + self.m_num - self.m_num_mid, q1 + 1
+
+ def k_max(self, n: int) -> int:
+ """First sample index after signal end not touched by a time slice.
+
+ `k_max` - 1 is the largest sample index of the slice `p_max` - 1 for a
+ given input signal of `n` samples.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples of input signal (must be ≥ half of the window length).
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ ShortTimeFFT: Class this method belongs to.
+ """
+ return self._post_padding(n)[0]
+
+ def p_max(self, n: int) -> int:
+ """Index of first non-overlapping upper time slice for `n` sample
+ input.
+
+ Note that center point t[p_max] = (p_max(n)-1) * `delta_t` is typically
+ larger than last time index t[n-1] == (`n`-1) * `T`. The upper border
+ of samples indexes covered by the window slices is given by `k_max`.
+ Furthermore, `p_max` does not denote the number of slices `p_num` since
+ `p_min` is typically less than zero.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ p_min: The smallest possible slice index.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ ShortTimeFFT: Class this method belongs to.
+ """
+ return self._post_padding(n)[1]
+
+ def p_num(self, n: int) -> int:
+ """Number of time slices for an input signal with `n` samples.
+
+ It is given by `p_num` = `p_max` - `p_min` with `p_min` typically
+ being negative.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ lower_border_end: Where pre-padding effects end.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_range: Determine and validate slice index range.
+ upper_border_begin: Where post-padding effects start.
+ ShortTimeFFT: Class this method belongs to.
+ """
+ return self.p_max(n) - self.p_min
+
+ @property
+ def lower_border_end(self) -> tuple[int, int]:
+ """First signal index and first slice index unaffected by pre-padding.
+
+ Describes the point where the window does not stick out to the left
+ of the signal domain.
+ A detailed example is provided in the :ref:`tutorial_stft_sliding_win`
+ section of the :ref:`user_guide`.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ lower_border_end: Where pre-padding effects end.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ upper_border_begin: Where post-padding effects start.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ if self._lower_border_end is not None:
+ return self._lower_border_end
+
+ # first non-zero element in self.win:
+ m0 = np.flatnonzero(self.win.real**2 + self.win.imag**2)[0]
+
+ # move window to the right until does not stick out to the left:
+ k0 = -self.m_num_mid + m0
+ for q_, k_ in enumerate(range(k0, self.hop + 1, self.hop)):
+ if k_ + self.hop >= 0: # next entry does not stick out anymore
+ self._lower_border_end = (k_ + self.m_num, q_ + 1)
+ return self._lower_border_end
+ self._lower_border_end = (0, max(self.p_min, 0)) # ends at first slice
+ return self._lower_border_end
+
+ def upper_border_begin(self, n: int) -> tuple[int, int]:
+ """First signal index and first slice index affected by post-padding.
+
+ Describes the point where the window does begin stick out to the right
+ of the signal domain.
+ A detailed example is given :ref:`tutorial_stft_sliding_win` section
+ of the :ref:`user_guide`.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples of input signal (must be ≥ half of the window length).
+
+ Returns
+ -------
+ k_ub : int
+ Lowest signal index, where a touching time slice sticks out past the
+ signal end.
+ p_ub : int
+ Lowest index of time slice of which the end sticks out past the signal end.
+
+ Notes
+ -----
+ Note that the return values are cached together with the parameter `n` to avoid
+ unnecessary recalculations.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ lower_border_end: Where pre-padding effects end.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ p_range: Determine and validate slice index range.
+ ShortTimeFFT: Class this method belongs to.
+ """
+ if not (n >= (m2p := self.m_num - self.m_num_mid)):
+ raise ValueError(f"Parameter n must be >= ceil(m_num/2) = {m2p}!")
+ last_arg, last_return_value = self._cache_upper_border_begin
+ if n == last_arg: # use cached value:
+ return last_return_value
+ w2 = self.win.real**2 + self.win.imag**2
+ q2 = n // self.hop + 1 # first t[q] >= t[n]
+ q1 = max((n-self.m_num) // self.hop - 1, -1)
+ # move window left until does not stick out to the right:
+ for q_ in range(q2, q1, -1):
+ k_ = q_ * self.hop + (self.m_num - self.m_num_mid)
+ if k_ <= n or all(w2[n-k_:] == 0):
+ return_value = (q_ + 1) * self.hop - self.m_num_mid, q_ + 1
+ self. _cache_upper_border_begin = n, return_value
+ return return_value
+ # make linter happy:
+ raise RuntimeError("This code line should never run! Please file a bug.")
+
+ @property
+ def delta_t(self) -> float:
+ """Time increment of STFT.
+
+ The time increment `delta_t` = `T` * `hop` represents the sample
+ increment `hop` converted to time based on the sampling interval `T`.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ hop: Hop size in signal samples for sliding window.
+ t: Times of STFT for an input signal with `n` samples.
+ T: Sampling interval of input signal and window `win`.
+ ShortTimeFFT: Class this property belongs to
+ """
+ return self.T * self.hop
+
+ def p_range(self, n: int, p0: int | None = None,
+ p1: int | None = None) -> tuple[int, int]:
+ """Determine and validate slice index range.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples of input signal, assuming t[0] = 0.
+ p0 : int | None
+ First slice index. If 0 then the first slice is centered at t = 0.
+ If ``None`` then `p_min` is used. Note that p0 may be < 0 if
+ slices are left of t = 0.
+ p1 : int | None
+ End of interval (last value is p1-1).
+ If ``None`` then `p_max(n)` is used.
+
+
+ Returns
+ -------
+ p0_ : int
+ The fist slice index
+ p1_ : int
+ End of interval (last value is p1-1).
+
+ Notes
+ -----
+ A ``ValueError`` is raised if ``p_min <= p0 < p1 <= p_max(n)`` does not
+ hold.
+
+ See Also
+ --------
+ k_min: The smallest possible signal index.
+ k_max: First sample index after signal end not touched by a time slice.
+ lower_border_end: Where pre-padding effects end.
+ p_min: The smallest possible slice index.
+ p_max: Index of first non-overlapping upper time slice.
+ p_num: Number of time slices, i.e., `p_max` - `p_min`.
+ upper_border_begin: Where post-padding effects start.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ p_max = self.p_max(n) # shorthand
+ p0_ = self.p_min if p0 is None else p0
+ p1_ = p_max if p1 is None else p1
+ if not (self.p_min <= p0_ < p1_ <= p_max):
+ raise ValueError(f"Invalid Parameter {p0=}, {p1=}, i.e., " +
+ f"{self.p_min=} <= p0 < p1 <= {p_max=} " +
+ f"does not hold for signal length {n=}!")
+ return p0_, p1_
+
+ def t(self, n: int, p0: int | None = None, p1: int | None = None,
+ k_offset: int = 0) -> np.ndarray:
+ """Times of STFT for an input signal with `n` samples.
+
+ Returns a 1d array with times of the `~ShortTimeFFT.stft` values with
+ the same parametrization. Note that the slices are
+ ``delta_t = hop * T`` time units apart.
+
+ Parameters
+ ----------
+ n
+ Number of sample of the input signal.
+ p0
+ The first element of the range of slices to calculate. If ``None``
+ then it is set to :attr:`p_min`, which is the smallest possible
+ slice.
+ p1
+ The end of the array. If ``None`` then `p_max(n)` is used.
+ k_offset
+ Index of first sample (t = 0) in `x`.
+
+ Notes
+ -----
+ Note that the returned array is cached together with the method's call
+ parameters to avoid unnecessary recalculations.
+
+ See Also
+ --------
+ delta_t: Time increment of STFT (``hop*T``)
+ hop: Time increment in signal samples for sliding window.
+ nearest_k_p: Nearest sample index k_p for which t[k_p] == t[p] holds.
+ T: Sampling interval of input signal and of the window (``1/fs``).
+ fs: Sampling frequency (being ``1/T``)
+ ShortTimeFFT: Class this method belongs to.
+ """
+ if not (n > 0 and isinstance(n, int | np.integer)):
+ raise ValueError(f"Parameter {n=} is not a positive integer!")
+ args = n, p0, p1, k_offset, self.T # since `self.T` is mutable, it's needed too
+ last_args, last_return_value = self._cache_t
+ if args == last_args: # use cached value:
+ return last_return_value
+
+ p0, p1 = self.p_range(n, p0, p1)
+ return_value = np.arange(p0, p1) * self.delta_t + k_offset * self.T
+
+ self._cache_t = args, return_value
+ return return_value
+
+ def nearest_k_p(self, k: int, left: bool = True) -> int:
+ """Return nearest sample index k_p for which t[k_p] == t[p] holds.
+
+ The nearest next smaller time sample p (where t[p] is the center
+ position of the window of the p-th slice) is p_k = k // `hop`.
+ If `hop` is a divisor of `k` then `k` is returned.
+ If `left` is set then p_k * `hop` is returned else (p_k+1) * `hop`.
+
+ This method can be used to slice an input signal into chunks for
+ calculating the STFT and iSTFT incrementally.
+
+ See Also
+ --------
+ delta_t: Time increment of STFT (``hop*T``)
+ hop: Time increment in signal samples for sliding window.
+ T: Sampling interval of input signal and of the window (``1/fs``).
+ fs: Sampling frequency (being ``1/T``)
+ t: Times of STFT for an input signal with `n` samples.
+ ShortTimeFFT: Class this method belongs to.
+ """
+ p_q, remainder = divmod(k, self.hop)
+ if remainder == 0:
+ return k
+ return p_q * self.hop if left else (p_q + 1) * self.hop
+
+ @property
+ def delta_f(self) -> float:
+ """Width of the frequency bins of the STFT.
+
+ Return the frequency interval `delta_f` = 1 / (`mfft` * `T`).
+
+ See Also
+ --------
+ delta_t: Time increment of STFT.
+ f_pts: Number of points along the frequency axis.
+ f: Frequencies values of the STFT.
+ mfft: Length of the input for FFT used.
+ T: Sampling interval.
+ t: Times of STFT for an input signal with `n` samples.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return 1 / (self.mfft * self.T)
+
+ @property
+ def f_pts(self) -> int:
+ """Number of points along the frequency axis.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ f: Frequencies values of the STFT.
+ mfft: Length of the input for FFT used.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self.mfft // 2 + 1 if self.onesided_fft else self.mfft
+
+ @property
+ def onesided_fft(self) -> bool:
+ """Return True if a one-sided FFT is used.
+
+ Returns ``True`` if `fft_mode` is either 'onesided' or 'onesided2X'.
+
+ See Also
+ --------
+ fft_mode: Utilized FFT ('twosided', 'centered', 'onesided' or
+ 'onesided2X')
+ ShortTimeFFT: Class this property belongs to.
+ """
+ return self.fft_mode in {'onesided', 'onesided2X'}
+
+ @property
+ def f(self) -> np.ndarray:
+ """Frequencies values of the STFT.
+
+ A 1d array of length `f_pts` with `delta_f` spaced entries is returned.
+ This array is calculated lazily.
+
+ See Also
+ --------
+ delta_f: Width of the frequency bins of the STFT.
+ f_pts: Number of points along the frequency axis.
+ mfft: Length of the input for FFT used.
+ ShortTimeFFT: Class this property belongs to.
+ """
+ last_state, last_return_value = self._cache_f
+ current_state = self.fft_mode, self.mfft, self.T
+ if current_state == last_state: # use cached value:
+ return last_return_value
+
+ if self.fft_mode in {'onesided', 'onesided2X'}:
+ return_value = fft_lib.rfftfreq(self.mfft, self.T)
+ elif self.fft_mode == 'twosided':
+ return_value = fft_lib.fftfreq(self.mfft, self.T)
+ elif self.fft_mode == 'centered':
+ return_value = fft_lib.fftshift(fft_lib.fftfreq(self.mfft, self.T))
+ else: # This should never happen but makes the Linters happy:
+ fft_modes = get_args(FFT_MODE_TYPE)
+ raise RuntimeError(f"{self.fft_mode=} not in {fft_modes}!")
+ self._cache_f = current_state, return_value
+ return return_value
+
+ def _fft_func(self, x: np.ndarray) -> np.ndarray:
+ """FFT based on the `fft_mode`, `mfft`, `scaling` and `phase_shift`
+ attributes.
+
+ For multidimensional arrays the transformation is carried out on the
+ last axis.
+ """
+ if self.phase_shift is not None:
+ if x.shape[-1] < self.mfft: # zero pad if needed
+ z_shape = list(x.shape)
+ z_shape[-1] = self.mfft - x.shape[-1]
+ x = np.hstack((x, np.zeros(z_shape, dtype=x.dtype)))
+ p_s = (self.phase_shift + self.m_num_mid) % self.m_num
+ x = np.roll(x, -p_s, axis=-1)
+
+ if self.fft_mode == 'twosided':
+ return fft_lib.fft(x, n=self.mfft, axis=-1)
+ if self.fft_mode == 'centered':
+ return fft_lib.fftshift(fft_lib.fft(x, self.mfft, axis=-1), axes=-1)
+ if self.fft_mode == 'onesided':
+ return fft_lib.rfft(x, n=self.mfft, axis=-1)
+ if self.fft_mode == 'onesided2X':
+ X = fft_lib.rfft(x, n=self.mfft, axis=-1)
+ # Either squared magnitude (psd) or magnitude is doubled:
+ fac = np.sqrt(2) if self.scaling == 'psd' else 2
+ # For even input length, the last entry is unpaired:
+ X[..., 1: -1 if self.mfft % 2 == 0 else None] *= fac
+ return X
+ # This should never happen but makes the Linter happy:
+ fft_modes = get_args(FFT_MODE_TYPE)
+ raise RuntimeError(f"{self.fft_mode=} not in {fft_modes}!")
+
+ def _ifft_func(self, X: np.ndarray) -> np.ndarray:
+ """Inverse to `_fft_func`.
+
+ Returned is an array of length `m_num`. If the FFT is `onesided`
+ then a float array is returned else a complex array is returned.
+ For multidimensional arrays the transformation is carried out on the
+ last axis.
+ """
+ if self.fft_mode == 'twosided':
+ x = fft_lib.ifft(X, n=self.mfft, axis=-1)
+ elif self.fft_mode == 'centered':
+ x = fft_lib.ifft(fft_lib.ifftshift(X, axes=-1), n=self.mfft, axis=-1)
+ elif self.fft_mode == 'onesided':
+ x = fft_lib.irfft(X, n=self.mfft, axis=-1)
+ elif self.fft_mode == 'onesided2X':
+ Xc = X.copy() # we do not want to modify function parameters
+ fac = np.sqrt(2) if self.scaling == 'psd' else 2
+ # For even length X the last value is not paired with a negative
+ # value on the two-sided FFT:
+ q1 = -1 if self.mfft % 2 == 0 else None
+ Xc[..., 1:q1] /= fac
+ x = fft_lib.irfft(Xc, n=self.mfft, axis=-1)
+ else: # This should never happen but makes the Linter happy:
+ raise RuntimeError(f"{self.fft_mode=} not in {get_args(FFT_MODE_TYPE)}!")
+
+ if self.phase_shift is None:
+ return x[..., :self.m_num]
+ p_s = (self.phase_shift + self.m_num_mid) % self.m_num
+ return np.roll(x, p_s, axis=-1)[..., :self.m_num]
+
+ def extent(self, n: int, axes_seq: Literal['tf', 'ft'] = 'tf',
+ center_bins: bool = False) -> tuple[float, float, float, float]:
+ """Return minimum and maximum values time-frequency values.
+
+ A tuple with four floats ``(t0, t1, f0, f1)`` for 'tf' and
+ ``(f0, f1, t0, t1)`` for 'ft' is returned describing the corners
+ of the time-frequency domain of the `~ShortTimeFFT.stft`.
+ That tuple can be passed to `matplotlib.pyplot.imshow` as a parameter
+ with the same name.
+
+ Parameters
+ ----------
+ n : int
+ Number of samples in input signal.
+ axes_seq : {'tf', 'ft'}
+ Return time extent first and then frequency extent or vice versa.
+ center_bins: bool
+ If set (default ``False``), the values of the time slots and
+ frequency bins are moved from the side the middle. This is useful,
+ when plotting the `~ShortTimeFFT.stft` values as step functions,
+ i.e., with no interpolation.
+
+ See Also
+ --------
+ :func:`matplotlib.pyplot.imshow`: Display data as an image.
+ :class:`scipy.signal.ShortTimeFFT`: Class this method belongs to.
+
+ Examples
+ --------
+ The following two plots illustrate the effect of the parameter `center_bins`:
+ The grid lines represent the three time and the four frequency values of the
+ STFT.
+ The left plot, where ``(t0, t1, f0, f1) = (0, 3, 0, 4)`` is passed as parameter
+ ``extent`` to `~matplotlib.pyplot.imshow`, shows the standard behavior of the
+ time and frequency values being at the lower edge of the corrsponding bin.
+ The right plot, with ``(t0, t1, f0, f1) = (-0.5, 2.5, -0.5, 3.5)``, shows that
+ the bins are centered over the respective values when passing
+ ``center_bins=True``.
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.signal import ShortTimeFFT
+ ...
+ >>> n, m = 12, 6
+ >>> SFT = ShortTimeFFT.from_window('hann', fs=m, nperseg=m, noverlap=0)
+ >>> Sxx = SFT.stft(np.cos(np.arange(n))) # produces a colorful plot
+ ...
+ >>> fig, axx = plt.subplots(1, 2, tight_layout=True, figsize=(6., 4.))
+ >>> for ax_, center_bins in zip(axx, (False, True)):
+ ... ax_.imshow(abs(Sxx), origin='lower', interpolation=None, aspect='equal',
+ ... cmap='viridis', extent=SFT.extent(n, 'tf', center_bins))
+ ... ax_.set_title(f"{center_bins=}")
+ ... ax_.set_xlabel(f"Time ({SFT.p_num(n)} points, Δt={SFT.delta_t})")
+ ... ax_.set_ylabel(f"Frequency ({SFT.f_pts} points, Δf={SFT.delta_f})")
+ ... ax_.set_xticks(SFT.t(n)) # vertical grid line are timestamps
+ ... ax_.set_yticks(SFT.f) # horizontal grid line are frequency values
+ ... ax_.grid(True)
+ >>> plt.show()
+
+ Note that the step-like behavior with the constant colors is caused by passing
+ ``interpolation=None`` to `~matplotlib.pyplot.imshow`.
+ """
+ if axes_seq not in ('tf', 'ft'):
+ raise ValueError(f"Parameter {axes_seq=} not in ['tf', 'ft']!")
+
+ if self.onesided_fft:
+ q0, q1 = 0, self.f_pts
+ elif self.fft_mode == 'centered':
+ q0 = -(self.mfft // 2)
+ q1 = self.mfft // 2 if self.mfft % 2 == 0 else self.mfft // 2 + 1
+ else:
+ raise ValueError(f"Attribute fft_mode={self.fft_mode} must be " +
+ "in ['centered', 'onesided', 'onesided2X']")
+
+ p0, p1 = self.p_min, self.p_max(n) # shorthand
+ if center_bins:
+ t0, t1 = self.delta_t * (p0 - 0.5), self.delta_t * (p1 - 0.5)
+ f0, f1 = self.delta_f * (q0 - 0.5), self.delta_f * (q1 - 0.5)
+ else:
+ t0, t1 = self.delta_t * p0, self.delta_t * p1
+ f0, f1 = self.delta_f * q0, self.delta_f * q1
+ return (t0, t1, f0, f1) if axes_seq == 'tf' else (f0, f1, t0, t1)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_signal_api.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_signal_api.py
new file mode 100644
index 0000000000000000000000000000000000000000..8a099dd4ee72775cb7b61d4686407e154ae5c784
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_signal_api.py
@@ -0,0 +1,30 @@
+"""This is the 'bare' scipy.signal API.
+
+This --- private! --- module only collects implementations of public API
+for _support_alternative_backends.
+The latter --- also private! --- module adds delegation to CuPy etc and
+re-exports decorated names to __init__.py
+"""
+
+from . import _sigtools, windows # noqa: F401
+from ._waveforms import * # noqa: F403
+from ._max_len_seq import max_len_seq # noqa: F401
+from ._upfirdn import upfirdn # noqa: F401
+
+from ._spline import sepfir2d # noqa: F401
+
+from ._spline_filters import * # noqa: F403
+from ._filter_design import * # noqa: F403
+from ._fir_filter_design import * # noqa: F403
+from ._ltisys import * # noqa: F403
+from ._lti_conversion import * # noqa: F403
+from ._signaltools import * # noqa: F403
+from ._savitzky_golay import savgol_coeffs, savgol_filter # noqa: F401
+from ._spectral_py import * # noqa: F403
+from ._short_time_fft import * # noqa: F403
+from ._peak_finding import * # noqa: F403
+from ._czt import * # noqa: F403
+from .windows import get_window # keep this one in signal namespace # noqa: F401
+
+
+__all__ = [s for s in dir() if not s.startswith('_')]
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_signaltools.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_signaltools.py
new file mode 100644
index 0000000000000000000000000000000000000000..dc4f986059cd522ff0bcd19dfbd7d1ab9c84971c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_signaltools.py
@@ -0,0 +1,5356 @@
+# Author: Travis Oliphant
+# 1999 -- 2002
+
+from __future__ import annotations # Provides typing union operator `|` in Python 3.9
+import operator
+import math
+from math import prod as _prod
+import timeit
+import warnings
+from typing import Literal
+
+from numpy._typing import ArrayLike
+
+from scipy.spatial import cKDTree
+from . import _sigtools
+from ._ltisys import dlti
+from ._upfirdn import upfirdn, _output_len, _upfirdn_modes
+from scipy import linalg, fft as sp_fft
+from scipy import ndimage
+from scipy.fft._helper import _init_nd_shape_and_axes
+import numpy as np
+from scipy.special import lambertw
+from .windows import get_window
+from ._arraytools import axis_slice, axis_reverse, odd_ext, even_ext, const_ext
+from ._filter_design import cheby1, _validate_sos, zpk2sos
+from ._fir_filter_design import firwin
+from ._sosfilt import _sosfilt
+
+from scipy._lib._array_api import (
+ array_namespace, is_torch, is_numpy, xp_copy, xp_size, xp_default_dtype,
+ xp_swapaxes
+
+)
+from scipy._lib.array_api_compat import is_array_api_obj
+import scipy._lib.array_api_extra as xpx
+
+
+__all__ = ['correlate', 'correlation_lags', 'correlate2d',
+ 'convolve', 'convolve2d', 'fftconvolve', 'oaconvolve',
+ 'order_filter', 'medfilt', 'medfilt2d', 'wiener', 'lfilter',
+ 'lfiltic', 'sosfilt', 'deconvolve', 'hilbert', 'hilbert2', 'envelope',
+ 'unique_roots', 'invres', 'invresz', 'residue',
+ 'residuez', 'resample', 'resample_poly', 'detrend',
+ 'lfilter_zi', 'sosfilt_zi', 'sosfiltfilt', 'choose_conv_method',
+ 'filtfilt', 'decimate', 'vectorstrength']
+
+
+_modedict = {'valid': 0, 'same': 1, 'full': 2}
+
+_boundarydict = {'fill': 0, 'pad': 0, 'wrap': 2, 'circular': 2, 'symm': 1,
+ 'symmetric': 1, 'reflect': 4}
+
+
+def _valfrommode(mode):
+ try:
+ return _modedict[mode]
+ except KeyError as e:
+ raise ValueError("Acceptable mode flags are 'valid',"
+ " 'same', or 'full'.") from e
+
+
+def _bvalfromboundary(boundary):
+ try:
+ return _boundarydict[boundary] << 2
+ except KeyError as e:
+ raise ValueError("Acceptable boundary flags are 'fill', 'circular' "
+ "(or 'wrap'), and 'symmetric' (or 'symm').") from e
+
+
+def _inputs_swap_needed(mode, shape1, shape2, axes=None):
+ """Determine if inputs arrays need to be swapped in `"valid"` mode.
+
+ If in `"valid"` mode, returns whether or not the input arrays need to be
+ swapped depending on whether `shape1` is at least as large as `shape2` in
+ every calculated dimension.
+
+ This is important for some of the correlation and convolution
+ implementations in this module, where the larger array input needs to come
+ before the smaller array input when operating in this mode.
+
+ Note that if the mode provided is not 'valid', False is immediately
+ returned.
+
+ """
+ if mode != 'valid':
+ return False
+
+ if not shape1:
+ return False
+
+ if axes is None:
+ axes = range(len(shape1))
+
+ ok1 = all(shape1[i] >= shape2[i] for i in axes)
+ ok2 = all(shape2[i] >= shape1[i] for i in axes)
+
+ if not (ok1 or ok2):
+ raise ValueError("For 'valid' mode, one must be at least "
+ "as large as the other in every dimension")
+
+ return not ok1
+
+
+def correlate(in1, in2, mode='full', method='auto'):
+ r"""
+ Cross-correlate two N-dimensional arrays.
+
+ Cross-correlate `in1` and `in2`, with the output size determined by the
+ `mode` argument.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear cross-correlation
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ The output is the same size as `in1`, centered
+ with respect to the 'full' output.
+ method : str {'auto', 'direct', 'fft'}, optional
+ A string indicating which method to use to calculate the correlation.
+
+ ``direct``
+ The correlation is determined directly from sums, the definition of
+ correlation.
+ ``fft``
+ The Fast Fourier Transform is used to perform the correlation more
+ quickly (only available for numerical arrays.)
+ ``auto``
+ Automatically chooses direct or Fourier method based on an estimate
+ of which is faster (default). See `convolve` Notes for more detail.
+
+ .. versionadded:: 0.19.0
+
+ Returns
+ -------
+ correlate : array
+ An N-dimensional array containing a subset of the discrete linear
+ cross-correlation of `in1` with `in2`.
+
+ See Also
+ --------
+ choose_conv_method : contains more documentation on `method`.
+ correlation_lags : calculates the lag / displacement indices array for 1D
+ cross-correlation.
+
+ Notes
+ -----
+ The correlation z of two d-dimensional arrays x and y is defined as::
+
+ z[...,k,...] = sum[..., i_l, ...] x[..., i_l,...] * conj(y[..., i_l - k,...])
+
+ This way, if ``x`` and ``y`` are 1-D arrays and ``z = correlate(x, y, 'full')``
+ then
+
+ .. math::
+
+ z[k] = \sum_{l=0}^{N-1} x_l \, y_{l-k}^{*}
+
+ for :math:`k = -(M-1), \dots, (N-1)`, where :math:`N` is the length of ``x``,
+ :math:`M` is the length of ``y``, and :math:`y_m = 0` when :math:`m` is outside the
+ valid range :math:`[0, M-1]`. The size of :math:`z` is :math:`N + M - 1` and
+ :math:`y^*` denotes the complex conjugate of :math:`y`.
+
+ ``method='fft'`` only works for numerical arrays as it relies on
+ `fftconvolve`. In certain cases (i.e., arrays of objects or when
+ rounding integers can lose precision), ``method='direct'`` is always used.
+
+ When using ``mode='same'`` with even-length inputs, the outputs of `correlate`
+ and `correlate2d` differ: There is a 1-index offset between them.
+
+ Examples
+ --------
+ Implement a matched filter using cross-correlation, to recover a signal
+ that has passed through a noisy channel.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+
+ >>> sig = np.repeat([0., 1., 1., 0., 1., 0., 0., 1.], 128)
+ >>> sig_noise = sig + rng.standard_normal(len(sig))
+ >>> corr = signal.correlate(sig_noise, np.ones(128), mode='same') / 128
+
+ >>> clock = np.arange(64, len(sig), 128)
+ >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, sharex=True)
+ >>> ax_orig.plot(sig)
+ >>> ax_orig.plot(clock, sig[clock], 'ro')
+ >>> ax_orig.set_title('Original signal')
+ >>> ax_noise.plot(sig_noise)
+ >>> ax_noise.set_title('Signal with noise')
+ >>> ax_corr.plot(corr)
+ >>> ax_corr.plot(clock, corr[clock], 'ro')
+ >>> ax_corr.axhline(0.5, ls=':')
+ >>> ax_corr.set_title('Cross-correlated with rectangular pulse')
+ >>> ax_orig.margins(0, 0.1)
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ Compute the cross-correlation of a noisy signal with the original signal.
+
+ >>> x = np.arange(128) / 128
+ >>> sig = np.sin(2 * np.pi * x)
+ >>> sig_noise = sig + rng.standard_normal(len(sig))
+ >>> corr = signal.correlate(sig_noise, sig)
+ >>> lags = signal.correlation_lags(len(sig), len(sig_noise))
+ >>> corr /= np.max(corr)
+
+ >>> fig, (ax_orig, ax_noise, ax_corr) = plt.subplots(3, 1, figsize=(4.8, 4.8))
+ >>> ax_orig.plot(sig)
+ >>> ax_orig.set_title('Original signal')
+ >>> ax_orig.set_xlabel('Sample Number')
+ >>> ax_noise.plot(sig_noise)
+ >>> ax_noise.set_title('Signal with noise')
+ >>> ax_noise.set_xlabel('Sample Number')
+ >>> ax_corr.plot(lags, corr)
+ >>> ax_corr.set_title('Cross-correlated signal')
+ >>> ax_corr.set_xlabel('Lag')
+ >>> ax_orig.margins(0, 0.1)
+ >>> ax_noise.margins(0, 0.1)
+ >>> ax_corr.margins(0, 0.1)
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ """
+ xp = array_namespace(in1, in2)
+
+ in1 = xp.asarray(in1)
+ in2 = xp.asarray(in2)
+
+ if in1.ndim == in2.ndim == 0:
+ in2_conj = (xp.conj(in2)
+ if xp.isdtype(in2.dtype, 'complex floating')
+ else in2)
+ return in1 * in2_conj
+ elif in1.ndim != in2.ndim:
+ raise ValueError("in1 and in2 should have the same dimensionality")
+
+ # Don't use _valfrommode, since correlate should not accept numeric modes
+ try:
+ val = _modedict[mode]
+ except KeyError as e:
+ raise ValueError("Acceptable mode flags are 'valid',"
+ " 'same', or 'full'.") from e
+
+ # this either calls fftconvolve or this function with method=='direct'
+ if method in ('fft', 'auto'):
+ return convolve(in1, _reverse_and_conj(in2, xp), mode, method)
+
+ elif method == 'direct':
+ # fastpath to faster numpy.correlate for 1d inputs when possible
+ if _np_conv_ok(in1, in2, mode, xp):
+ a_in1 = np.asarray(in1)
+ a_in2 = np.asarray(in2)
+ out = np.correlate(a_in1, a_in2, mode)
+ return xp.asarray(out)
+
+ # _correlateND is far slower when in2.size > in1.size, so swap them
+ # and then undo the effect afterward if mode == 'full'. Also, it fails
+ # with 'valid' mode if in2 is larger than in1, so swap those, too.
+ # Don't swap inputs for 'same' mode, since shape of in1 matters.
+ swapped_inputs = ((mode == 'full') and (xp_size(in2) > xp_size(in1)) or
+ _inputs_swap_needed(mode, in1.shape, in2.shape))
+
+ if swapped_inputs:
+ in1, in2 = in2, in1
+
+ # convert to numpy & back for _sigtools._correlateND
+ a_in1 = np.asarray(in1)
+ a_in2 = np.asarray(in2)
+
+ if mode == 'valid':
+ ps = [i - j + 1 for i, j in zip(in1.shape, in2.shape)]
+ out = np.empty(ps, a_in1.dtype)
+
+ z = _sigtools._correlateND(a_in1, a_in2, out, val)
+
+ else:
+ ps = [i + j - 1 for i, j in zip(in1.shape, in2.shape)]
+
+ # zero pad input
+ in1zpadded = np.zeros(ps, a_in1.dtype)
+ sc = tuple(slice(0, i) for i in in1.shape)
+ in1zpadded[sc] = a_in1.copy()
+
+ if mode == 'full':
+ out = np.empty(ps, a_in1.dtype)
+ elif mode == 'same':
+ out = np.empty(in1.shape, a_in1.dtype)
+
+ z = _sigtools._correlateND(in1zpadded, a_in2, out, val)
+
+ z = xp.asarray(z)
+
+ if swapped_inputs:
+ # Reverse and conjugate to undo the effect of swapping inputs
+ z = _reverse_and_conj(z, xp)
+
+ return z
+
+ else:
+ raise ValueError("Acceptable method flags are 'auto',"
+ " 'direct', or 'fft'.")
+
+
+def correlation_lags(in1_len, in2_len, mode='full'):
+ r"""
+ Calculates the lag / displacement indices array for 1D cross-correlation.
+
+ Parameters
+ ----------
+ in1_len : int
+ First input size.
+ in2_len : int
+ Second input size.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output.
+ See the documentation `correlate` for more information.
+
+ Returns
+ -------
+ lags : array
+ Returns an array containing cross-correlation lag/displacement indices.
+ Indices can be indexed with the np.argmax of the correlation to return
+ the lag/displacement.
+
+ See Also
+ --------
+ correlate : Compute the N-dimensional cross-correlation.
+
+ Notes
+ -----
+ Cross-correlation for continuous functions :math:`f` and :math:`g` is
+ defined as:
+
+ .. math::
+
+ \left ( f\star g \right )\left ( \tau \right )
+ \triangleq \int_{t_0}^{t_0 +T}
+ \overline{f\left ( t \right )}g\left ( t+\tau \right )dt
+
+ Where :math:`\tau` is defined as the displacement, also known as the lag.
+
+ Cross correlation for discrete functions :math:`f` and :math:`g` is
+ defined as:
+
+ .. math::
+ \left ( f\star g \right )\left [ n \right ]
+ \triangleq \sum_{-\infty}^{\infty}
+ \overline{f\left [ m \right ]}g\left [ m+n \right ]
+
+ Where :math:`n` is the lag.
+
+ Examples
+ --------
+ Cross-correlation of a signal with its time-delayed self.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> rng = np.random.default_rng()
+ >>> x = rng.standard_normal(1000)
+ >>> y = np.concatenate([rng.standard_normal(100), x])
+ >>> correlation = signal.correlate(x, y, mode="full")
+ >>> lags = signal.correlation_lags(x.size, y.size, mode="full")
+ >>> lag = lags[np.argmax(correlation)]
+ """
+
+ # calculate lag ranges in different modes of operation
+ if mode == "full":
+ # the output is the full discrete linear convolution
+ # of the inputs. (Default)
+ lags = np.arange(-in2_len + 1, in1_len)
+ elif mode == "same":
+ # the output is the same size as `in1`, centered
+ # with respect to the 'full' output.
+ # calculate the full output
+ lags = np.arange(-in2_len + 1, in1_len)
+ # determine the midpoint in the full output
+ mid = lags.size // 2
+ # determine lag_bound to be used with respect
+ # to the midpoint
+ lag_bound = in1_len // 2
+ # calculate lag ranges for even and odd scenarios
+ if in1_len % 2 == 0:
+ lags = lags[(mid-lag_bound):(mid+lag_bound)]
+ else:
+ lags = lags[(mid-lag_bound):(mid+lag_bound)+1]
+ elif mode == "valid":
+ # the output consists only of those elements that do not
+ # rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ # must be at least as large as the other in every dimension.
+
+ # the lag_bound will be either negative or positive
+ # this let's us infer how to present the lag range
+ lag_bound = in1_len - in2_len
+ if lag_bound >= 0:
+ lags = np.arange(lag_bound + 1)
+ else:
+ lags = np.arange(lag_bound, 1)
+ else:
+ raise ValueError(f"Mode {mode} is invalid")
+ return lags
+
+
+def _centered(arr, newshape):
+ # Return the center newshape portion of the array.
+ newshape = np.asarray(newshape)
+ currshape = np.array(arr.shape)
+ startind = (currshape - newshape) // 2
+ endind = startind + newshape
+ myslice = [slice(startind[k], endind[k]) for k in range(len(endind))]
+ return arr[tuple(myslice)]
+
+
+def _init_freq_conv_axes(in1, in2, mode, axes, sorted_axes=False):
+ """Handle the axes argument for frequency-domain convolution.
+
+ Returns the inputs and axes in a standard form, eliminating redundant axes,
+ swapping the inputs if necessary, and checking for various potential
+ errors.
+
+ Parameters
+ ----------
+ in1 : array
+ First input.
+ in2 : array
+ Second input.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output.
+ See the documentation `fftconvolve` for more information.
+ axes : list of ints
+ Axes over which to compute the FFTs.
+ sorted_axes : bool, optional
+ If `True`, sort the axes.
+ Default is `False`, do not sort.
+
+ Returns
+ -------
+ in1 : array
+ The first input, possible swapped with the second input.
+ in2 : array
+ The second input, possible swapped with the first input.
+ axes : list of ints
+ Axes over which to compute the FFTs.
+
+ """
+ s1 = in1.shape
+ s2 = in2.shape
+ noaxes = axes is None
+
+ _, axes = _init_nd_shape_and_axes(in1, shape=None, axes=axes)
+
+ if not noaxes and not len(axes):
+ raise ValueError("when provided, axes cannot be empty")
+
+ # Axes of length 1 can rely on broadcasting rules for multiply,
+ # no fft needed.
+ axes = [a for a in axes if s1[a] != 1 and s2[a] != 1]
+
+ if sorted_axes:
+ axes.sort()
+
+ if not all(s1[a] == s2[a] or s1[a] == 1 or s2[a] == 1
+ for a in range(in1.ndim) if a not in axes):
+ raise ValueError("incompatible shapes for in1 and in2:"
+ f" {s1} and {s2}")
+
+ # Check that input sizes are compatible with 'valid' mode.
+ if _inputs_swap_needed(mode, s1, s2, axes=axes):
+ # Convolution is commutative; order doesn't have any effect on output.
+ in1, in2 = in2, in1
+
+ return in1, in2, axes
+
+
+def _freq_domain_conv(xp, in1, in2, axes, shape, calc_fast_len=False):
+ """Convolve two arrays in the frequency domain.
+
+ This function implements only base the FFT-related operations.
+ Specifically, it converts the signals to the frequency domain, multiplies
+ them, then converts them back to the time domain. Calculations of axes,
+ shapes, convolution mode, etc. are implemented in higher level-functions,
+ such as `fftconvolve` and `oaconvolve`. Those functions should be used
+ instead of this one.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ axes : array_like of ints
+ Axes over which to compute the FFTs.
+ shape : array_like of ints
+ The sizes of the FFTs.
+ calc_fast_len : bool, optional
+ If `True`, set each value of `shape` to the next fast FFT length.
+ Default is `False`, use `axes` as-is.
+
+ Returns
+ -------
+ out : array
+ An N-dimensional array containing the discrete linear convolution of
+ `in1` with `in2`.
+
+ """
+ if not len(axes):
+ return in1 * in2
+
+ complex_result = (xp.isdtype(in1.dtype, 'complex floating') or
+ xp.isdtype(in2.dtype, 'complex floating'))
+
+ if calc_fast_len:
+ # Speed up FFT by padding to optimal size.
+ fshape = [
+ sp_fft.next_fast_len(shape[a], not complex_result) for a in axes]
+ else:
+ fshape = shape
+
+ if not complex_result:
+ fft, ifft = sp_fft.rfftn, sp_fft.irfftn
+ else:
+ fft, ifft = sp_fft.fftn, sp_fft.ifftn
+
+ if xp.isdtype(in1.dtype, 'integral'):
+ in1 = xp.astype(in1, xp.float64)
+ if xp.isdtype(in2.dtype, 'integral'):
+ in2 = xp.astype(in2, xp.float64)
+
+ sp1 = fft(in1, fshape, axes=axes)
+ sp2 = fft(in2, fshape, axes=axes)
+
+ ret = ifft(sp1 * sp2, fshape, axes=axes)
+
+ if calc_fast_len:
+ fslice = tuple([slice(sz) for sz in shape])
+ ret = ret[fslice]
+
+ return ret
+
+
+def _apply_conv_mode(ret, s1, s2, mode, axes, xp):
+ """Calculate the convolution result shape based on the `mode` argument.
+
+ Returns the result sliced to the correct size for the given mode.
+
+ Parameters
+ ----------
+ ret : array
+ The result array, with the appropriate shape for the 'full' mode.
+ s1 : list of int
+ The shape of the first input.
+ s2 : list of int
+ The shape of the second input.
+ mode : str {'full', 'valid', 'same'}
+ A string indicating the size of the output.
+ See the documentation `fftconvolve` for more information.
+ axes : list of ints
+ Axes over which to compute the convolution.
+
+ Returns
+ -------
+ ret : array
+ A copy of `res`, sliced to the correct size for the given `mode`.
+
+ """
+ if mode == "full":
+ return xp_copy(ret, xp=xp)
+ elif mode == "same":
+ return xp_copy(_centered(ret, s1), xp=xp)
+ elif mode == "valid":
+ shape_valid = [ret.shape[a] if a not in axes else s1[a] - s2[a] + 1
+ for a in range(ret.ndim)]
+ return xp_copy(_centered(ret, shape_valid), xp=xp)
+ else:
+ raise ValueError("acceptable mode flags are 'valid',"
+ " 'same', or 'full'")
+
+
+def fftconvolve(in1, in2, mode="full", axes=None):
+ """Convolve two N-dimensional arrays using FFT.
+
+ Convolve `in1` and `in2` using the fast Fourier transform method, with
+ the output size determined by the `mode` argument.
+
+ This is generally much faster than `convolve` for large arrays (n > ~500),
+ but can be slower when only a few output values are needed, and can only
+ output float arrays (int or object array inputs will be cast to float).
+
+ As of v0.19, `convolve` automatically chooses this method or the direct
+ method based on an estimation of which is faster.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear convolution
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ The output is the same size as `in1`, centered
+ with respect to the 'full' output.
+ axes : int or array_like of ints or None, optional
+ Axes over which to compute the convolution.
+ The default is over all axes.
+
+ Returns
+ -------
+ out : array
+ An N-dimensional array containing a subset of the discrete linear
+ convolution of `in1` with `in2`.
+
+ See Also
+ --------
+ convolve : Uses the direct convolution or FFT convolution algorithm
+ depending on which is faster.
+ oaconvolve : Uses the overlap-add method to do convolution, which is
+ generally faster when the input arrays are large and
+ significantly different in size.
+
+ Examples
+ --------
+ Autocorrelation of white noise is an impulse.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> rng = np.random.default_rng()
+ >>> sig = rng.standard_normal(1000)
+ >>> autocorr = signal.fftconvolve(sig, sig[::-1], mode='full')
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1)
+ >>> ax_orig.plot(sig)
+ >>> ax_orig.set_title('White noise')
+ >>> ax_mag.plot(np.arange(-len(sig)+1,len(sig)), autocorr)
+ >>> ax_mag.set_title('Autocorrelation')
+ >>> fig.tight_layout()
+ >>> fig.show()
+
+ Gaussian blur implemented using FFT convolution. Notice the dark borders
+ around the image, due to the zero-padding beyond its boundaries.
+ The `convolve2d` function allows for other types of image boundaries,
+ but is far slower.
+
+ >>> from scipy import datasets
+ >>> face = datasets.face(gray=True)
+ >>> kernel = np.outer(signal.windows.gaussian(70, 8),
+ ... signal.windows.gaussian(70, 8))
+ >>> blurred = signal.fftconvolve(face, kernel, mode='same')
+
+ >>> fig, (ax_orig, ax_kernel, ax_blurred) = plt.subplots(3, 1,
+ ... figsize=(6, 15))
+ >>> ax_orig.imshow(face, cmap='gray')
+ >>> ax_orig.set_title('Original')
+ >>> ax_orig.set_axis_off()
+ >>> ax_kernel.imshow(kernel, cmap='gray')
+ >>> ax_kernel.set_title('Gaussian kernel')
+ >>> ax_kernel.set_axis_off()
+ >>> ax_blurred.imshow(blurred, cmap='gray')
+ >>> ax_blurred.set_title('Blurred')
+ >>> ax_blurred.set_axis_off()
+ >>> fig.show()
+
+ """
+ xp = array_namespace(in1, in2)
+
+ in1 = xp.asarray(in1)
+ in2 = xp.asarray(in2)
+
+ if in1.ndim == in2.ndim == 0: # scalar inputs
+ return in1 * in2
+ elif in1.ndim != in2.ndim:
+ raise ValueError("in1 and in2 should have the same dimensionality")
+ elif xp_size(in1) == 0 or xp_size(in2) == 0: # empty arrays
+ return xp.asarray([])
+
+ in1, in2, axes = _init_freq_conv_axes(in1, in2, mode, axes,
+ sorted_axes=False)
+
+ s1 = in1.shape
+ s2 = in2.shape
+
+ shape = [max((s1[i], s2[i])) if i not in axes else s1[i] + s2[i] - 1
+ for i in range(in1.ndim)]
+
+ ret = _freq_domain_conv(xp, in1, in2, axes, shape, calc_fast_len=True)
+
+ return _apply_conv_mode(ret, s1, s2, mode, axes, xp=xp)
+
+
+def _calc_oa_lens(s1, s2):
+ """Calculate the optimal FFT lengths for overlap-add convolution.
+
+ The calculation is done for a single dimension.
+
+ Parameters
+ ----------
+ s1 : int
+ Size of the dimension for the first array.
+ s2 : int
+ Size of the dimension for the second array.
+
+ Returns
+ -------
+ block_size : int
+ The size of the FFT blocks.
+ overlap : int
+ The amount of overlap between two blocks.
+ in1_step : int
+ The size of each step for the first array.
+ in2_step : int
+ The size of each step for the first array.
+
+ """
+ # Set up the arguments for the conventional FFT approach.
+ fallback = (s1+s2-1, None, s1, s2)
+
+ # Use conventional FFT convolve if sizes are same.
+ if s1 == s2 or s1 == 1 or s2 == 1:
+ return fallback
+
+ if s2 > s1:
+ s1, s2 = s2, s1
+ swapped = True
+ else:
+ swapped = False
+
+ # There cannot be a useful block size if s2 is more than half of s1.
+ if s2 >= s1/2:
+ return fallback
+
+ # Derivation of optimal block length
+ # For original formula see:
+ # https://en.wikipedia.org/wiki/Overlap-add_method
+ #
+ # Formula:
+ # K = overlap = s2-1
+ # N = block_size
+ # C = complexity
+ # e = exponential, exp(1)
+ #
+ # C = (N*(log2(N)+1))/(N-K)
+ # C = (N*log2(2N))/(N-K)
+ # C = N/(N-K) * log2(2N)
+ # C1 = N/(N-K)
+ # C2 = log2(2N) = ln(2N)/ln(2)
+ #
+ # dC1/dN = (1*(N-K)-N)/(N-K)^2 = -K/(N-K)^2
+ # dC2/dN = 2/(2*N*ln(2)) = 1/(N*ln(2))
+ #
+ # dC/dN = dC1/dN*C2 + dC2/dN*C1
+ # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + N/(N*ln(2)*(N-K))
+ # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + 1/(ln(2)*(N-K))
+ # dC/dN = -K*ln(2N)/(ln(2)*(N-K)^2) + (N-K)/(ln(2)*(N-K)^2)
+ # dC/dN = (-K*ln(2N) + (N-K)/(ln(2)*(N-K)^2)
+ # dC/dN = (N - K*ln(2N) - K)/(ln(2)*(N-K)^2)
+ #
+ # Solve for minimum, where dC/dN = 0
+ # 0 = (N - K*ln(2N) - K)/(ln(2)*(N-K)^2)
+ # 0 * ln(2)*(N-K)^2 = N - K*ln(2N) - K
+ # 0 = N - K*ln(2N) - K
+ # 0 = N - K*(ln(2N) + 1)
+ # 0 = N - K*ln(2Ne)
+ # N = K*ln(2Ne)
+ # N/K = ln(2Ne)
+ #
+ # e^(N/K) = e^ln(2Ne)
+ # e^(N/K) = 2Ne
+ # 1/e^(N/K) = 1/(2*N*e)
+ # e^(N/-K) = 1/(2*N*e)
+ # e^(N/-K) = K/N*1/(2*K*e)
+ # N/K*e^(N/-K) = 1/(2*e*K)
+ # N/-K*e^(N/-K) = -1/(2*e*K)
+ #
+ # Using Lambert W function
+ # https://en.wikipedia.org/wiki/Lambert_W_function
+ # x = W(y) It is the solution to y = x*e^x
+ # x = N/-K
+ # y = -1/(2*e*K)
+ #
+ # N/-K = W(-1/(2*e*K))
+ #
+ # N = -K*W(-1/(2*e*K))
+ overlap = s2-1
+ opt_size = -overlap*lambertw(-1/(2*math.e*overlap), k=-1).real
+ block_size = sp_fft.next_fast_len(math.ceil(opt_size))
+
+ # Use conventional FFT convolve if there is only going to be one block.
+ if block_size >= s1:
+ return fallback
+
+ if not swapped:
+ in1_step = block_size-s2+1
+ in2_step = s2
+ else:
+ in1_step = s2
+ in2_step = block_size-s2+1
+
+ return block_size, overlap, in1_step, in2_step
+
+
+# may want to look at moving xp_swapaxes and this to array-api-extra,
+# cross-ref https://github.com/data-apis/array-api-extra/issues/97
+def _split(x, indices_or_sections, axis, xp):
+ """A simplified version of np.split, with `indices` being an list.
+ """
+ # https://github.com/numpy/numpy/blob/v2.2.0/numpy/lib/_shape_base_impl.py#L743
+ Ntotal = x.shape[axis]
+
+ # handle array case.
+ Nsections = len(indices_or_sections) + 1
+ div_points = [0] + list(indices_or_sections) + [Ntotal]
+
+ sub_arys = []
+ sary = xp_swapaxes(x, axis, 0, xp=xp)
+ for i in range(Nsections):
+ st = div_points[i]
+ end = div_points[i + 1]
+ sub_arys.append(xp_swapaxes(sary[st:end, ...], axis, 0, xp=xp))
+
+ return sub_arys
+
+
+def oaconvolve(in1, in2, mode="full", axes=None):
+ """Convolve two N-dimensional arrays using the overlap-add method.
+
+ Convolve `in1` and `in2` using the overlap-add method, with
+ the output size determined by the `mode` argument.
+
+ This is generally much faster than `convolve` for large arrays (n > ~500),
+ and generally much faster than `fftconvolve` when one array is much
+ larger than the other, but can be slower when only a few output values are
+ needed or when the arrays are very similar in shape, and can only
+ output float arrays (int or object array inputs will be cast to float).
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear convolution
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ The output is the same size as `in1`, centered
+ with respect to the 'full' output.
+ axes : int or array_like of ints or None, optional
+ Axes over which to compute the convolution.
+ The default is over all axes.
+
+ Returns
+ -------
+ out : array
+ An N-dimensional array containing a subset of the discrete linear
+ convolution of `in1` with `in2`.
+
+ See Also
+ --------
+ convolve : Uses the direct convolution or FFT convolution algorithm
+ depending on which is faster.
+ fftconvolve : An implementation of convolution using FFT.
+
+ Notes
+ -----
+ .. versionadded:: 1.4.0
+
+ References
+ ----------
+ .. [1] Wikipedia, "Overlap-add_method".
+ https://en.wikipedia.org/wiki/Overlap-add_method
+ .. [2] Richard G. Lyons. Understanding Digital Signal Processing,
+ Third Edition, 2011. Chapter 13.10.
+ ISBN 13: 978-0137-02741-5
+
+ Examples
+ --------
+ Convolve a 100,000 sample signal with a 512-sample filter.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> rng = np.random.default_rng()
+ >>> sig = rng.standard_normal(100000)
+ >>> filt = signal.firwin(512, 0.01)
+ >>> fsig = signal.oaconvolve(sig, filt)
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax_orig, ax_mag) = plt.subplots(2, 1)
+ >>> ax_orig.plot(sig)
+ >>> ax_orig.set_title('White noise')
+ >>> ax_mag.plot(fsig)
+ >>> ax_mag.set_title('Filtered noise')
+ >>> fig.tight_layout()
+ >>> fig.show()
+
+ """
+ xp = array_namespace(in1, in2)
+
+ in1 = xp.asarray(in1)
+ in2 = xp.asarray(in2)
+
+ if in1.ndim == in2.ndim == 0: # scalar inputs
+ return in1 * in2
+ elif in1.ndim != in2.ndim:
+ raise ValueError("in1 and in2 should have the same dimensionality")
+ elif in1.size == 0 or in2.size == 0: # empty arrays
+ return xp.asarray([])
+ elif in1.shape == in2.shape: # Equivalent to fftconvolve
+ return fftconvolve(in1, in2, mode=mode, axes=axes)
+
+ in1, in2, axes = _init_freq_conv_axes(in1, in2, mode, axes,
+ sorted_axes=True)
+
+ s1 = in1.shape
+ s2 = in2.shape
+
+ if not axes:
+ ret = in1 * in2
+ return _apply_conv_mode(ret, s1, s2, mode, axes, xp)
+
+ # Calculate this now since in1 is changed later
+ shape_final = [None if i not in axes else
+ s1[i] + s2[i] - 1 for i in range(in1.ndim)]
+
+ # Calculate the block sizes for the output, steps, first and second inputs.
+ # It is simpler to calculate them all together than doing them in separate
+ # loops due to all the special cases that need to be handled.
+ optimal_sizes = ((-1, -1, s1[i], s2[i]) if i not in axes else
+ _calc_oa_lens(s1[i], s2[i]) for i in range(in1.ndim))
+ block_size, overlaps, \
+ in1_step, in2_step = zip(*optimal_sizes)
+
+ # Fall back to fftconvolve if there is only one block in every dimension.
+ if in1_step == s1 and in2_step == s2:
+ return fftconvolve(in1, in2, mode=mode, axes=axes)
+
+ # Figure out the number of steps and padding.
+ # This would get too complicated in a list comprehension.
+ nsteps1 = []
+ nsteps2 = []
+ pad_size1 = []
+ pad_size2 = []
+ for i in range(in1.ndim):
+ if i not in axes:
+ pad_size1 += [(0, 0)]
+ pad_size2 += [(0, 0)]
+ continue
+
+ if s1[i] > in1_step[i]:
+ curnstep1 = math.ceil((s1[i]+1)/in1_step[i])
+ if (block_size[i] - overlaps[i])*curnstep1 < shape_final[i]:
+ curnstep1 += 1
+
+ curpad1 = curnstep1*in1_step[i] - s1[i]
+ else:
+ curnstep1 = 1
+ curpad1 = 0
+
+ if s2[i] > in2_step[i]:
+ curnstep2 = math.ceil((s2[i]+1)/in2_step[i])
+ if (block_size[i] - overlaps[i])*curnstep2 < shape_final[i]:
+ curnstep2 += 1
+
+ curpad2 = curnstep2*in2_step[i] - s2[i]
+ else:
+ curnstep2 = 1
+ curpad2 = 0
+
+ nsteps1 += [curnstep1]
+ nsteps2 += [curnstep2]
+ pad_size1 += [(0, curpad1)]
+ pad_size2 += [(0, curpad2)]
+
+ # Pad the array to a size that can be reshaped to the desired shape
+ # if necessary.
+ if not all(curpad == (0, 0) for curpad in pad_size1):
+ in1 = xpx.pad(in1, pad_size1, mode='constant', constant_values=0, xp=xp)
+
+ if not all(curpad == (0, 0) for curpad in pad_size2):
+ in2 = xpx.pad(in2, pad_size2, mode='constant', constant_values=0, xp=xp)
+
+ # Reshape the overlap-add parts to input block sizes.
+ split_axes = [iax+i for i, iax in enumerate(axes)]
+ fft_axes = [iax+1 for iax in split_axes]
+
+ # We need to put each new dimension before the corresponding dimension
+ # being reshaped in order to get the data in the right layout at the end.
+ reshape_size1 = list(in1_step)
+ reshape_size2 = list(in2_step)
+ for i, iax in enumerate(split_axes):
+ reshape_size1.insert(iax, nsteps1[i])
+ reshape_size2.insert(iax, nsteps2[i])
+
+ in1 = xp.reshape(in1, tuple(reshape_size1))
+ in2 = xp.reshape(in2, tuple(reshape_size2))
+
+ # Do the convolution.
+ fft_shape = [block_size[i] for i in axes]
+ ret = _freq_domain_conv(xp, in1, in2, fft_axes, fft_shape, calc_fast_len=False)
+
+ # Do the overlap-add.
+ for ax, ax_fft, ax_split in zip(axes, fft_axes, split_axes):
+ overlap = overlaps[ax]
+ if overlap is None:
+ continue
+
+ ret, overpart = _split(ret, [-overlap], ax_fft, xp=xp)
+ overpart = _split(overpart, [-1], ax_split, xp=xp)[0]
+
+ ret_overpart = _split(ret, [overlap], ax_fft, xp=xp)[0]
+ ret_overpart = _split(ret_overpart, [1], ax_split, xp)[1]
+ ret_overpart += overpart
+
+ # Reshape back to the correct dimensionality.
+ shape_ret = [ret.shape[i] if i not in fft_axes else
+ ret.shape[i]*ret.shape[i-1]
+ for i in range(ret.ndim) if i not in split_axes]
+ ret = xp.reshape(ret, tuple(shape_ret))
+
+ # Slice to the correct size.
+ slice_final = tuple([slice(islice) for islice in shape_final])
+ ret = ret[slice_final]
+
+ return _apply_conv_mode(ret, s1, s2, mode, axes, xp)
+
+
+def _numeric_arrays(arrays, kinds='buifc', xp=None):
+ """
+ See if a list of arrays are all numeric.
+
+ Parameters
+ ----------
+ arrays : array or list of arrays
+ arrays to check if numeric.
+ kinds : string-like
+ The dtypes of the arrays to be checked. If the dtype.kind of
+ the ndarrays are not in this string the function returns False and
+ otherwise returns True.
+ """
+ if xp is None:
+ xp = array_namespace(*arrays)
+ if not is_numpy(xp):
+ return True
+
+ if type(arrays) is np.ndarray:
+ return arrays.dtype.kind in kinds
+ for array_ in arrays:
+ if array_.dtype.kind not in kinds:
+ return False
+ return True
+
+
+def _conv_ops(x_shape, h_shape, mode):
+ """
+ Find the number of operations required for direct/fft methods of
+ convolution. The direct operations were recorded by making a dummy class to
+ record the number of operations by overriding ``__mul__`` and ``__add__``.
+ The FFT operations rely on the (well-known) computational complexity of the
+ FFT (and the implementation of ``_freq_domain_conv``).
+
+ """
+ if mode == "full":
+ out_shape = [n + k - 1 for n, k in zip(x_shape, h_shape)]
+ elif mode == "valid":
+ out_shape = [abs(n - k) + 1 for n, k in zip(x_shape, h_shape)]
+ elif mode == "same":
+ out_shape = x_shape
+ else:
+ raise ValueError("Acceptable mode flags are 'valid',"
+ f" 'same', or 'full', not mode={mode}")
+
+ s1, s2 = x_shape, h_shape
+ if len(x_shape) == 1:
+ s1, s2 = s1[0], s2[0]
+ if mode == "full":
+ direct_ops = s1 * s2
+ elif mode == "valid":
+ direct_ops = (s2 - s1 + 1) * s1 if s2 >= s1 else (s1 - s2 + 1) * s2
+ elif mode == "same":
+ direct_ops = (s1 * s2 if s1 < s2 else
+ s1 * s2 - (s2 // 2) * ((s2 + 1) // 2))
+ else:
+ if mode == "full":
+ direct_ops = min(_prod(s1), _prod(s2)) * _prod(out_shape)
+ elif mode == "valid":
+ direct_ops = min(_prod(s1), _prod(s2)) * _prod(out_shape)
+ elif mode == "same":
+ direct_ops = _prod(s1) * _prod(s2)
+
+ full_out_shape = [n + k - 1 for n, k in zip(x_shape, h_shape)]
+ N = _prod(full_out_shape)
+ fft_ops = 3 * N * np.log(N) # 3 separate FFTs of size full_out_shape
+ return fft_ops, direct_ops
+
+
+def _fftconv_faster(x, h, mode):
+ """
+ See if using fftconvolve or convolve is faster.
+
+ Parameters
+ ----------
+ x : np.ndarray
+ Signal
+ h : np.ndarray
+ Kernel
+ mode : str
+ Mode passed to convolve
+
+ Returns
+ -------
+ fft_faster : bool
+
+ Notes
+ -----
+ See docstring of `choose_conv_method` for details on tuning hardware.
+
+ See pull request 11031 for more detail:
+ https://github.com/scipy/scipy/pull/11031.
+
+ """
+ fft_ops, direct_ops = _conv_ops(x.shape, h.shape, mode)
+ offset = -1e-3 if x.ndim == 1 else -1e-4
+ constants = {
+ "valid": (1.89095737e-9, 2.1364985e-10, offset),
+ "full": (1.7649070e-9, 2.1414831e-10, offset),
+ "same": (3.2646654e-9, 2.8478277e-10, offset)
+ if h.size <= x.size
+ else (3.21635404e-9, 1.1773253e-8, -1e-5),
+ } if x.ndim == 1 else {
+ "valid": (1.85927e-9, 2.11242e-8, offset),
+ "full": (1.99817e-9, 1.66174e-8, offset),
+ "same": (2.04735e-9, 1.55367e-8, offset),
+ }
+ O_fft, O_direct, O_offset = constants[mode]
+ return O_fft * fft_ops < O_direct * direct_ops + O_offset
+
+
+def _reverse_and_conj(x, xp):
+ """
+ Reverse array `x` in all dimensions and perform the complex conjugate
+ """
+ if not is_torch(xp):
+ reverse = (slice(None, None, -1),) * x.ndim
+ x_rev = x[reverse]
+ else:
+ # NB: is a copy, not a view as torch does not allow negative indices
+ # in slices, x-ref https://github.com/pytorch/pytorch/issues/59786
+ x_rev = xp.flip(x)
+
+ # cf https://github.com/data-apis/array-api/issues/824
+ if xp.isdtype(x.dtype, 'complex floating'):
+ return xp.conj(x_rev)
+ else:
+ return x_rev
+
+
+def _np_conv_ok(volume, kernel, mode, xp):
+ """
+ See if numpy supports convolution of `volume` and `kernel` (i.e. both are
+ 1D ndarrays and of the appropriate shape). NumPy's 'same' mode uses the
+ size of the larger input, while SciPy's uses the size of the first input.
+
+ Invalid mode strings will return False and be caught by the calling func.
+ """
+ if volume.ndim == kernel.ndim == 1:
+ if mode in ('full', 'valid'):
+ return True
+ elif mode == 'same':
+ return xp_size(volume) >= xp_size(kernel)
+ else:
+ return False
+
+
+def _timeit_fast(stmt="pass", setup="pass", repeat=3):
+ """
+ Returns the time the statement/function took, in seconds.
+
+ Faster, less precise version of IPython's timeit. `stmt` can be a statement
+ written as a string or a callable.
+
+ Will do only 1 loop (like IPython's timeit) with no repetitions
+ (unlike IPython) for very slow functions. For fast functions, only does
+ enough loops to take 5 ms, which seems to produce similar results (on
+ Windows at least), and avoids doing an extraneous cycle that isn't
+ measured.
+
+ """
+ timer = timeit.Timer(stmt, setup)
+
+ # determine number of calls per rep so total time for 1 rep >= 5 ms
+ x = 0
+ for p in range(0, 10):
+ number = 10**p
+ x = timer.timeit(number) # seconds
+ if x >= 5e-3 / 10: # 5 ms for final test, 1/10th that for this one
+ break
+ if x > 1: # second
+ # If it's macroscopic, don't bother with repetitions
+ best = x
+ else:
+ number *= 10
+ r = timer.repeat(repeat, number)
+ best = min(r)
+
+ sec = best / number
+ return sec
+
+
+def choose_conv_method(in1, in2, mode='full', measure=False):
+ """
+ Find the fastest convolution/correlation method.
+
+ This primarily exists to be called during the ``method='auto'`` option in
+ `convolve` and `correlate`. It can also be used to determine the value of
+ ``method`` for many different convolutions of the same dtype/shape.
+ In addition, it supports timing the convolution to adapt the value of
+ ``method`` to a particular set of inputs and/or hardware.
+
+ Parameters
+ ----------
+ in1 : array_like
+ The first argument passed into the convolution function.
+ in2 : array_like
+ The second argument passed into the convolution function.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear convolution
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding.
+ ``same``
+ The output is the same size as `in1`, centered
+ with respect to the 'full' output.
+ measure : bool, optional
+ If True, run and time the convolution of `in1` and `in2` with both
+ methods and return the fastest. If False (default), predict the fastest
+ method using precomputed values.
+
+ Returns
+ -------
+ method : str
+ A string indicating which convolution method is fastest, either
+ 'direct' or 'fft'
+ times : dict, optional
+ A dictionary containing the times (in seconds) needed for each method.
+ This value is only returned if ``measure=True``.
+
+ See Also
+ --------
+ convolve
+ correlate
+
+ Notes
+ -----
+ Generally, this method is 99% accurate for 2D signals and 85% accurate
+ for 1D signals for randomly chosen input sizes. For precision, use
+ ``measure=True`` to find the fastest method by timing the convolution.
+ This can be used to avoid the minimal overhead of finding the fastest
+ ``method`` later, or to adapt the value of ``method`` to a particular set
+ of inputs.
+
+ Experiments were run on an Amazon EC2 r5a.2xlarge machine to test this
+ function. These experiments measured the ratio between the time required
+ when using ``method='auto'`` and the time required for the fastest method
+ (i.e., ``ratio = time_auto / min(time_fft, time_direct)``). In these
+ experiments, we found:
+
+ * There is a 95% chance of this ratio being less than 1.5 for 1D signals
+ and a 99% chance of being less than 2.5 for 2D signals.
+ * The ratio was always less than 2.5/5 for 1D/2D signals respectively.
+ * This function is most inaccurate for 1D convolutions that take between 1
+ and 10 milliseconds with ``method='direct'``. A good proxy for this
+ (at least in our experiments) is ``1e6 <= in1.size * in2.size <= 1e7``.
+
+ The 2D results almost certainly generalize to 3D/4D/etc because the
+ implementation is the same (the 1D implementation is different).
+
+ All the numbers above are specific to the EC2 machine. However, we did find
+ that this function generalizes fairly decently across hardware. The speed
+ tests were of similar quality (and even slightly better) than the same
+ tests performed on the machine to tune this function's numbers (a mid-2014
+ 15-inch MacBook Pro with 16GB RAM and a 2.5GHz Intel i7 processor).
+
+ There are cases when `fftconvolve` supports the inputs but this function
+ returns `direct` (e.g., to protect against floating point integer
+ precision).
+
+ .. versionadded:: 0.19
+
+ Examples
+ --------
+ Estimate the fastest method for a given input:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> rng = np.random.default_rng()
+ >>> img = rng.random((32, 32))
+ >>> filter = rng.random((8, 8))
+ >>> method = signal.choose_conv_method(img, filter, mode='same')
+ >>> method
+ 'fft'
+
+ This can then be applied to other arrays of the same dtype and shape:
+
+ >>> img2 = rng.random((32, 32))
+ >>> filter2 = rng.random((8, 8))
+ >>> corr2 = signal.correlate(img2, filter2, mode='same', method=method)
+ >>> conv2 = signal.convolve(img2, filter2, mode='same', method=method)
+
+ The output of this function (``method``) works with `correlate` and
+ `convolve`.
+
+ """
+ xp = array_namespace(in1, in2)
+
+ volume = xp.asarray(in1)
+ kernel = xp.asarray(in2)
+
+ if measure:
+ times = {}
+ for method in ['fft', 'direct']:
+ times[method] = _timeit_fast(lambda: convolve(volume, kernel,
+ mode=mode, method=method))
+
+ chosen_method = 'fft' if times['fft'] < times['direct'] else 'direct'
+ return chosen_method, times
+
+ # for integer input,
+ # catch when more precision required than float provides (representing an
+ # integer as float can lose precision in fftconvolve if larger than 2**52)
+ if any([_numeric_arrays([x], kinds='ui', xp=xp) for x in [volume, kernel]]):
+ max_value = int(xp.max(xp.abs(volume))) * int(xp.max(xp.abs(kernel)))
+ max_value *= int(min(xp_size(volume), xp_size(kernel)))
+ if max_value > 2**np.finfo('float').nmant - 1:
+ return 'direct'
+
+ if _numeric_arrays([volume, kernel], kinds='b', xp=xp):
+ return 'direct'
+
+ if _numeric_arrays([volume, kernel], xp=xp):
+ if _fftconv_faster(volume, kernel, mode):
+ return 'fft'
+
+ return 'direct'
+
+
+def convolve(in1, in2, mode='full', method='auto'):
+ """
+ Convolve two N-dimensional arrays.
+
+ Convolve `in1` and `in2`, with the output size determined by the
+ `mode` argument.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear convolution
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ The output is the same size as `in1`, centered
+ with respect to the 'full' output.
+ method : str {'auto', 'direct', 'fft'}, optional
+ A string indicating which method to use to calculate the convolution.
+
+ ``direct``
+ The convolution is determined directly from sums, the definition of
+ convolution.
+ ``fft``
+ The Fourier Transform is used to perform the convolution by calling
+ `fftconvolve`.
+ ``auto``
+ Automatically chooses direct or Fourier method based on an estimate
+ of which is faster (default). See Notes for more detail.
+
+ .. versionadded:: 0.19.0
+
+ Returns
+ -------
+ convolve : array
+ An N-dimensional array containing a subset of the discrete linear
+ convolution of `in1` with `in2`.
+
+ Warns
+ -----
+ RuntimeWarning
+ Use of the FFT convolution on input containing NAN or INF will lead
+ to the entire output being NAN or INF. Use method='direct' when your
+ input contains NAN or INF values.
+
+ See Also
+ --------
+ numpy.polymul : performs polynomial multiplication (same operation, but
+ also accepts poly1d objects)
+ choose_conv_method : chooses the fastest appropriate convolution method
+ fftconvolve : Always uses the FFT method.
+ oaconvolve : Uses the overlap-add method to do convolution, which is
+ generally faster when the input arrays are large and
+ significantly different in size.
+
+ Notes
+ -----
+ By default, `convolve` and `correlate` use ``method='auto'``, which calls
+ `choose_conv_method` to choose the fastest method using pre-computed
+ values (`choose_conv_method` can also measure real-world timing with a
+ keyword argument). Because `fftconvolve` relies on floating point numbers,
+ there are certain constraints that may force ``method='direct'`` (more detail
+ in `choose_conv_method` docstring).
+
+ Examples
+ --------
+ Smooth a square pulse using a Hann window:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> sig = np.repeat([0., 1., 0.], 100)
+ >>> win = signal.windows.hann(50)
+ >>> filtered = signal.convolve(sig, win, mode='same') / sum(win)
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax_orig, ax_win, ax_filt) = plt.subplots(3, 1, sharex=True)
+ >>> ax_orig.plot(sig)
+ >>> ax_orig.set_title('Original pulse')
+ >>> ax_orig.margins(0, 0.1)
+ >>> ax_win.plot(win)
+ >>> ax_win.set_title('Filter impulse response')
+ >>> ax_win.margins(0, 0.1)
+ >>> ax_filt.plot(filtered)
+ >>> ax_filt.set_title('Filtered signal')
+ >>> ax_filt.margins(0, 0.1)
+ >>> fig.tight_layout()
+ >>> fig.show()
+
+ """
+ xp = array_namespace(in1, in2)
+
+ volume = xp.asarray(in1)
+ kernel = xp.asarray(in2)
+
+ if volume.ndim == kernel.ndim == 0:
+ return volume * kernel
+ elif volume.ndim != kernel.ndim:
+ raise ValueError("volume and kernel should have the same "
+ "dimensionality")
+
+ if _inputs_swap_needed(mode, volume.shape, kernel.shape):
+ # Convolution is commutative; order doesn't have any effect on output
+ volume, kernel = kernel, volume
+
+ if method == 'auto':
+ method = choose_conv_method(volume, kernel, mode=mode)
+
+ if method == 'fft':
+ out = fftconvolve(volume, kernel, mode=mode)
+ result_type = xp.result_type(volume, kernel)
+ if xp.isdtype(result_type, 'integral'):
+ out = xp.round(out)
+
+ if xp.isnan(xp.reshape(out, (-1,))[0]) or xp.isinf(xp.reshape(out, (-1,))[0]):
+ warnings.warn("Use of fft convolution on input with NAN or inf"
+ " results in NAN or inf output. Consider using"
+ " method='direct' instead.",
+ category=RuntimeWarning, stacklevel=2)
+
+ return xp.astype(out, result_type)
+ elif method == 'direct':
+ # fastpath to faster numpy.convolve for 1d inputs when possible
+ if _np_conv_ok(volume, kernel, mode, xp):
+ # convert to numpy and back
+ a_volume = np.asarray(volume)
+ a_kernel = np.asarray(kernel)
+ out = np.convolve(a_volume, a_kernel, mode)
+ return xp.asarray(out)
+
+ return correlate(volume, _reverse_and_conj(kernel, xp), mode, 'direct')
+ else:
+ raise ValueError("Acceptable method flags are 'auto',"
+ " 'direct', or 'fft'.")
+
+
+def order_filter(a, domain, rank):
+ """
+ Perform an order filter on an N-D array.
+
+ Perform an order filter on the array in. The domain argument acts as a
+ mask centered over each pixel. The non-zero elements of domain are
+ used to select elements surrounding each input pixel which are placed
+ in a list. The list is sorted, and the output for that pixel is the
+ element corresponding to rank in the sorted list.
+
+ Parameters
+ ----------
+ a : ndarray
+ The N-dimensional input array.
+ domain : array_like
+ A mask array with the same number of dimensions as `a`.
+ Each dimension should have an odd number of elements.
+ rank : int
+ A non-negative integer which selects the element from the
+ sorted list (0 corresponds to the smallest element, 1 is the
+ next smallest element, etc.).
+
+ Returns
+ -------
+ out : ndarray
+ The results of the order filter in an array with the same
+ shape as `a`.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> x = np.arange(25).reshape(5, 5)
+ >>> domain = np.identity(3)
+ >>> x
+ array([[ 0, 1, 2, 3, 4],
+ [ 5, 6, 7, 8, 9],
+ [10, 11, 12, 13, 14],
+ [15, 16, 17, 18, 19],
+ [20, 21, 22, 23, 24]])
+ >>> signal.order_filter(x, domain, 0)
+ array([[ 0, 0, 0, 0, 0],
+ [ 0, 0, 1, 2, 0],
+ [ 0, 5, 6, 7, 0],
+ [ 0, 10, 11, 12, 0],
+ [ 0, 0, 0, 0, 0]])
+ >>> signal.order_filter(x, domain, 2)
+ array([[ 6, 7, 8, 9, 4],
+ [ 11, 12, 13, 14, 9],
+ [ 16, 17, 18, 19, 14],
+ [ 21, 22, 23, 24, 19],
+ [ 20, 21, 22, 23, 24]])
+
+ """
+ xp = array_namespace(a, domain)
+
+ domain = xp.asarray(domain)
+ for dimsize in domain.shape:
+ if (dimsize % 2) != 1:
+ raise ValueError("Each dimension of domain argument "
+ "should have an odd number of elements.")
+
+ a = xp.asarray(a)
+ if not (
+ xp.isdtype(a.dtype, "integral") or a.dtype in (xp.float32, xp.float64)
+ ):
+ raise ValueError(f"dtype={a.dtype} is not supported by order_filter")
+ result = ndimage.rank_filter(a, rank, footprint=domain, mode='constant')
+ return result
+
+
+def medfilt(volume, kernel_size=None):
+ """
+ Perform a median filter on an N-dimensional array.
+
+ Apply a median filter to the input array using a local window-size
+ given by `kernel_size`. The array will automatically be zero-padded.
+
+ Parameters
+ ----------
+ volume : array_like
+ An N-dimensional input array.
+ kernel_size : array_like, optional
+ A scalar or an N-length list giving the size of the median filter
+ window in each dimension. Elements of `kernel_size` should be odd.
+ If `kernel_size` is a scalar, then this scalar is used as the size in
+ each dimension. Default size is 3 for each dimension.
+
+ Returns
+ -------
+ out : ndarray
+ An array the same size as input containing the median filtered
+ result.
+
+ Warns
+ -----
+ UserWarning
+ If array size is smaller than kernel size along any dimension
+
+ See Also
+ --------
+ scipy.ndimage.median_filter
+ scipy.signal.medfilt2d
+
+ """
+ xp = array_namespace(volume)
+ volume = xp.asarray(volume)
+ if volume.ndim == 0:
+ volume = xpx.atleast_nd(volume, ndim=1, xp=xp)
+
+ if not (xp.isdtype(volume.dtype, "integral") or
+ volume.dtype in [xp.float32, xp.float64]):
+ raise ValueError(f"dtype={volume.dtype} is not supported by medfilt")
+
+ if kernel_size is None:
+ kernel_size = [3] * volume.ndim
+ kernel_size = xp.asarray(kernel_size)
+ if kernel_size.shape == ():
+ kernel_size = xp.repeat(kernel_size, volume.ndim)
+
+ for k in range(volume.ndim):
+ if (kernel_size[k] % 2) != 1:
+ raise ValueError("Each element of kernel_size should be odd.")
+ if any(k > s for k, s in zip(kernel_size, volume.shape)):
+ warnings.warn('kernel_size exceeds volume extent: the volume will be '
+ 'zero-padded.',
+ stacklevel=2)
+
+ size = math.prod(kernel_size)
+ result = ndimage.rank_filter(volume, size // 2, size=kernel_size,
+ mode='constant')
+
+ return result
+
+
+def wiener(im, mysize=None, noise=None):
+ """
+ Perform a Wiener filter on an N-dimensional array.
+
+ Apply a Wiener filter to the N-dimensional array `im`.
+
+ Parameters
+ ----------
+ im : ndarray
+ An N-dimensional array.
+ mysize : int or array_like, optional
+ A scalar or an N-length list giving the size of the Wiener filter
+ window in each dimension. Elements of mysize should be odd.
+ If mysize is a scalar, then this scalar is used as the size
+ in each dimension.
+ noise : float, optional
+ The noise-power to use. If None, then noise is estimated as the
+ average of the local variance of the input.
+
+ Returns
+ -------
+ out : ndarray
+ Wiener filtered result with the same shape as `im`.
+
+ Notes
+ -----
+ This implementation is similar to wiener2 in Matlab/Octave.
+ For more details see [1]_
+
+ References
+ ----------
+ .. [1] Lim, Jae S., Two-Dimensional Signal and Image Processing,
+ Englewood Cliffs, NJ, Prentice Hall, 1990, p. 548.
+
+ Examples
+ --------
+ >>> from scipy.datasets import face
+ >>> from scipy.signal import wiener
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> rng = np.random.default_rng()
+ >>> img = rng.random((40, 40)) #Create a random image
+ >>> filtered_img = wiener(img, (5, 5)) #Filter the image
+ >>> f, (plot1, plot2) = plt.subplots(1, 2)
+ >>> plot1.imshow(img)
+ >>> plot2.imshow(filtered_img)
+ >>> plt.show()
+
+ """
+ xp = array_namespace(im)
+
+ im = xp.asarray(im)
+ if mysize is None:
+ mysize = [3] * im.ndim
+ mysize_arr = xp.asarray(mysize)
+ if mysize_arr.shape == ():
+ mysize = [mysize] * im.ndim
+
+ # Estimate the local mean
+ size = math.prod(mysize)
+ lMean = correlate(im, xp.ones(mysize), 'same')
+ lsize = float(size)
+ lMean = lMean / lsize
+
+ # Estimate the local variance
+ lVar = (correlate(im ** 2, xp.ones(mysize), 'same') / lsize - lMean ** 2)
+
+ # Estimate the noise power if needed.
+ if noise is None:
+ noise = xp.mean(xp.reshape(lVar, (-1,)), axis=0)
+
+ res = (im - lMean)
+ res *= (1 - noise / lVar)
+ res += lMean
+ out = xp.where(lVar < noise, lMean, res)
+
+ return out
+
+
+def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0):
+ """
+ Convolve two 2-dimensional arrays.
+
+ Convolve `in1` and `in2` with output size determined by `mode`, and
+ boundary conditions determined by `boundary` and `fillvalue`.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear convolution
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ The output is the same size as `in1`, centered
+ with respect to the 'full' output.
+ boundary : str {'fill', 'wrap', 'symm'}, optional
+ A flag indicating how to handle boundaries:
+
+ ``fill``
+ pad input arrays with fillvalue. (default)
+ ``wrap``
+ circular boundary conditions.
+ ``symm``
+ symmetrical boundary conditions.
+
+ fillvalue : scalar, optional
+ Value to fill pad input arrays with. Default is 0.
+
+ Returns
+ -------
+ out : ndarray
+ A 2-dimensional array containing a subset of the discrete linear
+ convolution of `in1` with `in2`.
+
+ Examples
+ --------
+ Compute the gradient of an image by 2D convolution with a complex Scharr
+ operator. (Horizontal operator is real, vertical is imaginary.) Use
+ symmetric boundary condition to avoid creating edges at the image
+ boundaries.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy import datasets
+ >>> ascent = datasets.ascent()
+ >>> scharr = np.array([[ -3-3j, 0-10j, +3 -3j],
+ ... [-10+0j, 0+ 0j, +10 +0j],
+ ... [ -3+3j, 0+10j, +3 +3j]]) # Gx + j*Gy
+ >>> grad = signal.convolve2d(ascent, scharr, boundary='symm', mode='same')
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax_orig, ax_mag, ax_ang) = plt.subplots(3, 1, figsize=(6, 15))
+ >>> ax_orig.imshow(ascent, cmap='gray')
+ >>> ax_orig.set_title('Original')
+ >>> ax_orig.set_axis_off()
+ >>> ax_mag.imshow(np.absolute(grad), cmap='gray')
+ >>> ax_mag.set_title('Gradient magnitude')
+ >>> ax_mag.set_axis_off()
+ >>> ax_ang.imshow(np.angle(grad), cmap='hsv') # hsv is cyclic, like angles
+ >>> ax_ang.set_title('Gradient orientation')
+ >>> ax_ang.set_axis_off()
+ >>> fig.show()
+
+ """
+ xp = array_namespace(in1, in2)
+
+ # NB: do work in NumPy, only convert the output
+
+ in1 = np.asarray(in1)
+ in2 = np.asarray(in2)
+
+ if not in1.ndim == in2.ndim == 2:
+ raise ValueError('convolve2d inputs must both be 2-D arrays')
+
+ if _inputs_swap_needed(mode, in1.shape, in2.shape):
+ in1, in2 = in2, in1
+
+ val = _valfrommode(mode)
+ bval = _bvalfromboundary(boundary)
+ out = _sigtools._convolve2d(in1, in2, 1, val, bval, fillvalue)
+ return xp.asarray(out)
+
+
+def correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0):
+ """
+ Cross-correlate two 2-dimensional arrays.
+
+ Cross correlate `in1` and `in2` with output size determined by `mode`, and
+ boundary conditions determined by `boundary` and `fillvalue`.
+
+ Parameters
+ ----------
+ in1 : array_like
+ First input.
+ in2 : array_like
+ Second input. Should have the same number of dimensions as `in1`.
+ mode : str {'full', 'valid', 'same'}, optional
+ A string indicating the size of the output:
+
+ ``full``
+ The output is the full discrete linear cross-correlation
+ of the inputs. (Default)
+ ``valid``
+ The output consists only of those elements that do not
+ rely on the zero-padding. In 'valid' mode, either `in1` or `in2`
+ must be at least as large as the other in every dimension.
+ ``same``
+ The output is the same size as `in1`, centered
+ with respect to the 'full' output.
+ boundary : str {'fill', 'wrap', 'symm'}, optional
+ A flag indicating how to handle boundaries:
+
+ ``fill``
+ pad input arrays with fillvalue. (default)
+ ``wrap``
+ circular boundary conditions.
+ ``symm``
+ symmetrical boundary conditions.
+
+ fillvalue : scalar, optional
+ Value to fill pad input arrays with. Default is 0.
+
+ Returns
+ -------
+ correlate2d : ndarray
+ A 2-dimensional array containing a subset of the discrete linear
+ cross-correlation of `in1` with `in2`.
+
+ Notes
+ -----
+ When using "same" mode with even-length inputs, the outputs of `correlate`
+ and `correlate2d` differ: There is a 1-index offset between them.
+
+ Examples
+ --------
+ Use 2D cross-correlation to find the location of a template in a noisy
+ image:
+
+ >>> import numpy as np
+ >>> from scipy import signal, datasets, ndimage
+ >>> rng = np.random.default_rng()
+ >>> face = datasets.face(gray=True) - datasets.face(gray=True).mean()
+ >>> face = ndimage.zoom(face[30:500, 400:950], 0.5) # extract the face
+ >>> template = np.copy(face[135:165, 140:175]) # right eye
+ >>> template -= template.mean()
+ >>> face = face + rng.standard_normal(face.shape) * 50 # add noise
+ >>> corr = signal.correlate2d(face, template, boundary='symm', mode='same')
+ >>> y, x = np.unravel_index(np.argmax(corr), corr.shape) # find the match
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax_orig, ax_template, ax_corr) = plt.subplots(3, 1,
+ ... figsize=(6, 15))
+ >>> ax_orig.imshow(face, cmap='gray')
+ >>> ax_orig.set_title('Original')
+ >>> ax_orig.set_axis_off()
+ >>> ax_template.imshow(template, cmap='gray')
+ >>> ax_template.set_title('Template')
+ >>> ax_template.set_axis_off()
+ >>> ax_corr.imshow(corr, cmap='gray')
+ >>> ax_corr.set_title('Cross-correlation')
+ >>> ax_corr.set_axis_off()
+ >>> ax_orig.plot(x, y, 'ro')
+ >>> fig.show()
+
+ """
+ xp = array_namespace(in1, in2)
+ in1 = np.asarray(in1)
+ in2 = np.asarray(in2)
+
+ if not in1.ndim == in2.ndim == 2:
+ raise ValueError('correlate2d inputs must both be 2-D arrays')
+
+ swapped_inputs = _inputs_swap_needed(mode, in1.shape, in2.shape)
+ if swapped_inputs:
+ in1, in2 = in2, in1
+
+ val = _valfrommode(mode)
+ bval = _bvalfromboundary(boundary)
+ out = _sigtools._convolve2d(in1, in2.conj(), 0, val, bval, fillvalue)
+
+ if swapped_inputs:
+ out = out[::-1, ::-1]
+
+ return xp.asarray(out)
+
+
+def medfilt2d(input, kernel_size=3):
+ """
+ Median filter a 2-dimensional array.
+
+ Apply a median filter to the `input` array using a local window-size
+ given by `kernel_size` (must be odd). The array is zero-padded
+ automatically.
+
+ Parameters
+ ----------
+ input : array_like
+ A 2-dimensional input array.
+ kernel_size : array_like, optional
+ A scalar or a list of length 2, giving the size of the
+ median filter window in each dimension. Elements of
+ `kernel_size` should be odd. If `kernel_size` is a scalar,
+ then this scalar is used as the size in each dimension.
+ Default is a kernel of size (3, 3).
+
+ Returns
+ -------
+ out : ndarray
+ An array the same size as input containing the median filtered
+ result.
+
+ See Also
+ --------
+ scipy.ndimage.median_filter
+
+ Notes
+ -----
+ This is faster than `medfilt` when the input dtype is ``uint8``,
+ ``float32``, or ``float64``; for other types, this falls back to
+ `medfilt`. In some situations, `scipy.ndimage.median_filter` may be
+ faster than this function.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> x = np.arange(25).reshape(5, 5)
+ >>> x
+ array([[ 0, 1, 2, 3, 4],
+ [ 5, 6, 7, 8, 9],
+ [10, 11, 12, 13, 14],
+ [15, 16, 17, 18, 19],
+ [20, 21, 22, 23, 24]])
+
+ # Replaces i,j with the median out of 5*5 window
+
+ >>> signal.medfilt2d(x, kernel_size=5)
+ array([[ 0, 0, 2, 0, 0],
+ [ 0, 3, 7, 4, 0],
+ [ 2, 8, 12, 9, 4],
+ [ 0, 8, 12, 9, 0],
+ [ 0, 0, 12, 0, 0]])
+
+ # Replaces i,j with the median out of default 3*3 window
+
+ >>> signal.medfilt2d(x)
+ array([[ 0, 1, 2, 3, 0],
+ [ 1, 6, 7, 8, 4],
+ [ 6, 11, 12, 13, 9],
+ [11, 16, 17, 18, 14],
+ [ 0, 16, 17, 18, 0]])
+
+ # Replaces i,j with the median out of default 5*3 window
+
+ >>> signal.medfilt2d(x, kernel_size=[5,3])
+ array([[ 0, 1, 2, 3, 0],
+ [ 0, 6, 7, 8, 3],
+ [ 5, 11, 12, 13, 8],
+ [ 5, 11, 12, 13, 8],
+ [ 0, 11, 12, 13, 0]])
+
+ # Replaces i,j with the median out of default 3*5 window
+
+ >>> signal.medfilt2d(x, kernel_size=[3,5])
+ array([[ 0, 0, 2, 1, 0],
+ [ 1, 5, 7, 6, 3],
+ [ 6, 10, 12, 11, 8],
+ [11, 15, 17, 16, 13],
+ [ 0, 15, 17, 16, 0]])
+
+ # As seen in the examples,
+ # kernel numbers must be odd and not exceed original array dim
+
+ """
+ xp = array_namespace(input)
+
+ image = np.asarray(input)
+
+ # checking dtype.type, rather than just dtype, is necessary for
+ # excluding np.longdouble with MS Visual C.
+ if image.dtype.type not in (np.ubyte, np.float32, np.float64):
+ return xp.asarray(medfilt(image, kernel_size))
+
+ if kernel_size is None:
+ kernel_size = [3] * 2
+ kernel_size = np.asarray(kernel_size)
+ if kernel_size.shape == ():
+ kernel_size = np.repeat(kernel_size.item(), 2)
+
+ for size in kernel_size:
+ if (size % 2) != 1:
+ raise ValueError("Each element of kernel_size should be odd.")
+
+ result_np = _sigtools._medfilt2d(image, kernel_size)
+ return xp.asarray(result_np)
+
+
+def lfilter(b, a, x, axis=-1, zi=None):
+ """
+ Filter data along one-dimension with an IIR or FIR filter.
+
+ Filter a data sequence, `x`, using a digital filter. This works for many
+ fundamental data types (including Object type). The filter is a direct
+ form II transposed implementation of the standard difference equation
+ (see Notes).
+
+ The function `sosfilt` (and filter design using ``output='sos'``) should be
+ preferred over `lfilter` for most filtering tasks, as second-order sections
+ have fewer numerical problems.
+
+ Parameters
+ ----------
+ b : array_like
+ The numerator coefficient vector in a 1-D sequence.
+ a : array_like
+ The denominator coefficient vector in a 1-D sequence. If ``a[0]``
+ is not 1, then both `a` and `b` are normalized by ``a[0]``.
+ x : array_like
+ An N-dimensional input array.
+ axis : int, optional
+ The axis of the input data array along which to apply the
+ linear filter. The filter is applied to each subarray along
+ this axis. Default is -1.
+ zi : array_like, optional
+ Initial conditions for the filter delays. It is a vector
+ (or array of vectors for an N-dimensional input) of length
+ ``max(len(a), len(b)) - 1``. If `zi` is None or is not given then
+ initial rest is assumed. See `lfiltic` for more information.
+
+ Returns
+ -------
+ y : array
+ The output of the digital filter.
+ zf : array, optional
+ If `zi` is None, this is not returned, otherwise, `zf` holds the
+ final filter delay values.
+
+ See Also
+ --------
+ lfiltic : Construct initial conditions for `lfilter`.
+ lfilter_zi : Compute initial state (steady state of step response) for
+ `lfilter`.
+ filtfilt : A forward-backward filter, to obtain a filter with zero phase.
+ savgol_filter : A Savitzky-Golay filter.
+ sosfilt: Filter data using cascaded second-order sections.
+ sosfiltfilt: A forward-backward filter using second-order sections.
+
+ Notes
+ -----
+ The filter function is implemented as a direct II transposed structure.
+ This means that the filter implements::
+
+ a[0]*y[n] = b[0]*x[n] + b[1]*x[n-1] + ... + b[M]*x[n-M]
+ - a[1]*y[n-1] - ... - a[N]*y[n-N]
+
+ where `M` is the degree of the numerator, `N` is the degree of the
+ denominator, and `n` is the sample number. It is implemented using
+ the following difference equations (assuming M = N)::
+
+ a[0]*y[n] = b[0] * x[n] + d[0][n-1]
+ d[0][n] = b[1] * x[n] - a[1] * y[n] + d[1][n-1]
+ d[1][n] = b[2] * x[n] - a[2] * y[n] + d[2][n-1]
+ ...
+ d[N-2][n] = b[N-1]*x[n] - a[N-1]*y[n] + d[N-1][n-1]
+ d[N-1][n] = b[N] * x[n] - a[N] * y[n]
+
+ where `d` are the state variables.
+
+ The rational transfer function describing this filter in the
+ z-transform domain is::
+
+ -1 -M
+ b[0] + b[1]z + ... + b[M] z
+ Y(z) = -------------------------------- X(z)
+ -1 -N
+ a[0] + a[1]z + ... + a[N] z
+
+ Examples
+ --------
+ Generate a noisy signal to be filtered:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+ >>> t = np.linspace(-1, 1, 201)
+ >>> x = (np.sin(2*np.pi*0.75*t*(1-t) + 2.1) +
+ ... 0.1*np.sin(2*np.pi*1.25*t + 1) +
+ ... 0.18*np.cos(2*np.pi*3.85*t))
+ >>> xn = x + rng.standard_normal(len(t)) * 0.08
+
+ Create an order 3 lowpass butterworth filter:
+
+ >>> b, a = signal.butter(3, 0.05)
+
+ Apply the filter to xn. Use lfilter_zi to choose the initial condition of
+ the filter:
+
+ >>> zi = signal.lfilter_zi(b, a)
+ >>> z, _ = signal.lfilter(b, a, xn, zi=zi*xn[0])
+
+ Apply the filter again, to have a result filtered at an order the same as
+ filtfilt:
+
+ >>> z2, _ = signal.lfilter(b, a, z, zi=zi*z[0])
+
+ Use filtfilt to apply the filter:
+
+ >>> y = signal.filtfilt(b, a, xn)
+
+ Plot the original signal and the various filtered versions:
+
+ >>> plt.figure
+ >>> plt.plot(t, xn, 'b', alpha=0.75)
+ >>> plt.plot(t, z, 'r--', t, z2, 'r', t, y, 'k')
+ >>> plt.legend(('noisy signal', 'lfilter, once', 'lfilter, twice',
+ ... 'filtfilt'), loc='best')
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ """
+ xp = array_namespace(b, a, x, zi)
+
+ b = np.atleast_1d(b)
+ a = np.atleast_1d(a)
+ x = np.asarray(x)
+ if zi is not None:
+ zi = np.asarray(zi)
+
+ if not (b.ndim == 1 and xp_size(b) > 0):
+ raise ValueError(f"Parameter b is not a non-empty 1d array, since {b.shape=}!")
+ if not (a.ndim == 1 and xp_size(a) > 0):
+ raise ValueError(f"Parameter a is not a non-empty 1d array, since {a.shape=}!")
+
+ if len(a) == 1:
+ # This path only supports types fdgFDGO to mirror _linear_filter below.
+ # Any of b, a, x, or zi can set the dtype, but there is no default
+ # casting of other types; instead a NotImplementedError is raised.
+ b = np.asarray(b)
+ a = np.asarray(a)
+ x = _validate_x(x)
+ inputs = [b, a, x]
+ if zi is not None:
+ # _linear_filter does not broadcast zi, but does do expansion of
+ # singleton dims.
+ zi = np.asarray(zi)
+ if zi.ndim != x.ndim:
+ raise ValueError("Dimensions of parameters x and zi must match, but " +
+ f"{x.ndim=}, {zi.ndim=}!")
+ expected_shape = list(x.shape)
+ expected_shape[axis] = b.shape[0] - 1
+ expected_shape = tuple(expected_shape)
+ # check the trivial case where zi is the right shape first
+ if zi.shape != expected_shape:
+ strides = zi.ndim * [None]
+ if axis < 0:
+ axis += zi.ndim
+ for k in range(zi.ndim):
+ if k == axis and zi.shape[k] == expected_shape[k]:
+ strides[k] = zi.strides[k]
+ elif k != axis and zi.shape[k] == expected_shape[k]:
+ strides[k] = zi.strides[k]
+ elif k != axis and zi.shape[k] == 1:
+ strides[k] = 0
+ else:
+ raise ValueError('Unexpected shape for parameter zi: expected '
+ f'{expected_shape}, found {zi.shape}.')
+ zi = np.lib.stride_tricks.as_strided(zi, expected_shape,
+ strides)
+ inputs.append(zi)
+ dtype = np.result_type(*inputs)
+
+ if dtype.char not in 'fdgFDGO':
+ raise NotImplementedError("Parameter's dtypes produced result type " +
+ f"'{dtype}', which is not supported!")
+
+ b = np.array(b, dtype=dtype)
+ a = np.asarray(a, dtype=dtype)
+ b /= a[0]
+ x = np.asarray(x, dtype=dtype)
+
+ out_full = np.apply_along_axis(lambda y: np.convolve(b, y), axis, x)
+ ind = out_full.ndim * [slice(None)]
+ if zi is not None:
+ ind[axis] = slice(zi.shape[axis])
+ out_full[tuple(ind)] += zi
+
+ ind[axis] = slice(out_full.shape[axis] - len(b) + 1)
+ out = out_full[tuple(ind)]
+
+ if zi is None:
+ return xp.asarray(out)
+ else:
+ ind[axis] = slice(out_full.shape[axis] - len(b) + 1, None)
+ zf = out_full[tuple(ind)]
+ return xp.asarray(out), xp.asarray(zf)
+ else:
+ if zi is None:
+ result =_sigtools._linear_filter(b, a, x, axis)
+ return xp.asarray(result)
+ else:
+ out, zf = _sigtools._linear_filter(b, a, x, axis, zi)
+ return xp.asarray(out), xp.asarray(zf)
+
+
+def lfiltic(b, a, y, x=None):
+ """
+ Construct initial conditions for lfilter given input and output vectors.
+
+ Given a linear filter (b, a) and initial conditions on the output `y`
+ and the input `x`, return the initial conditions on the state vector zi
+ which is used by `lfilter` to generate the output given the input.
+
+ Parameters
+ ----------
+ b : array_like
+ Linear filter term.
+ a : array_like
+ Linear filter term.
+ y : array_like
+ Initial conditions.
+
+ If ``N = len(a) - 1``, then ``y = {y[-1], y[-2], ..., y[-N]}``.
+
+ If `y` is too short, it is padded with zeros.
+ x : array_like, optional
+ Initial conditions.
+
+ If ``M = len(b) - 1``, then ``x = {x[-1], x[-2], ..., x[-M]}``.
+
+ If `x` is not given, its initial conditions are assumed zero.
+
+ If `x` is too short, it is padded with zeros.
+
+ Returns
+ -------
+ zi : ndarray
+ The state vector ``zi = {z_0[-1], z_1[-1], ..., z_K-1[-1]}``,
+ where ``K = max(M, N)``.
+
+ See Also
+ --------
+ lfilter, lfilter_zi
+
+ """
+ xp = array_namespace(a, b, y, x)
+
+ a = xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp)
+ b = xpx.atleast_nd(xp.asarray(b), ndim=1, xp=xp)
+ if a.ndim > 1:
+ raise ValueError('Filter coefficients `a` must be 1-D.')
+ if b.ndim > 1:
+ raise ValueError('Filter coefficients `b` must be 1-D.')
+ N = a.shape[0] - 1
+ M = b.shape[0] - 1
+ K = max(M, N)
+ y = xp.asarray(y)
+
+ if N < 0:
+ raise ValueError("There must be at least one `a` coefficient.")
+
+ if x is None:
+ result_type = xp.result_type(b, a, y)
+ if xp.isdtype(result_type, ('bool', 'integral')): #'bui':
+ result_type = xp.float64
+ x = xp.zeros(M, dtype=result_type)
+ else:
+ x = xp.asarray(x)
+
+ result_type = xp.result_type(b, a, y, x)
+ if xp.isdtype(result_type, ('bool', 'integral')): #'bui':
+ result_type = xp.float64
+ x = xp.astype(x, result_type)
+
+ L = xp_size(x)
+ if L < M:
+ x = xp.concat((x, xp.zeros(M - L)))
+
+ y = xp.astype(y, result_type)
+ zi = xp.zeros(K, dtype=result_type)
+
+ L = xp_size(y)
+ if L < N:
+ y = xp.concat((y, xp.zeros(N - L)))
+
+ for m in range(M):
+ zi[m] = xp.sum(b[m + 1:] * x[:M - m], axis=0)
+
+ for m in range(N):
+ zi[m] -= xp.sum(a[m + 1:] * y[:N - m], axis=0)
+
+ if a[0] != 1.:
+ if a[0] == 0.:
+ raise ValueError("First `a` filter coefficient must be non-zero.")
+ zi /= a[0]
+
+ return zi
+
+
+def deconvolve(signal, divisor):
+ """Deconvolves ``divisor`` out of ``signal`` using inverse filtering.
+
+ Returns the quotient and remainder such that
+ ``signal = convolve(divisor, quotient) + remainder``
+
+ Parameters
+ ----------
+ signal : (N,) array_like
+ Signal data, typically a recorded signal
+ divisor : (N,) array_like
+ Divisor data, typically an impulse response or filter that was
+ applied to the original signal
+
+ Returns
+ -------
+ quotient : ndarray
+ Quotient, typically the recovered original signal
+ remainder : ndarray
+ Remainder
+
+ See Also
+ --------
+ numpy.polydiv : performs polynomial division (same operation, but
+ also accepts poly1d objects)
+
+ Examples
+ --------
+ Deconvolve a signal that's been filtered:
+
+ >>> from scipy import signal
+ >>> original = [0, 1, 0, 0, 1, 1, 0, 0]
+ >>> impulse_response = [2, 1]
+ >>> recorded = signal.convolve(impulse_response, original)
+ >>> recorded
+ array([0, 2, 1, 0, 2, 3, 1, 0, 0])
+ >>> recovered, remainder = signal.deconvolve(recorded, impulse_response)
+ >>> recovered
+ array([ 0., 1., 0., 0., 1., 1., 0., 0.])
+ >>> remainder
+ array([0., 0., 0., 0., 0., 0., 0., 0., 0.])
+ """
+ xp = array_namespace(signal, divisor)
+
+ num = xpx.atleast_nd(xp.asarray(signal), ndim=1, xp=xp)
+ den = xpx.atleast_nd(xp.asarray(divisor), ndim=1, xp=xp)
+ if not (num.ndim == 1 and xp_size(num) > 0):
+ raise ValueError("Parameter signal must be non-empty 1d array, " +
+ f"but its shape is {num.shape}!")
+ if not (den.ndim == 1 and xp_size(den) > 0):
+ raise ValueError("Parameter divisor must be non-empty 1d array, " +
+ f"but its shape is {den.shape}!")
+ N = num.shape[0]
+ D = den.shape[0]
+ if D > N:
+ quot = []
+ rem = num
+ else:
+ input = xp.zeros(N - D + 1, dtype=xp.float64)
+ input[0] = 1
+ quot = lfilter(num, den, input)
+ rem = num - convolve(den, quot, mode='full')
+ return quot, rem
+
+
+def hilbert(x, N=None, axis=-1):
+ r"""FFT-based computation of the analytic signal.
+
+ The analytic signal is calculated by zeroing out the negative frequencies and
+ doubling the amplitudes of the positive frequencies in the FFT domain.
+ The imaginary part of the result is the hilbert transform of the real-valued input
+ signal.
+
+ The transformation is done along the last axis by default.
+
+ For numpy arrays, `scipy.fft.set_workers` can be used to change the number of
+ workers used for the FFTs.
+
+ Parameters
+ ----------
+ x : array_like
+ Signal data. Must be real.
+ N : int, optional
+ Number of output samples. `x` is initially cropped or zero-padded to length
+ `N` along `axis`. Default: ``x.shape[axis]``
+ axis : int, optional
+ Axis along which to do the transformation. Default: -1.
+
+ Returns
+ -------
+ xa : ndarray
+ Analytic signal of `x`, of each 1-D array along `axis`
+
+ Notes
+ -----
+ The analytic signal ``x_a(t)`` of a real-valued signal ``x(t)``
+ can be expressed as [1]_
+
+ .. math:: x_a = F^{-1}(F(x) 2U) = x + i y\ ,
+
+ where `F` is the Fourier transform, `U` the unit step function,
+ and `y` the Hilbert transform of `x`. [2]_
+
+ In other words, the negative half of the frequency spectrum is zeroed
+ out, turning the real-valued signal into a complex-valued signal. The Hilbert
+ transformed signal can be obtained from ``np.imag(hilbert(x))``, and the
+ original signal from ``np.real(hilbert(x))``.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Analytic signal".
+ https://en.wikipedia.org/wiki/Analytic_signal
+ .. [2] Wikipedia, "Hilbert Transform".
+ https://en.wikipedia.org/wiki/Hilbert_transform
+ .. [3] Leon Cohen, "Time-Frequency Analysis", 1995. Chapter 2.
+ .. [4] Alan V. Oppenheim, Ronald W. Schafer. Discrete-Time Signal
+ Processing, Third Edition, 2009. Chapter 12.
+ ISBN 13: 978-1292-02572-8
+
+ See Also
+ --------
+ envelope: Compute envelope of a real- or complex-valued signal.
+
+ Examples
+ --------
+ In this example we use the Hilbert transform to determine the amplitude
+ envelope and instantaneous frequency of an amplitude-modulated signal.
+
+ Let's create a chirp of which the frequency increases from 20 Hz to 100 Hz and
+ apply an amplitude modulation:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import hilbert, chirp
+ ...
+ >>> duration, fs = 1, 400 # 1 s signal with sampling frequency of 400 Hz
+ >>> t = np.arange(int(fs*duration)) / fs # timestamps of samples
+ >>> signal = chirp(t, 20.0, t[-1], 100.0)
+ >>> signal *= (1.0 + 0.5 * np.sin(2.0*np.pi*3.0*t) )
+
+ The amplitude envelope is given by the magnitude of the analytic signal. The
+ instantaneous frequency can be obtained by differentiating the
+ instantaneous phase in respect to time. The instantaneous phase corresponds
+ to the phase angle of the analytic signal.
+
+ >>> analytic_signal = hilbert(signal)
+ >>> amplitude_envelope = np.abs(analytic_signal)
+ >>> instantaneous_phase = np.unwrap(np.angle(analytic_signal))
+ >>> instantaneous_frequency = np.diff(instantaneous_phase) / (2.0*np.pi) * fs
+ ...
+ >>> fig, (ax0, ax1) = plt.subplots(nrows=2, sharex='all', tight_layout=True)
+ >>> ax0.set_title("Amplitude-modulated Chirp Signal")
+ >>> ax0.set_ylabel("Amplitude")
+ >>> ax0.plot(t, signal, label='Signal')
+ >>> ax0.plot(t, amplitude_envelope, label='Envelope')
+ >>> ax0.legend()
+ >>> ax1.set(xlabel="Time in seconds", ylabel="Frequency in Hz", ylim=(0, 120))
+ >>> ax1.plot(t[1:], instantaneous_frequency, 'C2-',
+ ... label='Instantaneous Frequency')
+ >>> ax1.legend()
+ >>> plt.show()
+
+ """
+ xp = array_namespace(x)
+
+ x = xp.asarray(x)
+ if xp.isdtype(x.dtype, 'complex floating'):
+ raise ValueError("x must be real.")
+
+ if N is None:
+ N = x.shape[axis]
+ if N <= 0:
+ raise ValueError("N must be positive.")
+
+ Xf = sp_fft.fft(x, N, axis=axis)
+ Xf = xp.moveaxis(Xf, axis, -1)
+ if N % 2 == 0:
+ Xf[..., 1: N // 2] *= 2.0
+ Xf[..., N // 2 + 1:N] = 0.0
+ else:
+ Xf[..., 1:(N + 1) // 2] *= 2.0
+ Xf[..., (N + 1) // 2:N] = 0.0
+
+ Xf = xp.moveaxis(Xf, -1, axis)
+ x = sp_fft.ifft(Xf, axis=axis)
+ return x
+
+
+def hilbert2(x, N=None, axes=(-2, -1)):
+ r"""Compute the '2-D' analytic signal of `x`.
+
+ The 2-D analytic signal is calculated as a so-called "single-orthant" transform.
+ This is achieved by applying one-dimensional Hilbert functions (as in
+ `~scipy.signal.hilbert`) to the first and to the second array axis in Fourier space.
+
+ For NumPy arrays, `scipy.fft.set_workers` can be used to change the number of
+ workers used for the FFTs.
+
+ Parameters
+ ----------
+ x : array_like
+ Input signal. Must be at least two-dimensional.
+ N : int or tuple of two ints, optional
+ Number of output samples. `x` is initially cropped or zero-padded to length
+ `N` along `axes`. Default: ``x.shape[i] for i in axes``
+ axes : tuple of two ints, optional
+ Axes along which to do the transformation. Default: (-2, -1).
+
+ .. versionchanged:: 1.17
+
+ Added `axes` parameter
+
+ Returns
+ -------
+ xa : ndarray
+ Analytic signal of `x` taken along given axes.
+
+ Notes
+ -----
+ The "single-orthant" transform, as defined in [2]_, is calculated by performing the
+ following steps:
+
+ 1. Calculate the two-dimensional FFT of the input, i.e.,
+
+ .. math::
+
+ X[p,q] = \sum_{k,l=0}^{N_0,N_1} x[k,l]\,
+ e^{-2j\pi k p/N_0}\, e^{-2j\pi l q/N_1}
+
+ 2. Zero negative frequency bins and double their positive counterparts, i.e.,
+
+ .. math::
+
+ X_a[p,q] = \big(1 + s_{N_0}(p)\big) \big(1 + s_{N_1}(q)\big) X[p,q]
+
+ with :math:`s_N(.)` being a modified sign function defined as
+
+ .. math::
+
+ s_N(p) := \begin{cases}
+ -1 & \text{ for } p < 0\ ,\\
+ \phantom{-}0 & \text{ for } p = 0\ ,\\
+ +1 & \text{ for } 1 \leq p < (N+1) // 2\ ,\\
+ \phantom{-}0 & \text{ elsewhere.}
+ \end{cases}
+
+ The limitation of the ":math:`+1`" case to the range of ``[1:(N+1)//2]``
+ accounts for the unpaired Nyquist frequency bin at :math:`N/2` for even
+ :math:`N`. Note that :math:`X_a[p] = \big(1 + s_N(p)\big) X[p]` is the
+ one-dimensional Hilbert function (as in `~scipy.signal.hilbert`) in Fourier
+ space.
+
+ 3. Produce the analytic signal by performing the inverse FFT, i.e.,
+
+ .. math::
+
+ x_a[k, l] = \frac{1}{N_0 N_1}
+ \sum_{p,q=0}^{N_0,N_1} X_a[p,q]\, e^{2j\pi k p/N_0}\, e^{2j\pi l q/N_1}
+
+ The "single-orthant" transform is not the only possible definition of an analytic
+ signal in multiple dimensions (as noted in [1]_). Consult [3]_ for a description of
+ properties that this 2-D transform does and does not share with the 1-D transform.
+ The second example below shows one of the downsides of this approach.
+
+ References
+ ----------
+ .. [1] Wikipedia, "Analytic signal",
+ https://en.wikipedia.org/wiki/Analytic_signal
+ .. [2] Hahn, Stefan L. "Multidimensional complex signals with
+ single-orthant spectra." Proceedings of the IEEE 80.8
+ (1992): 1287-1300.
+ `PDF `__
+ .. [3] Bülow, Thomas, and Gerald Sommer. "A novel approach to the 2D analytic
+ signal." In International Conference on Computer Analysis of Images and
+ Patterns, pp. 25-32. Berlin, Heidelberg: Springer Berlin Heidelberg, 1999.
+ `PDF `__
+
+ Examples
+ --------
+ The following example calculates the two-dimensional analytic signal from a single
+ impulse with an added constant offset. The impulse produces an FFT where each bin
+ has a value of one and the constant offset component produces only a non-zero
+ component at the ``(0,0)`` bin.
+
+ >>> import numpy as np
+ >>> from scipy.fft import fft2, fftshift, ifftshift
+ >>> from scipy.signal import hilbert2
+ ...
+ >>> # Input signal is unit impulse with a constant offset:
+ >>> x = np.ones((5, 5)) / 5
+ >>> x[0, 0] += 1
+ ...
+ >>> X = fftshift(fft2(x)) # Zero frequency bin is at center
+ >>> print(X)
+ [[1.-0.j 1.-0.j 1.-0.j 1.+0.j 1.+0.j]
+ [1.-0.j 1.-0.j 1.-0.j 1.+0.j 1.+0.j]
+ [1.-0.j 1.-0.j 6.-0.j 1.+0.j 1.+0.j]
+ [1.-0.j 1.-0.j 1.+0.j 1.+0.j 1.+0.j]
+ [1.-0.j 1.-0.j 1.+0.j 1.+0.j 1.+0.j]]
+ >>> x_a = hilbert2(x)
+ >>> X_a = fftshift(fft2(x_a))
+ >>> print(np.round(X_a, 3))
+ [[ 0.+0.j 0.+0.j -0.+0.j 0.+0.j 0.+0.j]
+ [ 0.+0.j 0.+0.j -0.+0.j 0.+0.j 0.+0.j]
+ [ 0.+0.j 0.+0.j 6.+0.j 2.+0.j 2.+0.j]
+ [ 0.+0.j 0.+0.j 2.+0.j 4.+0.j 4.+0.j]
+ [ 0.+0.j 0.+0.j 2.+0.j 4.+0.j 4.+0.j]]
+
+ The FFT of the result illustrates that the values of the lower right quadrant (or
+ orthant) with purely positive frequency bins have been quadrupled. The values at its
+ borders, where only one frequency component is zero, are doubled. The zero frequency
+ bin ``(0, 0)`` has not been altered. All other quadrants have been set to zero.
+
+ This second example illustrates a problem with the "single-orthant" convention. A
+ purely real signal can produce an analytic signal which is completely zero:
+
+ >>> from scipy.fft import fft2, fftshift, ifft2, ifftshift
+ >>> from scipy.signal import hilbert2
+ ...
+ >>> # Create a real signal by ensuring `Z[-p,-q] == np.conj(Z[p,q])` holds:
+ >>> Z = np.array([[0, 0, 0, 0, 0],
+ ... [0, 0, 0, 1, 0],
+ ... [0, 0, 0, 0, 0],
+ ... [0, 1, 0, 0, 0],
+ ... [0, 0, 0, 0, 0]]) * 25
+ >>> z = ifft2(ifftshift(Z))
+ >>> np.allclose(z.imag, 0) # z is a real signal
+ True
+ >>> np.sum(z.real**2) # z.real is non-zero
+ np.float64(50.0)
+ >>> z_a = hilbert2(z.real)
+ >>> np.allclose(z_a, 0) # analytic signal is zero
+ True
+
+ """
+ xp = array_namespace(x)
+ x = xpx.atleast_nd(xp.asarray(x), ndim=2, xp=xp)
+ if xp.isdtype(x.dtype, 'complex floating'):
+ raise ValueError("x must be real.")
+ if len(axes) != 2:
+ raise ValueError("axes must be a tuple of length 2")
+ if axes[0] == axes[1]:
+ raise ValueError("axes must contain 2 distinct axes")
+
+ if N is None:
+ N = (x.shape[axes[0]], x.shape[axes[1]])
+ elif isinstance(N, int):
+ if N <= 0:
+ raise ValueError("N must be positive.")
+ N = (N, N)
+ elif len(N) != 2 or np.any(np.asarray(N) <= 0):
+ raise ValueError("When given as a tuple, N must hold exactly "
+ "two positive integers")
+
+ Xf = sp_fft.fft2(x, N, axes=axes)
+ Xf = xp.moveaxis(Xf, axes, (-2, -1))
+ k0, k1 = (N[0] + 1) // 2, (N[1] + 1) // 2
+
+ if k0 > 1: # condition k0 > 1 needed for Dask backend
+ Xf[..., 1:k0, :] *= 2.0
+ if k1 > 1: # condition k1 > 1 needed for Dask backend
+ Xf[..., :, 1:k1] *= 2.0
+ Xf[..., k0:, :] = 0.0
+ Xf[..., :, k1:] = 0.0
+
+ Xf = xp.moveaxis(Xf, (-2, -1), axes)
+ x = sp_fft.ifft2(Xf, axes=axes)
+ return x
+
+
+def envelope(z, bp_in: tuple[int | None, int | None] = (1, None), *,
+ n_out: int | None = None, squared: bool = False,
+ residual: Literal['lowpass', 'all', None] = 'lowpass',
+ axis: int = -1):
+ r"""Compute the envelope of a real- or complex-valued signal.
+
+ Parameters
+ ----------
+ z : ndarray
+ Real- or complex-valued input signal, which is assumed to be made up of ``n``
+ samples and having sampling interval ``T``. `z` may also be a multidimensional
+ array with the time axis being defined by `axis`.
+ bp_in : tuple[int | None, int | None], optional
+ 2-tuple defining the frequency band ``bp_in[0]:bp_in[1]`` of the input filter.
+ The corner frequencies are specified as integer multiples of ``1/(n*T)`` with
+ ``-n//2 <= bp_in[0] < bp_in[1] <= (n+1)//2`` being the allowed frequency range.
+ ``None`` entries are replaced with ``-n//2`` or ``(n+1)//2`` respectively. The
+ default of ``(1, None)`` removes the mean value as well as the negative
+ frequency components.
+ n_out : int | None, optional
+ If not ``None`` the output will be resampled to `n_out` samples. The default
+ of ``None`` sets the output to the same length as the input `z`.
+ squared : bool, optional
+ If set, the square of the envelope is returned. The bandwidth of the squared
+ envelope is often smaller than the non-squared envelope bandwidth due to the
+ nonlinear nature of the utilized absolute value function. I.e., the embedded
+ square root function typically produces addiational harmonics.
+ The default is ``False``.
+ residual : Literal['lowpass', 'all', None], optional
+ This option determines what kind of residual, i.e., the signal part which the
+ input bandpass filter removes, is returned. ``'all'`` returns everything except
+ the contents of the frequency band ``bp_in[0]:bp_in[1]``, ``'lowpass'``
+ returns the contents of the frequency band ``< bp_in[0]``. If ``None`` then
+ only the envelope is returned. Default: ``'lowpass'``.
+ axis : int, optional
+ Axis of `z` over which to compute the envelope. Default is last the axis.
+
+ Returns
+ -------
+ ndarray
+ If parameter `residual` is ``None`` then an array ``z_env`` with the same shape
+ as the input `z` is returned, containing its envelope. Otherwise, an array with
+ shape ``(2, *z.shape)``, containing the arrays ``z_env`` and ``z_res``, stacked
+ along the first axis, is returned.
+ It allows unpacking, i.e., ``z_env, z_res = envelope(z, residual='all')``.
+ The residual ``z_res`` contains the signal part which the input bandpass filter
+ removed, depending on the parameter `residual`. Note that for real-valued
+ signals, a real-valued residual is returned. Hence, the negative frequency
+ components of `bp_in` are ignored.
+
+ Notes
+ -----
+ Any complex-valued signal :math:`z(t)` can be described by a real-valued
+ instantaneous amplitude :math:`a(t)` and a real-valued instantaneous phase
+ :math:`\phi(t)`, i.e., :math:`z(t) = a(t) \exp\!\big(j \phi(t)\big)`. The
+ envelope is defined as the absolute value of the amplitude :math:`|a(t)| = |z(t)|`,
+ which is at the same time the absolute value of the signal. Hence, :math:`|a(t)|`
+ "envelopes" the class of all signals with amplitude :math:`a(t)` and arbitrary
+ phase :math:`\phi(t)`.
+ For real-valued signals, :math:`x(t) = a(t) \cos\!\big(\phi(t)\big)` is the
+ analogous formulation. Hence, :math:`|a(t)|` can be determined by converting
+ :math:`x(t)` into an analytic signal :math:`z_a(t)` by means of a Hilbert
+ transform, i.e.,
+ :math:`z_a(t) = a(t) \cos\!\big(\phi(t)\big) + j a(t) \sin\!\big(\phi(t) \big)`,
+ which produces a complex-valued signal with the same envelope :math:`|a(t)|`.
+
+ The implementation is based on computing the FFT of the input signal and then
+ performing the necessary operations in Fourier space. Hence, the typical FFT
+ caveats need to be taken into account:
+
+ * The signal is assumed to be periodic. Discontinuities between signal start and
+ end can lead to unwanted results due to Gibbs phenomenon.
+ * The FFT is slow if the signal length is prime or very long. Also, the memory
+ demands are typically higher than a comparable FIR/IIR filter based
+ implementation.
+ * The frequency spacing ``1 / (n*T)`` for corner frequencies of the bandpass filter
+ corresponds to the frequencies produced by ``scipy.fft.fftfreq(len(z), T)``.
+
+ If the envelope of a complex-valued signal `z` with no bandpass filtering is
+ desired, i.e., ``bp_in=(None, None)``, then the envelope corresponds to the
+ absolute value. Hence, it is more efficient to use ``np.abs(z)`` instead of this
+ function.
+
+ Although computing the envelope based on the analytic signal [1]_ is the natural
+ method for real-valued signals, other methods are also frequently used. The most
+ popular alternative is probably the so-called "square-law" envelope detector and
+ its relatives [2]_. They do not always compute the correct result for all kinds of
+ signals, but are usually correct and typically computationally more efficient for
+ most kinds of narrowband signals. The definition for an envelope presented here is
+ common where instantaneous amplitude and phase are of interest (e.g., as described
+ in [3]_). There exist also other concepts, which rely on the general mathematical
+ idea of an envelope [4]_: A pragmatic approach is to determine all upper and lower
+ signal peaks and use a spline interpolation to determine the curves [5]_.
+
+
+ References
+ ----------
+ .. [1] "Analytic Signal", Wikipedia,
+ https://en.wikipedia.org/wiki/Analytic_signal
+ .. [2] Lyons, Richard, "Digital envelope detection: The good, the bad, and the
+ ugly", IEEE Signal Processing Magazine 34.4 (2017): 183-187.
+ `PDF `__
+ .. [3] T.G. Kincaid, "The complex representation of signals.",
+ TIS R67# MH5, General Electric Co. (1966).
+ `PDF `__
+ .. [4] "Envelope (mathematics)", Wikipedia,
+ https://en.wikipedia.org/wiki/Envelope_(mathematics)
+ .. [5] Yang, Yanli. "A signal theoretic approach for envelope analysis of
+ real-valued signals." IEEE Access 5 (2017): 5623-5630.
+ `PDF `__
+
+
+ See Also
+ --------
+ hilbert: Compute analytic signal by means of Hilbert transform.
+
+
+ Examples
+ --------
+ The following plot illustrates the envelope of a signal with variable frequency and
+ a low-frequency drift. To separate the drift from the envelope, a 4 Hz highpass
+ filter is used. The low-pass residuum of the input bandpass filter is utilized to
+ determine an asymmetric upper and lower bound to enclose the signal. Due to the
+ smoothness of the resulting envelope, it is down-sampled from 500 to 40 samples.
+ Note that the instantaneous amplitude ``a_x`` and the computed envelope ``x_env``
+ are not perfectly identical. This is due to the signal not being perfectly periodic
+ as well as the existence of some spectral overlapping of ``x_carrier`` and
+ ``x_drift``. Hence, they cannot be completely separated by a bandpass filter.
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.signal.windows import gaussian
+ >>> from scipy.signal import envelope
+ ...
+ >>> n, n_out = 500, 40 # number of signal samples and envelope samples
+ >>> T = 2 / n # sampling interval for 2 s duration
+ >>> t = np.arange(n) * T # time stamps
+ >>> a_x = gaussian(len(t), 0.4/T) # instantaneous amplitude
+ >>> phi_x = 30*np.pi*t + 35*np.cos(2*np.pi*0.25*t) # instantaneous phase
+ >>> x_carrier = a_x * np.cos(phi_x)
+ >>> x_drift = 0.3 * gaussian(len(t), 0.4/T) # drift
+ >>> x = x_carrier + x_drift
+ ...
+ >>> bp_in = (int(4 * (n*T)), None) # 4 Hz highpass input filter
+ >>> x_env, x_res = envelope(x, bp_in, n_out=n_out)
+ >>> t_out = np.arange(n_out) * (n / n_out) * T
+ ...
+ >>> fg0, ax0 = plt.subplots(1, 1, tight_layout=True)
+ >>> ax0.set_title(r"$4\,$Hz Highpass Envelope of Drifting Signal")
+ >>> ax0.set(xlabel="Time in seconds", xlim=(0, n*T), ylabel="Amplitude")
+ >>> ax0.plot(t, x, 'C0-', alpha=0.5, label="Signal")
+ >>> ax0.plot(t, x_drift, 'C2--', alpha=0.25, label="Drift")
+ >>> ax0.plot(t_out, x_res+x_env, 'C1.-', alpha=0.5, label="Envelope")
+ >>> ax0.plot(t_out, x_res-x_env, 'C1.-', alpha=0.5, label=None)
+ >>> ax0.grid(True)
+ >>> ax0.legend()
+ >>> plt.show()
+
+ The second example provides a geometric envelope interpretation of complex-valued
+ signals: The following two plots show the complex-valued signal as a blue
+ 3d-trajectory and the envelope as an orange round tube with varying diameter, i.e.,
+ as :math:`|a(t)| \exp(j\rho(t))`, with :math:`\rho(t)\in[-\pi,\pi]`. Also, the
+ projection into the 2d real and imaginary coordinate planes of trajectory and tube
+ is depicted. Every point of the complex-valued signal touches the tube's surface.
+
+ The left plot shows an analytic signal, i.e, the phase difference between
+ imaginary and real part is always 90 degrees, resulting in a spiraling trajectory.
+ It can be seen that in this case the real part has also the expected envelope,
+ i.e., representing the absolute value of the instantaneous amplitude.
+
+ The right plot shows the real part of that analytic signal being interpreted
+ as a complex-vauled signal, i.e., having zero imaginary part. There the resulting
+ envelope is not as smooth as in the analytic case and the instantaneous amplitude
+ in the real plane is not recovered. If ``z_re`` had been passed as a real-valued
+ signal, i.e., as ``z_re = z.real`` instead of ``z_re = z.real + 0j``, the result
+ would have been identical to the left plot. The reason for this is that real-valued
+ signals are interpreted as being the real part of a complex-valued analytic signal.
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.signal.windows import gaussian
+ >>> from scipy.signal import envelope
+ ...
+ >>> n, T = 1000, 1/1000 # number of samples and sampling interval
+ >>> t = np.arange(n) * T # time stamps for 1 s duration
+ >>> f_c = 3 # Carrier frequency for signal
+ >>> z = gaussian(len(t), 0.3/T) * np.exp(2j*np.pi*f_c*t) # analytic signal
+ >>> z_re = z.real + 0j # complex signal with zero imaginary part
+ ...
+ >>> e_a, e_r = (envelope(z_, (None, None), residual=None) for z_ in (z, z_re))
+ ...
+ >>> # Generate grids to visualize envelopes as 2d and 3d surfaces:
+ >>> E2d_t, E2_amp = np.meshgrid(t, [-1, 1])
+ >>> E2d_1 = np.ones_like(E2_amp)
+ >>> E3d_t, E3d_phi = np.meshgrid(t, np.linspace(-np.pi, np.pi, 300))
+ >>> ma = 1.8 # maximum axis values in real and imaginary direction
+ ...
+ >>> fg0 = plt.figure(figsize=(6.2, 4.))
+ >>> ax00 = fg0.add_subplot(1, 2, 1, projection='3d')
+ >>> ax01 = fg0.add_subplot(1, 2, 2, projection='3d', sharex=ax00,
+ ... sharey=ax00, sharez=ax00)
+ >>> ax00.set_title("Analytic Signal")
+ >>> ax00.set(xlim=(0, 1), ylim=(-ma, ma), zlim=(-ma, ma))
+ >>> ax01.set_title("Real-valued Signal")
+ >>> for z_, e_, ax_ in zip((z, z.real), (e_a, e_r), (ax00, ax01)):
+ ... ax_.set(xlabel="Time $t$", ylabel="Real Amp. $x(t)$",
+ ... zlabel="Imag. Amp. $y(t)$")
+ ... ax_.plot(t, z_.real, 'C0-', zs=-ma, zdir='z', alpha=0.5, label="Real")
+ ... ax_.plot_surface(E2d_t, e_*E2_amp, -ma*E2d_1, color='C1', alpha=0.25)
+ ... ax_.plot(t, z_.imag, 'C0-', zs=+ma, zdir='y', alpha=0.5, label="Imag.")
+ ... ax_.plot_surface(E2d_t, ma*E2d_1, e_*E2_amp, color='C1', alpha=0.25)
+ ... ax_.plot(t, z_.real, z_.imag, 'C0-', label="Signal")
+ ... ax_.plot_surface(E3d_t, e_*np.cos(E3d_phi), e_*np.sin(E3d_phi),
+ ... color='C1', alpha=0.5, shade=True, label="Envelope")
+ ... ax_.view_init(elev=22.7, azim=-114.3)
+ >>> fg0.subplots_adjust(left=0.08, right=0.97, wspace=0.15)
+ >>> plt.show()
+ """
+ xp = array_namespace(z)
+ if not (-z.ndim <= axis < z.ndim):
+ raise ValueError(f"Invalid parameter {axis=} for {z.shape=}!")
+ if not (z.shape[axis] > 0):
+ raise ValueError(f"z.shape[axis] not > 0 for {z.shape=}, {axis=}!")
+ if len(bp_in) != 2 or not all((isinstance(b_, int) or b_ is None) for b_ in bp_in):
+ raise ValueError(f"{bp_in=} isn't a 2-tuple of type (int | None, int | None)!")
+ if not ((isinstance(n_out, int) and 0 < n_out) or n_out is None):
+ raise ValueError(f"{n_out=} is not a positive integer or None!")
+ if residual not in ('lowpass', 'all', None):
+ raise ValueError(f"{residual=} not in ['lowpass', 'all', None]!")
+
+ n = z.shape[axis] # number of time samples of input
+ n_out = n if n_out is None else n_out
+ fak = n_out / n # scaling factor for resampling
+
+ bp = slice(bp_in[0] if bp_in[0] is not None else -(n//2),
+ bp_in[1] if bp_in[1] is not None else (n+1)//2)
+ if not (-n//2 <= bp.start < bp.stop <= (n+1)//2):
+ raise ValueError("`-n//2 <= bp_in[0] < bp_in[1] <= (n+1)//2` does not hold " +
+ f"for n={z.shape[axis]=} and {bp_in=}!")
+
+ # moving active axis to end allows to use `...` for indexing:
+ z = xp.moveaxis(z, axis, -1)
+
+ if xp.isdtype(z.dtype, 'complex floating'):
+ Z = sp_fft.fft(z)
+ else: # avoid calculating negative frequency bins for real signals:
+ dt = sp_fft.rfft(z[..., :1]).dtype
+ Z = xp.zeros_like(z, dtype=dt)
+ Z[..., :n//2 + 1] = sp_fft.rfft(z)
+ if bp.start > 0: # make signal analytic within bp_in band:
+ Z[..., bp] *= 2
+ elif bp.stop > 0:
+ Z[..., 1:bp.stop] *= 2
+ if not (bp.start <= 0 < bp.stop): # envelope is invariant to freq. shifts.
+ z_bb = sp_fft.ifft(Z[..., bp], n=n_out) * fak # baseband signal
+ else:
+ bp_shift = slice(bp.start + n//2, bp.stop + n//2)
+ z_bb = sp_fft.ifft(sp_fft.fftshift(Z, axes=-1)[..., bp_shift], n=n_out) * fak
+
+ z_env = xp.abs(z_bb) if not squared else xp.real(z_bb) ** 2 + xp.imag(z_bb) ** 2
+ z_env = xp.moveaxis(z_env, -1, axis)
+
+ # Calculate the residual from the input bandpass filter:
+ if residual is None:
+ return z_env
+ if not (bp.start <= 0 < bp.stop):
+ Z[..., bp] = 0
+ else:
+ Z[..., :bp.stop], Z[..., bp.start:] = 0, 0
+ if residual == 'lowpass':
+ if bp.stop > 0:
+ Z[..., bp.stop:(n+1) // 2] = 0
+ else:
+ Z[..., bp.start:], Z[..., 0:(n + 1) // 2] = 0, 0
+
+ if xp.isdtype(z.dtype, 'complex floating'): # resample accounts for unpaired bins:
+ z_res = resample(Z, n_out, axis=-1, domain='freq') # ifft() with corrections
+ else: # account for unpaired bin at m//2 before doing irfft():
+ if n_out != n and (m := min(n, n_out)) % 2 == 0:
+ Z[..., m//2] *= 2 if n_out < n else 0.5
+ z_res = fak * sp_fft.irfft(Z, n=n_out)
+ return xp.stack((z_env, xp.moveaxis(z_res, -1, axis)), axis=0)
+
+
+def _cmplx_sort(p):
+ """Sort roots based on magnitude.
+
+ Parameters
+ ----------
+ p : array_like
+ The roots to sort, as a 1-D array.
+
+ Returns
+ -------
+ p_sorted : ndarray
+ Sorted roots.
+ indx : ndarray
+ Array of indices needed to sort the input `p`.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> vals = [1, 4, 1+1.j, 3]
+ >>> p_sorted, indx = signal.cmplx_sort(vals)
+ >>> p_sorted
+ array([1.+0.j, 1.+1.j, 3.+0.j, 4.+0.j])
+ >>> indx
+ array([0, 2, 3, 1])
+ """
+ p = np.asarray(p)
+ indx = np.argsort(abs(p))
+ return np.take(p, indx, 0), indx
+
+
+def unique_roots(p, tol=1e-3, rtype='min'):
+ """Determine unique roots and their multiplicities from a list of roots.
+
+ Parameters
+ ----------
+ p : array_like
+ The list of roots.
+ tol : float, optional
+ The tolerance for two roots to be considered equal in terms of
+ the distance between them. Default is 1e-3. Refer to Notes about
+ the details on roots grouping.
+ rtype : {'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}, optional
+ How to determine the returned root if multiple roots are within
+ `tol` of each other.
+
+ - 'max', 'maximum': pick the maximum of those roots
+ - 'min', 'minimum': pick the minimum of those roots
+ - 'avg', 'mean': take the average of those roots
+
+ When finding minimum or maximum among complex roots they are compared
+ first by the real part and then by the imaginary part.
+
+ Returns
+ -------
+ unique : ndarray
+ The list of unique roots.
+ multiplicity : ndarray
+ The multiplicity of each root.
+
+ Notes
+ -----
+ If we have 3 roots ``a``, ``b`` and ``c``, such that ``a`` is close to
+ ``b`` and ``b`` is close to ``c`` (distance is less than `tol`), then it
+ doesn't necessarily mean that ``a`` is close to ``c``. It means that roots
+ grouping is not unique. In this function we use "greedy" grouping going
+ through the roots in the order they are given in the input `p`.
+
+ This utility function is not specific to roots but can be used for any
+ sequence of values for which uniqueness and multiplicity has to be
+ determined. For a more general routine, see `numpy.unique`.
+
+ Examples
+ --------
+ >>> from scipy import signal
+ >>> vals = [0, 1.3, 1.31, 2.8, 1.25, 2.2, 10.3]
+ >>> uniq, mult = signal.unique_roots(vals, tol=2e-2, rtype='avg')
+
+ Check which roots have multiplicity larger than 1:
+
+ >>> uniq[mult > 1]
+ array([ 1.305])
+ """
+ if rtype in ['max', 'maximum']:
+ reduce = np.max
+ elif rtype in ['min', 'minimum']:
+ reduce = np.min
+ elif rtype in ['avg', 'mean']:
+ reduce = np.mean
+ else:
+ raise ValueError("`rtype` must be one of "
+ "{'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}")
+
+ p = np.asarray(p)
+
+ points = np.empty((len(p), 2))
+ points[:, 0] = np.real(p)
+ points[:, 1] = np.imag(p)
+ tree = cKDTree(points)
+
+ p_unique = []
+ p_multiplicity = []
+ used = np.zeros(len(p), dtype=bool)
+ for i in range(len(p)):
+ if used[i]:
+ continue
+
+ group = tree.query_ball_point(points[i], tol)
+ group = [x for x in group if not used[x]]
+
+ p_unique.append(reduce(p[group]))
+ p_multiplicity.append(len(group))
+
+ used[group] = True
+
+ return np.asarray(p_unique), np.asarray(p_multiplicity)
+
+
+def invres(r, p, k, tol=1e-3, rtype='avg'):
+ """Compute b(s) and a(s) from partial fraction expansion.
+
+ If `M` is the degree of numerator `b` and `N` the degree of denominator
+ `a`::
+
+ b(s) b[0] s**(M) + b[1] s**(M-1) + ... + b[M]
+ H(s) = ------ = ------------------------------------------
+ a(s) a[0] s**(N) + a[1] s**(N-1) + ... + a[N]
+
+ then the partial-fraction expansion H(s) is defined as::
+
+ r[0] r[1] r[-1]
+ = -------- + -------- + ... + --------- + k(s)
+ (s-p[0]) (s-p[1]) (s-p[-1])
+
+ If there are any repeated roots (closer together than `tol`), then H(s)
+ has terms like::
+
+ r[i] r[i+1] r[i+n-1]
+ -------- + ----------- + ... + -----------
+ (s-p[i]) (s-p[i])**2 (s-p[i])**n
+
+ This function is used for polynomials in positive powers of s or z,
+ such as analog filters or digital filters in controls engineering. For
+ negative powers of z (typical for digital filters in DSP), use `invresz`.
+
+ Parameters
+ ----------
+ r : array_like
+ Residues corresponding to the poles. For repeated poles, the residues
+ must be ordered to correspond to ascending by power fractions.
+ p : array_like
+ Poles. Equal poles must be adjacent.
+ k : array_like
+ Coefficients of the direct polynomial term.
+ tol : float, optional
+ The tolerance for two roots to be considered equal in terms of
+ the distance between them. Default is 1e-3. See `unique_roots`
+ for further details.
+ rtype : {'avg', 'min', 'max'}, optional
+ Method for computing a root to represent a group of identical roots.
+ Default is 'avg'. See `unique_roots` for further details.
+
+ Returns
+ -------
+ b : ndarray
+ Numerator polynomial coefficients.
+ a : ndarray
+ Denominator polynomial coefficients.
+
+ See Also
+ --------
+ residue, invresz, unique_roots
+
+ """
+ r = np.atleast_1d(r)
+ p = np.atleast_1d(p)
+ k = np.trim_zeros(np.atleast_1d(k), 'f')
+
+ unique_poles, multiplicity = _group_poles(p, tol, rtype)
+ factors, denominator = _compute_factors(unique_poles, multiplicity,
+ include_powers=True)
+
+ if len(k) == 0:
+ numerator = 0
+ else:
+ numerator = np.polymul(k, denominator)
+
+ for residue, factor in zip(r, factors):
+ numerator = np.polyadd(numerator, residue * factor)
+
+ return numerator, denominator
+
+
+def _compute_factors(roots, multiplicity, include_powers=False):
+ """Compute the total polynomial divided by factors for each root."""
+ current = np.array([1])
+ suffixes = [current]
+ for pole, mult in zip(roots[-1:0:-1], multiplicity[-1:0:-1]):
+ monomial = np.array([1, -pole])
+ for _ in range(mult):
+ current = np.polymul(current, monomial)
+ suffixes.append(current)
+ suffixes = suffixes[::-1]
+
+ factors = []
+ current = np.array([1])
+ for pole, mult, suffix in zip(roots, multiplicity, suffixes):
+ monomial = np.array([1, -pole])
+ block = []
+ for i in range(mult):
+ if i == 0 or include_powers:
+ block.append(np.polymul(current, suffix))
+ current = np.polymul(current, monomial)
+ factors.extend(reversed(block))
+
+ return factors, current
+
+
+def _compute_residues(poles, multiplicity, numerator):
+ denominator_factors, _ = _compute_factors(poles, multiplicity)
+ numerator = numerator.astype(poles.dtype)
+
+ residues = []
+ for pole, mult, factor in zip(poles, multiplicity,
+ denominator_factors):
+ if mult == 1:
+ residues.append(np.polyval(numerator, pole) /
+ np.polyval(factor, pole))
+ else:
+ numer = numerator.copy()
+ monomial = np.array([1, -pole])
+ factor, d = np.polydiv(factor, monomial)
+
+ block = []
+ for _ in range(mult):
+ numer, n = np.polydiv(numer, monomial)
+ r = n[0] / d[0]
+ numer = np.polysub(numer, r * factor)
+ block.append(r)
+
+ residues.extend(reversed(block))
+
+ return np.asarray(residues)
+
+
+def residue(b, a, tol=1e-3, rtype='avg'):
+ """Compute partial-fraction expansion of b(s) / a(s).
+
+ If `M` is the degree of numerator `b` and `N` the degree of denominator
+ `a`::
+
+ b(s) b[0] s**(M) + b[1] s**(M-1) + ... + b[M]
+ H(s) = ------ = ------------------------------------------
+ a(s) a[0] s**(N) + a[1] s**(N-1) + ... + a[N]
+
+ then the partial-fraction expansion H(s) is defined as::
+
+ r[0] r[1] r[-1]
+ = -------- + -------- + ... + --------- + k(s)
+ (s-p[0]) (s-p[1]) (s-p[-1])
+
+ If there are any repeated roots (closer together than `tol`), then H(s)
+ has terms like::
+
+ r[i] r[i+1] r[i+n-1]
+ -------- + ----------- + ... + -----------
+ (s-p[i]) (s-p[i])**2 (s-p[i])**n
+
+ This function is used for polynomials in positive powers of s or z,
+ such as analog filters or digital filters in controls engineering. For
+ negative powers of z (typical for digital filters in DSP), use `residuez`.
+
+ See Notes for details about the algorithm.
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator polynomial coefficients.
+ a : array_like
+ Denominator polynomial coefficients.
+ tol : float, optional
+ The tolerance for two roots to be considered equal in terms of
+ the distance between them. Default is 1e-3. See `unique_roots`
+ for further details.
+ rtype : {'avg', 'min', 'max'}, optional
+ Method for computing a root to represent a group of identical roots.
+ Default is 'avg'. See `unique_roots` for further details.
+
+ Returns
+ -------
+ r : ndarray
+ Residues corresponding to the poles. For repeated poles, the residues
+ are ordered to correspond to ascending by power fractions.
+ p : ndarray
+ Poles ordered by magnitude in ascending order.
+ k : ndarray
+ Coefficients of the direct polynomial term.
+
+ See Also
+ --------
+ invres, residuez, numpy.poly, unique_roots
+
+ Notes
+ -----
+ The "deflation through subtraction" algorithm is used for
+ computations --- method 6 in [1]_.
+
+ The form of partial fraction expansion depends on poles multiplicity in
+ the exact mathematical sense. However there is no way to exactly
+ determine multiplicity of roots of a polynomial in numerical computing.
+ Thus you should think of the result of `residue` with given `tol` as
+ partial fraction expansion computed for the denominator composed of the
+ computed poles with empirically determined multiplicity. The choice of
+ `tol` can drastically change the result if there are close poles.
+
+ References
+ ----------
+ .. [1] J. F. Mahoney, B. D. Sivazlian, "Partial fractions expansion: a
+ review of computational methodology and efficiency", Journal of
+ Computational and Applied Mathematics, Vol. 9, 1983.
+ """
+ b = np.asarray(b)
+ a = np.asarray(a)
+ if (np.issubdtype(b.dtype, np.complexfloating)
+ or np.issubdtype(a.dtype, np.complexfloating)):
+ b = b.astype(complex)
+ a = a.astype(complex)
+ else:
+ b = b.astype(float)
+ a = a.astype(float)
+
+ b = np.trim_zeros(np.atleast_1d(b), 'f')
+ a = np.trim_zeros(np.atleast_1d(a), 'f')
+
+ if a.size == 0:
+ raise ValueError("Denominator `a` is zero.")
+
+ poles = np.roots(a)
+ if b.size == 0:
+ return np.zeros(poles.shape), _cmplx_sort(poles)[0], np.array([])
+
+ if len(b) < len(a):
+ k = np.empty(0)
+ else:
+ k, b = np.polydiv(b, a)
+
+ unique_poles, multiplicity = unique_roots(poles, tol=tol, rtype=rtype)
+ unique_poles, order = _cmplx_sort(unique_poles)
+ multiplicity = multiplicity[order]
+
+ residues = _compute_residues(unique_poles, multiplicity, b)
+
+ index = 0
+ for pole, mult in zip(unique_poles, multiplicity):
+ poles[index:index + mult] = pole
+ index += mult
+
+ return residues / a[0], poles, k
+
+
+def residuez(b, a, tol=1e-3, rtype='avg'):
+ """Compute partial-fraction expansion of b(z) / a(z).
+
+ If `M` is the degree of numerator `b` and `N` the degree of denominator
+ `a`::
+
+ b(z) b[0] + b[1] z**(-1) + ... + b[M] z**(-M)
+ H(z) = ------ = ------------------------------------------
+ a(z) a[0] + a[1] z**(-1) + ... + a[N] z**(-N)
+
+ then the partial-fraction expansion H(z) is defined as::
+
+ r[0] r[-1]
+ = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ...
+ (1-p[0]z**(-1)) (1-p[-1]z**(-1))
+
+ If there are any repeated roots (closer than `tol`), then the partial
+ fraction expansion has terms like::
+
+ r[i] r[i+1] r[i+n-1]
+ -------------- + ------------------ + ... + ------------------
+ (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n
+
+ This function is used for polynomials in negative powers of z,
+ such as digital filters in DSP. For positive powers, use `residue`.
+
+ See Notes of `residue` for details about the algorithm.
+
+ Parameters
+ ----------
+ b : array_like
+ Numerator polynomial coefficients.
+ a : array_like
+ Denominator polynomial coefficients.
+ tol : float, optional
+ The tolerance for two roots to be considered equal in terms of
+ the distance between them. Default is 1e-3. See `unique_roots`
+ for further details.
+ rtype : {'avg', 'min', 'max'}, optional
+ Method for computing a root to represent a group of identical roots.
+ Default is 'avg'. See `unique_roots` for further details.
+
+ Returns
+ -------
+ r : ndarray
+ Residues corresponding to the poles. For repeated poles, the residues
+ are ordered to correspond to ascending by power fractions.
+ p : ndarray
+ Poles ordered by magnitude in ascending order.
+ k : ndarray
+ Coefficients of the direct polynomial term.
+
+ See Also
+ --------
+ invresz, residue, unique_roots
+ """
+ b = np.asarray(b)
+ a = np.asarray(a)
+ if (np.issubdtype(b.dtype, np.complexfloating)
+ or np.issubdtype(a.dtype, np.complexfloating)):
+ b = b.astype(complex)
+ a = a.astype(complex)
+ else:
+ b = b.astype(float)
+ a = a.astype(float)
+
+ b = np.trim_zeros(np.atleast_1d(b), 'b')
+ a = np.trim_zeros(np.atleast_1d(a), 'b')
+
+ if a.size == 0:
+ raise ValueError("Denominator `a` is zero.")
+ elif a[0] == 0:
+ raise ValueError("First coefficient of determinant `a` must be "
+ "non-zero.")
+
+ poles = np.roots(a)
+ if b.size == 0:
+ return np.zeros(poles.shape), _cmplx_sort(poles)[0], np.array([])
+
+ b_rev = b[::-1]
+ a_rev = a[::-1]
+
+ if len(b_rev) < len(a_rev):
+ k_rev = np.empty(0)
+ else:
+ k_rev, b_rev = np.polydiv(b_rev, a_rev)
+
+ unique_poles, multiplicity = unique_roots(poles, tol=tol, rtype=rtype)
+ unique_poles, order = _cmplx_sort(unique_poles)
+ multiplicity = multiplicity[order]
+
+ residues = _compute_residues(1 / unique_poles, multiplicity, b_rev)
+
+ index = 0
+ powers = np.empty(len(residues), dtype=int)
+ for pole, mult in zip(unique_poles, multiplicity):
+ poles[index:index + mult] = pole
+ powers[index:index + mult] = 1 + np.arange(mult)
+ index += mult
+
+ residues *= (-poles) ** powers / a_rev[0]
+
+ return residues, poles, k_rev[::-1]
+
+
+def _group_poles(poles, tol, rtype):
+ if rtype in ['max', 'maximum']:
+ reduce = np.max
+ elif rtype in ['min', 'minimum']:
+ reduce = np.min
+ elif rtype in ['avg', 'mean']:
+ reduce = np.mean
+ else:
+ raise ValueError("`rtype` must be one of "
+ "{'max', 'maximum', 'min', 'minimum', 'avg', 'mean'}")
+
+ unique = []
+ multiplicity = []
+
+ pole = poles[0]
+ block = [pole]
+ for i in range(1, len(poles)):
+ if abs(poles[i] - pole) <= tol:
+ block.append(pole)
+ else:
+ unique.append(reduce(block))
+ multiplicity.append(len(block))
+ pole = poles[i]
+ block = [pole]
+
+ unique.append(reduce(block))
+ multiplicity.append(len(block))
+
+ return np.asarray(unique), np.asarray(multiplicity)
+
+
+def invresz(r, p, k, tol=1e-3, rtype='avg'):
+ """Compute b(z) and a(z) from partial fraction expansion.
+
+ If `M` is the degree of numerator `b` and `N` the degree of denominator
+ `a`::
+
+ b(z) b[0] + b[1] z**(-1) + ... + b[M] z**(-M)
+ H(z) = ------ = ------------------------------------------
+ a(z) a[0] + a[1] z**(-1) + ... + a[N] z**(-N)
+
+ then the partial-fraction expansion H(z) is defined as::
+
+ r[0] r[-1]
+ = --------------- + ... + ---------------- + k[0] + k[1]z**(-1) ...
+ (1-p[0]z**(-1)) (1-p[-1]z**(-1))
+
+ If there are any repeated roots (closer than `tol`), then the partial
+ fraction expansion has terms like::
+
+ r[i] r[i+1] r[i+n-1]
+ -------------- + ------------------ + ... + ------------------
+ (1-p[i]z**(-1)) (1-p[i]z**(-1))**2 (1-p[i]z**(-1))**n
+
+ This function is used for polynomials in negative powers of z,
+ such as digital filters in DSP. For positive powers, use `invres`.
+
+ Parameters
+ ----------
+ r : array_like
+ Residues corresponding to the poles. For repeated poles, the residues
+ must be ordered to correspond to ascending by power fractions.
+ p : array_like
+ Poles. Equal poles must be adjacent.
+ k : array_like
+ Coefficients of the direct polynomial term.
+ tol : float, optional
+ The tolerance for two roots to be considered equal in terms of
+ the distance between them. Default is 1e-3. See `unique_roots`
+ for further details.
+ rtype : {'avg', 'min', 'max'}, optional
+ Method for computing a root to represent a group of identical roots.
+ Default is 'avg'. See `unique_roots` for further details.
+
+ Returns
+ -------
+ b : ndarray
+ Numerator polynomial coefficients.
+ a : ndarray
+ Denominator polynomial coefficients.
+
+ See Also
+ --------
+ residuez, unique_roots, invres
+
+ """
+ r = np.atleast_1d(r)
+ p = np.atleast_1d(p)
+ k = np.trim_zeros(np.atleast_1d(k), 'b')
+
+ unique_poles, multiplicity = _group_poles(p, tol, rtype)
+ factors, denominator = _compute_factors(unique_poles, multiplicity,
+ include_powers=True)
+
+ if len(k) == 0:
+ numerator = 0
+ else:
+ numerator = np.polymul(k[::-1], denominator[::-1])
+
+ for residue, factor in zip(r, factors):
+ numerator = np.polyadd(numerator, residue * factor[::-1])
+
+ return numerator[::-1], denominator
+
+
+def resample(x, num, t=None, axis=0, window=None, domain='time'):
+ r"""Resample `x` to `num` samples using the Fourier method along the given `axis`.
+
+ The resampling is performed by shortening or zero-padding the FFT of `x`. This has
+ the advantages of providing an ideal antialiasing filter and allowing arbitrary
+ up- or down-sampling ratios. The main drawback is the requirement of assuming `x`
+ to be a periodic signal.
+
+ Parameters
+ ----------
+ x : array_like
+ The input signal made up of equidistant samples. If `x` is a multidimensional
+ array, the parameter `axis` specifies the time/frequency axis. It is assumed
+ here that ``n_x = x.shape[axis]`` specifies the number of samples and ``T`` the
+ sampling interval.
+ num : int
+ The number of samples of the resampled output signal. It may be larger or
+ smaller than ``n_x``.
+ t : array_like, optional
+ If `t` is not ``None``, then the timestamps of the resampled signal are also
+ returned. `t` must contain at least the first two timestamps of the input
+ signal `x` (all others are ignored). The timestamps of the output signal are
+ determined by ``t[0] + T * n_x / num * np.arange(num)`` with
+ ``T = t[1] - t[0]``. Default is ``None``.
+ axis : int, optional
+ The time/frequency axis of `x` along which the resampling take place.
+ The Default is 0.
+ window : array_like, callable, string, float, or tuple, optional
+ If not ``None``, it specifies a filter in the Fourier domain, which is applied
+ before resampling. I.e., the FFT ``X`` of `x` is calculated by
+ ``X = W * fft(x, axis=axis)``. ``W`` may be interpreted as a spectral windowing
+ function ``W(f_X)`` which consumes the frequencies ``f_X = fftfreq(n_x, T)``.
+
+ If `window` is a 1d array of length ``n_x`` then ``W=window``.
+ If `window` is a callable then ``W = window(f_X)``.
+ Otherwise, `window` is passed to `~scipy.signal.get_window`, i.e.,
+ ``W = fftshift(signal.get_window(window, n_x))``. Default is ``None``.
+
+ domain : 'time' | 'freq', optional
+ If set to ``'time'`` (default) then an FFT is applied to `x`, otherwise
+ (``'freq'``) it is asssmued that an FFT was already applied, i.e.,
+ ``x = fft(x_t, axis=axis)`` with ``x_t`` being the input signal in the time
+ domain.
+
+ Returns
+ -------
+ x_r : ndarray
+ The resampled signal made up of `num` samples and sampling interval
+ ``T * n_x / num``.
+ t_r : ndarray, optional
+ The `num` equidistant timestamps of `x_r`.
+ This is only returned if paramater `t` is not ``None``.
+
+ See Also
+ --------
+ decimate : Downsample a (periodic/non-periodic) signal after applying an FIR
+ or IIR filter.
+ resample_poly : Resample a (periodic/non-periodic) signal using polyphase filtering
+ and an FIR filter.
+
+ Notes
+ -----
+ This function uses the more efficient one-sided FFT, i.e. `~scipy.fft.rfft` /
+ `~scipy.fft.irfft`, if `x` is real-valued and in the time domain.
+ Else, the two-sided FFT, i.e., `~scipy.fft.fft` / `~scipy.fft.ifft`, is used
+ (all FFT functions are taken from the `scipy.fft` module).
+
+ If a `window` is applied to a real-valued `x`, the one-sided spectral windowing
+ function is determined by taking the average of the negative and the positive
+ frequency component. This ensures that real-valued signals and complex signals with
+ zero imaginary part are treated identically. I.e., passing `x` or passing
+ ``x.astype(np.complex128)`` produce the same numeric result.
+
+ If the number of input or output samples are prime or have few prime factors, this
+ function may be slow due to utilizing FFTs. Consult `~scipy.fft.prev_fast_len` and
+ `~scipy.fft.next_fast_len` for determining efficient signals lengths.
+ Alternatively, utilizing `resample_poly` to calculate an intermediate signal (as
+ illustrated in the example below) can result in significant speed increases.
+
+ `resample` is intended to be used for periodic signals with equidistant sampling
+ intervals. For non-periodic signals, `resample_poly` may be a better choice.
+ Consult the `scipy.interpolate` module for methods of resampling signals with
+ non-constant sampling intervals.
+
+ Examples
+ --------
+ The following example depicts a signal being up-sampled from 20 samples to 100
+ samples. The ringing at the beginning of the up-sampled signal is due to
+ interpreting the signal being periodic. The red square in the plot illustrates that
+ periodictiy by showing the first sample of the next cycle of the signal.
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import resample
+ ...
+ >>> n0, n1 = 20, 100 # number of samples
+ >>> t0 = np.linspace(0, 10, n0, endpoint=False) # input time stamps
+ >>> x0 = np.cos(-t0**2/6) # input signal
+ ...
+ >>> x1 = resample(x0, n1) # resampled signal
+ >>> t1 = np.linspace(0, 10, n1, endpoint=False) # timestamps of x1
+ ...
+ >>> fig0, ax0 = plt.subplots(1, 1, tight_layout=True)
+ >>> ax0.set_title(f"Resampling $x(t)$ from {n0} samples to {n1} samples")
+ >>> ax0.set(xlabel="Time $t$", ylabel="Amplitude $x(t)$")
+ >>> ax0.plot(t1, x1, '.-', alpha=.5, label=f"Resampled")
+ >>> ax0.plot(t0, x0, 'o-', alpha=.5, label="Original")
+ >>> ax0.plot(10, x0[0], 'rs', alpha=.5, label="Next Cycle")
+ >>> ax0.legend(loc='best')
+ >>> ax0.grid(True)
+ >>> plt.show()
+
+ The following example compares this function with a naive `~scipy.fft.rfft` /
+ `~scipy.fft.irfft` combination: An input signal with a sampling interval of one
+ second is upsampled by a factor of eight. The first figure depicts an odd number of
+ input samples whereas the second figure an even number. The upper subplots show the
+ signals over time: The input samples are marked by large green dots, the upsampled
+ signals by a continuous and a dashed line. The lower subplots show the magnitude
+ spectrum: The FFT values of the input are depicted by large green dots, which lie
+ in the frequency interval [-0.5, 0.5] Hz, whereas the frequency interval of the
+ upsampled signal is [-4, 4] Hz. The continuous green line depicts the upsampled
+ spectrum without antialiasing filter, which is a periodic continuation of the input
+ spectrum. The blue x's and orange dots depict the FFT values of the signal created
+ by the naive approach as well as this function's result.
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.fft import fftshift, fftfreq, fft, rfft, irfft
+ >>> from scipy.signal import resample, resample_poly
+ ...
+ >>> fac, T0, T1 = 8, 1, 1/8 # upsampling factor and sampling intervals
+ >>> for n0 in (15, 16): # number of samples of input signal
+ ... n1 = fac * n0 # number of samples of upsampled signal
+ ... t0, t1 = T0 * np.arange(n0), T1 * np.arange(n1) # time stamps
+ ... x0 = np.zeros(n0) # input signal has two non-zero sample values
+ ... x0[n0//2], x0[n0//2+1] = n0 // 2, -(n0 // 2)
+ ...
+ ... x1n = irfft(rfft(x0), n=n1) * n1 / n0 # naive resampling
+ ... x1r = resample(x0, n1) # resample signal
+ ...
+ ... # Determine magnitude spectrum:
+ ... x0_up = np.zeros_like(x1r) # upsampling without antialiasing filter
+ ... x0_up[::n1 // n0] = x0
+ ... X0, X0_up = (fftshift(fft(x_)) / n0 for x_ in (x0, x0_up))
+ ... XX1 = (fftshift(fft(x_)) / n1 for x_ in (x1n, x1r))
+ ... f0, f1 = fftshift(fftfreq(n0, T0)), fftshift(fftfreq(n1, T1)) # frequencies
+ ... df = f0[1] - f0[0] # frequency resolution
+ ...
+ ... fig, (ax0, ax1) = plt.subplots(2, 1, layout='constrained', figsize=(5, 4))
+ ... ax0.set_title(rf"Upsampling ${fac}\times$ from {n0} to {n1} samples")
+ ... ax0.set(xlabel="Time $t$ in seconds", ylabel="Amplitude $x(t)$",
+ ... xlim=(0, n1*T1))
+ ... ax0.step(t0, x0, 'C2o-', where='post', alpha=.3, linewidth=2,
+ ... label="$x_0(t)$ / $X_0(f)$")
+ ... for x_, l_ in zip((x1n, x1r), ('C0--', 'C1-')):
+ ... ax0.plot(t1, x_, l_, alpha=.5, label=None)
+ ... ax0.grid()
+ ... ax1.set(xlabel=rf"Frequency $f$ in hertz ($\Delta f = {df*1e3:.1f}\,$mHz)",
+ ... ylabel="Magnitude $|X(f)|$", xlim=(-0.7, 0.7))
+ ... ax1.axvspan(0.5/T0, f1[-1], color='gray', alpha=.2)
+ ... ax1.axvspan(f1[0], -0.5/T0, color='gray', alpha=.2)
+ ... ax1.plot(f1, abs(X0_up), 'C2-', f0, abs(X0), 'C2o', alpha=.3, linewidth=2)
+ ... for X_, n_, l_ in zip(XX1, ("naive", "resample"), ('C0x--', 'C1.-')):
+ ... ax1.plot(f1, abs(X_), l_, alpha=.5, label=n_)
+ ... ax1.grid()
+ ... fig.legend(loc='outside lower center', ncols=4)
+ >>> plt.show()
+
+ The first figure shows that upsampling an odd number of samples produces identical
+ results. The second figure illustrates that the signal produced with the naive
+ approach (dashed blue line) from an even number of samples does not touch all
+ original samples. This deviation is due to `resample` correctly treating unpaired
+ frequency bins. I.e., the input `x1` has a bin pair ±0.5 Hz, whereas the output has
+ only one unpaired bin at -0.5 Hz, which demands rescaling of that bin pair.
+ Generally, special treatment is required if ``n_x != num`` and ``min(n_x, num)`` is
+ even. If the bin values at `±m` are zero, obviously, no special treatment is
+ needed. Consult the source code of `resample` for details.
+
+ The final example shows how to utilize `resample_poly` to speed up the
+ down-sampling: The input signal a non-zero value at :math:`t=0` and is downsampled
+ from 19937 to 128 samples. Since 19937 is prime, the FFT is expected to be slow. To
+ speed matters up, `resample_poly` is used to downsample first by a factor of ``n0
+ // n1 = 155`` and then pass the result to `resample`. Two parameterization of
+ `resample_poly` are used: Passing ``padtype='wrap'`` treats the input as being
+ periodic wheras the default parametrization performs zero-padding. The upper
+ subplot shows the resulting signals over time whereas the lower subplot depicts the
+ resulting one-sided magnitude spectra.
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.fft import rfftfreq, rfft
+ >>> from scipy.signal import resample, resample_poly
+ ...
+ >>> n0 = 19937 # number of input samples - prime
+ >>> n1 = 128 # number of output samples - fast FFT length
+ >>> T0, T1 = 1/n0, 1/n1 # sampling intervals
+ >>> t0, t1 = np.arange(n0)*T0, np.arange(n1)*T1 # time stamps
+ ...
+ >>> x0 = np.zeros(n0) # Input has one non-zero sample
+ >>> x0[0] = n0
+ >>>
+ >>> x1r = resample(x0, n1) # slow due to n0 being prime
+ >>> # This is faster:
+ >>> x1p = resample(resample_poly(x0, 1, n0 // n1, padtype='wrap'), n1) # periodic
+ >>> x2p = resample(resample_poly(x0, 1, n0 // n1), n1) # with zero-padding
+ ...
+ >>> X0 = rfft(x0) / n0
+ >>> X1r, X1p, X2p = rfft(x1r) / n1, rfft(x1p) / n1, rfft(x2p) / n1
+ >>> f0, f1 = rfftfreq(n0, T0), rfftfreq(n1, T1)
+ ...
+ >>> fig, (ax0, ax1) = plt.subplots(2, 1, layout='constrained', figsize=(5, 4))
+ >>> ax0.set_title(f"Dowsampled Impulse response (from {n0} to {n1} samples)")
+ >>> ax0.set(xlabel="Time $t$ in seconds", ylabel="Amplitude $x(t)$", xlim=(-T1, 1))
+ >>> for x_ in (x1r, x1p, x2p):
+ ... ax0.plot(t1, x_, alpha=.5)
+ >>> ax0.grid()
+ >>> ax1.set(xlabel=rf"Frequency $f$ in hertz ($\Delta f = {f1[1]}\,$Hz)",
+ ... ylabel="Magnitude $|X(f)|$", xlim=(0, 0.55/T1))
+ >>> ax1.axvspan(0.5/T1, f0[-1], color='gray', alpha=.2)
+ >>> ax1.plot(f1, abs(X1r), 'C0.-', alpha=.5, label="resample")
+ >>> ax1.plot(f1, abs(X1p), 'C1.-', alpha=.5, label="resample_poly(padtype='wrap')")
+ >>> ax1.plot(f1, abs(X2p), 'C2x-', alpha=.5, label="resample_poly")
+ >>> ax1.grid()
+ >>> fig.legend(loc='outside lower center', ncols=2)
+ >>> plt.show()
+
+ The plots show that the results of the "pure" `resample` and the usage of the
+ default parameters of `resample_poly` agree well. The periodic padding of
+ `resample_poly` (``padtype='wrap'``) on the other hand produces significant
+ deviations. This is caused by the disconiuity at the beginning of the signal, for
+ which the default filter of `resample_poly` is not suited well. This example
+ illustrates that for some use cases, adpating the `resample_poly` parameters may
+ be beneficial. `resample` has a big advantage in this regard: It uses the ideal
+ antialiasing filter with the maximum bandwidth by default.
+
+ Note that the doubled spectral magnitude at the Nyqist frequency of 64 Hz is due the
+ even number of ``n1=128`` output samples, which requires a special treatment as
+ discussed in the previous example.
+ """
+ if domain not in ('time', 'freq'):
+ raise ValueError(f"Parameter {domain=} not in ('time', 'freq')!")
+
+ xp = array_namespace(x, t)
+ x = xp.asarray(x)
+ if x.ndim > 1: # moving active axis to end allows to use `...` in indexing:
+ x = xp.moveaxis(x, axis, -1)
+ n_x = x.shape[-1] # number of samples along the time/frequency axis
+ s_fac = n_x / num # scaling factor represents sample interval dilatation
+ m = min(num, n_x) # number of relevant frequency bins
+ m2 = m // 2 + 1 # number of relevant frequency bins of a one-sided FFT
+
+ if window is None: # Determine spectral windowing function:
+ W = None
+ elif callable(window):
+ W = window(sp_fft.fftfreq(n_x))
+ elif hasattr(window, 'shape'): # must be an array object
+ if window.shape != (n_x,):
+ raise ValueError(f"{window.shape=} != ({n_x},), i.e., window length " +
+ "is not equal to number of frequency bins!")
+ W = xp.asarray(window, copy=True) # prevent modifying the function parameters
+ else:
+ W = sp_fft.fftshift(get_window(window, n_x, xp=xp))
+ W = xp.astype(W, xp_default_dtype(xp)) # get_window always returns float64
+
+ if domain == 'time' and not xp.isdtype(x.dtype, 'complex floating'): # use rfft():
+ X = sp_fft.rfft(x)
+ if W is not None: # fold window, i.e., W1[l] = (W[l] + W[-l]) / 2 for l > 0
+ n_X = X.shape[-1]
+ W[1:n_X] += xp.flip(W[-n_X+1:]) #W[:-n_X:-1]
+ W[1:n_X] /= 2
+ X *= W[:n_X] # apply window
+ X = X[..., :m2] # extract relevant data
+ if m % 2 == 0 and num != n_x: # Account for unpaired bin at m//2:
+ X[..., m//2] *= 2 if num < n_x else 0.5
+ x_r = sp_fft.irfft(X / s_fac, n=num, overwrite_x=True)
+ else: # use standard two-sided FFT:
+ X = sp_fft.fft(x) if domain == 'time' else x
+ if W is not None:
+ X = X * W # writing X *= W could modify parameter x
+ Y = xp.zeros(X.shape[:-1] + (num,), dtype=X.dtype)
+ Y[..., :m2] = X[..., :m2] # copy part up to Nyquist frequency
+ if m2 < m: # == m > 2
+ Y[..., m2-m:] = X[..., m2-m:] # copy negative frequency part
+ if m % 2 == 0: # Account for unpaired bin at m//2:
+ if num < n_x: # down-sampling: unite bin pair into one unpaired bin
+ Y[..., -m//2] += X[..., -m//2]
+ elif n_x < num: # up-sampling: split unpaired bin into bin pair
+ Y[..., m//2] /= 2
+ Y[..., num-m//2] = Y[..., m//2]
+ x_r = sp_fft.ifft(Y / s_fac, n=num, overwrite_x=True)
+
+ if x_r.ndim > 1: # moving active axis back to original position:
+ x_r = xp.moveaxis(x_r, -1, axis)
+ if t is not None:
+ return x_r, t[0] + (t[1] - t[0]) * s_fac * xp.arange(num)
+ return x_r
+
+
+def resample_poly(x, up, down, axis=0, window=('kaiser', 5.0),
+ padtype='constant', cval=None):
+ """
+ Resample `x` along the given axis using polyphase filtering.
+
+ The signal `x` is upsampled by the factor `up`, a zero-phase low-pass
+ FIR filter is applied, and then it is downsampled by the factor `down`.
+ The resulting sample rate is ``up / down`` times the original sample
+ rate. By default, values beyond the boundary of the signal are assumed
+ to be zero during the filtering step.
+
+ Parameters
+ ----------
+ x : array_like
+ The data to be resampled.
+ up : int
+ The upsampling factor.
+ down : int
+ The downsampling factor.
+ axis : int, optional
+ The axis of `x` that is resampled. Default is 0.
+ window : string, tuple, or array_like, optional
+ Desired window to use to design the low-pass filter, or the FIR filter
+ coefficients to employ. See below for details.
+ padtype : string, optional
+ `constant`, `line`, `mean`, `median`, `maximum`, `minimum` or any of
+ the other signal extension modes supported by `scipy.signal.upfirdn`.
+ Changes assumptions on values beyond the boundary. If `constant`,
+ assumed to be `cval` (default zero). If `line` assumed to continue a
+ linear trend defined by the first and last points. `mean`, `median`,
+ `maximum` and `minimum` work as in `np.pad` and assume that the values
+ beyond the boundary are the mean, median, maximum or minimum
+ respectively of the array along the axis.
+
+ .. versionadded:: 1.4.0
+ cval : float, optional
+ Value to use if `padtype='constant'`. Default is zero.
+
+ .. versionadded:: 1.4.0
+
+ Returns
+ -------
+ resampled_x : array
+ The resampled array.
+
+ See Also
+ --------
+ decimate : Downsample the signal after applying an FIR or IIR filter.
+ resample : Resample up or down using the FFT method.
+
+ Notes
+ -----
+ This polyphase method will likely be faster than the Fourier method
+ in `scipy.signal.resample` when the number of samples is large and
+ prime, or when the number of samples is large and `up` and `down`
+ share a large greatest common denominator. The length of the FIR
+ filter used will depend on ``max(up, down) // gcd(up, down)``, and
+ the number of operations during polyphase filtering will depend on
+ the filter length and `down` (see `scipy.signal.upfirdn` for details).
+
+ The argument `window` specifies the FIR low-pass filter design.
+
+ If `window` is an array_like it is assumed to be the FIR filter
+ coefficients. Note that the FIR filter is applied after the upsampling
+ step, so it should be designed to operate on a signal at a sampling
+ frequency higher than the original by a factor of `up//gcd(up, down)`.
+ This function's output will be centered with respect to this array, so it
+ is best to pass a symmetric filter with an odd number of samples if, as
+ is usually the case, a zero-phase filter is desired.
+
+ For any other type of `window`, the functions `scipy.signal.get_window`
+ and `scipy.signal.firwin` are called to generate the appropriate filter
+ coefficients.
+
+ The first sample of the returned vector is the same as the first
+ sample of the input vector. The spacing between samples is changed
+ from ``dx`` to ``dx * down / float(up)``.
+
+ Examples
+ --------
+ By default, the end of the resampled data rises to meet the first
+ sample of the next cycle for the FFT method, and gets closer to zero
+ for the polyphase method:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> x = np.linspace(0, 10, 20, endpoint=False)
+ >>> y = np.cos(-x**2/6.0)
+ >>> f_fft = signal.resample(y, 100)
+ >>> f_poly = signal.resample_poly(y, 100, 20)
+ >>> xnew = np.linspace(0, 10, 100, endpoint=False)
+
+ >>> plt.plot(xnew, f_fft, 'b.-', xnew, f_poly, 'r.-')
+ >>> plt.plot(x, y, 'ko-')
+ >>> plt.plot(10, y[0], 'bo', 10, 0., 'ro') # boundaries
+ >>> plt.legend(['resample', 'resamp_poly', 'data'], loc='best')
+ >>> plt.show()
+
+ This default behaviour can be changed by using the padtype option:
+
+ >>> N = 5
+ >>> x = np.linspace(0, 1, N, endpoint=False)
+ >>> y = 2 + x**2 - 1.7*np.sin(x) + .2*np.cos(11*x)
+ >>> y2 = 1 + x**3 + 0.1*np.sin(x) + .1*np.cos(11*x)
+ >>> Y = np.stack([y, y2], axis=-1)
+ >>> up = 4
+ >>> xr = np.linspace(0, 1, N*up, endpoint=False)
+
+ >>> y2 = signal.resample_poly(Y, up, 1, padtype='constant')
+ >>> y3 = signal.resample_poly(Y, up, 1, padtype='mean')
+ >>> y4 = signal.resample_poly(Y, up, 1, padtype='line')
+
+ >>> for i in [0,1]:
+ ... plt.figure()
+ ... plt.plot(xr, y4[:,i], 'g.', label='line')
+ ... plt.plot(xr, y3[:,i], 'y.', label='mean')
+ ... plt.plot(xr, y2[:,i], 'r.', label='constant')
+ ... plt.plot(x, Y[:,i], 'k-')
+ ... plt.legend()
+ >>> plt.show()
+
+ """
+ xp = array_namespace(x)
+
+ x = xp.asarray(x)
+ if up != int(up):
+ raise ValueError("up must be an integer")
+ if down != int(down):
+ raise ValueError("down must be an integer")
+ up = int(up)
+ down = int(down)
+ if up < 1 or down < 1:
+ raise ValueError('up and down must be >= 1')
+ if cval is not None and padtype != 'constant':
+ raise ValueError('cval has no effect when padtype is ', padtype)
+
+ # Determine our up and down factors
+ # Use a rational approximation to save computation time on really long
+ # signals
+ g_ = math.gcd(up, down)
+ up //= g_
+ down //= g_
+ if up == down == 1:
+ return xp.asarray(x, copy=True)
+ n_in = x.shape[axis]
+ n_out = n_in * up
+ n_out = n_out // down + bool(n_out % down)
+
+ if isinstance(window, list) or is_array_api_obj(window):
+ window = xp.asarray(window, copy=True) # force a copy (we modify `window`)
+ if window.ndim > 1:
+ raise ValueError('window must be 1-D')
+ half_len = (xp_size(window) - 1) // 2
+ h = window
+ else:
+ # Design a linear-phase low-pass FIR filter
+ max_rate = max(up, down)
+ f_c = 1. / max_rate # cutoff of FIR filter (rel. to Nyquist)
+ half_len = 10 * max_rate # reasonable cutoff for sinc-like function
+ if xp.isdtype(x.dtype, ("real floating", "complex floating")):
+ h = firwin(2 * half_len + 1, f_c, window=window)
+ h = xp.asarray(h, dtype=x.dtype) # match dtype of x
+ else:
+ h = firwin(2 * half_len + 1, f_c, window=window)
+ h = xp.asarray(h)
+
+ h *= up
+
+ # Zero-pad our filter to put the output samples at the center
+ n_pre_pad = (down - half_len % down)
+ n_post_pad = 0
+ n_pre_remove = (half_len + n_pre_pad) // down
+ # We should rarely need to do this given our filter lengths...
+ while _output_len(h.shape[0] + n_pre_pad + n_post_pad, n_in,
+ up, down) < n_out + n_pre_remove:
+ n_post_pad += 1
+ h = xp.concat((xp.zeros(n_pre_pad, dtype=h.dtype), h,
+ xp.zeros(n_post_pad, dtype=h.dtype)))
+ n_pre_remove_end = n_pre_remove + n_out
+
+ # XXX consider using stats.quantile, which is natively Array API compatible
+ def _median(x, *args, **kwds):
+ return xp.asarray(np.median(np.asarray(x), *args, **kwds))
+
+ # Remove background depending on the padtype option
+ funcs = {'mean': xp.mean, 'median': _median,
+ 'minimum': xp.min, 'maximum': xp.max}
+ upfirdn_kwargs = {'mode': 'constant', 'cval': 0}
+ if padtype in funcs:
+ background_values = funcs[padtype](x, axis=axis, keepdims=True)
+ elif padtype in _upfirdn_modes:
+ upfirdn_kwargs = {'mode': padtype}
+ if padtype == 'constant':
+ if cval is None:
+ cval = 0
+ upfirdn_kwargs['cval'] = cval
+ else:
+ raise ValueError(
+ 'padtype must be one of: maximum, mean, median, minimum, ' +
+ ', '.join(_upfirdn_modes))
+
+ if padtype in funcs:
+ x = x - background_values
+
+ # filter then remove excess
+ y = upfirdn(h, x, up, down, axis=axis, **upfirdn_kwargs)
+ keep = [slice(None), ]*x.ndim
+ keep[axis] = slice(n_pre_remove, n_pre_remove_end)
+ y_keep = y[tuple(keep)]
+
+ # Add background back
+ if padtype in funcs:
+ y_keep += background_values
+
+ return y_keep
+
+
+def _angle(z, xp):
+ """np.angle replacement
+ """
+ # XXX: https://github.com/data-apis/array-api/issues/595
+ zimag = xp.imag(z) if xp.isdtype(z.dtype, 'complex floating') else 0.
+ a = xp.atan2(zimag, xp.real(z))
+ return a
+
+
+def vectorstrength(events, period):
+ '''
+ Determine the vector strength of the events corresponding to the given
+ period.
+
+ The vector strength is a measure of phase synchrony, how well the
+ timing of the events is synchronized to a single period of a periodic
+ signal.
+
+ If multiple periods are used, calculate the vector strength of each.
+ This is called the "resonating vector strength".
+
+ Parameters
+ ----------
+ events : 1D array_like
+ An array of time points containing the timing of the events.
+ period : float or array_like
+ The period of the signal that the events should synchronize to.
+ The period is in the same units as `events`. It can also be an array
+ of periods, in which case the outputs are arrays of the same length.
+
+ Returns
+ -------
+ strength : float or 1D array
+ The strength of the synchronization. 1.0 is perfect synchronization
+ and 0.0 is no synchronization. If `period` is an array, this is also
+ an array with each element containing the vector strength at the
+ corresponding period.
+ phase : float or array
+ The phase that the events are most strongly synchronized to in radians.
+ If `period` is an array, this is also an array with each element
+ containing the phase for the corresponding period.
+
+ References
+ ----------
+ van Hemmen, JL, Longtin, A, and Vollmayr, AN. Testing resonating vector
+ strength: Auditory system, electric fish, and noise.
+ Chaos 21, 047508 (2011);
+ :doi:`10.1063/1.3670512`.
+ van Hemmen, JL. Vector strength after Goldberg, Brown, and von Mises:
+ biological and mathematical perspectives. Biol Cybern.
+ 2013 Aug;107(4):385-96. :doi:`10.1007/s00422-013-0561-7`.
+ van Hemmen, JL and Vollmayr, AN. Resonating vector strength: what happens
+ when we vary the "probing" frequency while keeping the spike times
+ fixed. Biol Cybern. 2013 Aug;107(4):491-94.
+ :doi:`10.1007/s00422-013-0560-8`.
+ '''
+ xp = array_namespace(events, period)
+
+ events = xp.asarray(events)
+ period = xp.asarray(period)
+ if xp.isdtype(period.dtype, 'integral'):
+ period = xp.astype(period, xp.float64)
+
+ if events.ndim > 1:
+ raise ValueError('events cannot have dimensions more than 1')
+ if period.ndim > 1:
+ raise ValueError('period cannot have dimensions more than 1')
+
+ # we need to know later if period was originally a scalar
+ scalarperiod = not period.ndim
+
+ events = xpx.atleast_nd(events, ndim=2, xp=xp)
+ period = xpx.atleast_nd(period, ndim=2, xp=xp)
+ if xp.any(period <= 0):
+ raise ValueError('periods must be positive')
+
+ # this converts the times to vectors
+ events_ = xp.astype(events, period.dtype)
+ vectors = xp.exp(2j * (xp.pi / period.T @ events_))
+
+ # the vector strength is just the magnitude of the mean of the vectors
+ # the vector phase is the angle of the mean of the vectors
+ vectormean = xp.mean(vectors, axis=1)
+ strength = xp.abs(vectormean)
+ phase = _angle(vectormean, xp)
+
+ # if the original period was a scalar, return scalars
+ if scalarperiod:
+ strength = strength[0]
+ phase = phase[0]
+ return strength, phase
+
+
+def detrend(data: np.ndarray, axis: int = -1,
+ type: Literal['linear', 'constant'] = 'linear',
+ bp: ArrayLike | int = 0, overwrite_data: bool = False) -> np.ndarray:
+ r"""Remove linear or constant trend along axis from data.
+
+ Parameters
+ ----------
+ data : array_like
+ The input data.
+ axis : int, optional
+ The axis along which to detrend the data. By default this is the
+ last axis (-1).
+ type : {'linear', 'constant'}, optional
+ The type of detrending. If ``type == 'linear'`` (default),
+ the result of a linear least-squares fit to `data` is subtracted
+ from `data`.
+ If ``type == 'constant'``, only the mean of `data` is subtracted.
+ bp : array_like of ints, optional
+ A sequence of break points. If given, an individual linear fit is
+ performed for each part of `data` between two break points.
+ Break points are specified as indices into `data`. This parameter
+ only has an effect when ``type == 'linear'``.
+ overwrite_data: bool, optional
+ If True, allow in place detrending and avoid a copy. Default is
+ False. In place modification applies only if ``type == 'linear'``
+ and `data` is of the floating point dtype ``float32``, ``float64``,
+ ``complex64`` or ``complex128``.
+
+ Returns
+ -------
+ ret : ndarray
+ The detrended input data.
+
+ Notes
+ -----
+ Detrending can be interpreted as subtracting a least squares fit polynomial:
+ Setting the parameter `type` to 'constant' corresponds to fitting a zeroth degree
+ polynomial, 'linear' to a first degree polynomial. Consult the example below.
+
+ See Also
+ --------
+ :meth:`numpy.polynomial.polynomial.Polynomial.fit` : Create least squares fit polynomial.
+
+
+ Examples
+ --------
+ The following example detrends the function :math:`x(t) = \sin(\pi t) + 1/4`:
+
+ >>> import matplotlib.pyplot as plt
+ >>> import numpy as np
+ >>> from scipy.signal import detrend
+ ...
+ >>> t = np.linspace(-0.5, 0.5, 21)
+ >>> x = np.sin(np.pi*t) + 1/4
+ ...
+ >>> x_d_const = detrend(x, type='constant')
+ >>> x_d_linear = detrend(x, type='linear')
+ ...
+ >>> fig1, ax1 = plt.subplots()
+ >>> ax1.set_title(r"Detrending $x(t)=\sin(\pi t) + 1/4$")
+ >>> ax1.set(xlabel="t", ylabel="$x(t)$", xlim=(t[0], t[-1]))
+ >>> ax1.axhline(y=0, color='black', linewidth=.5)
+ >>> ax1.axvline(x=0, color='black', linewidth=.5)
+ >>> ax1.plot(t, x, 'C0.-', label="No detrending")
+ >>> ax1.plot(t, x_d_const, 'C1x-', label="type='constant'")
+ >>> ax1.plot(t, x_d_linear, 'C2+-', label="type='linear'")
+ >>> ax1.legend()
+ >>> plt.show()
+
+ Alternatively, NumPy's `~numpy.polynomial.polynomial.Polynomial` can be used for
+ detrending as well:
+
+ >>> pp0 = np.polynomial.Polynomial.fit(t, x, deg=0) # fit degree 0 polynomial
+ >>> np.allclose(x_d_const, x - pp0(t)) # compare with constant detrend
+ True
+ >>> pp1 = np.polynomial.Polynomial.fit(t, x, deg=1) # fit degree 1 polynomial
+ >>> np.allclose(x_d_linear, x - pp1(t)) # compare with linear detrend
+ True
+
+ Note that `~numpy.polynomial.polynomial.Polynomial` also allows fitting higher
+ degree polynomials. Consult its documentation on how to extract the polynomial
+ coefficients.
+ """ # noqa: E501
+ if type not in ['linear', 'l', 'constant', 'c']:
+ raise ValueError("Trend type must be 'linear' or 'constant'.")
+
+ xp = array_namespace(data, bp)
+
+ data = np.asarray(data)
+ dtype = data.dtype.char
+ if dtype not in 'dfDF':
+ dtype = 'd'
+ if type in ['constant', 'c']:
+ ret = data - np.mean(data, axis, keepdims=True)
+ return xp.asarray(ret)
+ else:
+ dshape = data.shape
+ N = dshape[axis]
+ bp = np.asarray(bp)
+ bp = np.sort(np.unique(np.concatenate(np.atleast_1d(0, bp, N))))
+ if np.any(bp > N):
+ raise ValueError("Breakpoints must be less than length "
+ "of data along given axis.")
+
+ # Restructure data so that axis is along first dimension and
+ # all other dimensions are collapsed into second dimension
+ rnk = len(dshape)
+ if axis < 0:
+ axis = axis + rnk
+ newdata = np.moveaxis(data, axis, 0)
+ newdata_shape = newdata.shape
+ newdata = newdata.reshape(N, -1)
+
+ if not overwrite_data:
+ newdata = newdata.copy() # make sure we have a copy
+ if newdata.dtype.char not in 'dfDF':
+ newdata = newdata.astype(dtype)
+
+# Nreg = len(bp) - 1
+ # Find leastsq fit and remove it for each piece
+ for m in range(len(bp) - 1):
+ Npts = bp[m + 1] - bp[m]
+ A = np.ones((Npts, 2), dtype)
+ A[:, 0] = np.arange(1, Npts + 1, dtype=dtype) / Npts
+ sl = slice(bp[m], bp[m + 1])
+ coef, resids, rank, s = linalg.lstsq(A, newdata[sl])
+ newdata[sl] = newdata[sl] - A @ coef
+
+ # Put data back in original shape.
+ newdata = newdata.reshape(newdata_shape)
+ ret = np.moveaxis(newdata, 0, axis)
+ return xp.asarray(ret)
+
+
+def lfilter_zi(b, a):
+ """
+ Construct initial conditions for lfilter for step response steady-state.
+
+ Compute an initial state `zi` for the `lfilter` function that corresponds
+ to the steady state of the step response.
+
+ A typical use of this function is to set the initial state so that the
+ output of the filter starts at the same value as the first element of
+ the signal to be filtered.
+
+ Parameters
+ ----------
+ b, a : array_like (1-D)
+ The IIR filter coefficients. See `lfilter` for more
+ information.
+
+ Returns
+ -------
+ zi : 1-D ndarray
+ The initial state for the filter.
+
+ See Also
+ --------
+ lfilter, lfiltic, filtfilt
+
+ Notes
+ -----
+ A linear filter with order m has a state space representation (A, B, C, D),
+ for which the output y of the filter can be expressed as::
+
+ z(n+1) = A*z(n) + B*x(n)
+ y(n) = C*z(n) + D*x(n)
+
+ where z(n) is a vector of length m, A has shape (m, m), B has shape
+ (m, 1), C has shape (1, m) and D has shape (1, 1) (assuming x(n) is
+ a scalar). lfilter_zi solves::
+
+ zi = A*zi + B
+
+ In other words, it finds the initial condition for which the response
+ to an input of all ones is a constant.
+
+ Given the filter coefficients `a` and `b`, the state space matrices
+ for the transposed direct form II implementation of the linear filter,
+ which is the implementation used by scipy.signal.lfilter, are::
+
+ A = scipy.linalg.companion(a).T
+ B = b[1:] - a[1:]*b[0]
+
+ assuming ``a[0]`` is 1.0; if ``a[0]`` is not 1, `a` and `b` are first
+ divided by a[0].
+
+ Examples
+ --------
+ The following code creates a lowpass Butterworth filter. Then it
+ applies that filter to an array whose values are all 1.0; the
+ output is also all 1.0, as expected for a lowpass filter. If the
+ `zi` argument of `lfilter` had not been given, the output would have
+ shown the transient signal.
+
+ >>> from numpy import array, ones
+ >>> from scipy.signal import lfilter, lfilter_zi, butter
+ >>> b, a = butter(5, 0.25)
+ >>> zi = lfilter_zi(b, a)
+ >>> y, zo = lfilter(b, a, ones(10), zi=zi)
+ >>> y
+ array([1., 1., 1., 1., 1., 1., 1., 1., 1., 1.])
+
+ Another example:
+
+ >>> x = array([0.5, 0.5, 0.5, 0.0, 0.0, 0.0, 0.0])
+ >>> y, zf = lfilter(b, a, x, zi=zi*x[0])
+ >>> y
+ array([ 0.5 , 0.5 , 0.5 , 0.49836039, 0.48610528,
+ 0.44399389, 0.35505241])
+
+ Note that the `zi` argument to `lfilter` was computed using
+ `lfilter_zi` and scaled by ``x[0]``. Then the output `y` has no
+ transient until the input drops from 0.5 to 0.0.
+
+ """
+ xp = array_namespace(b, a)
+
+ # FIXME: Can this function be replaced with an appropriate
+ # use of lfiltic? For example, when b,a = butter(N,Wn),
+ # lfiltic(b, a, y=numpy.ones_like(a), x=numpy.ones_like(b)).
+ #
+
+ # We could use scipy.signal.normalize, but it uses warnings in
+ # cases where a ValueError is more appropriate, and it allows
+ # b to be 2D.
+ b = xpx.atleast_nd(xp.asarray(b), ndim=1, xp=xp)
+ if b.ndim != 1:
+ raise ValueError("Numerator b must be 1-D.")
+ a = xpx.atleast_nd(xp.asarray(a), ndim=1, xp=xp)
+ if a.ndim != 1:
+ raise ValueError("Denominator a must be 1-D.")
+
+ while a.shape[0] > 1 and a[0] == 0.0:
+ a = a[1:]
+ if xp_size(a) < 1:
+ raise ValueError("There must be at least one nonzero `a` coefficient.")
+
+ if a[0] != 1.0:
+ # Normalize the coefficients so a[0] == 1.
+ b = b / a[0]
+ a = a / a[0]
+
+ n = max(a.shape[0], b.shape[0])
+
+ # Pad a or b with zeros so they are the same length.
+ if a.shape[0] < n:
+ a = xp.concat((a, xp.zeros(n - a.shape[0], dtype=a.dtype)))
+ elif b.shape[0] < n:
+ b = xp.concat((b, xp.zeros(n - b.shape[0], dtype=b.dtype)))
+
+ dt = xp.result_type(a, b)
+ IminusA = np.eye(n - 1) - linalg.companion(a).T
+ IminusA = xp.asarray(IminusA, dtype=dt)
+ B = b[1:] - a[1:] * b[0]
+ # Solve zi = A*zi + B
+ zi = xp.linalg.solve(IminusA, B)
+
+ # For future reference: we could also use the following
+ # explicit formulas to solve the linear system:
+ #
+ # zi = np.zeros(n - 1)
+ # zi[0] = B.sum() / IminusA[:,0].sum()
+ # asum = 1.0
+ # csum = 0.0
+ # for k in range(1,n-1):
+ # asum += a[k]
+ # csum += b[k] - a[k]*b[0]
+ # zi[k] = asum*zi[0] - csum
+
+ return zi
+
+
+def sosfilt_zi(sos):
+ """
+ Construct initial conditions for sosfilt for step response steady-state.
+
+ Compute an initial state `zi` for the `sosfilt` function that corresponds
+ to the steady state of the step response.
+
+ A typical use of this function is to set the initial state so that the
+ output of the filter starts at the same value as the first element of
+ the signal to be filtered.
+
+ Parameters
+ ----------
+ sos : array_like
+ Array of second-order filter coefficients, must have shape
+ ``(n_sections, 6)``. See `sosfilt` for the SOS filter format
+ specification.
+
+ Returns
+ -------
+ zi : ndarray
+ Initial conditions suitable for use with ``sosfilt``, shape
+ ``(n_sections, 2)``.
+
+ See Also
+ --------
+ sosfilt, zpk2sos
+
+ Notes
+ -----
+ .. versionadded:: 0.16.0
+
+ Examples
+ --------
+ Filter a rectangular pulse that begins at time 0, with and without
+ the use of the `zi` argument of `scipy.signal.sosfilt`.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ >>> sos = signal.butter(9, 0.125, output='sos')
+ >>> zi = signal.sosfilt_zi(sos)
+ >>> x = (np.arange(250) < 100).astype(int)
+ >>> f1 = signal.sosfilt(sos, x)
+ >>> f2, zo = signal.sosfilt(sos, x, zi=zi)
+
+ >>> plt.plot(x, 'k--', label='x')
+ >>> plt.plot(f1, 'b', alpha=0.5, linewidth=2, label='filtered')
+ >>> plt.plot(f2, 'g', alpha=0.25, linewidth=4, label='filtered with zi')
+ >>> plt.legend(loc='best')
+ >>> plt.show()
+
+ """
+ xp = array_namespace(sos)
+
+ sos = xp.asarray(sos)
+ if sos.ndim != 2 or sos.shape[1] != 6:
+ raise ValueError('sos must be shape (n_sections, 6)')
+
+ if xp.isdtype(sos.dtype, ("integral", "bool")):
+ sos = xp.astype(sos, xp.float64)
+
+ n_sections = sos.shape[0]
+ zi = xp.empty((n_sections, 2), dtype=sos.dtype)
+ scale = 1.0
+ for section in range(n_sections):
+ b = sos[section, :3]
+ a = sos[section, 3:]
+ zi[section, ...] = scale * lfilter_zi(b, a)
+ # If H(z) = B(z)/A(z) is this section's transfer function, then
+ # b.sum()/a.sum() is H(1), the gain at omega=0. That's the steady
+ # state value of this section's step response.
+ scale *= xp.sum(b) / xp.sum(a)
+
+ return zi
+
+
+def _filtfilt_gust(b, a, x, axis=-1, irlen=None):
+ """Forward-backward IIR filter that uses Gustafsson's method.
+
+ Apply the IIR filter defined by ``(b,a)`` to `x` twice, first forward
+ then backward, using Gustafsson's initial conditions [1]_.
+
+ Let ``y_fb`` be the result of filtering first forward and then backward,
+ and let ``y_bf`` be the result of filtering first backward then forward.
+ Gustafsson's method is to compute initial conditions for the forward
+ pass and the backward pass such that ``y_fb == y_bf``.
+
+ Parameters
+ ----------
+ b : scalar or 1-D ndarray
+ Numerator coefficients of the filter.
+ a : scalar or 1-D ndarray
+ Denominator coefficients of the filter.
+ x : ndarray
+ Data to be filtered.
+ axis : int, optional
+ Axis of `x` to be filtered. Default is -1.
+ irlen : int or None, optional
+ The length of the nonnegligible part of the impulse response.
+ If `irlen` is None, or if the length of the signal is less than
+ ``2 * irlen``, then no part of the impulse response is ignored.
+
+ Returns
+ -------
+ y : ndarray
+ The filtered data.
+ x0 : ndarray
+ Initial condition for the forward filter.
+ x1 : ndarray
+ Initial condition for the backward filter.
+
+ Notes
+ -----
+ Typically the return values `x0` and `x1` are not needed by the
+ caller. The intended use of these return values is in unit tests.
+
+ References
+ ----------
+ .. [1] F. Gustaffson. Determining the initial states in forward-backward
+ filtering. Transactions on Signal Processing, 46(4):988-992, 1996.
+
+ """
+ # In the comments, "Gustafsson's paper" and [1] refer to the
+ # paper referenced in the docstring.
+
+ b = np.atleast_1d(b)
+ a = np.atleast_1d(a)
+
+ order = max(len(b), len(a)) - 1
+ if order == 0:
+ # The filter is just scalar multiplication, with no state.
+ scale = (b[0] / a[0])**2
+ y = scale * x
+ return y, np.array([]), np.array([])
+
+ if axis != -1 or axis != x.ndim - 1:
+ # Move the axis containing the data to the end.
+ x = np.swapaxes(x, axis, x.ndim - 1)
+
+ # n is the number of samples in the data to be filtered.
+ n = x.shape[-1]
+
+ if irlen is None or n <= 2*irlen:
+ m = n
+ else:
+ m = irlen
+
+ # Create Obs, the observability matrix (called O in the paper).
+ # This matrix can be interpreted as the operator that propagates
+ # an arbitrary initial state to the output, assuming the input is
+ # zero.
+ # In Gustafsson's paper, the forward and backward filters are not
+ # necessarily the same, so he has both O_f and O_b. We use the same
+ # filter in both directions, so we only need O. The same comment
+ # applies to S below.
+ Obs = np.zeros((m, order))
+ zi = np.zeros(order)
+ zi[0] = 1
+ Obs[:, 0] = lfilter(b, a, np.zeros(m), zi=zi)[0]
+ for k in range(1, order):
+ Obs[k:, k] = Obs[:-k, 0]
+
+ # Obsr is O^R (Gustafsson's notation for row-reversed O)
+ Obsr = Obs[::-1]
+
+ # Create S. S is the matrix that applies the filter to the reversed
+ # propagated initial conditions. That is,
+ # out = S.dot(zi)
+ # is the same as
+ # tmp, _ = lfilter(b, a, zeros(), zi=zi) # Propagate ICs.
+ # out = lfilter(b, a, tmp[::-1]) # Reverse and filter.
+
+ # Equations (5) & (6) of [1]
+ S = lfilter(b, a, Obs[::-1], axis=0)
+
+ # Sr is S^R (row-reversed S)
+ Sr = S[::-1]
+
+ # M is [(S^R - O), (O^R - S)]
+ if m == n:
+ M = np.hstack((Sr - Obs, Obsr - S))
+ else:
+ # Matrix described in section IV of [1].
+ M = np.zeros((2*m, 2*order))
+ M[:m, :order] = Sr - Obs
+ M[m:, order:] = Obsr - S
+
+ # Naive forward-backward and backward-forward filters.
+ # These have large transients because the filters use zero initial
+ # conditions.
+ y_f = lfilter(b, a, x)
+ y_fb = lfilter(b, a, y_f[..., ::-1])[..., ::-1]
+
+ y_b = lfilter(b, a, x[..., ::-1])[..., ::-1]
+ y_bf = lfilter(b, a, y_b)
+
+ delta_y_bf_fb = y_bf - y_fb
+ if m == n:
+ delta = delta_y_bf_fb
+ else:
+ start_m = delta_y_bf_fb[..., :m]
+ end_m = delta_y_bf_fb[..., -m:]
+ delta = np.concatenate((start_m, end_m), axis=-1)
+
+ # ic_opt holds the "optimal" initial conditions.
+ # The following code computes the result shown in the formula
+ # of the paper between equations (6) and (7).
+ if delta.ndim == 1:
+ ic_opt = linalg.lstsq(M, delta)[0]
+ else:
+ # Reshape delta so it can be used as an array of multiple
+ # right-hand-sides in linalg.lstsq.
+ delta2d = delta.reshape(-1, delta.shape[-1]).T
+ ic_opt0 = linalg.lstsq(M, delta2d)[0].T
+ ic_opt = ic_opt0.reshape(delta.shape[:-1] + (M.shape[-1],))
+
+ # Now compute the filtered signal using equation (7) of [1].
+ # First, form [S^R, O^R] and call it W.
+ if m == n:
+ W = np.hstack((Sr, Obsr))
+ else:
+ W = np.zeros((2*m, 2*order))
+ W[:m, :order] = Sr
+ W[m:, order:] = Obsr
+
+ # Equation (7) of [1] says
+ # Y_fb^opt = Y_fb^0 + W * [x_0^opt; x_{N-1}^opt]
+ # `wic` is (almost) the product on the right.
+ # W has shape (m, 2*order), and ic_opt has shape (..., 2*order),
+ # so we can't use W.dot(ic_opt). Instead, we dot ic_opt with W.T,
+ # so wic has shape (..., m).
+ wic = ic_opt.dot(W.T)
+
+ # `wic` is "almost" the product of W and the optimal ICs in equation
+ # (7)--if we're using a truncated impulse response (m < n), `wic`
+ # contains only the adjustments required for the ends of the signal.
+ # Here we form y_opt, taking this into account if necessary.
+ y_opt = y_fb
+ if m == n:
+ y_opt += wic
+ else:
+ y_opt[..., :m] += wic[..., :m]
+ y_opt[..., -m:] += wic[..., -m:]
+
+ x0 = ic_opt[..., :order]
+ x1 = ic_opt[..., -order:]
+ if axis != -1 or axis != x.ndim - 1:
+ # Restore the data axis to its original position.
+ x0 = np.swapaxes(x0, axis, x.ndim - 1)
+ x1 = np.swapaxes(x1, axis, x.ndim - 1)
+ y_opt = np.swapaxes(y_opt, axis, x.ndim - 1)
+
+ return y_opt, x0, x1
+
+
+def filtfilt(b, a, x, axis=-1, padtype='odd', padlen=None, method='pad',
+ irlen=None):
+ """
+ Apply a digital filter forward and backward to a signal.
+
+ This function applies a linear digital filter twice, once forward and
+ once backwards. The combined filter has zero phase and a filter order
+ twice that of the original.
+
+ The function provides options for handling the edges of the signal.
+
+ The function `sosfiltfilt` (and filter design using ``output='sos'``)
+ should be preferred over `filtfilt` for most filtering tasks, as
+ second-order sections have fewer numerical problems.
+
+ Parameters
+ ----------
+ b : (N,) array_like
+ The numerator coefficient vector of the filter.
+ a : (N,) array_like
+ The denominator coefficient vector of the filter. If ``a[0]``
+ is not 1, then both `a` and `b` are normalized by ``a[0]``.
+ x : array_like
+ The array of data to be filtered.
+ axis : int, optional
+ The axis of `x` to which the filter is applied.
+ Default is -1.
+ padtype : str or None, optional
+ Must be 'odd', 'even', 'constant', or None. This determines the
+ type of extension to use for the padded signal to which the filter
+ is applied. If `padtype` is None, no padding is used. The default
+ is 'odd'.
+ padlen : int or None, optional
+ The number of elements by which to extend `x` at both ends of
+ `axis` before applying the filter. This value must be less than
+ ``x.shape[axis] - 1``. ``padlen=0`` implies no padding.
+ The default value is ``3 * max(len(a), len(b))``.
+ method : str, optional
+ Determines the method for handling the edges of the signal, either
+ "pad" or "gust". When `method` is "pad", the signal is padded; the
+ type of padding is determined by `padtype` and `padlen`, and `irlen`
+ is ignored. When `method` is "gust", Gustafsson's method is used,
+ and `padtype` and `padlen` are ignored.
+ irlen : int or None, optional
+ When `method` is "gust", `irlen` specifies the length of the
+ impulse response of the filter. If `irlen` is None, no part
+ of the impulse response is ignored. For a long signal, specifying
+ `irlen` can significantly improve the performance of the filter.
+
+ Returns
+ -------
+ y : ndarray
+ The filtered output with the same shape as `x`.
+
+ See Also
+ --------
+ sosfiltfilt, lfilter_zi, lfilter, lfiltic, savgol_filter, sosfilt
+
+ Notes
+ -----
+ When `method` is "pad", the function pads the data along the given axis
+ in one of three ways: odd, even or constant. The odd and even extensions
+ have the corresponding symmetry about the end point of the data. The
+ constant extension extends the data with the values at the end points. On
+ both the forward and backward passes, the initial condition of the
+ filter is found by using `lfilter_zi` and scaling it by the end point of
+ the extended data.
+
+ When `method` is "gust", Gustafsson's method [1]_ is used. Initial
+ conditions are chosen for the forward and backward passes so that the
+ forward-backward filter gives the same result as the backward-forward
+ filter.
+
+ The option to use Gustaffson's method was added in scipy version 0.16.0.
+
+ References
+ ----------
+ .. [1] F. Gustaffson, "Determining the initial states in forward-backward
+ filtering", Transactions on Signal Processing, Vol. 46, pp. 988-992,
+ 1996.
+
+ Examples
+ --------
+ The examples will use several functions from `scipy.signal`.
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ First we create a one second signal that is the sum of two pure sine
+ waves, with frequencies 5 Hz and 250 Hz, sampled at 2000 Hz.
+
+ >>> t = np.linspace(0, 1.0, 2001)
+ >>> xlow = np.sin(2 * np.pi * 5 * t)
+ >>> xhigh = np.sin(2 * np.pi * 250 * t)
+ >>> x = xlow + xhigh
+
+ Now create a lowpass Butterworth filter with a cutoff of 0.125 times
+ the Nyquist frequency, or 125 Hz, and apply it to ``x`` with `filtfilt`.
+ The result should be approximately ``xlow``, with no phase shift.
+
+ >>> b, a = signal.butter(8, 0.125)
+ >>> y = signal.filtfilt(b, a, x, padlen=150)
+ >>> np.abs(y - xlow).max()
+ 9.1086182074789912e-06
+
+ We get a fairly clean result for this artificial example because
+ the odd extension is exact, and with the moderately long padding,
+ the filter's transients have dissipated by the time the actual data
+ is reached. In general, transient effects at the edges are
+ unavoidable.
+
+ The following example demonstrates the option ``method="gust"``.
+
+ First, create a filter.
+
+ >>> b, a = signal.ellip(4, 0.01, 120, 0.125) # Filter to be applied.
+
+ `sig` is a random input signal to be filtered.
+
+ >>> rng = np.random.default_rng()
+ >>> n = 60
+ >>> sig = rng.standard_normal(n)**3 + 3*rng.standard_normal(n).cumsum()
+
+ Apply `filtfilt` to `sig`, once using the Gustafsson method, and
+ once using padding, and plot the results for comparison.
+
+ >>> fgust = signal.filtfilt(b, a, sig, method="gust")
+ >>> fpad = signal.filtfilt(b, a, sig, padlen=50)
+ >>> plt.plot(sig, 'k-', label='input')
+ >>> plt.plot(fgust, 'b-', linewidth=4, label='gust')
+ >>> plt.plot(fpad, 'c-', linewidth=1.5, label='pad')
+ >>> plt.legend(loc='best')
+ >>> plt.show()
+
+ The `irlen` argument can be used to improve the performance
+ of Gustafsson's method.
+
+ Estimate the impulse response length of the filter.
+
+ >>> z, p, k = signal.tf2zpk(b, a)
+ >>> eps = 1e-9
+ >>> r = np.max(np.abs(p))
+ >>> approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r)))
+ >>> approx_impulse_len
+ 137
+
+ Apply the filter to a longer signal, with and without the `irlen`
+ argument. The difference between `y1` and `y2` is small. For long
+ signals, using `irlen` gives a significant performance improvement.
+
+ >>> x = rng.standard_normal(4000)
+ >>> y1 = signal.filtfilt(b, a, x, method='gust')
+ >>> y2 = signal.filtfilt(b, a, x, method='gust', irlen=approx_impulse_len)
+ >>> print(np.max(np.abs(y1 - y2)))
+ 2.875334415008979e-10
+
+ """
+ xp = array_namespace(b, a, x)
+
+ b = np.atleast_1d(np.asarray(b))
+ a = np.atleast_1d(np.asarray(a))
+ x = np.asarray(x)
+
+ if method not in ["pad", "gust"]:
+ raise ValueError("method must be 'pad' or 'gust'.")
+
+ if method == "gust":
+ y, z1, z2 = _filtfilt_gust(b, a, x, axis=axis, irlen=irlen)
+ return xp.asarray(y)
+
+ # method == "pad"
+ edge, ext = _validate_pad(padtype, padlen, x, axis,
+ ntaps=max(len(a), len(b)))
+
+ # Get the steady state of the filter's step response.
+ zi = lfilter_zi(b, a)
+
+ # Reshape zi and create x0 so that zi*x0 broadcasts
+ # to the correct value for the 'zi' keyword argument
+ # to lfilter.
+ zi_shape = [1] * x.ndim
+ zi_shape[axis] = zi.size
+ zi = np.reshape(zi, zi_shape)
+ x0 = axis_slice(ext, stop=1, axis=axis)
+
+ # Forward filter.
+ (y, zf) = lfilter(b, a, ext, axis=axis, zi=zi * x0)
+
+ # Backward filter.
+ # Create y0 so zi*y0 broadcasts appropriately.
+ y0 = axis_slice(y, start=-1, axis=axis)
+ (y, zf) = lfilter(b, a, axis_reverse(y, axis=axis), axis=axis, zi=zi * y0)
+
+ # Reverse y.
+ y = axis_reverse(y, axis=axis)
+
+ if edge > 0:
+ # Slice the actual signal from the extended signal.
+ y = axis_slice(y, start=edge, stop=-edge, axis=axis)
+ if is_torch(xp):
+ y = y.copy() # pytorch/pytorch#59786 : no negative strides in pytorch
+
+ return xp.asarray(y)
+
+
+def _validate_pad(padtype, padlen, x, axis, ntaps):
+ """Helper to validate padding for filtfilt"""
+ if padtype not in ['even', 'odd', 'constant', None]:
+ raise ValueError(f"Unknown value '{padtype}' given to padtype. "
+ "padtype must be 'even', 'odd', 'constant', or None.")
+
+ if padtype is None:
+ padlen = 0
+
+ if padlen is None:
+ # Original padding; preserved for backwards compatibility.
+ edge = ntaps * 3
+ else:
+ edge = padlen
+
+ # x's 'axis' dimension must be bigger than edge.
+ if x.shape[axis] <= edge:
+ raise ValueError(
+ f"The length of the input vector x must be greater than padlen, "
+ f"which is {edge}."
+ )
+
+ if padtype is not None and edge > 0:
+ # Make an extension of length `edge` at each
+ # end of the input array.
+ if padtype == 'even':
+ ext = even_ext(x, edge, axis=axis)
+ elif padtype == 'odd':
+ ext = odd_ext(x, edge, axis=axis)
+ else:
+ ext = const_ext(x, edge, axis=axis)
+ else:
+ ext = x
+ return edge, ext
+
+
+def _validate_x(x):
+ x = np.asarray(x)
+ if x.ndim == 0:
+ raise ValueError('x must be at least 1-D')
+ return x
+
+
+def sosfilt(sos, x, axis=-1, zi=None):
+ """
+ Filter data along one dimension using cascaded second-order sections.
+
+ Filter a data sequence, `x`, using a digital IIR filter defined by
+ `sos`.
+
+ Parameters
+ ----------
+ sos : array_like
+ Array of second-order filter coefficients, must have shape
+ ``(n_sections, 6)``. Each row corresponds to a second-order
+ section, with the first three columns providing the numerator
+ coefficients and the last three providing the denominator
+ coefficients.
+ x : array_like
+ An N-dimensional input array.
+ axis : int, optional
+ The axis of the input data array along which to apply the
+ linear filter. The filter is applied to each subarray along
+ this axis. Default is -1.
+ zi : array_like, optional
+ Initial conditions for the cascaded filter delays. It is a (at
+ least 2D) vector of shape ``(n_sections, ..., 2, ...)``, where
+ ``..., 2, ...`` denotes the shape of `x`, but with ``x.shape[axis]``
+ replaced by 2. If `zi` is None or is not given then initial rest
+ (i.e. all zeros) is assumed.
+ Note that these initial conditions are *not* the same as the initial
+ conditions given by `lfiltic` or `lfilter_zi`.
+
+ Returns
+ -------
+ y : ndarray
+ The output of the digital filter.
+ zf : ndarray, optional
+ If `zi` is None, this is not returned, otherwise, `zf` holds the
+ final filter delay values.
+
+ See Also
+ --------
+ zpk2sos, sos2zpk, sosfilt_zi, sosfiltfilt, freqz_sos
+
+ Notes
+ -----
+ The filter function is implemented as a series of second-order filters
+ with direct-form II transposed structure. It is designed to minimize
+ numerical precision errors for high-order filters.
+
+ .. versionadded:: 0.16.0
+
+ Examples
+ --------
+ Plot a 13th-order filter's impulse response using both `lfilter` and
+ `sosfilt`, showing the instability that results from trying to do a
+ 13th-order filter in a single stage (the numerical error pushes some poles
+ outside of the unit circle):
+
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy import signal
+ >>> b, a = signal.ellip(13, 0.009, 80, 0.05, output='ba')
+ >>> sos = signal.ellip(13, 0.009, 80, 0.05, output='sos')
+ >>> x = signal.unit_impulse(700)
+ >>> y_tf = signal.lfilter(b, a, x)
+ >>> y_sos = signal.sosfilt(sos, x)
+ >>> plt.plot(y_tf, 'r', label='TF')
+ >>> plt.plot(y_sos, 'k', label='SOS')
+ >>> plt.legend(loc='best')
+ >>> plt.show()
+
+ """
+ xp = array_namespace(sos, x, zi)
+
+ x = _validate_x(x)
+ sos, n_sections = _validate_sos(sos)
+ x_zi_shape = list(x.shape)
+ x_zi_shape[axis] = 2
+ x_zi_shape = tuple([n_sections] + x_zi_shape)
+ inputs = [sos, x]
+ if zi is not None:
+ inputs.append(np.asarray(zi))
+ dtype = np.result_type(*inputs)
+ if dtype.char not in 'fdgFDGO':
+ raise NotImplementedError(f"input type '{dtype}' not supported")
+ if zi is not None:
+ zi = np.asarray(zi, dtype=dtype)
+
+ # make a copy so that we can operate in place
+ # NB: 1. use xp_copy to paper over numpy 1/2 copy= keyword
+ # 2. make sure the copied zi remains a numpy array
+ zi = xp_copy(zi, xp=array_namespace(zi))
+ if zi.shape != x_zi_shape:
+ raise ValueError(
+ f"Invalid zi shape. With axis={axis!r}, "
+ f"an input with shape {x.shape!r}, "
+ f"and an sos array with {n_sections} sections, zi must have "
+ f"shape {x_zi_shape!r}, got {zi.shape!r}."
+ )
+ return_zi = True
+ else:
+ zi = np.zeros(x_zi_shape, dtype=dtype)
+ return_zi = False
+ axis = axis % x.ndim # make positive
+ x = np.moveaxis(x, axis, -1)
+ zi = np.moveaxis(zi, (0, axis + 1), (-2, -1))
+ x_shape, zi_shape = x.shape, zi.shape
+ x = np.reshape(x, (-1, x.shape[-1]))
+ x = np.array(x, dtype, order='C') # make a copy, can modify in place
+ zi = np.ascontiguousarray(np.reshape(zi, (-1, n_sections, 2)))
+ sos = sos.astype(dtype, copy=False)
+ _sosfilt(sos, x, zi)
+ x = x.reshape(x_shape)
+ x = np.moveaxis(x, -1, axis)
+ if return_zi:
+ zi = zi.reshape(zi_shape)
+ zi = np.moveaxis(zi, (-2, -1), (0, axis + 1))
+ out = (xp.asarray(x), xp.asarray(zi))
+ else:
+ out = xp.asarray(x)
+ return out
+
+
+def sosfiltfilt(sos, x, axis=-1, padtype='odd', padlen=None):
+ """
+ A forward-backward digital filter using cascaded second-order sections.
+
+ See `filtfilt` for more complete information about this method.
+
+ Parameters
+ ----------
+ sos : array_like
+ Array of second-order filter coefficients, must have shape
+ ``(n_sections, 6)``. Each row corresponds to a second-order
+ section, with the first three columns providing the numerator
+ coefficients and the last three providing the denominator
+ coefficients.
+ x : array_like
+ The array of data to be filtered.
+ axis : int, optional
+ The axis of `x` to which the filter is applied.
+ Default is -1.
+ padtype : str or None, optional
+ Must be 'odd', 'even', 'constant', or None. This determines the
+ type of extension to use for the padded signal to which the filter
+ is applied. If `padtype` is None, no padding is used. The default
+ is 'odd'.
+ padlen : int or None, optional
+ The number of elements by which to extend `x` at both ends of
+ `axis` before applying the filter. This value must be less than
+ ``x.shape[axis] - 1``. ``padlen=0`` implies no padding.
+ The default value is::
+
+ 3 * (2 * len(sos) + 1 - min((sos[:, 2] == 0).sum(),
+ (sos[:, 5] == 0).sum()))
+
+ The extra subtraction at the end attempts to compensate for poles
+ and zeros at the origin (e.g. for odd-order filters) to yield
+ equivalent estimates of `padlen` to those of `filtfilt` for
+ second-order section filters built with `scipy.signal` functions.
+
+ Returns
+ -------
+ y : ndarray
+ The filtered output with the same shape as `x`.
+
+ See Also
+ --------
+ filtfilt, sosfilt, sosfilt_zi, freqz_sos
+
+ Notes
+ -----
+ .. versionadded:: 0.18.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.signal import sosfiltfilt, butter
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+
+ Create an interesting signal to filter.
+
+ >>> n = 201
+ >>> t = np.linspace(0, 1, n)
+ >>> x = 1 + (t < 0.5) - 0.25*t**2 + 0.05*rng.standard_normal(n)
+
+ Create a lowpass Butterworth filter, and use it to filter `x`.
+
+ >>> sos = butter(4, 0.125, output='sos')
+ >>> y = sosfiltfilt(sos, x)
+
+ For comparison, apply an 8th order filter using `sosfilt`. The filter
+ is initialized using the mean of the first four values of `x`.
+
+ >>> from scipy.signal import sosfilt, sosfilt_zi
+ >>> sos8 = butter(8, 0.125, output='sos')
+ >>> zi = x[:4].mean() * sosfilt_zi(sos8)
+ >>> y2, zo = sosfilt(sos8, x, zi=zi)
+
+ Plot the results. Note that the phase of `y` matches the input, while
+ `y2` has a significant phase delay.
+
+ >>> plt.plot(t, x, alpha=0.5, label='x(t)')
+ >>> plt.plot(t, y, label='y(t)')
+ >>> plt.plot(t, y2, label='y2(t)')
+ >>> plt.legend(framealpha=1, shadow=True)
+ >>> plt.grid(alpha=0.25)
+ >>> plt.xlabel('t')
+ >>> plt.show()
+
+ """
+ xp = array_namespace(sos, x)
+
+ sos, n_sections = _validate_sos(sos)
+ x = _validate_x(x)
+
+ # `method` is "pad"...
+ ntaps = 2 * n_sections + 1
+ ntaps -= min((sos[:, 2] == 0).sum(), (sos[:, 5] == 0).sum())
+ edge, ext = _validate_pad(padtype, padlen, x, axis,
+ ntaps=ntaps)
+
+ # These steps follow the same form as filtfilt with modifications
+ zi = sosfilt_zi(sos) # shape (n_sections, 2) --> (n_sections, ..., 2, ...)
+ zi_shape = [1] * x.ndim
+ zi_shape[axis] = 2
+ zi = zi.reshape([n_sections] + zi_shape)
+ x_0 = axis_slice(ext, stop=1, axis=axis)
+ (y, zf) = sosfilt(sos, ext, axis=axis, zi=zi * x_0)
+ y_0 = axis_slice(y, start=-1, axis=axis)
+ (y, zf) = sosfilt(sos, axis_reverse(y, axis=axis), axis=axis, zi=zi * y_0)
+ y = axis_reverse(y, axis=axis)
+ if edge > 0:
+ y = axis_slice(y, start=edge, stop=-edge, axis=axis)
+ return xp.asarray(y)
+
+
+def decimate(x, q, n=None, ftype='iir', axis=-1, zero_phase=True):
+ """
+ Downsample the signal after applying an anti-aliasing filter.
+
+ By default, an order 8 Chebyshev type I filter is used. A 30 point FIR
+ filter with Hamming window is used if `ftype` is 'fir'.
+
+ Parameters
+ ----------
+ x : array_like
+ The input signal made up of equidistant samples. If `x` is a multidimensional
+ array, the parameter `axis` specifies the time axis.
+ q : int
+ The downsampling factor, which is a postive integer. When using IIR
+ downsampling, it is recommended to call `decimate` multiple times for
+ downsampling factors higher than 13.
+ n : int, optional
+ The order of the filter (1 less than the length for 'fir'). Defaults to
+ 8 for 'iir' and 20 times the downsampling factor for 'fir'.
+ ftype : str {'iir', 'fir'} or ``dlti`` instance, optional
+ If 'iir' or 'fir', specifies the type of lowpass filter. If an instance
+ of an `dlti` object, uses that object to filter before downsampling.
+ axis : int, optional
+ The axis along which to decimate.
+ zero_phase : bool, optional
+ Prevent phase shift by filtering with `filtfilt` instead of `lfilter`
+ when using an IIR filter, and shifting the outputs back by the filter's
+ group delay when using an FIR filter. The default value of ``True`` is
+ recommended, since a phase shift is generally not desired.
+
+ .. versionadded:: 0.18.0
+
+ Returns
+ -------
+ y : ndarray
+ The down-sampled signal.
+
+ See Also
+ --------
+ resample : Resample up or down using the FFT method.
+ resample_poly : Resample using polyphase filtering and an FIR filter.
+
+ Notes
+ -----
+ For non-integer downsampling factors, `~scipy.signal.resample` can be used. Consult
+ the `scipy.interpolate` module for methods of resampling signals with non-constant
+ sampling intervals.
+
+ The ``zero_phase`` keyword was added in 0.18.0.
+ The possibility to use instances of ``dlti`` as ``ftype`` was added in
+ 0.18.0.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+
+ Define wave parameters.
+
+ >>> wave_duration = 3
+ >>> sample_rate = 100
+ >>> freq = 2
+ >>> q = 5
+
+ Calculate number of samples.
+
+ >>> samples = wave_duration*sample_rate
+ >>> samples_decimated = int(samples/q)
+
+ Create cosine wave.
+
+ >>> x = np.linspace(0, wave_duration, samples, endpoint=False)
+ >>> y = np.cos(x*np.pi*freq*2)
+
+ Decimate cosine wave.
+
+ >>> ydem = signal.decimate(y, q)
+ >>> xnew = np.linspace(0, wave_duration, samples_decimated, endpoint=False)
+
+ Plot original and decimated waves.
+
+ >>> plt.plot(x, y, '.-', xnew, ydem, 'o-')
+ >>> plt.xlabel('Time, Seconds')
+ >>> plt.legend(['data', 'decimated'], loc='best')
+ >>> plt.show()
+
+ """
+
+ x = np.asarray(x)
+ q = operator.index(q)
+
+ if n is not None:
+ n = operator.index(n)
+
+ result_type = x.dtype
+ if not np.issubdtype(result_type, np.inexact) \
+ or result_type.type == np.float16:
+ # upcast integers and float16 to float64
+ result_type = np.float64
+
+ if ftype == 'fir':
+ if n is None:
+ half_len = 10 * q # reasonable cutoff for our sinc-like function
+ n = 2 * half_len
+ b, a = firwin(n+1, 1. / q, window='hamming'), 1.
+ b = np.asarray(b, dtype=result_type)
+ a = np.asarray(a, dtype=result_type)
+ elif ftype == 'iir':
+ iir_use_sos = True
+ if n is None:
+ n = 8
+ sos = cheby1(n, 0.05, 0.8 / q, output='sos')
+ sos = np.asarray(sos, dtype=result_type)
+ elif isinstance(ftype, dlti):
+ system = ftype._as_zpk()
+ if system.poles.shape[0] == 0:
+ # FIR
+ system = ftype._as_tf()
+ b, a = system.num, system.den
+ ftype = 'fir'
+ elif (any(np.iscomplex(system.poles))
+ or any(np.iscomplex(system.poles))
+ or np.iscomplex(system.gain)):
+ # sosfilt & sosfiltfilt don't handle complex coeffs
+ iir_use_sos = False
+ system = ftype._as_tf()
+ b, a = system.num, system.den
+ else:
+ iir_use_sos = True
+ sos = zpk2sos(system.zeros, system.poles, system.gain)
+ sos = np.asarray(sos, dtype=result_type)
+ else:
+ raise ValueError('invalid ftype')
+
+ sl = [slice(None)] * x.ndim
+
+ if ftype == 'fir':
+ b = b / a
+ if zero_phase:
+ y = resample_poly(x, 1, q, axis=axis, window=b)
+ else:
+ # upfirdn is generally faster than lfilter by a factor equal to the
+ # downsampling factor, since it only calculates the needed outputs
+ n_out = x.shape[axis] // q + bool(x.shape[axis] % q)
+ y = upfirdn(b, x, up=1, down=q, axis=axis)
+ sl[axis] = slice(None, n_out, None)
+
+ else: # IIR case
+ if zero_phase:
+ if iir_use_sos:
+ y = sosfiltfilt(sos, x, axis=axis)
+ else:
+ y = filtfilt(b, a, x, axis=axis)
+ else:
+ if iir_use_sos:
+ y = sosfilt(sos, x, axis=axis)
+ else:
+ y = lfilter(b, a, x, axis=axis)
+
+ sl[axis] = slice(None, None, q)
+
+ return y[tuple(sl)]
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_sigtools.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_sigtools.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..12a6e79e5f4778e37407bee0e7f910638157c523
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_sigtools.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:93010b023d131c82a81eeb9be8de3193cb6f6df694a9ff9888a601b7612017ed
+size 123120
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_sosfilt.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_sosfilt.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ef6f78fed6027e626b0604319ddfd8282c744cd2
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_sosfilt.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:d4c7e7301110fb60f4ca5984260eb33856e6da40a23806a7309e1a114db69318
+size 114464
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spectral_py.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spectral_py.py
new file mode 100644
index 0000000000000000000000000000000000000000..47b1e4d7cfc869e0f931fb3b5fa462ee957056aa
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spectral_py.py
@@ -0,0 +1,2489 @@
+"""Tools for spectral analysis.
+"""
+import numpy as np
+import numpy.typing as npt
+from scipy import fft as sp_fft
+from scipy._lib.deprecation import _deprecate_positional_args, _NoValue
+from . import _signaltools
+from ._short_time_fft import ShortTimeFFT, FFT_MODE_TYPE
+from .windows import get_window
+from ._arraytools import const_ext, even_ext, odd_ext, zero_ext
+import warnings
+from typing import cast, Literal
+
+
+__all__ = ['periodogram', 'welch', 'lombscargle', 'csd', 'coherence',
+ 'spectrogram', 'stft', 'istft', 'check_COLA', 'check_NOLA']
+
+
+@_deprecate_positional_args(version="1.19.0")
+def lombscargle(
+ x: npt.ArrayLike,
+ y: npt.ArrayLike,
+ freqs: npt.ArrayLike,
+ *,
+ precenter: bool = _NoValue,
+ normalize: bool | Literal["power", "normalize", "amplitude"] = False,
+ weights: npt.NDArray | None = None,
+ floating_mean: bool = False,
+) -> npt.NDArray:
+ """
+ Compute the generalized Lomb-Scargle periodogram.
+
+ The Lomb-Scargle periodogram was developed by Lomb [1]_ and further
+ extended by Scargle [2]_ to find, and test the significance of weak
+ periodic signals with uneven temporal sampling. The algorithm used
+ here is based on a weighted least-squares fit of the form
+ ``y(ω) = a*cos(ω*x) + b*sin(ω*x) + c``, where the fit is calculated for
+ each frequency independently. This algorithm was developed by Zechmeister
+ and Kürster which improves the Lomb-Scargle periodogram by enabling
+ the weighting of individual samples and calculating an unknown y offset
+ (also called a "floating-mean" model) [3]_. For more details, and practical
+ considerations, see the excellent reference on the Lomb-Scargle periodogram [4]_.
+
+ When *normalize* is False (or "power") (default) the computed periodogram
+ is unnormalized, it takes the value ``(A**2) * N/4`` for a harmonic
+ signal with amplitude A for sufficiently large N. Where N is the length of x or y.
+
+ When *normalize* is True (or "normalize") the computed periodogram is normalized
+ by the residuals of the data around a constant reference model (at zero).
+
+ When *normalize* is "amplitude" the computed periodogram is the complex
+ representation of the amplitude and phase.
+
+ Input arrays should be 1-D of a real floating data type, which are converted into
+ float64 arrays before processing.
+
+ Parameters
+ ----------
+ x : array_like
+ Sample times.
+ y : array_like
+ Measurement values. Values are assumed to have a baseline of ``y = 0``. If
+ there is a possibility of a y offset, it is recommended to set `floating_mean`
+ to True.
+ freqs : array_like
+ Angular frequencies (e.g., having unit rad/s=2Ï€/s for `x` having unit s) for
+ output periodogram. Frequencies are normally >= 0, as any peak at ``-freq`` will
+ also exist at ``+freq``.
+ precenter : bool, optional
+ Pre-center measurement values by subtracting the mean, if True. This is
+ a legacy parameter and unnecessary if `floating_mean` is True.
+
+ .. deprecated:: 1.17.0
+ The `precenter` argument is deprecated and will be removed in SciPy 1.19.0.
+ The functionality can be substituted by passing ``y - y.mean()`` to `y`.
+
+ normalize : bool | str, optional
+ Compute normalized or complex (amplitude + phase) periodogram.
+ Valid options are: ``False``/``"power"``, ``True``/``"normalize"``, or
+ ``"amplitude"``.
+ weights : array_like, optional
+ Weights for each sample. Weights must be nonnegative.
+ floating_mean : bool, optional
+ Determines a y offset for each frequency independently, if True.
+ Else the y offset is assumed to be `0`.
+
+ Returns
+ -------
+ pgram : array_like
+ Lomb-Scargle periodogram.
+
+ Raises
+ ------
+ ValueError
+ If any of the input arrays x, y, freqs, or weights are not 1D, or if any are
+ zero length. Or, if the input arrays x, y, and weights do not have the same
+ shape as each other.
+ ValueError
+ If any weight is < 0, or the sum of the weights is <= 0.
+ ValueError
+ If the normalize parameter is not one of the allowed options.
+
+ See Also
+ --------
+ periodogram: Power spectral density using a periodogram
+ welch: Power spectral density by Welch's method
+ csd: Cross spectral density by Welch's method
+
+ Notes
+ -----
+ The algorithm used will not automatically account for any unknown y offset, unless
+ `floating_mean` is ``True``. Therefore, for most use cases, if there is a
+ possibility of a y offset, it is recommended to set `floating_mean` to ``True``.
+ Furthermore, `floating_mean` accounts for sample weights, and will also correct for
+ any bias due to consistently missing observations at peaks and/or troughs.
+
+ The legacy concept of "pre-centering" entails removing the mean from parameter `y`
+ before processing, i.e., passing ``y - y.mean()`` instead of setting the parameter
+ `floating_mean` to ``True``.
+
+ When the normalize parameter is "amplitude", for any frequency in freqs that is
+ below ``(2*pi)/(x.max() - x.min())``, the predicted amplitude will tend towards
+ infinity. The concept of a "Nyquist frequency" limit (see Nyquist-Shannon sampling
+ theorem) is not generally applicable to unevenly sampled data. Therefore, with
+ unevenly sampled data, valid frequencies in freqs can often be much higher than
+ expected for those familiar with methods like FFT.
+
+ References
+ ----------
+ .. [1] N.R. Lomb "Least-squares frequency analysis of unequally spaced
+ data", Astrophysics and Space Science, vol 39, pp. 447-462, 1976
+ :doi:`10.1007/bf00648343`
+
+ .. [2] J.D. Scargle "Studies in astronomical time series analysis. II -
+ Statistical aspects of spectral analysis of unevenly spaced data",
+ The Astrophysical Journal, vol 263, pp. 835-853, 1982
+ :doi:`10.1086/160554`
+
+ .. [3] M. Zechmeister and M. Kürster, "The generalised Lomb-Scargle periodogram.
+ A new formalism for the floating-mean and Keplerian periodograms,"
+ Astronomy and Astrophysics, vol. 496, pp. 577-584, 2009
+ :doi:`10.1051/0004-6361:200811296`
+
+ .. [4] J.T. VanderPlas, "Understanding the Lomb-Scargle Periodogram,"
+ The Astrophysical Journal Supplement Series, vol. 236, no. 1, p. 16,
+ May 2018
+ :doi:`10.3847/1538-4365/aab766`
+
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> rng = np.random.default_rng()
+
+ First define some input parameters for the signal:
+
+ >>> A = 2. # amplitude
+ >>> c = 2. # offset
+ >>> w0 = 1. # rad/sec
+ >>> nin = 150
+ >>> nout = 1002
+
+ Randomly generate sample times:
+
+ >>> x = rng.uniform(0, 10*np.pi, nin)
+
+ Plot a sine wave for the selected times:
+
+ >>> y = A * np.cos(w0*x) + c
+
+ Define the array of frequencies for which to compute the periodogram:
+
+ >>> w = np.linspace(0.25, 10, nout)
+
+ Calculate Lomb-Scargle periodogram for each of the normalize options:
+
+ >>> from scipy.signal import lombscargle
+ >>> pgram_power = lombscargle(x, y, w, normalize=False)
+ >>> pgram_norm = lombscargle(x, y, w, normalize=True)
+ >>> pgram_amp = lombscargle(x, y, w, normalize='amplitude')
+ ...
+ >>> pgram_power_f = lombscargle(x, y, w, normalize=False, floating_mean=True)
+ >>> pgram_norm_f = lombscargle(x, y, w, normalize=True, floating_mean=True)
+ >>> pgram_amp_f = lombscargle(x, y, w, normalize='amplitude', floating_mean=True)
+
+ Now make a plot of the input data:
+
+ >>> import matplotlib.pyplot as plt
+ >>> fig, (ax_t, ax_p, ax_n, ax_a) = plt.subplots(4, 1, figsize=(5, 6))
+ >>> ax_t.plot(x, y, 'b+')
+ >>> ax_t.set_xlabel('Time [s]')
+ >>> ax_t.set_ylabel('Amplitude')
+
+ Then plot the periodogram for each of the normalize options, as well as with and
+ without floating_mean=True:
+
+ >>> ax_p.plot(w, pgram_power, label='default')
+ >>> ax_p.plot(w, pgram_power_f, label='floating_mean=True')
+ >>> ax_p.set_xlabel('Angular frequency [rad/s]')
+ >>> ax_p.set_ylabel('Power')
+ >>> ax_p.legend(prop={'size': 7})
+ ...
+ >>> ax_n.plot(w, pgram_norm, label='default')
+ >>> ax_n.plot(w, pgram_norm_f, label='floating_mean=True')
+ >>> ax_n.set_xlabel('Angular frequency [rad/s]')
+ >>> ax_n.set_ylabel('Normalized')
+ >>> ax_n.legend(prop={'size': 7})
+ ...
+ >>> ax_a.plot(w, np.abs(pgram_amp), label='default')
+ >>> ax_a.plot(w, np.abs(pgram_amp_f), label='floating_mean=True')
+ >>> ax_a.set_xlabel('Angular frequency [rad/s]')
+ >>> ax_a.set_ylabel('Amplitude')
+ >>> ax_a.legend(prop={'size': 7})
+ ...
+ >>> plt.tight_layout()
+ >>> plt.show()
+
+ """
+
+ # if no weights are provided, assume all data points are equally important
+ if weights is None:
+ weights = np.ones_like(y, dtype=np.float64)
+ else:
+ # if provided, make sure weights is an array and cast to float64
+ weights = np.asarray(weights, dtype=np.float64)
+
+ # make sure other inputs are arrays and cast to float64
+ # done before validation, in case they were not arrays
+ x = np.asarray(x, dtype=np.float64)
+ y = np.asarray(y, dtype=np.float64)
+ freqs = np.asarray(freqs, dtype=np.float64)
+
+ # validate input shapes
+ if not (x.ndim == 1 and x.size > 0 and x.shape == y.shape == weights.shape):
+ raise ValueError("Parameters x, y, weights must be 1-D arrays of "
+ "equal non-zero length!")
+ if not (freqs.ndim == 1 and freqs.size > 0):
+ raise ValueError("Parameter freqs must be a 1-D array of non-zero length!")
+
+ # validate weights
+ if not (np.all(weights >= 0) and np.sum(weights) > 0):
+ raise ValueError("Parameter weights must have only non-negative entries "
+ "which sum to a positive value!")
+
+ # validate normalize parameter
+ if isinstance(normalize, bool):
+ # if bool, convert to str literal
+ normalize = "normalize" if normalize else "power"
+
+ if normalize not in ["power", "normalize", "amplitude"]:
+ raise ValueError(
+ "Normalize must be: False (or 'power'), True (or 'normalize'), "
+ "or 'amplitude'."
+ )
+
+ # weight vector must sum to 1
+ weights = weights * (1.0 / weights.sum())
+
+ # if requested, perform precenter
+ if precenter is not _NoValue:
+ msg = ("Use of parameter 'precenter' is deprecated as of SciPy 1.17.0 and "
+ "will be removed in 1.19.0. Please leave 'precenter' unspecified. "
+ "Passing True to 'precenter' "
+ "can be exactly substituted by passing 'y = (y - y.mean())' into "
+ "the input. Consider setting `floating_mean` to True instead.")
+ warnings.warn(msg, DeprecationWarning, stacklevel=2)
+ if precenter:
+ y = y - y.mean()
+
+ # transform arrays
+ # row vector
+ freqs = freqs.reshape(1, -1)
+ # column vectors
+ x = x.reshape(-1, 1)
+ y = y.reshape(-1, 1)
+ weights = weights.reshape(-1, 1)
+
+ # store frequent intermediates
+ weights_y = weights * y
+ freqst = freqs * x
+ coswt = np.cos(freqst)
+ sinwt = np.sin(freqst)
+
+ Y = np.dot(weights.T, y) # Eq. 7
+ CC = np.dot(weights.T, coswt * coswt) # Eq. 13
+ SS = 1.0 - CC # trig identity: S^2 = 1 - C^2 Eq.14
+ CS = np.dot(weights.T, coswt * sinwt) # Eq. 15
+
+ if floating_mean:
+ C = np.dot(weights.T, coswt) # Eq. 8
+ S = np.dot(weights.T, sinwt) # Eq. 9
+ CC -= C * C # Eq. 13
+ SS -= S * S # Eq. 14
+ CS -= C * S # Eq. 15
+
+ # calculate tau (phase offset to eliminate CS variable)
+ tau = 0.5 * np.arctan2(2.0 * CS, CC - SS) # Eq. 19
+ freqst_tau = freqst - tau
+
+ # coswt and sinwt are now offset by tau, which eliminates CS
+ coswt_tau = np.cos(freqst_tau)
+ sinwt_tau = np.sin(freqst_tau)
+
+ YC = np.dot(weights_y.T, coswt_tau) # Eq. 11
+ YS = np.dot(weights_y.T, sinwt_tau) # Eq. 12
+ CC = np.dot(weights.T, coswt_tau * coswt_tau) # Eq. 13, CC range is [0.5, 1.0]
+ SS = 1.0 - CC # trig identity: S^2 = 1 - C^2 Eq. 14, SS range is [0.0, 0.5]
+
+ if floating_mean:
+ C = np.dot(weights.T, coswt_tau) # Eq. 8
+ S = np.dot(weights.T, sinwt_tau) # Eq. 9
+ YC -= Y * C # Eq. 11
+ YS -= Y * S # Eq. 12
+ CC -= C * C # Eq. 13, CC range is now [0.0, 1.0]
+ SS -= S * S # Eq. 14, SS range is now [0.0, 0.5]
+
+ # to prevent division by zero errors with a and b, as well as correcting for
+ # numerical precision errors that lead to CC or SS being approximately -0.0,
+ # make sure CC and SS are both > 0
+ epsneg = np.finfo(dtype=y.dtype).epsneg
+ CC[CC < epsneg] = epsneg
+ SS[SS < epsneg] = epsneg
+
+ # calculate a and b
+ # where: y(w) = a*cos(w) + b*sin(w) + c
+ a = YC / CC # Eq. A.4 and 6, eliminating CS
+ b = YS / SS # Eq. A.4 and 6, eliminating CS
+ # c = Y - a * C - b * S
+
+ # store final value as power in A^2 (i.e., (y units)^2)
+ pgram = 2.0 * (a * YC + b * YS)
+
+ # squeeze back to a vector
+ pgram = np.squeeze(pgram)
+
+ if normalize == "power": # (default)
+ # return the legacy power units ((A**2) * N/4)
+
+ pgram *= float(x.shape[0]) / 4.0
+
+ elif normalize == "normalize":
+ # return the normalized power (power at current frequency wrt the entire signal)
+ # range will be [0, 1]
+
+ YY = np.dot(weights_y.T, y) # Eq. 10
+ if floating_mean:
+ YY -= Y * Y # Eq. 10
+
+ pgram *= 0.5 / np.squeeze(YY) # Eq. 20
+
+ else: # normalize == "amplitude":
+ # return the complex representation of the best-fit amplitude and phase
+
+ # squeeze back to vectors
+ a = np.squeeze(a)
+ b = np.squeeze(b)
+ tau = np.squeeze(tau)
+
+ # calculate the complex representation, and correct for tau rotation
+ pgram = (a + 1j * b) * np.exp(1j * tau)
+
+ return pgram
+
+
+def periodogram(x, fs=1.0, window='boxcar', nfft=None, detrend='constant',
+ return_onesided=True, scaling='density', axis=-1):
+ """
+ Estimate power spectral density using a periodogram.
+
+ Parameters
+ ----------
+ x : array_like
+ Time series of measurement values
+ fs : float, optional
+ Sampling frequency of the `x` time series. Defaults to 1.0.
+ window : str or tuple or array_like, optional
+ Desired window to use. If `window` is a string or tuple, it is
+ passed to `get_window` to generate the window values, which are
+ DFT-even by default. See `get_window` for a list of windows and
+ required parameters. If `window` is array_like it will be used
+ directly as the window and its length must be equal to the length
+ of the axis over which the periodogram is computed. Defaults
+ to 'boxcar'.
+ nfft : int, optional
+ Length of the FFT used. If `None` the length of `x` will be
+ used.
+ detrend : str or function or `False`, optional
+ Specifies how to detrend each segment. If `detrend` is a
+ string, it is passed as the `type` argument to the `detrend`
+ function. If it is a function, it takes a segment and returns a
+ detrended segment. If `detrend` is `False`, no detrending is
+ done. Defaults to 'constant'.
+ return_onesided : bool, optional
+ If `True`, return a one-sided spectrum for real data. If
+ `False` return a two-sided spectrum. Defaults to `True`, but for
+ complex data, a two-sided spectrum is always returned.
+ scaling : { 'density', 'spectrum' }, optional
+ Selects between computing the power spectral density ('density')
+ where `Pxx` has units of V²/Hz and computing the squared magnitude
+ spectrum ('spectrum') where `Pxx` has units of V², if `x`
+ is measured in V and `fs` is measured in Hz. Defaults to
+ 'density'
+ axis : int, optional
+ Axis along which the periodogram is computed; the default is
+ over the last axis (i.e. ``axis=-1``).
+
+ Returns
+ -------
+ f : ndarray
+ Array of sample frequencies.
+ Pxx : ndarray
+ Power spectral density or power spectrum of `x`.
+
+ See Also
+ --------
+ welch: Estimate power spectral density using Welch's method
+ lombscargle: Lomb-Scargle periodogram for unevenly sampled data
+
+ Notes
+ -----
+ The ratio of the squared magnitude (``scaling='spectrum'``) divided by the spectral
+ power density (``scaling='density'``) is the constant factor of
+ ``sum(abs(window)**2)*fs / abs(sum(window))**2``.
+ If `return_onesided` is ``True``, the values of the negative frequencies are added
+ to values of the corresponding positive ones.
+
+ Consult the :ref:`tutorial_SpectralAnalysis` section of the :ref:`user_guide`
+ for a discussion of the scalings of the power spectral density and
+ the magnitude (squared) spectrum.
+
+ .. versionadded:: 0.12.0
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+
+ Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by
+ 0.001 V**2/Hz of white noise sampled at 10 kHz.
+
+ >>> fs = 10e3
+ >>> N = 1e5
+ >>> amp = 2*np.sqrt(2)
+ >>> freq = 1234.0
+ >>> noise_power = 0.001 * fs / 2
+ >>> time = np.arange(N) / fs
+ >>> x = amp*np.sin(2*np.pi*freq*time)
+ >>> x += rng.normal(scale=np.sqrt(noise_power), size=time.shape)
+
+ Compute and plot the power spectral density.
+
+ >>> f, Pxx_den = signal.periodogram(x, fs)
+ >>> plt.semilogy(f, Pxx_den)
+ >>> plt.ylim([1e-7, 1e2])
+ >>> plt.xlabel('frequency [Hz]')
+ >>> plt.ylabel('PSD [V**2/Hz]')
+ >>> plt.show()
+
+ If we average the last half of the spectral density, to exclude the
+ peak, we can recover the noise power on the signal.
+
+ >>> np.mean(Pxx_den[25000:])
+ 0.000985320699252543
+
+ Now compute and plot the power spectrum.
+
+ >>> f, Pxx_spec = signal.periodogram(x, fs, 'flattop', scaling='spectrum')
+ >>> plt.figure()
+ >>> plt.semilogy(f, np.sqrt(Pxx_spec))
+ >>> plt.ylim([1e-4, 1e1])
+ >>> plt.xlabel('frequency [Hz]')
+ >>> plt.ylabel('Linear spectrum [V RMS]')
+ >>> plt.show()
+
+ The peak height in the power spectrum is an estimate of the RMS
+ amplitude.
+
+ >>> np.sqrt(Pxx_spec.max())
+ 2.0077340678640727
+
+ """
+ x = np.asarray(x)
+
+ if x.size == 0:
+ return np.empty(x.shape), np.empty(x.shape)
+
+ if window is None:
+ window = 'boxcar'
+
+ if nfft is None:
+ nperseg = x.shape[axis]
+ elif nfft == x.shape[axis]:
+ nperseg = nfft
+ elif nfft > x.shape[axis]:
+ nperseg = x.shape[axis]
+ elif nfft < x.shape[axis]:
+ s = [np.s_[:]]*len(x.shape)
+ s[axis] = np.s_[:nfft]
+ x = x[tuple(s)]
+ nperseg = nfft
+ nfft = None
+
+ if hasattr(window, 'size'):
+ if window.size != nperseg:
+ raise ValueError('the size of the window must be the same size '
+ 'of the input on the specified axis')
+
+ return welch(x, fs=fs, window=window, nperseg=nperseg, noverlap=0,
+ nfft=nfft, detrend=detrend, return_onesided=return_onesided,
+ scaling=scaling, axis=axis)
+
+
+def welch(x, fs=1.0, window='hann_periodic', nperseg=None, noverlap=None, nfft=None,
+ detrend='constant', return_onesided=True, scaling='density',
+ axis=-1, average='mean'):
+ r"""
+ Estimate power spectral density using Welch's method.
+
+ Welch's method [1]_ computes an estimate of the power spectral
+ density by dividing the data into overlapping segments, computing a
+ modified periodogram for each segment and averaging the
+ periodograms.
+
+ Parameters
+ ----------
+ x : array_like
+ Time series of measurement values
+ fs : float, optional
+ Sampling frequency of the `x` time series. Defaults to 1.0.
+ window : str or tuple or array_like, optional
+ Desired window to use. If `window` is a string or tuple, it is
+ passed to `get_window` to generate the window values, which are
+ DFT-even by default. See `get_window` for a list of windows and
+ required parameters. If `window` is array_like it will be used
+ directly as the window and its length must be nperseg. Defaults
+ to a periodic Hann window.
+ nperseg : int, optional
+ Length of each segment. Defaults to None, but if window is str or
+ tuple, is set to 256, and if window is array_like, is set to the
+ length of the window.
+ noverlap : int, optional
+ Number of points to overlap between segments. If `None`,
+ ``noverlap = nperseg // 2``. Defaults to `None`.
+ nfft : int, optional
+ Length of the FFT used, if a zero padded FFT is desired. If
+ `None`, the FFT length is `nperseg`. Defaults to `None`.
+ detrend : str or function or `False`, optional
+ Specifies how to detrend each segment. If `detrend` is a
+ string, it is passed as the `type` argument to the `detrend`
+ function. If it is a function, it takes a segment and returns a
+ detrended segment. If `detrend` is `False`, no detrending is
+ done. Defaults to 'constant'.
+ return_onesided : bool, optional
+ If `True`, return a one-sided spectrum for real data. If
+ `False` return a two-sided spectrum. Defaults to `True`, but for
+ complex data, a two-sided spectrum is always returned.
+ scaling : { 'density', 'spectrum' }, optional
+ Selects between computing the power spectral density ('density')
+ where `Pxx` has units of V**2/Hz and computing the squared magnitude
+ spectrum ('spectrum') where `Pxx` has units of V**2, if `x`
+ is measured in V and `fs` is measured in Hz. Defaults to
+ 'density'
+ axis : int, optional
+ Axis along which the periodogram is computed; the default is
+ over the last axis (i.e. ``axis=-1``).
+ average : { 'mean', 'median' }, optional
+ Method to use when averaging periodograms. Defaults to 'mean'.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ f : ndarray
+ Array of sample frequencies.
+ Pxx : ndarray
+ Power spectral density or power spectrum of x.
+
+ See Also
+ --------
+ csd: Cross power spectral density using Welch's method
+ periodogram: Simple, optionally modified periodogram
+ lombscargle: Lomb-Scargle periodogram for unevenly sampled data
+
+ Notes
+ -----
+ An appropriate amount of overlap will depend on the choice of window
+ and on your requirements. For the default Hann window an overlap of
+ 50% is a reasonable trade-off between accurately estimating the
+ signal power, while not over counting any of the data. Narrower
+ windows may require a larger overlap. If `noverlap` is 0, this
+ method is equivalent to Bartlett's method [2]_.
+
+ The ratio of the squared magnitude (``scaling='spectrum'``) divided by the spectral
+ power density (``scaling='density'``) is the constant factor of
+ ``sum(abs(window)**2)*fs / abs(sum(window))**2``.
+ If `return_onesided` is ``True``, the values of the negative frequencies are added
+ to values of the corresponding positive ones.
+
+ Consult the :ref:`tutorial_SpectralAnalysis` section of the :ref:`user_guide`
+ for a discussion of the scalings of the power spectral density and
+ the (squared) magnitude spectrum.
+
+ .. versionadded:: 0.12.0
+
+ References
+ ----------
+ .. [1] P. Welch, "The use of the fast Fourier transform for the
+ estimation of power spectra: A method based on time averaging
+ over short, modified periodograms", IEEE Trans. Audio
+ Electroacoust. vol. 15, pp. 70-73, 1967.
+ .. [2] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
+ Biometrika, vol. 37, pp. 1-16, 1950.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+
+ Generate a test signal, a 2 Vrms sine wave at 1234 Hz, corrupted by
+ 0.001 V**2/Hz of white noise sampled at 10 kHz.
+
+ >>> fs = 10e3
+ >>> N = 1e5
+ >>> amp = 2*np.sqrt(2)
+ >>> freq = 1234.0
+ >>> noise_power = 0.001 * fs / 2
+ >>> time = np.arange(N) / fs
+ >>> x = amp*np.sin(2*np.pi*freq*time)
+ >>> x += rng.normal(scale=np.sqrt(noise_power), size=time.shape)
+
+ Compute and plot the power spectral density.
+
+ >>> f, Pxx_den = signal.welch(x, fs, nperseg=1024)
+ >>> plt.semilogy(f, Pxx_den)
+ >>> plt.ylim([0.5e-3, 1])
+ >>> plt.xlabel('frequency [Hz]')
+ >>> plt.ylabel('PSD [V**2/Hz]')
+ >>> plt.show()
+
+ If we average the last half of the spectral density, to exclude the
+ peak, we can recover the noise power on the signal.
+
+ >>> np.mean(Pxx_den[256:])
+ 0.0009924865443739191
+
+ Now compute and plot the power spectrum.
+
+ >>> f, Pxx_spec = signal.welch(x, fs, 'flattop', 1024, scaling='spectrum')
+ >>> plt.figure()
+ >>> plt.semilogy(f, np.sqrt(Pxx_spec))
+ >>> plt.xlabel('frequency [Hz]')
+ >>> plt.ylabel('Linear spectrum [V RMS]')
+ >>> plt.show()
+
+ The peak height in the power spectrum is an estimate of the RMS
+ amplitude.
+
+ >>> np.sqrt(Pxx_spec.max())
+ 2.0077340678640727
+
+ If we now introduce a discontinuity in the signal, by increasing the
+ amplitude of a small portion of the signal by 50, we can see the
+ corruption of the mean average power spectral density, but using a
+ median average better estimates the normal behaviour.
+
+ >>> x[int(N//2):int(N//2)+10] *= 50.
+ >>> f, Pxx_den = signal.welch(x, fs, nperseg=1024)
+ >>> f_med, Pxx_den_med = signal.welch(x, fs, nperseg=1024, average='median')
+ >>> plt.semilogy(f, Pxx_den, label='mean')
+ >>> plt.semilogy(f_med, Pxx_den_med, label='median')
+ >>> plt.ylim([0.5e-3, 1])
+ >>> plt.xlabel('frequency [Hz]')
+ >>> plt.ylabel('PSD [V**2/Hz]')
+ >>> plt.legend()
+ >>> plt.show()
+
+ """
+ freqs, Pxx = csd(x, x, fs=fs, window=window, nperseg=nperseg,
+ noverlap=noverlap, nfft=nfft, detrend=detrend,
+ return_onesided=return_onesided, scaling=scaling,
+ axis=axis, average=average)
+
+ return freqs, Pxx.real
+
+
+def csd(x, y, fs=1.0, window='hann_periodic', nperseg=None, noverlap=None, nfft=None,
+ detrend='constant', return_onesided=True, scaling='density',
+ axis=-1, average='mean'):
+ r"""
+ Estimate the cross power spectral density, Pxy, using Welch's method.
+
+ Parameters
+ ----------
+ x : array_like
+ Time series of measurement values
+ y : array_like
+ Time series of measurement values
+ fs : float, optional
+ Sampling frequency of the `x` and `y` time series. Defaults
+ to 1.0.
+ window : str or tuple or array_like, optional
+ Desired window to use. If `window` is a string or tuple, it is
+ passed to `get_window` to generate the window values, which are
+ DFT-even by default. See `get_window` for a list of windows and
+ required parameters. If `window` is array_like it will be used
+ directly as the window and its length must be nperseg. Defaults
+ to a periodic Hann window.
+ nperseg : int, optional
+ Length of each segment. Defaults to None, but if window is str or
+ tuple, is set to 256, and if window is array_like, is set to the
+ length of the window.
+ noverlap: int, optional
+ Number of points to overlap between segments. If `None`,
+ ``noverlap = nperseg // 2``. Defaults to `None` and may
+ not be greater than `nperseg`.
+ nfft : int, optional
+ Length of the FFT used, if a zero padded FFT is desired. If
+ `None`, the FFT length is `nperseg`. Defaults to `None`.
+ detrend : str or function or `False`, optional
+ Specifies how to detrend each segment. If `detrend` is a
+ string, it is passed as the `type` argument to the `detrend`
+ function. If it is a function, it takes a segment and returns a
+ detrended segment. If `detrend` is `False`, no detrending is
+ done. Defaults to 'constant'.
+ return_onesided : bool, optional
+ If `True`, return a one-sided spectrum for real data. If
+ `False` return a two-sided spectrum. Defaults to `True`, but for
+ complex data, a two-sided spectrum is always returned.
+ scaling : { 'density', 'spectrum' }, optional
+ Selects between computing the cross spectral density ('density')
+ where `Pxy` has units of V**2/Hz and computing the cross spectrum
+ ('spectrum') where `Pxy` has units of V**2, if `x` and `y` are
+ measured in V and `fs` is measured in Hz. Defaults to 'density'
+ axis : int, optional
+ Axis along which the CSD is computed for both inputs; the
+ default is over the last axis (i.e. ``axis=-1``).
+ average : { 'mean', 'median' }, optional
+ Method to use when averaging periodograms. If the spectrum is
+ complex, the average is computed separately for the real and
+ imaginary parts. Defaults to 'mean'.
+
+ .. versionadded:: 1.2.0
+
+ Returns
+ -------
+ f : ndarray
+ Array of sample frequencies.
+ Pxy : ndarray
+ Cross spectral density or cross power spectrum of x,y.
+
+ See Also
+ --------
+ periodogram: Simple, optionally modified periodogram
+ lombscargle: Lomb-Scargle periodogram for unevenly sampled data
+ welch: Power spectral density by Welch's method. [Equivalent to
+ csd(x,x)]
+ coherence: Magnitude squared coherence by Welch's method.
+
+ Notes
+ -----
+ By convention, Pxy is computed with the conjugate FFT of X
+ multiplied by the FFT of Y.
+
+ If the input series differ in length, the shorter series will be
+ zero-padded to match.
+
+ An appropriate amount of overlap will depend on the choice of window
+ and on your requirements. For the default Hann window an overlap of
+ 50% is a reasonable trade-off between accurately estimating the
+ signal power, while not over counting any of the data. Narrower
+ windows may require a larger overlap.
+
+ The ratio of the cross spectrum (``scaling='spectrum'``) divided by the cross
+ spectral density (``scaling='density'``) is the constant factor of
+ ``sum(abs(window)**2)*fs / abs(sum(window))**2``.
+ If `return_onesided` is ``True``, the values of the negative frequencies are added
+ to values of the corresponding positive ones.
+
+ Consult the :ref:`tutorial_SpectralAnalysis` section of the :ref:`user_guide`
+ for a discussion of the scalings of a spectral density and an (amplitude) spectrum.
+
+ Welch's method may be interpreted as taking the average over the time slices of a
+ (cross-) spectrogram. Internally, this function utilizes the `ShortTimeFFT` to
+ determine the required (cross-) spectrogram. An example below illustrates that it
+ is straightforward to calculate `Pxy` directly with the `ShortTimeFFT`. However,
+ there are some notable differences in the behavior of the `ShortTimeFFT`:
+
+ * There is no direct `ShortTimeFFT` equivalent for the `csd` parameter
+ combination ``return_onesided=True, scaling='density'``, since
+ ``fft_mode='onesided2X'`` requires ``'psd'`` scaling. The is due to `csd`
+ returning the doubled squared magnitude in this case, which does not have a
+ sensible interpretation.
+ * `ShortTimeFFT` uses `float64` / `complex128` internally, which is due to the
+ behavior of the utilized `~scipy.fft` module. Thus, those are the dtypes being
+ returned. The `csd` function casts the return values to `float32` / `complex64`
+ if the input is `float32` / `complex64` as well.
+ * The `csd` function calculates ``np.conj(Sx[q,p]) * Sy[q,p]``, whereas
+ `~ShortTimeFFT.spectrogram` calculates ``Sx[q,p] * np.conj(Sy[q,p])`` where
+ ``Sx[q,p]``, ``Sy[q,p]`` are the STFTs of `x` and `y`. Also, the window
+ positioning is different.
+
+ .. versionadded:: 0.16.0
+
+ References
+ ----------
+ .. [1] P. Welch, "The use of the fast Fourier transform for the
+ estimation of power spectra: A method based on time averaging
+ over short, modified periodograms", IEEE Trans. Audio
+ Electroacoust. vol. 15, pp. 70-73, 1967.
+ .. [2] Rabiner, Lawrence R., and B. Gold. "Theory and Application of
+ Digital Signal Processing" Prentice-Hall, pp. 414-419, 1975
+
+ Examples
+ --------
+ The following example plots the cross power spectral density of two signals with
+ some common features:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+ ...
+ ... # Generate two test signals with some common features:
+ >>> N, fs = 100_000, 10e3 # number of samples and sampling frequency
+ >>> amp, freq = 20, 1234.0 # amplitude and frequency of utilized sine signal
+ >>> noise_power = 0.001 * fs / 2
+ >>> time = np.arange(N) / fs
+ >>> b, a = signal.butter(2, 0.25, 'low')
+ >>> x = rng.normal(scale=np.sqrt(noise_power), size=time.shape)
+ >>> y = signal.lfilter(b, a, x)
+ >>> x += amp*np.sin(2*np.pi*freq*time)
+ >>> y += rng.normal(scale=0.1*np.sqrt(noise_power), size=time.shape)
+ ...
+ ... # Compute and plot the magnitude of the cross spectral density:
+ >>> nperseg, noverlap, win = 1024, 512, 'hann'
+ >>> f, Pxy = signal.csd(x, y, fs, win, nperseg, noverlap)
+ >>> fig0, ax0 = plt.subplots(tight_layout=True)
+ >>> ax0.set_title(f"CSD ({win.title()}-window, {nperseg=}, {noverlap=})")
+ >>> ax0.set(xlabel="Frequency $f$ in kHz", ylabel="CSD Magnitude in V²/Hz")
+ >>> ax0.semilogy(f/1e3, np.abs(Pxy))
+ >>> ax0.grid()
+ >>> plt.show()
+
+ The cross spectral density is calculated by taking the average over the time slices
+ of a spectrogram:
+
+ >>> SFT = signal.ShortTimeFFT.from_window('hann', fs, nperseg, noverlap,
+ ... scale_to='psd', fft_mode='onesided2X',
+ ... phase_shift=None)
+ >>> Sxy1 = SFT.spectrogram(y, x, detr='constant', k_offset=nperseg//2,
+ ... p0=0, p1=(N-noverlap) // SFT.hop)
+ >>> Pxy1 = Sxy1.mean(axis=-1)
+ >>> np.allclose(Pxy, Pxy1) # same result as with csd()
+ True
+
+ As discussed in the Notes section, the results of using an approach analogous to
+ the code snippet above and the `csd` function may deviate due to implementation
+ details.
+
+ Note that the code snippet above can be easily adapted to determine other
+ statistical properties than the mean value.
+ """
+ # The following lines are resembling the behavior of the originally utilized
+ # `_spectral_helper()` function:
+ same_data, axis = y is x, int(axis)
+ x = np.asarray(x)
+
+ if not same_data:
+ y = np.asarray(y)
+ # Check if we can broadcast the outer axes together
+ x_outer, y_outer = list(x.shape), list(y.shape)
+ x_outer.pop(axis)
+ y_outer.pop(axis)
+ try:
+ outer_shape = np.broadcast_shapes(x_outer, y_outer)
+ except ValueError as e:
+ raise ValueError('x and y cannot be broadcast together.') from e
+ if x.size == 0 or y.size == 0:
+ out_shape = outer_shape + (min([x.shape[axis], y.shape[axis]]),)
+ empty_out = np.moveaxis(np.empty(out_shape), -1, axis)
+ return empty_out, empty_out
+ out_dtype = np.result_type(x, y, np.complex64)
+ else: # x is y:
+ if x.size == 0:
+ return np.empty(x.shape), np.empty(x.shape)
+ out_dtype = np.result_type(x, np.complex64)
+
+ n = x.shape[axis] if same_data else max(x.shape[axis], y.shape[axis])
+ if isinstance(window, str) or isinstance(window, tuple):
+ nperseg = int(nperseg) if nperseg is not None else 256
+ if nperseg < 1:
+ raise ValueError(f"Parameter {nperseg=} is not a positive integer!")
+ elif n < nperseg:
+ warnings.warn(f"{nperseg=} is greater than signal length max(len(x), " +
+ f"len(y)) = {n}, using nperseg = {n}", stacklevel=3)
+ nperseg = n
+ win = get_window(window, nperseg)
+ else:
+ win = np.asarray(window)
+ if nperseg is None:
+ nperseg = len(win)
+ if nperseg != len(win):
+ raise ValueError(f"{nperseg=} does not equal {len(win)=}")
+
+ nfft = int(nfft) if nfft is not None else nperseg
+ if nfft < nperseg:
+ raise ValueError(f"{nfft=} must be greater than or equal to {nperseg=}!")
+ noverlap = int(noverlap) if noverlap is not None else nperseg // 2
+ if noverlap >= nperseg:
+ raise ValueError(f"{noverlap=} must be less than {nperseg=}!")
+ if np.iscomplexobj(x) and return_onesided:
+ return_onesided = False
+
+ if x.shape[axis] < y.shape[axis]: # zero-pad x to shape of y:
+ z_shape = list(y.shape)
+ z_shape[axis] = y.shape[axis] - x.shape[axis]
+ x = np.concatenate((x, np.zeros(z_shape)), axis=axis)
+ elif y.shape[axis] < x.shape[axis]: # zero-pad y to shape of x:
+ z_shape = list(x.shape)
+ z_shape[axis] = x.shape[axis] - y.shape[axis]
+ y = np.concatenate((y, np.zeros(z_shape)), axis=axis)
+
+ # using cast() to make mypy happy:
+ fft_mode = cast(FFT_MODE_TYPE, 'onesided' if return_onesided else 'twosided')
+ if scaling not in (scales := {'spectrum': 'magnitude', 'density': 'psd'}):
+ raise ValueError(f"Parameter {scaling=} not in {scales}!")
+
+ SFT = ShortTimeFFT(win, nperseg - noverlap, fs, fft_mode=fft_mode, mfft=nfft,
+ scale_to=scales[scaling], phase_shift=None)
+ # csd() calculates X.conj()*Y instead of X*Y.conj():
+ Pxy = SFT.spectrogram(y, x, detr=None if detrend is False else detrend,
+ p0=0, p1=(n - noverlap) // SFT.hop, k_offset=nperseg // 2,
+ axis=axis)
+
+ # Note:
+ # 'onesided2X' scaling of ShortTimeFFT conflicts with the
+ # scaling='spectrum' parameter, since it doubles the squared magnitude,
+ # which in the view of the ShortTimeFFT implementation does not make sense.
+ # Hence, the doubling of the square is implemented here:
+ if return_onesided:
+ f_axis = Pxy.ndim - 1 + axis if axis < 0 else axis
+ Pxy = np.moveaxis(Pxy, f_axis, -1)
+ Pxy[..., 1:-1 if SFT.mfft % 2 == 0 else None] *= 2
+ Pxy = np.moveaxis(Pxy, -1, f_axis)
+
+ # Average over windows.
+ if Pxy.shape[-1] > 1:
+ if average == 'median':
+ # np.median must be passed real arrays for the desired result
+ bias = _median_bias(Pxy.shape[-1])
+ if np.iscomplexobj(Pxy):
+ Pxy = (np.median(np.real(Pxy), axis=-1) +
+ np.median(np.imag(Pxy), axis=-1) * 1j)
+ else:
+ Pxy = np.median(Pxy, axis=-1)
+ Pxy /= bias
+ elif average == 'mean':
+ Pxy = Pxy.mean(axis=-1)
+ else:
+ raise ValueError(f"Parameter {average=} must be 'median' or 'mean'!")
+ else:
+ Pxy = np.reshape(Pxy, Pxy.shape[:-1])
+
+ # cast output type;
+ Pxy = Pxy.astype(out_dtype)
+ if same_data:
+ Pxy = Pxy.real
+ return SFT.f, Pxy
+
+
+def spectrogram(x, fs=1.0, window=('tukey_periodic', .25), nperseg=None, noverlap=None,
+ nfft=None, detrend='constant', return_onesided=True,
+ scaling='density', axis=-1, mode='psd'):
+ """Compute a spectrogram with consecutive Fourier transforms (legacy function).
+
+ Spectrograms can be used as a way of visualizing the change of a
+ nonstationary signal's frequency content over time.
+
+ .. legacy:: function
+
+ :class:`ShortTimeFFT` is a newer STFT / ISTFT implementation with more
+ features also including a :meth:`~ShortTimeFFT.spectrogram` method.
+ A :ref:`comparison ` between the
+ implementations can be found in the :ref:`tutorial_stft` section of
+ the :ref:`user_guide`.
+
+ Parameters
+ ----------
+ x : array_like
+ Time series of measurement values
+ fs : float, optional
+ Sampling frequency of the `x` time series. Defaults to 1.0.
+ window : str or tuple or array_like, optional
+ Desired window to use. If `window` is a string or tuple, it is
+ passed to `get_window` to generate the window values, which are
+ DFT-even by default. See `get_window` for a list of windows and
+ required parameters. If `window` is array_like it will be used
+ directly as the window and its length must be nperseg.
+ Defaults to a periodic Tukey window with shape parameter of 0.25.
+ nperseg : int, optional
+ Length of each segment. Defaults to None, but if window is str or
+ tuple, is set to 256, and if window is array_like, is set to the
+ length of the window.
+ noverlap : int, optional
+ Number of points to overlap between segments. If `None`,
+ ``noverlap = nperseg // 8``. Defaults to `None`.
+ nfft : int, optional
+ Length of the FFT used, if a zero padded FFT is desired. If
+ `None`, the FFT length is `nperseg`. Defaults to `None`.
+ detrend : str or function or `False`, optional
+ Specifies how to detrend each segment. If `detrend` is a
+ string, it is passed as the `type` argument to the `detrend`
+ function. If it is a function, it takes a segment and returns a
+ detrended segment. If `detrend` is `False`, no detrending is
+ done. Defaults to 'constant'.
+ return_onesided : bool, optional
+ If `True`, return a one-sided spectrum for real data. If
+ `False` return a two-sided spectrum. Defaults to `True`, but for
+ complex data, a two-sided spectrum is always returned.
+ scaling : { 'density', 'spectrum' }, optional
+ Selects between computing the power spectral density ('density')
+ where `Sxx` has units of V**2/Hz and computing the power
+ spectrum ('spectrum') where `Sxx` has units of V**2, if `x`
+ is measured in V and `fs` is measured in Hz. Defaults to
+ 'density'.
+ axis : int, optional
+ Axis along which the spectrogram is computed; the default is over
+ the last axis (i.e. ``axis=-1``).
+ mode : str, optional
+ Defines what kind of return values are expected. Options are
+ ['psd', 'complex', 'magnitude', 'angle', 'phase']. 'complex' is
+ equivalent to the output of `stft` with no padding or boundary
+ extension. 'magnitude' returns the absolute magnitude of the
+ STFT. 'angle' and 'phase' return the complex angle of the STFT,
+ with and without unwrapping, respectively.
+
+ Returns
+ -------
+ f : ndarray
+ Array of sample frequencies.
+ t : ndarray
+ Array of segment times.
+ Sxx : ndarray
+ Spectrogram of x. By default, the last axis of Sxx corresponds
+ to the segment times.
+
+ See Also
+ --------
+ periodogram: Simple, optionally modified periodogram
+ lombscargle: Lomb-Scargle periodogram for unevenly sampled data
+ welch: Power spectral density by Welch's method.
+ csd: Cross spectral density by Welch's method.
+ ShortTimeFFT: Newer STFT/ISTFT implementation providing more features,
+ which also includes a :meth:`~ShortTimeFFT.spectrogram`
+ method.
+
+ Notes
+ -----
+ An appropriate amount of overlap will depend on the choice of window
+ and on your requirements. In contrast to welch's method, where the
+ entire data stream is averaged over, one may wish to use a smaller
+ overlap (or perhaps none at all) when computing a spectrogram, to
+ maintain some statistical independence between individual segments.
+ It is for this reason that the default window is a Tukey window with
+ 1/8th of a window's length overlap at each end.
+
+
+ .. versionadded:: 0.16.0
+
+ References
+ ----------
+ .. [1] Oppenheim, Alan V., Ronald W. Schafer, John R. Buck
+ "Discrete-Time Signal Processing", Prentice Hall, 1999.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fftshift
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+
+ Generate a test signal, a 2 Vrms sine wave whose frequency is slowly
+ modulated around 3kHz, corrupted by white noise of exponentially
+ decreasing magnitude sampled at 10 kHz.
+
+ >>> fs = 10e3
+ >>> N = 1e5
+ >>> amp = 2 * np.sqrt(2)
+ >>> noise_power = 0.01 * fs / 2
+ >>> time = np.arange(N) / float(fs)
+ >>> mod = 500*np.cos(2*np.pi*0.25*time)
+ >>> carrier = amp * np.sin(2*np.pi*3e3*time + mod)
+ >>> noise = rng.normal(scale=np.sqrt(noise_power), size=time.shape)
+ >>> noise *= np.exp(-time/5)
+ >>> x = carrier + noise
+
+ Compute and plot the spectrogram.
+
+ >>> f, t, Sxx = signal.spectrogram(x, fs)
+ >>> plt.pcolormesh(t, f, Sxx, shading='gouraud')
+ >>> plt.ylabel('Frequency [Hz]')
+ >>> plt.xlabel('Time [sec]')
+ >>> plt.show()
+
+ Note, if using output that is not one sided, then use the following:
+
+ >>> f, t, Sxx = signal.spectrogram(x, fs, return_onesided=False)
+ >>> plt.pcolormesh(t, fftshift(f), fftshift(Sxx, axes=0), shading='gouraud')
+ >>> plt.ylabel('Frequency [Hz]')
+ >>> plt.xlabel('Time [sec]')
+ >>> plt.show()
+
+ """
+ modelist = ['psd', 'complex', 'magnitude', 'angle', 'phase']
+ if mode not in modelist:
+ raise ValueError(f'unknown value for mode {mode}, must be one of {modelist}')
+
+ # need to set default for nperseg before setting default for noverlap below
+ window, nperseg = _triage_segments(window, nperseg,
+ input_length=x.shape[axis])
+
+ # Less overlap than welch, so samples are more statistically independent
+ if noverlap is None:
+ noverlap = nperseg // 8
+
+ if mode == 'psd':
+ freqs, time, Sxx = _spectral_helper(x, x, fs, window, nperseg,
+ noverlap, nfft, detrend,
+ return_onesided, scaling, axis,
+ mode='psd')
+
+ else:
+ freqs, time, Sxx = _spectral_helper(x, x, fs, window, nperseg,
+ noverlap, nfft, detrend,
+ return_onesided, scaling, axis,
+ mode='stft')
+
+ if mode == 'magnitude':
+ Sxx = np.abs(Sxx)
+ elif mode in ['angle', 'phase']:
+ Sxx = np.angle(Sxx)
+ if mode == 'phase':
+ # Sxx has one additional dimension for time strides
+ if axis < 0:
+ axis -= 1
+ Sxx = np.unwrap(Sxx, axis=axis)
+
+ # mode =='complex' is same as `stft`, doesn't need modification
+
+ return freqs, time, Sxx
+
+
+def check_COLA(window, nperseg, noverlap, tol=1e-10):
+ r"""Check whether the Constant OverLap Add (COLA) constraint is met
+ (legacy function).
+
+ .. legacy:: function
+
+ The COLA constraint is equivalent of having a constant dual window, i.e.,
+ ``all(ShortTimeFFT.dual_win == ShortTimeFFT.dual_win[0])``. Hence,
+ `closest_STFT_dual_window` generalizes this function, as the following
+ example shows:
+
+ >>> import numpy as np
+ >>> from scipy.signal import check_COLA, closest_STFT_dual_window, windows
+ ...
+ >>> w, w_rect, hop = windows.hann(12, sym=False), np.ones(12), 6
+ >>> dual_win, alpha = closest_STFT_dual_window(w, hop, w_rect, scaled=True)
+ >>> np.allclose(dual_win/alpha, w_rect, atol=1e-10, rtol=0)
+ True
+ >>> check_COLA(w, len(w), len(w) - hop) # equivalent legacy function call
+ True
+
+
+ Parameters
+ ----------
+ window : str or tuple or array_like
+ Desired window to use. If `window` is a string or tuple, it is
+ passed to `get_window` to generate the window values, which are
+ DFT-even by default. See `get_window` for a list of windows and
+ required parameters. If `window` is array_like it will be used
+ directly as the window and its length must be nperseg.
+ nperseg : int
+ Length of each segment.
+ noverlap : int
+ Number of points to overlap between segments.
+ tol : float, optional
+ The allowed variance of a bin's weighted sum from the median bin
+ sum.
+
+ Returns
+ -------
+ verdict : bool
+ `True` if chosen combination satisfies COLA within `tol`,
+ `False` otherwise
+
+ See Also
+ --------
+ closest_STFT_dual_window: Allows determining the closest window meeting the
+ COLA constraint for a given window
+ check_NOLA: Check whether the Nonzero Overlap Add (NOLA) constraint is met
+ ShortTimeFFT: Provide short-time Fourier transform and its inverse
+ stft: Short-time Fourier transform (legacy)
+ istft: Inverse Short-time Fourier transform (legacy)
+
+ Notes
+ -----
+ In order to invert a short-time Fourier transfrom (STFT) with the so-called
+ "overlap-add method", the signal windowing must obey the constraint of
+ "Constant OverLap Add" (COLA). This ensures that every point in the input
+ data is equally weighted, thereby avoiding aliasing and allowing full
+ reconstruction. Note that the algorithms implemented in `ShortTimeFFT.istft`
+ and in `istft` (legacy) only require that the weaker "nonzero overlap-add"
+ condition (as in `check_NOLA`) is met.
+
+ Some examples of windows that satisfy COLA:
+ - Rectangular window at overlap of 0, 1/2, 2/3, 3/4, ...
+ - Bartlett window at overlap of 1/2, 3/4, 5/6, ...
+ - Hann window at 1/2, 2/3, 3/4, ...
+ - Any Blackman family window at 2/3 overlap
+ - Any window with ``noverlap = nperseg-1``
+
+ A very comprehensive list of other windows may be found in [2]_,
+ wherein the COLA condition is satisfied when the "Amplitude
+ Flatness" is unity.
+
+ .. versionadded:: 0.19.0
+
+ References
+ ----------
+ .. [1] Julius O. Smith III, "Spectral Audio Signal Processing", W3K
+ Publishing, 2011,ISBN 978-0-9745607-3-1.
+ .. [2] G. Heinzel, A. Ruediger and R. Schilling, "Spectrum and
+ spectral density estimation by the Discrete Fourier transform
+ (DFT), including a comprehensive list of window functions and
+ some new at-top windows", 2002,
+ http://hdl.handle.net/11858/00-001M-0000-0013-557A-5
+
+ Examples
+ --------
+ >>> from scipy import signal
+
+ Confirm COLA condition for rectangular window of 75% (3/4) overlap:
+
+ >>> signal.check_COLA(signal.windows.boxcar(100), 100, 75)
+ True
+
+ COLA is not true for 25% (1/4) overlap, though:
+
+ >>> signal.check_COLA(signal.windows.boxcar(100), 100, 25)
+ False
+
+ "Symmetrical" Hann window (for filter design) is not COLA:
+
+ >>> signal.check_COLA(signal.windows.hann(120, sym=True), 120, 60)
+ False
+
+ "Periodic" or "DFT-even" Hann window (for FFT analysis) is COLA for
+ overlap of 1/2, 2/3, 3/4, etc.:
+
+ >>> signal.check_COLA(signal.windows.hann(120, sym=False), 120, 60)
+ True
+
+ >>> signal.check_COLA(signal.windows.hann(120, sym=False), 120, 80)
+ True
+
+ >>> signal.check_COLA(signal.windows.hann(120, sym=False), 120, 90)
+ True
+
+ """
+ nperseg = int(nperseg)
+
+ if nperseg < 1:
+ raise ValueError('nperseg must be a positive integer')
+
+ if noverlap >= nperseg:
+ raise ValueError('noverlap must be less than nperseg.')
+ noverlap = int(noverlap)
+
+ if isinstance(window, str) or type(window) is tuple:
+ win = get_window(window, nperseg)
+ else:
+ win = np.asarray(window)
+ if len(win.shape) != 1:
+ raise ValueError('window must be 1-D')
+ if win.shape[0] != nperseg:
+ raise ValueError('window must have length of nperseg')
+
+ step = nperseg - noverlap
+ binsums = sum(win[ii*step:(ii+1)*step] for ii in range(nperseg//step))
+
+ if nperseg % step != 0:
+ binsums[:nperseg % step] += win[-(nperseg % step):]
+
+ deviation = binsums - np.median(binsums)
+ return np.max(np.abs(deviation)) < tol
+
+
+def check_NOLA(window, nperseg, noverlap, tol=1e-10):
+ r"""Check whether the Nonzero Overlap Add (NOLA) constraint is met.
+
+ Parameters
+ ----------
+ window : str or tuple or array_like
+ Desired window to use. If `window` is a string or tuple, it is
+ passed to `get_window` to generate the window values, which are
+ DFT-even by default. See `get_window` for a list of windows and
+ required parameters. If `window` is array_like it will be used
+ directly as the window and its length must be nperseg.
+ nperseg : int
+ Length of each segment.
+ noverlap : int
+ Number of points to overlap between segments.
+ tol : float, optional
+ The allowed variance of a bin's weighted sum from the median bin
+ sum.
+
+ Returns
+ -------
+ verdict : bool
+ `True` if chosen combination satisfies the NOLA constraint within
+ `tol`, `False` otherwise
+
+ See Also
+ --------
+ check_COLA: Check whether the Constant OverLap Add (COLA) constraint is met
+ stft: Short Time Fourier Transform
+ istft: Inverse Short Time Fourier Transform
+
+ Notes
+ -----
+ In order to enable inversion of an STFT via the inverse STFT in
+ `istft`, the signal windowing must obey the constraint of "nonzero
+ overlap add" (NOLA):
+
+ .. math:: \sum_{t}w^{2}[n-tH] \ne 0
+
+ for all :math:`n`, where :math:`w` is the window function, :math:`t` is the
+ frame index, and :math:`H` is the hop size (:math:`H` = `nperseg` -
+ `noverlap`).
+
+ This ensures that the normalization factors in the denominator of the
+ overlap-add inversion equation are not zero. Only very pathological windows
+ will fail the NOLA constraint.
+
+ .. versionadded:: 1.2.0
+
+ References
+ ----------
+ .. [1] Julius O. Smith III, "Spectral Audio Signal Processing", W3K
+ Publishing, 2011,ISBN 978-0-9745607-3-1.
+ .. [2] G. Heinzel, A. Ruediger and R. Schilling, "Spectrum and
+ spectral density estimation by the Discrete Fourier transform
+ (DFT), including a comprehensive list of window functions and
+ some new at-top windows", 2002,
+ http://hdl.handle.net/11858/00-001M-0000-0013-557A-5
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+
+ Confirm NOLA condition for rectangular window of 75% (3/4) overlap:
+
+ >>> signal.check_NOLA(signal.windows.boxcar(100), 100, 75)
+ True
+
+ NOLA is also true for 25% (1/4) overlap:
+
+ >>> signal.check_NOLA(signal.windows.boxcar(100), 100, 25)
+ True
+
+ "Symmetrical" Hann window (for filter design) is also NOLA:
+
+ >>> signal.check_NOLA(signal.windows.hann(120, sym=True), 120, 60)
+ True
+
+ As long as there is overlap, it takes quite a pathological window to fail
+ NOLA:
+
+ >>> w = np.ones(64, dtype="float")
+ >>> w[::2] = 0
+ >>> signal.check_NOLA(w, 64, 32)
+ False
+
+ If there is not enough overlap, a window with zeros at the ends will not
+ work:
+
+ >>> signal.check_NOLA(signal.windows.hann(64), 64, 0)
+ False
+ >>> signal.check_NOLA(signal.windows.hann(64), 64, 1)
+ False
+ >>> signal.check_NOLA(signal.windows.hann(64), 64, 2)
+ True
+
+ """
+ nperseg = int(nperseg)
+
+ if nperseg < 1:
+ raise ValueError('nperseg must be a positive integer')
+
+ if noverlap >= nperseg:
+ raise ValueError('noverlap must be less than nperseg')
+ if noverlap < 0:
+ raise ValueError('noverlap must be a nonnegative integer')
+ noverlap = int(noverlap)
+
+ if isinstance(window, str) or type(window) is tuple:
+ win = get_window(window, nperseg)
+ else:
+ win = np.asarray(window)
+ if len(win.shape) != 1:
+ raise ValueError('window must be 1-D')
+ if win.shape[0] != nperseg:
+ raise ValueError('window must have length of nperseg')
+
+ step = nperseg - noverlap
+ binsums = sum(win[ii*step:(ii+1)*step]**2 for ii in range(nperseg//step))
+
+ if nperseg % step != 0:
+ binsums[:nperseg % step] += win[-(nperseg % step):]**2
+
+ return np.min(binsums) > tol
+
+
+def stft(x, fs=1.0, window='hann_periodic', nperseg=256, noverlap=None, nfft=None,
+ detrend=False, return_onesided=True, boundary='zeros', padded=True,
+ axis=-1, scaling='spectrum'):
+ r"""Compute the Short Time Fourier Transform (legacy function).
+
+ STFTs can be used as a way of quantifying the change of a
+ nonstationary signal's frequency and phase content over time.
+
+ .. legacy:: function
+
+ `ShortTimeFFT` is a newer STFT / ISTFT implementation with more
+ features. A :ref:`comparison ` between the
+ implementations can be found in the :ref:`tutorial_stft` section of the
+ :ref:`user_guide`.
+
+ Parameters
+ ----------
+ x : array_like
+ Time series of measurement values
+ fs : float, optional
+ Sampling frequency of the `x` time series. Defaults to 1.0.
+ window : str or tuple or array_like, optional
+ Desired window to use. If `window` is a string or tuple, it is
+ passed to `get_window` to generate the window values, which are
+ DFT-even by default. See `get_window` for a list of windows and
+ required parameters. If `window` is array_like it will be used
+ directly as the window and its length must be nperseg. Defaults
+ to a periodic Hann window.
+ nperseg : int, optional
+ Length of each segment. Defaults to 256.
+ noverlap : int, optional
+ Number of points to overlap between segments. If `None`,
+ ``noverlap = nperseg // 2``. Defaults to `None`. When
+ specified, the COLA constraint must be met (see Notes below).
+ nfft : int, optional
+ Length of the FFT used, if a zero padded FFT is desired. If
+ `None`, the FFT length is `nperseg`. Defaults to `None`.
+ detrend : str or function or `False`, optional
+ Specifies how to detrend each segment. If `detrend` is a
+ string, it is passed as the `type` argument to the `detrend`
+ function. If it is a function, it takes a segment and returns a
+ detrended segment. If `detrend` is `False`, no detrending is
+ done. Defaults to `False`.
+ return_onesided : bool, optional
+ If `True`, return a one-sided spectrum for real data. If
+ `False` return a two-sided spectrum. Defaults to `True`, but for
+ complex data, a two-sided spectrum is always returned.
+ boundary : str or None, optional
+ Specifies whether the input signal is extended at both ends, and
+ how to generate the new values, in order to center the first
+ windowed segment on the first input point. This has the benefit
+ of enabling reconstruction of the first input point when the
+ employed window function starts at zero. Valid options are
+ ``['even', 'odd', 'constant', 'zeros', None]``. Defaults to
+ 'zeros', for zero padding extension. I.e. ``[1, 2, 3, 4]`` is
+ extended to ``[0, 1, 2, 3, 4, 0]`` for ``nperseg=3``.
+ padded : bool, optional
+ Specifies whether the input signal is zero-padded at the end to
+ make the signal fit exactly into an integer number of window
+ segments, so that all of the signal is included in the output.
+ Defaults to `True`. Padding occurs after boundary extension, if
+ `boundary` is not `None`, and `padded` is `True`, as is the
+ default.
+ axis : int, optional
+ Axis along which the STFT is computed; the default is over the
+ last axis (i.e. ``axis=-1``).
+ scaling: {'spectrum', 'psd'}
+ The default 'spectrum' scaling allows each frequency line of `Zxx` to
+ be interpreted as a magnitude spectrum. The 'psd' option scales each
+ line to a power spectral density - it allows to calculate the signal's
+ energy by numerically integrating over ``abs(Zxx)**2``.
+
+ .. versionadded:: 1.9.0
+
+ Returns
+ -------
+ f : ndarray
+ Array of sample frequencies.
+ t : ndarray
+ Array of segment times.
+ Zxx : ndarray
+ STFT of `x`. By default, the last axis of `Zxx` corresponds
+ to the segment times.
+
+ See Also
+ --------
+ istft: Inverse Short Time Fourier Transform
+ ShortTimeFFT: Newer STFT/ISTFT implementation providing more features.
+ check_COLA: Check whether the Constant OverLap Add (COLA) constraint
+ is met
+ check_NOLA: Check whether the Nonzero Overlap Add (NOLA) constraint is met
+ welch: Power spectral density by Welch's method.
+ spectrogram: Spectrogram by Welch's method.
+ csd: Cross spectral density by Welch's method.
+ lombscargle: Lomb-Scargle periodogram for unevenly sampled data
+
+ Notes
+ -----
+ In order to enable inversion of an STFT via the inverse STFT in
+ `istft`, the signal windowing must obey the constraint of "Nonzero
+ OverLap Add" (NOLA), and the input signal must have complete
+ windowing coverage (i.e. ``(x.shape[axis] - nperseg) %
+ (nperseg-noverlap) == 0``). The `padded` argument may be used to
+ accomplish this.
+
+ Given a time-domain signal :math:`x[n]`, a window :math:`w[n]`, and a hop
+ size :math:`H` = `nperseg - noverlap`, the windowed frame at time index
+ :math:`t` is given by
+
+ .. math:: x_{t}[n]=x[n]w[n-tH]
+
+ The overlap-add (OLA) reconstruction equation is given by
+
+ .. math:: x[n]=\frac{\sum_{t}x_{t}[n]w[n-tH]}{\sum_{t}w^{2}[n-tH]}
+
+ The NOLA constraint ensures that every normalization term that appears
+ in the denominator of the OLA reconstruction equation is nonzero. Whether a
+ choice of `window`, `nperseg`, and `noverlap` satisfy this constraint can
+ be tested with `check_NOLA`.
+
+
+ .. versionadded:: 0.19.0
+
+ References
+ ----------
+ .. [1] Oppenheim, Alan V., Ronald W. Schafer, John R. Buck
+ "Discrete-Time Signal Processing", Prentice Hall, 1999.
+ .. [2] Daniel W. Griffin, Jae S. Lim "Signal Estimation from
+ Modified Short-Time Fourier Transform", IEEE 1984,
+ 10.1109/TASSP.1984.1164317
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+
+ Generate a test signal, a 2 Vrms sine wave whose frequency is slowly
+ modulated around 3kHz, corrupted by white noise of exponentially
+ decreasing magnitude sampled at 10 kHz.
+
+ >>> fs = 10e3
+ >>> N = 1e5
+ >>> amp = 2 * np.sqrt(2)
+ >>> noise_power = 0.01 * fs / 2
+ >>> time = np.arange(N) / float(fs)
+ >>> mod = 500*np.cos(2*np.pi*0.25*time)
+ >>> carrier = amp * np.sin(2*np.pi*3e3*time + mod)
+ >>> noise = rng.normal(scale=np.sqrt(noise_power),
+ ... size=time.shape)
+ >>> noise *= np.exp(-time/5)
+ >>> x = carrier + noise
+
+ Compute and plot the STFT's magnitude.
+
+ >>> f, t, Zxx = signal.stft(x, fs, nperseg=1000)
+ >>> plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp, shading='gouraud')
+ >>> plt.title('STFT Magnitude')
+ >>> plt.ylabel('Frequency [Hz]')
+ >>> plt.xlabel('Time [sec]')
+ >>> plt.show()
+
+ Compare the energy of the signal `x` with the energy of its STFT:
+
+ >>> E_x = sum(x**2) / fs # Energy of x
+ >>> # Calculate a two-sided STFT with PSD scaling:
+ >>> f, t, Zxx = signal.stft(x, fs, nperseg=1000, return_onesided=False,
+ ... scaling='psd')
+ >>> # Integrate numerically over abs(Zxx)**2:
+ >>> df, dt = f[1] - f[0], t[1] - t[0]
+ >>> E_Zxx = sum(np.sum(Zxx.real**2 + Zxx.imag**2, axis=0) * df) * dt
+ >>> # The energy is the same, but the numerical errors are quite large:
+ >>> np.isclose(E_x, E_Zxx, rtol=1e-2)
+ True
+
+ """
+ if scaling == 'psd':
+ scaling = 'density'
+ elif scaling != 'spectrum':
+ raise ValueError(f"Parameter {scaling=} not in ['spectrum', 'psd']!")
+
+ freqs, time, Zxx = _spectral_helper(x, x, fs, window, nperseg, noverlap,
+ nfft, detrend, return_onesided,
+ scaling=scaling, axis=axis,
+ mode='stft', boundary=boundary,
+ padded=padded)
+
+ return freqs, time, Zxx
+
+
+def istft(Zxx, fs=1.0, window='hann_periodic', nperseg=None, noverlap=None, nfft=None,
+ input_onesided=True, boundary=True, time_axis=-1, freq_axis=-2,
+ scaling='spectrum'):
+ r"""Perform the inverse Short Time Fourier transform (legacy function).
+
+ .. legacy:: function
+
+ `ShortTimeFFT` is a newer STFT / ISTFT implementation with more
+ features. A :ref:`comparison ` between the
+ implementations can be found in the :ref:`tutorial_stft` section of the
+ :ref:`user_guide`.
+
+ Parameters
+ ----------
+ Zxx : array_like
+ STFT of the signal to be reconstructed. If a purely real array
+ is passed, it will be cast to a complex data type.
+ fs : float, optional
+ Sampling frequency of the time series. Defaults to 1.0.
+ window : str or tuple or array_like, optional
+ Desired window to use. If `window` is a string or tuple, it is
+ passed to `get_window` to generate the window values, which are
+ DFT-even by default. See `get_window` for a list of windows and
+ required parameters. If `window` is array_like it will be used
+ directly as the window and its length must be nperseg. Defaults
+ to a periodic Hann window. Must match the window used to generate the
+ STFT for faithful inversion.
+ nperseg : int, optional
+ Number of data points corresponding to each STFT segment. This
+ parameter must be specified if the number of data points per
+ segment is odd, or if the STFT was padded via ``nfft >
+ nperseg``. If `None`, the value depends on the shape of
+ `Zxx` and `input_onesided`. If `input_onesided` is `True`,
+ ``nperseg=2*(Zxx.shape[freq_axis] - 1)``. Otherwise,
+ ``nperseg=Zxx.shape[freq_axis]``. Defaults to `None`.
+ noverlap : int, optional
+ Number of points to overlap between segments. If `None`, half
+ of the segment length. Defaults to `None`. When specified, the
+ COLA constraint must be met (see Notes below), and should match
+ the parameter used to generate the STFT. Defaults to `None`.
+ nfft : int, optional
+ Number of FFT points corresponding to each STFT segment. This
+ parameter must be specified if the STFT was padded via ``nfft >
+ nperseg``. If `None`, the default values are the same as for
+ `nperseg`, detailed above, with one exception: if
+ `input_onesided` is True and
+ ``nperseg==2*Zxx.shape[freq_axis] - 1``, `nfft` also takes on
+ that value. This case allows the proper inversion of an
+ odd-length unpadded STFT using ``nfft=None``. Defaults to
+ `None`.
+ input_onesided : bool, optional
+ If `True`, interpret the input array as one-sided FFTs, such
+ as is returned by `stft` with ``return_onesided=True`` and
+ `numpy.fft.rfft`. If `False`, interpret the input as a a
+ two-sided FFT. Defaults to `True`.
+ boundary : bool, optional
+ Specifies whether the input signal was extended at its
+ boundaries by supplying a non-`None` ``boundary`` argument to
+ `stft`. Defaults to `True`.
+ time_axis : int, optional
+ Where the time segments of the STFT is located; the default is
+ the last axis (i.e. ``axis=-1``).
+ freq_axis : int, optional
+ Where the frequency axis of the STFT is located; the default is
+ the penultimate axis (i.e. ``axis=-2``).
+ scaling: {'spectrum', 'psd'}
+ The default 'spectrum' scaling allows each frequency line of `Zxx` to
+ be interpreted as a magnitude spectrum. The 'psd' option scales each
+ line to a power spectral density - it allows to calculate the signal's
+ energy by numerically integrating over ``abs(Zxx)**2``.
+
+ Returns
+ -------
+ t : ndarray
+ Array of output data times.
+ x : ndarray
+ iSTFT of `Zxx`.
+
+ See Also
+ --------
+ stft: Short Time Fourier Transform
+ ShortTimeFFT: Newer STFT/ISTFT implementation providing more features.
+ check_COLA: Check whether the Constant OverLap Add (COLA) constraint
+ is met
+ check_NOLA: Check whether the Nonzero Overlap Add (NOLA) constraint is met
+
+ Notes
+ -----
+ In order to enable inversion of an STFT via the inverse STFT with
+ `istft`, the signal windowing must obey the constraint of "nonzero
+ overlap add" (NOLA):
+
+ .. math:: \sum_{t}w^{2}[n-tH] \ne 0
+
+ This ensures that the normalization factors that appear in the denominator
+ of the overlap-add reconstruction equation
+
+ .. math:: x[n]=\frac{\sum_{t}x_{t}[n]w[n-tH]}{\sum_{t}w^{2}[n-tH]}
+
+ are not zero. The NOLA constraint can be checked with the `check_NOLA`
+ function.
+
+ An STFT which has been modified (via masking or otherwise) is not
+ guaranteed to correspond to an exactly realizible signal. This
+ function implements the iSTFT via the least-squares estimation
+ algorithm detailed in [2]_, which produces a signal that minimizes
+ the mean squared error between the STFT of the returned signal and
+ the modified STFT.
+
+
+ .. versionadded:: 0.19.0
+
+ References
+ ----------
+ .. [1] Oppenheim, Alan V., Ronald W. Schafer, John R. Buck
+ "Discrete-Time Signal Processing", Prentice Hall, 1999.
+ .. [2] Daniel W. Griffin, Jae S. Lim "Signal Estimation from
+ Modified Short-Time Fourier Transform", IEEE 1984,
+ 10.1109/TASSP.1984.1164317
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+
+ Generate a test signal, a 2 Vrms sine wave at 50Hz corrupted by
+ 0.001 V**2/Hz of white noise sampled at 1024 Hz.
+
+ >>> fs = 1024
+ >>> N = 10*fs
+ >>> nperseg = 512
+ >>> amp = 2 * np.sqrt(2)
+ >>> noise_power = 0.001 * fs / 2
+ >>> time = np.arange(N) / float(fs)
+ >>> carrier = amp * np.sin(2*np.pi*50*time)
+ >>> noise = rng.normal(scale=np.sqrt(noise_power),
+ ... size=time.shape)
+ >>> x = carrier + noise
+
+ Compute the STFT, and plot its magnitude
+
+ >>> f, t, Zxx = signal.stft(x, fs=fs, nperseg=nperseg)
+ >>> plt.figure()
+ >>> plt.pcolormesh(t, f, np.abs(Zxx), vmin=0, vmax=amp, shading='gouraud')
+ >>> plt.ylim([f[1], f[-1]])
+ >>> plt.title('STFT Magnitude')
+ >>> plt.ylabel('Frequency [Hz]')
+ >>> plt.xlabel('Time [sec]')
+ >>> plt.yscale('log')
+ >>> plt.show()
+
+ Zero the components that are 10% or less of the carrier magnitude,
+ then convert back to a time series via inverse STFT
+
+ >>> Zxx = np.where(np.abs(Zxx) >= amp/10, Zxx, 0)
+ >>> _, xrec = signal.istft(Zxx, fs)
+
+ Compare the cleaned signal with the original and true carrier signals.
+
+ >>> plt.figure()
+ >>> plt.plot(time, x, time, xrec, time, carrier)
+ >>> plt.xlim([2, 2.1])
+ >>> plt.xlabel('Time [sec]')
+ >>> plt.ylabel('Signal')
+ >>> plt.legend(['Carrier + Noise', 'Filtered via STFT', 'True Carrier'])
+ >>> plt.show()
+
+ Note that the cleaned signal does not start as abruptly as the original,
+ since some of the coefficients of the transient were also removed:
+
+ >>> plt.figure()
+ >>> plt.plot(time, x, time, xrec, time, carrier)
+ >>> plt.xlim([0, 0.1])
+ >>> plt.xlabel('Time [sec]')
+ >>> plt.ylabel('Signal')
+ >>> plt.legend(['Carrier + Noise', 'Filtered via STFT', 'True Carrier'])
+ >>> plt.show()
+
+ """
+ # Make sure input is an ndarray of appropriate complex dtype
+ Zxx = np.asarray(Zxx) + 0j
+ freq_axis = int(freq_axis)
+ time_axis = int(time_axis)
+
+ if Zxx.ndim < 2:
+ raise ValueError('Input stft must be at least 2d!')
+
+ if freq_axis == time_axis:
+ raise ValueError('Must specify differing time and frequency axes!')
+
+ nseg = Zxx.shape[time_axis]
+
+ if input_onesided:
+ # Assume even segment length
+ n_default = 2*(Zxx.shape[freq_axis] - 1)
+ else:
+ n_default = Zxx.shape[freq_axis]
+
+ # Check windowing parameters
+ if nperseg is None:
+ nperseg = n_default
+ else:
+ nperseg = int(nperseg)
+ if nperseg < 1:
+ raise ValueError('nperseg must be a positive integer')
+
+ if nfft is None:
+ if (input_onesided) and (nperseg == n_default + 1):
+ # Odd nperseg, no FFT padding
+ nfft = nperseg
+ else:
+ nfft = n_default
+ elif nfft < nperseg:
+ raise ValueError('nfft must be greater than or equal to nperseg.')
+ else:
+ nfft = int(nfft)
+
+ if noverlap is None:
+ noverlap = nperseg//2
+ else:
+ noverlap = int(noverlap)
+ if noverlap >= nperseg:
+ raise ValueError('noverlap must be less than nperseg.')
+ nstep = nperseg - noverlap
+
+ # Rearrange axes if necessary
+ if time_axis != Zxx.ndim-1 or freq_axis != Zxx.ndim-2:
+ # Turn negative indices to positive for the call to transpose
+ if freq_axis < 0:
+ freq_axis = Zxx.ndim + freq_axis
+ if time_axis < 0:
+ time_axis = Zxx.ndim + time_axis
+ zouter = list(range(Zxx.ndim))
+ for ax in sorted([time_axis, freq_axis], reverse=True):
+ zouter.pop(ax)
+ Zxx = np.transpose(Zxx, zouter+[freq_axis, time_axis])
+
+ # Get window as array
+ if isinstance(window, str) or type(window) is tuple:
+ win = get_window(window, nperseg)
+ else:
+ win = np.asarray(window)
+ if len(win.shape) != 1:
+ raise ValueError('window must be 1-D')
+ if win.shape[0] != nperseg:
+ raise ValueError(f'window must have length of {nperseg}')
+
+ ifunc = sp_fft.irfft if input_onesided else sp_fft.ifft
+ xsubs = ifunc(Zxx, axis=-2, n=nfft)[..., :nperseg, :]
+
+ # Initialize output and normalization arrays
+ outputlength = nperseg + (nseg-1)*nstep
+ x = np.zeros(list(Zxx.shape[:-2])+[outputlength], dtype=xsubs.dtype)
+ norm = np.zeros(outputlength, dtype=xsubs.dtype)
+
+ if np.result_type(win, xsubs) != xsubs.dtype:
+ win = win.astype(xsubs.dtype)
+
+ if scaling == 'spectrum':
+ xsubs *= win.sum()
+ elif scaling == 'psd':
+ xsubs *= np.sqrt(fs * sum(win**2))
+ else:
+ raise ValueError(f"Parameter {scaling=} not in ['spectrum', 'psd']!")
+
+ # Construct the output from the ifft segments
+ # This loop could perhaps be vectorized/strided somehow...
+ for ii in range(nseg):
+ # Window the ifft
+ x[..., ii*nstep:ii*nstep+nperseg] += xsubs[..., ii] * win
+ norm[..., ii*nstep:ii*nstep+nperseg] += win**2
+
+ # Remove extension points
+ if boundary:
+ x = x[..., nperseg//2:-(nperseg//2)]
+ norm = norm[..., nperseg//2:-(nperseg//2)]
+
+ # Divide out normalization where non-tiny
+ if np.sum(norm > 1e-10) != len(norm):
+ warnings.warn(
+ "NOLA condition failed, STFT may not be invertible."
+ + (" Possibly due to missing boundary" if not boundary else ""),
+ stacklevel=2
+ )
+ x /= np.where(norm > 1e-10, norm, 1.0)
+
+ if input_onesided:
+ x = x.real
+
+ # Put axes back
+ if x.ndim > 1:
+ if time_axis != Zxx.ndim-1:
+ if freq_axis < time_axis:
+ time_axis -= 1
+ x = np.moveaxis(x, -1, time_axis)
+
+ time = np.arange(x.shape[0])/float(fs)
+ return time, x
+
+
+def coherence(x, y, fs=1.0, window='hann_periodic', nperseg=None, noverlap=None,
+ nfft=None, detrend='constant', axis=-1):
+ r"""
+ Estimate the magnitude squared coherence estimate, Cxy, of
+ discrete-time signals X and Y using Welch's method.
+
+ ``Cxy = abs(Pxy)**2/(Pxx*Pyy)``, where `Pxx` and `Pyy` are power
+ spectral density estimates of X and Y, and `Pxy` is the cross
+ spectral density estimate of X and Y.
+
+ Parameters
+ ----------
+ x : array_like
+ Time series of measurement values
+ y : array_like
+ Time series of measurement values
+ fs : float, optional
+ Sampling frequency of the `x` and `y` time series. Defaults
+ to 1.0.
+ window : str or tuple or array_like, optional
+ Desired window to use. If `window` is a string or tuple, it is
+ passed to `get_window` to generate the window values, which are
+ DFT-even by default. See `get_window` for a list of windows and
+ required parameters. If `window` is array_like it will be used
+ directly as the window and its length must be nperseg. Defaults
+ to a periodic Hann window.
+ nperseg : int, optional
+ Length of each segment. Defaults to None, but if window is str or
+ tuple, is set to 256, and if window is array_like, is set to the
+ length of the window.
+ noverlap: int, optional
+ Number of points to overlap between segments. If `None`,
+ ``noverlap = nperseg // 2``. Defaults to `None`.
+ nfft : int, optional
+ Length of the FFT used, if a zero padded FFT is desired. If
+ `None`, the FFT length is `nperseg`. Defaults to `None`.
+ detrend : str or function or `False`, optional
+ Specifies how to detrend each segment. If `detrend` is a
+ string, it is passed as the `type` argument to the `detrend`
+ function. If it is a function, it takes a segment and returns a
+ detrended segment. If `detrend` is `False`, no detrending is
+ done. Defaults to 'constant'.
+ axis : int, optional
+ Axis along which the coherence is computed for both inputs; the
+ default is over the last axis (i.e. ``axis=-1``).
+
+ Returns
+ -------
+ f : ndarray
+ Array of sample frequencies.
+ Cxy : ndarray
+ Magnitude squared coherence of x and y.
+
+ See Also
+ --------
+ periodogram: Simple, optionally modified periodogram
+ lombscargle: Lomb-Scargle periodogram for unevenly sampled data
+ welch: Power spectral density by Welch's method.
+ csd: Cross spectral density by Welch's method.
+
+ Notes
+ -----
+ An appropriate amount of overlap will depend on the choice of window
+ and on your requirements. For the default Hann window an overlap of
+ 50% is a reasonable trade-off between accurately estimating the
+ signal power, while not over counting any of the data. Narrower
+ windows may require a larger overlap.
+
+ .. versionadded:: 0.16.0
+
+ References
+ ----------
+ .. [1] P. Welch, "The use of the fast Fourier transform for the
+ estimation of power spectra: A method based on time averaging
+ over short, modified periodograms", IEEE Trans. Audio
+ Electroacoust. vol. 15, pp. 70-73, 1967.
+ .. [2] Stoica, Petre, and Randolph Moses, "Spectral Analysis of
+ Signals" Prentice Hall, 2005
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> rng = np.random.default_rng()
+
+ Generate two test signals with some common features.
+
+ >>> fs = 10e3
+ >>> N = 1e5
+ >>> amp = 20
+ >>> freq = 1234.0
+ >>> noise_power = 0.001 * fs / 2
+ >>> time = np.arange(N) / fs
+ >>> b, a = signal.butter(2, 0.25, 'low')
+ >>> x = rng.normal(scale=np.sqrt(noise_power), size=time.shape)
+ >>> y = signal.lfilter(b, a, x)
+ >>> x += amp*np.sin(2*np.pi*freq*time)
+ >>> y += rng.normal(scale=0.1*np.sqrt(noise_power), size=time.shape)
+
+ Compute and plot the coherence.
+
+ >>> f, Cxy = signal.coherence(x, y, fs, nperseg=1024)
+ >>> plt.semilogy(f, Cxy)
+ >>> plt.xlabel('frequency [Hz]')
+ >>> plt.ylabel('Coherence')
+ >>> plt.show()
+
+ """
+ freqs, Pxx = welch(x, fs=fs, window=window, nperseg=nperseg,
+ noverlap=noverlap, nfft=nfft, detrend=detrend,
+ axis=axis)
+ _, Pyy = welch(y, fs=fs, window=window, nperseg=nperseg, noverlap=noverlap,
+ nfft=nfft, detrend=detrend, axis=axis)
+ _, Pxy = csd(x, y, fs=fs, window=window, nperseg=nperseg,
+ noverlap=noverlap, nfft=nfft, detrend=detrend, axis=axis)
+
+ Cxy = np.abs(Pxy)**2 / Pxx / Pyy
+
+ return freqs, Cxy
+
+
+def _spectral_helper(x, y, fs=1.0, window='hann', nperseg=None, noverlap=None,
+ nfft=None, detrend='constant', return_onesided=True,
+ scaling='density', axis=-1, mode='psd', boundary=None,
+ padded=False):
+ """Calculate various forms of windowed FFTs for PSD, CSD, etc.
+
+ .. legacy:: function
+
+ This function is soley used by the legacy functions `spectrogram` and `stft`
+ (which are also in this same source file `scipy/signal/_spectral_py.py`).
+
+ This is a helper function that implements the commonality between
+ the stft, psd, csd, and spectrogram functions. It is not designed to
+ be called externally. The windows are not averaged over; the result
+ from each window is returned.
+
+ Parameters
+ ----------
+ x : array_like
+ Array or sequence containing the data to be analyzed.
+ y : array_like
+ Array or sequence containing the data to be analyzed. If this is
+ the same object in memory as `x` (i.e. ``_spectral_helper(x,
+ x, ...)``), the extra computations are spared.
+ fs : float, optional
+ Sampling frequency of the time series. Defaults to 1.0.
+ window : str or tuple or array_like, optional
+ Desired window to use. If `window` is a string or tuple, it is
+ passed to `get_window` to generate the window values, which are
+ DFT-even by default. See `get_window` for a list of windows and
+ required parameters. If `window` is array_like it will be used
+ directly as the window and its length must be nperseg. Defaults
+ to a Hann window.
+ nperseg : int, optional
+ Length of each segment. Defaults to None, but if window is str or
+ tuple, is set to 256, and if window is array_like, is set to the
+ length of the window.
+ noverlap : int, optional
+ Number of points to overlap between segments. If `None`,
+ ``noverlap = nperseg // 2``. Defaults to `None`.
+ nfft : int, optional
+ Length of the FFT used, if a zero padded FFT is desired. If
+ `None`, the FFT length is `nperseg`. Defaults to `None`.
+ detrend : str or function or `False`, optional
+ Specifies how to detrend each segment. If `detrend` is a
+ string, it is passed as the `type` argument to the `detrend`
+ function. If it is a function, it takes a segment and returns a
+ detrended segment. If `detrend` is `False`, no detrending is
+ done. Defaults to 'constant'.
+ return_onesided : bool, optional
+ If `True`, return a one-sided spectrum for real data. If
+ `False` return a two-sided spectrum. Defaults to `True`, but for
+ complex data, a two-sided spectrum is always returned.
+ scaling : { 'density', 'spectrum' }, optional
+ Selects between computing the cross spectral density ('density')
+ where `Pxy` has units of V²/Hz and computing the cross
+ spectrum ('spectrum') where `Pxy` has units of V², if `x`
+ and `y` are measured in V and `fs` is measured in Hz.
+ Defaults to 'density'
+ axis : int, optional
+ Axis along which the FFTs are computed; the default is over the
+ last axis (i.e. ``axis=-1``).
+ mode: str {'psd', 'stft'}, optional
+ Defines what kind of return values are expected. Defaults to
+ 'psd'.
+ boundary : str or None, optional
+ Specifies whether the input signal is extended at both ends, and
+ how to generate the new values, in order to center the first
+ windowed segment on the first input point. This has the benefit
+ of enabling reconstruction of the first input point when the
+ employed window function starts at zero. Valid options are
+ ``['even', 'odd', 'constant', 'zeros', None]``. Defaults to
+ `None`.
+ padded : bool, optional
+ Specifies whether the input signal is zero-padded at the end to
+ make the signal fit exactly into an integer number of window
+ segments, so that all of the signal is included in the output.
+ Defaults to `False`. Padding occurs after boundary extension, if
+ `boundary` is not `None`, and `padded` is `True`.
+
+ Returns
+ -------
+ freqs : ndarray
+ Array of sample frequencies.
+ t : ndarray
+ Array of times corresponding to each data segment
+ result : ndarray
+ Array of output data, contents dependent on *mode* kwarg.
+
+ Notes
+ -----
+ Adapted from matplotlib.mlab
+
+ .. versionadded:: 0.16.0
+ """
+ if mode not in ['psd', 'stft']:
+ raise ValueError(f"Unknown value for mode {mode}, must be one of: "
+ "{'psd', 'stft'}")
+
+ boundary_funcs = {'even': even_ext,
+ 'odd': odd_ext,
+ 'constant': const_ext,
+ 'zeros': zero_ext,
+ None: None}
+
+ if boundary not in boundary_funcs:
+ raise ValueError(f"Unknown boundary option '{boundary}', "
+ f"must be one of: {list(boundary_funcs.keys())}")
+
+ # If x and y are the same object we can save ourselves some computation.
+ same_data = y is x
+
+ if not same_data and mode != 'psd':
+ raise ValueError("x and y must be equal if mode is 'stft'")
+
+ axis = int(axis)
+
+ # Ensure we have np.arrays, get outdtype
+ x = np.asarray(x)
+ if not same_data:
+ y = np.asarray(y)
+ outdtype = np.result_type(x, y, np.complex64)
+ else:
+ outdtype = np.result_type(x, np.complex64)
+
+ if not same_data:
+ # Check if we can broadcast the outer axes together
+ xouter = list(x.shape)
+ youter = list(y.shape)
+ xouter.pop(axis)
+ youter.pop(axis)
+ try:
+ outershape = np.broadcast(np.empty(xouter), np.empty(youter)).shape
+ except ValueError as e:
+ raise ValueError('x and y cannot be broadcast together.') from e
+
+ if same_data:
+ if x.size == 0:
+ return np.empty(x.shape), np.empty(x.shape), np.empty(x.shape)
+ else:
+ if x.size == 0 or y.size == 0:
+ outshape = outershape + (min([x.shape[axis], y.shape[axis]]),)
+ emptyout = np.moveaxis(np.empty(outshape), -1, axis)
+ return emptyout, emptyout, emptyout
+
+ if x.ndim > 1:
+ if axis != -1:
+ x = np.moveaxis(x, axis, -1)
+ if not same_data and y.ndim > 1:
+ y = np.moveaxis(y, axis, -1)
+
+ # Check if x and y are the same length, zero-pad if necessary
+ if not same_data:
+ if x.shape[-1] != y.shape[-1]:
+ if x.shape[-1] < y.shape[-1]:
+ pad_shape = list(x.shape)
+ pad_shape[-1] = y.shape[-1] - x.shape[-1]
+ x = np.concatenate((x, np.zeros(pad_shape)), -1)
+ else:
+ pad_shape = list(y.shape)
+ pad_shape[-1] = x.shape[-1] - y.shape[-1]
+ y = np.concatenate((y, np.zeros(pad_shape)), -1)
+
+ if nperseg is not None: # if specified by user
+ nperseg = int(nperseg)
+ if nperseg < 1:
+ raise ValueError('nperseg must be a positive integer')
+
+ # parse window; if array like, then set nperseg = win.shape
+ win, nperseg = _triage_segments(window, nperseg, input_length=x.shape[-1])
+
+ if nfft is None:
+ nfft = nperseg
+ elif nfft < nperseg:
+ raise ValueError('nfft must be greater than or equal to nperseg.')
+ else:
+ nfft = int(nfft)
+
+ if noverlap is None:
+ noverlap = nperseg//2
+ else:
+ noverlap = int(noverlap)
+ if noverlap >= nperseg:
+ raise ValueError('noverlap must be less than nperseg.')
+ nstep = nperseg - noverlap
+
+ # Padding occurs after boundary extension, so that the extended signal ends
+ # in zeros, instead of introducing an impulse at the end.
+ # I.e. if x = [..., 3, 2]
+ # extend then pad -> [..., 3, 2, 2, 3, 0, 0, 0]
+ # pad then extend -> [..., 3, 2, 0, 0, 0, 2, 3]
+
+ if boundary is not None:
+ ext_func = boundary_funcs[boundary]
+ x = ext_func(x, nperseg//2, axis=-1)
+ if not same_data:
+ y = ext_func(y, nperseg//2, axis=-1)
+
+ if padded:
+ # Pad to integer number of windowed segments
+ # I.e. make x.shape[-1] = nperseg + (nseg-1)*nstep, with integer nseg
+ nadd = (-(x.shape[-1]-nperseg) % nstep) % nperseg
+ zeros_shape = list(x.shape[:-1]) + [nadd]
+ x = np.concatenate((x, np.zeros(zeros_shape)), axis=-1)
+ if not same_data:
+ zeros_shape = list(y.shape[:-1]) + [nadd]
+ y = np.concatenate((y, np.zeros(zeros_shape)), axis=-1)
+
+ # Handle detrending and window functions
+ if not detrend:
+ def detrend_func(d):
+ return d
+ elif not hasattr(detrend, '__call__'):
+ def detrend_func(d):
+ return _signaltools.detrend(d, type=detrend, axis=-1)
+ elif axis != -1:
+ # Wrap this function so that it receives a shape that it could
+ # reasonably expect to receive.
+ def detrend_func(d):
+ d = np.moveaxis(d, -1, axis)
+ d = detrend(d)
+ return np.moveaxis(d, axis, -1)
+ else:
+ detrend_func = detrend
+
+ if np.result_type(win, np.complex64) != outdtype:
+ win = win.astype(outdtype)
+
+ if scaling == 'density':
+ scale = 1.0 / (fs * (win*win).sum())
+ elif scaling == 'spectrum':
+ scale = 1.0 / win.sum()**2
+ else:
+ raise ValueError(f'Unknown scaling: {scaling!r}')
+
+ if mode == 'stft':
+ scale = np.sqrt(scale)
+
+ if return_onesided:
+ if np.iscomplexobj(x):
+ sides = 'twosided'
+ warnings.warn('Input data is complex, switching to return_onesided=False',
+ stacklevel=3)
+ else:
+ sides = 'onesided'
+ if not same_data:
+ if np.iscomplexobj(y):
+ sides = 'twosided'
+ warnings.warn('Input data is complex, switching to '
+ 'return_onesided=False',
+ stacklevel=3)
+ else:
+ sides = 'twosided'
+
+ if sides == 'twosided':
+ freqs = sp_fft.fftfreq(nfft, 1/fs)
+ elif sides == 'onesided':
+ freqs = sp_fft.rfftfreq(nfft, 1/fs)
+
+ # Perform the windowed FFTs
+ result = _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides)
+
+ if not same_data:
+ # All the same operations on the y data
+ result_y = _fft_helper(y, win, detrend_func, nperseg, noverlap, nfft,
+ sides)
+ result = np.conjugate(result) * result_y
+ elif mode == 'psd':
+ result = np.conjugate(result) * result
+
+ result *= scale
+ if sides == 'onesided' and mode == 'psd':
+ if nfft % 2:
+ result[..., 1:] *= 2
+ else:
+ # Last point is unpaired Nyquist freq point, don't double
+ result[..., 1:-1] *= 2
+
+ time = np.arange(nperseg/2, x.shape[-1] - nperseg/2 + 1,
+ nperseg - noverlap)/float(fs)
+ if boundary is not None:
+ time -= (nperseg/2) / fs
+
+ result = result.astype(outdtype)
+
+ # All imaginary parts are zero anyways
+ if same_data and mode != 'stft':
+ result = result.real
+
+ # Output is going to have new last axis for time/window index, so a
+ # negative axis index shifts down one
+ if axis < 0:
+ axis -= 1
+
+ # Roll frequency axis back to axis where the data came from
+ result = np.moveaxis(result, -1, axis)
+
+ return freqs, time, result
+
+
+def _fft_helper(x, win, detrend_func, nperseg, noverlap, nfft, sides):
+ """
+ Calculate windowed FFT, for internal use by
+ `scipy.signal._spectral_helper`.
+
+ .. legacy:: function
+
+ This function is solely used by the legacy `_spectral_helper` function,
+ which is located also in this file.
+
+ This is a helper function that does the main FFT calculation for
+ `_spectral helper`. All input validation is performed there, and the
+ data axis is assumed to be the last axis of x. It is not designed to
+ be called externally. The windows are not averaged over; the result
+ from each window is returned.
+
+ Returns
+ -------
+ result : ndarray
+ Array of FFT data
+
+ Notes
+ -----
+ Adapted from matplotlib.mlab
+
+ .. versionadded:: 0.16.0
+ """
+ # Created sliding window view of array
+ if nperseg == 1 and noverlap == 0:
+ result = x[..., np.newaxis]
+ else:
+ step = nperseg - noverlap
+ result = np.lib.stride_tricks.sliding_window_view(
+ x, window_shape=nperseg, axis=-1, writeable=True
+ )
+ result = result[..., 0::step, :]
+
+ # Detrend each data segment individually
+ result = detrend_func(result)
+
+ # Apply window by multiplication
+ result = win * result
+
+ # Perform the fft. Acts on last axis by default. Zero-pads automatically
+ if sides == 'twosided':
+ func = sp_fft.fft
+ else:
+ result = result.real
+ func = sp_fft.rfft
+ result = func(result, n=nfft)
+
+ return result
+
+
+def _triage_segments(window, nperseg, input_length):
+ """
+ Parses window and nperseg arguments for spectrogram and _spectral_helper.
+ This is a helper function, not meant to be called externally.
+
+ .. legacy:: function
+
+ This function is soley used by the legacy functions `spectrogram` and
+ `_spectral_helper` (which are also in this file).
+
+ Parameters
+ ----------
+ window : string, tuple, or ndarray
+ If window is specified by a string or tuple and nperseg is not
+ specified, nperseg is set to the default of 256 and returns a window of
+ that length.
+ If instead the window is array_like and nperseg is not specified, then
+ nperseg is set to the length of the window. A ValueError is raised if
+ the user supplies both an array_like window and a value for nperseg but
+ nperseg does not equal the length of the window.
+
+ nperseg : int
+ Length of each segment
+
+ input_length: int
+ Length of input signal, i.e. x.shape[-1]. Used to test for errors.
+
+ Returns
+ -------
+ win : ndarray
+ window. If function was called with string or tuple than this will hold
+ the actual array used as a window.
+
+ nperseg : int
+ Length of each segment. If window is str or tuple, nperseg is set to
+ 256. If window is array_like, nperseg is set to the length of the
+ window.
+ """
+ # parse window; if array like, then set nperseg = win.shape
+ if isinstance(window, str) or isinstance(window, tuple):
+ # if nperseg not specified
+ if nperseg is None:
+ nperseg = 256 # then change to default
+ if nperseg > input_length:
+ warnings.warn(f'nperseg = {nperseg:d} is greater than input length '
+ f' = {input_length:d}, using nperseg = {input_length:d}',
+ stacklevel=3)
+ nperseg = input_length
+ win = get_window(window, nperseg)
+ else:
+ win = np.asarray(window)
+ if len(win.shape) != 1:
+ raise ValueError('window must be 1-D')
+ if input_length < win.shape[-1]:
+ raise ValueError('window is longer than input signal')
+ if nperseg is None:
+ nperseg = win.shape[0]
+ elif nperseg is not None:
+ if nperseg != win.shape[0]:
+ raise ValueError("value specified for nperseg is different"
+ " from length of window")
+ return win, nperseg
+
+
+def _median_bias(n):
+ """
+ Returns the bias of the median of a set of periodograms relative to
+ the mean.
+
+ See Appendix B from [1]_ for details.
+
+ Parameters
+ ----------
+ n : int
+ Numbers of periodograms being averaged.
+
+ Returns
+ -------
+ bias : float
+ Calculated bias.
+
+ References
+ ----------
+ .. [1] B. Allen, W.G. Anderson, P.R. Brady, D.A. Brown, J.D.E. Creighton.
+ "FINDCHIRP: an algorithm for detection of gravitational waves from
+ inspiraling compact binaries", Physical Review D 85, 2012,
+ :arxiv:`gr-qc/0509116`
+ """
+ ii_2 = 2 * np.arange(1., (n-1) // 2 + 1)
+ return 1 + np.sum(1. / (ii_2 + 1) - 1. / ii_2)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spline.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spline.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..6a35e1d2a8bd8088834d1e9dbc9c4107325d8890
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spline.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spline.pyi b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spline.pyi
new file mode 100644
index 0000000000000000000000000000000000000000..c4225577db7ea188a2add225ecec1fbec855de06
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spline.pyi
@@ -0,0 +1,34 @@
+
+import numpy as np
+from numpy.typing import NDArray
+
+FloatingArray = NDArray[np.float32] | NDArray[np.float64]
+ComplexArray = NDArray[np.complex64] | NDArray[np.complex128]
+FloatingComplexArray = FloatingArray | ComplexArray
+
+
+def symiirorder1_ic(signal: FloatingComplexArray,
+ c0: float,
+ z1: float,
+ precision: float) -> FloatingComplexArray:
+ ...
+
+
+def symiirorder2_ic_fwd(signal: FloatingArray,
+ r: float,
+ omega: float,
+ precision: float) -> FloatingArray:
+ ...
+
+
+def symiirorder2_ic_bwd(signal: FloatingArray,
+ r: float,
+ omega: float,
+ precision: float) -> FloatingArray:
+ ...
+
+
+def sepfir2d(input: FloatingComplexArray,
+ hrow: FloatingComplexArray,
+ hcol: FloatingComplexArray) -> FloatingComplexArray:
+ ...
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spline_filters.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spline_filters.py
new file mode 100644
index 0000000000000000000000000000000000000000..e95869326a48c9d71cdc0152de897f472ea72265
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_spline_filters.py
@@ -0,0 +1,847 @@
+import math
+
+from numpy import (zeros_like, array, tan, arange, floor,
+ r_, atleast_1d, greater, cos, add, sin,
+ moveaxis, abs, complex64, float32)
+import numpy as np
+
+from scipy._lib._array_api import array_namespace, xp_promote
+
+from scipy._lib._util import normalize_axis_index
+
+# From splinemodule.c
+from ._spline import sepfir2d, symiirorder1_ic, symiirorder2_ic_fwd, symiirorder2_ic_bwd
+from ._signaltools import lfilter, sosfilt, lfiltic
+from ._arraytools import axis_slice, axis_reverse
+
+from scipy.interpolate import BSpline
+
+
+__all__ = ['spline_filter', 'gauss_spline',
+ 'cspline1d', 'qspline1d', 'qspline2d', 'cspline2d',
+ 'cspline1d_eval', 'qspline1d_eval', 'symiirorder1', 'symiirorder2']
+
+
+def spline_filter(Iin, lmbda=5.0):
+ """Smoothing spline (cubic) filtering of a rank-2 array.
+
+ Filter an input data set, `Iin`, using a (cubic) smoothing spline of
+ fall-off `lmbda`.
+
+ Parameters
+ ----------
+ Iin : array_like
+ input data set
+ lmbda : float, optional
+ spline smoothing fall-off value, default is `5.0`.
+
+ Returns
+ -------
+ res : ndarray
+ filtered input data
+
+ Examples
+ --------
+ We can filter an multi dimensional signal (ex: 2D image) using cubic
+ B-spline filter:
+
+ >>> import numpy as np
+ >>> from scipy.signal import spline_filter
+ >>> import matplotlib.pyplot as plt
+ >>> orig_img = np.eye(20) # create an image
+ >>> orig_img[10, :] = 1.0
+ >>> sp_filter = spline_filter(orig_img, lmbda=0.1)
+ >>> 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()
+
+ """
+ xp = array_namespace(Iin)
+ Iin = np.asarray(Iin)
+
+ if Iin.dtype not in [np.float32, np.float64, np.complex64, np.complex128]:
+ raise TypeError(f"Invalid data type for Iin: {Iin.dtype = }")
+
+ # XXX: note that complex-valued computations are done in single precision
+ # this is historic, and the root reason is unclear,
+ # see https://github.com/scipy/scipy/issues/9209
+ # Attempting to work in complex double precision leads to symiirorder1
+ # failing to converge for the boundary conditions.
+ intype = Iin.dtype
+ hcol = array([1.0, 4.0, 1.0], np.float32) / 6.0
+ if intype == np.complex128:
+ Iin = Iin.astype(np.complex64)
+
+ ck = cspline2d(Iin, lmbda)
+ out = sepfir2d(ck, hcol, hcol)
+ out = out.astype(intype)
+ return xp.asarray(out)
+
+
+_splinefunc_cache = {}
+
+
+def gauss_spline(x, n):
+ r"""Gaussian approximation to B-spline basis function of order n.
+
+ Parameters
+ ----------
+ x : array_like
+ a knot vector
+ n : int
+ The order of the spline. Must be non-negative, i.e., n >= 0
+
+ Returns
+ -------
+ res : ndarray
+ B-spline basis function values approximated by a zero-mean Gaussian
+ function.
+
+ Notes
+ -----
+ The B-spline basis function can be approximated well by a zero-mean
+ Gaussian function with standard-deviation equal to :math:`\sigma=(n+1)/12`
+ for large `n` :
+
+ .. math:: \frac{1}{\sqrt {2\pi\sigma^2}}exp(-\frac{x^2}{2\sigma})
+
+ References
+ ----------
+ .. [1] Bouma H., Vilanova A., Bescos J.O., ter Haar Romeny B.M., Gerritsen
+ F.A. (2007) Fast and Accurate Gaussian Derivatives Based on B-Splines. In:
+ Sgallari F., Murli A., Paragios N. (eds) Scale Space and Variational
+ Methods in Computer Vision. SSVM 2007. Lecture Notes in Computer
+ Science, vol 4485. Springer, Berlin, Heidelberg.
+
+ Examples
+ --------
+ We can calculate B-Spline basis functions approximated by a Gaussian
+ distribution:
+
+ >>> import numpy as np
+ >>> from scipy.signal import gauss_spline
+ >>> knots = np.array([-1.0, 0.0, -1.0])
+ >>> gauss_spline(knots, 3)
+ array([0.15418033, 0.6909883, 0.15418033]) # may vary
+
+ """
+ xp = array_namespace(x)
+ x = xp.asarray(x)
+ signsq = (n + 1) / 12.0
+ return 1 / math.sqrt(2 * math.pi * signsq) * xp.exp(-x ** 2 / 2 / signsq)
+
+
+def _cubic(x):
+ xp = array_namespace(x)
+
+ x = np.asarray(x, dtype=float)
+ b = BSpline.basis_element([-2, -1, 0, 1, 2], extrapolate=False)
+ out = b(x)
+ out[(x < -2) | (x > 2)] = 0
+ return xp.asarray(out)
+
+
+def _quadratic(x):
+ xp = array_namespace(x)
+
+ x = abs(np.asarray(x, dtype=float))
+ b = BSpline.basis_element([-1.5, -0.5, 0.5, 1.5], extrapolate=False)
+ out = b(x)
+ out[(x < -1.5) | (x > 1.5)] = 0
+ return xp.asarray(out)
+
+
+def _coeff_smooth(lam):
+ xi = 1 - 96 * lam + 24 * lam * math.sqrt(3 + 144 * lam)
+ omeg = math.atan2(math.sqrt(144 * lam - 1), math.sqrt(xi))
+ rho = (24 * lam - 1 - math.sqrt(xi)) / (24 * lam)
+ rho = rho * math.sqrt((48 * lam + 24 * lam * math.sqrt(3 + 144 * lam)) / xi)
+ return rho, omeg
+
+
+def _hc(k, cs, rho, omega):
+ return (cs / sin(omega) * (rho ** k) * sin(omega * (k + 1)) *
+ greater(k, -1))
+
+
+def _hs(k, cs, rho, omega):
+ c0 = (cs * cs * (1 + rho * rho) / (1 - rho * rho) /
+ (1 - 2 * rho * rho * cos(2 * omega) + rho ** 4))
+ gamma = (1 - rho * rho) / (1 + rho * rho) / tan(omega)
+ ak = abs(k)
+ return c0 * rho ** ak * (cos(omega * ak) + gamma * sin(omega * ak))
+
+
+def _cubic_smooth_coeff(signal, lamb):
+ signal = np.asarray(signal)
+
+ rho, omega = _coeff_smooth(lamb)
+ cs = 1 - 2 * rho * cos(omega) + rho * rho
+ K = len(signal)
+ k = arange(K)
+
+ zi_2 = (_hc(0, cs, rho, omega) * signal[0] +
+ add.reduce(_hc(k + 1, cs, rho, omega) * signal))
+ zi_1 = (_hc(0, cs, rho, omega) * signal[0] +
+ _hc(1, cs, rho, omega) * signal[1] +
+ add.reduce(_hc(k + 2, cs, rho, omega) * signal))
+
+ # Forward filter:
+ # for n in range(2, K):
+ # yp[n] = (cs * signal[n] + 2 * rho * cos(omega) * yp[n - 1] -
+ # rho * rho * yp[n - 2])
+ zi = lfiltic(cs, r_[1, -2 * rho * cos(omega), rho * rho], r_[zi_1, zi_2])
+ zi = zi.reshape(1, -1)
+
+ sos = r_[cs, 0, 0, 1, -2 * rho * cos(omega), rho * rho]
+ sos = sos.reshape(1, -1)
+
+ yp, _ = sosfilt(sos, signal[2:], zi=zi)
+ yp = r_[zi_2, zi_1, yp]
+
+ # Reverse filter:
+ # for n in range(K - 3, -1, -1):
+ # y[n] = (cs * yp[n] + 2 * rho * cos(omega) * y[n + 1] -
+ # rho * rho * y[n + 2])
+
+ zi_2 = add.reduce((_hs(k, cs, rho, omega) +
+ _hs(k + 1, cs, rho, omega)) * signal[::-1])
+ zi_1 = add.reduce((_hs(k - 1, cs, rho, omega) +
+ _hs(k + 2, cs, rho, omega)) * signal[::-1])
+
+ zi = lfiltic(cs, r_[1, -2 * rho * cos(omega), rho * rho], r_[zi_1, zi_2])
+ zi = zi.reshape(1, -1)
+ y, _ = sosfilt(sos, yp[-3::-1], zi=zi)
+ y = r_[y[::-1], zi_1, zi_2]
+ return y
+
+
+def _cubic_coeff(signal):
+ signal = np.asarray(signal)
+
+ zi = -2 + math.sqrt(3)
+ K = len(signal)
+ powers = zi ** np.arange(K)
+
+ if K == 1:
+ yplus = signal[0] + zi * add.reduce(powers * signal)
+ output = zi / (zi - 1) * yplus
+ return atleast_1d(output)
+
+ # Forward filter:
+ # yplus[0] = signal[0] + zi * add.reduce(powers * signal)
+ # for k in range(1, K):
+ # yplus[k] = signal[k] + zi * yplus[k - 1]
+
+ state = lfiltic(1, np.r_[1, -zi], np.atleast_1d(add.reduce(powers * signal)))
+
+ b = np.ones(1)
+ a = np.r_[1, -zi]
+ yplus, _ = lfilter(b, a, signal, zi=state)
+
+ # Reverse filter:
+ # output[K - 1] = zi / (zi - 1) * yplus[K - 1]
+ # for k in range(K - 2, -1, -1):
+ # output[k] = zi * (output[k + 1] - yplus[k])
+ out_last = zi / (zi - 1) * yplus[K - 1]
+ state = lfiltic(-zi, r_[1, -zi], np.atleast_1d(out_last))
+
+ b = np.asarray([-zi])
+ output, _ = lfilter(b, a, yplus[-2::-1], zi=state)
+ output = np.r_[output[::-1], out_last]
+ return output * 6.0
+
+
+def _quadratic_coeff(signal):
+ signal = np.asarray(signal)
+
+ zi = -3 + 2 * math.sqrt(2.0)
+ K = len(signal)
+ powers = zi ** np.arange(K)
+
+ if K == 1:
+ yplus = signal[0] + zi * np.add.reduce(powers * signal)
+ output = zi / (zi - 1) * yplus
+ return atleast_1d(output)
+
+ # Forward filter:
+ # yplus[0] = signal[0] + zi * add.reduce(powers * signal)
+ # for k in range(1, K):
+ # yplus[k] = signal[k] + zi * yplus[k - 1]
+
+ state = lfiltic(1, np.r_[1, -zi], np.atleast_1d(np.add.reduce(powers * signal)))
+
+ b = np.ones(1)
+ a = np.r_[1, -zi]
+ yplus, _ = lfilter(b, a, signal, zi=state)
+
+ # Reverse filter:
+ # output[K - 1] = zi / (zi - 1) * yplus[K - 1]
+ # for k in range(K - 2, -1, -1):
+ # output[k] = zi * (output[k + 1] - yplus[k])
+ out_last = zi / (zi - 1) * yplus[K - 1]
+ state = lfiltic(-zi, r_[1, -zi], np.atleast_1d(out_last))
+
+ b = np.asarray([-zi])
+ output, _ = lfilter(b, a, yplus[-2::-1], zi=state)
+ output = np.r_[output[::-1], out_last]
+ return output * 8.0
+
+
+def compute_root_from_lambda(lamb):
+ tmp = math.sqrt(3 + 144 * lamb)
+ xi = 1 - 96 * lamb + 24 * lamb * tmp
+ omega = math.atan(math.sqrt((144 * lamb - 1.0) / xi))
+ tmp2 = math.sqrt(xi)
+ r = ((24 * lamb - 1 - tmp2) / (24 * lamb) *
+ math.sqrt(48*lamb + 24 * lamb * tmp) / tmp2)
+ return r, omega
+
+
+def cspline1d(signal, lamb=0.0):
+ """
+ Compute cubic spline coefficients for rank-1 array.
+
+ Find the cubic spline coefficients for a 1-D signal assuming
+ mirror-symmetric boundary conditions. To obtain the signal back from the
+ spline representation mirror-symmetric-convolve these coefficients with a
+ length 3 FIR window [1.0, 4.0, 1.0]/ 6.0 .
+
+ Parameters
+ ----------
+ signal : ndarray
+ A rank-1 array representing samples of a signal.
+ lamb : float, optional
+ Smoothing coefficient, default is 0.0.
+
+ Returns
+ -------
+ c : ndarray
+ Cubic spline coefficients.
+
+ See Also
+ --------
+ cspline1d_eval : Evaluate a cubic spline at the new set of points.
+
+ Examples
+ --------
+ We can filter a signal to reduce and smooth out high-frequency noise with
+ a cubic spline:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import cspline1d, cspline1d_eval
+ >>> rng = np.random.default_rng()
+ >>> sig = np.repeat([0., 1., 0.], 100)
+ >>> sig += rng.standard_normal(len(sig))*0.05 # add noise
+ >>> time = np.linspace(0, len(sig))
+ >>> filtered = cspline1d_eval(cspline1d(sig), time)
+ >>> plt.plot(sig, label="signal")
+ >>> plt.plot(time, filtered, label="filtered")
+ >>> plt.legend()
+ >>> plt.show()
+
+ """
+ xp = array_namespace(signal)
+
+ if lamb != 0.0:
+ ret = _cubic_smooth_coeff(signal, lamb)
+ else:
+ ret = _cubic_coeff(signal)
+ return xp.asarray(ret)
+
+
+def qspline1d(signal, lamb=0.0):
+ """Compute quadratic spline coefficients for rank-1 array.
+
+ Parameters
+ ----------
+ signal : ndarray
+ A rank-1 array representing samples of a signal.
+ lamb : float, optional
+ Smoothing coefficient (must be zero for now).
+
+ Returns
+ -------
+ c : ndarray
+ Quadratic spline coefficients.
+
+ See Also
+ --------
+ qspline1d_eval : Evaluate a quadratic spline at the new set of points.
+
+ Notes
+ -----
+ Find the quadratic spline coefficients for a 1-D signal assuming
+ mirror-symmetric boundary conditions. To obtain the signal back from the
+ spline representation mirror-symmetric-convolve these coefficients with a
+ length 3 FIR window [1.0, 6.0, 1.0]/ 8.0 .
+
+ Examples
+ --------
+ We can filter a signal to reduce and smooth out high-frequency noise with
+ a quadratic spline:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import qspline1d, qspline1d_eval
+ >>> rng = np.random.default_rng()
+ >>> sig = np.repeat([0., 1., 0.], 100)
+ >>> sig += rng.standard_normal(len(sig))*0.05 # add noise
+ >>> time = np.linspace(0, len(sig))
+ >>> filtered = qspline1d_eval(qspline1d(sig), time)
+ >>> plt.plot(sig, label="signal")
+ >>> plt.plot(time, filtered, label="filtered")
+ >>> plt.legend()
+ >>> plt.show()
+
+ """
+ xp = array_namespace(signal)
+
+ if lamb != 0.0:
+ raise ValueError("Smoothing quadratic splines not supported yet.")
+ else:
+ return xp.asarray(_quadratic_coeff(signal))
+
+
+def collapse_2d(x, axis):
+ x = moveaxis(x, axis, -1)
+ x_shape = x.shape
+ x = x.reshape(-1, x.shape[-1])
+ if not x.flags.c_contiguous:
+ x = x.copy()
+ return x, x_shape
+
+
+def symiirorder_nd(func, input, *args, axis=-1, **kwargs):
+ axis = normalize_axis_index(axis, input.ndim)
+ input_shape = input.shape
+ input_ndim = input.ndim
+ if input.ndim > 1:
+ input, input_shape = collapse_2d(input, axis)
+
+ out = func(input, *args, **kwargs)
+
+ if input_ndim > 1:
+ out = out.reshape(input_shape)
+ out = moveaxis(out, -1, axis)
+ if not out.flags.c_contiguous:
+ out = out.copy()
+ return out
+
+
+def qspline2d(signal, lamb=0.0, precision=-1.0):
+ """
+ Coefficients for 2-D quadratic (2nd order) B-spline.
+
+ Return the second-order B-spline coefficients over a regularly spaced
+ input grid for the two-dimensional input image.
+
+ Parameters
+ ----------
+ input : ndarray
+ The input signal.
+ lamb : float
+ Specifies the amount of smoothing in the transfer function.
+ precision : float
+ Specifies the precision for computing the infinite sum needed to apply
+ mirror-symmetric boundary conditions.
+
+ Returns
+ -------
+ output : ndarray
+ The filtered signal.
+ """
+ if precision < 0.0 or precision >= 1.0:
+ if signal.dtype in [float32, complex64]:
+ precision = 1e-3
+ else:
+ precision = 1e-6
+
+ if lamb > 0:
+ raise ValueError('lambda must be negative or zero')
+
+ # normal quadratic spline
+ r = -3 + 2 * math.sqrt(2.0)
+ c0 = -r * 8.0
+ z1 = r
+
+ out = symiirorder_nd(symiirorder1, signal, c0, z1, precision, axis=-1)
+ out = symiirorder_nd(symiirorder1, out, c0, z1, precision, axis=0)
+ return out
+
+
+def cspline2d(signal, lamb=0.0, precision=-1.0):
+ """
+ Coefficients for 2-D cubic (3rd order) B-spline.
+
+ Return the third-order B-spline coefficients over a regularly spaced
+ input grid for the two-dimensional input image.
+
+ Parameters
+ ----------
+ input : ndarray
+ The input signal.
+ lamb : float
+ Specifies the amount of smoothing in the transfer function.
+ precision : float
+ Specifies the precision for computing the infinite sum needed to apply
+ mirror-symmetric boundary conditions.
+
+ Returns
+ -------
+ output : ndarray
+ The filtered signal.
+ """
+ xp = array_namespace(signal)
+ signal = np.asarray(signal)
+
+ if precision < 0.0 or precision >= 1.0:
+ if signal.dtype in [np.float32, np.complex64]:
+ precision = 1e-3
+ else:
+ precision = 1e-6
+
+ if lamb <= 1 / 144.0:
+ # Normal cubic spline
+ r = -2 + math.sqrt(3.0)
+ out = symiirorder_nd(
+ symiirorder1, signal, -r * 6.0, r, precision=precision, axis=-1)
+ out = symiirorder_nd(
+ symiirorder1, out, -r * 6.0, r, precision=precision, axis=0)
+ return out
+
+ r, omega = compute_root_from_lambda(lamb)
+ out = symiirorder_nd(symiirorder2, signal, r, omega,
+ precision=precision, axis=-1)
+ out = symiirorder_nd(symiirorder2, out, r, omega,
+ precision=precision, axis=0)
+ return xp.asarray(out)
+
+
+def cspline1d_eval(cj, newx, dx=1.0, x0=0):
+ """Evaluate a cubic spline at the new set of points.
+
+ `dx` is the old sample-spacing while `x0` was the old origin. In
+ other-words the old-sample points (knot-points) for which the `cj`
+ represent spline coefficients were at equally-spaced points of:
+
+ oldx = x0 + j*dx j=0...N-1, with N=len(cj)
+
+ Edges are handled using mirror-symmetric boundary conditions.
+
+ Parameters
+ ----------
+ cj : ndarray
+ cublic spline coefficients
+ newx : ndarray
+ New set of points.
+ dx : float, optional
+ Old sample-spacing, the default value is 1.0.
+ x0 : int, optional
+ Old origin, the default value is 0.
+
+ Returns
+ -------
+ res : ndarray
+ Evaluated a cubic spline points.
+
+ See Also
+ --------
+ cspline1d : Compute cubic spline coefficients for rank-1 array.
+
+ Examples
+ --------
+ We can filter a signal to reduce and smooth out high-frequency noise with
+ a cubic spline:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import cspline1d, cspline1d_eval
+ >>> rng = np.random.default_rng()
+ >>> sig = np.repeat([0., 1., 0.], 100)
+ >>> sig += rng.standard_normal(len(sig))*0.05 # add noise
+ >>> time = np.linspace(0, len(sig))
+ >>> filtered = cspline1d_eval(cspline1d(sig), time)
+ >>> plt.plot(sig, label="signal")
+ >>> plt.plot(time, filtered, label="filtered")
+ >>> plt.legend()
+ >>> plt.show()
+
+ """
+ xp = array_namespace(cj, newx)
+
+ newx = (np.asarray(newx) - x0) / float(dx)
+ cj = np.asarray(cj)
+
+ if cj.size == 0:
+ raise ValueError("Spline coefficients 'cj' must not be empty.")
+
+ res = zeros_like(newx, dtype=cj.dtype)
+ if res.size == 0:
+ return xp.asarray(res)
+ N = len(cj)
+ cond1 = newx < 0
+ cond2 = newx > (N - 1)
+ cond3 = ~(cond1 | cond2)
+ # handle general mirror-symmetry
+ res[cond1] = cspline1d_eval(cj, -newx[cond1])
+ res[cond2] = cspline1d_eval(cj, 2 * (N - 1) - newx[cond2])
+ newx = newx[cond3]
+ if newx.size == 0:
+ return xp.asarray(res)
+ result = zeros_like(newx, dtype=cj.dtype)
+ jlower = floor(newx - 2).astype(int) + 1
+ for i in range(4):
+ thisj = jlower + i
+ indj = thisj.clip(0, N - 1) # handle edge cases
+ result += cj[indj] * _cubic(newx - thisj)
+ res[cond3] = result
+ return xp.asarray(res)
+
+
+def qspline1d_eval(cj, newx, dx=1.0, x0=0):
+ """Evaluate a quadratic spline at the new set of points.
+
+ Parameters
+ ----------
+ cj : ndarray
+ Quadratic spline coefficients
+ newx : ndarray
+ New set of points.
+ dx : float, optional
+ Old sample-spacing, the default value is 1.0.
+ x0 : int, optional
+ Old origin, the default value is 0.
+
+ Returns
+ -------
+ res : ndarray
+ Evaluated a quadratic spline points.
+
+ See Also
+ --------
+ qspline1d : Compute quadratic spline coefficients for rank-1 array.
+
+ Notes
+ -----
+ `dx` is the old sample-spacing while `x0` was the old origin. In
+ other-words the old-sample points (knot-points) for which the `cj`
+ represent spline coefficients were at equally-spaced points of::
+
+ oldx = x0 + j*dx j=0...N-1, with N=len(cj)
+
+ Edges are handled using mirror-symmetric boundary conditions.
+
+ Examples
+ --------
+ We can filter a signal to reduce and smooth out high-frequency noise with
+ a quadratic spline:
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import qspline1d, qspline1d_eval
+ >>> rng = np.random.default_rng()
+ >>> sig = np.repeat([0., 1., 0.], 100)
+ >>> sig += rng.standard_normal(len(sig))*0.05 # add noise
+ >>> time = np.linspace(0, len(sig))
+ >>> filtered = qspline1d_eval(qspline1d(sig), time)
+ >>> plt.plot(sig, label="signal")
+ >>> plt.plot(time, filtered, label="filtered")
+ >>> plt.legend()
+ >>> plt.show()
+
+ """
+ xp = array_namespace(newx, cj)
+
+ newx = (np.asarray(newx) - x0) / dx
+ res = np.zeros_like(newx)
+ if res.size == 0:
+ return xp.asarray(res)
+
+ cj = np.asarray(cj)
+ if cj.size == 0:
+ raise ValueError("Spline coefficients 'cj' must not be empty.")
+
+ N = len(cj)
+ cond1 = newx < 0
+ cond2 = newx > (N - 1)
+ cond3 = ~(cond1 | cond2)
+ # handle general mirror-symmetry
+ res[cond1] = qspline1d_eval(cj, -newx[cond1])
+ res[cond2] = qspline1d_eval(cj, 2 * (N - 1) - newx[cond2])
+ newx = newx[cond3]
+ if newx.size == 0:
+ return xp.asarray(res)
+ result = zeros_like(newx)
+ jlower = floor(newx - 1.5).astype(int) + 1
+ for i in range(3):
+ thisj = jlower + i
+ indj = thisj.clip(0, N - 1) # handle edge cases
+ result += cj[indj] * _quadratic(newx - thisj)
+ res[cond3] = result
+ return xp.asarray(res)
+
+
+def symiirorder1(signal, c0, z1, precision=-1.0):
+ """
+ Implement a smoothing IIR filter with mirror-symmetric boundary conditions
+ using a cascade of first-order sections.
+
+ The second section uses a reversed sequence. This implements a system with
+ the following transfer function and mirror-symmetric boundary conditions::
+
+ c0
+ H(z) = ---------------------
+ (1-z1/z) (1 - z1 z)
+
+ The resulting signal will have mirror symmetric boundary conditions
+ as well.
+
+ Parameters
+ ----------
+ signal : ndarray
+ The input signal. If 2D, then the filter will be applied in a batched
+ fashion across the last axis.
+ c0, z1 : scalar
+ Parameters in the transfer function.
+ precision :
+ Specifies the precision for calculating initial conditions
+ of the recursive filter based on mirror-symmetric input.
+
+ Returns
+ -------
+ output : ndarray
+ The filtered signal.
+ """
+ xp = array_namespace(signal)
+ signal = xp_promote(signal, force_floating=True, xp=xp)
+ # This function uses C internals
+ signal = np.asarray(signal)
+
+ if abs(z1) >= 1:
+ raise ValueError('|z1| must be less than 1.0')
+
+ if signal.ndim > 2:
+ raise ValueError('Input must be 1D or 2D')
+
+ squeeze_dim = False
+ if signal.ndim == 1:
+ signal = signal[None, :]
+ squeeze_dim = True
+
+ y0 = symiirorder1_ic(signal, z1, precision)
+
+ # Apply first the system 1 / (1 - z1 * z^-1)
+ b = np.ones(1, dtype=signal.dtype)
+ a = np.r_[1, -z1]
+ a = a.astype(signal.dtype)
+
+ # Compute the initial state for lfilter.
+ zii = y0 * z1
+
+ y1, _ = lfilter(b, a, axis_slice(signal, 1), zi=zii)
+ y1 = np.c_[y0, y1]
+
+ # Compute backward symmetric condition and apply the system
+ # c0 / (1 - z1 * z)
+ b = np.asarray([c0], dtype=signal.dtype)
+ out_last = -c0 / (z1 - 1.0) * axis_slice(y1, -1)
+
+ # Compute the initial state for lfilter.
+ zii = out_last * z1
+
+ # Apply the system c0 / (1 - z1 * z) by reversing the output of the previous stage
+ out, _ = lfilter(b, a, axis_slice(y1, -2, step=-1), zi=zii)
+ out = np.c_[axis_reverse(out), out_last]
+
+ if squeeze_dim:
+ out = out[0]
+
+ return xp.asarray(out)
+
+
+def symiirorder2(input, r, omega, precision=-1.0):
+ """
+ Implement a smoothing IIR filter with mirror-symmetric boundary conditions
+ using a cascade of second-order sections.
+
+ The second section uses a reversed sequence. This implements the following
+ transfer function::
+
+ cs^2
+ H(z) = ---------------------------------------
+ (1 - a2/z - a3/z^2) (1 - a2 z - a3 z^2 )
+
+ where::
+
+ a2 = 2 * r * cos(omega)
+ a3 = - r ** 2
+ cs = 1 - 2 * r * cos(omega) + r ** 2
+
+ Parameters
+ ----------
+ input : ndarray
+ The input signal.
+ r, omega : float
+ Parameters in the transfer function.
+ precision : float
+ Specifies the precision for calculating initial conditions
+ of the recursive filter based on mirror-symmetric input.
+
+ Returns
+ -------
+ output : ndarray
+ The filtered signal.
+ """
+ xp = array_namespace(input)
+ input = xp_promote(input, force_floating=True, xp=xp)
+ # This function uses C internals
+ input = np.ascontiguousarray(input)
+
+ if r >= 1.0:
+ raise ValueError('r must be less than 1.0')
+
+ if input.ndim > 2:
+ raise ValueError('Input must be 1D or 2D')
+
+ squeeze_dim = False
+ if input.ndim == 1:
+ input = input[None, :]
+ squeeze_dim = True
+
+ rsq = r * r
+ a2 = 2 * r * math.cos(omega)
+ a3 = -rsq
+ cs = 1 - 2 * r * math.cos(omega) + rsq
+ sos = np.asarray([cs, 0, 0, 1, -a2, -a3], dtype=input.dtype)
+
+ # Find the starting (forward) conditions.
+ ic_fwd = symiirorder2_ic_fwd(input, r, omega, precision)
+
+ # Apply first the system cs / (1 - a2 * z^-1 - a3 * z^-2)
+ # Compute the initial conditions in the form expected by sosfilt
+ # coef = np.asarray([[a3, a2], [0, a3]], dtype=input.dtype)
+ coef = np.asarray([[a3, a2], [0, a3]], dtype=input.dtype)
+ zi = np.matmul(coef, ic_fwd[:, :, None])[:, :, 0]
+
+ y_fwd, _ = sosfilt(sos, axis_slice(input, 2), zi=zi[None])
+ y_fwd = np.c_[ic_fwd, y_fwd]
+
+ # Then compute the symmetric backward starting conditions
+ ic_bwd = symiirorder2_ic_bwd(input, r, omega, precision)
+
+ # Apply the system cs / (1 - a2 * z^1 - a3 * z^2)
+ # Compute the initial conditions in the form expected by sosfilt
+ zi = np.matmul(coef, ic_bwd[:, :, None])[:, :, 0]
+ y, _ = sosfilt(sos, axis_slice(y_fwd, -3, step=-1), zi=zi[None])
+ out = np.c_[axis_reverse(y), axis_reverse(ic_bwd)]
+
+ if squeeze_dim:
+ out = out[0]
+
+ return xp.asarray(out)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_support_alternative_backends.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_support_alternative_backends.py
new file mode 100644
index 0000000000000000000000000000000000000000..3ddeb10ab0829ae52cc98189bf9a6b5a299dd3e3
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_support_alternative_backends.py
@@ -0,0 +1,388 @@
+import functools
+import types
+from scipy._lib._array_api import (
+ is_cupy, is_jax, scipy_namespace_for, SCIPY_ARRAY_API, xp_capabilities
+)
+
+from ._signal_api import * # noqa: F403
+from . import _signal_api
+from . import _delegators
+__all__ = _signal_api.__all__
+
+
+MODULE_NAME = 'signal'
+
+# jax.scipy.signal has only partial coverage of scipy.signal, so we keep the list
+# of functions we can delegate to JAX
+# https://jax.readthedocs.io/en/latest/jax.scipy.html
+JAX_SIGNAL_FUNCS = [
+ 'fftconvolve', 'convolve', 'convolve2d', 'correlate', 'correlate2d',
+ 'csd', 'detrend', 'istft', 'welch'
+]
+
+# some cupyx.scipy.signal functions are incompatible with their scipy counterparts
+CUPY_BLACKLIST = [
+ 'lfilter_zi', 'sosfilt_zi', 'get_window', 'besselap', 'envelope', 'remez', 'bessel'
+]
+
+# freqz_sos is a sosfreqz rename, and cupy does not have the new name yet (in v13.x)
+CUPY_RENAMES = {'freqz_sos': 'sosfreqz'}
+
+
+def delegate_xp(delegator, module_name):
+ def inner(func):
+ @functools.wraps(func)
+ def wrapper(*args, **kwds):
+ try:
+ xp = delegator(*args, **kwds)
+ except TypeError:
+ # object arrays
+ if func.__name__ == "tf2ss":
+ import numpy as np
+ xp = np
+ else:
+ raise
+
+ # try delegating to a cupyx/jax namesake
+ if is_cupy(xp) and func.__name__ not in CUPY_BLACKLIST:
+ func_name = CUPY_RENAMES.get(func.__name__, func.__name__)
+
+ # 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)
+ kwds.pop('xp', None)
+ return cupyx_func(*args, **kwds)
+ elif is_jax(xp) and func.__name__ in JAX_SIGNAL_FUNCS:
+ spx = scipy_namespace_for(xp)
+ jax_module = getattr(spx, module_name)
+ jax_func = getattr(jax_module, func.__name__)
+ kwds.pop('xp', None)
+ return jax_func(*args, **kwds)
+ else:
+ # the original function
+ return func(*args, **kwds)
+ return wrapper
+ return inner
+
+
+# Although most of these functions currently exist in CuPy and some in JAX,
+# there are no alternative backend tests for any of them in the current
+# test suite. Each will be documented as np_only until tests are added.
+untested = {
+ "argrelextrema",
+ "argrelmax",
+ "argrelmin",
+ "band_stop_obj",
+ "check_NOLA",
+ "chirp",
+ "coherence",
+ "csd",
+ "czt_points",
+ "dbode",
+ "dfreqresp",
+ "dlsim",
+ "dstep",
+ "find_peaks",
+ "find_peaks_cwt",
+ "findfreqs",
+ "freqresp",
+ "gausspulse",
+ "lombscargle",
+ "lsim",
+ "max_len_seq",
+ "peak_prominences",
+ "peak_widths",
+ "periodogram",
+ "place_pols",
+ "sawtooth",
+ "sepfir2d",
+ "square",
+ "ss2tf",
+ "ss2zpk",
+ "step",
+ "sweep_poly",
+ "symiirorder1",
+ "symiirorder2",
+ "tf2ss",
+ "unit_impulse",
+ "welch",
+ "zoom_fft",
+ "zpk2ss",
+}
+
+
+def get_default_capabilities(func_name, delegator):
+ if delegator is None or func_name in untested:
+ return xp_capabilities(np_only=True)
+ return xp_capabilities()
+
+bilinear_extra_note = \
+ """CuPy does not accept complex inputs.
+
+ """
+
+uses_choose_conv_extra_note = \
+ """CuPy does not support inputs with ``ndim>1`` when ``method="auto"``
+ but does support higher dimensional arrays for ``method="direct"``
+ and ``method="fft"``.
+
+ """
+
+resample_poly_extra_note = \
+ """CuPy only supports ``padtype="constant"``.
+
+ """
+
+upfirdn_extra_note = \
+ """CuPy only supports ``mode="constant"`` and ``cval=0.0``.
+
+ """
+
+xord_extra_note = \
+ """The ``torch`` backend on GPU does not support the case where
+ `wp` and `ws` specify a Bandstop filter.
+
+ """
+
+convolve2d_extra_note = \
+ """The JAX backend only supports ``boundary="fill"`` and ``fillvalue=0``.
+
+ """
+
+zpk2tf_extra_note = \
+ """The CuPy and JAX backends both support only 1d input.
+
+ """
+
+capabilities_overrides = {
+ "bessel": xp_capabilities(cpu_only=True, jax_jit=False, allow_dask_compute=True),
+ "bilinear": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ jax_jit=False, allow_dask_compute=True,
+ reason="Uses np.polynomial.Polynomial",
+ extra_note=bilinear_extra_note),
+ "bilinear_zpk": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True),
+ "butter": xp_capabilities(cpu_only=True, exceptions=["cupy"], jax_jit=False,
+ allow_dask_compute=True),
+ "buttord": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True,
+ extra_note=xord_extra_note),
+ "cheb1ord": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True,
+ extra_note=xord_extra_note),
+ "cheb2ord": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True,
+ extra_note=xord_extra_note),
+ "cheby1": xp_capabilities(cpu_only=True, exceptions=["cupy"], jax_jit=False,
+ allow_dask_compute=True),
+
+ "cheby2": xp_capabilities(cpu_only=True, exceptions=["cupy"], jax_jit=False,
+ allow_dask_compute=True),
+ "cont2discrete": xp_capabilities(np_only=True, exceptions=["cupy"]),
+ "convolve": xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"],
+ allow_dask_compute=True,
+ extra_note=uses_choose_conv_extra_note),
+ "convolve2d": xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"],
+ allow_dask_compute=True,
+ extra_note=convolve2d_extra_note),
+ "correlate": xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"],
+ allow_dask_compute=True,
+ extra_note=uses_choose_conv_extra_note),
+ "correlate2d": xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"],
+ allow_dask_compute=True,
+ extra_note=convolve2d_extra_note),
+ "correlation_lags": xp_capabilities(out_of_scope=True),
+ "cspline1d": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ jax_jit=False, allow_dask_compute=True),
+ "cspline1d_eval": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ jax_jit=False, allow_dask_compute=True),
+ "cspline2d": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ jax_jit=False, allow_dask_compute=True),
+ "czt": xp_capabilities(np_only=True, exceptions=["cupy"]),
+ "deconvolve": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ allow_dask_compute=True,
+ skip_backends=[("jax.numpy", "item assignment")]),
+ "decimate": xp_capabilities(np_only=True, exceptions=["cupy"]),
+ "detrend": xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"],
+ allow_dask_compute=True),
+ "dimpulse": xp_capabilities(np_only=True, exceptions=["cupy"]),
+ "dlti": xp_capabilities(np_only=True,
+ reason="works in CuPy but delegation isn't set up yet"),
+ "ellip": xp_capabilities(cpu_only=True, exceptions=["cupy"], jax_jit=False,
+ allow_dask_compute=True,
+ reason="scipy.special.ellipk"),
+ "ellipord": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ jax_jit=False, allow_dask_compute=True,
+ reason="scipy.special.ellipk"),
+ "firls": xp_capabilities(cpu_only=True, allow_dask_compute=True, jax_jit=False,
+ reason="lstsq"),
+ "firwin": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True),
+ "firwin2": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ jax_jit=False, allow_dask_compute=True,
+ reason="firwin uses np.interp"),
+ "fftconvolve": xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"]),
+ "freqs": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True),
+ "freqs_zpk": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True),
+ "freqz": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True),
+ "freqz_sos": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True),
+ "group_delay": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ jax_jit=False, allow_dask_compute=True),
+ "hilbert": xp_capabilities(
+ cpu_only=True, exceptions=["cupy", "torch"],
+ skip_backends=[("jax.numpy", "item assignment")],
+ ),
+ "hilbert2": xp_capabilities(
+ cpu_only=True, exceptions=["cupy", "torch"],
+ skip_backends=[("jax.numpy", "item assignment")],
+ ),
+ "invres": xp_capabilities(np_only=True, exceptions=["cupy"]),
+ "invresz": xp_capabilities(np_only=True, exceptions=["cupy"]),
+ "iircomb": xp_capabilities(xfail_backends=[("jax.numpy", "inaccurate")]),
+ "iirfilter": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True),
+ "kaiser_atten": xp_capabilities(
+ out_of_scope=True, reason="scalars in, scalars out"
+ ),
+ "kaiser_beta": xp_capabilities(out_of_scope=True, reason="scalars in, scalars out"),
+ "kaiserord": xp_capabilities(out_of_scope=True, reason="scalars in, scalars out"),
+ "lfilter": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ allow_dask_compute=True, jax_jit=False),
+ "lfilter_zi": xp_capabilities(cpu_only=True, allow_dask_compute=True,
+ jax_jit=False),
+ "lfiltic": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ allow_dask_compute=True),
+ "lp2bp": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ allow_dask_compute=True,
+ skip_backends=[("jax.numpy", "in-place item assignment")]),
+ "lp2bp_zpk": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ allow_dask_compute=True, jax_jit=False),
+ "lp2bs": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ allow_dask_compute=True,
+ skip_backends=[("jax.numpy", "in-place item assignment")]),
+ "lp2bs_zpk": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ allow_dask_compute=True, jax_jit=False),
+ "lp2lp": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ allow_dask_compute=True, jax_jit=False),
+ "lp2lp_zpk": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ allow_dask_compute=True, jax_jit=False),
+ "lp2hp": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ allow_dask_compute=True,
+ skip_backends=[("jax.numpy", "in-place item assignment")]),
+ "lp2hp_zpk": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ allow_dask_compute=True, jax_jit=False),
+ "lti": xp_capabilities(np_only=True,
+ reason="works in CuPy but delegation isn't set up yet"),
+ "medfilt": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ allow_dask_compute=True, jax_jit=False,
+ reason="uses scipy.ndimage.rank_filter"),
+ "medfilt2d": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ allow_dask_compute=True, jax_jit=False,
+ reason="c extension module"),
+ "minimum_phase": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ allow_dask_compute=True, jax_jit=False),
+ "normalize": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True),
+ "oaconvolve": xp_capabilities(
+ cpu_only=True, exceptions=["cupy", "torch"],
+ skip_backends=[("jax.numpy", "fails all around")],
+ xfail_backends=[("dask.array", "wrong answer")],
+ ),
+ "order_filter": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ allow_dask_compute=True, jax_jit=False,
+ reason="uses scipy.ndimage.rank_filter"),
+ "qspline1d": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ jax_jit=False, allow_dask_compute=True),
+ "qspline1d_eval": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ jax_jit=False, allow_dask_compute=True),
+ "qspline2d": xp_capabilities(np_only=True, exceptions=["cupy"]),
+ "remez": xp_capabilities(cpu_only=True, allow_dask_compute=True, jax_jit=False),
+ "resample": xp_capabilities(
+ cpu_only=True, exceptions=["cupy"],
+ skip_backends=[
+ ("dask.array", "XXX something in dask"),
+ ("jax.numpy", "XXX: immutable arrays"),
+ ]
+ ),
+ "resample_poly": xp_capabilities(
+ cpu_only=True, exceptions=["cupy"],
+ jax_jit=False, skip_backends=[("dask.array", "XXX something in dask")],
+ extra_note=resample_poly_extra_note,
+ ),
+ "residue": xp_capabilities(np_only=True, exceptions=["cupy"]),
+ "residuez": xp_capabilities(np_only=True, exceptions=["cupy"]),
+ "savgol_filter": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ jax_jit=False,
+ reason="convolve1d is cpu-only"),
+ "sepfir2d": xp_capabilities(np_only=True),
+ "sos2zpk": xp_capabilities(cpu_only=True, exceptions=["cupy"], jax_jit=False,
+ allow_dask_compute=True),
+ "sos2tf": xp_capabilities(cpu_only=True, exceptions=["cupy"], jax_jit=False,
+ allow_dask_compute=True),
+ "sosfilt": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ allow_dask_compute=True),
+ "sosfiltfilt": xp_capabilities(
+ cpu_only=True, exceptions=["cupy"],
+ skip_backends=[
+ (
+ "dask.array",
+ "sosfiltfilt directly sets shape attributes on arrays"
+ " which dask doesn't like"
+ ),
+ ("torch", "negative strides"),
+ ("jax.numpy", "sosfilt works in-place"),
+ ],
+ ),
+ "sosfreqz": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ jax_jit=False, allow_dask_compute=True),
+ "spline_filter": xp_capabilities(cpu_only=True, exceptions=["cupy"],
+ jax_jit=False, allow_dask_compute=True),
+ "tf2sos": xp_capabilities(cpu_only=True, exceptions=["cupy"], jax_jit=False,
+ allow_dask_compute=True),
+ "tf2zpk": xp_capabilities(cpu_only=True, exceptions=["cupy"], jax_jit=False,
+ allow_dask_compute=True),
+ "unique_roots": xp_capabilities(np_only=True, exceptions=["cupy"]),
+ "upfirdn": xp_capabilities(cpu_only=True, exceptions=["cupy"], jax_jit=False,
+ allow_dask_compute=True,
+ reason="Cython implementation",
+ extra_note=upfirdn_extra_note),
+ "vectorstrength": xp_capabilities(cpu_only=True, exceptions=["cupy", "torch"],
+ allow_dask_compute=True, jax_jit=False),
+ "wiener": xp_capabilities(cpu_only=True, exceptions=["cupy", "jax.numpy"],
+ allow_dask_compute=True, jax_jit=False,
+ reason="uses scipy.signal.correlate"),
+ "zpk2sos": xp_capabilities(cpu_only=True, exceptions=["cupy"], jax_jit=False,
+ allow_dask_compute=True),
+ "zpk2tf": xp_capabilities(cpu_only=True, exceptions=["cupy"], jax_jit=False,
+ allow_dask_compute=True,
+ extra_note=zpk2tf_extra_note),
+ "spectrogram": xp_capabilities(out_of_scope=True), # legacy
+ "stft": xp_capabilities(out_of_scope=True), # legacy
+ "istft": xp_capabilities(out_of_scope=True), # legacy
+ "check_COLA": xp_capabilities(out_of_scope=True), # legacy
+}
+
+
+# ### decorate ###
+for obj_name in _signal_api.__all__:
+ bare_obj = getattr(_signal_api, obj_name)
+ delegator = getattr(_delegators, obj_name + "_signature", None)
+
+ if SCIPY_ARRAY_API and delegator is not None:
+ f = delegate_xp(delegator, MODULE_NAME)(bare_obj)
+ else:
+ f = bare_obj
+
+ if not isinstance(f, types.ModuleType):
+ capabilities = capabilities_overrides.get(
+ obj_name, get_default_capabilities(obj_name, delegator)
+ )
+ f = capabilities(f)
+
+ # add the decorated function to the namespace, to be imported in __init__.py
+ vars()[obj_name] = f
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_upfirdn.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_upfirdn.py
new file mode 100644
index 0000000000000000000000000000000000000000..d01a3a36b15c0172907a49afb16236cf75b565ab
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_upfirdn.py
@@ -0,0 +1,219 @@
+# Code adapted from "upfirdn" python library with permission:
+#
+# Copyright (c) 2009, Motorola, 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:
+#
+# * 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 Motorola 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 numpy as np
+
+from scipy._lib._array_api import array_namespace
+from ._upfirdn_apply import _output_len, _apply, mode_enum
+
+__all__ = ['upfirdn', '_output_len']
+
+_upfirdn_modes = [
+ 'constant', 'wrap', 'edge', 'smooth', 'symmetric', 'reflect',
+ 'antisymmetric', 'antireflect', 'line',
+]
+
+
+def _pad_h(h, up):
+ """Store coefficients in a transposed, flipped arrangement.
+
+ For example, suppose upRate is 3, and the
+ input number of coefficients is 10, represented as h[0], ..., h[9].
+
+ Then the internal buffer will look like this::
+
+ h[9], h[6], h[3], h[0], // flipped phase 0 coefs
+ 0, h[7], h[4], h[1], // flipped phase 1 coefs (zero-padded)
+ 0, h[8], h[5], h[2], // flipped phase 2 coefs (zero-padded)
+
+ """
+ h_padlen = len(h) + (-len(h) % up)
+ h_full = np.zeros(h_padlen, h.dtype)
+ h_full[:len(h)] = h
+ h_full = h_full.reshape(-1, up).T[:, ::-1].ravel()
+ return h_full
+
+
+def _check_mode(mode):
+ mode = mode.lower()
+ enum = mode_enum(mode)
+ return enum
+
+
+class _UpFIRDn:
+ """Helper for resampling."""
+
+ def __init__(self, h, x_dtype, up, down):
+ h = np.asarray(h)
+ if h.ndim != 1 or h.size == 0:
+ raise ValueError('h must be 1-D with non-zero length')
+ self._output_type = np.result_type(h.dtype, x_dtype, np.float32)
+ h = np.asarray(h, self._output_type)
+ self._up = int(up)
+ self._down = int(down)
+ if self._up < 1 or self._down < 1:
+ raise ValueError('Both up and down must be >= 1')
+ # This both transposes, and "flips" each phase for filtering
+ self._h_trans_flip = _pad_h(h, self._up)
+ self._h_trans_flip = np.ascontiguousarray(self._h_trans_flip)
+ self._h_len_orig = len(h)
+
+ def apply_filter(self, x, axis=-1, mode='constant', cval=0):
+ """Apply the prepared filter to the specified axis of N-D signal x."""
+ output_len = _output_len(self._h_len_orig, x.shape[axis],
+ self._up, self._down)
+ # Explicit use of np.int64 for output_shape dtype avoids OverflowError
+ # when allocating large array on platforms where intp is 32 bits.
+ output_shape = np.asarray(x.shape, dtype=np.int64)
+ output_shape[axis] = output_len
+ out = np.zeros(output_shape, dtype=self._output_type, order='C')
+ axis = axis % x.ndim
+ mode = _check_mode(mode)
+ _apply(np.asarray(x, self._output_type),
+ self._h_trans_flip, out,
+ self._up, self._down, axis, mode, cval)
+ return out
+
+
+def upfirdn(h, x, up=1, down=1, axis=-1, mode='constant', cval=0):
+ """Upsample, FIR filter, and downsample.
+
+ Parameters
+ ----------
+ h : array_like
+ 1-D FIR (finite-impulse response) filter coefficients.
+ x : array_like
+ Input signal array.
+ up : int, optional
+ Upsampling rate. Default is 1.
+ down : int, optional
+ Downsampling rate. Default is 1.
+ axis : int, optional
+ The axis of the input data array along which to apply the
+ linear filter. The filter is applied to each subarray along
+ this axis. Default is -1.
+ mode : str, optional
+ The signal extension mode to use. The set
+ ``{"constant", "symmetric", "reflect", "edge", "wrap"}`` correspond to
+ modes provided by `numpy.pad`. ``"smooth"`` implements a smooth
+ extension by extending based on the slope of the last 2 points at each
+ end of the array. ``"antireflect"`` and ``"antisymmetric"`` are
+ anti-symmetric versions of ``"reflect"`` and ``"symmetric"``. The mode
+ `"line"` extends the signal based on a linear trend defined by the
+ first and last points along the ``axis``.
+
+ .. versionadded:: 1.4.0
+ cval : float, optional
+ The constant value to use when ``mode == "constant"``.
+
+ .. versionadded:: 1.4.0
+
+ Returns
+ -------
+ y : ndarray
+ The output signal array. Dimensions will be the same as `x` except
+ for along `axis`, which will change size according to the `h`,
+ `up`, and `down` parameters.
+
+ Notes
+ -----
+ The algorithm is an implementation of the block diagram shown on page 129
+ of the Vaidyanathan text [1]_ (Figure 4.3-8d).
+
+ The direct approach of upsampling by factor of P with zero insertion,
+ FIR filtering of length ``N``, and downsampling by factor of Q is
+ O(N*Q) per output sample. The polyphase implementation used here is
+ O(N/P).
+
+ .. versionadded:: 0.18
+
+ References
+ ----------
+ .. [1] P. P. Vaidyanathan, Multirate Systems and Filter Banks,
+ Prentice Hall, 1993.
+
+ Examples
+ --------
+ Simple operations:
+
+ >>> import numpy as np
+ >>> from scipy.signal import upfirdn
+ >>> upfirdn([1, 1, 1], [1, 1, 1]) # FIR filter
+ array([ 1., 2., 3., 2., 1.])
+ >>> upfirdn([1], [1, 2, 3], 3) # upsampling with zeros insertion
+ array([ 1., 0., 0., 2., 0., 0., 3.])
+ >>> upfirdn([1, 1, 1], [1, 2, 3], 3) # upsampling with sample-and-hold
+ array([ 1., 1., 1., 2., 2., 2., 3., 3., 3.])
+ >>> upfirdn([.5, 1, .5], [1, 1, 1], 2) # linear interpolation
+ array([ 0.5, 1. , 1. , 1. , 1. , 1. , 0.5])
+ >>> upfirdn([1], np.arange(10), 1, 3) # decimation by 3
+ array([ 0., 3., 6., 9.])
+ >>> upfirdn([.5, 1, .5], np.arange(10), 2, 3) # linear interp, rate 2/3
+ array([ 0. , 1. , 2.5, 4. , 5.5, 7. , 8.5])
+
+ Apply a single filter to multiple signals:
+
+ >>> x = np.reshape(np.arange(8), (4, 2))
+ >>> x
+ array([[0, 1],
+ [2, 3],
+ [4, 5],
+ [6, 7]])
+
+ Apply along the last dimension of ``x``:
+
+ >>> h = [1, 1]
+ >>> upfirdn(h, x, 2)
+ array([[ 0., 0., 1., 1.],
+ [ 2., 2., 3., 3.],
+ [ 4., 4., 5., 5.],
+ [ 6., 6., 7., 7.]])
+
+ Apply along the 0th dimension of ``x``:
+
+ >>> upfirdn(h, x, 2, axis=0)
+ array([[ 0., 1.],
+ [ 0., 1.],
+ [ 2., 3.],
+ [ 2., 3.],
+ [ 4., 5.],
+ [ 4., 5.],
+ [ 6., 7.],
+ [ 6., 7.]])
+ """
+ xp = array_namespace(h, x)
+
+ x = np.asarray(x)
+ ufd = _UpFIRDn(h, x.dtype, up, down)
+ # This is equivalent to (but faster than) using np.apply_along_axis
+ return xp.asarray(ufd.apply_filter(x, axis, mode, cval))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_upfirdn_apply.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_upfirdn_apply.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..1dffab8b105b1c9eab9aa2d2b7de856752393d68
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_upfirdn_apply.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:0dcac4b2879ba90af26172809c08e66c1297af74116e37afc8e63955d10b9d37
+size 184968
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_waveforms.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_waveforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..2867a55cdd3fa8eed9da591b10d0b02651a832c0
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_waveforms.py
@@ -0,0 +1,687 @@
+# Author: Travis Oliphant
+# 2003
+#
+# Feb. 2010: Updated by Warren Weckesser:
+# Rewrote much of chirp()
+# Added sweep_poly()
+import numpy as np
+from numpy import asarray, zeros, place, nan, mod, pi, extract, log, sqrt, \
+ exp, cos, sin, polyval, polyint
+
+
+__all__ = ['sawtooth', 'square', 'gausspulse', 'chirp', 'sweep_poly',
+ 'unit_impulse']
+
+
+def sawtooth(t, width=1):
+ """
+ Return a periodic sawtooth or triangle waveform.
+
+ The sawtooth waveform has a period ``2*pi``, rises from -1 to 1 on the
+ interval 0 to ``width*2*pi``, then drops from 1 to -1 on the interval
+ ``width*2*pi`` to ``2*pi``. `width` must be in the interval [0, 1].
+
+ Note that this is not band-limited. It produces an infinite number
+ of harmonics, which are aliased back and forth across the frequency
+ spectrum.
+
+ Parameters
+ ----------
+ t : array_like
+ Time.
+ width : array_like, optional
+ Width of the rising ramp as a proportion of the total cycle.
+ Default is 1, producing a rising ramp, while 0 produces a falling
+ ramp. `width` = 0.5 produces a triangle wave.
+ If an array, causes wave shape to change over time, and must be the
+ same length as t.
+
+ Returns
+ -------
+ y : ndarray
+ Output array containing the sawtooth waveform.
+
+ Examples
+ --------
+ A 5 Hz waveform sampled at 500 Hz for 1 second:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> t = np.linspace(0, 1, 500)
+ >>> plt.plot(t, signal.sawtooth(2 * np.pi * 5 * t))
+
+ """
+ t, w = asarray(t), asarray(width)
+ w = asarray(w + (t - t))
+ t = asarray(t + (w - w))
+ y = zeros(t.shape, dtype="d")
+
+ # width must be between 0 and 1 inclusive
+ mask1 = (w > 1) | (w < 0)
+ place(y, mask1, nan)
+
+ # take t modulo 2*pi
+ tmod = mod(t, 2 * pi)
+
+ # on the interval 0 to width*2*pi function is
+ # tmod / (pi*w) - 1
+ mask2 = (1 - mask1) & (tmod < w * 2 * pi)
+ tsub = extract(mask2, tmod)
+ wsub = extract(mask2, w)
+ place(y, mask2, tsub / (pi * wsub) - 1)
+
+ # on the interval width*2*pi to 2*pi function is
+ # (pi*(w+1)-tmod) / (pi*(1-w))
+
+ mask3 = (1 - mask1) & (1 - mask2)
+ tsub = extract(mask3, tmod)
+ wsub = extract(mask3, w)
+ place(y, mask3, (pi * (wsub + 1) - tsub) / (pi * (1 - wsub)))
+ return y
+
+
+def square(t, duty=0.5):
+ """
+ Return a periodic square-wave waveform.
+
+ The square wave has a period ``2*pi``, has value +1 from 0 to
+ ``2*pi*duty`` and -1 from ``2*pi*duty`` to ``2*pi``. `duty` must be in
+ the interval [0,1].
+
+ Note that this is not band-limited. It produces an infinite number
+ of harmonics, which are aliased back and forth across the frequency
+ spectrum.
+
+ Parameters
+ ----------
+ t : array_like
+ The input time array.
+ duty : array_like, optional
+ Duty cycle. Default is 0.5 (50% duty cycle).
+ If an array, causes wave shape to change over time, and must be the
+ same length as t.
+
+ Returns
+ -------
+ y : ndarray
+ Output array containing the square waveform.
+
+ Examples
+ --------
+ A 5 Hz waveform sampled at 500 Hz for 1 second:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> t = np.linspace(0, 1, 500, endpoint=False)
+ >>> plt.plot(t, signal.square(2 * np.pi * 5 * t))
+ >>> plt.ylim(-2, 2)
+
+ A pulse-width modulated sine wave:
+
+ >>> plt.figure()
+ >>> sig = np.sin(2 * np.pi * t)
+ >>> pwm = signal.square(2 * np.pi * 30 * t, duty=(sig + 1)/2)
+ >>> plt.subplot(2, 1, 1)
+ >>> plt.plot(t, sig)
+ >>> plt.subplot(2, 1, 2)
+ >>> plt.plot(t, pwm)
+ >>> plt.ylim(-1.5, 1.5)
+
+ """
+ t, w = asarray(t), asarray(duty)
+ w = asarray(w + (t - t))
+ t = asarray(t + (w - w))
+ y = zeros(t.shape, dtype="d")
+
+ # width must be between 0 and 1 inclusive
+ mask1 = (w > 1) | (w < 0)
+ place(y, mask1, nan)
+
+ # on the interval 0 to duty*2*pi function is 1
+ tmod = mod(t, 2 * pi)
+ mask2 = (1 - mask1) & (tmod < w * 2 * pi)
+ place(y, mask2, 1)
+
+ # on the interval duty*2*pi to 2*pi function is
+ # (pi*(w+1)-tmod) / (pi*(1-w))
+ mask3 = (1 - mask1) & (1 - mask2)
+ place(y, mask3, -1)
+ return y
+
+
+def gausspulse(t, fc=1000, bw=0.5, bwr=-6, tpr=-60, retquad=False,
+ retenv=False):
+ """
+ Return a Gaussian modulated sinusoid:
+
+ ``exp(-a t^2) exp(1j*2*pi*fc*t).``
+
+ If `retquad` is True, then return the real and imaginary parts
+ (in-phase and quadrature).
+ If `retenv` is True, then return the envelope (unmodulated signal).
+ Otherwise, return the real part of the modulated sinusoid.
+
+ Parameters
+ ----------
+ t : ndarray or the string 'cutoff'
+ Input array.
+ fc : float, optional
+ Center frequency (e.g. Hz). Default is 1000.
+ bw : float, optional
+ Fractional bandwidth in frequency domain of pulse (e.g. Hz).
+ Default is 0.5.
+ bwr : float, optional
+ Reference level at which fractional bandwidth is calculated (dB).
+ Default is -6.
+ tpr : float, optional
+ If `t` is 'cutoff', then the function returns the cutoff
+ time for when the pulse amplitude falls below `tpr` (in dB).
+ Default is -60.
+ retquad : bool, optional
+ If True, return the quadrature (imaginary) as well as the real part
+ of the signal. Default is False.
+ retenv : bool, optional
+ If True, return the envelope of the signal. Default is False.
+
+ Returns
+ -------
+ yI : ndarray
+ Real part of signal. Always returned.
+ yQ : ndarray
+ Imaginary part of signal. Only returned if `retquad` is True.
+ yenv : ndarray
+ Envelope of signal. Only returned if `retenv` is True.
+
+ Examples
+ --------
+ Plot real component, imaginary component, and envelope for a 5 Hz pulse,
+ sampled at 100 Hz for 2 seconds:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> t = np.linspace(-1, 1, 2 * 100, endpoint=False)
+ >>> i, q, e = signal.gausspulse(t, fc=5, retquad=True, retenv=True)
+ >>> plt.plot(t, i, t, q, t, e, '--')
+
+ """
+ if fc < 0:
+ raise ValueError(f"Center frequency (fc={fc:.2f}) must be >=0.")
+ if bw <= 0:
+ raise ValueError(f"Fractional bandwidth (bw={bw:.2f}) must be > 0.")
+ if bwr >= 0:
+ raise ValueError(f"Reference level for bandwidth (bwr={bwr:.2f}) "
+ "must be < 0 dB")
+
+ # exp(-a t^2) <-> sqrt(pi/a) exp(-pi^2/a * f^2) = g(f)
+
+ ref = pow(10.0, bwr / 20.0)
+ # fdel = fc*bw/2: g(fdel) = ref --- solve this for a
+ #
+ # pi^2/a * fc^2 * bw^2 /4=-log(ref)
+ a = -(pi * fc * bw) ** 2 / (4.0 * log(ref))
+
+ if isinstance(t, str):
+ if t == 'cutoff': # compute cut_off point
+ # Solve exp(-a tc**2) = tref for tc
+ # tc = sqrt(-log(tref) / a) where tref = 10^(tpr/20)
+ if tpr >= 0:
+ raise ValueError("Reference level for time cutoff must "
+ "be < 0 dB")
+ tref = pow(10.0, tpr / 20.0)
+ return sqrt(-log(tref) / a)
+ else:
+ raise ValueError("If `t` is a string, it must be 'cutoff'")
+
+ yenv = exp(-a * t * t)
+ yI = yenv * cos(2 * pi * fc * t)
+ yQ = yenv * sin(2 * pi * fc * t)
+ if not retquad and not retenv:
+ return yI
+ if not retquad and retenv:
+ return yI, yenv
+ if retquad and not retenv:
+ return yI, yQ
+ if retquad and retenv:
+ return yI, yQ, yenv
+
+
+def chirp(t, f0, t1, f1, method='linear', phi=0, vertex_zero=True, *,
+ complex=False):
+ r"""Frequency-swept cosine generator.
+
+ In the following, 'Hz' should be interpreted as 'cycles per unit';
+ there is no requirement here that the unit is one second. The
+ important distinction is that the units of rotation are cycles, not
+ radians. Likewise, `t` could be a measurement of space instead of time.
+
+ Parameters
+ ----------
+ t : array_like
+ Times at which to evaluate the waveform.
+ f0 : float
+ Frequency (e.g. Hz) at time t=0.
+ t1 : float
+ Time at which `f1` is specified.
+ f1 : float
+ Frequency (e.g. Hz) of the waveform at time `t1`.
+ method : {'linear', 'quadratic', 'logarithmic', 'hyperbolic'}, optional
+ Kind of frequency sweep. If not given, `linear` is assumed. See
+ Notes below for more details.
+ phi : float, optional
+ Phase offset, in degrees. Default is 0.
+ vertex_zero : bool, optional
+ This parameter is only used when `method` is 'quadratic'.
+ It determines whether the vertex of the parabola that is the graph
+ of the frequency is at t=0 or t=t1.
+ complex : bool, optional
+ This parameter creates a complex-valued analytic signal instead of a
+ real-valued signal. It allows the use of complex baseband (in communications
+ domain). Default is False.
+
+ .. versionadded:: 1.15.0
+
+ Returns
+ -------
+ y : ndarray
+ A numpy array containing the signal evaluated at `t` with the requested
+ time-varying frequency. More precisely, the function returns
+ ``exp(1j*phase + 1j*(pi/180)*phi) if complex else cos(phase + (pi/180)*phi)``
+ where `phase` is the integral (from 0 to `t`) of ``2*pi*f(t)``.
+ The instantaneous frequency ``f(t)`` is defined below.
+
+ See Also
+ --------
+ sweep_poly
+
+ Notes
+ -----
+ There are four possible options for the parameter `method`, which have a (long)
+ standard form and some allowed abbreviations. The formulas for the instantaneous
+ frequency :math:`f(t)` of the generated signal are as follows:
+
+ 1. Parameter `method` in ``('linear', 'lin', 'li')``:
+
+ .. math::
+ f(t) = f_0 + \beta\, t \quad\text{with}\quad
+ \beta = \frac{f_1 - f_0}{t_1}
+
+ Frequency :math:`f(t)` varies linearly over time with a constant rate
+ :math:`\beta`.
+
+ 2. Parameter `method` in ``('quadratic', 'quad', 'q')``:
+
+ .. math::
+ f(t) =
+ \begin{cases}
+ f_0 + \beta\, t^2 & \text{if vertex_zero is True,}\\
+ f_1 + \beta\, (t_1 - t)^2 & \text{otherwise,}
+ \end{cases}
+ \quad\text{with}\quad
+ \beta = \frac{f_1 - f_0}{t_1^2}
+
+ The graph of the frequency f(t) is a parabola through :math:`(0, f_0)` and
+ :math:`(t_1, f_1)`. By default, the vertex of the parabola is at
+ :math:`(0, f_0)`. If `vertex_zero` is ``False``, then the vertex is at
+ :math:`(t_1, f_1)`.
+ To use a more general quadratic function, or an arbitrary
+ polynomial, use the function `scipy.signal.sweep_poly`.
+
+ 3. Parameter `method` in ``('logarithmic', 'log', 'lo')``:
+
+ .. math::
+ f(t) = f_0 \left(\frac{f_1}{f_0}\right)^{t/t_1}
+
+ :math:`f_0` and :math:`f_1` must be nonzero and have the same sign.
+ This signal is also known as a geometric or exponential chirp.
+
+ 4. Parameter `method` in ``('hyperbolic', 'hyp')``:
+
+ .. math::
+ f(t) = \frac{\alpha}{\beta\, t + \gamma} \quad\text{with}\quad
+ \alpha = f_0 f_1 t_1, \ \beta = f_0 - f_1, \ \gamma = f_1 t_1
+
+ :math:`f_0` and :math:`f_1` must be nonzero.
+
+
+ Examples
+ --------
+ For the first example, a linear chirp ranging from 6 Hz to 1 Hz over 10 seconds is
+ plotted:
+
+ >>> import numpy as np
+ >>> from matplotlib.pyplot import tight_layout
+ >>> from scipy.signal import chirp, square, ShortTimeFFT
+ >>> from scipy.signal.windows import gaussian
+ >>> import matplotlib.pyplot as plt
+ ...
+ >>> N, T = 1000, 0.01 # number of samples and sampling interval for 10 s signal
+ >>> t = np.arange(N) * T # timestamps
+ ...
+ >>> x_lin = chirp(t, f0=6, f1=1, t1=10, method='linear')
+ ...
+ >>> fg0, ax0 = plt.subplots()
+ >>> ax0.set_title(r"Linear Chirp from $f(0)=6\,$Hz to $f(10)=1\,$Hz")
+ >>> ax0.set(xlabel="Time $t$ in Seconds", ylabel=r"Amplitude $x_\text{lin}(t)$")
+ >>> ax0.plot(t, x_lin)
+ >>> plt.show()
+
+ The following four plots each show the short-time Fourier transform of a chirp
+ ranging from 45 Hz to 5 Hz with different values for the parameter `method`
+ (and `vertex_zero`):
+
+ >>> x_qu0 = chirp(t, f0=45, f1=5, t1=N*T, method='quadratic', vertex_zero=True)
+ >>> x_qu1 = chirp(t, f0=45, f1=5, t1=N*T, method='quadratic', vertex_zero=False)
+ >>> x_log = chirp(t, f0=45, f1=5, t1=N*T, method='logarithmic')
+ >>> x_hyp = chirp(t, f0=45, f1=5, t1=N*T, method='hyperbolic')
+ ...
+ >>> win = gaussian(50, std=12, sym=True)
+ >>> SFT = ShortTimeFFT(win, hop=2, fs=1/T, mfft=800, scale_to='magnitude')
+ >>> ts = ("'quadratic', vertex_zero=True", "'quadratic', vertex_zero=False",
+ ... "'logarithmic'", "'hyperbolic'")
+ >>> fg1, ax1s = plt.subplots(2, 2, sharex='all', sharey='all',
+ ... figsize=(6, 5), layout="constrained")
+ >>> for x_, ax_, t_ in zip([x_qu0, x_qu1, x_log, x_hyp], ax1s.ravel(), ts):
+ ... aSx = abs(SFT.stft(x_))
+ ... im_ = ax_.imshow(aSx, origin='lower', aspect='auto', extent=SFT.extent(N),
+ ... cmap='plasma')
+ ... ax_.set_title(t_)
+ ... if t_ == "'hyperbolic'":
+ ... fg1.colorbar(im_, ax=ax1s, label='Magnitude $|S_z(t,f)|$')
+ >>> _ = fg1.supxlabel("Time $t$ in Seconds") # `_ =` is needed to pass doctests
+ >>> _ = fg1.supylabel("Frequency $f$ in Hertz")
+ >>> plt.show()
+
+ Finally, the short-time Fourier transform of a complex-valued linear chirp
+ ranging from -30 Hz to 30 Hz is depicted:
+
+ >>> z_lin = chirp(t, f0=-30, f1=30, t1=N*T, method="linear", complex=True)
+ >>> SFT.fft_mode = 'centered' # needed to work with complex signals
+ >>> aSz = abs(SFT.stft(z_lin))
+ ...
+ >>> fg2, ax2 = plt.subplots()
+ >>> ax2.set_title(r"Linear Chirp from $-30\,$Hz to $30\,$Hz")
+ >>> ax2.set(xlabel="Time $t$ in Seconds", ylabel="Frequency $f$ in Hertz")
+ >>> im2 = ax2.imshow(aSz, origin='lower', aspect='auto',
+ ... extent=SFT.extent(N), cmap='viridis')
+ >>> fg2.colorbar(im2, label='Magnitude $|S_z(t,f)|$')
+ >>> plt.show()
+
+ Note that using negative frequencies makes only sense with complex-valued signals.
+ Furthermore, the magnitude of the complex exponential function is one whereas the
+ magnitude of the real-valued cosine function is only 1/2.
+ """
+ # 'phase' is computed in _chirp_phase, to make testing easier.
+ phase = _chirp_phase(t, f0, t1, f1, method, vertex_zero) + np.deg2rad(phi)
+ return np.exp(1j*phase) if complex else np.cos(phase)
+
+
+def _chirp_phase(t, f0, t1, f1, method='linear', vertex_zero=True):
+ """
+ Calculate the phase used by `chirp` to generate its output.
+
+ See `chirp` for a description of the arguments.
+
+ """
+ t = asarray(t)
+ f0 = float(f0)
+ t1 = float(t1)
+ f1 = float(f1)
+ if method in ['linear', 'lin', 'li']:
+ beta = (f1 - f0) / t1
+ phase = 2 * pi * (f0 * t + 0.5 * beta * t * t)
+
+ elif method in ['quadratic', 'quad', 'q']:
+ beta = (f1 - f0) / (t1 ** 2)
+ if vertex_zero:
+ phase = 2 * pi * (f0 * t + beta * t ** 3 / 3)
+ else:
+ phase = 2 * pi * (f1 * t + beta * ((t1 - t) ** 3 - t1 ** 3) / 3)
+
+ elif method in ['logarithmic', 'log', 'lo']:
+ if f0 * f1 <= 0.0:
+ raise ValueError("For a logarithmic chirp, f0 and f1 must be "
+ "nonzero and have the same sign.")
+ if f0 == f1:
+ phase = 2 * pi * f0 * t
+ else:
+ beta = t1 / log(f1 / f0)
+ phase = 2 * pi * beta * f0 * (pow(f1 / f0, t / t1) - 1.0)
+
+ elif method in ['hyperbolic', 'hyp']:
+ if f0 == 0 or f1 == 0:
+ raise ValueError("For a hyperbolic chirp, f0 and f1 must be "
+ "nonzero.")
+ if f0 == f1:
+ # Degenerate case: constant frequency.
+ phase = 2 * pi * f0 * t
+ else:
+ # Singular point: the instantaneous frequency blows up
+ # when t == sing.
+ sing = -f1 * t1 / (f0 - f1)
+ phase = 2 * pi * (-sing * f0) * log(np.abs(1 - t/sing))
+
+ else:
+ raise ValueError("method must be 'linear', 'quadratic', 'logarithmic', "
+ f"or 'hyperbolic', but a value of {method!r} was given.")
+
+ return phase
+
+
+def sweep_poly(t, poly, phi=0):
+ """
+ Frequency-swept cosine generator, with a time-dependent frequency.
+
+ This function generates a sinusoidal function whose instantaneous
+ frequency varies with time. The frequency at time `t` is given by
+ the polynomial `poly`.
+
+ Parameters
+ ----------
+ t : ndarray
+ Times at which to evaluate the waveform.
+ poly : 1-D array_like or instance of numpy.poly1d
+ The desired frequency expressed as a polynomial. If `poly` is
+ a list or ndarray of length n, then the elements of `poly` are
+ the coefficients of the polynomial, and the instantaneous
+ frequency is
+
+ ``f(t) = poly[0]*t**(n-1) + poly[1]*t**(n-2) + ... + poly[n-1]``
+
+ If `poly` is an instance of numpy.poly1d, then the
+ instantaneous frequency is
+
+ ``f(t) = poly(t)``
+
+ phi : float, optional
+ Phase offset, in degrees, Default: 0.
+
+ Returns
+ -------
+ sweep_poly : ndarray
+ A numpy array containing the signal evaluated at `t` with the
+ requested time-varying frequency. More precisely, the function
+ returns ``cos(phase + (pi/180)*phi)``, where `phase` is the integral
+ (from 0 to t) of ``2 * pi * f(t)``; ``f(t)`` is defined above.
+
+ See Also
+ --------
+ chirp
+
+ Notes
+ -----
+ .. versionadded:: 0.8.0
+
+ If `poly` is a list or ndarray of length `n`, then the elements of
+ `poly` are the coefficients of the polynomial, and the instantaneous
+ frequency is:
+
+ ``f(t) = poly[0]*t**(n-1) + poly[1]*t**(n-2) + ... + poly[n-1]``
+
+ If `poly` is an instance of `numpy.poly1d`, then the instantaneous
+ frequency is:
+
+ ``f(t) = poly(t)``
+
+ Finally, the output `s` is:
+
+ ``cos(phase + (pi/180)*phi)``
+
+ where `phase` is the integral from 0 to `t` of ``2 * pi * f(t)``,
+ ``f(t)`` as defined above.
+
+ Examples
+ --------
+ Compute the waveform with instantaneous frequency::
+
+ f(t) = 0.025*t**3 - 0.36*t**2 + 1.25*t + 2
+
+ over the interval 0 <= t <= 10.
+
+ >>> import numpy as np
+ >>> from scipy.signal import sweep_poly
+ >>> p = np.poly1d([0.025, -0.36, 1.25, 2.0])
+ >>> t = np.linspace(0, 10, 5001)
+ >>> w = sweep_poly(t, p)
+
+ Plot it:
+
+ >>> import matplotlib.pyplot as plt
+ >>> plt.subplot(2, 1, 1)
+ >>> plt.plot(t, w)
+ >>> plt.title("Sweep Poly\\nwith frequency " +
+ ... "$f(t) = 0.025t^3 - 0.36t^2 + 1.25t + 2$")
+ >>> plt.subplot(2, 1, 2)
+ >>> plt.plot(t, p(t), 'r', label='f(t)')
+ >>> plt.legend()
+ >>> plt.xlabel('t')
+ >>> plt.tight_layout()
+ >>> plt.show()
+
+ """
+ # 'phase' is computed in _sweep_poly_phase, to make testing easier.
+ phase = _sweep_poly_phase(t, poly)
+ # Convert to radians.
+ phi *= pi / 180
+ return cos(phase + phi)
+
+
+def _sweep_poly_phase(t, poly):
+ """
+ Calculate the phase used by sweep_poly to generate its output.
+
+ See `sweep_poly` for a description of the arguments.
+
+ """
+ # polyint handles lists, ndarrays and instances of poly1d automatically.
+ intpoly = polyint(poly)
+ phase = 2 * pi * polyval(intpoly, t)
+ return phase
+
+
+def unit_impulse(shape, idx=None, dtype=float):
+ r"""
+ Unit impulse signal (discrete delta function) or unit basis vector.
+
+ Parameters
+ ----------
+ shape : int or tuple of int
+ Number of samples in the output (1-D), or a tuple that represents the
+ shape of the output (N-D).
+ idx : None or int or tuple of int or 'mid', optional
+ Index at which the value is 1. If None, defaults to the 0th element.
+ If ``idx='mid'``, the impulse will be centered at ``shape // 2`` in
+ all dimensions. If an int, the impulse will be at `idx` in all
+ dimensions.
+ dtype : data-type, optional
+ The desired data-type for the array, e.g., ``numpy.int8``. Default is
+ ``numpy.float64``.
+
+ Returns
+ -------
+ y : ndarray
+ Output array containing an impulse signal.
+
+ Notes
+ -----
+ In digital signal processing literature the unit impulse signal is often
+ represented by the Kronecker delta. [1]_ I.e., a signal :math:`u_k[n]`,
+ which is zero everywhere except being one at the :math:`k`-th sample,
+ can be expressed as
+
+ .. math::
+
+ u_k[n] = \delta[n-k] \equiv \delta_{n,k}\ .
+
+ Furthermore, the unit impulse is frequently interpreted as the discrete-time
+ version of the continuous-time Dirac distribution. [2]_
+
+ References
+ ----------
+ .. [1] "Kronecker delta", *Wikipedia*,
+ https://en.wikipedia.org/wiki/Kronecker_delta#Digital_signal_processing
+ .. [2] "Dirac delta function" *Wikipedia*,
+ https://en.wikipedia.org/wiki/Dirac_delta_function#Relationship_to_the_Kronecker_delta
+
+ .. versionadded:: 0.19.0
+
+ Examples
+ --------
+ An impulse at the 0th element (:math:`\\delta[n]`):
+
+ >>> from scipy import signal
+ >>> signal.unit_impulse(8)
+ array([ 1., 0., 0., 0., 0., 0., 0., 0.])
+
+ Impulse offset by 2 samples (:math:`\\delta[n-2]`):
+
+ >>> signal.unit_impulse(7, 2)
+ array([ 0., 0., 1., 0., 0., 0., 0.])
+
+ 2-dimensional impulse, centered:
+
+ >>> signal.unit_impulse((3, 3), 'mid')
+ array([[ 0., 0., 0.],
+ [ 0., 1., 0.],
+ [ 0., 0., 0.]])
+
+ Impulse at (2, 2), using broadcasting:
+
+ >>> signal.unit_impulse((4, 4), 2)
+ array([[ 0., 0., 0., 0.],
+ [ 0., 0., 0., 0.],
+ [ 0., 0., 1., 0.],
+ [ 0., 0., 0., 0.]])
+
+ Plot the impulse response of a 4th-order Butterworth lowpass filter:
+
+ >>> imp = signal.unit_impulse(100, 'mid')
+ >>> b, a = signal.butter(4, 0.2)
+ >>> response = signal.lfilter(b, a, imp)
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> plt.plot(np.arange(-50, 50), imp)
+ >>> plt.plot(np.arange(-50, 50), response)
+ >>> plt.margins(0.1, 0.1)
+ >>> plt.xlabel('Time [samples]')
+ >>> plt.ylabel('Amplitude')
+ >>> plt.grid(True)
+ >>> plt.show()
+
+ """
+ out = zeros(shape, dtype)
+
+ shape = np.atleast_1d(shape)
+
+ if idx is None:
+ idx = (0,) * len(shape)
+ elif idx == 'mid':
+ idx = tuple(shape // 2)
+ elif not hasattr(idx, "__iter__"):
+ idx = (idx,) * len(shape)
+
+ out[idx] = 1
+ return out
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_wavelets.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_wavelets.py
new file mode 100644
index 0000000000000000000000000000000000000000..9da68aed88ed380dfe04f59ce0acad2471c20cfb
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/_wavelets.py
@@ -0,0 +1,29 @@
+import numpy as np
+from scipy.signal._signaltools import convolve
+
+
+def _ricker(points, a):
+ A = 2 / (np.sqrt(3 * a) * (np.pi**0.25))
+ wsq = a**2
+ vec = np.arange(0, points) - (points - 1.0) / 2
+ xsq = vec**2
+ mod = (1 - xsq / wsq)
+ gauss = np.exp(-xsq / (2 * wsq))
+ total = A * mod * gauss
+ return total
+
+
+def _cwt(data, wavelet, widths, dtype=None, **kwargs):
+ # Determine output type
+ if dtype is None:
+ if np.asarray(wavelet(1, widths[0], **kwargs)).dtype.char in 'FDG':
+ dtype = np.complex128
+ else:
+ dtype = np.float64
+
+ output = np.empty((len(widths), len(data)), dtype=dtype)
+ for ind, width in enumerate(widths):
+ N = np.min([10 * width, len(data)])
+ wavelet_data = np.conj(wavelet(N, width, **kwargs)[::-1])
+ output[ind] = convolve(data, wavelet_data, mode='same')
+ return output
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/bsplines.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/bsplines.py
new file mode 100644
index 0000000000000000000000000000000000000000..0328d45c107bda78cbdbd374148237ca09ac411d
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/bsplines.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.signal` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [ # noqa: F822
+ 'spline_filter', 'gauss_spline',
+ 'cspline1d', 'qspline1d', 'cspline1d_eval', 'qspline1d_eval',
+ 'cspline2d', 'sepfir2d'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="signal", module="bsplines",
+ private_modules=["_spline_filters"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..41dc230a7f24a7ac3209f821d8d0f9417130afbd
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/filter_design.py
@@ -0,0 +1,28 @@
+# This file is not meant for public use and will be removed in SciPy v2.0.0.
+# Use the `scipy.signal` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [ # noqa: F822
+ 'findfreqs', 'freqs', 'freqz', 'tf2zpk', 'zpk2tf', 'normalize',
+ 'lp2lp', 'lp2hp', 'lp2bp', 'lp2bs', 'bilinear', 'iirdesign',
+ 'iirfilter', 'butter', 'cheby1', 'cheby2', 'ellip', 'bessel',
+ 'band_stop_obj', 'buttord', 'cheb1ord', 'cheb2ord', 'ellipord',
+ 'buttap', 'cheb1ap', 'cheb2ap', 'ellipap', 'besselap',
+ 'BadCoefficients', 'freqs_zpk', 'freqz_zpk',
+ 'tf2sos', 'sos2tf', 'zpk2sos', 'sos2zpk', 'group_delay',
+ 'sosfreqz', 'freqz_sos', 'iirnotch', 'iirpeak', 'bilinear_zpk',
+ 'lp2lp_zpk', 'lp2hp_zpk', 'lp2bp_zpk', 'lp2bs_zpk',
+ 'gammatone', 'iircomb',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="signal", module="filter_design",
+ private_modules=["_filter_design"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/fir_filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/fir_filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..4c7be58b151835a55eb494e31047e6b846e2dae8
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/fir_filter_design.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.signal` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [ # noqa: F822
+ 'kaiser_beta', 'kaiser_atten', 'kaiserord',
+ 'firwin', 'firwin2', 'remez', 'firls', 'minimum_phase',
+ 'firwin_2d',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="signal", module="fir_filter_design",
+ private_modules=["_fir_filter_design"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/lti_conversion.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/lti_conversion.py
new file mode 100644
index 0000000000000000000000000000000000000000..7080990afc9e23e51e8a45aaa146b64c58dda3cf
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/lti_conversion.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.signal` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [ # noqa: F822
+ 'tf2ss', 'abcd_normalize', 'ss2tf', 'zpk2ss', 'ss2zpk',
+ 'cont2discrete', 'tf2zpk', 'zpk2tf', 'normalize'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="signal", module="lti_conversion",
+ private_modules=["_lti_conversion"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/ltisys.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/ltisys.py
new file mode 100644
index 0000000000000000000000000000000000000000..5123068de559f124bf444c12ef9824c3d14de64f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/ltisys.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.signal` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [ # noqa: F822
+ 'lti', 'dlti', 'TransferFunction', 'ZerosPolesGain', 'StateSpace',
+ 'lsim', 'impulse', 'step', 'bode',
+ 'freqresp', 'place_poles', 'dlsim', 'dstep', 'dimpulse',
+ 'dfreqresp', 'dbode',
+ 'tf2zpk', 'zpk2tf', 'normalize', 'freqs',
+ 'freqz', 'freqs_zpk', 'freqz_zpk', 'tf2ss', 'abcd_normalize',
+ 'ss2tf', 'zpk2ss', 'ss2zpk', 'cont2discrete',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="signal", module="ltisys",
+ private_modules=["_ltisys"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/signaltools.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/signaltools.py
new file mode 100644
index 0000000000000000000000000000000000000000..85d426f5fb2605c639fc6dbd1b4d0284a3f11e1b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/signaltools.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.signal` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [ # noqa: F822
+ 'correlate', 'correlation_lags', 'correlate2d',
+ 'convolve', 'convolve2d', 'fftconvolve', 'oaconvolve',
+ 'order_filter', 'medfilt', 'medfilt2d', 'wiener', 'lfilter',
+ 'lfiltic', 'sosfilt', 'deconvolve', 'hilbert', 'hilbert2',
+ 'unique_roots', 'invres', 'invresz', 'residue',
+ 'residuez', 'resample', 'resample_poly', 'detrend',
+ 'lfilter_zi', 'sosfilt_zi', 'sosfiltfilt', 'choose_conv_method',
+ 'filtfilt', 'decimate', 'vectorstrength',
+ 'dlti', 'upfirdn', 'get_window', 'cheby1', 'firwin'
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="signal", module="signaltools",
+ private_modules=["_signaltools"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/spectral.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..299ebed781b00a1f1f35e96c54f4c20d9bd9d0fc
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/spectral.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.signal` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [ # noqa: F822
+ 'periodogram', 'welch', 'lombscargle', 'csd', 'coherence',
+ 'spectrogram', 'stft', 'istft', 'check_COLA', 'check_NOLA',
+ 'get_window',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="signal", module="spectral",
+ private_modules=["_spectral_py"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/spline.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/spline.py
new file mode 100644
index 0000000000000000000000000000000000000000..30fb91ef8bbc17242959947b917dc41d7245cdc2
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/spline.py
@@ -0,0 +1,18 @@
+# This file is not meant for public use and will be removed in the future
+# versions of SciPy. Use the `scipy.signal` namespace for importing the
+# functions included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+
+__all__ = ['sepfir2d'] # noqa: F822
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="signal", module="spline",
+ private_modules=["_spline"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/.__scipy_spectral_test_shim.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/.__scipy_spectral_test_shim.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/.__scipy_spectral_test_shim.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._mpsig.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._mpsig.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._mpsig.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_array_tools.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_array_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_array_tools.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_bsplines.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_bsplines.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_bsplines.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_cont2discrete.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_cont2discrete.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_cont2discrete.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_czt.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_czt.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_czt.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_dltisys.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_dltisys.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_dltisys.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_filter_design.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_fir_filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_fir_filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_fir_filter_design.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_ltisys.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_ltisys.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_ltisys.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_max_len_seq.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_max_len_seq.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_max_len_seq.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_peak_finding.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_peak_finding.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_peak_finding.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_result_type.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_result_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_result_type.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_savitzky_golay.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_savitzky_golay.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_savitzky_golay.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_short_time_fft.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_short_time_fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_short_time_fft.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_signaltools.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_signaltools.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_signaltools.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_spectral.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_spectral.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_splines.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_splines.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_splines.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_upfirdn.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_upfirdn.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_upfirdn.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_waveforms.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_waveforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_waveforms.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_wavelets.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_wavelets.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_wavelets.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_windows.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/._test_windows.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py
new file mode 100644
index 0000000000000000000000000000000000000000..6003f68c0bce4ad33a110fe1379caabe14c2b1e7
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/_scipy_spectral_test_shim.py
@@ -0,0 +1,311 @@
+"""Helpers to utilize existing stft / istft tests for testing `ShortTimeFFT`.
+
+This module provides the functions stft_compare() and istft_compare(), which,
+compares the output between the existing (i)stft() and the shortTimeFFT based
+_(i)stft_wrapper() implementations in this module.
+
+For testing add the following imports to the file ``tests/test_spectral.py``::
+
+ from ._scipy_spectral_test_shim import stft_compare as stft
+ from ._scipy_spectral_test_shim import istft_compare as istft
+
+and remove the existing imports of stft and istft.
+
+The idea of these wrappers is not to provide a backward-compatible interface
+but to demonstrate that the ShortTimeFFT implementation is at least as capable
+as the existing one and delivers comparable results. Furthermore, the
+wrappers highlight the different philosophies of the implementations,
+especially in the border handling.
+"""
+import platform
+from typing import cast, Literal
+
+import numpy as np
+from numpy.testing import assert_allclose
+
+from scipy.signal import ShortTimeFFT
+from scipy.signal import get_window, stft, istft
+from scipy.signal._arraytools import const_ext, even_ext, odd_ext, zero_ext
+from scipy.signal._short_time_fft import FFT_MODE_TYPE
+from scipy.signal._spectral_py import _triage_segments
+
+
+def _stft_wrapper(x, fs=1.0, window='hann', nperseg=256, noverlap=None,
+ nfft=None, detrend=False, return_onesided=True,
+ boundary='zeros', padded=True, axis=-1, scaling='spectrum'):
+ """Wrapper for the SciPy `stft()` function based on `ShortTimeFFT` for
+ unit testing.
+
+ Handling the boundary and padding is where `ShortTimeFFT` and `stft()`
+ differ in behavior. Parts of `_spectral_helper()` were copied to mimic
+ the` stft()` behavior.
+
+ This function is meant to be solely used by `stft_compare()`.
+ """
+ if scaling not in ('psd', 'spectrum'): # same errors as in original stft:
+ raise ValueError(f"Parameter {scaling=} not in ['spectrum', 'psd']!")
+
+ # The following lines are taken from the original _spectral_helper():
+ boundary_funcs = {'even': even_ext,
+ 'odd': odd_ext,
+ 'constant': const_ext,
+ 'zeros': zero_ext,
+ None: None}
+
+ if boundary not in boundary_funcs:
+ raise ValueError(f"Unknown boundary option '{boundary}', must be one" +
+ f" of: {list(boundary_funcs.keys())}")
+ if x.size == 0:
+ return np.empty(x.shape), np.empty(x.shape), np.empty(x.shape)
+
+ if nperseg is not None: # if specified by user
+ nperseg = int(nperseg)
+ if nperseg < 1:
+ raise ValueError('nperseg must be a positive integer')
+
+ # parse window; if array like, then set nperseg = win.shape
+ win, nperseg = _triage_segments(window, nperseg,
+ input_length=x.shape[axis])
+
+ if nfft is None:
+ nfft = nperseg
+ elif nfft < nperseg:
+ raise ValueError('nfft must be greater than or equal to nperseg.')
+ else:
+ nfft = int(nfft)
+
+ if noverlap is None:
+ noverlap = nperseg//2
+ else:
+ noverlap = int(noverlap)
+ if noverlap >= nperseg:
+ raise ValueError('noverlap must be less than nperseg.')
+ nstep = nperseg - noverlap
+ n = x.shape[axis]
+
+ # Padding occurs after boundary extension, so that the extended signal ends
+ # in zeros, instead of introducing an impulse at the end.
+ # I.e. if x = [..., 3, 2]
+ # extend then pad -> [..., 3, 2, 2, 3, 0, 0, 0]
+ # pad then extend -> [..., 3, 2, 0, 0, 0, 2, 3]
+
+ if boundary is not None:
+ ext_func = boundary_funcs[boundary]
+ # Extend by nperseg//2 in front and back:
+ x = ext_func(x, nperseg//2, axis=axis)
+
+ if padded:
+ # Pad to integer number of windowed segments
+ # I.e make x.shape[-1] = nperseg + (nseg-1)*nstep, with integer nseg
+ x = np.moveaxis(x, axis, -1)
+
+ # This is an edge case where shortTimeFFT returns one more time slice
+ # than the Scipy stft() shorten to remove last time slice:
+ if n % 2 == 1 and nperseg % 2 == 1 and noverlap % 2 == 1:
+ x = x[..., : -1]
+
+ nadd = (-(x.shape[-1]-nperseg) % nstep) % nperseg
+ zeros_shape = list(x.shape[:-1]) + [nadd]
+ x = np.concatenate((x, np.zeros(zeros_shape)), axis=-1)
+ x = np.moveaxis(x, -1, axis)
+
+ # ... end original _spectral_helper() code.
+ scale_to = {'spectrum': 'magnitude', 'psd': 'psd'}[scaling]
+
+ if np.iscomplexobj(x) and return_onesided:
+ return_onesided = False
+ # using cast() to make mypy happy:
+ fft_mode = cast(FFT_MODE_TYPE, 'onesided' if return_onesided else 'twosided')
+
+ ST = ShortTimeFFT(win, nstep, fs, fft_mode=fft_mode, mfft=nfft,
+ scale_to=scale_to, phase_shift=None)
+
+ k_off = nperseg // 2
+ p0 = 0 # ST.lower_border_end[1] + 1
+ nn = x.shape[axis] if padded else n+k_off+1
+ # number of frames akin to legacy stft computation
+ p1 = (x.shape[axis] - nperseg) // nstep + 1
+
+ detr = None if detrend is False else detrend
+ Sxx = ST.stft_detrend(x, detr, p0, p1, k_offset=k_off, axis=axis)
+ t = ST.t(nn, 0, p1 - p0, k_offset=0 if boundary is not None else k_off)
+ if x.dtype in (np.float32, np.complex64):
+ Sxx = Sxx.astype(np.complex64)
+
+ return ST.f, t, Sxx
+
+
+def _istft_wrapper(Zxx, fs=1.0, window='hann', nperseg=None, noverlap=None,
+ nfft=None, input_onesided=True, boundary=True, time_axis=-1,
+ freq_axis=-2, scaling='spectrum') -> \
+ tuple[np.ndarray, np.ndarray, tuple[int, int]]:
+ """Wrapper for the SciPy `istft()` function based on `ShortTimeFFT` for
+ unit testing.
+
+ Note that only option handling is implemented as far as to handle the unit
+ tests. E.g., the case ``nperseg=None`` is not handled.
+
+ This function is meant to be solely used by `istft_compare()`.
+ """
+ # *** Lines are taken from _spectral_py.istft() ***:
+ if Zxx.ndim < 2:
+ raise ValueError('Input stft must be at least 2d!')
+
+ if freq_axis == time_axis:
+ raise ValueError('Must specify differing time and frequency axes!')
+
+ nseg = Zxx.shape[time_axis]
+
+ if input_onesided:
+ # Assume even segment length
+ n_default = 2*(Zxx.shape[freq_axis] - 1)
+ else:
+ n_default = Zxx.shape[freq_axis]
+
+ # Check windowing parameters
+ if nperseg is None:
+ nperseg = n_default
+ else:
+ nperseg = int(nperseg)
+ if nperseg < 1:
+ raise ValueError('nperseg must be a positive integer')
+
+ if nfft is None:
+ if input_onesided and (nperseg == n_default + 1):
+ # Odd nperseg, no FFT padding
+ nfft = nperseg
+ else:
+ nfft = n_default
+ elif nfft < nperseg:
+ raise ValueError('nfft must be greater than or equal to nperseg.')
+ else:
+ nfft = int(nfft)
+
+ if noverlap is None:
+ noverlap = nperseg//2
+ else:
+ noverlap = int(noverlap)
+ if noverlap >= nperseg:
+ raise ValueError('noverlap must be less than nperseg.')
+ nstep = nperseg - noverlap
+
+ # Get window as array
+ if isinstance(window, str) or type(window) is tuple:
+ win = get_window(window, nperseg)
+ else:
+ win = np.asarray(window)
+ if len(win.shape) != 1:
+ raise ValueError('window must be 1-D')
+ if win.shape[0] != nperseg:
+ raise ValueError(f'window must have length of {nperseg}')
+
+ outputlength = nperseg + (nseg-1)*nstep
+ # *** End block of: Taken from _spectral_py.istft() ***
+
+ # Using cast() to make mypy happy:
+ fft_mode = cast(FFT_MODE_TYPE, 'onesided' if input_onesided else 'twosided')
+ scale_to = cast(Literal['magnitude', 'psd'],
+ {'spectrum': 'magnitude', 'psd': 'psd'}[scaling])
+
+ ST = ShortTimeFFT(win, nstep, fs, fft_mode=fft_mode, mfft=nfft,
+ scale_to=scale_to, phase_shift=None)
+
+ if boundary:
+ j = nperseg if nperseg % 2 == 0 else nperseg - 1
+ k0 = ST.k_min + nperseg // 2
+ k1 = outputlength - j + k0
+ else:
+ raise NotImplementedError("boundary=False does not make sense with" +
+ "ShortTimeFFT.istft()!")
+
+ x = ST.istft(Zxx, k0=k0, k1=k1, f_axis=freq_axis, t_axis=time_axis)
+ t = np.arange(k1 - k0) * ST.T
+ k_hi = ST.upper_border_begin(k1 - k0)[0]
+ # using cast() to make mypy happy:
+ return t, x, (ST.lower_border_end[0], k_hi)
+
+
+def stft_compare(x, fs=1.0, window='hann', nperseg=256, noverlap=None,
+ nfft=None, detrend=False, return_onesided=True,
+ boundary='zeros', padded=True, axis=-1, scaling='spectrum'):
+ """Assert that the results from the existing `stft()` and `_stft_wrapper()`
+ are close to each other.
+
+ For comparing the STFT values an absolute tolerance of the floating point
+ resolution was added to circumvent problems with the following tests:
+ * For float32 the tolerances are much higher in
+ TestSTFT.test_roundtrip_float32()).
+ * The TestSTFT.test_roundtrip_scaling() has a high relative deviation.
+ Interestingly this did not appear in Scipy 1.9.1 but only in the current
+ development version.
+ """
+ kw = dict(x=x, fs=fs, window=window, nperseg=nperseg, noverlap=noverlap,
+ nfft=nfft, detrend=detrend, return_onesided=return_onesided,
+ boundary=boundary, padded=padded, axis=axis, scaling=scaling)
+ f, t, Zxx = stft(**kw)
+ f_wrapper, t_wrapper, Zxx_wrapper = _stft_wrapper(**kw)
+
+ e_msg_part = " of `stft_wrapper()` differ from `stft()`."
+ assert_allclose(f_wrapper, f, err_msg=f"Frequencies {e_msg_part}")
+ assert_allclose(t_wrapper, t, err_msg=f"Time slices {e_msg_part}")
+
+ # Adapted tolerances to account for:
+ atol = np.finfo(Zxx.dtype).resolution * 2
+ assert_allclose(Zxx_wrapper, Zxx, atol=atol,
+ err_msg=f"STFT values {e_msg_part}")
+ return f, t, Zxx
+
+
+def istft_compare(Zxx, fs=1.0, window='hann', nperseg=None, noverlap=None,
+ nfft=None, input_onesided=True, boundary=True, time_axis=-1,
+ freq_axis=-2, scaling='spectrum'):
+ """Assert that the results from the existing `istft()` and
+ `_istft_wrapper()` are close to each other.
+
+ Quirks:
+ * If ``boundary=False`` the comparison is skipped, since it does not
+ make sense with ShortTimeFFT.istft(). Only used in test
+ TestSTFT.test_roundtrip_boundary_extension().
+ * If ShortTimeFFT.istft() decides the STFT is not invertible, the
+ comparison is skipped, since istft() only emits a warning and does not
+ return a correct result. Only used in
+ ShortTimeFFT.test_roundtrip_not_nola().
+ * For comparing the signals an absolute tolerance of the floating point
+ resolution was added to account for the low accuracy of float32 (Occurs
+ only in TestSTFT.test_roundtrip_float32()).
+ """
+ kw = dict(Zxx=Zxx, fs=fs, window=window, nperseg=nperseg,
+ noverlap=noverlap, nfft=nfft, input_onesided=input_onesided,
+ boundary=boundary, time_axis=time_axis, freq_axis=freq_axis,
+ scaling=scaling)
+
+ t, x = istft(**kw)
+ if not boundary: # skip test_roundtrip_boundary_extension():
+ return t, x # _istft_wrapper does() not implement this case
+ try: # if inversion fails, istft() only emits a warning:
+ t_wrapper, x_wrapper, (k_lo, k_hi) = _istft_wrapper(**kw)
+ except ValueError as v: # Do nothing if inversion fails:
+ if v.args[0] == "Short-time Fourier Transform not invertible!":
+ return t, x
+ raise v
+
+ e_msg_part = " of `istft_wrapper()` differ from `istft()`"
+ assert_allclose(t, t_wrapper, err_msg=f"Sample times {e_msg_part}")
+
+ # Adapted tolerances to account for resolution loss:
+ atol = np.finfo(x.dtype).resolution*2 # instead of default atol = 0
+ rtol = 1e-7 # default for np.allclose()
+
+ # Relax atol on 32-Bit platforms a bit to pass CI tests.
+ # - Not clear why there are discrepancies (in the FFT maybe?)
+ # - Not sure what changed on 'i686' since earlier on those test passed
+ if x.dtype == np.float32 and platform.machine() == 'i686':
+ # float32 gets only used by TestSTFT.test_roundtrip_float32() so
+ # we are using the tolerances from there to circumvent CI problems
+ atol, rtol = 1e-4, 1e-5
+ elif platform.machine() in ('aarch64', 'i386', 'i686'):
+ atol = max(atol, 1e-12) # 2e-15 seems too tight for 32-Bit platforms
+
+ assert_allclose(x_wrapper[k_lo:k_hi], x[k_lo:k_hi], atol=atol, rtol=rtol,
+ err_msg=f"Signal values {e_msg_part}")
+ return t, x
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/mpsig.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/mpsig.py
new file mode 100644
index 0000000000000000000000000000000000000000..d129de74e5df00c22bc0b82c7d3f7b52483941f9
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/mpsig.py
@@ -0,0 +1,122 @@
+"""
+Some signal functions implemented using mpmath.
+"""
+
+try:
+ import mpmath
+except ImportError:
+ mpmath = None
+
+
+def _prod(seq):
+ """Returns the product of the elements in the sequence `seq`."""
+ p = 1
+ for elem in seq:
+ p *= elem
+ return p
+
+
+def _relative_degree(z, p):
+ """
+ Return relative degree of transfer function from zeros and poles.
+
+ This is simply len(p) - len(z), which must be nonnegative.
+ A ValueError is raised if len(p) < len(z).
+ """
+ degree = len(p) - len(z)
+ if degree < 0:
+ raise ValueError("Improper transfer function. "
+ "Must have at least as many poles as zeros.")
+ return degree
+
+
+def _zpkbilinear(z, p, k, fs):
+ """Bilinear transformation to convert a filter from analog to digital."""
+
+ degree = _relative_degree(z, p)
+
+ fs2 = 2*fs
+
+ # Bilinear transform the poles and zeros
+ z_z = [(fs2 + z1) / (fs2 - z1) for z1 in z]
+ p_z = [(fs2 + p1) / (fs2 - p1) for p1 in p]
+
+ # Any zeros that were at infinity get moved to the Nyquist frequency
+ z_z.extend([-1] * degree)
+
+ # Compensate for gain change
+ numer = _prod(fs2 - z1 for z1 in z)
+ denom = _prod(fs2 - p1 for p1 in p)
+ k_z = k * numer / denom
+
+ return z_z, p_z, k_z.real
+
+
+def _zpklp2lp(z, p, k, wo=1):
+ """Transform a lowpass filter to a different cutoff frequency."""
+
+ degree = _relative_degree(z, p)
+
+ # Scale all points radially from origin to shift cutoff frequency
+ z_lp = [wo * z1 for z1 in z]
+ p_lp = [wo * p1 for p1 in p]
+
+ # Each shifted pole decreases gain by wo, each shifted zero increases it.
+ # Cancel out the net change to keep overall gain the same
+ k_lp = k * wo**degree
+
+ return z_lp, p_lp, k_lp
+
+
+def _butter_analog_poles(n):
+ """
+ Poles of an analog Butterworth lowpass filter.
+
+ This is the same calculation as scipy.signal.buttap(n) or
+ scipy.signal.butter(n, 1, analog=True, output='zpk'), but mpmath is used,
+ and only the poles are returned.
+ """
+ poles = [-mpmath.exp(1j*mpmath.pi*k/(2*n)) for k in range(-n+1, n, 2)]
+ return poles
+
+
+def butter_lp(n, Wn):
+ """
+ Lowpass Butterworth digital filter design.
+
+ This computes the same result as scipy.signal.butter(n, Wn, output='zpk'),
+ but it uses mpmath, and the results are returned in lists instead of NumPy
+ arrays.
+ """
+ zeros = []
+ poles = _butter_analog_poles(n)
+ k = 1
+ fs = 2
+ warped = 2 * fs * mpmath.tan(mpmath.pi * Wn / fs)
+ z, p, k = _zpklp2lp(zeros, poles, k, wo=warped)
+ z, p, k = _zpkbilinear(z, p, k, fs=fs)
+ return z, p, k
+
+
+def zpkfreqz(z, p, k, worN=None):
+ """
+ Frequency response of a filter in zpk format, using mpmath.
+
+ This is the same calculation as scipy.signal.freqz, but the input is in
+ zpk format, the calculation is performed using mpath, and the results are
+ returned in lists instead of NumPy arrays.
+ """
+ if worN is None or isinstance(worN, int):
+ N = worN or 512
+ ws = [mpmath.pi * mpmath.mpf(j) / N for j in range(N)]
+ else:
+ ws = worN
+
+ h = []
+ for wk in ws:
+ zm1 = mpmath.exp(1j * wk)
+ numer = _prod([zm1 - t for t in z])
+ denom = _prod([zm1 - t for t in p])
+ hk = k * numer / denom
+ h.append(hk)
+ return ws, h
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_array_tools.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_array_tools.py
new file mode 100644
index 0000000000000000000000000000000000000000..4bda9716e0bc4b6ad3ed0c3954147043b74c421a
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_array_tools.py
@@ -0,0 +1,111 @@
+import numpy as np
+
+from scipy._lib._array_api import xp_assert_equal
+from pytest import raises as assert_raises
+
+from scipy.signal._arraytools import (axis_slice, axis_reverse,
+ odd_ext, even_ext, const_ext, zero_ext)
+
+
+class TestArrayTools:
+
+ def test_axis_slice(self):
+ a = np.arange(12).reshape(3, 4)
+
+ s = axis_slice(a, start=0, stop=1, axis=0)
+ xp_assert_equal(s, a[0:1, :])
+
+ s = axis_slice(a, start=-1, axis=0)
+ xp_assert_equal(s, a[-1:, :])
+
+ s = axis_slice(a, start=0, stop=1, axis=1)
+ xp_assert_equal(s, a[:, 0:1])
+
+ s = axis_slice(a, start=-1, axis=1)
+ xp_assert_equal(s, a[:, -1:])
+
+ s = axis_slice(a, start=0, step=2, axis=0)
+ xp_assert_equal(s, a[::2, :])
+
+ s = axis_slice(a, start=0, step=2, axis=1)
+ xp_assert_equal(s, a[:, ::2])
+
+ def test_axis_reverse(self):
+ a = np.arange(12).reshape(3, 4)
+
+ r = axis_reverse(a, axis=0)
+ xp_assert_equal(r, a[::-1, :])
+
+ r = axis_reverse(a, axis=1)
+ xp_assert_equal(r, a[:, ::-1])
+
+ def test_odd_ext(self):
+ a = np.array([[1, 2, 3, 4, 5],
+ [9, 8, 7, 6, 5]])
+
+ odd = odd_ext(a, 2, axis=1)
+ expected = np.array([[-1, 0, 1, 2, 3, 4, 5, 6, 7],
+ [11, 10, 9, 8, 7, 6, 5, 4, 3]])
+ xp_assert_equal(odd, expected)
+
+ odd = odd_ext(a, 1, axis=0)
+ expected = np.array([[-7, -4, -1, 2, 5],
+ [1, 2, 3, 4, 5],
+ [9, 8, 7, 6, 5],
+ [17, 14, 11, 8, 5]])
+ xp_assert_equal(odd, expected)
+
+ assert_raises(ValueError, odd_ext, a, 2, axis=0)
+ assert_raises(ValueError, odd_ext, a, 5, axis=1)
+
+ def test_even_ext(self):
+ a = np.array([[1, 2, 3, 4, 5],
+ [9, 8, 7, 6, 5]])
+
+ even = even_ext(a, 2, axis=1)
+ expected = np.array([[3, 2, 1, 2, 3, 4, 5, 4, 3],
+ [7, 8, 9, 8, 7, 6, 5, 6, 7]])
+ xp_assert_equal(even, expected)
+
+ even = even_ext(a, 1, axis=0)
+ expected = np.array([[9, 8, 7, 6, 5],
+ [1, 2, 3, 4, 5],
+ [9, 8, 7, 6, 5],
+ [1, 2, 3, 4, 5]])
+ xp_assert_equal(even, expected)
+
+ assert_raises(ValueError, even_ext, a, 2, axis=0)
+ assert_raises(ValueError, even_ext, a, 5, axis=1)
+
+ def test_const_ext(self):
+ a = np.array([[1, 2, 3, 4, 5],
+ [9, 8, 7, 6, 5]])
+
+ const = const_ext(a, 2, axis=1)
+ expected = np.array([[1, 1, 1, 2, 3, 4, 5, 5, 5],
+ [9, 9, 9, 8, 7, 6, 5, 5, 5]])
+ xp_assert_equal(const, expected)
+
+ const = const_ext(a, 1, axis=0)
+ expected = np.array([[1, 2, 3, 4, 5],
+ [1, 2, 3, 4, 5],
+ [9, 8, 7, 6, 5],
+ [9, 8, 7, 6, 5]])
+ xp_assert_equal(const, expected)
+
+ def test_zero_ext(self):
+ a = np.array([[1, 2, 3, 4, 5],
+ [9, 8, 7, 6, 5]])
+
+ zero = zero_ext(a, 2, axis=1)
+ expected = np.array([[0, 0, 1, 2, 3, 4, 5, 0, 0],
+ [0, 0, 9, 8, 7, 6, 5, 0, 0]])
+ xp_assert_equal(zero, expected)
+
+ zero = zero_ext(a, 1, axis=0)
+ expected = np.array([[0, 0, 0, 0, 0],
+ [1, 2, 3, 4, 5],
+ [9, 8, 7, 6, 5],
+ [0, 0, 0, 0, 0]])
+ xp_assert_equal(zero, expected)
+
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_bsplines.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_bsplines.py
new file mode 100644
index 0000000000000000000000000000000000000000..a4d3ffe88b79b0147cc52b51e0d89fa3a61ceb34
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_bsplines.py
@@ -0,0 +1,391 @@
+# pylint: disable=missing-docstring
+import math
+import numpy as np
+
+from scipy._lib._array_api import (
+ assert_almost_equal, xp_assert_close, xp_assert_equal, make_xp_test_case,
+ xp_default_dtype, array_namespace, _xp_copy_to_numpy
+)
+import pytest
+from pytest import raises
+
+from scipy import signal
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+lazy_xp_modules = [signal]
+
+
+class TestBSplines:
+ """Test behaviors of B-splines. Some of the values tested against were
+ returned as of SciPy 1.1.0 and are included for regression testing
+ purposes. Others (at integer points) are compared to theoretical
+ expressions (cf. Unser, Aldroubi, Eden, IEEE TSP 1993, Table 1)."""
+
+ @make_xp_test_case(signal.spline_filter)
+ def test_spline_filter(self, xp):
+ rng = np.random.RandomState(12457)
+ # Test the type-error branch
+ raises(TypeError, signal.spline_filter, xp.asarray([0]), 0)
+ # Test the real branch
+ data_array_real = rng.rand(12, 12)
+ # make the magnitude exceed 1, and make some negative
+ data_array_real = 10*(1-2*data_array_real)
+ data_array_real = xp.asarray(data_array_real)
+ result_array_real = xp.asarray(
+ [[-.463312621, 8.33391222, .697290949, 5.28390836,
+ 5.92066474, 6.59452137, 9.84406950, -8.78324188,
+ 7.20675750, -8.17222994, -4.38633345, 9.89917069],
+ [2.67755154, 6.24192170, -3.15730578, 9.87658581,
+ -9.96930425, 3.17194115, -4.50919947, 5.75423446,
+ 9.65979824, -8.29066885, .971416087, -2.38331897],
+ [-7.08868346, 4.89887705, -1.37062289, 7.70705838,
+ 2.51526461, 3.65885497, 5.16786604, -8.77715342e-03,
+ 4.10533325, 9.04761993, -.577960351, 9.86382519],
+ [-4.71444301, -1.68038985, 2.84695116, 1.14315938,
+ -3.17127091, 1.91830461, 7.13779687, -5.35737482,
+ -9.66586425, -9.87717456, 9.93160672, 4.71948144],
+ [9.49551194, -1.92958436, 6.25427993, -9.05582911,
+ 3.97562282, 7.68232426, -1.04514824, -5.86021443,
+ -8.43007451, 5.47528997, 2.06330736, -8.65968112],
+ [-8.91720100, 8.87065356, 3.76879937, 2.56222894,
+ -.828387146, 8.72288903, 6.42474741, -6.84576083,
+ 9.94724115, 6.90665380, -6.61084494, -9.44907391],
+ [9.25196790, -.774032030, 7.05371046, -2.73505725,
+ 2.53953305, -1.82889155, 2.95454824, -1.66362046,
+ 5.72478916, -3.10287679, 1.54017123, -7.87759020],
+ [-3.98464539, -2.44316992, -1.12708657, 1.01725672,
+ -8.89294671, -5.42145629, -6.16370321, 2.91775492,
+ 9.64132208, .702499998, -2.02622392, 1.56308431],
+ [-2.22050773, 7.89951554, 5.98970713, -7.35861835,
+ 5.45459283, -7.76427957, 3.67280490, -4.05521315,
+ 4.51967507, -3.22738749, -3.65080177, 3.05630155],
+ [-6.21240584, -.296796126, -8.34800163, 9.21564563,
+ -3.61958784, -4.77120006, -3.99454057, 1.05021988e-03,
+ -6.95982829, 6.04380797, 8.43181250, -2.71653339],
+ [1.19638037, 6.99718842e-02, 6.72020394, -2.13963198,
+ 3.75309875, -5.70076744, 5.92143551, -7.22150575,
+ -3.77114594, -1.11903194, -5.39151466, 3.06620093],
+ [9.86326886, 1.05134482, -7.75950607, -3.64429655,
+ 7.81848957, -9.02270373, 3.73399754, -4.71962549,
+ -7.71144306, 3.78263161, 6.46034818, -4.43444731]], dtype=xp.float64)
+ xp_assert_close(signal.spline_filter(data_array_real, 0),
+ result_array_real)
+
+ @make_xp_test_case(signal.spline_filter)
+ def test_spline_filter_complex(self, xp):
+ rng = np.random.RandomState(12457)
+ data_array_complex = rng.rand(7, 7) + rng.rand(7, 7)*1j
+ # make the magnitude exceed 1, and make some negative
+ data_array_complex = 10*(1+1j-2*data_array_complex)
+ data_array_complex = xp.asarray(data_array_complex)
+
+ result_array_complex = xp.asarray(
+ [[-4.61489230e-01-1.92994022j, 8.33332443+6.25519943j,
+ 6.96300745e-01-9.05576038j, 5.28294849+3.97541356j,
+ 5.92165565+7.68240595j, 6.59493160-1.04542804j,
+ 9.84503460-5.85946894j],
+ [-8.78262329-8.4295969j, 7.20675516+5.47528982j,
+ -8.17223072+2.06330729j, -4.38633347-8.65968037j,
+ 9.89916801-8.91720295j, 2.67755103+8.8706522j,
+ 6.24192142+3.76879835j],
+ [-3.15627527+2.56303072j, 9.87658501-0.82838702j,
+ -9.96930313+8.72288895j, 3.17193985+6.42474651j,
+ -4.50919819-6.84576082j, 5.75423431+9.94723988j,
+ 9.65979767+6.90665293j],
+ [-8.28993416-6.61064005j, 9.71416473e-01-9.44907284j,
+ -2.38331890+9.25196648j, -7.08868170-0.77403212j,
+ 4.89887714+7.05371094j, -1.37062311-2.73505688j,
+ 7.70705748+2.5395329j],
+ [2.51528406-1.82964492j, 3.65885472+2.95454836j,
+ 5.16786575-1.66362023j, -8.77737999e-03+5.72478867j,
+ 4.10533333-3.10287571j, 9.04761887+1.54017115j,
+ -5.77960968e-01-7.87758923j],
+ [9.86398506-3.98528528j, -4.71444130-2.44316983j,
+ -1.68038976-1.12708664j, 2.84695053+1.01725709j,
+ 1.14315915-8.89294529j, -3.17127085-5.42145538j,
+ 1.91830420-6.16370344j],
+ [7.13875294+2.91851187j, -5.35737514+9.64132309j,
+ -9.66586399+0.70250005j, -9.87717438-2.0262239j,
+ 9.93160629+1.5630846j, 4.71948051-2.22050714j,
+ 9.49550819+7.8995142j]], dtype=xp.complex128)
+ # FIXME: for complex types, the computations are done in
+ # single precision (reason unclear). When this is changed,
+ # this test needs updating.
+ xp_assert_close(signal.spline_filter(data_array_complex, 0),
+ result_array_complex, rtol=1e-6)
+
+ @make_xp_test_case(signal.gauss_spline)
+ def test_gauss_spline(self, xp):
+ assert math.isclose(signal.gauss_spline(0, 0), 1.381976597885342)
+
+ xp_assert_close(signal.gauss_spline(xp.asarray([1.]), 1),
+ xp.asarray([0.04865217]), atol=1e-9
+ )
+
+ @skip_xp_backends(np_only=True, reason="deliberate: array-likes are accepted")
+ @make_xp_test_case(signal.gauss_spline)
+ def test_gauss_spline_list(self, xp):
+ # regression test for gh-12152 (accept array_like)
+ knots = [-1.0, 0.0, -1.0]
+ assert_almost_equal(signal.gauss_spline(knots, 3),
+ np.asarray([0.15418033, 0.6909883, 0.15418033])
+ )
+
+ @make_xp_test_case(signal.cspline1d)
+ def test_cspline1d(self, xp):
+ xp_assert_equal(signal.cspline1d(xp.asarray([0])),
+ xp.asarray([0.], dtype=xp.float64))
+ c1d = xp.asarray([1.21037185, 1.86293902, 2.98834059, 4.11660378,
+ 4.78893826], dtype=xp.float64)
+ # test lamda != 0
+ xp_assert_close(signal.cspline1d(xp.asarray([1., 2, 3, 4, 5]), 1), c1d)
+ c1d0 = xp.asarray([0.78683946, 2.05333735, 2.99981113, 3.94741812,
+ 5.21051638], dtype=xp.float64)
+ xp_assert_close(signal.cspline1d(xp.asarray([1., 2, 3, 4, 5])), c1d0)
+
+ @make_xp_test_case(signal.qspline1d)
+ def test_qspline1d(self, xp):
+ xp_assert_equal(signal.qspline1d(xp.asarray([0])),
+ xp.asarray([0.], dtype=xp.float64))
+ # test lamda != 0
+ raises(ValueError, signal.qspline1d, xp.asarray([1., 2, 3, 4, 5]), 1.)
+ raises(ValueError, signal.qspline1d, xp.asarray([1., 2, 3, 4, 5]), -1.)
+ q1d0 = xp.asarray([0.85350007, 2.02441743, 2.99999534, 3.97561055,
+ 5.14634135], dtype=xp.float64)
+ xp_assert_close(
+ signal.qspline1d(xp.asarray([1., 2, 3, 4, 5], dtype=xp.float64)), q1d0
+ )
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/9484")
+ @make_xp_test_case(signal.cspline1d_eval)
+ def test_cspline1d_eval(self, xp):
+ r = signal.cspline1d_eval(xp.asarray([0., 0], dtype=xp.float64),
+ xp.asarray([0.], dtype=xp.float64))
+ xp_assert_close(r, xp.asarray([0.], dtype=xp.float64))
+
+ r = signal.cspline1d_eval(xp.asarray([1., 0, 1], dtype=xp.float64),
+ xp.asarray([], dtype=xp.float64))
+ xp_assert_equal(r, xp.asarray([], dtype=xp.float64))
+
+ # Test case for newx that gets filtered down to empty
+ r = signal.cspline1d_eval(xp.asarray([1.0, 0, 1], dtype=xp.float64),
+ xp.asarray([-1.0], dtype=xp.float64))
+ xp_assert_close(r, xp.asarray([0.33333333], dtype=xp.float64))
+
+ x = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
+ dx = x[1] - x[0]
+ newx = [-6., -5.5, -5., -4.5, -4., -3.5, -3., -2.5, -2., -1.5, -1.,
+ -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6.,
+ 6.5, 7., 7.5, 8., 8.5, 9., 9.5, 10., 10.5, 11., 11.5, 12.,
+ 12.5]
+ y = xp.asarray([4.216, 6.864, 3.514, 6.203, 6.759, 7.433, 7.874, 5.879,
+ 1.396, 4.094])
+ cj = xp.asarray(signal.cspline1d(_xp_copy_to_numpy(y)))
+ newy = xp.asarray([6.203, 4.41570658, 3.514, 5.16924703, 6.864, 6.04643068,
+ 4.21600281, 6.04643068, 6.864, 5.16924703, 3.514,
+ 4.41570658, 6.203, 6.80717667, 6.759, 6.98971173, 7.433,
+ 7.79560142, 7.874, 7.41525761, 5.879, 3.18686814, 1.396,
+ 2.24889482, 4.094, 2.24889482, 1.396, 3.18686814, 5.879,
+ 7.41525761, 7.874, 7.79560142, 7.433, 6.98971173, 6.759,
+ 6.80717667, 6.203, 4.41570658], dtype=xp.float64)
+ xp_assert_close(
+ signal.cspline1d_eval(cj, xp.asarray(newx), dx=dx, x0=x[0]), newy
+ )
+
+ with pytest.raises(ValueError,
+ match="Spline coefficients 'cj' must not be empty."):
+ signal.cspline1d_eval(xp.asarray([], dtype=xp.float64),
+ xp.asarray([0.0], dtype=xp.float64))
+
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/pull/9484")
+ @make_xp_test_case(signal.qspline1d_eval)
+ def test_qspline1d_eval(self, xp):
+ xp_assert_close(signal.qspline1d_eval(xp.asarray([0., 0]), xp.asarray([0.])),
+ xp.asarray([0.])
+ )
+ xp_assert_equal(signal.qspline1d_eval(xp.asarray([1., 0, 1]), xp.asarray([])),
+ xp.asarray([])
+ )
+
+ # Test case for newx that gets filtered down to empty
+ r = signal.qspline1d_eval(xp.asarray([1.0, 0, 1], dtype=xp.float64),
+ xp.asarray([-1.0], dtype=xp.float64))
+ xp_assert_equal(r, xp.asarray([0.25], dtype=xp.float64))
+
+ x = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6]
+ dx = x[1] - x[0]
+ newx = [-6., -5.5, -5., -4.5, -4., -3.5, -3., -2.5, -2., -1.5, -1.,
+ -0.5, 0., 0.5, 1., 1.5, 2., 2.5, 3., 3.5, 4., 4.5, 5., 5.5, 6.,
+ 6.5, 7., 7.5, 8., 8.5, 9., 9.5, 10., 10.5, 11., 11.5, 12.,
+ 12.5]
+ y = xp.asarray([4.216, 6.864, 3.514, 6.203, 6.759, 7.433, 7.874, 5.879,
+ 1.396, 4.094])
+ cj = signal.qspline1d(y)
+ newy = xp.asarray([6.203, 4.49418159, 3.514, 5.18390821, 6.864, 5.91436915,
+ 4.21600002, 5.91436915, 6.864, 5.18390821, 3.514,
+ 4.49418159, 6.203, 6.71900226, 6.759, 7.03980488, 7.433,
+ 7.81016848, 7.874, 7.32718426, 5.879, 3.23872593, 1.396,
+ 2.34046013, 4.094, 2.34046013, 1.396, 3.23872593, 5.879,
+ 7.32718426, 7.874, 7.81016848, 7.433, 7.03980488, 6.759,
+ 6.71900226, 6.203, 4.49418159], dtype=xp.float64)
+ r = signal.qspline1d_eval(
+ cj, xp.asarray(newx, dtype=xp.float64), dx=dx, x0=x[0]
+ )
+ xp_assert_close(r, newy)
+
+ with pytest.raises(ValueError,
+ match="Spline coefficients 'cj' must not be empty."):
+ signal.qspline1d_eval(xp.asarray([], dtype=xp.float64),
+ xp.asarray([0.0], dtype=xp.float64))
+
+
+# i/o dtypes with scipy 1.9.1, likely fixed by backwards compat
+sepfir_dtype_map = {np.uint8: np.float32, int: np.float64,
+ np.float32: np.float32, float: float,
+ np.complex64: np.complex64, complex: complex}
+
+
+@skip_xp_backends(np_only=True)
+class TestSepfir2d:
+ def test_sepfir2d_invalid_filter(self, xp):
+ filt = xp.asarray([1.0, 2.0, 4.0, 2.0, 1.0])
+ image = np.random.rand(7, 9)
+ image = xp.asarray(image)
+ # No error for odd lengths
+ signal.sepfir2d(image, filt, filt[2:])
+
+ # Row or column filter must be odd
+ with pytest.raises(ValueError, match="odd length"):
+ signal.sepfir2d(image, filt, filt[1:])
+ with pytest.raises(ValueError, match="odd length"):
+ signal.sepfir2d(image, filt[1:], filt)
+
+ # Filters must be 1-dimensional
+ with pytest.raises(ValueError, match="object too deep"):
+ signal.sepfir2d(image, xp.reshape(filt, (1, -1)), filt)
+ with pytest.raises(ValueError, match="object too deep"):
+ signal.sepfir2d(image, filt, xp.reshape(filt, (1, -1)))
+
+ def test_sepfir2d_invalid_image(self, xp):
+ filt = xp.asarray([1.0, 2.0, 4.0, 2.0, 1.0])
+ image = np.random.rand(8, 8)
+ image = xp.asarray(image)
+
+ # Image must be 2 dimensional
+ with pytest.raises(ValueError, match="object too deep"):
+ signal.sepfir2d(xp.reshape(image, (4, 4, 4)), filt, filt)
+
+ with pytest.raises(ValueError, match="object of too small depth"):
+ signal.sepfir2d(image[0, :], filt, filt)
+
+ @pytest.mark.parametrize('dtyp',
+ [np.uint8, int, np.float32, float, np.complex64, complex]
+ )
+ def test_simple(self, dtyp, xp):
+ # test values on a paper-and-pencil example
+ a = np.array([[1, 2, 3, 3, 2, 1],
+ [1, 2, 3, 3, 2, 1],
+ [1, 2, 3, 3, 2, 1],
+ [1, 2, 3, 3, 2, 1]], dtype=dtyp)
+ h1 = [0.5, 1, 0.5]
+ h2 = [1]
+ result = signal.sepfir2d(a, h1, h2)
+ dt = sepfir_dtype_map[dtyp]
+ expected = np.asarray([[2.5, 4. , 5.5, 5.5, 4. , 2.5],
+ [2.5, 4. , 5.5, 5.5, 4. , 2.5],
+ [2.5, 4. , 5.5, 5.5, 4. , 2.5],
+ [2.5, 4. , 5.5, 5.5, 4. , 2.5]], dtype=dt)
+ xp_assert_close(result, expected, atol=1e-16)
+
+ result = signal.sepfir2d(a, h2, h1)
+ expected = np.asarray([[2., 4., 6., 6., 4., 2.],
+ [2., 4., 6., 6., 4., 2.],
+ [2., 4., 6., 6., 4., 2.],
+ [2., 4., 6., 6., 4., 2.]], dtype=dt)
+ xp_assert_close(result, expected, atol=1e-16)
+
+ @skip_xp_backends(np_only=True, reason="TODO: convert this test")
+ @pytest.mark.parametrize('dtyp',
+ [np.uint8, int, np.float32, float, np.complex64, complex]
+ )
+ def test_strided(self, dtyp, xp):
+ a = np.array([[1, 2, 3, 3, 2, 1, 1, 2, 3],
+ [1, 2, 3, 3, 2, 1, 1, 2, 3],
+ [1, 2, 3, 3, 2, 1, 1, 2, 3],
+ [1, 2, 3, 3, 2, 1, 1, 2, 3]])
+ h1, h2 = [0.5, 1, 0.5], [1]
+ result_strided = signal.sepfir2d(a[:, ::2], h1, h2)
+ result_contig = signal.sepfir2d(a[:, ::2].copy(), h1, h2)
+ xp_assert_close(result_strided, result_contig, atol=1e-15)
+ assert result_strided.dtype == result_contig.dtype
+
+ @skip_xp_backends(np_only=True, reason="TODO: convert this test")
+ @pytest.mark.xfail(reason="XXX: filt.size > image.shape: flaky")
+ def test_sepfir2d_strided_2(self, xp):
+ # XXX: this test is flaky: fails on some reruns, with
+ # result[0, 1] and result[1, 1] being ~1e+224.
+ filt = np.array([1.0, 2.0, 4.0, 2.0, 1.0, 3.0, 2.0])
+ image = np.random.rand(4, 4)
+
+ expected = np.asarray([[36.018162, 30.239061, 38.71187 , 43.878183],
+ [38.180999, 35.824583, 43.525247, 43.874945],
+ [43.269533, 40.834018, 46.757772, 44.276423],
+ [49.120928, 39.681844, 43.596067, 45.085854]])
+ xp_assert_close(signal.sepfir2d(image, filt, filt[::3]), expected)
+
+ @skip_xp_backends(np_only=True, reason="TODO: convert this test")
+ @pytest.mark.xfail(reason="XXX: flaky. pointers OOB on some platforms")
+ @pytest.mark.fail_asan
+ @pytest.mark.parametrize('dtyp',
+ [np.uint8, int, np.float32, float, np.complex64, complex]
+ )
+ def test_sepfir2d_strided_3(self, dtyp, xp):
+ # NB: 'image' and 'filt' dtypes match here. Otherwise we can run into
+ # unsafe casting errors for many combinations. Historically, dtype handling
+ # in `sepfir2d` is a tad baroque; fixing it is an enhancement.
+ filt = np.array([1, 2, 4, 2, 1, 3, 2], dtype=dtyp)
+ image = np.asarray([[0, 3, 0, 1, 2],
+ [2, 2, 3, 3, 3],
+ [0, 1, 3, 0, 3],
+ [2, 3, 0, 1, 3],
+ [3, 3, 2, 1, 2]], dtype=dtyp)
+
+ expected = [[123., 101., 91., 136., 127.],
+ [133., 125., 126., 152., 160.],
+ [136., 137., 150., 162., 177.],
+ [133., 124., 132., 148., 147.],
+ [173., 158., 152., 164., 141.]]
+ expected = np.asarray(expected)
+ result = signal.sepfir2d(image, filt, filt[::3])
+ xp_assert_close(result, expected, atol=1e-15)
+ assert result.dtype == sepfir_dtype_map[dtyp]
+
+ expected = [[22., 35., 41., 31., 47.],
+ [27., 39., 48., 47., 55.],
+ [33., 42., 49., 53., 59.],
+ [39., 44., 41., 36., 48.],
+ [67., 62., 47., 34., 46.]]
+ expected = np.asarray(expected)
+ result = signal.sepfir2d(image, filt[::3], filt[::3])
+ xp_assert_close(result, expected, atol=1e-15)
+ assert result.dtype == sepfir_dtype_map[dtyp]
+
+
+@make_xp_test_case(signal.cspline2d)
+def test_cspline2d(xp):
+ rng = np.random.RandomState(181819142)
+ image = rng.rand(71, 73)
+ image = xp.asarray(image, dtype=xp_default_dtype(xp))
+ result = signal.cspline2d(image, 8.0)
+ assert array_namespace(result) == xp
+
+
+@make_xp_test_case(signal.qspline2d)
+def test_qspline2d(xp):
+ rng = np.random.RandomState(181819143)
+ image = rng.rand(71, 73)
+ image = xp.asarray(image, dtype=xp_default_dtype(xp))
+ result = signal.qspline2d(image)
+ assert array_namespace(result) == xp
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_cont2discrete.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_cont2discrete.py
new file mode 100644
index 0000000000000000000000000000000000000000..c01ddab40da1793e72c06d7964757480f7a58fc7
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_cont2discrete.py
@@ -0,0 +1,438 @@
+import math
+import numpy as np
+from scipy._lib._array_api import (
+ assert_array_almost_equal, xp_assert_close,
+ make_xp_test_case
+)
+
+import pytest
+from scipy.signal import cont2discrete as c2d
+from scipy.signal import dlsim, ss2tf, ss2zpk, lsim, lti
+from scipy.signal import tf2ss, impulse, dimpulse, step, dstep
+
+# Author: Jeffrey Armstrong
+# March 29, 2011
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+@make_xp_test_case(c2d)
+class TestC2D:
+ def test_zoh(self, xp):
+ ac = xp.eye(2, dtype=xp.float64)
+ bc = xp.full((2, 1), 0.5, dtype=xp.float64)
+ cc = xp.asarray([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]])
+ dc = xp.asarray([[0.0], [0.0], [-0.33]])
+
+ ad_truth = 1.648721270700128 * xp.eye(2)
+ bd_truth = xp.full((2, 1), 0.324360635350064)
+ # c and d in discrete should be equal to their continuous counterparts
+ dt_requested = 0.5
+
+ ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, method='zoh')
+
+ assert_array_almost_equal(ad_truth, ad)
+ assert_array_almost_equal(bd_truth, bd)
+ assert_array_almost_equal(cc, cd)
+ assert_array_almost_equal(dc, dd)
+ assert math.isclose(dt, dt_requested, abs_tol=1e-14)
+
+ def test_foh(self, xp):
+ ac = xp.eye(2)
+ bc = xp.full((2, 1), 0.5)
+ cc = xp.asarray([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]])
+ dc = xp.asarray([[0.0], [0.0], [-0.33]])
+
+ # True values are verified with Matlab
+ ad_truth = 1.648721270700128 * xp.eye(2)
+ bd_truth = xp.full((2, 1), 0.420839287058789)
+ cd_truth = cc
+ dd_truth = xp.asarray([[0.260262223725224],
+ [0.297442541400256],
+ [-0.144098411624840]])
+ dt_requested = 0.5
+
+ ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested, method='foh')
+
+ assert_array_almost_equal(ad_truth, ad)
+ assert_array_almost_equal(bd_truth, bd)
+ assert_array_almost_equal(cd_truth, cd)
+ assert_array_almost_equal(dd_truth, dd)
+ assert math.isclose(dt, dt_requested, abs_tol=1e-14)
+
+ def test_impulse(self, xp):
+ ac = xp.eye(2)
+ bc = xp.full((2, 1), 0.5)
+ cc = xp.asarray([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]])
+ dc = xp.asarray([[0.0], [0.0], [0.0]])
+
+ # True values are verified with Matlab
+ ad_truth = 1.648721270700128 * xp.eye(2)
+ bd_truth = xp.full((2, 1), 0.412180317675032)
+ cd_truth = cc
+ dd_truth = xp.asarray([[0.4375], [0.5], [0.3125]])
+ dt_requested = 0.5
+
+ ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested,
+ method='impulse')
+
+ assert_array_almost_equal(ad_truth, ad)
+ assert_array_almost_equal(bd_truth, bd)
+ assert_array_almost_equal(cd_truth, cd)
+ assert_array_almost_equal(dd_truth, dd)
+ assert math.isclose(dt, dt_requested, abs_tol=1e-14)
+
+ def test_gbt(self, xp):
+ ac = xp.eye(2)
+ bc = xp.full((2, 1), 0.5)
+ cc = xp.asarray([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]])
+ dc = xp.asarray([[0.0], [0.0], [-0.33]])
+
+ dt_requested = 0.5
+ alpha = 1.0 / 3.0
+
+ ad_truth = 1.6 * xp.eye(2)
+ bd_truth = xp.full((2, 1), 0.3)
+ cd_truth = xp.asarray([[0.9, 1.2],
+ [1.2, 1.2],
+ [1.2, 0.3]])
+ dd_truth = xp.asarray([[0.175],
+ [0.2],
+ [-0.205]])
+
+ ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested,
+ method='gbt', alpha=alpha)
+
+ assert_array_almost_equal(ad_truth, ad)
+ assert_array_almost_equal(bd_truth, bd)
+ assert_array_almost_equal(cd_truth, cd)
+ assert_array_almost_equal(dd_truth, dd)
+
+ def test_euler(self, xp):
+ ac = xp.eye(2)
+ bc = xp.full((2, 1), 0.5)
+ cc = xp.asarray([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]])
+ dc = xp.asarray([[0.0], [0.0], [-0.33]])
+
+ dt_requested = 0.5
+
+ ad_truth = 1.5 * xp.eye(2)
+ bd_truth = xp.full((2, 1), 0.25)
+ cd_truth = xp.asarray([[0.75, 1.0],
+ [1.0, 1.0],
+ [1.0, 0.25]])
+ dd_truth = dc
+
+ ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested,
+ method='euler')
+
+ assert_array_almost_equal(ad_truth, ad)
+ assert_array_almost_equal(bd_truth, bd)
+ assert_array_almost_equal(cd_truth, cd)
+ assert_array_almost_equal(dd_truth, dd)
+ assert math.isclose(dt, dt_requested, abs_tol=1e-14)
+
+ def test_backward_diff(self, xp):
+ ac = xp.eye(2)
+ bc = xp.full((2, 1), 0.5)
+ cc = xp.asarray([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]])
+ dc = xp.asarray([[0.0], [0.0], [-0.33]])
+
+ dt_requested = 0.5
+
+ ad_truth = 2.0 * xp.eye(2)
+ bd_truth = xp.full((2, 1), 0.5)
+ cd_truth = xp.asarray([[1.5, 2.0],
+ [2.0, 2.0],
+ [2.0, 0.5]])
+ dd_truth = xp.asarray([[0.875],
+ [1.0],
+ [0.295]])
+
+ ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested,
+ method='backward_diff')
+
+ assert_array_almost_equal(ad_truth, ad)
+ assert_array_almost_equal(bd_truth, bd)
+ assert_array_almost_equal(cd_truth, cd)
+ assert_array_almost_equal(dd_truth, dd)
+
+ def test_bilinear(self, xp):
+ ac = xp.eye(2)
+ bc = xp.full((2, 1), 0.5)
+ cc = xp.asarray([[0.75, 1.0], [1.0, 1.0], [1.0, 0.25]])
+ dc = xp.asarray([[0.0], [0.0], [-0.33]])
+
+ dt_requested = 0.5
+
+ ad_truth = (5.0 / 3.0) * xp.eye(2)
+ bd_truth = xp.full((2, 1), 1.0 / 3.0)
+ cd_truth = xp.asarray([[1.0, 4.0 / 3.0],
+ [4.0 / 3.0, 4.0 / 3.0],
+ [4.0 / 3.0, 1.0 / 3.0]])
+ dd_truth = xp.asarray([[0.291666666666667],
+ [1.0 / 3.0],
+ [-0.121666666666667]])
+
+ ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested,
+ method='bilinear')
+
+ assert_array_almost_equal(ad_truth, ad)
+ assert_array_almost_equal(bd_truth, bd)
+ assert_array_almost_equal(cd_truth, cd)
+ assert_array_almost_equal(dd_truth, dd)
+ assert math.isclose(dt, dt_requested, abs_tol=1e-14)
+
+ # Same continuous system again, but change sampling rate
+
+ ad_truth = 1.4 * xp.eye(2)
+ bd_truth = xp.full((2, 1), 0.2)
+ cd_truth = xp.asarray([[0.9, 1.2], [1.2, 1.2], [1.2, 0.3]])
+ dd_truth = xp.asarray([[0.175], [0.2], [-0.205]])
+
+ dt_requested = 1.0 / 3.0
+
+ ad, bd, cd, dd, dt = c2d((ac, bc, cc, dc), dt_requested,
+ method='bilinear')
+
+ assert_array_almost_equal(ad_truth, ad)
+ assert_array_almost_equal(bd_truth, bd)
+ assert_array_almost_equal(cd_truth, cd)
+ assert_array_almost_equal(dd_truth, dd)
+ assert math.isclose(dt_requested, dt)
+
+ def test_transferfunction(self, xp):
+ numc = xp.asarray([0.25, 0.25, 0.5])
+ denc = xp.asarray([0.75, 0.75, 1.0])
+
+ numd = xp.asarray([[1.0 / 3.0, -0.427419169438754, 0.221654141101125]])
+ dend = xp.asarray([1.0, -1.351394049721225, 0.606530659712634])
+
+ dt_requested = 0.5
+
+ num, den, dt = c2d((numc, denc), dt_requested, method='zoh')
+
+ assert_array_almost_equal(numd, num)
+ assert_array_almost_equal(dend, den)
+ assert math.isclose(dt_requested, dt)
+
+ def test_zerospolesgain(self, xp):
+ zeros_c = xp.array([0.5, -0.5])
+ poles_c = xp.array([1.j / xp.sqrt(2), -1.j / xp.sqrt(2)])
+ k_c = 1.0
+
+ zeros_d = xp.asarray([1.23371727305860, 0.735356894461267])
+ polls_d = xp.asarray([0.938148335039729 + 0.346233593780536j,
+ 0.938148335039729 - 0.346233593780536j])
+ k_d = 1.0
+
+ dt_requested = 0.5
+
+ zeros, poles, k, dt = c2d((zeros_c, poles_c, k_c), dt_requested,
+ method='zoh')
+
+ assert_array_almost_equal(zeros_d, zeros)
+ assert_array_almost_equal(polls_d, poles)
+ assert math.isclose(k_d, k)
+ assert math.isclose(dt_requested, dt)
+
+ @skip_xp_backends(np_only=True)
+ def test_gbt_with_sio_tf_and_zpk(self, xp):
+ """Test method='gbt' with alpha=0.25 for tf and zpk cases."""
+ # State space coefficients for the continuous SIO system.
+ A = -1.0
+ B = 1.0
+ C = 1.0
+ D = 0.5
+
+ # The continuous transfer function coefficients.
+ cnum, cden = ss2tf(A, B, C, D)
+
+ # Continuous zpk representation
+ cz, cp, ck = ss2zpk(A, B, C, D)
+
+ h = 1.0
+ alpha = 0.25
+
+ # Explicit formulas, in the scalar case.
+ Ad = (1 + (1 - alpha) * h * A) / (1 - alpha * h * A)
+ Bd = h * B / (1 - alpha * h * A)
+ Cd = C / (1 - alpha * h * A)
+ Dd = D + alpha * C * Bd
+
+ # Convert the explicit solution to tf
+ dnum, dden = ss2tf(Ad, Bd, Cd, Dd)
+
+ # Compute the discrete tf using cont2discrete.
+ c2dnum, c2dden, dt = c2d((cnum, cden), h, method='gbt', alpha=alpha)
+
+ xp_assert_close(dnum, c2dnum)
+ xp_assert_close(dden, c2dden)
+
+ # Convert explicit solution to zpk.
+ dz, dp, dk = ss2zpk(Ad, Bd, Cd, Dd)
+
+ # Compute the discrete zpk using cont2discrete.
+ c2dz, c2dp, c2dk, dt = c2d((cz, cp, ck), h, method='gbt', alpha=alpha)
+
+ xp_assert_close(dz, c2dz)
+ xp_assert_close(dp, c2dp)
+ xp_assert_close(dk, c2dk)
+
+ def test_discrete_approx(self, xp):
+ """
+ Test that the solution to the discrete approximation of a continuous
+ system actually approximates the solution to the continuous system.
+ This is an indirect test of the correctness of the implementation
+ of cont2discrete.
+ """
+
+ def u(t):
+ return xp.sin(2.5 * t)
+
+ a = xp.asarray([[-0.01]])
+ b = xp.asarray([[1.0]])
+ c = xp.asarray([[1.0]])
+ d = xp.asarray([[0.2]])
+ x0 = 1.0
+
+ t = xp.linspace(0, 10.0, 101)
+ dt = t[1] - t[0]
+ u1 = u(t)
+
+ # Use lsim to compute the solution to the continuous system.
+ t, yout, xout = lsim((a, b, c, d), T=t, U=u1, X0=x0)
+
+ # Convert the continuous system to a discrete approximation.
+ dsys = c2d((a, b, c, d), dt, method='bilinear')
+
+ # Use dlsim with the pairwise averaged input to compute the output
+ # of the discrete system.
+ u2 = 0.5 * (u1[:-1] + u1[1:])
+ t2 = t[:-1]
+ td2, yd2, xd2 = dlsim(dsys, u=u2.reshape(-1, 1), t=t2, x0=x0)
+
+ # ymid is the average of consecutive terms of the "exact" output
+ # computed by lsim2. This is what the discrete approximation
+ # actually approximates.
+ ymid = 0.5 * (yout[:-1] + yout[1:])
+
+ xp_assert_close(yd2.ravel(), ymid, rtol=1e-4)
+
+ @skip_xp_backends(np_only=True)
+ def test_simo_tf(self):
+ # See gh-5753
+ tf = ([[1, 0], [1, 1]], [1, 1])
+ num, den, dt = c2d(tf, 0.01)
+
+ assert dt == 0.01 # sanity check
+ xp_assert_close(den, [1, -0.990404983], rtol=1e-3)
+ xp_assert_close(num, [[1, -1], [1, -0.99004983]], rtol=1e-3)
+
+ @skip_xp_backends(np_only=True)
+ def test_multioutput(self):
+ ts = 0.01 # time step
+
+ tf = ([[1, -3], [1, 5]], [1, 1])
+ num, den, dt = c2d(tf, ts)
+
+ tf1 = (tf[0][0], tf[1])
+ num1, den1, dt1 = c2d(tf1, ts)
+
+ tf2 = (tf[0][1], tf[1])
+ num2, den2, dt2 = c2d(tf2, ts)
+
+ # Sanity checks
+ assert dt == dt1
+ assert dt == dt2
+
+ # Check that we get the same results
+ xp_assert_close(num, np.vstack((num1, num2)), rtol=1e-13)
+
+ # Single input, so the denominator should
+ # not be multidimensional like the numerator
+ xp_assert_close(den, den1, rtol=1e-13)
+ xp_assert_close(den, den2, rtol=1e-13)
+
+@skip_xp_backends(np_only=True, reason="lti currently not supported")
+class TestC2dLti:
+ def test_c2d_ss(self, xp):
+ # StateSpace
+ A = np.array([[-0.3, 0.1], [0.2, -0.7]])
+ B = np.array([[0], [1]])
+ C = np.array([[1, 0]])
+ D = 0
+ dt = 0.05
+
+ A_res = np.array([[0.985136404135682, 0.004876671474795],
+ [0.009753342949590, 0.965629718236502]])
+ B_res = np.array([[0.000122937599964], [0.049135527547844]])
+
+ sys_ssc = lti(A, B, C, D)
+ sys_ssd = sys_ssc.to_discrete(dt=dt)
+
+ xp_assert_close(sys_ssd.A, A_res)
+ xp_assert_close(sys_ssd.B, B_res)
+ xp_assert_close(sys_ssd.C, C)
+ xp_assert_close(sys_ssd.D, np.zeros_like(sys_ssd.D))
+
+ sys_ssd2 = c2d(sys_ssc, dt=dt)
+
+ xp_assert_close(sys_ssd2.A, A_res)
+ xp_assert_close(sys_ssd2.B, B_res)
+ xp_assert_close(sys_ssd2.C, C)
+ xp_assert_close(sys_ssd2.D, np.zeros_like(sys_ssd2.D))
+
+ def test_c2d_tf(self, xp):
+
+ sys = lti([0.5, 0.3], [1.0, 0.4])
+ sys = sys.to_discrete(0.005)
+
+ # Matlab results
+ num_res = np.array([0.5, -0.485149004980066])
+ den_res = np.array([1.0, -0.980198673306755])
+
+ # Somehow a lot of numerical errors
+ xp_assert_close(sys.den, den_res, atol=0.02)
+ xp_assert_close(sys.num, num_res, atol=0.02)
+
+
+@make_xp_test_case(c2d)
+class TestC2dInvariants:
+ # Some test cases for checking the invariances.
+ # Array of triplets: (system, sample time, number of samples)
+ cases = [
+ (tf2ss([1, 1], [1, 1.5, 1]), 0.25, 10),
+ (tf2ss([1, 2], [1, 1.5, 3, 1]), 0.5, 10),
+ (tf2ss(0.1, [1, 1, 2, 1]), 0.5, 10),
+ ]
+
+ # Check that systems discretized with the impulse-invariant
+ # method really hold the invariant
+ @make_xp_test_case(impulse, dimpulse)
+ @pytest.mark.parametrize("sys,sample_time,samples_number", cases)
+ def test_impulse_invariant(self, xp, sys, sample_time, samples_number):
+ sys = tuple(map(xp.asarray, sys))
+ time = xp.arange(samples_number) * sample_time
+ _, yout_cont = impulse(sys, T=time)
+ _, yout_disc = dimpulse(c2d(sys, sample_time, method='impulse'),
+ n=len(time))
+ xp_assert_close(sample_time * yout_cont.ravel(), yout_disc[0].ravel())
+
+ # Step invariant should hold for ZOH discretized systems
+ @pytest.mark.parametrize("sys,sample_time,samples_number", cases)
+ def test_step_invariant(self, xp, sys, sample_time, samples_number):
+ sys = tuple(map(xp.asarray, sys))
+ time = xp.arange(samples_number) * sample_time
+ _, yout_cont = step(sys, T=time)
+ _, yout_disc = dstep(c2d(sys, sample_time, method='zoh'), n=len(time))
+ xp_assert_close(yout_cont.ravel(), yout_disc[0].ravel())
+
+ # Linear invariant should hold for FOH discretized systems
+ @pytest.mark.parametrize("sys,sample_time,samples_number", cases)
+ def test_linear_invariant(self, xp, sys, sample_time, samples_number):
+ sys = tuple(map(xp.asarray, sys))
+ time = xp.arange(samples_number) * sample_time
+ _, yout_cont, _ = lsim(sys, T=time, U=time)
+ _, yout_disc, _ = dlsim(c2d(sys, sample_time, method='foh'), u=time)
+ xp_assert_close(yout_cont.ravel(), yout_disc.ravel())
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_czt.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_czt.py
new file mode 100644
index 0000000000000000000000000000000000000000..35087d99fec5057131f0735d43e0faa33a74ef82
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_czt.py
@@ -0,0 +1,221 @@
+# This program is public domain
+# Authors: Paul Kienzle, Nadav Horesh
+'''
+A unit test module for czt.py
+'''
+import pytest
+from scipy._lib._array_api import xp_assert_close
+from scipy.fft import fft
+from scipy.signal import (czt, zoom_fft, czt_points, CZT, ZoomFFT)
+import numpy as np
+
+
+def check_czt(x):
+ # Check that czt is the equivalent of normal fft
+ y = fft(x)
+ y1 = czt(x)
+ xp_assert_close(y1, y, rtol=1e-13)
+
+ # Check that interpolated czt is the equivalent of normal fft
+ y = fft(x, 100*len(x))
+ y1 = czt(x, 100*len(x))
+ xp_assert_close(y1, y, rtol=1e-12)
+
+
+def check_zoom_fft(x):
+ # Check that zoom_fft is the equivalent of normal fft
+ y = fft(x)
+ y1 = zoom_fft(x, [0, 2-2./len(y)], endpoint=True)
+ xp_assert_close(y1, y, rtol=1e-11, atol=1e-14)
+ y1 = zoom_fft(x, [0, 2])
+ xp_assert_close(y1, y, rtol=1e-11, atol=1e-14)
+
+ # Test fn scalar
+ y1 = zoom_fft(x, 2-2./len(y), endpoint=True)
+ xp_assert_close(y1, y, rtol=1e-11, atol=1e-14)
+ y1 = zoom_fft(x, 2)
+ xp_assert_close(y1, y, rtol=1e-11, atol=1e-14)
+
+ # Check that zoom_fft with oversampling is equivalent to zero padding
+ over = 10
+ yover = fft(x, over*len(x))
+ y2 = zoom_fft(x, [0, 2-2./len(yover)], m=len(yover), endpoint=True)
+ xp_assert_close(y2, yover, rtol=1e-12, atol=1e-10)
+ y2 = zoom_fft(x, [0, 2], m=len(yover))
+ xp_assert_close(y2, yover, rtol=1e-12, atol=1e-10)
+
+ # Check that zoom_fft works on a subrange
+ w = np.linspace(0, 2-2./len(x), len(x))
+ f1, f2 = w[3], w[6]
+ y3 = zoom_fft(x, [f1, f2], m=3*over+1, endpoint=True)
+ idx3 = slice(3*over, 6*over+1)
+ xp_assert_close(y3, yover[idx3], rtol=1e-13)
+
+
+def test_1D():
+ # Test of 1D version of the transforms
+
+ rng = np.random.RandomState(0) # Deterministic randomness
+
+ # Random signals
+ lengths = rng.randint(8, 200, 20)
+ np.append(lengths, 1)
+ for length in lengths:
+ x = rng.random(length)
+ check_zoom_fft(x)
+ check_czt(x)
+
+ # Gauss
+ t = np.linspace(-2, 2, 128)
+ x = np.exp(-t**2/0.01)
+ check_zoom_fft(x)
+
+ # Linear
+ x = [1, 2, 3, 4, 5, 6, 7]
+ check_zoom_fft(x)
+
+ # Check near powers of two
+ check_zoom_fft(range(126-31))
+ check_zoom_fft(range(127-31))
+ check_zoom_fft(range(128-31))
+ check_zoom_fft(range(129-31))
+ check_zoom_fft(range(130-31))
+
+ # Check transform on n-D array input
+ x = np.reshape(np.arange(3*2*28), (3, 2, 28))
+ y1 = zoom_fft(x, [0, 2-2./28])
+ y2 = zoom_fft(x[2, 0, :], [0, 2-2./28])
+ xp_assert_close(y1[2, 0], y2, rtol=1e-13, atol=1e-12)
+
+ y1 = zoom_fft(x, [0, 2], endpoint=False)
+ y2 = zoom_fft(x[2, 0, :], [0, 2], endpoint=False)
+ xp_assert_close(y1[2, 0], y2, rtol=1e-13, atol=1e-12)
+
+ # Random (not a test condition)
+ x = rng.rand(101)
+ check_zoom_fft(x)
+
+ # Spikes
+ t = np.linspace(0, 1, 128)
+ x = np.sin(2*np.pi*t*5)+np.sin(2*np.pi*t*13)
+ check_zoom_fft(x)
+
+ # Sines
+ x = np.zeros(100, dtype=complex)
+ x[[1, 5, 21]] = 1
+ check_zoom_fft(x)
+
+ # Sines plus complex component
+ x += 1j*np.linspace(0, 0.5, x.shape[0])
+ check_zoom_fft(x)
+
+
+def test_large_prime_lengths():
+ rng = np.random.RandomState(0) # Deterministic randomness
+ for N in (101, 1009, 10007):
+ x = rng.rand(N)
+ y = fft(x)
+ y1 = czt(x)
+ xp_assert_close(y, y1, rtol=1e-12)
+
+
+@pytest.mark.slow
+def test_czt_vs_fft():
+ rng = np.random.RandomState(123) # Deterministic randomness
+ random_lengths = rng.exponential(100000, size=10).astype('int')
+ for n in random_lengths:
+ a = rng.randn(n)
+ xp_assert_close(czt(a), fft(a), rtol=1e-11)
+
+
+def test_empty_input():
+ with pytest.raises(ValueError, match='Invalid number of CZT'):
+ czt([])
+ with pytest.raises(ValueError, match='Invalid number of CZT'):
+ zoom_fft([], 0.5)
+
+
+def test_0_rank_input():
+ with pytest.raises(IndexError, match='tuple index out of range'):
+ czt(5)
+ with pytest.raises(IndexError, match='tuple index out of range'):
+ zoom_fft(5, 0.5)
+
+
+@pytest.mark.parametrize('impulse', ([0, 0, 1], [0, 0, 1, 0, 0],
+ np.concatenate((np.array([0, 0, 1]),
+ np.zeros(100)))))
+@pytest.mark.parametrize('m', (1, 3, 5, 8, 101, 1021))
+@pytest.mark.parametrize('a', (1, 2, 0.5, 1.1))
+# Step that tests away from the unit circle, but not so far it explodes from
+# numerical error
+@pytest.mark.parametrize('w', (None, 0.98534 + 0.17055j))
+def test_czt_math(impulse, m, w, a):
+ # z-transform of an impulse is 1 everywhere
+ xp_assert_close(czt(impulse[2:], m=m, w=w, a=a),
+ np.ones(m, dtype=np.complex128), rtol=1e-10)
+
+ # z-transform of a delayed impulse is z**-1
+ xp_assert_close(czt(impulse[1:], m=m, w=w, a=a),
+ czt_points(m=m, w=w, a=a)**-1, rtol=1e-10)
+
+ # z-transform of a 2-delayed impulse is z**-2
+ xp_assert_close(czt(impulse, m=m, w=w, a=a),
+ czt_points(m=m, w=w, a=a)**-2, rtol=1e-10)
+
+
+def test_int_args():
+ # Integer argument `a` was producing all 0s
+ xp_assert_close(abs(czt([0, 1], m=10, a=2)), 0.5*np.ones(10), rtol=1e-15)
+ xp_assert_close(czt_points(11, w=2),
+ 1/(2**np.arange(11, dtype=np.complex128)), rtol=1e-30)
+
+
+def test_czt_points():
+ for N in (1, 2, 3, 8, 11, 100, 101, 10007):
+ xp_assert_close(czt_points(N), np.exp(2j*np.pi*np.arange(N)/N),
+ rtol=1e-30)
+
+ xp_assert_close(czt_points(7, w=1), np.ones(7, dtype=np.complex128), rtol=1e-30)
+ xp_assert_close(czt_points(11, w=2.),
+ 1/(2**np.arange(11, dtype=np.complex128)), rtol=1e-30)
+
+ func = CZT(12, m=11, w=2., a=1)
+ xp_assert_close(func.points(), 1/(2**np.arange(11)), rtol=1e-30)
+
+
+@pytest.mark.parametrize('cls, args', [(CZT, (100,)), (ZoomFFT, (100, 0.2))])
+def test_CZT_size_mismatch(cls, args):
+ # Data size doesn't match function's expected size
+ myfunc = cls(*args)
+ with pytest.raises(ValueError, match='CZT defined for'):
+ myfunc(np.arange(5))
+
+
+def test_invalid_range():
+ with pytest.raises(ValueError, match='2-length sequence'):
+ ZoomFFT(100, [1, 2, 3])
+
+
+@pytest.mark.parametrize('m', [0, -11, 5.5, 4.0])
+def test_czt_points_errors(m):
+ # Invalid number of points
+ with pytest.raises(ValueError, match='Invalid number of CZT'):
+ czt_points(m)
+
+
+@pytest.mark.parametrize('size', [0, -5, 3.5, 4.0])
+def test_nonsense_size(size):
+ # Numpy and Scipy fft() give ValueError for 0 output size, so we do, too
+ with pytest.raises(ValueError, match='Invalid number of CZT'):
+ CZT(size, 3)
+ with pytest.raises(ValueError, match='Invalid number of CZT'):
+ ZoomFFT(size, 0.2, 3)
+ with pytest.raises(ValueError, match='Invalid number of CZT'):
+ CZT(3, size)
+ with pytest.raises(ValueError, match='Invalid number of CZT'):
+ ZoomFFT(3, 0.2, size)
+ with pytest.raises(ValueError, match='Invalid number of CZT'):
+ czt([1, 2, 3], size)
+ with pytest.raises(ValueError, match='Invalid number of CZT'):
+ zoom_fft([1, 2, 3], 0.2, size)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_dltisys.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_dltisys.py
new file mode 100644
index 0000000000000000000000000000000000000000..d18313c34b6a261fd688fa913971f94667c7f5cb
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_dltisys.py
@@ -0,0 +1,601 @@
+# Author: Jeffrey Armstrong
+# April 4, 2011
+import warnings
+
+import numpy as np
+from pytest import raises as assert_raises
+from scipy._lib._array_api import (
+ assert_array_almost_equal, assert_almost_equal, xp_assert_close, xp_assert_equal,
+)
+
+from scipy.signal import (dlsim, dstep, dimpulse, tf2zpk, lti, dlti,
+ StateSpace, TransferFunction, ZerosPolesGain,
+ dfreqresp, dbode, BadCoefficients)
+
+
+class TestDLTI:
+
+ def test_dlsim(self):
+
+ a = np.asarray([[0.9, 0.1], [-0.2, 0.9]])
+ b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]])
+ c = np.asarray([[0.1, 0.3]])
+ d = np.asarray([[0.0, -0.1, 0.0]])
+ dt = 0.5
+
+ # Create an input matrix with inputs down the columns (3 cols) and its
+ # respective time input vector
+ u = np.hstack((np.linspace(0, 4.0, num=5)[:, np.newaxis],
+ np.full((5, 1), 0.01),
+ np.full((5, 1), -0.002)))
+ t_in = np.linspace(0, 2.0, num=5)
+
+ # Define the known result
+ yout_truth = np.array([[-0.001,
+ -0.00073,
+ 0.039446,
+ 0.0915387,
+ 0.13195948]]).T
+ xout_truth = np.asarray([[0, 0],
+ [0.0012, 0.0005],
+ [0.40233, 0.00071],
+ [1.163368, -0.079327],
+ [2.2402985, -0.3035679]])
+
+ tout, yout, xout = dlsim((a, b, c, d, dt), u, t_in)
+
+ assert_array_almost_equal(yout_truth, yout)
+ assert_array_almost_equal(xout_truth, xout)
+ assert_array_almost_equal(t_in, tout)
+
+ # Make sure input with single-dimension doesn't raise error
+ dlsim((1, 2, 3), 4)
+
+ # Interpolated control - inputs should have different time steps
+ # than the discrete model uses internally
+ u_sparse = u[[0, 4], :]
+ t_sparse = np.asarray([0.0, 2.0])
+
+ tout, yout, xout = dlsim((a, b, c, d, dt), u_sparse, t_sparse)
+
+ assert_array_almost_equal(yout_truth, yout)
+ assert_array_almost_equal(xout_truth, xout)
+ assert len(tout) == len(yout)
+
+ # Transfer functions (assume dt = 0.5)
+ num = np.asarray([1.0, -0.1])
+ den = np.asarray([0.3, 1.0, 0.2])
+ yout_truth = np.array([[0.0,
+ 0.0,
+ 3.33333333333333,
+ -4.77777777777778,
+ 23.0370370370370]]).T
+
+ # Assume use of the first column of the control input built earlier
+ tout, yout = dlsim((num, den, 0.5), u[:, 0], t_in)
+
+ assert_array_almost_equal(yout, yout_truth)
+ assert_array_almost_equal(t_in, tout)
+
+ # Retest the same with a 1-D input vector
+ uflat = np.asarray(u[:, 0])
+ uflat = uflat.reshape((5,))
+ tout, yout = dlsim((num, den, 0.5), uflat, t_in)
+
+ assert_array_almost_equal(yout, yout_truth)
+ assert_array_almost_equal(t_in, tout)
+
+ # zeros-poles-gain representation
+ zd = np.array([0.5, -0.5])
+ pd = np.array([1.j / np.sqrt(2), -1.j / np.sqrt(2)])
+ k = 1.0
+ yout_truth = np.array([[0.0, 1.0, 2.0, 2.25, 2.5]]).T
+
+ tout, yout = dlsim((zd, pd, k, 0.5), u[:, 0], t_in)
+
+ assert_array_almost_equal(yout, yout_truth)
+ assert_array_almost_equal(t_in, tout)
+
+ # Raise an error for continuous-time systems
+ system = lti([1], [1, 1])
+ assert_raises(AttributeError, dlsim, system, u)
+
+ def test_dstep(self):
+
+ a = np.asarray([[0.9, 0.1], [-0.2, 0.9]])
+ b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]])
+ c = np.asarray([[0.1, 0.3]])
+ d = np.asarray([[0.0, -0.1, 0.0]])
+ dt = 0.5
+
+ # Because b.shape[1] == 3, dstep should result in a tuple of three
+ # result vectors
+ yout_step_truth = (np.asarray([0.0, 0.04, 0.052, 0.0404, 0.00956,
+ -0.036324, -0.093318, -0.15782348,
+ -0.226628324, -0.2969374948]),
+ np.asarray([-0.1, -0.075, -0.058, -0.04815,
+ -0.04453, -0.0461895, -0.0521812,
+ -0.061588875, -0.073549579,
+ -0.08727047595]),
+ np.asarray([0.0, -0.01, -0.013, -0.0101, -0.00239,
+ 0.009081, 0.0233295, 0.03945587,
+ 0.056657081, 0.0742343737]))
+
+ tout, yout = dstep((a, b, c, d, dt), n=10)
+
+ assert len(yout) == 3
+
+ for i in range(0, len(yout)):
+ assert yout[i].shape[0] == 10
+ assert_array_almost_equal(yout[i].flatten(), yout_step_truth[i])
+
+ # Check that the other two inputs (tf, zpk) will work as well
+ tfin = ([1.0], [1.0, 1.0], 0.5)
+ yout_tfstep = np.asarray([0.0, 1.0, 0.0])
+ tout, yout = dstep(tfin, n=3)
+ assert len(yout) == 1
+ assert_array_almost_equal(yout[0].flatten(), yout_tfstep)
+
+ zpkin = tf2zpk(tfin[0], tfin[1]) + (0.5,)
+ tout, yout = dstep(zpkin, n=3)
+ assert len(yout) == 1
+ assert_array_almost_equal(yout[0].flatten(), yout_tfstep)
+
+ # Raise an error for continuous-time systems
+ system = lti([1], [1, 1])
+ assert_raises(AttributeError, dstep, system)
+
+ def test_dimpulse(self):
+
+ a = np.asarray([[0.9, 0.1], [-0.2, 0.9]])
+ b = np.asarray([[0.4, 0.1, -0.1], [0.0, 0.05, 0.0]])
+ c = np.asarray([[0.1, 0.3]])
+ d = np.asarray([[0.0, -0.1, 0.0]])
+ dt = 0.5
+
+ # Because b.shape[1] == 3, dimpulse should result in a tuple of three
+ # result vectors
+ yout_imp_truth = (np.asarray([0.0, 0.04, 0.012, -0.0116, -0.03084,
+ -0.045884, -0.056994, -0.06450548,
+ -0.068804844, -0.0703091708]),
+ np.asarray([-0.1, 0.025, 0.017, 0.00985, 0.00362,
+ -0.0016595, -0.0059917, -0.009407675,
+ -0.011960704, -0.01372089695]),
+ np.asarray([0.0, -0.01, -0.003, 0.0029, 0.00771,
+ 0.011471, 0.0142485, 0.01612637,
+ 0.017201211, 0.0175772927]))
+
+ tout, yout = dimpulse((a, b, c, d, dt), n=10)
+
+ assert len(yout) == 3
+
+ for i in range(0, len(yout)):
+ assert yout[i].shape[0] == 10
+ assert_array_almost_equal(yout[i].flatten(), yout_imp_truth[i])
+
+ # Check that the other two inputs (tf, zpk) will work as well
+ tfin = ([1.0], [1.0, 1.0], 0.5)
+ yout_tfimpulse = np.asarray([0.0, 1.0, -1.0])
+ tout, yout = dimpulse(tfin, n=3)
+ assert len(yout) == 1
+ assert_array_almost_equal(yout[0].flatten(), yout_tfimpulse)
+
+ zpkin = tf2zpk(tfin[0], tfin[1]) + (0.5,)
+ tout, yout = dimpulse(zpkin, n=3)
+ assert len(yout) == 1
+ assert_array_almost_equal(yout[0].flatten(), yout_tfimpulse)
+
+ # Raise an error for continuous-time systems
+ system = lti([1], [1, 1])
+ assert_raises(AttributeError, dimpulse, system)
+
+ def test_dlsim_trivial(self):
+ a = np.array([[0.0]])
+ b = np.array([[0.0]])
+ c = np.array([[0.0]])
+ d = np.array([[0.0]])
+ n = 5
+ u = np.zeros(n).reshape(-1, 1)
+ tout, yout, xout = dlsim((a, b, c, d, 1), u)
+ xp_assert_equal(tout, np.arange(float(n)))
+ xp_assert_equal(yout, np.zeros((n, 1)))
+ xp_assert_equal(xout, np.zeros((n, 1)))
+
+ def test_dlsim_simple1d(self):
+ a = np.array([[0.5]])
+ b = np.array([[0.0]])
+ c = np.array([[1.0]])
+ d = np.array([[0.0]])
+ n = 5
+ u = np.zeros(n).reshape(-1, 1)
+ tout, yout, xout = dlsim((a, b, c, d, 1), u, x0=1)
+ xp_assert_equal(tout, np.arange(float(n)))
+ expected = (0.5 ** np.arange(float(n))).reshape(-1, 1)
+ xp_assert_equal(yout, expected)
+ xp_assert_equal(xout, expected)
+
+ def test_dlsim_simple2d(self):
+ lambda1 = 0.5
+ lambda2 = 0.25
+ a = np.array([[lambda1, 0.0],
+ [0.0, lambda2]])
+ b = np.array([[0.0],
+ [0.0]])
+ c = np.array([[1.0, 0.0],
+ [0.0, 1.0]])
+ d = np.array([[0.0],
+ [0.0]])
+ n = 5
+ u = np.zeros(n).reshape(-1, 1)
+ tout, yout, xout = dlsim((a, b, c, d, 1), u, x0=1)
+ xp_assert_equal(tout, np.arange(float(n)))
+ # The analytical solution:
+ expected = (np.array([lambda1, lambda2]) **
+ np.arange(float(n)).reshape(-1, 1))
+ xp_assert_equal(yout, expected)
+ xp_assert_equal(xout, expected)
+
+ def test_more_step_and_impulse(self):
+ lambda1 = 0.5
+ lambda2 = 0.75
+ a = np.array([[lambda1, 0.0],
+ [0.0, lambda2]])
+ b = np.array([[1.0, 0.0],
+ [0.0, 1.0]])
+ c = np.array([[1.0, 1.0]])
+ d = np.array([[0.0, 0.0]])
+
+ n = 10
+
+ # Check a step response.
+ ts, ys = dstep((a, b, c, d, 1), n=n)
+
+ # Create the exact step response.
+ stp0 = (1.0 / (1 - lambda1)) * (1.0 - lambda1 ** np.arange(n))
+ stp1 = (1.0 / (1 - lambda2)) * (1.0 - lambda2 ** np.arange(n))
+
+ xp_assert_close(ys[0][:, 0], stp0)
+ xp_assert_close(ys[1][:, 0], stp1)
+
+ # Check an impulse response with an initial condition.
+ x0 = np.array([1.0, 1.0])
+ ti, yi = dimpulse((a, b, c, d, 1), n=n, x0=x0)
+
+ # Create the exact impulse response.
+ imp = (np.array([lambda1, lambda2]) **
+ np.arange(-1, n + 1).reshape(-1, 1))
+ imp[0, :] = 0.0
+ # Analytical solution to impulse response
+ y0 = imp[:n, 0] + np.dot(imp[1:n + 1, :], x0)
+ y1 = imp[:n, 1] + np.dot(imp[1:n + 1, :], x0)
+
+ xp_assert_close(yi[0][:, 0], y0)
+ xp_assert_close(yi[1][:, 0], y1)
+
+ # Check that dt=0.1, n=3 gives 3 time values.
+ system = ([1.0], [1.0, -0.5], 0.1)
+ t, (y,) = dstep(system, n=3)
+ xp_assert_close(t, [0, 0.1, 0.2])
+ xp_assert_equal(y.T, [[0, 1.0, 1.5]])
+ t, (y,) = dimpulse(system, n=3)
+ xp_assert_close(t, [0, 0.1, 0.2])
+ xp_assert_equal(y.T, [[0, 1, 0.5]])
+
+
+class TestDlti:
+ def test_dlti_instantiation(self):
+ # Test that lti can be instantiated.
+
+ dt = 0.05
+ # TransferFunction
+ s = dlti([1], [-1], dt=dt)
+ assert isinstance(s, TransferFunction)
+ assert isinstance(s, dlti)
+ assert not isinstance(s, lti)
+ assert s.dt == dt
+
+ # ZerosPolesGain
+ s = dlti(np.array([]), np.array([-1]), 1, dt=dt)
+ assert isinstance(s, ZerosPolesGain)
+ assert isinstance(s, dlti)
+ assert not isinstance(s, lti)
+ assert s.dt == dt
+
+ # StateSpace
+ s = dlti([1], [-1], 1, 3, dt=dt)
+ assert isinstance(s, StateSpace)
+ assert isinstance(s, dlti)
+ assert not isinstance(s, lti)
+ assert s.dt == dt
+
+ # Number of inputs
+ assert_raises(ValueError, dlti, 1)
+ assert_raises(ValueError, dlti, 1, 1, 1, 1, 1)
+
+
+class TestStateSpaceDisc:
+ def test_initialization(self):
+ # Check that all initializations work
+ dt = 0.05
+ StateSpace(1, 1, 1, 1, dt=dt)
+ StateSpace([1], [2], [3], [4], dt=dt)
+ StateSpace(np.array([[1, 2], [3, 4]]), np.array([[1], [2]]),
+ np.array([[1, 0]]), np.array([[0]]), dt=dt)
+ StateSpace(1, 1, 1, 1, dt=True)
+
+ def test_conversion(self):
+ # Check the conversion functions
+ s = StateSpace(1, 2, 3, 4, dt=0.05)
+ assert isinstance(s.to_ss(), StateSpace)
+ assert isinstance(s.to_tf(), TransferFunction)
+ assert isinstance(s.to_zpk(), ZerosPolesGain)
+
+ # Make sure copies work
+ assert StateSpace(s) is not s
+ assert s.to_ss() is not s
+
+ def test_properties(self):
+ # Test setters/getters for cross class properties.
+ # This implicitly tests to_tf() and to_zpk()
+
+ # Getters
+ s = StateSpace(1, 1, 1, 1, dt=0.05)
+ xp_assert_equal(s.poles, [1.])
+ xp_assert_equal(s.zeros, [0.])
+
+
+class TestTransferFunction:
+ def test_initialization(self):
+ # Check that all initializations work
+ dt = 0.05
+ TransferFunction(1, 1, dt=dt)
+ TransferFunction([1], [2], dt=dt)
+ TransferFunction(np.array([1]), np.array([2]), dt=dt)
+ TransferFunction(1, 1, dt=True)
+
+ def test_conversion(self):
+ # Check the conversion functions
+ s = TransferFunction([1, 0], [1, -1], dt=0.05)
+ assert isinstance(s.to_ss(), StateSpace)
+ assert isinstance(s.to_tf(), TransferFunction)
+ assert isinstance(s.to_zpk(), ZerosPolesGain)
+
+ # Make sure copies work
+ assert TransferFunction(s) is not s
+ assert s.to_tf() is not s
+
+ def test_properties(self):
+ # Test setters/getters for cross class properties.
+ # This implicitly tests to_ss() and to_zpk()
+
+ # Getters
+ s = TransferFunction([1, 0], [1, -1], dt=0.05)
+ xp_assert_equal(s.poles, [1.])
+ xp_assert_equal(s.zeros, [0.])
+
+
+class TestZerosPolesGain:
+ def test_initialization(self):
+ # Check that all initializations work
+ dt = 0.05
+ ZerosPolesGain(1, 1, 1, dt=dt)
+ ZerosPolesGain([1], [2], 1, dt=dt)
+ ZerosPolesGain(np.array([1]), np.array([2]), 1, dt=dt)
+ ZerosPolesGain(1, 1, 1, dt=True)
+
+ def test_conversion(self):
+ # Check the conversion functions
+ s = ZerosPolesGain(1, 2, 3, dt=0.05)
+ assert isinstance(s.to_ss(), StateSpace)
+ assert isinstance(s.to_tf(), TransferFunction)
+ assert isinstance(s.to_zpk(), ZerosPolesGain)
+
+ # Make sure copies work
+ assert ZerosPolesGain(s) is not s
+ assert s.to_zpk() is not s
+
+
+class Test_dfreqresp:
+
+ def test_manual(self):
+ # Test dfreqresp() real part calculation (manual sanity check).
+ # 1st order low-pass filter: H(z) = 1 / (z - 0.2),
+ system = TransferFunction(1, [1, -0.2], dt=0.1)
+ w = [0.1, 1, 10]
+ w, H = dfreqresp(system, w=w)
+
+ # test real
+ expected_re = [1.2383, 0.4130, -0.7553]
+ assert_almost_equal(H.real, expected_re, decimal=4)
+
+ # test imag
+ expected_im = [-0.1555, -1.0214, 0.3955]
+ assert_almost_equal(H.imag, expected_im, decimal=4)
+
+ def test_auto(self):
+ # Test dfreqresp() real part calculation.
+ # 1st order low-pass filter: H(z) = 1 / (z - 0.2),
+ system = TransferFunction(1, [1, -0.2], dt=0.1)
+ w = [0.1, 1, 10, 100]
+ w, H = dfreqresp(system, w=w)
+ jw = np.exp(w * 1j)
+ y = np.polyval(system.num, jw) / np.polyval(system.den, jw)
+
+ # test real
+ expected_re = y.real
+ assert_almost_equal(H.real, expected_re)
+
+ # test imag
+ expected_im = y.imag
+ assert_almost_equal(H.imag, expected_im)
+
+ def test_freq_range(self):
+ # Test that freqresp() finds a reasonable frequency range.
+ # 1st order low-pass filter: H(z) = 1 / (z - 0.2),
+ # Expected range is from 0.01 to 10.
+ system = TransferFunction(1, [1, -0.2], dt=0.1)
+ n = 10
+ expected_w = np.linspace(0, np.pi, 10, endpoint=False)
+ w, H = dfreqresp(system, n=n)
+ assert_almost_equal(w, expected_w)
+
+ def test_pole_one(self):
+ # Test that freqresp() doesn't fail on a system with a pole at 0.
+ # integrator, pole at zero: H(s) = 1 / s
+ system = TransferFunction([1], [1, -1], dt=0.1)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "divide by zero", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ w, H = dfreqresp(system, n=2)
+ assert w[0] == 0. # a fail would give not-a-number
+
+ def test_error(self):
+ # Raise an error for continuous-time systems
+ system = lti([1], [1, 1])
+ assert_raises(AttributeError, dfreqresp, system)
+
+ def test_from_state_space(self):
+ # H(z) = 2 / z^3 - 0.5 * z^2
+
+ system_TF = dlti([2], [1, -0.5, 0, 0])
+
+ A = np.array([[0.5, 0, 0],
+ [1, 0, 0],
+ [0, 1, 0]])
+ B = np.array([[1, 0, 0]]).T
+ C = np.array([[0, 0, 2]])
+ D = 0
+
+ system_SS = dlti(A, B, C, D)
+ w = 10.0**np.arange(-3,0,.5)
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", BadCoefficients)
+ w1, H1 = dfreqresp(system_TF, w=w)
+ w2, H2 = dfreqresp(system_SS, w=w)
+
+ assert_almost_equal(H1, H2)
+
+ def test_from_zpk(self):
+ # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2),
+ system_ZPK = dlti([],[0.2],0.3)
+ system_TF = dlti(0.3, [1, -0.2])
+ w = [0.1, 1, 10, 100]
+ w1, H1 = dfreqresp(system_ZPK, w=w)
+ w2, H2 = dfreqresp(system_TF, w=w)
+ assert_almost_equal(H1, H2)
+
+
+class Test_bode:
+
+ def test_manual(self):
+ # Test bode() magnitude calculation (manual sanity check).
+ # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2),
+ dt = 0.1
+ system = TransferFunction(0.3, [1, -0.2], dt=dt)
+ w = [0.1, 0.5, 1, np.pi]
+ w2, mag, phase = dbode(system, w=w)
+
+ # Test mag
+ expected_mag = [-8.5329, -8.8396, -9.6162, -12.0412]
+ assert_almost_equal(mag, expected_mag, decimal=4)
+
+ # Test phase
+ expected_phase = [-7.1575, -35.2814, -67.9809, -180.0000]
+ assert_almost_equal(phase, expected_phase, decimal=4)
+
+ # Test frequency
+ xp_assert_equal(np.array(w) / dt, w2)
+
+ def test_auto(self):
+ # Test bode() magnitude calculation.
+ # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2),
+ system = TransferFunction(0.3, [1, -0.2], dt=0.1)
+ w = np.array([0.1, 0.5, 1, np.pi])
+ w2, mag, phase = dbode(system, w=w)
+ jw = np.exp(w * 1j)
+ y = np.polyval(system.num, jw) / np.polyval(system.den, jw)
+
+ # Test mag
+ expected_mag = 20.0 * np.log10(abs(y))
+ assert_almost_equal(mag, expected_mag)
+
+ # Test phase
+ expected_phase = np.rad2deg(np.angle(y))
+ assert_almost_equal(phase, expected_phase)
+
+ def test_range(self):
+ # Test that bode() finds a reasonable frequency range.
+ # 1st order low-pass filter: H(s) = 0.3 / (z - 0.2),
+ dt = 0.1
+ system = TransferFunction(0.3, [1, -0.2], dt=0.1)
+ n = 10
+ # Expected range is from 0.01 to 10.
+ expected_w = np.linspace(0, np.pi, n, endpoint=False) / dt
+ w, mag, phase = dbode(system, n=n)
+ assert_almost_equal(w, expected_w)
+
+ def test_pole_one(self):
+ # Test that freqresp() doesn't fail on a system with a pole at 0.
+ # integrator, pole at zero: H(s) = 1 / s
+ system = TransferFunction([1], [1, -1], dt=0.1)
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "divide by zero", RuntimeWarning)
+ warnings.filterwarnings(
+ "ignore", "invalid value encountered", RuntimeWarning)
+ w, mag, phase = dbode(system, n=2)
+ assert w[0] == 0. # a fail would give not-a-number
+
+ def test_imaginary(self):
+ # bode() should not fail on a system with pure imaginary poles.
+ # The test passes if bode doesn't raise an exception.
+ system = TransferFunction([1], [1, 0, 100], dt=0.1)
+ dbode(system, n=2)
+
+ def test_error(self):
+ # Raise an error for continuous-time systems
+ system = lti([1], [1, 1])
+ assert_raises(AttributeError, dbode, system)
+
+
+class TestTransferFunctionZConversion:
+ """Test private conversions between 'z' and 'z**-1' polynomials."""
+
+ def test_full(self):
+ # Numerator and denominator same order
+ num = np.asarray([2.0, 3, 4])
+ den = np.asarray([5.0, 6, 7])
+ num2, den2 = TransferFunction._z_to_zinv(num, den)
+ xp_assert_equal(num, num2)
+ xp_assert_equal(den, den2)
+
+ num2, den2 = TransferFunction._zinv_to_z(num, den)
+ xp_assert_equal(num, num2)
+ xp_assert_equal(den, den2)
+
+ def test_numerator(self):
+ # Numerator lower order than denominator
+ num = np.asarray([2.0, 3])
+ den = np.asarray([50, 6, 7])
+ num2, den2 = TransferFunction._z_to_zinv(num, den)
+ xp_assert_equal([0.0, 2, 3], num2)
+ xp_assert_equal(den, den2)
+
+ num2, den2 = TransferFunction._zinv_to_z(num, den)
+ xp_assert_equal([2.0, 3, 0], num2)
+ xp_assert_equal(den, den2)
+
+ def test_denominator(self):
+ # Numerator higher order than denominator
+ num = np.asarray([2., 3, 4])
+ den = np.asarray([5.0, 6])
+ num2, den2 = TransferFunction._z_to_zinv(num, den)
+ xp_assert_equal(num, num2)
+ xp_assert_equal([0.0, 5, 6], den2)
+
+ num2, den2 = TransferFunction._zinv_to_z(num, den)
+ xp_assert_equal(num, num2)
+ xp_assert_equal([5.0, 6, 0], den2)
+
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..d1ea9d9f0150fc49ce0daebb8668747481633bdd
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_filter_design.py
@@ -0,0 +1,5129 @@
+import math
+import cmath
+import warnings
+import os
+
+from itertools import product
+
+from scipy._lib import _pep440
+import numpy as np
+import pytest
+from pytest import raises as assert_raises
+from scipy._lib._array_api import (
+ xp_assert_close, xp_assert_equal, array_namespace,
+ assert_array_almost_equal, xp_size, xp_default_dtype, is_numpy,
+ make_xp_test_case, make_xp_pytest_param, is_cupy, is_torch, scipy_namespace_for,
+ _xp_copy_to_numpy, xp_assert_close_nulp
+)
+import scipy._lib.array_api_extra as xpx
+
+from numpy import array, spacing, sin, pi
+from scipy.signal import (argrelextrema, BadCoefficients, bessel, besselap, bilinear,
+ buttap, butter, buttord, cheb1ap, cheb1ord, cheb2ap,
+ cheb2ord, cheby1, cheby2, ellip, ellipap, ellipord,
+ firwin, freqs_zpk, freqs, freqz, freqz_zpk,
+ gammatone, group_delay, iircomb, iirdesign, iirfilter,
+ iirnotch, iirpeak, lp2bp, lp2bs, lp2hp, lp2lp, normalize,
+ sos2tf, sos2zpk, sosfreqz, freqz_sos, tf2sos, tf2zpk, zpk2sos,
+ zpk2tf, bilinear_zpk, lp2lp_zpk, lp2hp_zpk, lp2bp_zpk,
+ lp2bs_zpk)
+from scipy.signal._filter_design import (_cplxreal, _cplxpair, _norm_factor,
+ _bessel_poly, _bessel_zeros)
+from scipy.signal._filter_design import _logspace
+from scipy.signal import _polyutils as _pu
+from scipy.signal._polyutils import _sort_cmplx
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+
+DEFAULT_F32 = os.getenv('SCIPY_DEFAULT_DTYPE', default='float64') == 'float32'
+
+try:
+ import mpmath
+except ImportError:
+ mpmath = None
+
+
+def mpmath_check(min_ver):
+ return pytest.mark.skipif(
+ mpmath is None
+ or _pep440.parse(mpmath.__version__) < _pep440.Version(min_ver),
+ reason=f"mpmath version >= {min_ver} required",
+ )
+
+
+class TestCplxPair:
+
+ def test_trivial_input(self):
+ assert _cplxpair([]).size == 0
+ assert _cplxpair(1) == 1
+
+ def test_output_order(self):
+ xp_assert_close(_cplxpair([1+1j, 1-1j]), [1-1j, 1+1j])
+
+ a = [1+1j, 1+1j, 1, 1-1j, 1-1j, 2]
+ b = [1-1j, 1+1j, 1-1j, 1+1j, 1, 2]
+ xp_assert_close(_cplxpair(a), b)
+
+ # points spaced around the unit circle
+ z = np.exp(2j*pi*array([4, 3, 5, 2, 6, 1, 0])/7)
+ z1 = np.copy(z)
+ np.random.shuffle(z)
+ xp_assert_close(_cplxpair(z), z1)
+ np.random.shuffle(z)
+ xp_assert_close(_cplxpair(z), z1)
+ np.random.shuffle(z)
+ xp_assert_close(_cplxpair(z), z1)
+
+ # Should be able to pair up all the conjugates
+ x = np.random.rand(10000) + 1j * np.random.rand(10000)
+ y = x.conj()
+ z = np.random.rand(10000)
+ x = np.concatenate((x, y, z))
+ np.random.shuffle(x)
+ c = _cplxpair(x)
+
+ # Every other element of head should be conjugates:
+ xp_assert_close(c[0:20000:2], np.conj(c[1:20000:2]))
+ # Real parts of head should be in sorted order:
+ xp_assert_close(c[0:20000:2].real, np.sort(c[0:20000:2].real))
+ # Tail should be sorted real numbers:
+ xp_assert_close(c[20000:], np.sort(c[20000:]))
+
+ def test_real_integer_input(self):
+ xp_assert_equal(_cplxpair([2, 0, 1]), [0, 1, 2])
+
+ def test_tolerances(self):
+ eps = spacing(1)
+ xp_assert_close(_cplxpair([1j, -1j, 1+1j*eps], tol=2*eps),
+ [-1j, 1j, 1+1j*eps])
+
+ # sorting close to 0
+ xp_assert_close(_cplxpair([-eps+1j, +eps-1j]), [-1j, +1j])
+ xp_assert_close(_cplxpair([+eps+1j, -eps-1j]), [-1j, +1j])
+ xp_assert_close(_cplxpair([+1j, -1j]), [-1j, +1j])
+
+ def test_unmatched_conjugates(self):
+ # 1+2j is unmatched
+ assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+2j])
+
+ # 1+2j and 1-3j are unmatched
+ assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+2j, 1-3j])
+
+ # 1+3j is unmatched
+ assert_raises(ValueError, _cplxpair, [1+3j, 1-3j, 1+3j])
+
+ # Not conjugates
+ assert_raises(ValueError, _cplxpair, [4+5j, 4+5j])
+ assert_raises(ValueError, _cplxpair, [1-7j, 1-7j])
+
+ # No pairs
+ assert_raises(ValueError, _cplxpair, [1+3j])
+ assert_raises(ValueError, _cplxpair, [1-3j])
+
+
+class TestCplxReal:
+
+ def test_trivial_input(self):
+ assert all(x.size == 0 for x in _cplxreal([]))
+
+ x = _cplxreal(1)
+ assert x[0].size == 0
+ xp_assert_equal(x[1], np.asarray([1]))
+
+
+ def test_output_order(self):
+ zc, zr = _cplxreal(np.roots(array([1, 0, 0, 1])))
+ xp_assert_close(np.append(zc, zr), [1/2 + 1j*sin(pi/3), -1])
+
+ eps = spacing(1)
+
+ a = [0+1j, 0-1j, eps + 1j, eps - 1j, -eps + 1j, -eps - 1j,
+ 1, 4, 2, 3, 0, 0,
+ 2+3j, 2-3j,
+ 1-eps + 1j, 1+2j, 1-2j, 1+eps - 1j, # sorts out of order
+ 3+1j, 3+1j, 3+1j, 3-1j, 3-1j, 3-1j,
+ 2-3j, 2+3j]
+ zc, zr = _cplxreal(a)
+ xp_assert_close(zc, [1j, 1j, 1j, 1+1j, 1+2j, 2+3j, 2+3j, 3+1j, 3+1j,
+ 3+1j])
+ xp_assert_close(zr, [0.0, 0, 1, 2, 3, 4])
+
+ z = array([1-eps + 1j, 1+2j, 1-2j, 1+eps - 1j, 1+eps+3j, 1-2*eps-3j,
+ 0+1j, 0-1j, 2+4j, 2-4j, 2+3j, 2-3j, 3+7j, 3-7j, 4-eps+1j,
+ 4+eps-2j, 4-1j, 4-eps+2j])
+
+ zc, zr = _cplxreal(z)
+ xp_assert_close(zc, [1j, 1+1j, 1+2j, 1+3j, 2+3j, 2+4j, 3+7j, 4+1j,
+ 4+2j])
+ xp_assert_equal(zr, np.asarray([]))
+
+ def test_unmatched_conjugates(self):
+ # 1+2j is unmatched
+ assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+2j])
+
+ # 1+2j and 1-3j are unmatched
+ assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+2j, 1-3j])
+
+ # 1+3j is unmatched
+ assert_raises(ValueError, _cplxreal, [1+3j, 1-3j, 1+3j])
+
+ # No pairs
+ assert_raises(ValueError, _cplxreal, [1+3j])
+ assert_raises(ValueError, _cplxreal, [1-3j])
+
+ def test_real_integer_input(self):
+ zc, zr = _cplxreal([2, 0, 1, 4])
+ xp_assert_equal(zc, np.asarray([]))
+ xp_assert_equal(zr, [0, 1, 2, 4])
+
+
+@make_xp_test_case(tf2zpk)
+class TestTf2zpk:
+
+ @skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+ @pytest.mark.parametrize('dt', ('float64', 'complex128'))
+ def test_simple(self, dt, xp):
+ dtyp = getattr(xp, dt)
+
+ z_r = xp.asarray([0.5, -0.5])
+ p_r = xp.asarray([1.j / math.sqrt(2), -1.j / math.sqrt(2)])
+ # Sort the zeros/poles so that we don't fail the test if the order
+ # changes
+ z_r = _sort_cmplx(z_r, xp=xp)
+ p_r = _sort_cmplx(p_r, xp=xp)
+
+ b = xp.astype(_pu.poly(z_r, xp=xp), dtyp)
+ a = xp.astype(_pu.poly(p_r, xp=xp), dtyp)
+
+ z, p, k = tf2zpk(b, a)
+ z = _sort_cmplx(z, xp=xp)
+ # The real part of `p` is ~0.0, so sort by imaginary part
+ p = p[xp.argsort(xp.imag(p))]
+
+ assert_array_almost_equal(z, z_r)
+ assert_array_almost_equal(p, p_r)
+ assert math.isclose(xp.real(k), 1.)
+ assert k.dtype == dtyp
+
+ def test_bad_filter(self):
+ # Regression test for #651: better handling of badly conditioned
+ # filter coefficients.
+ with warnings.catch_warnings():
+ warnings.simplefilter("error", BadCoefficients)
+ assert_raises(BadCoefficients, tf2zpk, [1e-15], [1.0, 1.0])
+
+
+@make_xp_test_case(zpk2tf)
+class TestZpk2Tf:
+
+ def test_identity(self, xp):
+ """Test the identity transfer function."""
+ z = xp.asarray([])
+ p = xp.asarray([])
+ k = 1.
+ b, a = zpk2tf(z, p, k)
+ b_r = xp.asarray([1.]) # desired result
+ a_r = xp.asarray([1.]) # desired result
+ # The test for the *type* of the return values is a regression
+ # test for ticket #1095. In the case p=[], zpk2tf used to
+ # return the scalar 1.0 instead of array([1.0]).
+ xp_assert_equal(b, b_r)
+ xp_assert_equal(a, a_r)
+ if is_numpy(xp):
+ assert isinstance(b, np.ndarray)
+ assert isinstance(a, np.ndarray)
+
+ @skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+ def test_conj_pair(self, xp):
+ # conjugate pairs give real-coeff num & den
+ z = xp.asarray([1j, -1j, 2j, -2j])
+ z_np = _xp_copy_to_numpy(z)
+ # shouldn't need elements of pairs to be adjacent
+ p = xp.asarray([1+1j, 3-100j, 3+100j, 1-1j])
+ p_np = _xp_copy_to_numpy(p)
+
+ k = 23
+
+ # np.poly should do the right thing, but be explicit about
+ # taking real part
+ b_np = k * np.poly(z_np).real
+ a_np = np.poly(p_np).real
+ b, a = map(xp.asarray, (b_np, a_np))
+
+ bp, ap = zpk2tf(z, p, k)
+
+ atol = 5e-13 if is_cupy(xp) else 0.0
+ xp_assert_close(b, bp, atol=atol)
+ xp_assert_close(a, ap)
+
+ assert xp.isdtype(bp.dtype, 'real floating')
+ assert xp.isdtype(ap.dtype, 'real floating')
+
+ @skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+ def test_complexk(self, xp):
+ # regression: z, p real, k complex k gave real b, a
+ b, a = xp.asarray([1j, 1j]), xp.asarray([1.0, 2])
+ b_np, a_np = map(_xp_copy_to_numpy, (b, a))
+ z_np, p_np, k_np = tf2zpk(b_np, a_np)
+ z, p, k = map(xp.asarray, (z_np, p_np, k_np))
+ xp_assert_close(k, xp.asarray(1j), check_0d=False)
+ bp, ap = zpk2tf(z, p, k)
+ xp_assert_close(b, bp)
+ xp_assert_close(a, ap)
+
+ @skip_xp_backends("jax.numpy",
+ reason="zpk2tf not compatible with jax yet on multi-dim arrays")
+ @skip_xp_backends("cupy",
+ reason="multi-dim arrays not supported yet on cupy")
+ def test_zpk2tf_with_multi_dimensional_array(self, xp):
+ z = xp.asarray([[1, 2], [3, 4]]) # Multi-dimensional input
+ p = xp.asarray([1, 2])
+ k = 1
+ b, a = zpk2tf(z, p, k)
+ b_ref = xp.asarray([[1, -3, 2], [1, -7, 12]])
+ a_ref = xp.asarray([1, -3, 2])
+ xp_assert_close(b, b_ref, check_dtype=False)
+ xp_assert_close(a, a_ref, check_dtype=False)
+
+ @skip_xp_backends("cupy",
+ reason="multi-dim arrays not supported yet on cupy")
+ def test_zpk2tf_int_truncation(self, xp):
+ # regression test for gh-24382
+ z = xp.asarray([[ 1, 2.], [ 0., -1.]], dtype=xp.float64)
+ p = xp.asarray([3., 4.], dtype=xp.float64)
+ k = 2.5
+
+ b, a = zpk2tf(z, p, k)
+
+ # reference values from scipy 1.15.3
+ b_ref = xp.asarray([[ 2.5, -7.5, 5. ], [ 2.5, 2.5, 0. ]], dtype=xp.float64)
+ a_ref = xp.asarray([ 1., -7., 12.], dtype=xp.float64)
+
+ xp_assert_close(b, b_ref, atol=1e-14)
+ xp_assert_close(a, a_ref, atol=1e-14)
+
+
+@make_xp_test_case(sos2zpk)
+class TestSos2Zpk:
+
+ @skip_xp_backends("dask.array", reason="it https://github.com/dask/dask/issues/11883")
+ @xfail_xp_backends("jax.numpy", reason="inaccurate with jax")
+ def test_basic(self, xp):
+ sos = [[1, 0, 1, 1, 0, -0.81],
+ [1, 0, 0, 1, 0, +0.49]]
+ sos = xp.asarray(sos)
+ z, p, k = sos2zpk(sos)
+ z2 = xp.asarray([1j, -1j, 0, 0])
+ p2 = xp.asarray([0.9, -0.9, 0.7j, -0.7j])
+ k2 = 1.
+ assert_array_almost_equal(_sort_cmplx(z, xp), _sort_cmplx(z2, xp), decimal=4)
+ assert_array_almost_equal(_sort_cmplx(p, xp), _sort_cmplx(p2, xp), decimal=4)
+ assert math.isclose(k, k2)
+
+ sos = [[1.00000, +0.61803, 1.0000, 1.00000, +0.60515, 0.95873],
+ [1.00000, -1.61803, 1.0000, 1.00000, -1.58430, 0.95873],
+ [1.00000, +1.00000, 0.0000, 1.00000, +0.97915, 0.00000]]
+ sos = xp.asarray(sos)
+ z, p, k = sos2zpk(sos)
+ z2 = [-0.3090 + 0.9511j, -0.3090 - 0.9511j, 0.8090 + 0.5878j,
+ 0.8090 - 0.5878j, -1.0000 + 0.0000j, 0]
+ p2 = [-0.3026 + 0.9312j, -0.3026 - 0.9312j, 0.7922 + 0.5755j,
+ 0.7922 - 0.5755j, -0.9791 + 0.0000j, 0]
+ z2 = xp.asarray(z2)
+ p2 = xp.asarray(p2)
+ k2 = 1
+ assert_array_almost_equal(_sort_cmplx(z, xp), _sort_cmplx(z2, xp), decimal=4)
+ assert_array_almost_equal(_sort_cmplx(p, xp), _sort_cmplx(p2, xp), decimal=4)
+
+ sos = array([[1, 2, 3, 1, 0.2, 0.3],
+ [4, 5, 6, 1, 0.4, 0.5]])
+ z = array([-1 - 1.41421356237310j, -1 + 1.41421356237310j,
+ -0.625 - 1.05326872164704j, -0.625 + 1.05326872164704j])
+ p = array([-0.2 - 0.678232998312527j, -0.2 + 0.678232998312527j,
+ -0.1 - 0.538516480713450j, -0.1 + 0.538516480713450j])
+ sos, z, p = map(xp.asarray, (sos, z, p))
+ k = 4
+ z2, p2, k2 = sos2zpk(sos)
+
+ xp_assert_close(_sort_cmplx(z2, xp=xp), _sort_cmplx(z, xp=xp))
+ xp_assert_close(_sort_cmplx(p2, xp=xp), _sort_cmplx(p, xp=xp))
+ assert k2 == k
+
+ def test_fewer_zeros(self, xp):
+ """Test not the expected number of p/z (effectively at origin)."""
+ sos = butter(3, 0.1, output='sos')
+ z, p, k = sos2zpk(xp.asarray(sos))
+ assert z.shape[0] == 4
+ assert p.shape[0] == 4
+
+ sos = butter(12, [5., 30.], 'bandpass', fs=1200., analog=False, output='sos')
+ e = BadCoefficients
+ if is_cupy(xp):
+ e = scipy_namespace_for(xp).signal.BadCoefficients
+ with pytest.warns(e, match='Badly conditioned'):
+ z, p, k = sos2zpk(xp.asarray(sos))
+ assert z.shape[0] == 24
+ assert p.shape[0] == 24
+
+
+@make_xp_test_case(sos2tf)
+class TestSos2Tf:
+
+ def test_basic(self, xp):
+ sos = [[1.0, 1, 1, 1, 0, -1],
+ [-2, 3, 1, 1, 10, 1]]
+ sos = xp.asarray(sos)
+ b, a = sos2tf(sos)
+ assert_array_almost_equal(b, xp.asarray([-2.0, 1, 2, 4, 1]))
+ assert_array_almost_equal(a, xp.asarray([1.0, 10, 0, -10, -1]))
+
+
+@make_xp_test_case(tf2sos)
+class TestTf2Sos:
+
+ def test_basic(self, xp):
+ num = xp.asarray([2., 16, 44, 56, 32])
+ den = xp.asarray([3., 3, -15, 18, -12])
+ sos = tf2sos(num, den)
+ sos2 = [[0.6667, 4.0000, 5.3333, 1.0000, +2.0000, -4.0000],
+ [1.0000, 2.0000, 2.0000, 1.0000, -1.0000, +1.0000]]
+ sos2 = xp.asarray(sos2)
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ b = xp.asarray([1.0, -3, 11, -27, 18])
+ a = xp.asarray([16.0, 12, 2, -4, -1])
+ sos = tf2sos(b, a)
+ sos2 = [[0.0625, -0.1875, 0.1250, 1.0000, -0.2500, -0.1250],
+ [1.0000, +0.0000, 9.0000, 1.0000, +1.0000, +0.5000]]
+ sos2 = xp.asarray(sos2)
+ #assert_array_almost_equal(sos, sos2, decimal=4)
+
+ @pytest.mark.parametrize('b, a, analog, sos',
+ [([1.0], [1.0], False, [[1., 0., 0., 1., 0., 0.]]),
+ ([1.0], [1.0], True, [[0., 0., 1., 0., 0., 1.]]),
+ ([1.0], [1., 0., -1.01, 0, 0.01], False,
+ [[1., 0., 0., 1., 0., -0.01],
+ [1., 0., 0., 1., 0., -1]]),
+ ([1.0], [1., 0., -1.01, 0, 0.01], True,
+ [[0., 0., 1., 1., 0., -1],
+ [0., 0., 1., 1., 0., -0.01]])])
+ @skip_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/9376")
+ def test_analog(self, b, a, analog, sos, xp):
+ b, a, sos = map(xp.asarray, (b, a, sos))
+ sos2 = tf2sos(b, a, analog=analog)
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+
+@make_xp_test_case(zpk2sos)
+class TestZpk2Sos:
+
+# @pytest.mark.parametrize('dt', 'fdgFDG')
+ # XXX: quietly remove float128 and complex256
+ @pytest.mark.parametrize('dt', ['float32', 'float64', 'complex64', 'complex128'])
+ @pytest.mark.parametrize('pairing, analog',
+ [('nearest', False),
+ ('keep_odd', False),
+ ('minimal', False),
+ ('minimal', True)])
+ def test_dtypes(self, dt, pairing, analog, xp):
+ dtype = getattr(xp, dt)
+ # the poles have to be complex
+ cdtype = (1j*xp.empty(0, dtype=dtype)).dtype
+
+ z = xp.asarray([-1, -1], dtype=dtype)
+ p = xp.asarray([0.57149 + 0.29360j, 0.57149 - 0.29360j], dtype=cdtype)
+ k = xp.asarray(1, dtype=dtype)
+ sos = zpk2sos(z, p, k, pairing=pairing, analog=analog)
+ # octave & MATLAB
+ sos2 = xp.asarray([[1, 2, 1, 1, -1.14298, 0.41280]], dtype=dtype)
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ def test_basic(self, xp):
+ for pairing in ('nearest', 'keep_odd'):
+ #
+ # Cases that match octave
+ #
+
+ z = xp.asarray([-1.0, -1.0])
+ p = xp.asarray([0.57149 + 0.29360j, 0.57149 - 0.29360j])
+ k = 1
+ sos = zpk2sos(z, p, k, pairing=pairing)
+ sos2 = xp.asarray([[1, 2, 1, 1, -1.14298, 0.41280]]) # octave & MATLAB
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ z = xp.asarray([1j, -1j])
+ p = xp.asarray([0.9, -0.9, 0.7j, -0.7j])
+ k = 1
+ sos = zpk2sos(z, p, k, pairing=pairing)
+ sos2 = [[1, 0, 1, 1, 0, +0.49],
+ [1, 0, 0, 1, 0, -0.81]] # octave
+ sos2 = xp.asarray(sos2)
+ # sos2 = [[0, 0, 1, 1, -0.9, 0],
+ # [1, 0, 1, 1, 0.9, 0]] # MATLAB
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ z = xp.asarray([])
+ p = xp.asarray([0.8, -0.5+0.25j, -0.5-0.25j])
+ k = 1.
+ sos = zpk2sos(z, p, k, pairing=pairing)
+ sos2 = [[1., 0., 0., 1., 1., 0.3125],
+ [1., 0., 0., 1., -0.8, 0.]] # octave, MATLAB fails
+ sos2 = xp.asarray(sos2)
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ z = xp.asarray([1., 1., 0.9j, -0.9j])
+ p = xp.asarray([0.99+0.01j, 0.99-0.01j, 0.1+0.9j, 0.1-0.9j])
+ k = 1
+ sos = zpk2sos(z, p, k, pairing=pairing)
+ sos2 = [[1, 0, 0.81, 1, -0.2, 0.82],
+ [1, -2, 1, 1, -1.98, 0.9802]] # octave
+ sos2 = xp.asarray(sos2)
+ # sos2 = [[1, -2, 1, 1, -0.2, 0.82],
+ # [1, 0, 0.81, 1, -1.98, 0.9802]] # MATLAB
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ z = xp.asarray([0.9+0.1j, 0.9-0.1j, -0.9])
+ p = xp.asarray([0.75+0.25j, 0.75-0.25j, 0.9])
+ k = 1
+ sos = zpk2sos(z, p, k, pairing=pairing)
+ if pairing == 'keep_odd':
+ sos2 = [[1, -1.8, 0.82, 1, -1.5, 0.625],
+ [1, 0.9, 0, 1, -0.9, 0]] # octave; MATLAB fails
+ sos2 = xp.asarray(sos2)
+ assert_array_almost_equal(sos, sos2, decimal=4)
+ else: # pairing == 'nearest'
+ sos2 = [[1, 0.9, 0, 1, -1.5, 0.625],
+ [1, -1.8, 0.82, 1, -0.9, 0]] # our algorithm
+ sos2 = xp.asarray(sos2)
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ #
+ # Cases that differ from octave:
+ #
+
+ z = [-0.3090 + 0.9511j, -0.3090 - 0.9511j, 0.8090 + 0.5878j,
+ +0.8090 - 0.5878j, -1.0000 + 0.0000j]
+ p = [-0.3026 + 0.9312j, -0.3026 - 0.9312j, 0.7922 + 0.5755j,
+ +0.7922 - 0.5755j, -0.9791 + 0.0000j]
+ z = xp.asarray(z)
+ p = xp.asarray(p)
+ k = 1
+ sos = zpk2sos(z, p, k, pairing=pairing)
+ # sos2 = [[1, 0.618, 1, 1, 0.6052, 0.95870],
+ # [1, -1.618, 1, 1, -1.5844, 0.95878],
+ # [1, 1, 0, 1, 0.9791, 0]] # octave, MATLAB fails
+ sos2 = [[1, 1, 0, 1, +0.97915, 0],
+ [1, 0.61803, 1, 1, +0.60515, 0.95873],
+ [1, -1.61803, 1, 1, -1.58430, 0.95873]]
+ sos2 = xp.asarray(sos2)
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ z = [-1 - 1.4142j, -1 + 1.4142j,
+ -0.625 - 1.0533j, -0.625 + 1.0533j]
+ p = [-0.2 - 0.6782j, -0.2 + 0.6782j,
+ -0.1 - 0.5385j, -0.1 + 0.5385j]
+ z = xp.asarray(z)
+ p = xp.asarray(p)
+ k = 4
+ sos = zpk2sos(z, p, k, pairing=pairing)
+ sos2 = [[4, 8, 12, 1, 0.2, 0.3],
+ [1, 1.25, 1.5, 1, 0.4, 0.5]] # MATLAB
+ sos2 = xp.asarray(sos2, dtype=xp.float64)
+ # sos2 = [[4, 8, 12, 1, 0.4, 0.5],
+ # [1, 1.25, 1.5, 1, 0.2, 0.3]] # octave
+ xp_assert_close(sos, sos2, rtol=1e-4, atol=1e-4)
+
+ z = xp.asarray([])
+ p = xp.asarray([0.2, -0.5+0.25j, -0.5-0.25j])
+ k = 1.
+ sos = zpk2sos(z, p, k, pairing=pairing)
+ sos2 = [[1., 0., 0., 1., -0.2, 0.],
+ [1., 0., 0., 1., 1., 0.3125]]
+ sos2 = xp.asarray(sos2)
+ # sos2 = [[1., 0., 0., 1., 1., 0.3125],
+ # [1., 0., 0., 1., -0.2, 0]] # octave, MATLAB fails
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ # The next two examples are adapted from Leland B. Jackson,
+ # "Digital Filters and Signal Processing (1995) p.400:
+ # http://books.google.com/books?id=VZ8uabI1pNMC&lpg=PA400&ots=gRD9pi8Jua&dq=Pole%2Fzero%20pairing%20for%20minimum%20roundoff%20noise%20in%20BSF.&pg=PA400#v=onepage&q=Pole%2Fzero%20pairing%20for%20minimum%20roundoff%20noise%20in%20BSF.&f=false
+
+ deg2rad = xp.pi / 180.
+ k = 1.
+
+ # first example
+ thetas = xp.asarray([22.5, 45, 77.5])
+ mags = xp.asarray([0.8, 0.6, 0.9])
+ z = xp.exp(1j * deg2rad * thetas)
+ z = xp.concat((z, xp.conj(z)))
+ p = xp.exp(1j * deg2rad * thetas) * mags
+ p = xp.concat((p, xp.conj(p)))
+ sos = zpk2sos(z, p, k)
+ # sos2 = [[1, -0.43288, 1, 1, -0.38959, 0.81], # octave,
+ # [1, -1.41421, 1, 1, -0.84853, 0.36], # MATLAB fails
+ # [1, -1.84776, 1, 1, -1.47821, 0.64]]
+ # Note that pole-zero pairing matches, but ordering is different
+ sos2 = [[1, -1.41421, 1, 1, -0.84853, 0.36],
+ [1, -1.84776, 1, 1, -1.47821, 0.64],
+ [1, -0.43288, 1, 1, -0.38959, 0.81]]
+ sos2 = xp.asarray(sos2)
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ # second example
+ thetas = xp.asarray([85., 10.])
+ z = xp.exp(1j * deg2rad * thetas)
+ z = xp.concat((z, xp.conj(z), xp.asarray([1.0, -1.0])))
+ sos = zpk2sos(z, p, k)
+
+ # sos2 = [[1, -0.17431, 1, 1, -0.38959, 0.81], # octave "wrong",
+ # [1, -1.96962, 1, 1, -0.84853, 0.36], # MATLAB fails
+ # [1, 0, -1, 1, -1.47821, 0.64000]]
+ # Our pole-zero pairing matches the text, Octave does not
+ sos2 = [[1, 0, -1, 1, -0.84853, 0.36],
+ [1, -1.96962, 1, 1, -1.47821, 0.64],
+ [1, -0.17431, 1, 1, -0.38959, 0.81]]
+ sos2 = xp.asarray(sos2)
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ # these examples are taken from the doc string, and show the
+ # effect of the 'pairing' argument
+ @pytest.mark.parametrize('pairing, sos',
+ [('nearest',
+ np.array([[1., 1., 0.5, 1., -0.75, 0.],
+ [1., 1., 0., 1., -1.6, 0.65]])),
+ ('keep_odd',
+ np.array([[1., 1., 0, 1., -0.75, 0.],
+ [1., 1., 0.5, 1., -1.6, 0.65]])),
+ ('minimal',
+ np.array([[0., 1., 1., 0., 1., -0.75],
+ [1., 1., 0.5, 1., -1.6, 0.65]]))])
+ def test_pairing(self, pairing, sos, xp):
+ sos = xp.asarray(sos)
+ z1 = xp.asarray([-1, -0.5-0.5j, -0.5+0.5j])
+ p1 = xp.asarray([0.75, 0.8+0.1j, 0.8-0.1j])
+ sos2 = zpk2sos(z1, p1, 1, pairing=pairing)
+ assert_array_almost_equal(sos, sos2, decimal=4)
+
+ @pytest.mark.parametrize('p, sos_dt',
+ [([-1, 1, -0.1, 0.1],
+ [[0., 0., 1., 1., 0., -0.01],
+ [0., 0., 1., 1., 0., -1]]),
+ ([-0.7071+0.7071j, -0.7071-0.7071j, -0.1j, 0.1j],
+ [[0., 0., 1., 1., 0., 0.01],
+ [0., 0., 1., 1., 1.4142, 1.]])])
+ def test_analog(self, p, sos_dt, xp):
+ # test `analog` argument
+ # for discrete time, poles closest to unit circle should appear last
+ # for cont. time, poles closest to imaginary axis should appear last
+ z, p = xp.asarray([]), xp.asarray(p)
+ sos_dt = xp.asarray(sos_dt)
+ sos2_dt = zpk2sos(z, p, 1, pairing='minimal', analog=False)
+ sos2_ct = zpk2sos(z, p, 1, pairing='minimal', analog=True)
+ assert_array_almost_equal(sos_dt, sos2_dt, decimal=4)
+ assert_array_almost_equal(xp.flip(sos_dt, axis=0), sos2_ct, decimal=4)
+
+ def test_bad_args(self):
+ with pytest.raises(ValueError, match=r'pairing must be one of'):
+ zpk2sos([1], [2], 1, pairing='no_such_pairing')
+
+ with pytest.raises(ValueError, match=r'.*pairing must be "minimal"'):
+ zpk2sos([1], [2], 1, pairing='keep_odd', analog=True)
+
+ with pytest.raises(ValueError,
+ match=r'.*must have len\(p\)>=len\(z\)'):
+ zpk2sos([1, 1], [2], 1, analog=True)
+
+ with pytest.raises(ValueError, match=r'k must be real'):
+ zpk2sos([1], [2], k=1j)
+
+
+@make_xp_test_case(freqs)
+class TestFreqs:
+
+ def test_basic(self, xp):
+ _, h = freqs(xp.asarray([1.0]), xp.asarray([1.0]), worN=8)
+ assert_array_almost_equal(h, xp.ones(8))
+
+ def test_output(self, xp):
+ # 1st order low-pass filter: H(s) = 1 / (s + 1)
+ w = xp.asarray([0.1, 1, 10, 100])
+ num = xp.asarray([1.])
+ den = xp.asarray([1, 1.])
+ w, H = freqs(num, den, worN=w)
+ s = w * 1j
+ expected = 1 / (s + 1)
+ assert_array_almost_equal(xp.real(H), xp.real(expected))
+ assert_array_almost_equal(xp.imag(H), xp.imag(expected))
+
+ def test_freq_range(self, xp):
+ # Test that freqresp() finds a reasonable frequency range.
+ # 1st order low-pass filter: H(s) = 1 / (s + 1)
+ # Expected range is from 0.01 to 10.
+ num = xp.asarray([1.])
+ den = xp.asarray([1, 1.])
+ n = 10
+ expected_w = _logspace(-2, 1, n, xp=xp)
+ w, H = freqs(num, den, worN=n)
+ assert_array_almost_equal(w, expected_w)
+
+ def test_plot(self, xp):
+
+ def plot(w, h):
+ assert_array_almost_equal(h, xp.ones(8))
+
+ with assert_raises(ZeroDivisionError):
+ freqs([1.0], [1.0], worN=8, plot=lambda w, h: 1 / 0)
+
+ freqs(xp.asarray([1.0]), xp.asarray([1.0]), worN=8, plot=plot)
+
+ def test_backward_compat(self, xp):
+ # For backward compatibility, test if None act as a wrapper for default
+ w1, h1 = freqs(xp.asarray([1.0]), xp.asarray([1.0]))
+ w2, h2 = freqs(xp.asarray([1.0]), xp.asarray([1.0]), None)
+ assert_array_almost_equal(w1, w2)
+ assert_array_almost_equal(h1, h2)
+
+ def test_w_or_N_types(self):
+ # Measure at 8 equally-spaced points
+ for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8),
+ np.array(8)):
+ w, h = freqs([1.0], [1.0], worN=N)
+ assert len(w) == 8
+ assert_array_almost_equal(h, np.ones(8))
+
+ # Measure at frequency 8 rad/sec
+ for w in (8.0, 8.0+0j):
+ w_out, h = freqs([1.0], [1.0], worN=w)
+ assert_array_almost_equal(w_out, [8])
+ assert_array_almost_equal(h, [1])
+
+
+@make_xp_test_case(freqs_zpk)
+class TestFreqs_zpk:
+
+ def test_basic(self, xp):
+ _, h = freqs_zpk(
+ xp.asarray([1.0]), xp.asarray([1.0]), xp.asarray([1.0]), worN=8
+ )
+ assert_array_almost_equal(h, xp.ones(8))
+
+ def test_output(self, xp):
+ # 1st order low-pass filter: H(s) = 1 / (s + 1)
+ w = xp.asarray([0.1, 1, 10, 100])
+ z = xp.asarray([])
+ p = xp.asarray([-1.0])
+ k = 1
+ w, H = freqs_zpk(z, p, k, worN=w)
+ s = w * 1j
+ expected = 1 / (s + 1)
+ assert_array_almost_equal(xp.real(H), xp.real(expected))
+ assert_array_almost_equal(xp.imag(H), xp.imag(expected))
+
+ def test_freq_range(self, xp):
+ # Test that freqresp() finds a reasonable frequency range.
+ # 1st order low-pass filter: H(s) = 1 / (s + 1)
+ # Expected range is from 0.01 to 10.
+ z = xp.asarray([])
+ p = xp.asarray([-1.])
+ k = 1
+ n = 10
+ expected_w = _logspace(-2, 1, n, xp=xp)
+ w, H = freqs_zpk(z, p, k, worN=n)
+ assert_array_almost_equal(w, expected_w)
+
+ def test_vs_freqs(self, xp):
+ b, a = cheby1(4, 5, 100., analog=True, output='ba')
+ z, p, k = cheby1(4, 5, 100., analog=True, output='zpk')
+
+ w1, h1 = map(xp.asarray, freqs(b, a))
+ z, p, k = map(xp.asarray, (z, p, k))
+ w2, h2 = freqs_zpk(z, p, k)
+ xp_assert_close(w1, w2)
+ xp_assert_close(h1, h2, rtol=1e-6)
+
+ def test_backward_compat(self, xp):
+ # For backward compatibility, test if None act as a wrapper for default
+ # Also, keep testing `k` a length-one list: it is documented as a scalar,
+ # but the implementation was allowing for a one-element array-likes
+ w1, h1 = freqs_zpk(xp.asarray([1.0]), xp.asarray([1.0]), [1.0])
+ w2, h2 = freqs_zpk(xp.asarray([1.0]), xp.asarray([1.0]), [1.0], None)
+ assert_array_almost_equal(w1, w2)
+ assert_array_almost_equal(h1, h2)
+
+ def test_w_or_N_types(self):
+ # Measure at 8 equally-spaced points
+ for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8),
+ np.array(8)):
+ w, h = freqs_zpk([], [], 1, worN=N)
+ assert len(w) == 8
+ assert_array_almost_equal(h, np.ones(8))
+
+ # Measure at frequency 8 rad/sec
+ for w in (8.0, 8.0+0j):
+ w_out, h = freqs_zpk([], [], 1, worN=w)
+ assert_array_almost_equal(w_out, [8])
+ assert_array_almost_equal(h, [1])
+
+
+@make_xp_test_case(freqz)
+class TestFreqz:
+
+ def test_ticket1441(self, xp):
+ """Regression test for ticket 1441."""
+ # Because freqz previously used arange instead of linspace,
+ # when N was large, it would return one more point than
+ # requested.
+ N = 100000
+ w, h = freqz(xp.asarray([1.0]), worN=N)
+ assert w.shape == (N,)
+
+ def test_gh_22886(self, xp):
+ w, h = freqz(xp.asarray([1.]), worN=xp.asarray([0., 0.1]))
+ xp_assert_equal(w, xp.asarray([0. , 0.1]))
+ xp_assert_equal(h, xp.asarray([1.+0.j, 1.+0.j]))
+
+ def test_basic(self, xp):
+ w, h = freqz(xp.asarray([1.0]), worN=8)
+ assert_array_almost_equal(w, xp.pi * xp.arange(8, dtype=w.dtype) / 8.)
+ assert_array_almost_equal(h, xp.ones(8))
+ w, h = freqz(xp.asarray([1.0]), worN=9)
+ assert_array_almost_equal(w, xp.pi * xp.arange(9, dtype=w.dtype) / 9.)
+ assert_array_almost_equal(h, xp.ones(9))
+
+ for a in [1, xp.ones(2)]:
+ w, h = freqz(xp.ones(2), a, worN=0)
+ assert w.shape == (0,)
+ assert h.shape == (0,)
+ hdt = xp.complex128 if xp_default_dtype(xp) == xp.float64 else xp.complex64
+ assert h.dtype == hdt
+
+ def test_basic2(self, xp):
+ t = xp.linspace(0, 1, 4, endpoint=False)
+ for b, a, h_whole in zip(
+ (xp.asarray([1., 0, 0, 0]), xp.sin(2 * xp.pi * t)),
+ (xp.asarray([1., 0, 0, 0]), xp.asarray([0.5, 0, 0, 0])),
+ (xp.asarray([1., 1., 1., 1.]), xp.asarray([0, -4j, 0, 4j]))
+ ):
+
+ w, h = freqz(b, a, worN=4, whole=True)
+ expected_w = xp.linspace(0, 2 * xp.pi, 4, endpoint=False)
+ assert_array_almost_equal(w, expected_w)
+ assert_array_almost_equal(h, h_whole)
+
+ if is_numpy(xp):
+ # simultaneously check int-like support
+ w, h = freqz(b, a, worN=np.int32(4), whole=True)
+ assert_array_almost_equal(w, expected_w)
+ assert_array_almost_equal(h, h_whole)
+
+ w, h = freqz(b, a, worN=w, whole=True)
+ assert_array_almost_equal(w, expected_w)
+ assert_array_almost_equal(h, h_whole)
+
+ def test_basic3(self):
+ t = np.linspace(0, 1, 4, endpoint=False)
+ expected_w = np.linspace(0, 2 * np.pi, 4, endpoint=False)
+ for b, a, h_whole in zip(
+ (np.asarray([1., 0, 0, 0]), np.sin(2 * np.pi * t)),
+ (np.asarray([1., 0, 0, 0]), np.asarray([0.5, 0, 0, 0])),
+ (np.asarray([1., 1., 1., 1.]), np.asarray([0, -4j, 0, 4j]))
+ ):
+
+ w, h = freqz(b, a, worN=np.int32(4), whole=True)
+ assert_array_almost_equal(w, expected_w)
+ assert_array_almost_equal(h, h_whole)
+
+ w, h = freqz(b, a, worN=w, whole=True)
+ assert_array_almost_equal(w, expected_w)
+ assert_array_almost_equal(h, h_whole)
+
+ def test_basic_whole(self, xp):
+ w, h = freqz(xp.asarray([1.0]), worN=8, whole=True)
+ assert_array_almost_equal(w, 2 * xp.pi * xp.arange(8.0) / 8)
+ assert_array_almost_equal(h, xp.ones(8))
+
+ def test_plot(self, xp):
+
+ def plot(w, h):
+ assert_array_almost_equal(w, xp.pi * xp.arange(8.0) / 8)
+ assert_array_almost_equal(h, xp.ones(8))
+
+ with assert_raises(ZeroDivisionError):
+ freqz(xp.asarray([1.0]), worN=8, plot=lambda w, h: 1 / 0)
+
+ freqz(xp.asarray([1.0]), worN=8, plot=plot)
+
+ def test_fft_wrapping(self, xp):
+ # Some simple real FIR filters
+ bs = list() # filters
+ as_ = list()
+ hs_whole = list()
+ hs_half = list()
+ # 3 taps
+ t = xp.linspace(0, 1, 3, endpoint=False)
+ bs.append(xp.sin(2 * xp.pi * t))
+ as_.append(3.)
+ hs_whole.append(xp.asarray([0, -0.5j, 0.5j]))
+ hs_half.append(xp.asarray([0, math.sqrt(1./12.), -0.5j]))
+ # 4 taps
+ t = xp.linspace(0, 1, 4, endpoint=False)
+ bs.append(xp.sin(2 * xp.pi * t))
+ as_.append(0.5)
+ hs_whole.append(xp.asarray([0, -4j, 0, 4j]))
+ hs_half.append(xp.asarray([0, math.sqrt(8), -4j, -math.sqrt(8)]))
+ del t
+ for ii, b in enumerate(bs):
+ # whole
+ a = as_[ii]
+ expected_w = xp.linspace(0, 2 * xp.pi, b.shape[0], endpoint=False)
+ w, h = freqz(b, a, worN=expected_w, whole=True) # polyval
+ err_msg = f'b = {b}, a={a}'
+ assert_array_almost_equal(w, expected_w, err_msg=err_msg)
+ assert_array_almost_equal(h, hs_whole[ii], err_msg=err_msg)
+
+ w, h = freqz(b, a, worN=b.shape[0], whole=True) # FFT
+ assert_array_almost_equal(w, expected_w, err_msg=err_msg)
+ assert_array_almost_equal(h, hs_whole[ii], err_msg=err_msg)
+
+ # non-whole
+ expected_w = xp.linspace(0, xp.pi, b.shape[0], endpoint=False)
+ w, h = freqz(b, a, worN=expected_w, whole=False) # polyval
+ assert_array_almost_equal(w, expected_w, err_msg=err_msg)
+ assert_array_almost_equal(h, hs_half[ii], err_msg=err_msg)
+
+ w, h = freqz(b, a, worN=b.shape[0], whole=False) # FFT
+ assert_array_almost_equal(w, expected_w, err_msg=err_msg)
+ assert_array_almost_equal(h, hs_half[ii], err_msg=err_msg)
+
+ # some random FIR filters (real + complex)
+ # assume polyval is accurate
+ rng = np.random.RandomState(0)
+ for ii in range(2, 10): # number of taps
+ b = xp.asarray(rng.randn(ii))
+ for kk in range(2):
+ a = xp.asarray(rng.randn(1) if kk == 0 else rng.randn(3))
+ for jj in range(2):
+ if jj == 1:
+ b = b + xp.asarray(rng.randn(ii)) * 1j
+
+ # whole
+ expected_w = xp.linspace(0, 2 * xp.pi, ii, endpoint=False)
+ w, expected_h = freqz(b, a, worN=expected_w, whole=True)
+ assert_array_almost_equal(w, expected_w)
+ w, h = freqz(b, a, worN=ii, whole=True)
+ assert_array_almost_equal(w, expected_w)
+ assert_array_almost_equal(h, expected_h, decimal=4)
+
+ # half
+ expected_w = xp.linspace(0, xp.pi, ii, endpoint=False)
+ w, expected_h = freqz(b, a, worN=expected_w, whole=False)
+ assert_array_almost_equal(w, expected_w)
+ w, h = freqz(b, a, worN=ii, whole=False)
+ assert_array_almost_equal(w, expected_w)
+ assert_array_almost_equal(h, expected_h, decimal=4)
+
+ def test_broadcasting1(self, xp):
+ # Test broadcasting with worN an integer or a 1-D array,
+ # b and a are n-dimensional arrays.
+ np.random.seed(123)
+ b = np.random.rand(3, 5, 1)
+ a = np.random.rand(2, 1)
+ b, a = map(xp.asarray, (b, a))
+
+ for whole in [False, True]:
+ # Test with worN being integers (one fast for FFT and one not),
+ # a 1-D array, and an empty array.
+ for worN in [16, 17, xp.linspace(0, 1, 10), xp.asarray([])]:
+ w, h = freqz(b, a, worN=worN, whole=whole)
+ for k in range(b.shape[1]):
+ bk = b[:, k, 0]
+ ak = a[:, 0]
+ ww, hh = freqz(bk, ak, worN=worN, whole=whole)
+ xp_assert_close(ww, w)
+ xp_assert_close(hh, h[k, ...])
+
+ def test_broadcasting2(self, xp):
+ # Test broadcasting with worN an integer or a 1-D array,
+ # b is an n-dimensional array, and a is left at the default value.
+ np.random.seed(123)
+ b = np.random.rand(3, 5, 1)
+ b = xp.asarray(b)
+ for whole in [False, True]:
+ for worN in [16, 17, xp.linspace(0, 1, 10)]:
+ w, h = freqz(b, worN=worN, whole=whole)
+ for k in range(b.shape[1]):
+ bk = b[:, k, 0]
+ ww, hh = freqz(bk, worN=worN, whole=whole)
+ xp_assert_close(ww, w)
+ xp_assert_close(hh, h[k, :])
+
+ def test_broadcasting3(self, xp):
+ # Test broadcasting where b.shape[-1] is the same length
+ # as worN, and a is left at the default value.
+ np.random.seed(123)
+ N = 16
+ b = np.random.rand(3, N)
+ b = xp.asarray(b)
+ for whole in [False, True]:
+ for worN in [N, xp.linspace(0, 1, N)]:
+ w, h = freqz(b, worN=worN, whole=whole)
+ assert xp_size(w) == N
+ for k in range(N):
+ bk = b[:, k]
+ ww, hh = freqz(bk, worN=w[k], whole=whole)
+ xp_assert_close(ww, xp.asarray(w[k])[None])
+ xp_assert_close(hh, xp.asarray(h[k])[None])
+
+ def test_broadcasting4(self, xp):
+ # Test broadcasting with worN a 2-D array.
+ np.random.seed(123)
+ b = np.random.rand(4, 2, 1, 1)
+ a = np.random.rand(5, 2, 1, 1)
+ b, a = map(xp.asarray, (b, a))
+
+ for whole in [False, True]:
+ for worN in [np.random.rand(6, 7), np.empty((6, 0))]:
+ worN = xp.asarray(worN)
+ w, h = freqz(b, a, worN=worN, whole=whole)
+ xp_assert_close(w, worN, rtol=1e-14)
+ assert h.shape == (2,) + worN.shape
+ for k in range(2):
+ ww, hh = freqz(b[:, k, 0, 0], a[:, k, 0, 0],
+ worN=xp.reshape(worN, (-1,)),
+ whole=whole)
+ xp_assert_close(ww, xp.reshape(worN, (-1,)), rtol=1e-14)
+ xp_assert_close(hh, xp.reshape(h[k, :, :], (-1,)))
+
+ def test_backward_compat(self):
+ # For backward compatibility, test if None act as a wrapper for default
+ w1, h1 = freqz([1.0], 1)
+ w2, h2 = freqz([1.0], 1, None)
+ assert_array_almost_equal(w1, w2)
+ assert_array_almost_equal(h1, h2)
+
+ def test_fs_param(self, xp):
+ fs = 900
+ b = xp.asarray([0.039479155677484369, 0.11843746703245311, 0.11843746703245311,
+ 0.039479155677484369])
+ a = xp.asarray([1.0, -1.3199152021838287, 0.80341991081938424,
+ -0.16767146321568049])
+
+ # N = None, whole=False
+ w1, h1 = freqz(b, a, fs=fs)
+ w2, h2 = freqz(b, a)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.linspace(0, fs/2, 512, endpoint=False))
+
+ # N = None, whole=True
+ w1, h1 = freqz(b, a, whole=True, fs=fs)
+ w2, h2 = freqz(b, a, whole=True)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.linspace(0, fs, 512, endpoint=False))
+
+ # N = 5, whole=False
+ w1, h1 = freqz(b, a, 5, fs=fs)
+ w2, h2 = freqz(b, a, 5)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.linspace(0, fs/2, 5, endpoint=False))
+
+ # N = 5, whole=True
+ w1, h1 = freqz(b, a, 5, whole=True, fs=fs)
+ w2, h2 = freqz(b, a, 5, whole=True)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.linspace(0, fs, 5, endpoint=False))
+
+ if is_numpy(xp):
+ # w is an array_like
+ for w in ([123], (123,), xp.asarray([123]), (50, 123, 230),
+ xp.asarray([50, 123, 230])):
+ w1, h1 = freqz(b, a, w, fs=fs)
+ w2, h2 = freqz(b, a, 2*pi*xp.asarray(w, dtype=xp.float64)/ fs)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.asarray(w), check_dtype=False)
+
+ def test_w_or_N_types(self):
+ # Measure at 7 (polyval) or 8 (fft) equally-spaced points
+ for N in (7, np.int8(7), np.int16(7), np.int32(7), np.int64(7),
+ np.array(7),
+ 8, np.int8(8), np.int16(8), np.int32(8), np.int64(8),
+ np.array(8)):
+
+ w, h = freqz([1.0], worN=N)
+ assert_array_almost_equal(w, np.pi * np.arange(N) / N)
+ assert_array_almost_equal(h, np.ones(N))
+
+ w, h = freqz([1.0], worN=N, fs=100)
+ assert_array_almost_equal(w, np.linspace(0, 50, N, endpoint=False))
+ assert_array_almost_equal(h, np.ones(N))
+
+ # Measure at frequency 8 Hz
+ for w in (8.0, 8.0+0j):
+ # Only makes sense when fs is specified
+ w_out, h = freqz(np.asarray([1.0]), worN=w, fs=100)
+ assert_array_almost_equal(w_out, np.asarray([8]))
+ assert_array_almost_equal(h, np.asarray(1.), check_0d=False)
+
+ def test_nyquist(self, xp):
+ w, h = freqz(xp.asarray([1.0]), worN=8, include_nyquist=True)
+ assert_array_almost_equal(w, xp.pi * xp.arange(8, dtype=w.dtype) / 7.)
+ assert_array_almost_equal(h, xp.ones(8))
+ w, h = freqz(xp.asarray([1.0]), worN=9, include_nyquist=True)
+ assert_array_almost_equal(w, xp.pi * xp.arange(9, dtype=w.dtype) / 8.)
+ assert_array_almost_equal(h, xp.ones(9))
+
+ for a in [1, xp.ones(2)]:
+ w, h = freqz(xp.ones(2), a, worN=0, include_nyquist=True)
+ assert w.shape == (0,)
+ assert h.shape == (0,)
+ hdt = xp.complex128 if xp_default_dtype(xp) == xp.float64 else xp.complex64
+ assert h.dtype == hdt
+
+ w1, h1 = freqz(xp.asarray([1.0]), worN=8, whole = True, include_nyquist=True)
+ w2, h2 = freqz(xp.asarray([1.0]), worN=8, whole = True, include_nyquist=False)
+ assert_array_almost_equal(w1, w2)
+ assert_array_almost_equal(h1, h2)
+
+ # https://github.com/scipy/scipy/issues/17289
+ # https://github.com/scipy/scipy/issues/15273
+ @pytest.mark.parametrize('whole,nyquist,worN',
+ [(False, False, 32),
+ (False, True, 32),
+ (True, False, 32),
+ (True, True, 32),
+ (False, False, 257),
+ (False, True, 257),
+ (True, False, 257),
+ (True, True, 257)])
+
+ @xfail_xp_backends("cupy", reason="XXX: CuPy's version suspect")
+ def test_17289(self, whole, nyquist, worN, xp):
+ d = xp.asarray([0.0, 1.0])
+ w, Drfft = freqz(d, worN=32, whole=whole, include_nyquist=nyquist)
+ _, Dpoly = freqz(d, worN=w)
+ xp_assert_close(Drfft, Dpoly)
+
+ def test_fs_validation(self):
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ freqz([1.0], fs=np.array([10, 20]))
+
+ with pytest.raises(ValueError, match="Sampling.*be none."):
+ freqz([1.0], fs=None)
+
+
+
+@make_xp_test_case(freqz_sos)
+class TestFreqz_sos:
+
+ def test_freqz_sos_basic(self, xp):
+ # Compare the results of freqz and freqz_sos for a low order
+ # Butterworth filter.
+
+ N = 500
+
+ b, a = butter(4, 0.2)
+ sos = butter(4, 0.2, output='sos')
+ w, h = freqz(b, a, worN=N)
+
+ w, h, sos = map(xp.asarray, (w, h, sos))
+ w2, h2 = freqz_sos(sos, worN=N)
+ xp_assert_close(w2, w, rtol=1e-15)
+ xp_assert_close(h2, h, rtol=1e-10, atol=1e-14)
+
+ b, a = ellip(3, 1, 30, (0.2, 0.3), btype='bandpass')
+ sos = ellip(3, 1, 30, (0.2, 0.3), btype='bandpass', output='sos')
+ w, h = freqz(b, a, worN=N)
+
+ w, h, sos = map(xp.asarray, (w, h, sos))
+ w2, h2 = freqz_sos(sos, worN=N)
+ xp_assert_close(w2, w, rtol=1e-15)
+ xp_assert_close(h2, h, rtol=1e-10, atol=1e-14)
+
+ # must have at least one section
+ with assert_raises(ValueError):
+ freqz_sos(sos[:0, ...])
+
+ def test_backward_compat(self, xp):
+ # For backward compatibility, test if None act as a wrapper for default
+ N = 500
+
+ sos = butter(4, 0.2, output='sos')
+ w2, h2 = sosfreqz(sos, worN=N)
+ sos, w2, h2 = map(xp.asarray, (sos, w2, h2))
+ w1, h1 = freqz_sos(sos, worN=N)
+ assert_array_almost_equal(w1, w2)
+ assert_array_almost_equal(h1, h2)
+
+ @skip_xp_backends("dask.array", reason="float cannot be interpreted as an integer")
+ def test_freqz_sos_design(self, xp):
+ # Compare freqz_sos output against expected values for different
+ # filter types
+ # TODO: split into multiple tests, or parameterize across filter types
+ # in some way.
+
+ # from cheb2ord
+ N, Wn = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60)
+ sos = cheby2(N, 60, Wn, 'stop', output='sos')
+ sos = xp.asarray(sos) # XXX
+ zero = xp.asarray(0., dtype=xp.float64)
+
+ w, h = freqz_sos(sos)
+ h = xp.abs(h)
+ w = w / xp.pi
+ xp_assert_close(20 * xp.log10(h[w <= 0.1]),
+ zero, atol=3.01,
+ check_shape=False)
+ xp_assert_close(20 * xp.log10(h[w >= 0.6]),
+ zero, atol=3.01,
+ check_shape=False)
+ xp_assert_close(h[(w >= 0.2) & (w <= 0.5)],
+ zero, atol=1e-3,
+ check_shape=False) # <= -60 dB
+
+ N, Wn = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 150)
+ sos = cheby2(N, 150, Wn, 'stop', output='sos')
+ sos = xp.asarray(sos)
+
+ w, h = freqz_sos(sos)
+ dB = 20*xp.log10(xp.abs(h))
+ w = w / xp.pi
+ xp_assert_close(dB[w <= 0.1], zero, atol=3.01, check_shape=False)
+ xp_assert_close(dB[w >= 0.6], zero, atol=3.01, check_shape=False)
+ assert xp.all(dB[(w >= 0.2) & (w <= 0.5)] < -149.9)
+
+ # from cheb1ord
+ N, Wn = cheb1ord(0.2, 0.3, 3, 40)
+ sos = cheby1(N, 3, Wn, 'low', output='sos')
+ sos = xp.asarray(sos)
+
+ w, h = freqz_sos(sos)
+ h = xp.abs(h)
+ w = w / xp.pi
+ xp_assert_close(20 * xp.log10(h[w <= 0.2]), zero, atol=3.01,
+ check_shape=False)
+ xp_assert_close(h[w >= 0.3], zero, atol=1e-2,
+ check_shape=False) # <= -40 dB
+
+ N, Wn = cheb1ord(0.2, 0.3, 1, 150)
+ sos = cheby1(N, 1, Wn, 'low', output='sos')
+ sos = xp.asarray(sos)
+
+ w, h = freqz_sos(sos)
+ dB = 20*xp.log10(xp.abs(h))
+ w /= np.pi
+ xp_assert_close(dB[w <= 0.2], zero, atol=1.01, check_shape=False)
+ assert xp.all(dB[w >= 0.3] < -149.9)
+
+ # adapted from ellipord
+ N, Wn = ellipord(0.3, 0.2, 3, 60)
+ sos = ellip(N, 0.3, 60, Wn, 'high', output='sos')
+ sos = xp.asarray(sos)
+
+ w, h = freqz_sos(sos)
+ h = xp.abs(h)
+ w = w / xp.pi
+ xp_assert_close(20 * xp.log10(h[w >= 0.3]), zero, atol=3.01,
+ check_shape=False)
+ xp_assert_close(h[w <= 0.1], zero, atol=1.5e-3,
+ check_shape=False) # <= -60 dB (approx)
+
+ # adapted from buttord
+ N, Wn = buttord([0.2, 0.5], [0.14, 0.6], 3, 40)
+ sos = butter(N, Wn, 'band', output='sos')
+ sos = xp.asarray(sos)
+
+ w, h = freqz_sos(sos)
+ h = xp.abs(h)
+ w = w / xp.pi
+
+ h014 = h[w <= 0.14]
+ xp_assert_close(h014, xp.zeros_like(h014), atol=1e-2) # <= -40 dB
+ h06 = h[w >= 0.6]
+ xp_assert_close(h06, xp.zeros_like(h06), atol=1e-2) # <= -40 dB
+ h0205 = 20 * xp.log10(h[(w >= 0.2) & (w <= 0.5)])
+ xp_assert_close(h0205, xp.zeros_like(h0205), atol=3.01)
+
+ N, Wn = buttord([0.2, 0.5], [0.14, 0.6], 3, 100)
+ sos = butter(N, Wn, 'band', output='sos')
+ sos = xp.asarray(sos)
+
+ w, h = freqz_sos(sos)
+ dB = 20*xp.log10(xp.maximum(xp.abs(h), xp.asarray(1e-10)))
+ w = w / xp.pi
+
+ assert xp.all(dB[(w > 0) & (w <= 0.14)] < -99.9)
+ assert xp.all(dB[w >= 0.6] < -99.9)
+ db0205 = dB[(w >= 0.2) & (w <= 0.5)]
+ xp_assert_close(db0205, xp.zeros_like(db0205), atol=3.01)
+
+ def test_freqz_sos_design_ellip(self, xp):
+ N, Wn = ellipord(0.3, 0.1, 3, 60)
+ sos = ellip(N, 0.3, 60, Wn, 'high', output='sos')
+ sos = xp.asarray(sos)
+
+ w, h = freqz_sos(sos)
+ h = xp.abs(h)
+ w = w / xp.pi
+
+ h03 = 20 * xp.log10(h[w >= 0.3])
+ xp_assert_close(h03, xp.zeros_like(h03), atol=3.01)
+ h01 = h[w <= 0.1]
+ xp_assert_close(h01, xp.zeros_like(h01), atol=1.5e-3) # <= -60 dB (approx)
+
+ N, Wn = ellipord(0.3, 0.2, .5, 150)
+ sos = ellip(N, .5, 150, Wn, 'high', output='sos')
+ sos = xp.asarray(sos)
+
+ w, h = freqz_sos(sos)
+ dB = 20*xp.log10(xp.maximum(xp.abs(h), xp.asarray(1e-10)))
+ w = w / xp.pi
+
+ db03 = dB[w >= 0.3]
+ xp_assert_close(db03, xp.zeros_like(db03), atol=.55)
+ # Allow some numerical slop in the upper bound -150, so this is
+ # a check that dB[w <= 0.2] is less than or almost equal to -150.
+ assert xp.max(dB[w <= 0.2]) < -150*(1 - 1e-12)
+
+ @pytest.mark.thread_unsafe(
+ reason=("mpmath gmpy2 backend is not thread-safe, "
+ "see https://github.com/mpmath/mpmath/issues/974"))
+ @mpmath_check("0.10")
+ def test_freqz_sos_against_mp(self, xp):
+ # Compare the result of freqz_sos applied to a high order Butterworth
+ # filter against the result computed using mpmath. (signal.freqz fails
+ # miserably with such high order filters.)
+ from . import mpsig
+ N = 500
+ order = 25
+ Wn = 0.15
+ with mpmath.workdps(80):
+ z_mp, p_mp, k_mp = mpsig.butter_lp(order, Wn)
+ w_mp, h_mp = mpsig.zpkfreqz(z_mp, p_mp, k_mp, N)
+ w_mp = xp.asarray([float(x) for x in w_mp], dtype=xp.float64)
+ h_mp = xp.asarray([complex(x) for x in h_mp], dtype=xp.complex128)
+
+ sos = butter(order, Wn, output='sos')
+ sos = xp.asarray(sos, dtype=xp.float64)
+ w, h = freqz_sos(sos, worN=N)
+ xp_assert_close(w, w_mp, rtol=1e-12, atol=1e-14)
+ xp_assert_close(h, h_mp, rtol=1e-12, atol=1e-14)
+
+ def test_fs_param(self, xp):
+ fs = 900
+ sos = xp.asarray(
+ [[0.03934683014103762, 0.07869366028207524, 0.03934683014103762,
+ 1.0, -0.37256600288916636, 0.0],
+ [1.0, 1.0, 0.0, 1.0, -0.9495739996946778, 0.45125966317124144]]
+ )
+
+ # N = None, whole=False
+ w1, h1 = freqz_sos(sos, fs=fs)
+ w2, h2 = freqz_sos(sos)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.linspace(0, fs/2, 512, endpoint=False))
+
+ # N = None, whole=True
+ w1, h1 = freqz_sos(sos, whole=True, fs=fs)
+ w2, h2 = freqz_sos(sos, whole=True)
+ xp_assert_close(h1, h2, atol=1e-27)
+ xp_assert_close(w1, xp.linspace(0, fs, 512, endpoint=False))
+
+ # N = 5, whole=False
+ w1, h1 = freqz_sos(sos, 5, fs=fs)
+ w2, h2 = freqz_sos(sos, 5)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.linspace(0, fs/2, 5, endpoint=False))
+
+ # N = 5, whole=True
+ w1, h1 = freqz_sos(sos, 5, whole=True, fs=fs)
+ w2, h2 = freqz_sos(sos, 5, whole=True)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.linspace(0, fs, 5, endpoint=False))
+
+ @skip_xp_backends(np_only=True, reason="array-likes")
+ def test_fs_param2(self, xp):
+ fs = 900
+ sos = xp.asarray(
+ [[0.03934683014103762, 0.07869366028207524, 0.03934683014103762,
+ 1.0, -0.37256600288916636, 0.0],
+ [1.0, 1.0, 0.0, 1.0, -0.9495739996946778, 0.45125966317124144]]
+ )
+
+ # w is an array_like
+ for w in ([123], (123,), xp.asarray([123]), (50, 123, 230),
+ xp.asarray([50, 123, 230])):
+ w1, h1 = freqz_sos(sos, w, fs=fs)
+ w1, h1 = map(xp.asarray, (w1, h1))
+
+ w2, h2 = freqz_sos(sos, 2*pi*xp.asarray(w, dtype=sos.dtype)/fs)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w, w1, check_dtype=False)
+
+ def test_w_or_N_types(self):
+ # Measure at 7 (polyval) or 8 (fft) equally-spaced points
+ for N in (7, np.int8(7), np.int16(7), np.int32(7), np.int64(7),
+ np.array(7),
+ 8, np.int8(8), np.int16(8), np.int32(8), np.int64(8),
+ np.array(8)):
+
+ w, h = freqz_sos([1, 0, 0, 1, 0, 0], worN=N)
+ assert_array_almost_equal(w, np.pi * np.arange(N) / N)
+ assert_array_almost_equal(h, np.ones(N))
+
+ w, h = freqz_sos([1, 0, 0, 1, 0, 0], worN=N, fs=100)
+ assert_array_almost_equal(w, np.linspace(0, 50, N, endpoint=False))
+ assert_array_almost_equal(h, np.ones(N))
+
+ # Measure at frequency 8 Hz
+ for w in (8.0, 8.0+0j):
+ # Only makes sense when fs is specified
+ w_out, h = freqz_sos([1, 0, 0, 1, 0, 0], worN=w, fs=100)
+ assert_array_almost_equal(w_out, [8])
+ assert_array_almost_equal(h, [1])
+
+ def test_fs_validation(self):
+ sos = butter(4, 0.2, output='sos')
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ freqz_sos(sos, fs=np.array([10, 20]))
+
+
+@make_xp_test_case(freqz_zpk)
+class TestFreqz_zpk:
+
+ def test_ticket1441(self, xp):
+ """Regression test for ticket 1441."""
+ # Because freqz previously used arange instead of linspace,
+ # when N was large, it would return one more point than
+ # requested.
+ N = 100000
+ w, h = freqz_zpk(xp.asarray([0.5]), xp.asarray([0.5]), 1.0, worN=N)
+ assert w.shape == (N,)
+
+ def test_basic(self, xp):
+ w, h = freqz_zpk(xp.asarray([0.5]), xp.asarray([0.5]), 1.0, worN=8)
+ assert_array_almost_equal(w, xp.pi * xp.arange(8.0) / 8)
+ assert_array_almost_equal(h, xp.ones(8))
+
+ def test_basic_whole(self, xp):
+ w, h = freqz_zpk(xp.asarray([0.5]), xp.asarray([0.5]), 1.0, worN=8, whole=True)
+ assert_array_almost_equal(w, 2 * xp.pi * xp.arange(8.0) / 8)
+ assert_array_almost_equal(h, xp.ones(8))
+
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ def test_vs_freqz(self, xp):
+ b, a = cheby1(4, 5, 0.5, analog=False, output='ba')
+ z, p, k = cheby1(4, 5, 0.5, analog=False, output='zpk')
+
+ w1, h1 = freqz(b, a)
+ z, p, k, w1, h1 = map(xp.asarray, (z, p, k, w1, h1))
+ w2, h2 = freqz_zpk(z, p, k)
+ xp_assert_close(w1, w2)
+ xp_assert_close(h1, h2, rtol=1.3e-6)
+
+ def test_backward_compat(self, xp):
+ # For backward compatibility, test if None act as a wrapper for default
+ w1, h1 = freqz_zpk(xp.asarray([0.5]), xp.asarray([0.5]), 1.0)
+ w2, h2 = freqz_zpk(xp.asarray([0.5]), xp.asarray([0.5]), 1.0, None)
+ assert_array_almost_equal(w1, w2)
+ assert_array_almost_equal(h1, h2)
+
+ def test_fs_param(self, xp):
+ fs = 900
+ z = xp.asarray([-1, -1, -1.0])
+ p = xp.asarray(
+ [0.4747869998473389 + 0.4752230717749344j,
+ 0.37256600288916636,
+ 0.4747869998473389 - 0.4752230717749344j]
+ )
+ k = 0.03934683014103762
+
+ # N = None, whole=False
+ w1, h1 = freqz_zpk(z, p, k, whole=False, fs=fs)
+ w2, h2 = freqz_zpk(z, p, k, whole=False)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.linspace(0, fs/2, 512, endpoint=False))
+
+ # N = None, whole=True
+ w1, h1 = freqz_zpk(z, p, k, whole=True, fs=fs)
+ w2, h2 = freqz_zpk(z, p, k, whole=True)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.linspace(0, fs, 512, endpoint=False))
+
+ # N = 5, whole=False
+ w1, h1 = freqz_zpk(z, p, k, 5, fs=fs)
+ w2, h2 = freqz_zpk(z, p, k, 5)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.linspace(0, fs/2, 5, endpoint=False))
+
+ # N = 5, whole=True
+ w1, h1 = freqz_zpk(z, p, k, 5, whole=True, fs=fs)
+ w2, h2 = freqz_zpk(z, p, k, 5, whole=True)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w1, xp.linspace(0, fs, 5, endpoint=False))
+
+ @skip_xp_backends(np_only=True, reason="array_likes")
+ def test_fs_param2(self, xp):
+ fs = 900
+ z = xp.asarray([-1, -1, -1.0])
+ p = xp.asarray(
+ [0.4747869998473389 + 0.4752230717749344j,
+ 0.37256600288916636,
+ 0.4747869998473389 - 0.4752230717749344j]
+ )
+ k = 0.03934683014103762
+
+ # w is an array_like
+ for w in ([123], (123,), xp.asarray([123]), (50, 123, 230),
+ xp.asarray([50, 123, 230])):
+ w1, h1 = freqz_zpk(z, p, k, w, fs=fs)
+ w2, h2 = freqz_zpk(z, p, k, 2*pi*xp.asarray(w)/fs)
+ xp_assert_close(h1, h2)
+ xp_assert_close(w, w1, check_dtype=False)
+
+ def test_w_or_N_types(self):
+ # Measure at 8 equally-spaced points
+ for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8),
+ np.array(8)):
+
+ w, h = freqz_zpk([], [], 1, worN=N)
+ assert_array_almost_equal(w, np.pi * np.arange(8) / 8.)
+ assert_array_almost_equal(h, np.ones(8))
+
+ w, h = freqz_zpk([], [], 1, worN=N, fs=100)
+ assert_array_almost_equal(w, np.linspace(0, 50, 8, endpoint=False))
+ assert_array_almost_equal(h, np.ones(8))
+
+ # Measure at frequency 8 Hz
+ for w in (8.0, 8.0+0j):
+ # Only makes sense when fs is specified
+ w_out, h = freqz_zpk([], [], 1, worN=w, fs=100)
+ assert_array_almost_equal(w_out, [8])
+ assert_array_almost_equal(h, [1])
+
+ def test_fs_validation(self):
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ freqz_zpk([1.0], [1.0], [1.0], fs=np.array([10., 20]))
+
+ with pytest.raises(ValueError, match="Sampling.*be none."):
+ freqz_zpk([1.0], [1.0], [1.0], fs=None)
+
+
+@make_xp_test_case(normalize)
+class TestNormalize:
+
+ def test_allclose(self, xp):
+ """Test for false positive on allclose in normalize() in
+ filter_design.py"""
+ # Test to make sure the allclose call within signal.normalize does not
+ # choose false positives. Then check against a known output from MATLAB
+ # to make sure the fix doesn't break anything.
+
+ # These are the coefficients returned from
+ # `[b,a] = cheby1(8, 0.5, 0.048)'
+ # in MATLAB. There are at least 15 significant figures in each
+ # coefficient, so it makes sense to test for errors on the order of
+ # 1e-13 (this can always be relaxed if different platforms have
+ # different rounding errors)
+ b_matlab = xp.asarray([2.150733144728282e-11, 1.720586515782626e-10,
+ 6.022052805239190e-10, 1.204410561047838e-09,
+ 1.505513201309798e-09, 1.204410561047838e-09,
+ 6.022052805239190e-10, 1.720586515782626e-10,
+ 2.150733144728282e-11])
+ a_matlab = xp.asarray([1.000000000000000e+00, -7.782402035027959e+00,
+ 2.654354569747454e+01, -5.182182531666387e+01,
+ 6.334127355102684e+01, -4.963358186631157e+01,
+ 2.434862182949389e+01, -6.836925348604676e+00,
+ 8.412934944449140e-01])
+
+ # This is the input to signal.normalize after passing through the
+ # equivalent steps in signal.iirfilter as was done for MATLAB
+ b_norm_in = xp.asarray([1.5543135865293012e-06, 1.2434508692234413e-05,
+ 4.3520780422820447e-05, 8.7041560845640893e-05,
+ 1.0880195105705122e-04, 8.7041560845640975e-05,
+ 4.3520780422820447e-05, 1.2434508692234413e-05,
+ 1.5543135865293012e-06])
+ a_norm_in = xp.asarray([7.2269025909127173e+04, -5.6242661430467968e+05,
+ 1.9182761917308895e+06, -3.7451128364682454e+06,
+ 4.5776121393762771e+06, -3.5869706138592605e+06,
+ 1.7596511818472347e+06, -4.9409793515707983e+05,
+ 6.0799461347219651e+04])
+
+ b_output, a_output = normalize(b_norm_in, a_norm_in)
+
+ # The test on b works for decimal=14 but the one for a does not. For
+ # the sake of consistency, both of these are decimal=13. If something
+ # breaks on another platform, it is probably fine to relax this lower.
+ decimal = 13 if xp_default_dtype(xp) == xp.float64 else 5
+ assert_array_almost_equal(b_matlab, b_output, decimal=decimal)
+ assert_array_almost_equal(a_matlab, a_output, decimal=decimal)
+
+ def test_errors(self):
+ """Test the error cases."""
+ # all zero denominator
+ assert_raises(ValueError, normalize, [1, 2], 0)
+
+ # denominator not 1 dimensional
+ assert_raises(ValueError, normalize, [1, 2], [[1]])
+
+ # numerator too many dimensions
+ assert_raises(ValueError, normalize, [[[1, 2]]], 1)
+
+
+@make_xp_test_case(lp2lp)
+class TestLp2lp:
+
+ def test_basic(self, xp):
+ b = xp.asarray([1])
+ a = xp.asarray([1, math.sqrt(2), 1])
+ b_lp, a_lp = lp2lp(b, a, 0.38574256627112119)
+ assert_array_almost_equal(b_lp, xp.asarray([0.1488]), decimal=4)
+ assert_array_almost_equal(a_lp, xp.asarray([1, 0.5455, 0.1488]), decimal=4)
+
+
+@make_xp_test_case(lp2hp)
+class TestLp2hp:
+
+ def test_basic(self, xp):
+ b = xp.asarray([0.25059432325190018])
+ a = xp.asarray(
+ [1, 0.59724041654134863, 0.92834805757524175, 0.25059432325190018]
+ )
+ b_hp, a_hp = lp2hp(b, a, 2*math.pi*5000)
+ xp_assert_close(b_hp, xp.asarray([1.0, 0, 0, 0]))
+ xp_assert_close(
+ a_hp, xp.asarray([1, 1.1638e5, 2.3522e9, 1.2373e14]), rtol=1e-4
+ )
+
+
+@make_xp_test_case(lp2bp)
+class TestLp2bp:
+
+ def test_basic(self, xp):
+ b = xp.asarray([1])
+ a = xp.asarray([1, 2, 2, 1])
+ b_bp, a_bp = lp2bp(b, a, 2*math.pi*4000, 2*math.pi*2000)
+ xp_assert_close(b_bp, xp.asarray([1.9844e12, 0, 0, 0]), rtol=1e-6)
+ xp_assert_close(
+ a_bp,
+ xp.asarray([1, 2.5133e4, 2.2108e9, 3.3735e13,
+ 1.3965e18, 1.0028e22, 2.5202e26]), rtol=1e-4
+ )
+
+
+@make_xp_test_case(lp2bs)
+class TestLp2bs:
+
+ def test_basic(self, xp):
+ b = xp.asarray([1])
+ a = xp.asarray([1, 1])
+ b_bs, a_bs = lp2bs(b, a, 0.41722257286366754, 0.18460575326152251)
+ assert_array_almost_equal(b_bs, xp.asarray([1, 0, 0.17407]), decimal=5)
+ assert_array_almost_equal(a_bs, xp.asarray([1, 0.18461, 0.17407]), decimal=5)
+
+
+@make_xp_test_case(bilinear)
+class TestBilinear:
+ """Tests for function `signal.bilinear`. """
+
+ def test_exceptions(self):
+ """Raise all exceptions in `bilinear()`. """
+ with pytest.raises(ValueError, match="Parameter a is not .*"):
+ bilinear(1., np.array([[1, 2, 3]]))
+ with pytest.raises(ValueError, match="Parameter b is not .*"):
+ bilinear(np.ones((2,3)), 1. )
+
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ def test_basic(self, xp):
+ # reference output values computed with sympy
+ b = [0.14879732743343033]
+ a = [1, 0.54552236880522209, 0.14879732743343033]
+ b, a = map(xp.asarray, (b, a))
+
+ b_zref = xp.asarray(
+ [0.08782128175913713, 0.17564256351827426, 0.08782128175913713]
+ )
+ a_zref = xp.asarray(
+ [1.0, -1.0047722097030667, 0.3560573367396151]
+ )
+
+ b_z, a_z = bilinear(b, a, 0.5)
+
+ xp_assert_close_nulp(b_z, b_zref)
+ xp_assert_close_nulp(a_z, a_zref)
+
+ b = xp.asarray([1, 0, 0.17407467530697837])
+ a = xp.asarray([1, 0.18460575326152251, 0.17407467530697837])
+
+ b_zref = xp.asarray(
+ [0.8641286432189045, -1.2157757001964216, 0.8641286432189045]
+ )
+ a_zref = xp.asarray([1.0, -1.2157757001964216, 0.7282572864378091])
+
+ b_z, a_z = bilinear(b, a, 0.5)
+
+ xp_assert_close_nulp(b_z, xp.asarray(b_zref))
+ xp_assert_close_nulp(a_z, xp.asarray(a_zref))
+
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ @xfail_xp_backends("cupy", reason="https://github.com/cupy/cupy/issues/9404")
+ def test_ignore_leading_zeros(self, xp):
+ # regression for gh-6606
+ # results shouldn't change when leading zeros are added to
+ # input numerator or denominator
+ b = [0.14879732743343033]
+ a = [1, 0.54552236880522209, 0.14879732743343033]
+ b, a = map(xp.asarray, (b, a))
+
+ b_zref = xp.asarray(
+ [0.08782128175913713, 0.17564256351827426, 0.08782128175913713]
+ )
+ a_zref = xp.asarray([1.0, -1.0047722097030667, 0.3560573367396151])
+
+ for lzn, lzd in product(range(4), range(4)):
+ b_z, a_z = bilinear(xpx.pad(b, (lzn, 0), xp=xp),
+ xpx.pad(a, (lzd, 0), xp=xp),
+ 0.5)
+ xp_assert_close_nulp(b_z, b_zref)
+ xp_assert_close_nulp(a_z, a_zref)
+
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ @xfail_xp_backends("cupy", reason="complex inputs not supported")
+ def test_complex(self, xp):
+ # reference output values computed with sympy
+ # this is an elliptical filter, 5Hz width, centered at +50Hz:
+ # z, p, k = signal.ellip(2, 0.5, 20, 2*np.pi*5/2, output='zpk', analog=True)
+ # z = z.astype(complex) + 2j * np.pi * 50
+ # p = p.astype(complex) + 2j * np.pi * 50
+ # b, a = signal.zpk2tf(z, p, k)
+ b = [(0.09999999999999991+0j),
+ -62.831853071795805j,
+ (-9505.857007071314+0j)]
+ a = [(1+0j),
+ (21.09511000343942-628.3185307179587j),
+ (-98310.74322875646-6627.2242613473845j)]
+ b, a = map(xp.asarray, (b, a))
+
+ # sample frequency
+ fs = 1000
+ b_zref = [(0.09905575106715676-0.00013441423112828688j),
+ (-0.18834281923181084-0.06032810039049478j),
+ (0.08054306669414343+0.05766172295523972j)]
+ a_zref = [(1+0j),
+ (-1.8839476369292854-0.606808151331815j),
+ (0.7954687330018285+0.5717459398142481j)]
+
+ b_zref, a_zref = map(xp.asarray, (b_zref, a_zref))
+
+ b_z, a_z = bilinear(b, a, fs)
+
+ # the 3 ulp difference determined from testing
+ xp_assert_close_nulp(b_z, b_zref, nulp=3)
+ xp_assert_close_nulp(a_z, a_zref, nulp=3)
+
+ def test_fs_validation(self):
+ b = [0.14879732743343033]
+ a = [1, 0.54552236880522209, 0.14879732743343033]
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ bilinear(b, a, fs=np.array([10, 20]))
+
+ with pytest.raises(ValueError, match="Sampling.*be none"):
+ bilinear(b, a, fs=None)
+
+
+@make_xp_test_case(lp2lp_zpk)
+class TestLp2lp_zpk:
+
+ @xfail_xp_backends(
+ 'dask.array', reason='https://github.com/dask/dask/issues/11883'
+ )
+ def test_basic(self, xp):
+ z = xp.asarray([])
+ p = xp.asarray([(-1+1j) / math.sqrt(2), (-1-1j) / math.sqrt(2)])
+ k = 1
+ z_lp, p_lp, k_lp = lp2lp_zpk(z, p, k, 5)
+ xp_assert_equal(z_lp, xp.asarray([]))
+ xp_assert_close(_sort_cmplx(p_lp, xp=xp), _sort_cmplx(p, xp=xp) * 5)
+ assert k_lp == 25.
+
+ # Pseudo-Chebyshev with both poles and zeros
+ z = xp.asarray([-2j, +2j])
+ p = xp.asarray([-0.75, -0.5-0.5j, -0.5+0.5j])
+ k = 3
+ z_lp, p_lp, k_lp = lp2lp_zpk(z, p, k, 20)
+ xp_assert_close(
+ _sort_cmplx(z_lp, xp=xp), _sort_cmplx([-40j, +40j], xp=xp)
+ )
+ xp_assert_close(
+ _sort_cmplx(p_lp, xp=xp), _sort_cmplx([-15, -10-10j, -10+10j], xp=xp)
+ )
+ assert k_lp == 60.
+
+ def test_fs_validation(self):
+ z = [-2j, +2j]
+ p = [-0.75, -0.5 - 0.5j, -0.5 + 0.5j]
+ k = 3
+
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ bilinear_zpk(z, p, k, fs=np.array([10, 20]))
+
+ with pytest.raises(ValueError, match="Sampling.*be none"):
+ bilinear_zpk(z, p, k, fs=None)
+
+
+@make_xp_test_case(lp2hp_zpk)
+class TestLp2hp_zpk:
+
+ @xfail_xp_backends(
+ 'dask.array', reason='https://github.com/dask/dask/issues/11883'
+ )
+ def test_basic(self, xp):
+ z = xp.asarray([])
+ p = xp.asarray([(-1+1j) / math.sqrt(2), (-1-1j) / math.sqrt(2)])
+ k = 1
+
+ z_hp, p_hp, k_hp = lp2hp_zpk(z, p, k, 5)
+ xp_assert_equal(z_hp, xp.asarray([0.0, 0.0], dtype=z_hp.dtype))
+ xp_assert_close(_sort_cmplx(p_hp, xp=xp), _sort_cmplx(p, xp=xp) * 5)
+ assert math.isclose(k_hp, 1.0, rel_tol=4e-7)
+
+ z = xp.asarray([-2j, +2j])
+ p = xp.asarray([-0.75, -0.5-0.5j, -0.5+0.5j])
+ k = 3
+ z_hp, p_hp, k_hp = lp2hp_zpk(z, p, k, 6)
+ xp_assert_close(
+ _sort_cmplx(z_hp, xp=xp), _sort_cmplx([-3j, 0, +3j], xp=xp)
+ )
+ xp_assert_close(
+ _sort_cmplx(p_hp, xp=xp), _sort_cmplx([-8, -6-6j, -6+6j], xp=xp)
+ )
+ assert k_hp == 32.0
+
+
+@make_xp_test_case(lp2bp_zpk)
+class TestLp2bp_zpk:
+
+ @xfail_xp_backends(
+ 'dask.array', reason='https://github.com/dask/dask/issues/11883'
+ )
+ def test_basic(self, xp):
+ z = xp.asarray([-2j, +2j])
+ p = xp.asarray([-0.75, -0.5-0.5j, -0.5+0.5j])
+ k = 3
+ z_bp, p_bp, k_bp = lp2bp_zpk(z, p, k, 15, 8)
+ xp_assert_close(
+ _sort_cmplx(z_bp, xp=xp),
+ _sort_cmplx([-25j, -9j, 0, +9j, +25j], xp=xp), check_dtype=False
+ )
+ xp_assert_close(
+ _sort_cmplx(p_bp, xp=xp),
+ _sort_cmplx(
+ [-3 + 6j*math.sqrt(6), -3 - 6j*math.sqrt(6),
+ +2j + cmath.sqrt(-8j - 225) - 2, -2j + cmath.sqrt(+8j - 225) - 2,
+ +2j - cmath.sqrt(-8j - 225) - 2, -2j - cmath.sqrt(+8j - 225) - 2
+ ], xp=xp
+ ), check_dtype=False
+ )
+ assert math.isclose(k_bp, 24.0)
+
+
+@make_xp_test_case(lp2bs_zpk)
+class TestLp2bs_zpk:
+
+ @xfail_xp_backends(
+ 'dask.array', reason='https://github.com/dask/dask/issues/11883'
+ )
+ def test_basic(self, xp):
+ z = xp.asarray([-2j, +2j])
+ p = xp.asarray([-0.75, -0.5-0.5j, -0.5+0.5j])
+ k = 3
+
+ z_bs, p_bs, k_bs = lp2bs_zpk(z, p, k, 35, 12)
+
+ xp_assert_close(
+ _sort_cmplx(z_bs, xp=xp),
+ _sort_cmplx([+35j, -35j,
+ +3j + math.sqrt(1234)*1j,
+ -3j + math.sqrt(1234)*1j,
+ +3j - math.sqrt(1234)*1j,
+ -3j - math.sqrt(1234)*1j], xp=xp), check_dtype=False
+ )
+ xp_assert_close(
+ _sort_cmplx(p_bs, xp=xp),
+ _sort_cmplx([+3j*math.sqrt(129) - 8,
+ -3j*math.sqrt(129) - 8,
+ (-6 + 6j) - cmath.sqrt(-1225 - 72j),
+ (-6 - 6j) - cmath.sqrt(-1225 + 72j),
+ (-6 + 6j) + cmath.sqrt(-1225 - 72j),
+ (-6 - 6j) + cmath.sqrt(-1225 + 72j), ], xp=xp),
+ check_dtype=False
+ )
+ assert math.isclose(k_bs, 32.0)
+
+
+@make_xp_test_case(bilinear_zpk)
+class TestBilinear_zpk:
+
+ @xfail_xp_backends(
+ 'dask.array', reason='https://github.com/dask/dask/issues/11883'
+ )
+ def test_basic(self, xp):
+ z = xp.asarray([-2j, +2j])
+ p = xp.asarray([-0.75, -0.5-0.5j, -0.5+0.5j])
+ k = 3
+
+ z_d, p_d, k_d = bilinear_zpk(z, p, k, 10)
+
+ xp_assert_close(
+ _sort_cmplx(z_d, xp=xp),
+ _sort_cmplx([(20-2j) / (20+2j), (20+2j) / (20-2j), -1], xp=xp)
+ )
+ xp_assert_close(
+ _sort_cmplx(p_d, xp=xp),
+ _sort_cmplx(
+ [77/83, (1j/2 + 39/2) / (41/2 - 1j/2), (39/2 - 1j/2) / (1j/2 + 41/2)],
+ xp=xp
+ )
+ )
+ assert math.isclose(k_d, 9696/69803, rel_tol=4e-7)
+
+
+class TestPrototypeType:
+
+ def test_output_type(self):
+ # Prototypes should consistently output arrays, not lists
+ # https://github.com/scipy/scipy/pull/441
+ for func in (buttap,
+ besselap,
+ lambda N: cheb1ap(N, 1),
+ lambda N: cheb2ap(N, 20),
+ lambda N: ellipap(N, 1, 20)):
+ for N in range(7):
+ z, p, k = func(N)
+ assert isinstance(z, np.ndarray)
+ assert isinstance(p, np.ndarray)
+
+ @pytest.mark.parametrize(
+ 'base_func,func', [
+ make_xp_pytest_param(buttap, buttap),
+ make_xp_pytest_param(besselap, besselap),
+ make_xp_pytest_param(cheb1ap, lambda N, xp: cheb1ap(N, 1, xp=xp)),
+ make_xp_pytest_param(cheb2ap, lambda N, xp: cheb2ap(N, 20, xp=xp)),
+ make_xp_pytest_param(ellipap, lambda N, xp: ellipap(N, 1, 20, xp=xp)),
+ ],
+ ids=['butter', 'bessel', 'cheb1', 'cheb2', 'ellip']
+ )
+ def test_with_xp(self, base_func, func, xp):
+ func(7, xp=xp)
+
+
+def dB(x):
+ # Return magnitude in decibels, avoiding divide-by-zero warnings
+ # (and deal with some "not less-ordered" errors when -inf shows up)
+ xp = array_namespace(x)
+ tiny = xp.asarray(np.finfo(np.float64).tiny)
+ return 20 * xp.log10(xp.maximum(xp.abs(x), tiny))
+
+
+@make_xp_test_case(buttord)
+@pytest.mark.skipif(DEFAULT_F32, reason="XXX needs figuring out")
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+class TestButtord:
+
+ def test_lowpass(self, xp):
+ wp = 0.2
+ ws = 0.3
+ rp = 3
+ rs = 60
+ N, Wn = buttord(xp.asarray(wp), ws, rp, rs, False)
+ b, a = butter(N, _xp_copy_to_numpy(Wn), 'lowpass', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp < dB(h[w <= wp]))
+ assert np.all(dB(h[ws <= w]) < -rs)
+
+ assert N == 16
+ xp_assert_close(Wn,
+ xp.asarray(2.0002776782743284e-01), rtol=1e-15, check_0d=False)
+
+ def test_highpass(self, xp):
+ wp = 0.3
+ ws = 0.2
+ rp = 3
+ rs = 70
+ N, Wn = buttord(xp.asarray(wp), ws, rp, rs, False)
+ b, a = butter(N, _xp_copy_to_numpy(Wn), 'highpass', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp < dB(h[wp <= w]))
+ assert np.all(dB(h[w <= ws]) < -rs)
+
+ assert N == 18
+ xp_assert_close(Wn,
+ xp.asarray(2.9996603079132672e-01), rtol=1e-15, check_0d=False)
+
+ def test_bandpass(self, xp):
+ wp = [0.2, 0.5]
+ ws = [0.1, 0.6]
+ rp = 3
+ rs = 80
+ N, Wn = buttord(xp.asarray(wp), xp.asarray(ws), rp, rs, False)
+ b, a = butter(N, _xp_copy_to_numpy(Wn), 'bandpass', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+
+ assert np.all((-rp - 0.1) < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])]))
+
+ assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < (-rs + 0.1))
+
+ assert N == 18
+ xp_assert_close(
+ Wn, xp.asarray([1.9998742411409134e-01, 5.0002139595676276e-01]),
+ rtol=1e-15,
+ )
+
+ @skip_xp_backends(
+ cpu_only=True, exceptions=["cupy"], reason="optimize.fminbound"
+ )
+ def test_bandstop(self, xp):
+ wp = [0.1, 0.6]
+ ws = [0.2, 0.5]
+ rp = 3
+ rs = 90
+ N, Wn = buttord(xp.asarray(wp), xp.asarray(ws), rp, rs, False)
+ b, a = butter(N, _xp_copy_to_numpy(Wn), 'bandstop', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+
+ assert np.all(-rp < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)]))
+ assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs)
+
+ assert N == 20
+ xp_assert_close(
+ Wn, xp.asarray([1.4759432329294042e-01, 5.9997365985276407e-01]),
+ rtol=1e-6
+ )
+
+ def test_analog(self, xp):
+ wp = 200.
+ ws = 600.
+ rp = 3
+ rs = 60
+ N, Wn = buttord(xp.asarray(wp), ws, rp, rs, True)
+ b, a = butter(N, _xp_copy_to_numpy(Wn), 'lowpass', True)
+ w, h = freqs(b, a)
+ assert np.all(-rp < dB(h[w <= wp]))
+ assert np.all(dB(h[ws <= w]) < -rs)
+
+ assert N == 7
+ xp_assert_close(
+ Wn, xp.asarray(2.0006785355671877e+02), rtol=1e-15, check_0d=False
+ )
+
+ n, Wn = buttord(1., xp.asarray(550/450), 1, 26, analog=True)
+ assert n == 19
+ xp_assert_close(
+ Wn, xp.asarray(1.0361980524629517), rtol=1e-15, check_0d=False
+ )
+
+ assert buttord(1, xp.asarray(1.2), 1, 80, analog=True)[0] == 55
+
+ def test_fs_param(self, xp):
+ wp = [4410, 11025]
+ ws = [2205, 13230]
+ rp = 3
+ rs = 80
+ fs = 44100
+ N, Wn = buttord(xp.asarray(wp), xp.asarray(ws), rp, rs, False, fs=fs)
+ b, a = butter(N, _xp_copy_to_numpy(Wn), 'bandpass', False, fs=fs)
+ w, h = freqz(b, a, fs=fs)
+
+ assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])]))
+ assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1)
+
+ assert N == 18
+ xp_assert_close(Wn, xp.asarray([4409.722701715714, 11025.47178084662]),
+ rtol=1e-15)
+
+ def test_invalid_input(self):
+ with pytest.raises(ValueError) as exc_info:
+ buttord([20, 50], [14, 60], 3, 2)
+ assert "gpass should be smaller than gstop" in str(exc_info.value)
+
+ with pytest.raises(ValueError) as exc_info:
+ buttord([20, 50], [14, 60], -1, 2)
+ assert "gpass should be larger than 0.0" in str(exc_info.value)
+
+ with pytest.raises(ValueError) as exc_info:
+ buttord([20, 50], [14, 60], 1, -2)
+ assert "gstop should be larger than 0.0" in str(exc_info.value)
+
+ def test_runtime_warnings(self):
+ msg = "Order is zero.*|divide by zero encountered"
+ with pytest.warns(RuntimeWarning, match=msg):
+ buttord(0.0, 1.0, 3, 60)
+
+ def test_ellip_butter(self):
+ # The purpose of the test is to compare to some known output from past
+ # scipy versions. The values to compare to are generated with scipy
+ # 1.9.1 (there is nothing special about this particular version though)
+ n, wn = buttord([0.1, 0.6], [0.2, 0.5], 3, 60)
+ assert n == 14
+
+ def test_fs_validation(self):
+ wp = 0.2
+ ws = 0.3
+ rp = 3
+ rs = 60
+
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ buttord(wp, ws, rp, rs, False, fs=np.array([10, 20]))
+
+
+@make_xp_test_case(cheb1ord)
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+class TestCheb1ord:
+
+ @xfail_xp_backends("torch", reason="accuracy is bad")
+ def test_lowpass(self, xp):
+ wp = 0.2
+ ws = 0.3
+ rp = 3
+ rs = 60
+ N, Wn = cheb1ord(xp.asarray(wp), ws, rp, rs, False)
+ b, a = cheby1(N, rp, _xp_copy_to_numpy(Wn), 'low', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[w <= wp]))
+ assert np.all(dB(h[ws <= w]) < -rs + 0.1)
+
+ assert N == 8
+ xp_assert_close(Wn, xp.asarray(0.2), rtol=1e-15, check_0d=False)
+
+ @xfail_xp_backends("torch", reason="accuracy is bad")
+ def test_highpass(self, xp):
+ wp = 0.3
+ ws = 0.2
+ rp = 3
+ rs = 70
+ N, Wn = cheb1ord(xp.asarray(wp), ws, rp, rs, False)
+ b, a = cheby1(N, rp, _xp_copy_to_numpy(Wn), 'high', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[wp <= w]))
+ assert np.all(dB(h[w <= ws]) < -rs + 0.1)
+
+ assert N == 9
+ xp_assert_close(Wn, xp.asarray(0.3), rtol=1e-15, check_0d=False)
+
+ def test_bandpass(self, xp):
+ wp = [0.2, 0.5]
+ ws = [0.1, 0.6]
+ rp = 3
+ rs = 80
+ N, Wn = cheb1ord(xp.asarray(wp), xp.asarray(ws), rp, rs, False)
+ b, a = cheby1(N, rp, _xp_copy_to_numpy(Wn), 'band', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])]))
+ assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1)
+
+ assert N == 9
+ xp_assert_close(Wn, xp.asarray([0.2, 0.5]), rtol=1e-15)
+
+ @skip_xp_backends(
+ cpu_only=True, exceptions=["cupy"], reason="optimize.fminbound"
+ )
+ def test_bandstop(self, xp):
+ wp = [0.1, 0.6]
+ ws = [0.2, 0.5]
+ rp = 3
+ rs = 90
+ N, Wn = cheb1ord(xp.asarray(wp), xp.asarray(ws), rp, rs, False)
+ b, a = cheby1(N, rp, _xp_copy_to_numpy(Wn), 'stop', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)]))
+ assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1)
+
+ assert N == 10
+ xp_assert_close(Wn, xp.asarray([0.14758232569947785, 0.6]), rtol=1e-5)
+
+ def test_analog(self, xp):
+ wp = 700
+ ws = 100.
+ rp = 3
+ rs = 70
+ N, Wn = cheb1ord(wp, xp.asarray(ws), rp, rs, True)
+ b, a = cheby1(N, rp, _xp_copy_to_numpy(Wn), 'high', True)
+ w, h = freqs(b, a)
+ assert np.all(-rp - 0.1 < dB(h[wp <= w]))
+ assert np.all(dB(h[w <= ws]) < -rs + 0.1)
+
+ assert N == 4
+ assert math.isclose(Wn, 700.0, rel_tol=1e-15)
+ assert array_namespace(Wn) == xp
+ assert cheb1ord(xp.asarray(1), 1.2, 1, 80, analog=True)[0] == 17
+
+ @xfail_xp_backends("torch", reason="accuracy issues")
+ def test_fs_param(self, xp):
+ wp = 4800
+ ws = 7200.
+ rp = 3
+ rs = 60
+ fs = 48000
+ N, Wn = cheb1ord(wp, xp.asarray(ws), rp, rs, False, fs=fs)
+ b, a = cheby1(N, rp, _xp_copy_to_numpy(Wn), 'low', False, fs=fs)
+ w, h = freqz(b, a, fs=fs)
+ assert np.all(-rp - 0.1 < dB(h[w <= wp]))
+ assert np.all(dB(h[ws <= w]) < -rs + 0.1)
+
+ assert N == 8
+ assert math.isclose(Wn, 4800.0, rel_tol=1e-15)
+ assert array_namespace(Wn) == xp
+
+ def test_invalid_input(self):
+ with pytest.raises(ValueError) as exc_info:
+ cheb1ord(0.2, 0.3, 3, 2)
+ assert "gpass should be smaller than gstop" in str(exc_info.value)
+
+ with pytest.raises(ValueError) as exc_info:
+ cheb1ord(0.2, 0.3, -1, 2)
+ assert "gpass should be larger than 0.0" in str(exc_info.value)
+
+ with pytest.raises(ValueError) as exc_info:
+ cheb1ord(0.2, 0.3, 1, -2)
+ assert "gstop should be larger than 0.0" in str(exc_info.value)
+
+ def test_ellip_cheb1(self):
+ # The purpose of the test is to compare to some known output from past
+ # scipy versions. The values to compare to are generated with scipy
+ # 1.9.1 (there is nothing special about this particular version though)
+ n, wn = cheb1ord([0.1, 0.6], [0.2, 0.5], 3, 60)
+ assert n == 7
+
+ n2, w2 = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60)
+ assert not (wn == w2).all()
+
+ def test_fs_validation(self):
+ wp = 0.2
+ ws = 0.3
+ rp = 3
+ rs = 60
+
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ cheb1ord(wp, ws, rp, rs, False, fs=np.array([10, 20]))
+
+
+@make_xp_test_case(cheb2ord)
+@pytest.mark.skipif(DEFAULT_F32, reason="XXX needs figuring out")
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+class TestCheb2ord:
+
+ def test_lowpass(self, xp):
+ wp = 0.2
+ ws = 0.3
+ rp = 3
+ rs = 60
+ N, Wn = cheb2ord(wp, xp.asarray(ws), rp, rs, False)
+ b, a = cheby2(N, rs, _xp_copy_to_numpy(Wn), 'lp', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[w <= wp]))
+ assert np.all(dB(h[ws <= w]) < -rs + 0.1)
+
+ assert N == 8
+ xp_assert_close(Wn, xp.asarray(0.28647639976553163), rtol=1e-15, check_0d=False)
+
+ def test_highpass(self, xp):
+ wp = 0.3
+ ws = 0.2
+ rp = 3
+ rs = 70
+ N, Wn = cheb2ord(wp, xp.asarray(ws), rp, rs, False)
+ b, a = cheby2(N, rs, _xp_copy_to_numpy(Wn), 'hp', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[wp <= w]))
+ assert np.all(dB(h[w <= ws]) < -rs + 0.1)
+
+ assert N == 9
+ xp_assert_close(Wn, xp.asarray(0.20697492182903282), rtol=1e-15, check_0d=False)
+
+ def test_bandpass(self, xp):
+ wp = [0.2, 0.5]
+ ws = [0.1, 0.6]
+ rp = 3
+ rs = 80
+ N, Wn = cheb2ord(xp.asarray(wp), xp.asarray(ws), rp, rs, False)
+ b, a = cheby2(N, rs, _xp_copy_to_numpy(Wn), 'bp', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])]))
+ assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1)
+
+ assert N == 9
+ xp_assert_close(Wn, xp.asarray([0.14876937565923479, 0.59748447842351482]),
+ rtol=1e-15)
+
+ @skip_xp_backends(
+ cpu_only=True, exceptions=["cupy"], reason="optimize.fminbound"
+ )
+ def test_bandstop(self, xp):
+ wp = [0.1, 0.6]
+ ws = [0.2, 0.5]
+ rp = 3
+ rs = 90
+ N, Wn = cheb2ord(xp.asarray(wp), xp.asarray(ws), rp, rs, False)
+ b, a = cheby2(N, rs, _xp_copy_to_numpy(Wn), 'bs', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)]))
+ assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1)
+
+ assert N == 10
+ xp_assert_close(Wn, xp.asarray([0.19926249974781743, 0.50125246585567362]),
+ rtol=1e-6)
+
+ def test_analog(self, xp):
+ wp = [20., 50]
+ ws = [10., 60]
+ rp = 3
+ rs = 80
+ N, Wn = cheb2ord(xp.asarray(wp), xp.asarray(ws), rp, rs, True)
+ b, a = cheby2(N, rs, _xp_copy_to_numpy(Wn), 'bp', True)
+ w, h = freqs(b, a)
+ assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])]))
+ assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1)
+
+ assert N == 11
+ xp_assert_close(Wn, xp.asarray([1.673740595370124e+01, 5.974641487254268e+01]),
+ rtol=1e-15)
+
+ def test_fs_param(self, xp):
+ wp = 150
+ ws = 100.
+ rp = 3
+ rs = 70
+ fs = 1000
+ N, Wn = cheb2ord(wp, xp.asarray(ws), rp, rs, False, fs=fs)
+ b, a = cheby2(N, rs, _xp_copy_to_numpy(Wn), 'hp', False, fs=fs)
+ w, h = freqz(b, a, fs=fs)
+ assert np.all(-rp - 0.1 < dB(h[wp <= w]))
+ assert np.all(dB(h[w <= ws]) < -rs + 0.1)
+
+ assert N == 9
+ assert math.isclose(Wn, 103.4874609145164, rel_tol=1e-15)
+ assert array_namespace(Wn) == xp
+
+ def test_invalid_input(self):
+ with pytest.raises(ValueError) as exc_info:
+ cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 2)
+ assert "gpass should be smaller than gstop" in str(exc_info.value)
+
+ with pytest.raises(ValueError) as exc_info:
+ cheb2ord([0.1, 0.6], [0.2, 0.5], -1, 2)
+ assert "gpass should be larger than 0.0" in str(exc_info.value)
+
+ with pytest.raises(ValueError) as exc_info:
+ cheb2ord([0.1, 0.6], [0.2, 0.5], 1, -2)
+ assert "gstop should be larger than 0.0" in str(exc_info.value)
+
+ def test_ellip_cheb2(self):
+ # The purpose of the test is to compare to some known output from past
+ # scipy versions. The values to compare to are generated with scipy
+ # 1.9.1 (there is nothing special about this particular version though)
+ n, wn = cheb2ord([0.1, 0.6], [0.2, 0.5], 3, 60)
+ assert n == 7
+
+ n1, w1 = cheb1ord([0.1, 0.6], [0.2, 0.5], 3, 60)
+ assert not (wn == w1).all()
+
+ def test_fs_validation(self):
+ wp = 0.2
+ ws = 0.3
+ rp = 3
+ rs = 60
+
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ cheb2ord(wp, ws, rp, rs, False, fs=np.array([10, 20]))
+
+
+@make_xp_test_case(ellipord)
+@pytest.mark.skipif(DEFAULT_F32, reason="XXX needs figuring out")
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+class TestEllipord:
+
+ def test_lowpass(self, xp):
+ wp = 0.2
+ ws = 0.3
+ rp = 3
+ rs = 60
+ N, Wn = ellipord(wp, xp.asarray(ws), rp, rs, False)
+ b, a = ellip(N, rp, rs, _xp_copy_to_numpy(Wn), 'lp', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[w <= wp]))
+ assert np.all(dB(h[ws <= w]) < -rs + 0.1)
+
+ assert N == 5
+ xp_assert_close(Wn, xp.asarray(0.2), rtol=1e-15, check_0d=False)
+
+ def test_lowpass_1000dB(self, xp):
+ # failed when ellipkm1 wasn't used in ellipord and ellipap
+ wp = 0.2
+ ws = 0.3
+ rp = 3
+ rs = 1000
+ N, Wn = ellipord(wp, xp.asarray(ws), rp, rs, False)
+ sos = ellip(N, rp, rs, _xp_copy_to_numpy(Wn), 'lp', False, output='sos')
+ w, h = freqz_sos(sos)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[w <= wp]))
+ assert np.all(dB(h[ws <= w]) < -rs + 0.1)
+ assert array_namespace(Wn) == xp
+
+ def test_highpass(self, xp):
+ wp = 0.3
+ ws = 0.2
+ rp = 3
+ rs = 70
+ N, Wn = ellipord(wp, xp.asarray(ws), rp, rs, False)
+ b, a = ellip(N, rp, rs, _xp_copy_to_numpy(Wn), 'hp', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[wp <= w]))
+ assert np.all(dB(h[w <= ws]) < -rs + 0.1)
+
+ assert N == 6
+ xp_assert_close(Wn, xp.asarray(0.3), rtol=1e-15, check_0d=False)
+ assert array_namespace(Wn) == xp
+
+ def test_bandpass(self, xp):
+ wp = [0.2, 0.5]
+ ws = [0.1, 0.6]
+ rp = 3
+ rs = 80
+ N, Wn = ellipord(xp.asarray(wp), xp.asarray(ws), rp, rs, False)
+ b, a = ellip(N, rp, rs, _xp_copy_to_numpy(Wn), 'bp', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[np.logical_and(wp[0] <= w, w <= wp[1])]))
+ assert np.all(dB(h[np.logical_or(w <= ws[0], ws[1] <= w)]) < -rs + 0.1)
+
+ assert N == 6
+ xp_assert_close(Wn, xp.asarray([0.2, 0.5]), rtol=1e-15)
+
+ @skip_xp_backends(
+ cpu_only=True, exceptions=["cupy"], reason="optimize.fminbound"
+ )
+ def test_bandstop(self, xp):
+ wp = [0.1, 0.6]
+ ws = [0.2, 0.5]
+ rp = 3
+ rs = 90
+ N, Wn = ellipord(xp.asarray(wp), xp.asarray(ws), rp, rs, False)
+ b, a = ellip(N, rp, rs, _xp_copy_to_numpy(Wn), 'bs', False)
+ w, h = freqz(b, a)
+ w /= np.pi
+ assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)]))
+ assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1)
+
+ assert N == 7
+ xp_assert_close(Wn, xp.asarray([0.14758232794342988, 0.6]), rtol=1e-5)
+
+ def test_analog(self, xp):
+ wp = [1000.0, 6000]
+ ws = [2000.0, 5000]
+ rp = 3
+ rs = 90
+ N, Wn = ellipord(xp.asarray(wp), xp.asarray(ws), rp, rs, True)
+ b, a = ellip(N, rp, rs, _xp_copy_to_numpy(Wn), 'bs', True)
+ w, h = freqs(b, a)
+ assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)]))
+ assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1)
+
+ assert N == 8
+ xp_assert_close(Wn, xp.asarray([1666.6666, 6000]))
+
+ assert ellipord(xp.asarray(1), 1.2, 1, 80, analog=True)[0] == 9
+
+ def test_fs_param(self, xp):
+ wp = [400.0, 2400]
+ ws = [800.0, 2000]
+ rp = 3
+ rs = 90
+ fs = 8000
+ N, Wn = ellipord(xp.asarray(wp), xp.asarray(ws), rp, rs, False, fs=fs)
+ b, a = ellip(N, rp, rs, _xp_copy_to_numpy(Wn), 'bs', False, fs=fs)
+ w, h = freqz(b, a, fs=fs)
+ assert np.all(-rp - 0.1 < dB(h[np.logical_or(w <= wp[0], wp[1] <= w)]))
+ assert np.all(dB(h[np.logical_and(ws[0] <= w, w <= ws[1])]) < -rs + 0.1)
+
+ assert N == 7
+ xp_assert_close(Wn, xp.asarray([590.3293117737195, 2400]), rtol=1e-5)
+
+ def test_invalid_input(self):
+ with pytest.raises(ValueError) as exc_info:
+ ellipord(0.2, 0.5, 3, 2)
+ assert "gpass should be smaller than gstop" in str(exc_info.value)
+
+ with pytest.raises(ValueError) as exc_info:
+ ellipord(0.2, 0.5, -1, 2)
+ assert "gpass should be larger than 0.0" in str(exc_info.value)
+
+ with pytest.raises(ValueError) as exc_info:
+ ellipord(0.2, 0.5, 1, -2)
+ assert "gstop should be larger than 0.0" in str(exc_info.value)
+
+ def test_ellip_butter(self, xp):
+ # The purpose of the test is to compare to some known output from past
+ # scipy versions. The values to compare to are generated with scipy
+ # 1.9.1 (there is nothing special about this particular version though)
+ n, Wn = ellipord(xp.asarray([0.1, 0.6]), xp.asarray([0.2, 0.5]), 3, 60)
+ assert array_namespace(Wn) == xp
+ assert n == 5
+
+ def test_fs_validation(self):
+ wp = 0.2
+ ws = 0.3
+ rp = 3
+ rs = 60
+
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ ellipord(wp, ws, rp, rs, False, fs=np.array([10, 20]))
+
+
+# Currently the filter functions tested below (bessel, butter, cheby1, cheby2,
+# and ellip) all return float64 (or complex128) output regardless of input
+# dtype. Therefore reference arrays in these tests are all given an explicit 64
+# bit dtype, because the output will not match the xp_default_dtype when the
+# default dtype is float32. Although the output arrays and all internal
+# calculations are in 64 bit precision, tolerances are still loosened for the
+# float32 case when results are impacted by reduced precision in the inputs.
+
+
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+@make_xp_test_case(bessel)
+class TestBessel:
+
+ def test_degenerate(self, xp):
+ for norm in ('delay', 'phase', 'mag'):
+ # 0-order filter is just a passthrough
+ b, a = bessel(0, xp.asarray(1), analog=True, norm=norm)
+ xp_assert_equal(b, xp.asarray([1.0], dtype=xp.float64))
+ xp_assert_equal(a, xp.asarray([1.0], dtype=xp.float64))
+
+ # 1-order filter is same for all types
+ b, a = bessel(1, xp.asarray(1.), analog=True, norm=norm)
+
+ xp_assert_close(b, xp.asarray([1.0], dtype=xp.float64), rtol=1e-15)
+ xp_assert_close(a, xp.asarray([1.0, 1], dtype=xp.float64), rtol=1e-15)
+
+ z, p, k = bessel(1, xp.asarray(0.3), analog=True, output='zpk', norm=norm)
+ xp_assert_equal(z, xp.asarray([], dtype=xp.float64))
+ xp_assert_close(
+ p, xp.asarray([-0.3+0j], dtype=xp.complex128),
+ rtol=1e-14 if not DEFAULT_F32 else 1e-7
+ )
+ assert math.isclose(
+ k, 0.3, rel_tol=1e-14 if not DEFAULT_F32 else 1e-6
+ )
+
+ @pytest.mark.xfail(reason="Failing in mypy workflow - see gh-23902")
+ def test_high_order(self, xp):
+ # high even order, 'phase'
+ z, p, k = bessel(24, xp.asarray(100), analog=True, output='zpk')
+ z2 = xp.asarray([], dtype=xp.float64)
+ p2 = [
+ -9.055312334014323e+01 + 4.844005815403969e+00j,
+ -8.983105162681878e+01 + 1.454056170018573e+01j,
+ -8.837357994162065e+01 + 2.426335240122282e+01j,
+ -8.615278316179575e+01 + 3.403202098404543e+01j,
+ -8.312326467067703e+01 + 4.386985940217900e+01j,
+ -7.921695461084202e+01 + 5.380628489700191e+01j,
+ -7.433392285433246e+01 + 6.388084216250878e+01j,
+ -6.832565803501586e+01 + 7.415032695116071e+01j,
+ -6.096221567378025e+01 + 8.470292433074425e+01j,
+ -5.185914574820616e+01 + 9.569048385258847e+01j,
+ -4.027853855197555e+01 + 1.074195196518679e+02j,
+ -2.433481337524861e+01 + 1.207298683731973e+02j,
+ ]
+
+ p2 = np.union1d(p2, np.conj(p2))
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 9.999999999999989e+47
+ xp_assert_equal(z, z2)
+ xp_assert_close(_sort_cmplx(p, xp=xp),
+ _sort_cmplx(p2, xp=xp))
+ assert math.isclose(k, k2, rel_tol=1e-14)
+
+ # high odd order, 'phase'
+ z, p, k = bessel(23, xp.asarray(1000.), analog=True, output='zpk')
+ z2 = xp.asarray([], dtype=xp.float64)
+ p2 = [
+ -2.497697202208956e+02 + 1.202813187870698e+03j,
+ -4.126986617510172e+02 + 1.065328794475509e+03j,
+ -5.304922463809596e+02 + 9.439760364018479e+02j,
+ -9.027564978975828e+02 + 1.010534334242318e+02j,
+ -8.909283244406079e+02 + 2.023024699647598e+02j,
+ -8.709469394347836e+02 + 3.039581994804637e+02j,
+ -8.423805948131370e+02 + 4.062657947488952e+02j,
+ -8.045561642249877e+02 + 5.095305912401127e+02j,
+ -7.564660146766259e+02 + 6.141594859516342e+02j,
+ -6.965966033906477e+02 + 7.207341374730186e+02j,
+ -6.225903228776276e+02 + 8.301558302815096e+02j,
+ -9.066732476324988e+02]
+ p2 = np.union1d(p2, np.conj(p2))
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 9.999999999999983e+68
+ xp_assert_equal(z, z2)
+ xp_assert_close(_sort_cmplx(p, xp=xp),
+ _sort_cmplx(p2, xp=xp))
+ assert math.isclose(k, k2, rel_tol=1e-14)
+
+ # high even order, 'delay' (Orchard 1965 "The Roots of the
+ # Maximally Flat-Delay Polynomials" Table 1)
+ z, p, k = bessel(31, xp.asarray(1.), analog=True, output='zpk', norm='delay')
+ p2 = [-20.876706,
+ -20.826543 + 1.735732j,
+ -20.675502 + 3.473320j,
+ -20.421895 + 5.214702j,
+ -20.062802 + 6.961982j,
+ -19.593895 + 8.717546j,
+ -19.009148 + 10.484195j,
+ -18.300400 + 12.265351j,
+ -17.456663 + 14.065350j,
+ -16.463032 + 15.889910j,
+ -15.298849 + 17.746914j,
+ -13.934466 + 19.647827j,
+ -12.324914 + 21.610519j,
+ -10.395893 + 23.665701j,
+ - 8.005600 + 25.875019j,
+ - 4.792045 + 28.406037j,
+ ]
+ p2 = np.union1d(p2, np.conj(p2))
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ xp_assert_close(_sort_cmplx(p, xp=xp),
+ _sort_cmplx(p2, xp=xp))
+
+ # high odd order, 'delay'
+ z, p, k = bessel(30, xp.asarray(1.), analog=True, output='zpk', norm='delay')
+ p2 = [-20.201029 + 0.867750j,
+ -20.097257 + 2.604235j,
+ -19.888485 + 4.343721j,
+ -19.572188 + 6.088363j,
+ -19.144380 + 7.840570j,
+ -18.599342 + 9.603147j,
+ -17.929195 + 11.379494j,
+ -17.123228 + 13.173901j,
+ -16.166808 + 14.992008j,
+ -15.039580 + 16.841580j,
+ -13.712245 + 18.733902j,
+ -12.140295 + 20.686563j,
+ -10.250119 + 22.729808j,
+ - 7.901170 + 24.924391j,
+ - 4.734679 + 27.435615j,
+ ]
+ p2 = np.union1d(p2, np.conj(p2))
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ xp_assert_close(_sort_cmplx(p, xp=xp),
+ _sort_cmplx(p2, xp=xp))
+
+ def test_refs(self, xp):
+ # Compare to http://www.crbond.com/papers/bsf2.pdf
+ # "Delay Normalized Bessel Polynomial Coefficients"
+ bond_b = xp.asarray([10395.0], dtype=xp.float64)
+ bond_a = xp.asarray([1.0, 21, 210, 1260, 4725, 10395, 10395], dtype=xp.float64)
+ b, a = bessel(6, xp.asarray(1.0), norm='delay', analog=True)
+ xp_assert_close(b, bond_b)
+ xp_assert_close(a, bond_a)
+
+ # "Delay Normalized Bessel Pole Locations"
+ bond_poles = {
+ 1: [-1.0000000000],
+ 2: [-1.5000000000 + 0.8660254038j],
+ 3: [-1.8389073227 + 1.7543809598j, -2.3221853546],
+ 4: [-2.1037893972 + 2.6574180419j, -2.8962106028 + 0.8672341289j],
+ 5: [-2.3246743032 + 3.5710229203j, -3.3519563992 + 1.7426614162j,
+ -3.6467385953],
+ 6: [-2.5159322478 + 4.4926729537j, -3.7357083563 + 2.6262723114j,
+ -4.2483593959 + 0.8675096732j],
+ 7: [-2.6856768789 + 5.4206941307j, -4.0701391636 + 3.5171740477j,
+ -4.7582905282 + 1.7392860611j, -4.9717868585],
+ 8: [-2.8389839489 + 6.3539112986j, -4.3682892172 + 4.4144425005j,
+ -5.2048407906 + 2.6161751526j, -5.5878860433 + 0.8676144454j],
+ 9: [-2.9792607982 + 7.2914636883j, -4.6384398872 + 5.3172716754j,
+ -5.6044218195 + 3.4981569179j, -6.1293679043 + 1.7378483835j,
+ -6.2970191817],
+ 10: [-3.1089162336 + 8.2326994591j, -4.8862195669 + 6.2249854825j,
+ -5.9675283286 + 4.3849471889j, -6.6152909655 + 2.6115679208j,
+ -6.9220449054 + 0.8676651955j]
+ }
+
+ for N in range(1, 11):
+ p1 = np.sort(bond_poles[N])
+ z, p, k = besselap(N, 'delay', xp=xp)
+ assert array_namespace(z) == array_namespace(p) == xp
+ p2 = np.sort(np.concatenate(_cplxreal(_xp_copy_to_numpy(p))))
+ assert_array_almost_equal(xp.asarray(p2), xp.asarray(p1), decimal=10)
+
+ # "Frequency Normalized Bessel Pole Locations"
+ bond_poles = {
+ 1: [-1.0000000000],
+ 2: [-1.1016013306 + 0.6360098248j],
+ 3: [-1.0474091610 + 0.9992644363j, -1.3226757999],
+ 4: [-0.9952087644 + 1.2571057395j, -1.3700678306 + 0.4102497175j],
+ 5: [-0.9576765486 + 1.4711243207j, -1.3808773259 + 0.7179095876j,
+ -1.5023162714],
+ 6: [-0.9306565229 + 1.6618632689j, -1.3818580976 + 0.9714718907j,
+ -1.5714904036 + 0.3208963742j],
+ 7: [-0.9098677806 + 1.8364513530j, -1.3789032168 + 1.1915667778j,
+ -1.6120387662 + 0.5892445069j, -1.6843681793],
+ 8: [-0.8928697188 + 1.9983258436j, -1.3738412176 + 1.3883565759j,
+ -1.6369394181 + 0.8227956251j, -1.7574084004 + 0.2728675751j],
+ 9: [-0.8783992762 + 2.1498005243j, -1.3675883098 + 1.5677337122j,
+ -1.6523964846 + 1.0313895670j, -1.8071705350 + 0.5123837306j,
+ -1.8566005012],
+ 10: [-0.8657569017 + 2.2926048310j, -1.3606922784 + 1.7335057427j,
+ -1.6618102414 + 1.2211002186j, -1.8421962445 + 0.7272575978j,
+ -1.9276196914 + 0.2416234710j]
+ }
+
+ for N in range(1, 11):
+ p1 = np.sort(bond_poles[N])
+ z, p, k = besselap(N, 'mag', xp=xp)
+ assert array_namespace(z) == array_namespace(p) == xp
+ p2 = np.sort(np.concatenate(_cplxreal(_xp_copy_to_numpy(p))))
+ assert_array_almost_equal(xp.asarray(p2), xp.asarray(p1), decimal=10)
+
+ # Compare to https://www.ranecommercial.com/legacy/note147.html
+ # "Table 1 - Bessel Crossovers of Second, Third, and Fourth-Order"
+ a = xp.asarray([1, 1, 1/3], dtype=xp.float64)
+ b2, a2 = bessel(2, xp.asarray(1.), norm='delay', analog=True)
+ xp_assert_close(a2/b2, xp.flip(a))
+
+ a = xp.asarray([1, 1, 2/5, 1/15], dtype=xp.float64)
+ b2, a2 = bessel(3, xp.asarray(1.), norm='delay', analog=True)
+ xp_assert_close(a2/b2, xp.flip(a))
+
+ a = xp.asarray([1, 1, 9/21, 2/21, 1/105], dtype=xp.float64)
+ b2, a2 = bessel(4, xp.asarray(1.), norm='delay', analog=True)
+ xp_assert_close(a2/b2, xp.flip(a))
+
+ a = xp.asarray([1, math.sqrt(3), 1], dtype=xp.float64)
+ b2, a2 = bessel(2, xp.asarray(1.), norm='phase', analog=True)
+ xp_assert_close(a2/b2, xp.flip(a))
+
+ # TODO: Why so inaccurate? Is reference flawed?
+ a = xp.asarray([1, 2.481, 2.463, 1.018], dtype=xp.float64)
+ b2, a2 = bessel(3, xp.asarray(1.), norm='phase', analog=True)
+ assert_array_almost_equal(a2/b2, xp.flip(a), decimal=1)
+
+ # TODO: Why so inaccurate? Is reference flawed?
+ a = xp.asarray([1, 3.240, 4.5, 3.240, 1.050], dtype=xp.float64)
+ b2, a2 = bessel(4, xp.asarray(1.), norm='phase', analog=True)
+ assert_array_almost_equal(a2/b2, xp.flip(a), decimal=1)
+
+ # Table of -3 dB factors:
+ N, scale = 2, xp.asarray([1.272, 1.272], dtype=xp.complex128)
+ scale2 = besselap(N, 'mag', xp=xp)[1] / besselap(N, 'phase', xp=xp)[1]
+ assert_array_almost_equal(scale2, scale, decimal=3)
+
+ # TODO: Why so inaccurate? Is reference flawed?
+ N, scale = 3, xp.asarray([1.413, 1.413, 1.413], dtype=xp.complex128)
+ scale2 = besselap(N, 'mag', xp=xp)[1] / besselap(N, 'phase', xp=xp)[1]
+ assert_array_almost_equal(scale2, scale, decimal=2)
+
+ # TODO: Why so inaccurate? Is reference flawed?
+ N, scale = 4, xp.asarray([1.533]*4, dtype=xp.complex128)
+ scale2 = besselap(N, 'mag', xp=xp)[1] / besselap(N, 'phase', xp=xp)[1]
+ assert_array_almost_equal(scale2, scale, decimal=1)
+
+ @pytest.mark.xfail(reason="Failing in mypy workflow - see gh-23902")
+ def test_hardcoded(self, xp):
+ # Compare to values from original hardcoded implementation
+ originals = {
+ 0: [],
+ 1: [-1],
+ 2: [-.8660254037844386467637229 + .4999999999999999999999996j],
+ 3: [-.9416000265332067855971980,
+ -.7456403858480766441810907 + .7113666249728352680992154j],
+ 4: [-.6572111716718829545787788 + .8301614350048733772399715j,
+ -.9047587967882449459642624 + .2709187330038746636700926j],
+ 5: [-.9264420773877602247196260,
+ -.8515536193688395541722677 + .4427174639443327209850002j,
+ -.5905759446119191779319432 + .9072067564574549539291747j],
+ 6: [-.9093906830472271808050953 + .1856964396793046769246397j,
+ -.7996541858328288520243325 + .5621717346937317988594118j,
+ -.5385526816693109683073792 + .9616876881954277199245657j],
+ 7: [-.9194871556490290014311619,
+ -.8800029341523374639772340 + .3216652762307739398381830j,
+ -.7527355434093214462291616 + .6504696305522550699212995j,
+ -.4966917256672316755024763 + 1.002508508454420401230220j],
+ 8: [-.9096831546652910216327629 + .1412437976671422927888150j,
+ -.8473250802359334320103023 + .4259017538272934994996429j,
+ -.7111381808485399250796172 + .7186517314108401705762571j,
+ -.4621740412532122027072175 + 1.034388681126901058116589j],
+ 9: [-.9154957797499037686769223,
+ -.8911217017079759323183848 + .2526580934582164192308115j,
+ -.8148021112269012975514135 + .5085815689631499483745341j,
+ -.6743622686854761980403401 + .7730546212691183706919682j,
+ -.4331415561553618854685942 + 1.060073670135929666774323j],
+ 10: [-.9091347320900502436826431 + .1139583137335511169927714j,
+ -.8688459641284764527921864 + .3430008233766309973110589j,
+ -.7837694413101441082655890 + .5759147538499947070009852j,
+ -.6417513866988316136190854 + .8175836167191017226233947j,
+ -.4083220732868861566219785 + 1.081274842819124562037210j],
+ 11: [-.9129067244518981934637318,
+ -.8963656705721166099815744 + .2080480375071031919692341j,
+ -.8453044014712962954184557 + .4178696917801248292797448j,
+ -.7546938934722303128102142 + .6319150050721846494520941j,
+ -.6126871554915194054182909 + .8547813893314764631518509j,
+ -.3868149510055090879155425 + 1.099117466763120928733632j],
+ 12: [-.9084478234140682638817772 + 95506365213450398415258360e-27j,
+ -.8802534342016826507901575 + .2871779503524226723615457j,
+ -.8217296939939077285792834 + .4810212115100676440620548j,
+ -.7276681615395159454547013 + .6792961178764694160048987j,
+ -.5866369321861477207528215 + .8863772751320727026622149j,
+ -.3679640085526312839425808 + 1.114373575641546257595657j],
+ 13: [-.9110914665984182781070663,
+ -.8991314665475196220910718 + .1768342956161043620980863j,
+ -.8625094198260548711573628 + .3547413731172988997754038j,
+ -.7987460692470972510394686 + .5350752120696801938272504j,
+ -.7026234675721275653944062 + .7199611890171304131266374j,
+ -.5631559842430199266325818 + .9135900338325109684927731j,
+ -.3512792323389821669401925 + 1.127591548317705678613239j],
+ 14: [-.9077932138396487614720659 + 82196399419401501888968130e-27j,
+ -.8869506674916445312089167 + .2470079178765333183201435j,
+ -.8441199160909851197897667 + .4131653825102692595237260j,
+ -.7766591387063623897344648 + .5819170677377608590492434j,
+ -.6794256425119233117869491 + .7552857305042033418417492j,
+ -.5418766775112297376541293 + .9373043683516919569183099j,
+ -.3363868224902037330610040 + 1.139172297839859991370924j],
+ 15: [-.9097482363849064167228581,
+ -.9006981694176978324932918 + .1537681197278439351298882j,
+ -.8731264620834984978337843 + .3082352470564267657715883j,
+ -.8256631452587146506294553 + .4642348752734325631275134j,
+ -.7556027168970728127850416 + .6229396358758267198938604j,
+ -.6579196593110998676999362 + .7862895503722515897065645j,
+ -.5224954069658330616875186 + .9581787261092526478889345j,
+ -.3229963059766444287113517 + 1.149416154583629539665297j],
+ 16: [-.9072099595087001356491337 + 72142113041117326028823950e-27j,
+ -.8911723070323647674780132 + .2167089659900576449410059j,
+ -.8584264231521330481755780 + .3621697271802065647661080j,
+ -.8074790293236003885306146 + .5092933751171800179676218j,
+ -.7356166304713115980927279 + .6591950877860393745845254j,
+ -.6379502514039066715773828 + .8137453537108761895522580j,
+ -.5047606444424766743309967 + .9767137477799090692947061j,
+ -.3108782755645387813283867 + 1.158552841199330479412225j],
+ 17: [-.9087141161336397432860029,
+ -.9016273850787285964692844 + .1360267995173024591237303j,
+ -.8801100704438627158492165 + .2725347156478803885651973j,
+ -.8433414495836129204455491 + .4100759282910021624185986j,
+ -.7897644147799708220288138 + .5493724405281088674296232j,
+ -.7166893842372349049842743 + .6914936286393609433305754j,
+ -.6193710717342144521602448 + .8382497252826992979368621j,
+ -.4884629337672704194973683 + .9932971956316781632345466j,
+ -.2998489459990082015466971 + 1.166761272925668786676672j],
+ 18: [-.9067004324162775554189031 + 64279241063930693839360680e-27j,
+ -.8939764278132455733032155 + .1930374640894758606940586j,
+ -.8681095503628830078317207 + .3224204925163257604931634j,
+ -.8281885016242836608829018 + .4529385697815916950149364j,
+ -.7726285030739558780127746 + .5852778162086640620016316j,
+ -.6987821445005273020051878 + .7204696509726630531663123j,
+ -.6020482668090644386627299 + .8602708961893664447167418j,
+ -.4734268069916151511140032 + 1.008234300314801077034158j,
+ -.2897592029880489845789953 + 1.174183010600059128532230j],
+ 19: [-.9078934217899404528985092,
+ -.9021937639390660668922536 + .1219568381872026517578164j,
+ -.8849290585034385274001112 + .2442590757549818229026280j,
+ -.8555768765618421591093993 + .3672925896399872304734923j,
+ -.8131725551578197705476160 + .4915365035562459055630005j,
+ -.7561260971541629355231897 + .6176483917970178919174173j,
+ -.6818424412912442033411634 + .7466272357947761283262338j,
+ -.5858613321217832644813602 + .8801817131014566284786759j,
+ -.4595043449730988600785456 + 1.021768776912671221830298j,
+ -.2804866851439370027628724 + 1.180931628453291873626003j],
+ 20: [-.9062570115576771146523497 + 57961780277849516990208850e-27j,
+ -.8959150941925768608568248 + .1740317175918705058595844j,
+ -.8749560316673332850673214 + .2905559296567908031706902j,
+ -.8427907479956670633544106 + .4078917326291934082132821j,
+ -.7984251191290606875799876 + .5264942388817132427317659j,
+ -.7402780309646768991232610 + .6469975237605228320268752j,
+ -.6658120544829934193890626 + .7703721701100763015154510j,
+ -.5707026806915714094398061 + .8982829066468255593407161j,
+ -.4465700698205149555701841 + 1.034097702560842962315411j,
+ -.2719299580251652601727704 + 1.187099379810885886139638j],
+ 21: [-.9072262653142957028884077,
+ -.9025428073192696303995083 + .1105252572789856480992275j,
+ -.8883808106664449854431605 + .2213069215084350419975358j,
+ -.8643915813643204553970169 + .3326258512522187083009453j,
+ -.8299435470674444100273463 + .4448177739407956609694059j,
+ -.7840287980408341576100581 + .5583186348022854707564856j,
+ -.7250839687106612822281339 + .6737426063024382240549898j,
+ -.6506315378609463397807996 + .7920349342629491368548074j,
+ -.5564766488918562465935297 + .9148198405846724121600860j,
+ -.4345168906815271799687308 + 1.045382255856986531461592j,
+ -.2640041595834031147954813 + 1.192762031948052470183960j],
+ 22: [-.9058702269930872551848625 + 52774908289999045189007100e-27j,
+ -.8972983138153530955952835 + .1584351912289865608659759j,
+ -.8799661455640176154025352 + .2644363039201535049656450j,
+ -.8534754036851687233084587 + .3710389319482319823405321j,
+ -.8171682088462720394344996 + .4785619492202780899653575j,
+ -.7700332930556816872932937 + .5874255426351153211965601j,
+ -.7105305456418785989070935 + .6982266265924524000098548j,
+ -.6362427683267827226840153 + .8118875040246347267248508j,
+ -.5430983056306302779658129 + .9299947824439872998916657j,
+ -.4232528745642628461715044 + 1.055755605227545931204656j,
+ -.2566376987939318038016012 + 1.197982433555213008346532j],
+ 23: [-.9066732476324988168207439,
+ -.9027564979912504609412993 + .1010534335314045013252480j,
+ -.8909283242471251458653994 + .2023024699381223418195228j,
+ -.8709469395587416239596874 + .3039581993950041588888925j,
+ -.8423805948021127057054288 + .4062657948237602726779246j,
+ -.8045561642053176205623187 + .5095305912227258268309528j,
+ -.7564660146829880581478138 + .6141594859476032127216463j,
+ -.6965966033912705387505040 + .7207341374753046970247055j,
+ -.6225903228771341778273152 + .8301558302812980678845563j,
+ -.5304922463810191698502226 + .9439760364018300083750242j,
+ -.4126986617510148836149955 + 1.065328794475513585531053j,
+ -.2497697202208956030229911 + 1.202813187870697831365338j],
+ 24: [-.9055312363372773709269407 + 48440066540478700874836350e-27j,
+ -.8983105104397872954053307 + .1454056133873610120105857j,
+ -.8837358034555706623131950 + .2426335234401383076544239j,
+ -.8615278304016353651120610 + .3403202112618624773397257j,
+ -.8312326466813240652679563 + .4386985933597305434577492j,
+ -.7921695462343492518845446 + .5380628490968016700338001j,
+ -.7433392285088529449175873 + .6388084216222567930378296j,
+ -.6832565803536521302816011 + .7415032695091650806797753j,
+ -.6096221567378335562589532 + .8470292433077202380020454j,
+ -.5185914574820317343536707 + .9569048385259054576937721j,
+ -.4027853855197518014786978 + 1.074195196518674765143729j,
+ -.2433481337524869675825448 + 1.207298683731972524975429j],
+ 25: [-.9062073871811708652496104,
+ -.9028833390228020537142561 + 93077131185102967450643820e-27j,
+ -.8928551459883548836774529 + .1863068969804300712287138j,
+ -.8759497989677857803656239 + .2798521321771408719327250j,
+ -.8518616886554019782346493 + .3738977875907595009446142j,
+ -.8201226043936880253962552 + .4686668574656966589020580j,
+ -.7800496278186497225905443 + .5644441210349710332887354j,
+ -.7306549271849967721596735 + .6616149647357748681460822j,
+ -.6704827128029559528610523 + .7607348858167839877987008j,
+ -.5972898661335557242320528 + .8626676330388028512598538j,
+ -.5073362861078468845461362 + .9689006305344868494672405j,
+ -.3934529878191079606023847 + 1.082433927173831581956863j,
+ -.2373280669322028974199184 + 1.211476658382565356579418j],
+ }
+ for N in originals:
+ p1 = xp.asarray(
+ np.union1d(originals[N], np.conj(originals[N])),
+ dtype=xp.complex128
+ )
+ p2 = besselap(N, xp=xp)[1]
+ xp_assert_close(_sort_cmplx(p2, xp=xp),
+ _sort_cmplx(p1, xp=xp), rtol=1e-14)
+
+ def test_norm_phase(self, xp):
+ # Test some orders and frequencies and see that they have the right
+ # phase at w0
+ if is_torch(xp) and DEFAULT_F32:
+ pytest.xfail(reason="inaccurate on torch with float32")
+ for N in (1, 2, 3, 4, 5, 51, 72):
+ for w0 in (1, 100):
+ b, a = bessel(N, xp.asarray(w0), analog=True, norm='phase')
+ assert array_namespace(b) == array_namespace(a) == xp
+ w = np.linspace(0, w0, 100)
+ w, h = freqs(_xp_copy_to_numpy(b), _xp_copy_to_numpy(a), w)
+ phase = np.unwrap(np.angle(h))
+ xp_assert_close(
+ xp.asarray(phase[[0, -1]], dtype=xp.float64),
+ xp.asarray([0, -N*xp.pi/4], dtype=xp.float64), rtol=1e-1
+ )
+
+ def test_norm_mag(self, xp):
+ # Test some orders and frequencies and see that they have the right
+ # mag at w0
+ if DEFAULT_F32 and is_torch(xp):
+ pytest.skip(reason="overflow occurs with float32 on torch")
+ for N in (1, 2, 3, 4, 5, 51, 72):
+ for w0 in (1, 100):
+ b, a = bessel(N, xp.asarray(w0), analog=True, norm='mag')
+ assert array_namespace(b) == array_namespace(a) == xp
+ w = [0.0, w0]
+ w, h = freqs(_xp_copy_to_numpy(b), _xp_copy_to_numpy(a), w)
+ mag = np.abs(h)
+ xp_assert_close(
+ xp.asarray(mag), xp.asarray([1, 1/math.sqrt(2)], dtype=xp.float64)
+ )
+
+ def test_norm_delay(self, xp):
+ # Test some orders and frequencies and see that they have the right
+ # delay at DC
+ if DEFAULT_F32 and is_torch(xp):
+ pytest.skip(reason="overflow occurs with float32 on torch")
+ for N in (1, 2, 3, 4, 5, 51, 72):
+ for w0 in (1, 100):
+ b, a = bessel(N, xp.asarray(w0), analog=True, norm='delay')
+ w = np.linspace(0, 10*w0, 1000)
+ w, h = freqs(_xp_copy_to_numpy(b), _xp_copy_to_numpy(a), w)
+ unwr_h = np.unwrap(np.angle(h))
+ delay = -np.diff(unwr_h) / np.diff(w)
+ assert math.isclose(delay[0], 1/w0, rel_tol=1e-4)
+
+ def test_norm_factor(self):
+ mpmath_values = {
+ 1: 1.0, 2: 1.361654128716130520, 3: 1.755672368681210649,
+ 4: 2.113917674904215843, 5: 2.427410702152628137,
+ 6: 2.703395061202921876, 7: 2.951722147038722771,
+ 8: 3.179617237510651330, 9: 3.391693138911660101,
+ 10: 3.590980594569163482, 11: 3.779607416439620092,
+ 12: 3.959150821144285315, 13: 4.130825499383535980,
+ 14: 4.295593409533637564, 15: 4.454233021624377494,
+ 16: 4.607385465472647917, 17: 4.755586548961147727,
+ 18: 4.899289677284488007, 19: 5.038882681488207605,
+ 20: 5.174700441742707423, 21: 5.307034531360917274,
+ 22: 5.436140703250035999, 23: 5.562244783787878196,
+ 24: 5.685547371295963521, 25: 5.806227623775418541,
+ 50: 8.268963160013226298, 51: 8.352374541546012058,
+ }
+ for N in mpmath_values:
+ z, p, k = besselap(N, 'delay')
+ xp_assert_close(_norm_factor(p, k), mpmath_values[N], rtol=1e-13)
+
+ def test_bessel_poly(self):
+ xp_assert_equal(_bessel_poly(5), [945, 945, 420, 105, 15, 1])
+ xp_assert_equal(_bessel_poly(4, True), [1, 10, 45, 105, 105])
+
+ def test_bessel_zeros(self):
+ xp_assert_equal(_bessel_zeros(0), [])
+
+ def test_invalid(self):
+ assert_raises(ValueError, besselap, 5, 'nonsense')
+ assert_raises(ValueError, besselap, -5)
+ assert_raises(ValueError, besselap, 3.2)
+ assert_raises(ValueError, _bessel_poly, -3)
+ assert_raises(ValueError, _bessel_poly, 3.3)
+
+ @pytest.mark.fail_slow(10)
+ def test_fs_param(self):
+ for norm in ('phase', 'mag', 'delay'):
+ for fs in (900, 900.1, 1234.567):
+ for N in (0, 1, 2, 3, 10):
+ for fc in (100, 100.1, 432.12345):
+ for btype in ('lp', 'hp'):
+ ba1 = bessel(N, fc, btype, norm=norm, fs=fs)
+ ba2 = bessel(N, fc/(fs/2), btype, norm=norm)
+ for ba1_, ba2_ in zip(ba1, ba2):
+ xp_assert_close(ba1_, ba2_)
+ for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)):
+ for btype in ('bp', 'bs'):
+ ba1 = bessel(N, fc, btype, norm=norm, fs=fs)
+ for seq in (list, tuple, array):
+ fcnorm = seq([f/(fs/2) for f in fc])
+ ba2 = bessel(N, fcnorm, btype, norm=norm)
+ for ba1_, ba2_ in zip(ba1, ba2):
+ xp_assert_close(ba1_, ba2_)
+
+
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+@make_xp_test_case(butter)
+class TestButter:
+
+ def test_degenerate(self, xp):
+ # 0-order filter is just a passthrough
+ b, a = butter(0, xp.asarray(1), analog=True)
+ xp_assert_equal(b, xp.asarray([1.0], dtype=xp.float64))
+ xp_assert_equal(a, xp.asarray([1.0], dtype=xp.float64))
+
+ # 1-order filter is same for all types
+ b, a = butter(1, xp.asarray(1), analog=True)
+ assert_array_almost_equal(b, xp.asarray([1.0], dtype=xp.float64))
+ assert_array_almost_equal(a, xp.asarray([1.0, 1.0], dtype=xp.float64))
+
+ z, p, k = butter(1, xp.asarray(0.3), output='zpk')
+ xp_assert_equal(z, xp.asarray([-1.0], dtype=xp.float64))
+ xp_assert_close(
+ p,
+ xp.asarray([3.249196962329063e-01 + 0j], dtype=xp.complex128),
+ rtol=1e-14 if not DEFAULT_F32 else 1e-7
+ )
+ assert math.isclose(
+ k, 3.375401518835469e-01, rel_tol=1e-14 if not DEFAULT_F32 else 1e-7
+ )
+
+ def test_basic(self, xp):
+ # analog s-plane
+ for N in range(25):
+ wn = 0.01
+ z, p, k = butter(N, xp.asarray(wn), 'low', analog=True, output='zpk')
+ assert_array_almost_equal(z, xp.asarray([], dtype=xp.float64))
+ assert p.shape[0] == N
+ # All poles should be at distance wn from origin
+ assert_array_almost_equal(xp.abs(p), xp.asarray(wn, dtype=xp.float64))
+ assert all(xp.real(p) <= 0) # No poles in right half of S-plane
+ assert math.isclose(k, wn**N, rel_tol=1e-9 if not DEFAULT_F32 else 1e-6)
+
+ # digital z-plane
+ for N in range(25):
+ wn = 0.01
+ z, p, k = butter(N, xp.asarray(wn), 'high', analog=False, output='zpk')
+ xp_assert_equal(z, xp.ones(N, dtype=xp.float64)) # All zeros exactly at DC
+ assert xp.all(xp.abs(p) <= 1) # No poles outside unit circle
+
+ b1, a1 = butter(2, xp.asarray(1), analog=True)
+ assert_array_almost_equal(b1, xp.asarray([1.0], dtype=xp.float64))
+ assert_array_almost_equal(
+ a1, xp.asarray([1, math.sqrt(2), 1], dtype=xp.float64)
+ )
+
+ b2, a2 = butter(5, xp.asarray(1.), analog=True)
+ assert_array_almost_equal(b2, xp.asarray([1], dtype=xp.float64))
+ assert_array_almost_equal(
+ a2, xp.asarray([1, 3.2361, 5.2361,
+ 5.2361, 3.2361, 1], dtype=xp.float64),
+ decimal=4
+ )
+
+ b3, a3 = butter(10, xp.asarray(1.0), analog=True)
+ assert_array_almost_equal(b3, xp.asarray([1.0], dtype=xp.float64))
+ assert_array_almost_equal(
+ a3, xp.asarray([1, 6.3925, 20.4317, 42.8021, 64.8824,
+ 74.2334, 64.8824, 42.8021, 20.4317,
+ 6.3925, 1], dtype=xp.float64),
+ decimal=4
+ )
+
+ b2, a2 = butter(19, xp.asarray(1.0441379169150726), analog=True)
+ assert_array_almost_equal(
+ b2, xp.asarray([2.2720], dtype=xp.float64), decimal=4
+ )
+ assert_array_almost_equal(
+ a2, 1.0e+004 * xp.asarray([
+ 0.0001, 0.0013, 0.0080, 0.0335, 0.1045, 0.2570,
+ 0.5164, 0.8669, 1.2338, 1.5010, 1.5672, 1.4044,
+ 1.0759, 0.6986, 0.3791, 0.1681, 0.0588, 0.0153,
+ 0.0026, 0.0002], dtype=xp.float64),
+ decimal=0
+ )
+
+ b, a = butter(5, xp.asarray(0.4))
+ assert_array_almost_equal(
+ b, xp.asarray([0.0219, 0.1097, 0.2194,
+ 0.2194, 0.1097, 0.0219], dtype=xp.float64),
+ decimal=4
+ )
+ assert_array_almost_equal(
+ a, xp.asarray([1.0000, -0.9853, 0.9738,
+ -0.3864, 0.1112, -0.0113], dtype=xp.float64),
+ decimal=4
+ )
+
+ def test_highpass(self, xp):
+ # highpass, high even order
+ z, p, k = butter(28, xp.asarray(0.43), 'high', output='zpk')
+ z2 = xp.ones(28, dtype=xp.float64)
+ p2 = [
+ 2.068257195514592e-01 + 9.238294351481734e-01j,
+ 2.068257195514592e-01 - 9.238294351481734e-01j,
+ 1.874933103892023e-01 + 8.269455076775277e-01j,
+ 1.874933103892023e-01 - 8.269455076775277e-01j,
+ 1.717435567330153e-01 + 7.383078571194629e-01j,
+ 1.717435567330153e-01 - 7.383078571194629e-01j,
+ 1.588266870755982e-01 + 6.564623730651094e-01j,
+ 1.588266870755982e-01 - 6.564623730651094e-01j,
+ 1.481881532502603e-01 + 5.802343458081779e-01j,
+ 1.481881532502603e-01 - 5.802343458081779e-01j,
+ 1.394122576319697e-01 + 5.086609000582009e-01j,
+ 1.394122576319697e-01 - 5.086609000582009e-01j,
+ 1.321840881809715e-01 + 4.409411734716436e-01j,
+ 1.321840881809715e-01 - 4.409411734716436e-01j,
+ 1.262633413354405e-01 + 3.763990035551881e-01j,
+ 1.262633413354405e-01 - 3.763990035551881e-01j,
+ 1.214660449478046e-01 + 3.144545234797277e-01j,
+ 1.214660449478046e-01 - 3.144545234797277e-01j,
+ 1.104868766650320e-01 + 2.771505404367791e-02j,
+ 1.104868766650320e-01 - 2.771505404367791e-02j,
+ 1.111768629525075e-01 + 8.331369153155753e-02j,
+ 1.111768629525075e-01 - 8.331369153155753e-02j,
+ 1.125740630842972e-01 + 1.394219509611784e-01j,
+ 1.125740630842972e-01 - 1.394219509611784e-01j,
+ 1.147138487992747e-01 + 1.963932363793666e-01j,
+ 1.147138487992747e-01 - 1.963932363793666e-01j,
+ 1.176516491045901e-01 + 2.546021573417188e-01j,
+ 1.176516491045901e-01 - 2.546021573417188e-01j,
+ ]
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 1.446671081817286e-06
+ xp_assert_equal(z, z2)
+ xp_assert_close(_sort_cmplx(p, xp), _sort_cmplx(p2, xp), rtol=1e-7)
+ assert math.isclose(k, k2, rel_tol=1e-10 if not DEFAULT_F32 else 1e-6)
+
+ # highpass, high odd order
+ z, p, k = butter(27, xp.asarray(0.56), 'high', output='zpk')
+ z2 = xp.ones(27, dtype=xp.float64)
+ p2 = [
+ -1.772572785680147e-01 + 9.276431102995948e-01j,
+ -1.772572785680147e-01 - 9.276431102995948e-01j,
+ -1.600766565322114e-01 + 8.264026279893268e-01j,
+ -1.600766565322114e-01 - 8.264026279893268e-01j,
+ -1.461948419016121e-01 + 7.341841939120078e-01j,
+ -1.461948419016121e-01 - 7.341841939120078e-01j,
+ -1.348975284762046e-01 + 6.493235066053785e-01j,
+ -1.348975284762046e-01 - 6.493235066053785e-01j,
+ -1.256628210712206e-01 + 5.704921366889227e-01j,
+ -1.256628210712206e-01 - 5.704921366889227e-01j,
+ -1.181038235962314e-01 + 4.966120551231630e-01j,
+ -1.181038235962314e-01 - 4.966120551231630e-01j,
+ -1.119304913239356e-01 + 4.267938916403775e-01j,
+ -1.119304913239356e-01 - 4.267938916403775e-01j,
+ -1.069237739782691e-01 + 3.602914879527338e-01j,
+ -1.069237739782691e-01 - 3.602914879527338e-01j,
+ -1.029178030691416e-01 + 2.964677964142126e-01j,
+ -1.029178030691416e-01 - 2.964677964142126e-01j,
+ -9.978747500816100e-02 + 2.347687643085738e-01j,
+ -9.978747500816100e-02 - 2.347687643085738e-01j,
+ -9.743974496324025e-02 + 1.747028739092479e-01j,
+ -9.743974496324025e-02 - 1.747028739092479e-01j,
+ -9.580754551625957e-02 + 1.158246860771989e-01j,
+ -9.580754551625957e-02 - 1.158246860771989e-01j,
+ -9.484562207782568e-02 + 5.772118357151691e-02j,
+ -9.484562207782568e-02 - 5.772118357151691e-02j,
+ -9.452783117928215e-02
+ ]
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 9.585686688851069e-09
+ xp_assert_equal(z, z2)
+ xp_assert_close(
+ _sort_cmplx(p, xp), _sort_cmplx(p2, xp),
+ rtol=1e-8 if not DEFAULT_F32 else 1e-6
+ )
+ assert math.isclose(k, k2, abs_tol=1e-13)
+
+ def test_bandpass(self, xp):
+ z, p, k = butter(8, xp.asarray([0.25, 0.33]), 'band', output='zpk')
+ z2 = [1 + 0j, 1, 1, 1, 1, 1, 1, 1,
+ -1, -1, -1, -1, -1, -1, -1, -1]
+ p2 = [
+ 4.979909925436156e-01 + 8.367609424799387e-01j,
+ 4.979909925436156e-01 - 8.367609424799387e-01j,
+ 4.913338722555539e-01 + 7.866774509868817e-01j,
+ 4.913338722555539e-01 - 7.866774509868817e-01j,
+ 5.035229361778706e-01 + 7.401147376726750e-01j,
+ 5.035229361778706e-01 - 7.401147376726750e-01j,
+ 5.307617160406101e-01 + 7.029184459442954e-01j,
+ 5.307617160406101e-01 - 7.029184459442954e-01j,
+ 5.680556159453138e-01 + 6.788228792952775e-01j,
+ 5.680556159453138e-01 - 6.788228792952775e-01j,
+ 6.100962560818854e-01 + 6.693849403338664e-01j,
+ 6.100962560818854e-01 - 6.693849403338664e-01j,
+ 6.904694312740631e-01 + 6.930501690145245e-01j,
+ 6.904694312740631e-01 - 6.930501690145245e-01j,
+ 6.521767004237027e-01 + 6.744414640183752e-01j,
+ 6.521767004237027e-01 - 6.744414640183752e-01j,
+ ]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 3.398854055800844e-08
+ xp_assert_equal(z, z2, check_dtype=False)
+ xp_assert_close(
+ _sort_cmplx(p, xp), _sort_cmplx(p2, xp),
+ rtol=1e-13 if not DEFAULT_F32 else 1e-7
+ )
+ assert math.isclose(k, k2, rel_tol=1e-13 if not DEFAULT_F32 else 1e-5)
+
+ # bandpass analog
+ z, p, k = butter(4, xp.asarray([90.5, 110.5]), 'bp', analog=True, output='zpk')
+ z2 = xp.zeros(4, dtype=xp.complex128)
+ p2 = [
+ -4.179137760733086e+00 + 1.095935899082837e+02j,
+ -4.179137760733086e+00 - 1.095935899082837e+02j,
+ -9.593598668443835e+00 + 1.034745398029734e+02j,
+ -9.593598668443835e+00 - 1.034745398029734e+02j,
+ -8.883991981781929e+00 + 9.582087115567160e+01j,
+ -8.883991981781929e+00 - 9.582087115567160e+01j,
+ -3.474530886568715e+00 + 9.111599925805801e+01j,
+ -3.474530886568715e+00 - 9.111599925805801e+01j,
+ ]
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 1.600000000000001e+05
+ xp_assert_equal(z, z2)
+ xp_assert_close(_sort_cmplx(p, xp), _sort_cmplx(p2, xp))
+ assert math.isclose(k, k2, rel_tol=1e-15)
+
+ def test_bandstop(self, xp):
+ z, p, k = butter(7, xp.asarray([0.45, 0.56]), 'stop', output='zpk')
+ z2 = [-1.594474531383421e-02 + 9.998728744679880e-01j,
+ -1.594474531383421e-02 - 9.998728744679880e-01j,
+ -1.594474531383421e-02 + 9.998728744679880e-01j,
+ -1.594474531383421e-02 - 9.998728744679880e-01j,
+ -1.594474531383421e-02 + 9.998728744679880e-01j,
+ -1.594474531383421e-02 - 9.998728744679880e-01j,
+ -1.594474531383421e-02 + 9.998728744679880e-01j,
+ -1.594474531383421e-02 - 9.998728744679880e-01j,
+ -1.594474531383421e-02 + 9.998728744679880e-01j,
+ -1.594474531383421e-02 - 9.998728744679880e-01j,
+ -1.594474531383421e-02 + 9.998728744679880e-01j,
+ -1.594474531383421e-02 - 9.998728744679880e-01j,
+ -1.594474531383421e-02 + 9.998728744679880e-01j,
+ -1.594474531383421e-02 - 9.998728744679880e-01j]
+ p2 = [-1.766850742887729e-01 + 9.466951258673900e-01j,
+ -1.766850742887729e-01 - 9.466951258673900e-01j,
+ 1.467897662432886e-01 + 9.515917126462422e-01j,
+ 1.467897662432886e-01 - 9.515917126462422e-01j,
+ -1.370083529426906e-01 + 8.880376681273993e-01j,
+ -1.370083529426906e-01 - 8.880376681273993e-01j,
+ 1.086774544701390e-01 + 8.915240810704319e-01j,
+ 1.086774544701390e-01 - 8.915240810704319e-01j,
+ -7.982704457700891e-02 + 8.506056315273435e-01j,
+ -7.982704457700891e-02 - 8.506056315273435e-01j,
+ 5.238812787110331e-02 + 8.524011102699969e-01j,
+ 5.238812787110331e-02 - 8.524011102699969e-01j,
+ -1.357545000491310e-02 + 8.382287744986582e-01j,
+ -1.357545000491310e-02 - 8.382287744986582e-01j]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 4.577122512960063e-01
+ xp_assert_close(_sort_cmplx(z, xp), _sort_cmplx(z2, xp))
+ xp_assert_close(_sort_cmplx(p, xp), _sort_cmplx(p2, xp))
+ assert math.isclose(k, k2, rel_tol=1e-14 if not DEFAULT_F32 else 1e-6)
+
+ @xfail_xp_backends("cupy", reason="inaccurate on CuPy")
+ def test_ba_output(self, xp):
+ b, a = butter(4, xp.asarray([100, 300]), 'bandpass', analog=True)
+ b2 = [1.6e+09, 0, 0, 0, 0]
+ a2 = [1.000000000000000e+00, 5.226251859505511e+02,
+ 2.565685424949238e+05, 6.794127417357160e+07,
+ 1.519411254969542e+10, 2.038238225207147e+12,
+ 2.309116882454312e+14, 1.411088002066486e+16,
+ 8.099999999999991e+17]
+ b2 = xp.asarray(b2, dtype=xp.float64)
+ a2 = xp.asarray(a2, dtype=xp.float64)
+ xp_assert_close(b, b2, rtol=1e-14)
+ xp_assert_close(a, a2, rtol=1e-14)
+
+ def test_fs_param(self):
+ for fs in (900, 900.1, 1234.567):
+ for N in (0, 1, 2, 3, 10):
+ for fc in (100, 100.1, 432.12345):
+ for btype in ('lp', 'hp'):
+ ba1 = butter(N, fc, btype, fs=fs)
+ ba2 = butter(N, fc/(fs/2), btype)
+ for ba1_, ba2_ in zip(ba1, ba2):
+ xp_assert_close(ba1_, ba2_)
+ for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)):
+ for btype in ('bp', 'bs'):
+ ba1 = butter(N, fc, btype, fs=fs)
+ for seq in (list, tuple, array):
+ fcnorm = seq([f/(fs/2) for f in fc])
+ ba2 = butter(N, fcnorm, btype)
+ for ba1_, ba2_ in zip(ba1, ba2):
+ xp_assert_close(ba1_, ba2_)
+
+
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+@make_xp_test_case(cheby1)
+class TestCheby1:
+
+ def test_degenerate(self, xp):
+ # 0-order filter is just a passthrough
+ # Even-order filters have DC gain of -rp dB
+ b, a = cheby1(0, 10*math.log10(2), xp.asarray(1), analog=True)
+ assert_array_almost_equal(
+ b, xp.asarray([1 / math.sqrt(2)], dtype=xp.float64)
+ )
+ xp_assert_equal(a, xp.asarray([1.0], dtype=xp.float64))
+
+ # 1-order filter is same for all types
+ b, a = cheby1(1, 10*math.log10(2), xp.asarray(1), analog=True)
+ assert_array_almost_equal(b, xp.asarray([1.], dtype=xp.float64))
+ assert_array_almost_equal(a, xp.asarray([1., 1], dtype=xp.float64))
+
+ z, p, k = cheby1(1, 0.1, xp.asarray(0.3), output='zpk')
+ xp_assert_equal(z, xp.asarray([-1.0], dtype=xp.float64))
+ xp_assert_close(
+ p, xp.asarray([-5.390126972799615e-01 + 0j], dtype=xp.complex128),
+ rtol=1e-14 if not DEFAULT_F32 else 1e-7
+ )
+ assert math.isclose(
+ k, 7.695063486399808e-01, rel_tol=1e-14 if not DEFAULT_F32 else 1e-7
+ )
+
+ def test_basic(self, xp):
+ for N in range(25):
+ wn = xp.asarray(0.01)
+ z, p, k = cheby1(N, 1, wn, 'low', analog=True, output='zpk')
+ assert_array_almost_equal(z, xp.asarray([], dtype=xp.float64))
+ assert p.shape[0] == N
+ assert xp.all(xp.real(p) <= 0) # No poles in right half of S-plane
+
+ for N in range(25):
+ wn = xp.asarray(0.01)
+ z, p, k = cheby1(N, 1, wn, 'high', analog=False, output='zpk')
+ xp_assert_equal(z, xp.ones(N, dtype=xp.float64)) # All zeros exactly at DC
+ assert xp.all(xp.abs(p) <= 1) # No poles outside unit circle
+
+ # Same test as TestNormalize
+ b, a = cheby1(8, 0.5, xp.asarray(0.048))
+ xp_assert_close(
+ b, xp.asarray([2.150733144728282e-11, 1.720586515782626e-10,
+ 6.022052805239190e-10, 1.204410561047838e-09,
+ 1.505513201309798e-09, 1.204410561047838e-09,
+ 6.022052805239190e-10, 1.720586515782626e-10,
+ 2.150733144728282e-11], dtype=xp.float64),
+ rtol=0, atol=1.5e-14
+ )
+ xp_assert_close(
+ a, xp.asarray([1.000000000000000e+00, -7.782402035027959e+00,
+ 2.654354569747454e+01, -5.182182531666387e+01,
+ 6.334127355102684e+01, -4.963358186631157e+01,
+ 2.434862182949389e+01, -6.836925348604676e+00,
+ 8.412934944449140e-01], dtype=xp.float64),
+ rtol=0, atol=5e-14 if not DEFAULT_F32 else 1e-7
+ )
+
+ b, a = cheby1(4, 1, xp.asarray([0.4, 0.7]), btype='band')
+ assert_array_almost_equal(
+ b, xp.asarray([0.0084, 0, -0.0335, 0, 0.0502, 0,
+ -0.0335, 0, 0.0084], dtype=xp.float64),
+ decimal=4
+ )
+ assert_array_almost_equal(
+ a, xp.asarray([1.0, 1.1191, 2.862, 2.2986, 3.4137,
+ 1.8653, 1.8982, 0.5676, 0.4103], dtype=xp.float64),
+ decimal=4
+ )
+
+ b2, a2 = cheby1(5, 3, xp.asarray(1), analog=True)
+ assert_array_almost_equal(
+ b2, xp.asarray([0.0626], dtype=xp.float64), decimal=4
+ )
+ assert_array_almost_equal(
+ a2, xp.asarray([1, 0.5745, 1.4150, 0.5489, 0.4080,
+ 0.0626], dtype=xp.float64),
+ decimal=4)
+
+ b, a = cheby1(8, 0.5, xp.asarray(0.1))
+ assert_array_almost_equal(
+ b,
+ 1.0e-006 * xp.asarray(
+ [0.00703924326028, 0.05631394608227, 0.19709881128793,
+ 0.39419762257586, 0.49274702821983, 0.39419762257586,
+ 0.19709881128793, 0.05631394608227, 0.00703924326028
+ ], dtype=xp.float64
+ ),
+ decimal=13
+ )
+ assert_array_almost_equal(
+ a, xp.asarray(
+ [1.00000000000000, -7.44912258934158, 24.46749067762108,
+ -46.27560200466141, 55.11160187999928, -42.31640010161038,
+ 20.45543300484147, -5.69110270561444, 0.69770374759022
+ ], dtype=xp.float64
+ ),
+ decimal=13 if not DEFAULT_F32 else 6
+ )
+
+ b, a = cheby1(8, 0.5, xp.asarray(0.25))
+ assert_array_almost_equal(
+ b,
+ 1.0e-003 * xp.asarray(
+ [0.00895261138923, 0.07162089111382, 0.25067311889837,
+ 0.50134623779673, 0.62668279724591, 0.50134623779673,
+ 0.25067311889837, 0.07162089111382, 0.00895261138923
+ ], dtype=xp.float64
+ ),
+ decimal=13)
+ assert_array_almost_equal(
+ a,
+ xp.asarray(
+ [1.00000000000000, -5.97529229188545,
+ 16.58122329202101, -27.71423273542923,
+ 30.39509758355313, -22.34729670426879,
+ 10.74509800434910, -3.08924633697497,
+ 0.40707685889802
+ ], dtype=xp.float64
+ ), decimal=13)
+
+ def test_highpass(self, xp):
+ # high even order
+ z, p, k = cheby1(24, 0.7, xp.asarray(0.2), 'high', output='zpk')
+ z2 = xp.ones(24, dtype=xp.float64)
+ p2 = [-6.136558509657073e-01 + 2.700091504942893e-01j,
+ -6.136558509657073e-01 - 2.700091504942893e-01j,
+ -3.303348340927516e-01 + 6.659400861114254e-01j,
+ -3.303348340927516e-01 - 6.659400861114254e-01j,
+ 8.779713780557169e-03 + 8.223108447483040e-01j,
+ 8.779713780557169e-03 - 8.223108447483040e-01j,
+ 2.742361123006911e-01 + 8.356666951611864e-01j,
+ 2.742361123006911e-01 - 8.356666951611864e-01j,
+ 4.562984557158206e-01 + 7.954276912303594e-01j,
+ 4.562984557158206e-01 - 7.954276912303594e-01j,
+ 5.777335494123628e-01 + 7.435821817961783e-01j,
+ 5.777335494123628e-01 - 7.435821817961783e-01j,
+ 6.593260977749194e-01 + 6.955390907990932e-01j,
+ 6.593260977749194e-01 - 6.955390907990932e-01j,
+ 7.149590948466562e-01 + 6.559437858502012e-01j,
+ 7.149590948466562e-01 - 6.559437858502012e-01j,
+ 7.532432388188739e-01 + 6.256158042292060e-01j,
+ 7.532432388188739e-01 - 6.256158042292060e-01j,
+ 7.794365244268271e-01 + 6.042099234813333e-01j,
+ 7.794365244268271e-01 - 6.042099234813333e-01j,
+ 7.967253874772997e-01 + 5.911966597313203e-01j,
+ 7.967253874772997e-01 - 5.911966597313203e-01j,
+ 8.069756417293870e-01 + 5.862214589217275e-01j,
+ 8.069756417293870e-01 - 5.862214589217275e-01j]
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 6.190427617192018e-04
+ xp_assert_equal(z, z2)
+ xp_assert_close(
+ _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp),
+ rtol=1e-10 if not DEFAULT_F32 else 1e-7
+ )
+ assert math.isclose(k, k2, rel_tol=1e-10 if not DEFAULT_F32 else 1e-6)
+
+ # high odd order
+ z, p, k = cheby1(23, 0.8, xp.asarray(0.3), 'high', output='zpk')
+ z2 = xp.ones(23, dtype=xp.float64)
+ p2 = [-7.676400532011010e-01,
+ -6.754621070166477e-01 + 3.970502605619561e-01j,
+ -6.754621070166477e-01 - 3.970502605619561e-01j,
+ -4.528880018446727e-01 + 6.844061483786332e-01j,
+ -4.528880018446727e-01 - 6.844061483786332e-01j,
+ -1.986009130216447e-01 + 8.382285942941594e-01j,
+ -1.986009130216447e-01 - 8.382285942941594e-01j,
+ 2.504673931532608e-02 + 8.958137635794080e-01j,
+ 2.504673931532608e-02 - 8.958137635794080e-01j,
+ 2.001089429976469e-01 + 9.010678290791480e-01j,
+ 2.001089429976469e-01 - 9.010678290791480e-01j,
+ 3.302410157191755e-01 + 8.835444665962544e-01j,
+ 3.302410157191755e-01 - 8.835444665962544e-01j,
+ 4.246662537333661e-01 + 8.594054226449009e-01j,
+ 4.246662537333661e-01 - 8.594054226449009e-01j,
+ 4.919620928120296e-01 + 8.366772762965786e-01j,
+ 4.919620928120296e-01 - 8.366772762965786e-01j,
+ 5.385746917494749e-01 + 8.191616180796720e-01j,
+ 5.385746917494749e-01 - 8.191616180796720e-01j,
+ 5.855636993537203e-01 + 8.060680937701062e-01j,
+ 5.855636993537203e-01 - 8.060680937701062e-01j,
+ 5.688812849391721e-01 + 8.086497795114683e-01j,
+ 5.688812849391721e-01 - 8.086497795114683e-01j]
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 1.941697029206324e-05
+ xp_assert_equal(z, z2)
+ xp_assert_close(
+ _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp),
+ rtol=1e-10 if not DEFAULT_F32 else 1e-7
+ )
+ assert math.isclose(
+ k, k2, rel_tol=1e-10 if not DEFAULT_F32 else 1e-6
+ )
+
+ z, p, k = cheby1(10, 1, xp.asarray(1000), 'high', analog=True, output='zpk')
+ z2 = xp.zeros(10, dtype=xp.float64)
+ p2 = [-3.144743169501551e+03 + 3.511680029092744e+03j,
+ -3.144743169501551e+03 - 3.511680029092744e+03j,
+ -5.633065604514602e+02 + 2.023615191183945e+03j,
+ -5.633065604514602e+02 - 2.023615191183945e+03j,
+ -1.946412183352025e+02 + 1.372309454274755e+03j,
+ -1.946412183352025e+02 - 1.372309454274755e+03j,
+ -7.987162953085479e+01 + 1.105207708045358e+03j,
+ -7.987162953085479e+01 - 1.105207708045358e+03j,
+ -2.250315039031946e+01 + 1.001723931471477e+03j,
+ -2.250315039031946e+01 - 1.001723931471477e+03j]
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 8.912509381337453e-01
+ xp_assert_equal(z, z2)
+ xp_assert_close(_sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp), rtol=1e-13)
+ assert math.isclose(k, k2, rel_tol=1e-15)
+
+ def test_bandpass(self, xp):
+ z, p, k = cheby1(8, 1, xp.asarray([0.3, 0.4]), 'bp', output='zpk')
+ z2 = [1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, -1, -1, -1, -1]
+ p2 = [3.077784854851463e-01 + 9.453307017592942e-01j,
+ 3.077784854851463e-01 - 9.453307017592942e-01j,
+ 3.280567400654425e-01 + 9.272377218689016e-01j,
+ 3.280567400654425e-01 - 9.272377218689016e-01j,
+ 3.677912763284301e-01 + 9.038008865279966e-01j,
+ 3.677912763284301e-01 - 9.038008865279966e-01j,
+ 4.194425632520948e-01 + 8.769407159656157e-01j,
+ 4.194425632520948e-01 - 8.769407159656157e-01j,
+ 4.740921994669189e-01 + 8.496508528630974e-01j,
+ 4.740921994669189e-01 - 8.496508528630974e-01j,
+ 5.234866481897429e-01 + 8.259608422808477e-01j,
+ 5.234866481897429e-01 - 8.259608422808477e-01j,
+ 5.844717632289875e-01 + 8.052901363500210e-01j,
+ 5.844717632289875e-01 - 8.052901363500210e-01j,
+ 5.615189063336070e-01 + 8.100667803850766e-01j,
+ 5.615189063336070e-01 - 8.100667803850766e-01j]
+ z2 = xp.asarray(z2, dtype=xp.float64)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 5.007028718074307e-09
+ xp_assert_equal(z, z2, check_dtype=False)
+ xp_assert_close(
+ _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp),
+ rtol=1e-13 if not DEFAULT_F32 else 1e-7
+ )
+ assert math.isclose(k, k2, rel_tol=1e-13 if not DEFAULT_F32 else 1e-6)
+
+ def test_bandstop(self, xp):
+ z, p, k = cheby1(7, 1, xp.asarray([0.5, 0.6]), 'stop', output='zpk')
+ z2 = [-1.583844403245361e-01 + 9.873775210440450e-01j,
+ -1.583844403245361e-01 - 9.873775210440450e-01j,
+ -1.583844403245361e-01 + 9.873775210440450e-01j,
+ -1.583844403245361e-01 - 9.873775210440450e-01j,
+ -1.583844403245361e-01 + 9.873775210440450e-01j,
+ -1.583844403245361e-01 - 9.873775210440450e-01j,
+ -1.583844403245361e-01 + 9.873775210440450e-01j,
+ -1.583844403245361e-01 - 9.873775210440450e-01j,
+ -1.583844403245361e-01 + 9.873775210440450e-01j,
+ -1.583844403245361e-01 - 9.873775210440450e-01j,
+ -1.583844403245361e-01 + 9.873775210440450e-01j,
+ -1.583844403245361e-01 - 9.873775210440450e-01j,
+ -1.583844403245361e-01 + 9.873775210440450e-01j,
+ -1.583844403245361e-01 - 9.873775210440450e-01j]
+ p2 = [-8.942974551472813e-02 + 3.482480481185926e-01j,
+ -8.942974551472813e-02 - 3.482480481185926e-01j,
+ 1.293775154041798e-01 + 8.753499858081858e-01j,
+ 1.293775154041798e-01 - 8.753499858081858e-01j,
+ 3.399741945062013e-02 + 9.690316022705607e-01j,
+ 3.399741945062013e-02 - 9.690316022705607e-01j,
+ 4.167225522796539e-04 + 9.927338161087488e-01j,
+ 4.167225522796539e-04 - 9.927338161087488e-01j,
+ -3.912966549550960e-01 + 8.046122859255742e-01j,
+ -3.912966549550960e-01 - 8.046122859255742e-01j,
+ -3.307805547127368e-01 + 9.133455018206508e-01j,
+ -3.307805547127368e-01 - 9.133455018206508e-01j,
+ -3.072658345097743e-01 + 9.443589759799366e-01j,
+ -3.072658345097743e-01 - 9.443589759799366e-01j]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 3.619438310405028e-01
+ xp_assert_close(
+ _sort_cmplx(z, xp=xp), _sort_cmplx(z2, xp=xp),
+ rtol=1e-13 if not DEFAULT_F32 else 1e-6
+ )
+ xp_assert_close(
+ _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp),
+ rtol=1e-13 if not DEFAULT_F32 else 1e-6
+ )
+ assert math.isclose(
+ k, k2, rel_tol=0, abs_tol=5e-16 if not DEFAULT_F32 else 1e-7
+ )
+
+ @xfail_xp_backends("cupy", reason="inaccurate on CuPy")
+ def test_ba_output(self, xp):
+ # with transfer function conversion, without digital conversion
+ b, a = cheby1(5, 0.9, xp.asarray([210, 310.0]), 'stop', analog=True)
+ b2 = [1.000000000000006e+00, 0,
+ 3.255000000000020e+05, 0,
+ 4.238010000000026e+10, 0,
+ 2.758944510000017e+15, 0,
+ 8.980364380050052e+19, 0,
+ 1.169243442282517e+24
+ ]
+ a2 = [1.000000000000000e+00, 4.630555945694342e+02,
+ 4.039266454794788e+05, 1.338060988610237e+08,
+ 5.844333551294591e+10, 1.357346371637638e+13,
+ 3.804661141892782e+15, 5.670715850340080e+17,
+ 1.114411200988328e+20, 8.316815934908471e+21,
+ 1.169243442282517e+24
+ ]
+ b2, a2 = map(lambda t: xp.asarray(t, dtype=xp.float64), (b2, a2))
+ xp_assert_close(b, b2, rtol=1e-14 if not DEFAULT_F32 else 1e-7)
+ xp_assert_close(a, a2, rtol=1e-14 if not DEFAULT_F32 else 1e-7)
+
+ def test_fs_param(self):
+ for fs in (900, 900.1, 1234.567):
+ for N in (0, 1, 2, 3, 10):
+ for fc in (100, 100.1, 432.12345):
+ for btype in ('lp', 'hp'):
+ ba1 = cheby1(N, 1, fc, btype, fs=fs)
+ ba2 = cheby1(N, 1, fc/(fs/2), btype)
+ for ba1_, ba2_ in zip(ba1, ba2):
+ xp_assert_close(ba1_, ba2_)
+ for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)):
+ for btype in ('bp', 'bs'):
+ ba1 = cheby1(N, 1, fc, btype, fs=fs)
+ for seq in (list, tuple, array):
+ fcnorm = seq([f/(fs/2) for f in fc])
+ ba2 = cheby1(N, 1, fcnorm, btype)
+ for ba1_, ba2_ in zip(ba1, ba2):
+ xp_assert_close(ba1_, ba2_)
+
+
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+@make_xp_test_case(cheby2)
+class TestCheby2:
+
+ def test_degenerate(self, xp):
+ # 0-order filter is just a passthrough
+ # Stopband ripple factor doesn't matter
+ b, a = cheby2(0, 123.456, xp.asarray(1), analog=True)
+ xp_assert_equal(b, xp.asarray([1.0], dtype=xp.float64))
+ xp_assert_equal(a, xp.asarray([1.0], dtype=xp.float64))
+
+ # 1-order filter is same for all types
+ b, a = cheby2(1, 10*math.log10(2), xp.asarray(1.), analog=True)
+ assert_array_almost_equal(b, xp.asarray([1], dtype=xp.float64))
+ assert_array_almost_equal(a, xp.asarray([1, 1], dtype=xp.float64))
+
+ z, p, k = cheby2(1, 50, xp.asarray(0.3), output='zpk')
+ xp_assert_equal(z, xp.asarray([-1], dtype=xp.complex128))
+ xp_assert_close(
+ p, xp.asarray([9.967826460175649e-01 + 0j], dtype=xp.complex128),
+ rtol=1e-14 if not DEFAULT_F32 else 1e-7
+ )
+ assert math.isclose(
+ k, 1.608676991217512e-03, rel_tol=1e-14 if not DEFAULT_F32 else 1e-6
+ )
+
+ def test_basic(self, xp):
+ for N in range(25):
+ wn = xp.asarray(0.01)
+ z, p, k = cheby2(N, 40, wn, 'low', analog=True, output='zpk')
+ assert p.shape[0] == N
+ assert all(xp.real(p) <= 0) # No poles in right half of S-plane
+
+ for N in range(25):
+ wn = xp.asarray(0.01)
+ z, p, k = cheby2(N, 40, wn, 'high', analog=False, output='zpk')
+ assert all(xp.abs(p) <= 1) # No poles outside unit circle
+
+ B, A = cheby2(18, 100, xp.asarray(0.5))
+ assert_array_almost_equal(
+ B, xp.asarray([
+ 0.00167583914216, 0.01249479541868, 0.05282702120282,
+ 0.15939804265706, 0.37690207631117, 0.73227013789108,
+ 1.20191856962356, 1.69522872823393, 2.07598674519837,
+ 2.21972389625291, 2.07598674519838, 1.69522872823395,
+ 1.20191856962359, 0.73227013789110, 0.37690207631118,
+ 0.15939804265707, 0.05282702120282, 0.01249479541868,
+ 0.00167583914216], dtype=xp.float64),
+ decimal=13 if not DEFAULT_F32 else 6
+ )
+ assert_array_almost_equal(
+ A, xp.asarray([
+ 1.00000000000000, -0.27631970006174, 3.19751214254060,
+ -0.15685969461355, 4.13926117356269, 0.60689917820044,
+ 2.95082770636540, 0.89016501910416, 1.32135245849798,
+ 0.51502467236824, 0.38906643866660, 0.15367372690642,
+ 0.07255803834919, 0.02422454070134, 0.00756108751837,
+ 0.00179848550988, 0.00033713574499, 0.00004258794833,
+ 0.00000281030149], dtype=xp.float64),
+ decimal=13 if not DEFAULT_F32 else 6
+ )
+
+ def test_highpass(self, xp):
+ # high even order
+ z, p, k = cheby2(26, 60, xp.asarray(0.3), 'high', output='zpk')
+ z2 = [9.981088955489852e-01 + 6.147058341984388e-02j,
+ 9.981088955489852e-01 - 6.147058341984388e-02j,
+ 9.832702870387426e-01 + 1.821525257215483e-01j,
+ 9.832702870387426e-01 - 1.821525257215483e-01j,
+ 9.550760158089112e-01 + 2.963609353922882e-01j,
+ 9.550760158089112e-01 - 2.963609353922882e-01j,
+ 9.162054748821922e-01 + 4.007087817803773e-01j,
+ 9.162054748821922e-01 - 4.007087817803773e-01j,
+ 8.700619897368064e-01 + 4.929423232136168e-01j,
+ 8.700619897368064e-01 - 4.929423232136168e-01j,
+ 5.889791753434985e-01 + 8.081482110427953e-01j,
+ 5.889791753434985e-01 - 8.081482110427953e-01j,
+ 5.984900456570295e-01 + 8.011302423760501e-01j,
+ 5.984900456570295e-01 - 8.011302423760501e-01j,
+ 6.172880888914629e-01 + 7.867371958365343e-01j,
+ 6.172880888914629e-01 - 7.867371958365343e-01j,
+ 6.448899971038180e-01 + 7.642754030030161e-01j,
+ 6.448899971038180e-01 - 7.642754030030161e-01j,
+ 6.804845629637927e-01 + 7.327624168637228e-01j,
+ 6.804845629637927e-01 - 7.327624168637228e-01j,
+ 8.202619107108660e-01 + 5.719881098737678e-01j,
+ 8.202619107108660e-01 - 5.719881098737678e-01j,
+ 7.228410452536148e-01 + 6.910143437705678e-01j,
+ 7.228410452536148e-01 - 6.910143437705678e-01j,
+ 7.702121399578629e-01 + 6.377877856007792e-01j,
+ 7.702121399578629e-01 - 6.377877856007792e-01j]
+ p2 = [7.365546198286450e-01 + 4.842085129329526e-02j,
+ 7.365546198286450e-01 - 4.842085129329526e-02j,
+ 7.292038510962885e-01 + 1.442201672097581e-01j,
+ 7.292038510962885e-01 - 1.442201672097581e-01j,
+ 7.151293788040354e-01 + 2.369925800458584e-01j,
+ 7.151293788040354e-01 - 2.369925800458584e-01j,
+ 6.955051820787286e-01 + 3.250341363856910e-01j,
+ 6.955051820787286e-01 - 3.250341363856910e-01j,
+ 6.719122956045220e-01 + 4.070475750638047e-01j,
+ 6.719122956045220e-01 - 4.070475750638047e-01j,
+ 6.461722130611300e-01 + 4.821965916689270e-01j,
+ 6.461722130611300e-01 - 4.821965916689270e-01j,
+ 5.528045062872224e-01 + 8.162920513838372e-01j,
+ 5.528045062872224e-01 - 8.162920513838372e-01j,
+ 5.464847782492791e-01 + 7.869899955967304e-01j,
+ 5.464847782492791e-01 - 7.869899955967304e-01j,
+ 5.488033111260949e-01 + 7.520442354055579e-01j,
+ 5.488033111260949e-01 - 7.520442354055579e-01j,
+ 6.201874719022955e-01 + 5.500894392527353e-01j,
+ 6.201874719022955e-01 - 5.500894392527353e-01j,
+ 5.586478152536709e-01 + 7.112676877332921e-01j,
+ 5.586478152536709e-01 - 7.112676877332921e-01j,
+ 5.958145844148228e-01 + 6.107074340842115e-01j,
+ 5.958145844148228e-01 - 6.107074340842115e-01j,
+ 5.747812938519067e-01 + 6.643001536914696e-01j,
+ 5.747812938519067e-01 - 6.643001536914696e-01j]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 6.190427617192018e-04
+ k2 = 9.932997786497189e-02
+ xp_assert_close(
+ _sort_cmplx(z, xp=xp), _sort_cmplx(z2, xp=xp),
+ rtol=1e-13 if not DEFAULT_F32 else 1e-6
+ )
+ xp_assert_close(
+ _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp),
+ rtol=1e-12 if not DEFAULT_F32 else 1e-6
+ )
+ assert math.isclose(
+ k, k2, rel_tol=1e-11 if not DEFAULT_F32 else 1e-6
+ )
+
+ # high odd order
+ z, p, k = cheby2(25, 80, xp.asarray(0.5), 'high', output='zpk')
+ z2 = [9.690690376586687e-01 + 2.467897896011971e-01j,
+ 9.690690376586687e-01 - 2.467897896011971e-01j,
+ 9.999999999999492e-01,
+ 8.835111277191199e-01 + 4.684101698261429e-01j,
+ 8.835111277191199e-01 - 4.684101698261429e-01j,
+ 7.613142857900539e-01 + 6.483830335935022e-01j,
+ 7.613142857900539e-01 - 6.483830335935022e-01j,
+ 6.232625173626231e-01 + 7.820126817709752e-01j,
+ 6.232625173626231e-01 - 7.820126817709752e-01j,
+ 4.864456563413621e-01 + 8.737108351316745e-01j,
+ 4.864456563413621e-01 - 8.737108351316745e-01j,
+ 3.618368136816749e-01 + 9.322414495530347e-01j,
+ 3.618368136816749e-01 - 9.322414495530347e-01j,
+ 2.549486883466794e-01 + 9.669545833752675e-01j,
+ 2.549486883466794e-01 - 9.669545833752675e-01j,
+ 1.676175432109457e-01 + 9.858520980390212e-01j,
+ 1.676175432109457e-01 - 9.858520980390212e-01j,
+ 1.975218468277521e-03 + 9.999980492540941e-01j,
+ 1.975218468277521e-03 - 9.999980492540941e-01j,
+ 1.786959496651858e-02 + 9.998403260399917e-01j,
+ 1.786959496651858e-02 - 9.998403260399917e-01j,
+ 9.967933660557139e-02 + 9.950196127985684e-01j,
+ 9.967933660557139e-02 - 9.950196127985684e-01j,
+ 5.013970951219547e-02 + 9.987422137518890e-01j,
+ 5.013970951219547e-02 - 9.987422137518890e-01j]
+ p2 = [4.218866331906864e-01,
+ 4.120110200127552e-01 + 1.361290593621978e-01j,
+ 4.120110200127552e-01 - 1.361290593621978e-01j,
+ 3.835890113632530e-01 + 2.664910809911026e-01j,
+ 3.835890113632530e-01 - 2.664910809911026e-01j,
+ 3.399195570456499e-01 + 3.863983538639875e-01j,
+ 3.399195570456499e-01 - 3.863983538639875e-01j,
+ 2.855977834508353e-01 + 4.929444399540688e-01j,
+ 2.855977834508353e-01 - 4.929444399540688e-01j,
+ 2.255765441339322e-01 + 5.851631870205766e-01j,
+ 2.255765441339322e-01 - 5.851631870205766e-01j,
+ 1.644087535815792e-01 + 6.637356937277153e-01j,
+ 1.644087535815792e-01 - 6.637356937277153e-01j,
+ -7.293633845273095e-02 + 9.739218252516307e-01j,
+ -7.293633845273095e-02 - 9.739218252516307e-01j,
+ 1.058259206358626e-01 + 7.304739464862978e-01j,
+ 1.058259206358626e-01 - 7.304739464862978e-01j,
+ -5.703971947785402e-02 + 9.291057542169088e-01j,
+ -5.703971947785402e-02 - 9.291057542169088e-01j,
+ 5.263875132656864e-02 + 7.877974334424453e-01j,
+ 5.263875132656864e-02 - 7.877974334424453e-01j,
+ -3.007943405982616e-02 + 8.846331716180016e-01j,
+ -3.007943405982616e-02 - 8.846331716180016e-01j,
+ 6.857277464483946e-03 + 8.383275456264492e-01j,
+ 6.857277464483946e-03 - 8.383275456264492e-01j]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 6.507068761705037e-03
+ xp_assert_close(
+ _sort_cmplx(z, xp=xp), _sort_cmplx(z2, xp=xp),
+ rtol=1e-13 if not DEFAULT_F32 else 1e-6
+ )
+ xp_assert_close(
+ _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp),
+ rtol=1e-12 if not DEFAULT_F32 else 1e-6
+ )
+ assert math.isclose(k, k2, rel_tol=1e-11 if not DEFAULT_F32 else 1e-6)
+
+ def test_bandpass(self, xp):
+ z, p, k = cheby2(9, 40, xp.asarray([0.07, 0.2]), 'pass', output='zpk')
+ z2 = [-9.999999999999999e-01,
+ 3.676588029658514e-01 + 9.299607543341383e-01j,
+ 3.676588029658514e-01 - 9.299607543341383e-01j,
+ 7.009689684982283e-01 + 7.131917730894889e-01j,
+ 7.009689684982283e-01 - 7.131917730894889e-01j,
+ 7.815697973765858e-01 + 6.238178033919218e-01j,
+ 7.815697973765858e-01 - 6.238178033919218e-01j,
+ 8.063793628819866e-01 + 5.913986160941200e-01j,
+ 8.063793628819866e-01 - 5.913986160941200e-01j,
+ 1.000000000000001e+00,
+ 9.944493019920448e-01 + 1.052168511576739e-01j,
+ 9.944493019920448e-01 - 1.052168511576739e-01j,
+ 9.854674703367308e-01 + 1.698642543566085e-01j,
+ 9.854674703367308e-01 - 1.698642543566085e-01j,
+ 9.762751735919308e-01 + 2.165335665157851e-01j,
+ 9.762751735919308e-01 - 2.165335665157851e-01j,
+ 9.792277171575134e-01 + 2.027636011479496e-01j,
+ 9.792277171575134e-01 - 2.027636011479496e-01j]
+ p2 = [8.143803410489621e-01 + 5.411056063397541e-01j,
+ 8.143803410489621e-01 - 5.411056063397541e-01j,
+ 7.650769827887418e-01 + 5.195412242095543e-01j,
+ 7.650769827887418e-01 - 5.195412242095543e-01j,
+ 6.096241204063443e-01 + 3.568440484659796e-01j,
+ 6.096241204063443e-01 - 3.568440484659796e-01j,
+ 6.918192770246239e-01 + 4.770463577106911e-01j,
+ 6.918192770246239e-01 - 4.770463577106911e-01j,
+ 6.986241085779207e-01 + 1.146512226180060e-01j,
+ 6.986241085779207e-01 - 1.146512226180060e-01j,
+ 8.654645923909734e-01 + 1.604208797063147e-01j,
+ 8.654645923909734e-01 - 1.604208797063147e-01j,
+ 9.164831670444591e-01 + 1.969181049384918e-01j,
+ 9.164831670444591e-01 - 1.969181049384918e-01j,
+ 9.630425777594550e-01 + 2.317513360702271e-01j,
+ 9.630425777594550e-01 - 2.317513360702271e-01j,
+ 9.438104703725529e-01 + 2.193509900269860e-01j,
+ 9.438104703725529e-01 - 2.193509900269860e-01j]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 9.345352824659604e-03
+ xp_assert_close(
+ _sort_cmplx(z, xp=xp), _sort_cmplx(z2, xp=xp),
+ rtol=1e-13 if not DEFAULT_F32 else 1e-6
+ )
+ xp_assert_close(
+ _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp),
+ rtol=1e-13 if not DEFAULT_F32 else 1e-6
+ )
+ assert math.isclose(k, k2, rel_tol=1e-11 if not DEFAULT_F32 else 1e-6)
+
+ def test_bandstop(self, xp):
+ z, p, k = cheby2(6, 55, xp.asarray([0.1, 0.9]), 'stop', output='zpk')
+ z2 = [6.230544895101009e-01 + 7.821784343111114e-01j,
+ 6.230544895101009e-01 - 7.821784343111114e-01j,
+ 9.086608545660115e-01 + 4.175349702471991e-01j,
+ 9.086608545660115e-01 - 4.175349702471991e-01j,
+ 9.478129721465802e-01 + 3.188268649763867e-01j,
+ 9.478129721465802e-01 - 3.188268649763867e-01j,
+ -6.230544895100982e-01 + 7.821784343111109e-01j,
+ -6.230544895100982e-01 - 7.821784343111109e-01j,
+ -9.086608545660116e-01 + 4.175349702472088e-01j,
+ -9.086608545660116e-01 - 4.175349702472088e-01j,
+ -9.478129721465784e-01 + 3.188268649763897e-01j,
+ -9.478129721465784e-01 - 3.188268649763897e-01j]
+ p2 = [-9.464094036167638e-01 + 1.720048695084344e-01j,
+ -9.464094036167638e-01 - 1.720048695084344e-01j,
+ -8.715844103386737e-01 + 1.370665039509297e-01j,
+ -8.715844103386737e-01 - 1.370665039509297e-01j,
+ -8.078751204586425e-01 + 5.729329866682983e-02j,
+ -8.078751204586425e-01 - 5.729329866682983e-02j,
+ 9.464094036167665e-01 + 1.720048695084332e-01j,
+ 9.464094036167665e-01 - 1.720048695084332e-01j,
+ 8.078751204586447e-01 + 5.729329866683007e-02j,
+ 8.078751204586447e-01 - 5.729329866683007e-02j,
+ 8.715844103386721e-01 + 1.370665039509331e-01j,
+ 8.715844103386721e-01 - 1.370665039509331e-01j]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 2.917823332763358e-03
+ xp_assert_close(
+ _sort_cmplx(z, xp=xp), _sort_cmplx(z2, xp=xp),
+ rtol=1e-13 if not DEFAULT_F32 else 1e-6
+ )
+ xp_assert_close(
+ _sort_cmplx(p, xp=xp), _sort_cmplx(p2, xp=xp),
+ rtol=1e-13 if not DEFAULT_F32 else 1e-6
+ )
+ assert math.isclose(k, k2, rel_tol=1e-11 if not DEFAULT_F32 else 1e-6)
+
+ @xfail_xp_backends("cupy", reason="inaccurate on CuPy")
+ def test_ba_output(self, xp):
+ # with transfer function conversion, without digital conversion
+ b, a = cheby2(5, 20, xp.asarray([2010, 2100]), 'stop', True)
+ b2 = [1.000000000000000e+00, 0, # Matlab: 6.683253076978249e-12,
+ 2.111512500000000e+07, 0, # Matlab: 1.134325604589552e-04,
+ 1.782966433781250e+14, 0, # Matlab: 7.216787944356781e+02,
+ 7.525901316990656e+20, 0, # Matlab: 2.039829265789886e+09,
+ 1.587960565565748e+27, 0, # Matlab: 2.161236218626134e+15,
+ 1.339913493808585e+33]
+ a2 = [1.000000000000000e+00, 1.849550755473371e+02,
+ 2.113222918998538e+07, 3.125114149732283e+09,
+ 1.785133457155609e+14, 1.979158697776348e+16,
+ 7.535048322653831e+20, 5.567966191263037e+22,
+ 1.589246884221346e+27, 5.871210648525566e+28,
+ 1.339913493808590e+33]
+ b2 = xp.asarray(b2, dtype=xp.float64)
+ a2 = xp.asarray(a2, dtype=xp.float64)
+ xp_assert_close(b, b2, rtol=5e-14 if not DEFAULT_F32 else 1e-7)
+ xp_assert_close(a, a2, rtol=5e-14 if not DEFAULT_F32 else 1e-7)
+
+ def test_fs_param(self):
+ for fs in (900, 900.1, 1234.567):
+ for N in (0, 1, 2, 3, 10):
+ for fc in (100, 100.1, 432.12345):
+ for btype in ('lp', 'hp'):
+ ba1 = cheby2(N, 20, fc, btype, fs=fs)
+ ba2 = cheby2(N, 20, fc/(fs/2), btype)
+ for ba1_, ba2_ in zip(ba1, ba2):
+ xp_assert_close(ba1_, ba2_)
+ for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)):
+ for btype in ('bp', 'bs'):
+ ba1 = cheby2(N, 20, fc, btype, fs=fs)
+ for seq in (list, tuple, array):
+ fcnorm = seq([f/(fs/2) for f in fc])
+ ba2 = cheby2(N, 20, fcnorm, btype)
+ for ba1_, ba2_ in zip(ba1, ba2):
+ xp_assert_close(ba1_, ba2_)
+
+
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+@make_xp_test_case(ellip)
+class TestEllip:
+
+ @xfail_xp_backends("cupy", reason="dtypes do not match")
+ def test_degenerate(self, xp):
+ # 0-order filter is just a passthrough
+ # Even-order filters have DC gain of -rp dB
+ # Stopband ripple factor doesn't matter
+ b, a = ellip(0, 10*math.log10(2), 123.456, xp.asarray(1.), analog=True)
+ assert_array_almost_equal(b, xp.asarray([1/math.sqrt(2)], dtype=xp.float64))
+ xp_assert_equal(a, xp.asarray([1.0], dtype=xp.float64))
+
+ # 1-order filter is same for all types
+ b, a = ellip(1, 10*math.log10(2), 1, xp.asarray(1.), analog=True)
+ assert_array_almost_equal(b, xp.asarray([1.], dtype=xp.float64))
+ assert_array_almost_equal(a, xp.asarray([1., 1], dtype=xp.float64))
+
+ z, p, k = ellip(1, 1, 55, xp.asarray(0.3), output='zpk')
+ xp_assert_close(
+ z, xp.asarray([-9.999999999999998e-01 + 0j], dtype=xp.complex128),
+ rtol=1e-14
+ )
+ xp_assert_close(
+ p, xp.asarray([-6.660721153525525e-04 + 0j], dtype=xp.complex128),
+ rtol=1e-10 if not DEFAULT_F32 else 5e-5
+ )
+ assert math.isclose(
+ k, 5.003330360576763e-01, rel_tol=1e-14 if not DEFAULT_F32 else 1e-7
+ )
+
+ def test_basic(self, xp):
+ for N in range(25):
+ wn = xp.asarray(0.01)
+ z, p, k = ellip(N, 1, 40, wn, 'low', analog=True, output='zpk')
+ assert p.shape[0] == N
+ assert xp.all(xp.real(p) <= 0) # No poles in right half of S-plane
+
+ for N in range(25):
+ wn = xp.asarray(0.01)
+ z, p, k = ellip(N, 1, 40, wn, 'high', analog=False, output='zpk')
+ assert xp.all(xp.abs(p) <= 1) # No poles outside unit circle
+
+ b3, a3 = ellip(5, 3, 26, xp.asarray(1.), analog=True)
+ assert_array_almost_equal(
+ b3, xp.asarray([0.1420, 0, 0.3764, 0, 0.2409], dtype=xp.float64),
+ decimal=4
+ )
+ assert_array_almost_equal(
+ a3,
+ xp.asarray([1, 0.5686, 1.8061, 0.8017, 0.8012, 0.2409], dtype=xp.float64),
+ decimal=4
+ )
+
+ b, a = ellip(3, 1, 60, xp.asarray([0.4, 0.7]), 'stop')
+ assert_array_almost_equal(
+ b, xp.asarray([0.3310, 0.3469, 1.1042, 0.7044, 1.1042,
+ 0.3469, 0.3310], dtype=xp.float64),
+ decimal=4
+ )
+ assert_array_almost_equal(
+ a, xp.asarray([1.0000, 0.6973, 1.1441, 0.5878, 0.7323,
+ 0.1131, -0.0060], dtype=xp.float64),
+ decimal=4
+ )
+
+ def test_highpass(self, xp):
+ # high even order
+ z, p, k = ellip(24, 1, 80, xp.asarray(0.3), 'high', output='zpk')
+ z2 = [9.761875332501075e-01 + 2.169283290099910e-01j,
+ 9.761875332501075e-01 - 2.169283290099910e-01j,
+ 8.413503353963494e-01 + 5.404901600661900e-01j,
+ 8.413503353963494e-01 - 5.404901600661900e-01j,
+ 7.160082576305009e-01 + 6.980918098681732e-01j,
+ 7.160082576305009e-01 - 6.980918098681732e-01j,
+ 6.456533638965329e-01 + 7.636306264739803e-01j,
+ 6.456533638965329e-01 - 7.636306264739803e-01j,
+ 6.127321820971366e-01 + 7.902906256703928e-01j,
+ 6.127321820971366e-01 - 7.902906256703928e-01j,
+ 5.983607817490196e-01 + 8.012267936512676e-01j,
+ 5.983607817490196e-01 - 8.012267936512676e-01j,
+ 5.922577552594799e-01 + 8.057485658286990e-01j,
+ 5.922577552594799e-01 - 8.057485658286990e-01j,
+ 5.896952092563588e-01 + 8.076258788449631e-01j,
+ 5.896952092563588e-01 - 8.076258788449631e-01j,
+ 5.886248765538837e-01 + 8.084063054565607e-01j,
+ 5.886248765538837e-01 - 8.084063054565607e-01j,
+ 5.881802711123132e-01 + 8.087298490066037e-01j,
+ 5.881802711123132e-01 - 8.087298490066037e-01j,
+ 5.879995719101164e-01 + 8.088612386766461e-01j,
+ 5.879995719101164e-01 - 8.088612386766461e-01j,
+ 5.879354086709576e-01 + 8.089078780868164e-01j,
+ 5.879354086709576e-01 - 8.089078780868164e-01j]
+ p2 = [-3.184805259081650e-01 + 4.206951906775851e-01j,
+ -3.184805259081650e-01 - 4.206951906775851e-01j,
+ 1.417279173459985e-01 + 7.903955262836452e-01j,
+ 1.417279173459985e-01 - 7.903955262836452e-01j,
+ 4.042881216964651e-01 + 8.309042239116594e-01j,
+ 4.042881216964651e-01 - 8.309042239116594e-01j,
+ 5.128964442789670e-01 + 8.229563236799665e-01j,
+ 5.128964442789670e-01 - 8.229563236799665e-01j,
+ 5.569614712822724e-01 + 8.155957702908510e-01j,
+ 5.569614712822724e-01 - 8.155957702908510e-01j,
+ 5.750478870161392e-01 + 8.118633973883931e-01j,
+ 5.750478870161392e-01 - 8.118633973883931e-01j,
+ 5.825314018170804e-01 + 8.101960910679270e-01j,
+ 5.825314018170804e-01 - 8.101960910679270e-01j,
+ 5.856397379751872e-01 + 8.094825218722543e-01j,
+ 5.856397379751872e-01 - 8.094825218722543e-01j,
+ 5.869326035251949e-01 + 8.091827531557583e-01j,
+ 5.869326035251949e-01 - 8.091827531557583e-01j,
+ 5.874697218855733e-01 + 8.090593298213502e-01j,
+ 5.874697218855733e-01 - 8.090593298213502e-01j,
+ 5.876904783532237e-01 + 8.090127161018823e-01j,
+ 5.876904783532237e-01 - 8.090127161018823e-01j,
+ 5.877753105317594e-01 + 8.090050577978136e-01j,
+ 5.877753105317594e-01 - 8.090050577978136e-01j]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 4.918081266957108e-02
+ xp_assert_close(_sort_cmplx(z, xp=xp),
+ _sort_cmplx(z2, xp=xp), rtol=1e-4)
+ xp_assert_close(_sort_cmplx(p, xp=xp),
+ _sort_cmplx(p2, xp=xp), rtol=1e-4)
+ assert math.isclose(k, k2, rel_tol=1e-3)
+
+ # high odd order
+ z, p, k = ellip(23, 1, 70, xp.asarray(0.5), 'high', output='zpk')
+ z2 = [9.999999999998661e-01,
+ 6.603717261750994e-01 + 7.509388678638675e-01j,
+ 6.603717261750994e-01 - 7.509388678638675e-01j,
+ 2.788635267510325e-01 + 9.603307416968041e-01j,
+ 2.788635267510325e-01 - 9.603307416968041e-01j,
+ 1.070215532544218e-01 + 9.942567008268131e-01j,
+ 1.070215532544218e-01 - 9.942567008268131e-01j,
+ 4.049427369978163e-02 + 9.991797705105507e-01j,
+ 4.049427369978163e-02 - 9.991797705105507e-01j,
+ 1.531059368627931e-02 + 9.998827859909265e-01j,
+ 1.531059368627931e-02 - 9.998827859909265e-01j,
+ 5.808061438534933e-03 + 9.999831330689181e-01j,
+ 5.808061438534933e-03 - 9.999831330689181e-01j,
+ 2.224277847754599e-03 + 9.999975262909676e-01j,
+ 2.224277847754599e-03 - 9.999975262909676e-01j,
+ 8.731857107534554e-04 + 9.999996187732845e-01j,
+ 8.731857107534554e-04 - 9.999996187732845e-01j,
+ 3.649057346914968e-04 + 9.999999334218996e-01j,
+ 3.649057346914968e-04 - 9.999999334218996e-01j,
+ 1.765538109802615e-04 + 9.999999844143768e-01j,
+ 1.765538109802615e-04 - 9.999999844143768e-01j,
+ 1.143655290967426e-04 + 9.999999934602630e-01j,
+ 1.143655290967426e-04 - 9.999999934602630e-01j]
+ p2 = [-6.322017026545028e-01,
+ -4.648423756662754e-01 + 5.852407464440732e-01j,
+ -4.648423756662754e-01 - 5.852407464440732e-01j,
+ -2.249233374627773e-01 + 8.577853017985717e-01j,
+ -2.249233374627773e-01 - 8.577853017985717e-01j,
+ -9.234137570557621e-02 + 9.506548198678851e-01j,
+ -9.234137570557621e-02 - 9.506548198678851e-01j,
+ -3.585663561241373e-02 + 9.821494736043981e-01j,
+ -3.585663561241373e-02 - 9.821494736043981e-01j,
+ -1.363917242312723e-02 + 9.933844128330656e-01j,
+ -1.363917242312723e-02 - 9.933844128330656e-01j,
+ -5.131505238923029e-03 + 9.975221173308673e-01j,
+ -5.131505238923029e-03 - 9.975221173308673e-01j,
+ -1.904937999259502e-03 + 9.990680819857982e-01j,
+ -1.904937999259502e-03 - 9.990680819857982e-01j,
+ -6.859439885466834e-04 + 9.996492201426826e-01j,
+ -6.859439885466834e-04 - 9.996492201426826e-01j,
+ -2.269936267937089e-04 + 9.998686250679161e-01j,
+ -2.269936267937089e-04 - 9.998686250679161e-01j,
+ -5.687071588789117e-05 + 9.999527573294513e-01j,
+ -5.687071588789117e-05 - 9.999527573294513e-01j,
+ -6.948417068525226e-07 + 9.999882737700173e-01j,
+ -6.948417068525226e-07 - 9.999882737700173e-01j]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 1.220910020289434e-02
+ xp_assert_close(_sort_cmplx(z, xp=xp),
+ _sort_cmplx(z2, xp=xp), rtol=1e-4)
+ xp_assert_close(_sort_cmplx(p, xp=xp),
+ _sort_cmplx(p2, xp=xp), rtol=1e-4)
+ assert math.isclose(k, k2, rel_tol=1e-3)
+
+ def test_bandpass(self, xp):
+ z, p, k = ellip(7, 1, 40, [0.07, 0.2], 'pass', output='zpk')
+ z2 = [-9.999999999999991e-01,
+ 6.856610961780020e-01 + 7.279209168501619e-01j,
+ 6.856610961780020e-01 - 7.279209168501619e-01j,
+ 7.850346167691289e-01 + 6.194518952058737e-01j,
+ 7.850346167691289e-01 - 6.194518952058737e-01j,
+ 7.999038743173071e-01 + 6.001281461922627e-01j,
+ 7.999038743173071e-01 - 6.001281461922627e-01j,
+ 9.999999999999999e-01,
+ 9.862938983554124e-01 + 1.649980183725925e-01j,
+ 9.862938983554124e-01 - 1.649980183725925e-01j,
+ 9.788558330548762e-01 + 2.045513580850601e-01j,
+ 9.788558330548762e-01 - 2.045513580850601e-01j,
+ 9.771155231720003e-01 + 2.127093189691258e-01j,
+ 9.771155231720003e-01 - 2.127093189691258e-01j]
+ p2 = [8.063992755498643e-01 + 5.858071374778874e-01j,
+ 8.063992755498643e-01 - 5.858071374778874e-01j,
+ 8.050395347071724e-01 + 5.639097428109795e-01j,
+ 8.050395347071724e-01 - 5.639097428109795e-01j,
+ 8.113124936559144e-01 + 4.855241143973142e-01j,
+ 8.113124936559144e-01 - 4.855241143973142e-01j,
+ 8.665595314082394e-01 + 3.334049560919331e-01j,
+ 8.665595314082394e-01 - 3.334049560919331e-01j,
+ 9.412369011968871e-01 + 2.457616651325908e-01j,
+ 9.412369011968871e-01 - 2.457616651325908e-01j,
+ 9.679465190411238e-01 + 2.228772501848216e-01j,
+ 9.679465190411238e-01 - 2.228772501848216e-01j,
+ 9.747235066273385e-01 + 2.178937926146544e-01j,
+ 9.747235066273385e-01 - 2.178937926146544e-01j]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 8.354782670263239e-03
+ xp_assert_close(_sort_cmplx(z, xp=xp),
+ _sort_cmplx(z2, xp=xp), rtol=1e-4)
+ xp_assert_close(_sort_cmplx(p, xp=xp),
+ _sort_cmplx(p2, xp=xp), rtol=1e-4)
+ assert math.isclose(k, k2, rel_tol=1e-3)
+
+ z, p, k = ellip(5, 1, 75, [90.5, 110.5], 'pass', True, 'zpk')
+ z2 = [-5.583607317695175e-14 + 1.433755965989225e+02j,
+ -5.583607317695175e-14 - 1.433755965989225e+02j,
+ 5.740106416459296e-14 + 1.261678754570291e+02j,
+ 5.740106416459296e-14 - 1.261678754570291e+02j,
+ -2.199676239638652e-14 + 6.974861996895196e+01j,
+ -2.199676239638652e-14 - 6.974861996895196e+01j,
+ -3.372595657044283e-14 + 7.926145989044531e+01j,
+ -3.372595657044283e-14 - 7.926145989044531e+01j,
+ 0]
+ p2 = [-8.814960004852743e-01 + 1.104124501436066e+02j,
+ -8.814960004852743e-01 - 1.104124501436066e+02j,
+ -2.477372459140184e+00 + 1.065638954516534e+02j,
+ -2.477372459140184e+00 - 1.065638954516534e+02j,
+ -3.072156842945799e+00 + 9.995404870405324e+01j,
+ -3.072156842945799e+00 - 9.995404870405324e+01j,
+ -2.180456023925693e+00 + 9.379206865455268e+01j,
+ -2.180456023925693e+00 - 9.379206865455268e+01j,
+ -7.230484977485752e-01 + 9.056598800801140e+01j,
+ -7.230484977485752e-01 - 9.056598800801140e+01j]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 3.774571622827070e-02
+ xp_assert_close(_sort_cmplx(z, xp=xp),
+ _sort_cmplx(z2, xp=xp), rtol=1e-4)
+ xp_assert_close(_sort_cmplx(p, xp=xp),
+ _sort_cmplx(p2, xp=xp), rtol=1e-6)
+ assert math.isclose(k, k2, rel_tol=1e-3)
+
+ def test_bandstop(self, xp):
+ z, p, k = ellip(8, 1, 65, [0.2, 0.4], 'stop', output='zpk')
+ z2 = [3.528578094286510e-01 + 9.356769561794296e-01j,
+ 3.528578094286510e-01 - 9.356769561794296e-01j,
+ 3.769716042264783e-01 + 9.262248159096587e-01j,
+ 3.769716042264783e-01 - 9.262248159096587e-01j,
+ 4.406101783111199e-01 + 8.976985411420985e-01j,
+ 4.406101783111199e-01 - 8.976985411420985e-01j,
+ 5.539386470258847e-01 + 8.325574907062760e-01j,
+ 5.539386470258847e-01 - 8.325574907062760e-01j,
+ 6.748464963023645e-01 + 7.379581332490555e-01j,
+ 6.748464963023645e-01 - 7.379581332490555e-01j,
+ 7.489887970285254e-01 + 6.625826604475596e-01j,
+ 7.489887970285254e-01 - 6.625826604475596e-01j,
+ 7.913118471618432e-01 + 6.114127579150699e-01j,
+ 7.913118471618432e-01 - 6.114127579150699e-01j,
+ 7.806804740916381e-01 + 6.249303940216475e-01j,
+ 7.806804740916381e-01 - 6.249303940216475e-01j]
+
+ p2 = [-1.025299146693730e-01 + 5.662682444754943e-01j,
+ -1.025299146693730e-01 - 5.662682444754943e-01j,
+ 1.698463595163031e-01 + 8.926678667070186e-01j,
+ 1.698463595163031e-01 - 8.926678667070186e-01j,
+ 2.750532687820631e-01 + 9.351020170094005e-01j,
+ 2.750532687820631e-01 - 9.351020170094005e-01j,
+ 3.070095178909486e-01 + 9.457373499553291e-01j,
+ 3.070095178909486e-01 - 9.457373499553291e-01j,
+ 7.695332312152288e-01 + 2.792567212705257e-01j,
+ 7.695332312152288e-01 - 2.792567212705257e-01j,
+ 8.083818999225620e-01 + 4.990723496863960e-01j,
+ 8.083818999225620e-01 - 4.990723496863960e-01j,
+ 8.066158014414928e-01 + 5.649811440393374e-01j,
+ 8.066158014414928e-01 - 5.649811440393374e-01j,
+ 8.062787978834571e-01 + 5.855780880424964e-01j,
+ 8.062787978834571e-01 - 5.855780880424964e-01j]
+ z2 = xp.asarray(z2, dtype=xp.complex128)
+ p2 = xp.asarray(p2, dtype=xp.complex128)
+ k2 = 2.068622545291259e-01
+ xp_assert_close(_sort_cmplx(z, xp=xp),
+ _sort_cmplx(z2, xp=xp), rtol=1e-6)
+ xp_assert_close(_sort_cmplx(p, xp=xp),
+ _sort_cmplx(p2, xp=xp), rtol=1e-5)
+ assert math.isclose(k, k2, rel_tol=1e-5)
+
+ @xfail_xp_backends("cupy", reason="inaccurate on CuPy")
+ def test_ba_output(self, xp):
+ # with transfer function conversion, without digital conversion
+ b, a = ellip(5, 1, 40, xp.asarray([201, 240]), 'stop', True)
+ b2 = [
+ 1.000000000000000e+00, 0, # Matlab: 1.743506051190569e-13,
+ 2.426561778314366e+05, 0, # Matlab: 3.459426536825722e-08,
+ 2.348218683400168e+10, 0, # Matlab: 2.559179747299313e-03,
+ 1.132780692872241e+15, 0, # Matlab: 8.363229375535731e+01,
+ 2.724038554089566e+19, 0, # Matlab: 1.018700994113120e+06,
+ 2.612380874940186e+23
+ ]
+ a2 = [
+ 1.000000000000000e+00, 1.337266601804649e+02,
+ 2.486725353510667e+05, 2.628059713728125e+07,
+ 2.436169536928770e+10, 1.913554568577315e+12,
+ 1.175208184614438e+15, 6.115751452473410e+16,
+ 2.791577695211466e+19, 7.241811142725384e+20,
+ 2.612380874940182e+23
+ ]
+ b2 = xp.asarray(b2, dtype=xp.float64)
+ a2 = xp.asarray(a2, dtype=xp.float64)
+ xp_assert_close(b, b2, rtol=1e-6)
+ xp_assert_close(a, a2, rtol=1e-4)
+
+ def test_fs_param(self):
+ for fs in (900, 900.1, 1234.567):
+ for N in (0, 1, 2, 3, 10):
+ for fc in (100, 100.1, 432.12345):
+ for btype in ('lp', 'hp'):
+ ba1 = ellip(N, 1, 20, fc, btype, fs=fs)
+ ba2 = ellip(N, 1, 20, fc/(fs/2), btype)
+ for ba1_, ba2_ in zip(ba1, ba2):
+ xp_assert_close(ba1_, ba2_)
+ for fc in ((100, 200), (100.1, 200.2), (321.123, 432.123)):
+ for btype in ('bp', 'bs'):
+ ba1 = ellip(N, 1, 20, fc, btype, fs=fs)
+ for seq in (list, tuple, array):
+ fcnorm = seq([f/(fs/2) for f in fc])
+ ba2 = ellip(N, 1, 20, fcnorm, btype)
+ for ba1_, ba2_ in zip(ba1, ba2):
+ xp_assert_close(ba1_, ba2_)
+
+ def test_fs_validation(self):
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ iirnotch(0.06, 30, fs=np.array([10, 20]))
+
+ with pytest.raises(ValueError, match="Sampling.*be none"):
+ iirnotch(0.06, 30, fs=None)
+
+
+def test_sos_consistency():
+ # Consistency checks of output='sos' for the specialized IIR filter
+ # design functions.
+ design_funcs = [(bessel, (0.1,)),
+ (butter, (0.1,)),
+ (cheby1, (45.0, 0.1)),
+ (cheby2, (0.087, 0.1)),
+ (ellip, (0.087, 45, 0.1))]
+ for func, args in design_funcs:
+ name = func.__name__
+
+ b, a = func(2, *args, output='ba')
+ sos = func(2, *args, output='sos')
+ xp_assert_close(sos, [np.hstack((b, a))], err_msg=f"{name}(2,...)")
+
+ zpk = func(3, *args, output='zpk')
+ sos = func(3, *args, output='sos')
+ xp_assert_close(sos, zpk2sos(*zpk), err_msg=f"{name}(3,...)")
+
+ zpk = func(4, *args, output='zpk')
+ sos = func(4, *args, output='sos')
+ xp_assert_close(sos, zpk2sos(*zpk), err_msg=f"{name}(4,...)")
+
+
+@make_xp_test_case(iirnotch)
+class TestIIRNotch:
+
+ def test_ba_output(self, xp):
+ # Compare coefficients with Matlab ones
+ # for the equivalent input:
+ b, a = iirnotch(0.06, 30, xp=xp)
+ b2 = xp.asarray([
+ 9.9686824e-01, -1.9584219e+00,
+ 9.9686824e-01
+ ])
+ a2 = xp.asarray([
+ 1.0000000e+00, -1.9584219e+00,
+ 9.9373647e-01
+ ])
+
+ xp_assert_close(b, b2, rtol=1e-8)
+ xp_assert_close(a, a2, rtol=1e-8)
+
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ @skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+ def test_frequency_response(self, xp):
+ # Get filter coefficients
+ b, a = iirnotch(0.3, 30, xp=xp)
+
+ # Get frequency response
+ w, h = freqz(b, a, 1000)
+
+ # Pick 5 point
+ p = [200, # w0 = 0.200
+ 295, # w0 = 0.295
+ 300, # w0 = 0.300
+ 305, # w0 = 0.305
+ 400] # w0 = 0.400
+
+ # Get frequency response correspondent to each of those points
+ hp = h[xp.asarray(p)]
+
+ # Check if the frequency response fulfill the specifications:
+ # hp[0] and hp[4] correspond to frequencies distant from
+ # w0 = 0.3 and should be close to 1
+ assert math.isclose(xp.abs(hp[0]), 1., rel_tol=1e-2)
+ assert math.isclose(xp.abs(hp[4]), 1., rel_tol=1e-2)
+
+ # hp[1] and hp[3] correspond to frequencies approximately
+ # on the edges of the passband and should be close to -3dB
+ assert math.isclose(xp.abs(hp[1]), 1 / math.sqrt(2), rel_tol=1e-2)
+ assert math.isclose(xp.abs(hp[3]), 1 / math.sqrt(2), rel_tol=1e-2)
+
+ # hp[2] correspond to the frequency that should be removed
+ # the frequency response should be very close to 0
+ assert math.isclose(xp.abs(hp[2]), 0.0, abs_tol=1e-10)
+
+ def test_errors(self):
+ # Exception should be raised if w0 > 1 or w0 <0
+ assert_raises(ValueError, iirnotch, w0=2, Q=30)
+ assert_raises(ValueError, iirnotch, w0=-1, Q=30)
+
+ # Exception should be raised if any of the parameters
+ # are not float (or cannot be converted to one)
+ assert_raises(ValueError, iirnotch, w0="blabla", Q=30)
+ assert_raises(TypeError, iirnotch, w0=-1, Q=[1, 2, 3])
+
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ @skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+ def test_fs_param(self, xp):
+ # Get filter coefficients
+ b, a = iirnotch(1500, 30, fs=10000, xp=xp)
+
+ # Get frequency response
+ w, h = freqz(b, a, 1000, fs=10000)
+
+ # Pick 5 point
+ p = [200, # w0 = 1000
+ 295, # w0 = 1475
+ 300, # w0 = 1500
+ 305, # w0 = 1525
+ 400] # w0 = 2000
+
+ # Get frequency response correspondent to each of those points
+ hp = h[xp.asarray(p)]
+
+ # Check if the frequency response fulfill the specifications:
+ # hp[0] and hp[4] correspond to frequencies distant from
+ # w0 = 1500 and should be close to 1
+ assert math.isclose(xp.abs(hp[0]), 1.0, rel_tol=1e-2)
+ assert math.isclose(xp.abs(hp[4]), 1.0, rel_tol=1e-2)
+
+ # hp[1] and hp[3] correspond to frequencies approximately
+ # on the edges of the passband and should be close to -3dB
+ assert math.isclose(xp.abs(hp[1]), 1 / math.sqrt(2), rel_tol=1e-2)
+ assert math.isclose(xp.abs(hp[3]), 1 / math.sqrt(2), rel_tol=1e-2)
+
+ # hp[2] correspond to the frequency that should be removed
+ # the frequency response should be very close to 0
+ assert math.isclose(xp.abs(hp[2]), 0.0, abs_tol=1e-10)
+
+
+@make_xp_test_case(iirpeak)
+class TestIIRPeak:
+
+ def test_ba_output(self, xp):
+ # Compare coefficients with Matlab ones
+ # for the equivalent input:
+ b, a = iirpeak(0.06, 30, xp=xp)
+ b2 = xp.asarray([
+ 3.131764229e-03, 0,
+ -3.131764229e-03
+ ])
+ a2 = xp.asarray([
+ 1.0000000e+00, -1.958421917e+00,
+ 9.9373647e-01
+ ])
+ xp_assert_close(b, b2, rtol=1e-8)
+ xp_assert_close(a, a2, rtol=1e-8)
+
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ @skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+ def test_frequency_response(self, xp):
+ # Get filter coefficients
+ b, a = iirpeak(0.3, 30, xp=xp)
+
+ # Get frequency response
+ w, h = freqz(b, a, 1000)
+
+ # Pick 5 point
+ p = [30, # w0 = 0.030
+ 295, # w0 = 0.295
+ 300, # w0 = 0.300
+ 305, # w0 = 0.305
+ 800] # w0 = 0.800
+
+ # Get frequency response correspondent to each of those points
+ hp = h[xp.asarray(p)]
+
+ # Check if the frequency response fulfill the specifications:
+ # hp[0] and hp[4] correspond to frequencies distant from
+ # w0 = 0.3 and should be close to 0
+ assert math.isclose(xp.abs(hp[0]), 0., abs_tol=1e-2)
+ assert math.isclose(xp.abs(hp[4]), 0., abs_tol=1e-2)
+
+ # hp[1] and hp[3] correspond to frequencies approximately
+ # on the edges of the passband and should be close to 10**(-3/20)
+ assert math.isclose(xp.abs(hp[1]), 1 / math.sqrt(2), rel_tol=1e-2)
+ assert math.isclose(xp.abs(hp[3]), 1 / math.sqrt(2), rel_tol=1e-2)
+
+ # hp[2] correspond to the frequency that should be retained and
+ # the frequency response should be very close to 1
+ assert math.isclose(xp.abs(hp[2]), 1.0, rel_tol=1e-10)
+
+ @skip_xp_backends(np_only=True)
+ def test_errors(self):
+ # Exception should be raised if w0 > 1 or w0 <0
+ assert_raises(ValueError, iirpeak, w0=2, Q=30)
+ assert_raises(ValueError, iirpeak, w0=-1, Q=30)
+
+ # Exception should be raised if any of the parameters
+ # are not float (or cannot be converted to one)
+ assert_raises(ValueError, iirpeak, w0="blabla", Q=30)
+ assert_raises(TypeError, iirpeak, w0=-1, Q=[1, 2, 3])
+
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ @skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+ def test_fs_param(self, xp):
+ # Get filter coefficients
+ b, a = iirpeak(1200, 30, fs=8000, xp=xp)
+
+ # Get frequency response
+ w, h = freqz(b, a, 1000, fs=8000)
+
+ # Pick 5 point
+ p = [30, # w0 = 120
+ 295, # w0 = 1180
+ 300, # w0 = 1200
+ 305, # w0 = 1220
+ 800] # w0 = 3200
+
+ # Get frequency response correspondent to each of those points
+ hp = h[xp.asarray(p)]
+
+ # Check if the frequency response fulfill the specifications:
+ # hp[0] and hp[4] correspond to frequencies distant from
+ # w0 = 1200 and should be close to 0
+ assert math.isclose(abs(hp[0]), 0.0, abs_tol=1e-2)
+ assert math.isclose(abs(hp[4]), 0.0, abs_tol=1e-2)
+
+ # hp[1] and hp[3] correspond to frequencies approximately
+ # on the edges of the passband and should be close to 10**(-3/20)
+ assert math.isclose(abs(hp[1]), 1 / math.sqrt(2), rel_tol=1e-2)
+ assert math.isclose(abs(hp[3]), 1 / math.sqrt(2), rel_tol=1e-2)
+
+ # hp[2] correspond to the frequency that should be retained and
+ # the frequency response should be very close to 1
+ assert math.isclose(abs(hp[2]), 1.0, rel_tol=1e-10)
+
+
+@pytest.mark.xfail(DEFAULT_F32, reason="wrong answers with torch/float32")
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+@make_xp_test_case(iircomb)
+class TestIIRComb:
+ # Test erroneous input cases
+ @skip_xp_backends(np_only=True)
+ def test_invalid_input(self):
+ # w0 is <= 0 or >= fs / 2
+ fs = 1000
+ for args in [(-fs, 30), (0, 35), (fs / 2, 40), (fs, 35)]:
+ with pytest.raises(ValueError, match='w0 must be between '):
+ iircomb(*args, fs=fs)
+
+ # fs is not divisible by w0
+ for args in [(120, 30), (157, 35)]:
+ with pytest.raises(ValueError, match='fs must be divisible '):
+ iircomb(*args, fs=fs)
+
+ # https://github.com/scipy/scipy/issues/14043#issuecomment-1107349140
+ # Previously, fs=44100, w0=49.999 was rejected, but fs=2,
+ # w0=49.999/int(44100/2) was accepted. Now it is rejected, too.
+ with pytest.raises(ValueError, match='fs must be divisible '):
+ iircomb(w0=49.999/int(44100/2), Q=30)
+
+ with pytest.raises(ValueError, match='fs must be divisible '):
+ iircomb(w0=49.999, Q=30, fs=44100)
+
+ # Filter type is not notch or peak
+ for args in [(0.2, 30, 'natch'), (0.5, 35, 'comb')]:
+ with pytest.raises(ValueError, match='ftype must be '):
+ iircomb(*args)
+
+ # Verify that the filter's frequency response contains a
+ # notch at the cutoff frequency
+ @pytest.mark.parametrize('ftype', ('notch', 'peak'))
+ def test_frequency_response(self, ftype, xp):
+ # Create a notching or peaking comb filter at 1000 Hz
+ b, a = iircomb(1000, 30, ftype=ftype, fs=10000, xp=xp)
+
+ # Compute the frequency response
+ freqs, response = freqz(b, a, 1000, fs=10000)
+
+ # Find the notch using argrelextrema
+ comb_points = argrelextrema(abs(_xp_copy_to_numpy(response)), np.less)[0]
+ comb_points = xp.asarray(comb_points)
+
+ # Verify that the first notch sits at 1000 Hz
+ comb1 = comb_points[0]
+ xp_assert_close(freqs[comb1], xp.asarray(1000.), check_0d=False)
+
+ # Verify pass_zero parameter
+ @pytest.mark.parametrize('ftype,pass_zero,peak,notch',
+ [('peak', True, 123.45, 61.725),
+ ('peak', False, 61.725, 123.45),
+ ('peak', None, 61.725, 123.45),
+ ('notch', None, 61.725, 123.45),
+ ('notch', True, 123.45, 61.725),
+ ('notch', False, 61.725, 123.45)])
+ def test_pass_zero(self, ftype, pass_zero, peak, notch, xp):
+ # Create a notching or peaking comb filter
+ b, a = iircomb(123.45, 30, ftype=ftype, fs=1234.5, pass_zero=pass_zero, xp=xp)
+
+ # Compute the frequency response
+ freqs, response = freqz(b, a, xp.asarray([peak, notch]), fs=1234.5)
+
+ # Verify that expected notches are notches and peaks are peaks
+ assert xp.abs(response[0]) > 0.99
+ assert xp.abs(response[1]) < 1e-10
+
+ # All built-in IIR filters are real, so should have perfectly
+ # symmetrical poles and zeros. Then ba representation (using
+ # numpy.poly) will be purely real instead of having negligible
+ # imaginary parts.
+ def test_iir_symmetry(self, xp):
+ b, a = iircomb(400, 30, fs=24000, xp=xp)
+ z, p, k = tf2zpk(b, a)
+ xp_assert_equal(_sort_cmplx(z, xp=xp), _sort_cmplx(xp.conj(z), xp=xp))
+ xp_assert_equal(_sort_cmplx(p, xp=xp), _sort_cmplx(xp.conj(p), xp=xp))
+ xp_assert_equal(k, xp.real(k))
+
+ isdtype = array_namespace(b).isdtype
+ assert isdtype(b.dtype, ('real floating', 'complex floating'))
+ assert isdtype(a.dtype, ('real floating', 'complex floating'))
+
+ # Verify filter coefficients with MATLAB's iircomb function
+ def test_ba_output(self, xp):
+ b_notch, a_notch = iircomb(60, 35, ftype='notch', fs=600, xp=xp)
+ b_notch2 = [0.957020174408697, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, -0.957020174408697]
+ a_notch2 = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, -0.914040348817395]
+ b_notch2 = xp.asarray(b_notch2)
+ a_notch2 = xp.asarray(a_notch2)
+ xp_assert_close(b_notch, b_notch2)
+ xp_assert_close(a_notch, a_notch2)
+
+ b_peak, a_peak = iircomb(60, 35, ftype='peak', fs=600, xp=xp)
+ b_peak2 = [0.0429798255913026, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, -0.0429798255913026]
+ a_peak2 = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0,
+ 0.0, 0.0, 0.0, 0.0, 0.914040348817395]
+ b_peak2 = xp.asarray(b_peak2)
+ a_peak2 = xp.asarray(a_peak2)
+ xp_assert_close(b_peak, b_peak2)
+ xp_assert_close(a_peak, a_peak2)
+
+ # Verify that https://github.com/scipy/scipy/issues/14043 is fixed
+ def test_nearest_divisor(self, xp):
+ # Create a notching comb filter
+ b, a = iircomb(50/int(44100/2), 50.0, ftype='notch', xp=xp)
+
+ # Compute the frequency response at an upper harmonic of 50
+ freqs, response = freqz(b, a, xp.asarray([22000]), fs=44100)
+
+ # Before bug fix, this would produce N = 881, so that 22 kHz was ~0 dB.
+ # Now N = 882 correctly and 22 kHz should be a notch <-220 dB
+ assert xp.abs(response[0]) < 1e-10
+
+ def test_fs_validation(self):
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ iircomb(1000, 30, fs=np.array([10, 20]))
+
+ with pytest.raises(ValueError, match="Sampling.*be none"):
+ iircomb(1000, 30, fs=None)
+
+
+class TestIIRDesign:
+
+ def test_exceptions(self):
+ with pytest.raises(ValueError, match="the same shape"):
+ iirdesign(0.2, [0.1, 0.3], 1, 40)
+ with pytest.raises(ValueError, match="the same shape"):
+ iirdesign(np.array([[0.3, 0.6], [0.3, 0.6]]),
+ np.array([[0.4, 0.5], [0.4, 0.5]]), 1, 40)
+
+ # discrete filter with non-positive frequency
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign(0, 0.5, 1, 40)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign(-0.1, 0.5, 1, 40)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign(0.1, 0, 1, 40)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign(0.1, -0.5, 1, 40)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([0, 0.3], [0.1, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([-0.1, 0.3], [0.1, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([0.1, 0], [0.1, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([0.1, -0.3], [0.1, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([0.1, 0.3], [0, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([0.1, 0.3], [-0.1, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([0.1, 0.3], [0.1, 0], 1, 40)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([0.1, 0.3], [0.1, -0.5], 1, 40)
+
+ # analog filter with negative frequency
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign(-0.1, 0.5, 1, 40, analog=True)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign(0.1, -0.5, 1, 40, analog=True)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([-0.1, 0.3], [0.1, 0.5], 1, 40, analog=True)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([0.1, -0.3], [0.1, 0.5], 1, 40, analog=True)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([0.1, 0.3], [-0.1, 0.5], 1, 40, analog=True)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirdesign([0.1, 0.3], [0.1, -0.5], 1, 40, analog=True)
+
+ # discrete filter with fs=None, freq > 1
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign(1, 0.5, 1, 40)
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign(1.1, 0.5, 1, 40)
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign(0.1, 1, 1, 40)
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign(0.1, 1.5, 1, 40)
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign([1, 0.3], [0.1, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign([1.1, 0.3], [0.1, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign([0.1, 1], [0.1, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign([0.1, 1.1], [0.1, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign([0.1, 0.3], [1, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign([0.1, 0.3], [1.1, 0.5], 1, 40)
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign([0.1, 0.3], [0.1, 1], 1, 40)
+ with pytest.raises(ValueError, match="must be less than 1"):
+ iirdesign([0.1, 0.3], [0.1, 1.5], 1, 40)
+
+ # discrete filter with fs>2, wp, ws < fs/2 must pass
+ iirdesign(100, 500, 1, 40, fs=2000)
+ iirdesign(500, 100, 1, 40, fs=2000)
+ iirdesign([200, 400], [100, 500], 1, 40, fs=2000)
+ iirdesign([100, 500], [200, 400], 1, 40, fs=2000)
+
+ # discrete filter with fs>2, freq > fs/2: this must raise
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign(1000, 400, 1, 40, fs=2000)
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign(1100, 500, 1, 40, fs=2000)
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign(100, 1000, 1, 40, fs=2000)
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign(100, 1100, 1, 40, fs=2000)
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign([1000, 400], [100, 500], 1, 40, fs=2000)
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign([1100, 400], [100, 500], 1, 40, fs=2000)
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign([200, 1000], [100, 500], 1, 40, fs=2000)
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign([200, 1100], [100, 500], 1, 40, fs=2000)
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign([200, 400], [1000, 500], 1, 40, fs=2000)
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign([200, 400], [1100, 500], 1, 40, fs=2000)
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign([200, 400], [100, 1000], 1, 40, fs=2000)
+ with pytest.raises(ValueError, match="must be less than fs/2"):
+ iirdesign([200, 400], [100, 1100], 1, 40, fs=2000)
+
+ with pytest.raises(ValueError, match="strictly inside stopband"):
+ iirdesign([0.1, 0.4], [0.5, 0.6], 1, 40)
+ with pytest.raises(ValueError, match="strictly inside stopband"):
+ iirdesign([0.5, 0.6], [0.1, 0.4], 1, 40)
+ with pytest.raises(ValueError, match="strictly inside stopband"):
+ iirdesign([0.3, 0.6], [0.4, 0.7], 1, 40)
+ with pytest.raises(ValueError, match="strictly inside stopband"):
+ iirdesign([0.4, 0.7], [0.3, 0.6], 1, 40)
+
+ def test_fs_validation(self):
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ iirfilter(1, 1, btype="low", fs=np.array([10, 20]))
+
+
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+@make_xp_test_case(iirfilter)
+class TestIIRFilter:
+
+ @pytest.mark.parametrize(
+ "func,ftype",
+ [
+ make_xp_pytest_param(butter, "butter"),
+ make_xp_pytest_param(bessel, "bessel"),
+ make_xp_pytest_param(cheby1, "cheby1"),
+ make_xp_pytest_param(cheby2, "cheby2"),
+ make_xp_pytest_param(ellip, "ellip"),
+ ]
+ )
+ def test_symmetry(self, func, ftype, xp):
+ # All built-in IIR filters are real, so should have perfectly
+ # symmetrical poles and zeros. Then ba representation (using
+ # numpy.poly) will be purely real instead of having negligible
+ # imaginary parts.
+ for N in range(1, 26):
+ z, p, k = iirfilter(N, xp.asarray(1.1), 1, 20, 'low', analog=True,
+ ftype=ftype, output='zpk')
+ xp_assert_close(_sort_cmplx(z, xp=xp), _sort_cmplx(xp.conj(z), xp=xp))
+ xp_assert_close(_sort_cmplx(p, xp=xp), _sort_cmplx(xp.conj(p), xp=xp))
+ assert complex(k).imag == 0
+
+ b, a = iirfilter(N, xp.asarray(1.1), 1, 20, 'low', analog=True,
+ ftype=ftype, output='ba')
+
+ isdtype = array_namespace(b).isdtype
+ assert isdtype(b.dtype, ('real floating', 'complex floating'))
+ assert isdtype(a.dtype, ('real floating', 'complex floating'))
+
+ @make_xp_test_case(bessel)
+ def test_int_inputs(self, xp):
+ # Using integer frequency arguments and large N should not produce
+ # numpy integers that wraparound to negative numbers
+ k = iirfilter(24, xp.asarray(100), btype='low', analog=True, ftype='bessel',
+ output='zpk')[2]
+ k2 = 9.999999999999989e+47
+ assert math.isclose(k, k2)
+ # if fs is specified then the normalization of Wn to have
+ # 0 <= Wn <= 1 should not cause an integer overflow
+ # the following line should not raise an exception
+ iirfilter(20, xp.asarray([1000000000, 1100000000]), btype='bp',
+ analog=False, fs=6250000000)
+
+ def test_invalid_wn_size(self):
+ # low and high have 1 Wn, band and stop have 2 Wn
+ assert_raises(ValueError, iirfilter, 1, [0.1, 0.9], btype='low')
+ assert_raises(ValueError, iirfilter, 1, [0.2, 0.5], btype='high')
+ assert_raises(ValueError, iirfilter, 1, 0.2, btype='bp')
+ assert_raises(ValueError, iirfilter, 1, 400, btype='bs', analog=True)
+
+ def test_invalid_wn_range(self):
+ # For digital filters, 0 <= Wn <= 1
+ assert_raises(ValueError, iirfilter, 1, 2, btype='low')
+ assert_raises(ValueError, iirfilter, 1, [0.5, 1], btype='band')
+ assert_raises(ValueError, iirfilter, 1, [0., 0.5], btype='band')
+ assert_raises(ValueError, iirfilter, 1, -1, btype='high')
+ assert_raises(ValueError, iirfilter, 1, [1, 2], btype='band')
+ assert_raises(ValueError, iirfilter, 1, [10, 20], btype='stop')
+
+ # analog=True with non-positive critical frequencies
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirfilter(2, 0, btype='low', analog=True)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirfilter(2, -1, btype='low', analog=True)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirfilter(2, [0, 100], analog=True)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirfilter(2, [-1, 100], analog=True)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirfilter(2, [10, 0], analog=True)
+ with pytest.raises(ValueError, match="must be greater than 0"):
+ iirfilter(2, [10, -1], analog=True)
+
+ @make_xp_test_case(butter)
+ def test_analog_sos(self, xp):
+ # first order Butterworth filter with Wn = 1 has tf 1/(s+1)
+ sos = xp.asarray([[0., 0., 1., 0., 1., 1.]])
+ sos2 = iirfilter(N=1, Wn=xp.asarray(1), btype='low', analog=True, output='sos')
+ assert_array_almost_equal(sos, sos2)
+
+ def test_wn1_ge_wn0(self):
+ # gh-15773: should raise error if Wn[0] >= Wn[1]
+ with pytest.raises(ValueError,
+ match=r"Wn\[0\] must be less than Wn\[1\]"):
+ iirfilter(2, [0.5, 0.5])
+ with pytest.raises(ValueError,
+ match=r"Wn\[0\] must be less than Wn\[1\]"):
+ iirfilter(2, [0.6, 0.5])
+
+
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+@make_xp_test_case(group_delay)
+class TestGroupDelay:
+ def test_identity_filter(self, xp):
+ w, gd = group_delay((1, xp.asarray(1)))
+ assert_array_almost_equal(w, xp.pi * xp.arange(512, dtype=w.dtype) / 512)
+ assert_array_almost_equal(gd, xp.zeros(512))
+
+ w, gd = group_delay((1, xp.asarray(1)), whole=True)
+ assert_array_almost_equal(w, 2 * xp.pi * xp.arange(512, dtype=w.dtype) / 512)
+ assert_array_almost_equal(gd, xp.zeros(512))
+
+ @xfail_xp_backends("cupy", reason="slightly inaccurate")
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ def test_fir(self, xp):
+ # Let's design linear phase FIR and check that the group delay
+ # is constant.
+ N = 100
+ b = firwin(N + 1, 0.1)
+ b = xp.asarray(b)
+ w, gd = group_delay((b, 1))
+ xp_assert_close(gd, xp.ones_like(gd)*(0.5 * N), rtol=5e-7)
+
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ def test_iir(self, xp):
+ # Let's design Butterworth filter and test the group delay at
+ # some points against MATLAB answer.
+ b, a = butter(4, 0.1)
+ b, a = map(xp.asarray, (b, a))
+ w = xp.linspace(0, xp.pi, num=10, endpoint=False)
+ w, gd = group_delay((b, a), w=w)
+ matlab_gd = xp.asarray([8.249313898506037, 11.958947880907104,
+ 2.452325615326005, 1.048918665702008,
+ 0.611382575635897, 0.418293269460578,
+ 0.317932917836572, 0.261371844762525,
+ 0.229038045801298, 0.212185774208521])
+ assert_array_almost_equal(gd, matlab_gd)
+
+ @xfail_xp_backends("cupy", reason="does not warn")
+ @xfail_xp_backends("torch", reason="does not warn")
+ def test_singular(self, xp):
+ # Let's create a filter with zeros and poles on the unit circle and
+ # check if warnings are raised at those frequencies.
+ z1 = np.exp(1j * 0.1 * pi)
+ z2 = np.exp(1j * 0.25 * pi)
+ p1 = np.exp(1j * 0.5 * pi)
+ p2 = np.exp(1j * 0.8 * pi)
+
+ b = np.convolve([1, -z1], [1, -z2])
+ a = np.convolve([1, -p1], [1, -p2])
+ b, a = map(xp.asarray, (b, a))
+
+ w = xp.asarray([0.1 * xp.pi, 0.25 * xp.pi, -0.5 * xp.pi, -0.8 * xp.pi])
+
+ with pytest.warns(UserWarning):
+ w, gd = group_delay((b, a), w=w)
+
+ def test_backward_compat(self, xp):
+ # For backward compatibility, test if None act as a wrapper for default
+ w1, gd1 = group_delay((1, xp.asarray(1)))
+ w2, gd2 = group_delay((1, xp.asarray(1)), None)
+ assert_array_almost_equal(w1, w2)
+ assert_array_almost_equal(gd1, gd2)
+
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ def test_fs_param(self, xp):
+ # Let's design Butterworth filter and test the group delay at
+ # some points against the normalized frequency answer.
+ b, a = butter(4, 4800, fs=96000)
+ b, a = map(xp.asarray, (b, a))
+ w = xp.linspace(0, 96000/2, num=10, endpoint=False)
+ w, gd = group_delay((b, a), w=w, fs=96000)
+ norm_gd = xp.asarray([8.249313898506037, 11.958947880907104,
+ 2.452325615326005, 1.048918665702008,
+ 0.611382575635897, 0.418293269460578,
+ 0.317932917836572, 0.261371844762525,
+ 0.229038045801298, 0.212185774208521])
+ assert_array_almost_equal(gd, norm_gd)
+
+ @skip_xp_backends(np_only=True, reason='numpy scalars')
+ def test_w_or_N_types(self, xp):
+ # Measure at 8 equally-spaced points
+ for N in (8, np.int8(8), np.int16(8), np.int32(8), np.int64(8),
+ np.array(8)):
+ w, gd = group_delay((1, 1), N)
+ assert_array_almost_equal(w, pi * np.arange(8) / 8)
+ assert_array_almost_equal(gd, np.zeros(8))
+
+ # Measure at frequency 8 rad/sec
+ for w in (8.0, 8.0+0j):
+ w_out, gd = group_delay((1, 1), w)
+ assert_array_almost_equal(w_out, [8])
+ assert_array_almost_equal(gd, [0])
+
+ @pytest.mark.xfail(DEFAULT_F32, reason="with torch/float32, the rtol is ~1e-7")
+ @xfail_xp_backends("cupy", reason="inaccurate")
+ def test_complex_coef(self, xp):
+ # gh-19586: handle complex coef TFs
+ #
+ # for g(z) = (alpha*z+1)/(1+conjugate(alpha)), group delay is
+ # given by function below.
+ #
+ # def gd_expr(w, alpha):
+ # num = 1j*(abs(alpha)**2-1)*np.exp(1j*w)
+ # den = (alpha*np.exp(1j*w)+1)*(np.exp(1j*w)+np.conj(alpha))
+ # return -np.imag(num/den)
+
+ # arbitrary non-real alpha
+ alpha = -0.6143077933232609 + 0.3355978770229421j
+ # 8 points from from -pi to pi
+ wref = xp.asarray([-3.141592653589793 ,
+ -2.356194490192345 ,
+ -1.5707963267948966,
+ -0.7853981633974483,
+ 0. ,
+ 0.7853981633974483,
+ 1.5707963267948966,
+ 2.356194490192345 ])
+ gdref = xp.asarray([0.18759548150354619,
+ 0.17999770352712252,
+ 0.23598047471879877,
+ 0.46539443069907194,
+ 1.9511492420564165 ,
+ 3.478129975138865 ,
+ 0.6228594960517333 ,
+ 0.27067831839471224])
+ b = xp.asarray([alpha, 1])
+ a = xp.asarray([1, alpha.conjugate()])
+ gdtest = group_delay((b, a), wref)[1]
+ # need nulp=14 for macOS arm64 wheel builds; added 2 for some
+ # robustness on other platforms.
+ xp_assert_close_nulp(gdtest, gdref, nulp=16)
+
+ def test_fs_validation(self):
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ group_delay((1, 1), fs=np.array([10, 20]))
+
+ with pytest.raises(ValueError, match="Sampling.*be none"):
+ group_delay((1, 1), fs=None)
+
+
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/11883")
+@make_xp_test_case(gammatone)
+class TestGammatone:
+ # Test erroneous input cases.
+ @skip_xp_backends(np_only=True)
+ def test_invalid_input(self, xp):
+ # Cutoff frequency is <= 0 or >= fs / 2.
+ fs = 16000
+ for args in [(-fs, 'iir'), (0, 'fir'), (fs / 2, 'iir'), (fs, 'fir')]:
+ with pytest.raises(ValueError, match='The frequency must be '
+ 'between '):
+ gammatone(*args, fs=fs)
+
+ # Filter type is not fir or iir
+ for args in [(440, 'fie'), (220, 'it')]:
+ with pytest.raises(ValueError, match='ftype must be '):
+ gammatone(*args, fs=fs)
+
+ # Order is <= 0 or > 24 for FIR filter.
+ for args in [(440, 'fir', -50), (220, 'fir', 0), (110, 'fir', 25),
+ (55, 'fir', 50)]:
+ with pytest.raises(ValueError, match='Invalid order: '):
+ gammatone(*args, numtaps=None, fs=fs)
+
+ # Verify that the filter's frequency response is approximately
+ # 1 at the cutoff frequency.
+ @pytest.mark.xfail(DEFAULT_F32, reason="wrong answer with torch/float32")
+ @xfail_xp_backends("cupy", reason="inaccurate")
+ def test_frequency_response(self, xp):
+ fs = 16000
+ ftypes = ['fir', 'iir']
+ for ftype in ftypes:
+ # Create a gammatone filter centered at 1000 Hz.
+ b, a = gammatone(1000, ftype, fs=fs, xp=xp)
+
+ # Calculate the frequency response.
+ freqs, response = freqz(_xp_copy_to_numpy(b), _xp_copy_to_numpy(a))
+
+ # Determine peak magnitude of the response
+ # and corresponding frequency.
+ response_max = np.max(np.abs(response))
+ freq_hz = freqs[np.argmax(np.abs(response))] / ((2 * np.pi) / fs)
+ response_max, freq_hz = map(xp.asarray, (response_max, freq_hz))
+
+ # Check that the peak magnitude is 1 and the frequency is 1000 Hz.
+ xp_assert_close(response_max,
+ xp.ones_like(response_max), rtol=1e-2, check_0d=False)
+ xp_assert_close(freq_hz,
+ 1000*xp.ones_like(freq_hz), rtol=1e-2, check_0d=False)
+
+ # All built-in IIR filters are real, so should have perfectly
+ # symmetrical poles and zeros. Then ba representation (using
+ # numpy.poly) will be purely real instead of having negligible
+ # imaginary parts.
+ def test_iir_symmetry(self, xp):
+ b, a = gammatone(440, 'iir', fs=24000, xp=xp)
+ z, p, k = tf2zpk(_xp_copy_to_numpy(b), _xp_copy_to_numpy(a))
+ z, p, k = map(xp.asarray, (z, p, k))
+ xp_assert_equal(_sort_cmplx(z, xp=xp), _sort_cmplx(xp.conj(z), xp=xp))
+ xp_assert_equal(_sort_cmplx(p, xp=xp), _sort_cmplx(xp.conj(p), xp=xp))
+ xp_assert_equal(k, xp.real(k))
+
+ isdtype = array_namespace(b).isdtype
+ assert isdtype(b.dtype, ('real floating', 'complex floating'))
+ assert isdtype(a.dtype, ('real floating', 'complex floating'))
+
+ # Verify FIR filter coefficients with the paper's
+ # Mathematica implementation
+ def test_fir_ba_output(self, xp):
+ b, _ = gammatone(15, 'fir', fs=1000, xp=xp)
+ b2 = [0.0, 2.2608075649884e-04,
+ 1.5077903981357e-03, 4.2033687753998e-03,
+ 8.1508962726503e-03, 1.2890059089154e-02,
+ 1.7833890391666e-02, 2.2392613558564e-02,
+ 2.6055195863104e-02, 2.8435872863284e-02,
+ 2.9293319149544e-02, 2.852976858014e-02,
+ 2.6176557156294e-02, 2.2371510270395e-02,
+ 1.7332485267759e-02]
+ b2 = xp.asarray(b2)
+ xp_assert_close(b, b2)
+
+ # Verify IIR filter coefficients with the paper's MATLAB implementation
+ def test_iir_ba_output(self, xp):
+ b, a = gammatone(440, 'iir', fs=16000, xp=xp)
+ b2 = [1.31494461367464e-06, -5.03391196645395e-06,
+ 7.00649426000897e-06, -4.18951968419854e-06,
+ 9.02614910412011e-07]
+ a2 = [1.0, -7.65646235454218,
+ 25.7584699322366, -49.7319214483238,
+ 60.2667361289181, -46.9399590980486,
+ 22.9474798808461, -6.43799381299034,
+ 0.793651554625368]
+ b2, a2 = map(xp.asarray, (b2, a2))
+ xp_assert_close(b, b2, atol=1e-10, rtol=5e-5)
+ xp_assert_close(a, a2, atol=1e-10, rtol=5e-5)
+
+ def test_fs_validation(self):
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ gammatone(440, 'iir', fs=np.asarray([10, 20]))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_fir_filter_design.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_fir_filter_design.py
new file mode 100644
index 0000000000000000000000000000000000000000..293361b6526b148ff3ec072d1d4e28e49ae07436
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_fir_filter_design.py
@@ -0,0 +1,868 @@
+import math
+import numpy as np
+
+from pytest import raises as assert_raises, warns as assert_warns
+import pytest
+
+import scipy._lib.array_api_extra as xpx
+import scipy.signal as signal
+from scipy._lib._array_api import (
+ xp_assert_close, xp_assert_equal, assert_almost_equal, assert_array_almost_equal,
+ array_namespace, xp_default_dtype, make_xp_test_case, _xp_copy_to_numpy
+)
+from scipy.fft import fft, fft2
+from scipy.signal import (kaiser_beta, kaiser_atten, kaiserord,
+ firwin, firwin2, freqz, remez, firls, minimum_phase, convolve2d, firwin_2d
+)
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+lazy_xp_modules = [signal]
+
+
+def test_kaiser_beta():
+ b = kaiser_beta(58.7)
+ assert_almost_equal(b, 0.1102 * 50.0)
+ b = kaiser_beta(22.0)
+ assert_almost_equal(b, 0.5842 + 0.07886)
+ b = kaiser_beta(21.0)
+ assert b == 0.0
+ b = kaiser_beta(10.0)
+ assert b == 0.0
+
+
+def test_kaiser_atten():
+ a = kaiser_atten(1, 1.0)
+ assert a == 7.95
+ a = kaiser_atten(2, 1/np.pi)
+ assert a == 2.285 + 7.95
+
+
+def test_kaiserord():
+ assert_raises(ValueError, kaiserord, 1.0, 1.0)
+ numtaps, beta = kaiserord(2.285 + 7.95 - 0.001, 1/np.pi)
+ assert (numtaps, beta) == (2, 0.0)
+
+
+@make_xp_test_case(firwin)
+class TestFirwin:
+
+ def check_response(self, h, expected_response, tol=.05):
+ xp = array_namespace(h)
+ N = h.shape[0]
+ alpha = 0.5 * (N-1)
+ m = xp.arange(0, N, dtype=xp_default_dtype(xp)) - alpha # time indices of taps
+ for freq, expected in expected_response:
+ actual = abs(xp.sum(h * xp.exp(-1j * xp.pi * m * freq)))
+ mse = abs(actual - expected)**2
+ assert mse < tol, f'response not as expected, mse={mse:g} > {tol:g}'
+
+ def test_response(self, xp):
+ N = 51
+ f = xp.asarray(.5)
+
+ # increase length just to try even/odd
+ h = firwin(N, f) # low-pass from 0 to f
+ self.check_response(h, [(.25,1), (.75,0)])
+
+ h = firwin(N+1, f, window='nuttall') # specific window
+ self.check_response(h, [(.25,1), (.75,0)])
+
+ h = firwin(N+2, f, pass_zero=False) # stop from 0 to f --> high-pass
+ self.check_response(h, [(.25,0), (.75,1)])
+
+ f1, f2, f3, f4 = .2, .4, .6, .8
+ h = firwin(N+3, [f1, f2], pass_zero=False) # band-pass filter
+ self.check_response(h, [(.1,0), (.3,1), (.5,0)])
+
+ h = firwin(N+4, [f1, f2]) # band-stop filter
+ self.check_response(h, [(.1,1), (.3,0), (.5,1)])
+
+ h = firwin(N+5, [f1, f2, f3, f4], pass_zero=False, scale=False)
+ self.check_response(h, [(.1,0), (.3,1), (.5,0), (.7,1), (.9,0)])
+
+ h = firwin(N+6, [f1, f2, f3, f4]) # multiband filter
+ self.check_response(h, [(.1,1), (.3,0), (.5,1), (.7,0), (.9,1)])
+
+ h = firwin(N+7, 0.1, width=.03) # low-pass
+ self.check_response(h, [(.05,1), (.75,0)])
+
+ h = firwin(N+8, 0.1, pass_zero=False) # high-pass
+ self.check_response(h, [(.05,0), (.75,1)])
+
+ def mse(self, h, bands):
+ """Compute mean squared error versus ideal response across frequency
+ band.
+ h -- coefficients
+ bands -- list of (left, right) tuples relative to 1==Nyquist of
+ passbands
+ """
+ xp = array_namespace(h)
+ h_np = _xp_copy_to_numpy(h)
+ w, H = freqz(h_np, worN=1024)
+ w, H = map(xp.asarray, (w, H))
+ f = w/xp.pi
+ passIndicator = xp.zeros(w.shape[0], dtype=xp.bool)
+ for left, right in bands:
+ passIndicator |= (f >= left) & (f < right)
+ Hideal = xp.where(passIndicator, xp.ones_like(passIndicator),
+ xp.zeros_like(passIndicator))
+ Hideal = xp.astype(Hideal, H.dtype)
+ mse = xp.mean(abs(abs(H)-Hideal)**2)
+ return mse
+
+ @pytest.mark.parametrize(
+ "cutoff,pass_zero,expected_response",
+ [
+ ([0.5], True, (0, 1)),
+ ([0.2, .6], False, (.4, 1)),
+ ([.5], False, (1, 1)),
+ ]
+ )
+ def test_scaling(self, cutoff, pass_zero, expected_response, xp):
+ """
+ For one lowpass, bandpass, and highpass example filter, this test
+ checks two things:
+ - the mean squared error over the frequency domain of the unscaled
+ filter is smaller than the scaled filter (true for rectangular
+ window)
+ - the response of the scaled filter is exactly unity at the center
+ of the first passband
+ """
+ N = 11
+ cutoff = xp.asarray(cutoff)
+ h = firwin(N, cutoff, scale=False, pass_zero=pass_zero, window='ones')
+ hs = firwin(N, cutoff, scale=True, pass_zero=pass_zero, window='ones')
+ if cutoff.shape[0] == 1:
+ if pass_zero:
+ cutoff = xp.concat([xp.asarray([0], dtype=cutoff.dtype), cutoff])
+ else:
+ cutoff = xp.concat([cutoff, xp.asarray([1], dtype=cutoff.dtype)])
+ msg = 'least squares violation'
+ assert self.mse(h, [cutoff]) < self.mse(hs, [cutoff]), msg
+ self.check_response(hs, [expected_response], 1e-12)
+
+ def test_fs_validation(self):
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ firwin(51, .5, fs=np.array([10, 20]))
+
+
+@make_xp_test_case(firwin)
+class TestFirWinMore:
+ """Different author, different style, different tests..."""
+
+ def test_lowpass(self, xp):
+ width = 0.04
+ ntaps, beta = kaiserord(120, width)
+ cutoff = xp.asarray(0.5)
+ kwargs = dict(cutoff=cutoff, window=('kaiser', beta), scale=False)
+ taps = firwin(ntaps, **kwargs)
+
+ # Check the symmetry of taps.
+ assert_array_almost_equal(taps[:ntaps//2], xp.flip(taps)[:ntaps//2])
+
+ # Check the gain at a few samples where
+ # we know it should be approximately 0 or 1.
+ freq_samples = xp.asarray([0.0, 0.25, 0.5-width/2, 0.5+width/2, 0.75, 1.0])
+ freq_samples = _xp_copy_to_numpy(freq_samples)
+ freqs, response = freqz(_xp_copy_to_numpy(taps), worN=np.pi*freq_samples)
+
+ assert_array_almost_equal(
+ xp.abs(xp.asarray(response)),
+ xp.asarray([1.0, 1.0, 1.0, 0.0, 0.0, 0.0]), decimal=5
+ )
+
+ taps_str = firwin(ntaps, pass_zero='lowpass', **kwargs)
+ xp_assert_close(taps, taps_str)
+
+ def test_highpass(self, xp):
+ width = 0.04
+ ntaps, beta = kaiserord(120, width)
+
+ # Ensure that ntaps is odd.
+ ntaps |= 1
+
+ cutoff = xp.asarray(0.5)
+ kwargs = dict(cutoff=cutoff, window=('kaiser', beta), scale=False)
+ taps = firwin(ntaps, pass_zero=False, **kwargs)
+
+ # Check the symmetry of taps.
+ assert_array_almost_equal(taps[:ntaps//2], xp.flip(taps)[:ntaps//2])
+
+ # Check the gain at a few samples where
+ # we know it should be approximately 0 or 1.
+ freq_samples = xp.asarray([0.0, 0.25, 0.5 - width/2, 0.5 + width/2, 0.75, 1.0])
+ freq_samples = _xp_copy_to_numpy(freq_samples)
+ freqs, response = freqz(_xp_copy_to_numpy(taps), worN=np.pi*freq_samples)
+
+ assert_array_almost_equal(xp.abs(xp.asarray(response)),
+ xp.asarray([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]), decimal=5)
+
+ taps_str = firwin(ntaps, pass_zero='highpass', **kwargs)
+ xp_assert_close(taps, taps_str)
+
+ def test_bandpass(self, xp):
+ width = 0.04
+ ntaps, beta = kaiserord(120, width)
+ kwargs = dict(
+ cutoff=xp.asarray([0.3, 0.7]), window=('kaiser', beta), scale=False
+ )
+ taps = firwin(ntaps, pass_zero=False, **kwargs)
+
+ # Check the symmetry of taps.
+ assert_array_almost_equal(taps[:ntaps//2], xp.flip(taps)[:ntaps//2])
+
+ # Check the gain at a few samples where
+ # we know it should be approximately 0 or 1.
+ freq_samples = xp.asarray([0.0, 0.2, 0.3 - width/2, 0.3 + width/2, 0.5,
+ 0.7 - width/2, 0.7 + width/2, 0.8, 1.0])
+ freq_samples = _xp_copy_to_numpy(freq_samples)
+ freqs, response = freqz(_xp_copy_to_numpy(taps), worN=np.pi*freq_samples)
+
+ assert_array_almost_equal(xp.abs(xp.asarray(response)),
+ xp.asarray([0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0]), decimal=5)
+
+ taps_str = firwin(ntaps, pass_zero='bandpass', **kwargs)
+ xp_assert_close(taps, taps_str)
+
+ def test_bandstop_multi(self, xp):
+ width = 0.04
+ ntaps, beta = kaiserord(120, width)
+ kwargs = dict(cutoff=xp.asarray([0.2, 0.5, 0.8]), window=('kaiser', beta),
+ scale=False)
+ taps = firwin(ntaps, **kwargs)
+
+ # Check the symmetry of taps.
+ assert_array_almost_equal(taps[:ntaps//2], xp.flip(taps)[:ntaps//2])
+
+ # Check the gain at a few samples where
+ # we know it should be approximately 0 or 1.
+ freq_samples = xp.asarray([0.0, 0.1, 0.2 - width/2, 0.2 + width/2, 0.35,
+ 0.5 - width/2, 0.5 + width/2, 0.65,
+ 0.8 - width/2, 0.8 + width/2, 0.9, 1.0])
+ freq_samples = _xp_copy_to_numpy(freq_samples)
+ freqs, response = freqz(_xp_copy_to_numpy(taps), worN=np.pi*freq_samples)
+
+ assert_array_almost_equal(
+ xp.abs(xp.asarray(response)),
+ xp.asarray([1.0, 1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0]),
+ decimal=5
+ )
+
+ taps_str = firwin(ntaps, pass_zero='bandstop', **kwargs)
+ xp_assert_close(taps, taps_str)
+
+ def test_fs_nyq(self, xp):
+ """Test the fs and nyq keywords."""
+ nyquist = 1000
+ width = 40.0
+ relative_width = width/nyquist
+ ntaps, beta = kaiserord(120, relative_width)
+ taps = firwin(ntaps, cutoff=xp.asarray([300, 700]), window=('kaiser', beta),
+ pass_zero=False, scale=False, fs=2*nyquist)
+
+ # Check the symmetry of taps.
+ assert_array_almost_equal(taps[:ntaps//2], xp.flip(taps)[:ntaps//2])
+
+ # Check the gain at a few samples where
+ # we know it should be approximately 0 or 1.
+ freq_samples = xp.asarray([0.0, 200, 300 - width/2, 300 + width/2, 500,
+ 700 - width/2, 700 + width/2, 800, 1000])
+ freq_samples = _xp_copy_to_numpy(freq_samples)
+ freqs, response = freqz(
+ _xp_copy_to_numpy(taps), worN=np.pi*freq_samples/nyquist
+ )
+
+ assert_array_almost_equal(xp.abs(xp.asarray(response)),
+ xp.asarray([0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 0.0, 0.0, 0.0]), decimal=5)
+
+ def test_array_cutoff(self, xp):
+ taps = firwin(3, xp.asarray([.1, .2]))
+ # smoke test against the value computed by scipy==1.5.2
+ xp_assert_close(
+ taps, xp.asarray([-0.00801395, 1.0160279, -0.00801395]), atol=1e-8
+ )
+
+ def test_bad_cutoff(self):
+ """Test that invalid cutoff argument raises ValueError."""
+ # cutoff values must be greater than 0 and less than 1.
+ assert_raises(ValueError, firwin, 99, -0.5)
+ assert_raises(ValueError, firwin, 99, 1.5)
+ # Don't allow 0 or 1 in cutoff.
+ assert_raises(ValueError, firwin, 99, [0, 0.5])
+ assert_raises(ValueError, firwin, 99, [0.5, 1])
+ # cutoff values must be strictly increasing.
+ assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.2])
+ assert_raises(ValueError, firwin, 99, [0.1, 0.5, 0.5])
+ # Must have at least one cutoff value.
+ assert_raises(ValueError, firwin, 99, [])
+ # 2D array not allowed.
+ assert_raises(ValueError, firwin, 99, [[0.1, 0.2],[0.3, 0.4]])
+ # cutoff values must be less than nyq.
+ assert_raises(ValueError, firwin, 99, 50.0, fs=80)
+ assert_raises(ValueError, firwin, 99, [10, 20, 30], fs=50)
+
+ def test_even_highpass_raises_value_error(self):
+ """Test that attempt to create a highpass filter with an even number
+ of taps raises a ValueError exception."""
+ assert_raises(ValueError, firwin, 40, 0.5, pass_zero=False)
+ assert_raises(ValueError, firwin, 40, [.25, 0.5])
+
+ def test_bad_pass_zero(self):
+ """Test degenerate pass_zero cases."""
+ with assert_raises(ValueError, match="^Parameter pass_zero='foo' not in "):
+ firwin(41, 0.5, pass_zero='foo')
+ with assert_raises(ValueError, match="^Parameter pass_zero=1.0 not in "):
+ firwin(41, 0.5, pass_zero=1.)
+ for pass_zero in ('lowpass', 'highpass'):
+ with assert_raises(ValueError, match='cutoff must have one'):
+ firwin(41, [0.5, 0.6], pass_zero=pass_zero)
+ for pass_zero in ('bandpass', 'bandstop'):
+ with assert_raises(ValueError, match='must have at least two'):
+ firwin(41, [0.5], pass_zero=pass_zero)
+
+ def test_fs_validation(self):
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ firwin2(51, .5, 1, fs=np.array([10, 20]))
+
+
+@make_xp_test_case(firwin2)
+class TestFirwin2:
+
+ def test_invalid_args(self):
+ # `freq` and `gain` have different lengths.
+ with assert_raises(ValueError, match='must be of same length'):
+ firwin2(50, [0, 0.5, 1], [0.0, 1.0])
+ # `nfreqs` is less than `ntaps`.
+ with assert_raises(ValueError, match='ntaps must be less than nfreqs'):
+ firwin2(50, [0, 0.5, 1], [0.0, 1.0, 1.0], nfreqs=33)
+ # Decreasing value in `freq`
+ with assert_raises(ValueError, match='must be nondecreasing'):
+ firwin2(50, [0, 0.5, 0.4, 1.0], [0, .25, .5, 1.0])
+ # Value in `freq` repeated more than once.
+ with assert_raises(ValueError, match='must not occur more than twice'):
+ firwin2(50, [0, .1, .1, .1, 1.0], [0.0, 0.5, 0.75, 1.0, 1.0])
+ # `freq` does not start at 0.0.
+ with assert_raises(ValueError, match='start with 0'):
+ firwin2(50, [0.5, 1.0], [0.0, 1.0])
+ # `freq` does not end at fs/2.
+ with assert_raises(ValueError, match='end with fs/2'):
+ firwin2(50, [0.0, 0.5], [0.0, 1.0])
+ # Value 0 is repeated in `freq`
+ with assert_raises(ValueError, match='0 must not be repeated'):
+ firwin2(50, [0.0, 0.0, 0.5, 1.0], [1.0, 1.0, 0.0, 0.0])
+ # Value fs/2 is repeated in `freq`
+ with assert_raises(ValueError, match='fs/2 must not be repeated'):
+ firwin2(50, [0.0, 0.5, 1.0, 1.0], [1.0, 1.0, 0.0, 0.0])
+ # Value in `freq` that is too close to a repeated number
+ with assert_raises(ValueError, match='cannot contain numbers '
+ 'that are too close'):
+ firwin2(50, [0.0, 0.5 - np.finfo(float).eps * 0.5, 0.5, 0.5, 1.0],
+ [1.0, 1.0, 1.0, 0.0, 0.0])
+
+ # Type II filter, but the gain at nyquist frequency is not zero.
+ with assert_raises(ValueError, match='Type II filter'):
+ firwin2(16, [0.0, 0.5, 1.0], [0.0, 1.0, 1.0])
+
+ # Type III filter, but the gains at nyquist and zero rate are not zero.
+ with assert_raises(ValueError, match='Type III filter'):
+ firwin2(17, [0.0, 0.5, 1.0], [0.0, 1.0, 1.0], antisymmetric=True)
+ with assert_raises(ValueError, match='Type III filter'):
+ firwin2(17, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0], antisymmetric=True)
+ with assert_raises(ValueError, match='Type III filter'):
+ firwin2(17, [0.0, 0.5, 1.0], [1.0, 1.0, 1.0], antisymmetric=True)
+
+ # Type IV filter, but the gain at zero rate is not zero.
+ with assert_raises(ValueError, match='Type IV filter'):
+ firwin2(16, [0.0, 0.5, 1.0], [1.0, 1.0, 0.0], antisymmetric=True)
+
+ def test01(self, xp):
+ width = 0.04
+ beta = 12.0
+ ntaps = 400
+ # Filter is 1 from w=0 to w=0.5, then decreases linearly from 1 to 0 as w
+ # increases from w=0.5 to w=1 (w=1 is the Nyquist frequency).
+ freq = xp.asarray([0.0, 0.5, 1.0])
+ gain = xp.asarray([1.0, 1.0, 0.0])
+ taps = firwin2(ntaps, freq, gain, window=('kaiser', beta))
+ freq_samples = xp.asarray([0.0, 0.25, 0.5 - width/2, 0.5 + width/2,
+ 0.75, 1.0 - width/2])
+ freq_samples = _xp_copy_to_numpy(freq_samples)
+ freqs, response = freqz(_xp_copy_to_numpy(taps), worN=np.pi*freq_samples)
+ assert_array_almost_equal(
+ xp.abs(xp.asarray(response)),
+ xp.asarray([1.0, 1.0, 1.0, 1.0 - width, 0.5, width]), decimal=5
+ )
+
+ @skip_xp_backends("jax.numpy", reason="immutable arrays")
+ def test02(self, xp):
+ width = 0.04
+ beta = 12.0
+ # ntaps must be odd for positive gain at Nyquist.
+ ntaps = 401
+ # An ideal highpass filter.
+ freq = xp.asarray([0.0, 0.5, 0.5, 1.0])
+ gain = xp.asarray([0.0, 0.0, 1.0, 1.0])
+ taps = firwin2(ntaps, freq, gain, window=('kaiser', beta))
+ freq_samples = xp.asarray([0.0, 0.25, 0.5 - width, 0.5 + width, 0.75, 1.0])
+ freq_samples = _xp_copy_to_numpy(freq_samples)
+ freqs, response = freqz(_xp_copy_to_numpy(taps), worN=np.pi*freq_samples)
+ assert_array_almost_equal(
+ xp.abs(xp.asarray(response)),
+ xp.asarray([0.0, 0.0, 0.0, 1.0, 1.0, 1.0]), decimal=5
+ )
+
+ @skip_xp_backends("jax.numpy", reason="immutable arrays")
+ def test03(self, xp):
+ width = 0.02
+ ntaps, beta = kaiserord(120, width)
+ # ntaps must be odd for positive gain at Nyquist.
+ ntaps = int(ntaps) | 1
+ freq = xp.asarray([0.0, 0.4, 0.4, 0.5, 0.5, 1.0])
+ gain = xp.asarray([1.0, 1.0, 0.0, 0.0, 1.0, 1.0])
+ taps = firwin2(ntaps, freq, gain, window=('kaiser', beta))
+ freq_samples = np.array([0.0, 0.4 - width, 0.4 + width, 0.45,
+ 0.5 - width, 0.5 + width, 0.75, 1.0])
+ freqs, response = freqz(_xp_copy_to_numpy(taps), worN=np.pi*freq_samples)
+ assert_array_almost_equal(
+ xp.abs(xp.asarray(response)),
+ xp.asarray([1.0, 1.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0]), decimal=5
+ )
+
+ @skip_xp_backends("jax.numpy", reason="immutable arrays")
+ def test04(self, xp):
+ """Test firwin2 when window=None."""
+ ntaps = 5
+ # Ideal lowpass: gain is 1 on [0,0.5], and 0 on [0.5, 1.0]
+ freq = xp.asarray([0.0, 0.5, 0.5, 1.0])
+ gain = xp.asarray([1.0, 1.0, 0.0, 0.0])
+
+ taps = firwin2(ntaps, freq, gain, window=None, nfreqs=8193)
+ alpha = 0.5 * (ntaps - 1)
+ m = xp.arange(0, ntaps, dtype=freq.dtype) - alpha
+ h = 0.5 * xpx.sinc(0.5 * m)
+ assert_array_almost_equal(h, taps)
+
+ def test05(self, xp):
+ """Test firwin2 for calculating Type IV filters"""
+ ntaps = 1500
+
+ freq = xp.asarray([0.0, 1.0])
+ gain = xp.asarray([0.0, 1.0])
+ taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True)
+
+ flip = array_namespace(freq).flip
+ dec = {'decimal': 4.5} if xp_default_dtype(xp) == xp.float32 else {}
+ assert_array_almost_equal(taps[: ntaps // 2], flip(-taps[ntaps // 2:]), **dec)
+
+ freqs, response = freqz(_xp_copy_to_numpy(taps), worN=2048)
+ freqs, response = map(xp.asarray, (freqs, response))
+ assert_array_almost_equal(xp.abs(response), freqs / xp.pi, decimal=4)
+
+ @skip_xp_backends("jax.numpy", reason="immutable arrays")
+ def test06(self, xp):
+ """Test firwin2 for calculating Type III filters"""
+ ntaps = 1501
+
+ freq = xp.asarray([0.0, 0.5, 0.55, 1.0])
+ gain = xp.asarray([0.0, 0.5, 0.0, 0.0])
+ taps = firwin2(ntaps, freq, gain, window=None, antisymmetric=True)
+ assert taps[ntaps // 2] == 0.0
+
+ flip = array_namespace(freq).flip
+ dec = {'decimal': 4.5} if xp_default_dtype(xp) == xp.float32 else {}
+ assert_array_almost_equal(taps[: ntaps // 2],
+ flip(-taps[ntaps // 2 + 1:]), **dec
+ )
+
+ freqs, response1 = freqz(_xp_copy_to_numpy(taps), worN=2048)
+ response2 = xp.asarray(
+ np.interp(freqs / np.pi, _xp_copy_to_numpy(freq), _xp_copy_to_numpy(gain))
+ )
+ assert_array_almost_equal(xp.abs(xp.asarray(response1)), response2, decimal=3)
+
+ def test_fs_nyq(self, xp):
+ taps1 = firwin2(80, xp.asarray([0.0, 0.5, 1.0]), xp.asarray([1.0, 1.0, 0.0]))
+ taps2 = firwin2(80, xp.asarray([0.0, 30.0, 60.0]), xp.asarray([1.0, 1.0, 0.0]),
+ fs=120.0)
+ assert_array_almost_equal(taps1, taps2)
+
+ def test_tuple(self):
+ taps1 = firwin2(150, (0.0, 0.5, 0.5, 1.0), (1.0, 1.0, 0.0, 0.0))
+ taps2 = firwin2(150, [0.0, 0.5, 0.5, 1.0], [1.0, 1.0, 0.0, 0.0])
+ assert_array_almost_equal(taps1, taps2)
+
+ @skip_xp_backends("jax.numpy", reason="immutable arrays")
+ def test_input_modyfication(self, xp):
+ freq1 = xp.asarray([0.0, 0.5, 0.5, 1.0])
+ freq2 = xp.asarray(freq1)
+ firwin2(80, freq1, xp.asarray([1.0, 1.0, 0.0, 0.0]))
+ xp_assert_equal(freq1, freq2)
+
+
+@make_xp_test_case(remez)
+class TestRemez:
+
+ def test_bad_args(self):
+ assert_raises(ValueError, remez, 11, [0.1, 0.4], [1], type='pooka')
+
+ def test_hilbert(self):
+ N = 11 # number of taps in the filter
+ a = 0.1 # width of the transition band
+
+ # design an unity gain hilbert bandpass filter from w to 0.5-w
+ h = remez(11, [a, 0.5-a], [1], type='hilbert')
+
+ # make sure the filter has correct # of taps
+ assert len(h) == N, "Number of Taps"
+
+ # make sure it is type III (anti-symmetric tap coefficients)
+ assert_array_almost_equal(h[:(N-1)//2], -h[:-(N-1)//2-1:-1])
+
+ # Since the requested response is symmetric, all even coefficients
+ # should be zero (or in this case really small)
+ assert (abs(h[1::2]) < 1e-15).all(), "Even Coefficients Equal Zero"
+
+ # now check the frequency response
+ w, H = freqz(h, 1)
+ f = w/2/np.pi
+ Hmag = abs(H)
+
+ # should have a zero at 0 and pi (in this case close to zero)
+ assert (Hmag[[0, -1]] < 0.02).all(), "Zero at zero and pi"
+
+ # check that the pass band is close to unity
+ idx = np.logical_and(f > a, f < 0.5-a)
+ assert (abs(Hmag[idx] - 1) < 0.015).all(), "Pass Band Close To Unity"
+
+ def test_compare(self, xp):
+ # test comparison to MATLAB
+ k = [0.024590270518440, -0.041314581814658, -0.075943803756711,
+ -0.003530911231040, 0.193140296954975, 0.373400753484939,
+ 0.373400753484939, 0.193140296954975, -0.003530911231040,
+ -0.075943803756711, -0.041314581814658, 0.024590270518440]
+ h = remez(12, xp.asarray([0, 0.3, 0.5, 1]), xp.asarray([1, 0]), fs=2.)
+ atol_arg = {'atol': 1e-8} if xp_default_dtype(xp) == xp.float32 else {}
+ xp_assert_close(h, xp.asarray(k, dtype=xp.float64), **atol_arg)
+
+ h = [-0.038976016082299, 0.018704846485491, -0.014644062687875,
+ 0.002879152556419, 0.016849978528150, -0.043276706138248,
+ 0.073641298245579, -0.103908158578635, 0.129770906801075,
+ -0.147163447297124, 0.153302248456347, -0.147163447297124,
+ 0.129770906801075, -0.103908158578635, 0.073641298245579,
+ -0.043276706138248, 0.016849978528150, 0.002879152556419,
+ -0.014644062687875, 0.018704846485491, -0.038976016082299]
+ atol_arg = {'atol': 3e-8} if xp_default_dtype(xp) == xp.float32 else {}
+ xp_assert_close(
+ remez(21, xp.asarray([0, 0.8, 0.9, 1]), xp.asarray([0, 1]), fs=2.),
+ xp.asarray(h, dtype=xp.float64), **atol_arg
+ )
+
+ def test_fs_validation(self):
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ remez(11, .1, 1, fs=np.array([10, 20]))
+
+ def test_gh_23266(self, xp):
+ bands = xp.asarray([0.0, 0.2, 0.3, 0.5])
+ desired = xp.asarray([1.0, 0.0])
+ weight = xp.asarray([1.0, 2.0])
+ remez(21, bands, desired, weight=weight)
+
+
+@make_xp_test_case(firls)
+class TestFirls:
+
+ def test_bad_args(self):
+ # even numtaps
+ assert_raises(ValueError, firls, 10, [0.1, 0.2], [0, 0])
+ # odd bands
+ assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.4], [0, 0, 0])
+ # len(bands) != len(desired)
+ assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.4], [0, 0, 0])
+ # non-monotonic bands
+ assert_raises(ValueError, firls, 11, [0.2, 0.1], [0, 0])
+ assert_raises(ValueError, firls, 11, [0.1, 0.2, 0.3, 0.3], [0] * 4)
+ assert_raises(ValueError, firls, 11, [0.3, 0.4, 0.1, 0.2], [0] * 4)
+ assert_raises(ValueError, firls, 11, [0.1, 0.3, 0.2, 0.4], [0] * 4)
+ # negative desired
+ assert_raises(ValueError, firls, 11, [0.1, 0.2], [-1, 1])
+ # len(weight) != len(pairs)
+ assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], weight=[1, 2])
+ # negative weight
+ assert_raises(ValueError, firls, 11, [0.1, 0.2], [0, 0], weight=[-1])
+
+ @skip_xp_backends("dask.array", reason="dask fancy indexing shape=(nan,)")
+ def test_firls(self, xp):
+ N = 11 # number of taps in the filter
+ a = 0.1 # width of the transition band
+
+ # design a halfband symmetric low-pass filter
+ h = firls(11, xp.asarray([0, a, 0.5 - a, 0.5]), xp.asarray([1, 1, 0, 0]),
+ fs=1.0)
+
+ # make sure the filter has correct # of taps
+ assert h.shape[0] == N
+
+ # make sure it is symmetric
+ midx = (N-1) // 2
+ flip = array_namespace(h).flip
+ assert_array_almost_equal(h[:midx], flip(h[midx+1:])) # h[:-midx-1:-1])
+
+ # make sure the center tap is 0.5
+ assert math.isclose(h[midx], 0.5, abs_tol=1e-8)
+
+ # For halfband symmetric, odd coefficients (except the center)
+ # should be zero (really small)
+ hodd = xp.stack((h[1:midx:2], h[-midx+1::2]))
+ assert_array_almost_equal(hodd, xp.zeros_like(hodd))
+
+ # now check the frequency response
+ w, H = freqz(_xp_copy_to_numpy(h), 1)
+ w, H = xp.asarray(w), xp.asarray(H)
+ f = w/2/xp.pi
+ Hmag = xp.abs(H)
+
+ # check that the pass band is close to unity
+ idx = xp.logical_and(f > 0, f < a)
+ assert_array_almost_equal(Hmag[idx], xp.ones_like(Hmag[idx]), decimal=3)
+
+ # check that the stop band is close to zero
+ idx = xp.logical_and(f > 0.5 - a, f < 0.5)
+ assert_array_almost_equal(Hmag[idx], xp.zeros_like(Hmag[idx]), decimal=3)
+
+ def test_compare(self, xp):
+ # compare to OCTAVE output
+ taps = firls(9, xp.asarray([0, 0.5, 0.55, 1]),
+ xp.asarray([1, 1, 0, 0]), weight=xp.asarray([1, 2]))
+ # >> taps = firls(8, [0 0.5 0.55 1], [1 1 0 0], [1, 2]);
+ known_taps = [-6.26930101730182e-04, -1.03354450635036e-01,
+ -9.81576747564301e-03, 3.17271686090449e-01,
+ 5.11409425599933e-01, 3.17271686090449e-01,
+ -9.81576747564301e-03, -1.03354450635036e-01,
+ -6.26930101730182e-04]
+ atol_arg = {'atol': 5e-8} if xp_default_dtype(xp) == xp.float32 else {}
+ known_taps = xp.asarray(known_taps, dtype=xp.float64)
+ xp_assert_close(taps, known_taps, **atol_arg)
+
+ # compare to MATLAB output
+ taps = firls(11, xp.asarray([0, 0.5, 0.5, 1]),
+ xp.asarray([1, 1, 0, 0]), weight=xp.asarray([1, 2]))
+ # >> taps = firls(10, [0 0.5 0.5 1], [1 1 0 0], [1, 2]);
+ known_taps = [
+ 0.058545300496815, -0.014233383714318, -0.104688258464392,
+ 0.012403323025279, 0.317930861136062, 0.488047220029700,
+ 0.317930861136062, 0.012403323025279, -0.104688258464392,
+ -0.014233383714318, 0.058545300496815]
+ known_taps = xp.asarray(known_taps, dtype=xp.float64)
+ atol_arg = {'atol': 3e-8} if xp_default_dtype(xp) == xp.float32 else {}
+ xp_assert_close(taps, known_taps, **atol_arg)
+
+ # With linear changes:
+ taps = firls(7, xp.asarray((0, 1, 2, 3, 4, 5)),
+ xp.asarray([1, 0, 0, 1, 1, 0]), fs=20)
+ # >> taps = firls(6, [0, 0.1, 0.2, 0.3, 0.4, 0.5], [1, 0, 0, 1, 1, 0])
+ known_taps = [
+ 1.156090832768218, -4.1385894727395849, 7.5288619164321826,
+ -8.5530572592947856, 7.5288619164321826, -4.1385894727395849,
+ 1.156090832768218]
+ known_taps = xp.asarray(known_taps, dtype=xp.float64)
+ xp_assert_close(taps, known_taps)
+
+ def test_rank_deficient(self, xp):
+ # solve() runs but warns (only sometimes, so here we don't use match)
+ x = firls(21, xp.asarray([0, 0.1, 0.9, 1]), xp.asarray([1, 1, 0, 0]))
+ w, h = freqz(_xp_copy_to_numpy(x), fs=2.)
+ w, h = map(xp.asarray, (w, h))
+ absh2 = xp.abs(h[:2])
+ xp_assert_close(absh2, xp.ones_like(absh2), atol=1e-5)
+ absh2 = xp.abs(h[-2:])
+ xp_assert_close(absh2, xp.zeros_like(absh2), atol=1e-6, rtol=1e-7)
+ # switch to pinvh (tolerances could be higher with longer
+ # filters, but using shorter ones is faster computationally and
+ # the idea is the same)
+ x = firls(101, xp.asarray([0, 0.01, 0.99, 1]), xp.asarray([1, 1, 0, 0]))
+ w, h = freqz(_xp_copy_to_numpy(x), fs=2.)
+ w, h = map(xp.asarray, (w, h))
+ mask = xp.asarray(w < 0.01)
+ h = xp.asarray(h)
+ assert xp.sum(xp.astype(mask, xp.int64)) > 3
+ habs = xp.abs(h[mask])
+ xp_assert_close(habs, xp.ones_like(habs), atol=1e-4)
+ mask = xp.asarray(w > 0.99)
+ assert xp.sum(xp.astype(mask, xp.int64)) > 3
+ habs = xp.abs(h[mask])
+ xp_assert_close(habs, xp.zeros_like(habs), atol=1e-4)
+
+ def test_fs_validation(self):
+ with pytest.raises(ValueError, match="Sampling.*single scalar"):
+ firls(11, .1, 1, fs=np.array([10, 20]))
+
+@make_xp_test_case(minimum_phase)
+class TestMinimumPhase:
+
+ def test_bad_args(self):
+ # not enough taps
+ assert_raises(ValueError, minimum_phase, [1.])
+ assert_raises(ValueError, minimum_phase, [1., 1.])
+ assert_raises(ValueError, minimum_phase, np.full(10, 1j))
+ assert_raises((ValueError, TypeError), minimum_phase, 'foo')
+ assert_raises(ValueError, minimum_phase, np.ones(10), n_fft=8)
+ assert_raises(ValueError, minimum_phase, np.ones(10), method='foo')
+ assert_warns(RuntimeWarning, minimum_phase, np.arange(3))
+ with pytest.raises(ValueError, match="is only supported when"):
+ minimum_phase(np.ones(3), method='hilbert', half=False)
+
+ def test_homomorphic(self):
+ # check that it can recover frequency responses of arbitrary
+ # linear-phase filters
+
+ # for some cases we can get the actual filter back
+ h = [1, -1]
+ h_new = minimum_phase(np.convolve(h, h[::-1]))
+ xp_assert_close(h_new, np.asarray(h, dtype=np.float64), rtol=0.05)
+
+ # but in general we only guarantee we get the magnitude back
+ rng = np.random.RandomState(0)
+ for n in (2, 3, 10, 11, 15, 16, 17, 20, 21, 100, 101):
+ h = rng.randn(n)
+ h_linear = np.convolve(h, h[::-1])
+ h_new = minimum_phase(h_linear)
+ xp_assert_close(np.abs(fft(h_new)), np.abs(fft(h)), rtol=1e-4)
+ h_new = minimum_phase(h_linear, half=False)
+ assert len(h_linear) == len(h_new)
+ xp_assert_close(np.abs(fft(h_new)), np.abs(fft(h_linear)), rtol=1e-4)
+
+ @skip_xp_backends("dask.array", reason="too slow")
+ @make_xp_test_case(signal.hilbert)
+ def test_hilbert(self, xp):
+ # compare to MATLAB output of reference implementation
+
+ # f=[0 0.3 0.5 1];
+ # a=[1 1 0 0];
+ # h=remez(11,f,a);
+ h = remez(12, [0, 0.3, 0.5, 1], [1, 0], fs=2.)
+ k = [0.349585548646686, 0.373552164395447, 0.326082685363438,
+ 0.077152207480935, -0.129943946349364, -0.059355880509749]
+ h = xp.asarray(h)
+ k = xp.asarray(k, dtype=xp.float64)
+ m = minimum_phase(h, 'hilbert')
+ xp_assert_close(m, k, rtol=5e-3)
+
+ # f=[0 0.8 0.9 1];
+ # a=[0 0 1 1];
+ # h=remez(20,f,a);
+ h = remez(21, [0, 0.8, 0.9, 1], [0, 1], fs=2.)
+ k = [0.232486803906329, -0.133551833687071, 0.151871456867244,
+ -0.157957283165866, 0.151739294892963, -0.129293146705090,
+ 0.100787844523204, -0.065832656741252, 0.035361328741024,
+ -0.014977068692269, -0.158416139047557]
+ h = xp.asarray(h)
+ k = xp.asarray(k, dtype=xp.float64)
+ m = minimum_phase(h, 'hilbert', n_fft=2**19)
+ xp_assert_close(m, k, rtol=2e-3)
+
+
+class Testfirwin_2d:
+ def test_invalid_args(self):
+ with pytest.raises(ValueError,
+ match="hsize must be a 2-element tuple or list"):
+ firwin_2d((50,), window=(("kaiser", 5.0), "boxcar"), fc=0.4)
+
+ with pytest.raises(ValueError,
+ match="window must be a 2-element tuple or list"):
+ firwin_2d((51, 51), window=("hamming",), fc=0.5)
+
+ with pytest.raises(ValueError,
+ match="window must be a 2-element tuple or list"):
+ firwin_2d((51, 51), window="invalid_window", fc=0.5)
+
+ def test_filter_design(self):
+ hsize = (51, 51)
+ window = (("kaiser", 8.0), ("kaiser", 8.0))
+ fc = 0.4
+ taps_kaiser = firwin_2d(hsize, window, fc=fc)
+ assert taps_kaiser.shape == (51, 51)
+
+ window = ("hamming", "hamming")
+ taps_hamming = firwin_2d(hsize, window, fc=fc)
+ assert taps_hamming.shape == (51, 51)
+
+ def test_impulse_response(self):
+ hsize = (31, 31)
+ window = ("hamming", "hamming")
+ fc = 0.4
+ taps = firwin_2d(hsize, window, fc=fc)
+
+ impulse = np.zeros((63, 63))
+ impulse[31, 31] = 1
+
+ response = convolve2d(impulse, taps, mode='same')
+
+ expected_response = taps
+ xp_assert_close(response[16:47, 16:47], expected_response, rtol=1e-5)
+
+ def test_frequency_response(self):
+ """Compare 1d and 2d frequency response. """
+ hsize = (31, 31)
+ windows = ("hamming", "hamming")
+ fc = 0.4
+ taps_1d = firwin(numtaps=hsize[0], cutoff=fc, window=windows[0])
+ taps_2d = firwin_2d(hsize, windows, fc=fc)
+
+ f_resp_1d = fft(taps_1d)
+ f_resp_2d = fft2(taps_2d)
+
+ xp_assert_close(f_resp_2d[0, :], f_resp_1d,
+ err_msg='DC Gain at (0, f1) is not unity!')
+ xp_assert_close(f_resp_2d[:, 0], f_resp_1d,
+ err_msg='DC Gain at (f0, 0) is not unity!')
+ xp_assert_close(f_resp_2d, np.outer(f_resp_1d, f_resp_1d),
+ atol=np.finfo(f_resp_2d.dtype).resolution,
+ err_msg='2d frequency response is not product of 1d responses')
+
+ def test_symmetry(self):
+ hsize = (51, 51)
+ window = ("hamming", "hamming")
+ fc = 0.4
+ taps = firwin_2d(hsize, window, fc=fc)
+ xp_assert_close(taps, np.flip(taps), rtol=1e-5)
+
+ def test_circular_symmetry(self):
+ hsize = (51, 51)
+ window = "hamming"
+ taps = firwin_2d(hsize, window, circular=True, fc=0.5)
+ center = hsize[0] // 2
+ for i in range(hsize[0]):
+ for j in range(hsize[1]):
+ xp_assert_close(taps[i, j],
+ taps[center - (i - center), center - (j - center)],
+ rtol=1e-5)
+
+ def test_edge_case_circular(self):
+ hsize = (3, 3)
+ window = "hamming"
+ taps_small = firwin_2d(hsize, window, circular=True, fc=0.5)
+ assert taps_small.shape == (3, 3)
+
+ hsize = (101, 101)
+ taps_large = firwin_2d(hsize, window, circular=True, fc=0.5)
+ assert taps_large.shape == (101, 101)
+
+ def test_known_result(self):
+ hsize = (5, 5)
+ window = ('kaiser', 8.0)
+ fc = 0.1
+ fs = 2
+
+ row_filter = firwin(hsize[0], cutoff=fc, window=window, fs=fs)
+ col_filter = firwin(hsize[1], cutoff=fc, window=window, fs=fs)
+ known_result = np.outer(row_filter, col_filter)
+
+ taps = firwin_2d(hsize, (window, window), fc=fc)
+ assert taps.shape == known_result.shape, (
+ f"Shape mismatch: {taps.shape} vs {known_result.shape}"
+ )
+ assert np.allclose(taps, known_result, rtol=1e-1), (
+ f"Filter shape mismatch: {taps} vs {known_result}"
+ )
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_ltisys.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_ltisys.py
new file mode 100644
index 0000000000000000000000000000000000000000..d8c4cde919d51ecc998405999a270a6733803377
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_ltisys.py
@@ -0,0 +1,1245 @@
+import warnings
+from types import GenericAlias
+
+import numpy as np
+import pytest
+from pytest import raises as assert_raises
+from scipy._lib._array_api import(
+ assert_almost_equal, xp_assert_equal, xp_assert_close, make_xp_test_case
+)
+
+from scipy.signal import (ss2tf, tf2ss, lti,
+ dlti, bode, freqresp, lsim, impulse, step,
+ abcd_normalize, place_poles,
+ TransferFunction, StateSpace, ZerosPolesGain)
+from scipy.signal._filter_design import BadCoefficients
+import scipy.linalg as linalg
+
+
+def _assert_poles_close(P1,P2, rtol=1e-8, atol=1e-8):
+ """
+ Check each pole in P1 is close to a pole in P2 with a 1e-8
+ relative tolerance or 1e-8 absolute tolerance (useful for zero poles).
+ These tolerances are very strict but the systems tested are known to
+ accept these poles so we should not be far from what is requested.
+ """
+ P2 = P2.copy()
+ for p1 in P1:
+ found = False
+ for p2_idx in range(P2.shape[0]):
+ if np.allclose([np.real(p1), np.imag(p1)],
+ [np.real(P2[p2_idx]), np.imag(P2[p2_idx])],
+ rtol, atol):
+ found = True
+ np.delete(P2, p2_idx)
+ break
+ if not found:
+ raise ValueError("Can't find pole " + str(p1) + " in " + str(P2))
+
+
+class TestPlacePoles:
+
+ def _check(self, A, B, P, **kwargs):
+ """
+ Perform the most common tests on the poles computed by place_poles
+ and return the Bunch object for further specific tests
+ """
+ fsf = place_poles(A, B, P, **kwargs)
+ expected, _ = np.linalg.eig(A - np.dot(B, fsf.gain_matrix))
+ _assert_poles_close(expected, fsf.requested_poles)
+ _assert_poles_close(expected, fsf.computed_poles)
+ _assert_poles_close(P,fsf.requested_poles)
+ return fsf
+
+ def test_real(self):
+ # Test real pole placement using KNV and YT0 algorithm and example 1 in
+ # section 4 of the reference publication (see place_poles docstring)
+ A = np.array([1.380, -0.2077, 6.715, -5.676, -0.5814, -4.290, 0,
+ 0.6750, 1.067, 4.273, -6.654, 5.893, 0.0480, 4.273,
+ 1.343, -2.104]).reshape(4, 4)
+ B = np.array([0, 5.679, 1.136, 1.136, 0, 0, -3.146,0]).reshape(4, 2)
+ P = np.array([-0.2, -0.5, -5.0566, -8.6659])
+
+ # Check that both KNV and YT compute correct K matrix
+ self._check(A, B, P, method='KNV0')
+ self._check(A, B, P, method='YT')
+
+ # Try to reach the specific case in _YT_real where two singular
+ # values are almost equal. This is to improve code coverage but I
+ # have no way to be sure this code is really reached
+
+ # on some architectures this can lead to a RuntimeWarning invalid
+ # value in divide (see gh-7590), so suppress it for now
+ with np.errstate(invalid='ignore'):
+ self._check(A, B, (2,2,3,3))
+
+ def test_complex(self):
+ # Test complex pole placement on a linearized car model, taken from L.
+ # Jaulin, Automatique pour la robotique, Cours et Exercices, iSTE
+ # editions p 184/185
+ A = np.array([[0, 7, 0, 0],
+ [0, 0, 0, 7/3.],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]])
+ B = np.array([[0, 0],
+ [0, 0],
+ [1, 0],
+ [0, 1]])
+ # Test complex poles on YT
+ P = np.array([-3, -1, -2-1j, -2+1j])
+ # on macOS arm64 this can lead to a RuntimeWarning invalid
+ # value in divide, so suppress it for now
+ with np.errstate(divide='ignore', invalid='ignore'):
+ self._check(A, B, P)
+
+ # Try to reach the specific case in _YT_complex where two singular
+ # values are almost equal. This is to improve code coverage but I
+ # have no way to be sure this code is really reached
+
+ P = [0-1e-6j,0+1e-6j,-10,10]
+ with np.errstate(divide='ignore', invalid='ignore'):
+ self._check(A, B, P, maxiter=1000)
+
+ # Try to reach the specific case in _YT_complex where the rank two
+ # update yields two null vectors. This test was found via Monte Carlo.
+
+ A = np.array(
+ [-2148,-2902, -2267, -598, -1722, -1829, -165, -283, -2546,
+ -167, -754, -2285, -543, -1700, -584, -2978, -925, -1300,
+ -1583, -984, -386, -2650, -764, -897, -517, -1598, 2, -1709,
+ -291, -338, -153, -1804, -1106, -1168, -867, -2297]
+ ).reshape(6,6)
+
+ B = np.array(
+ [-108, -374, -524, -1285, -1232, -161, -1204, -672, -637,
+ -15, -483, -23, -931, -780, -1245, -1129, -1290, -1502,
+ -952, -1374, -62, -964, -930, -939, -792, -756, -1437,
+ -491, -1543, -686]
+ ).reshape(6,5)
+ P = [-25.-29.j, -25.+29.j, 31.-42.j, 31.+42.j, 33.-41.j, 33.+41.j]
+ self._check(A, B, P)
+
+ # Use a lot of poles to go through all cases for update_order
+ # in _YT_loop
+
+ big_A = np.ones((11,11))-np.eye(11)
+ big_B = np.ones((11,10))-np.diag([1]*10,1)[:,1:]
+ big_A[:6,:6] = A
+ big_B[:6,:5] = B
+
+ P = [-10,-20,-30,40,50,60,70,-20-5j,-20+5j,5+3j,5-3j]
+ with np.errstate(divide='ignore', invalid='ignore'):
+ self._check(big_A, big_B, P)
+
+ #check with only complex poles and only real poles
+ P = [-10,-20,-30,-40,-50,-60,-70,-80,-90,-100]
+ self._check(big_A[:-1,:-1], big_B[:-1,:-1], P)
+ P = [-10+10j,-20+20j,-30+30j,-40+40j,-50+50j,
+ -10-10j,-20-20j,-30-30j,-40-40j,-50-50j]
+ self._check(big_A[:-1,:-1], big_B[:-1,:-1], P)
+
+ # need a 5x5 array to ensure YT handles properly when there
+ # is only one real pole and several complex
+ A = np.array([0,7,0,0,0,0,0,7/3.,0,0,0,0,0,0,0,0,
+ 0,0,0,5,0,0,0,0,9]).reshape(5,5)
+ B = np.array([0,0,0,0,1,0,0,1,2,3]).reshape(5,2)
+ P = np.array([-2, -3+1j, -3-1j, -1+1j, -1-1j])
+ with np.errstate(divide='ignore', invalid='ignore'):
+ place_poles(A, B, P)
+
+ # same test with an odd number of real poles > 1
+ # this is another specific case of YT
+ P = np.array([-2, -3, -4, -1+1j, -1-1j])
+ with np.errstate(divide='ignore', invalid='ignore'):
+ self._check(A, B, P)
+
+ def test_tricky_B(self):
+ # check we handle as we should the 1 column B matrices and
+ # n column B matrices (with n such as shape(A)=(n, n))
+ A = np.array([1.380, -0.2077, 6.715, -5.676, -0.5814, -4.290, 0,
+ 0.6750, 1.067, 4.273, -6.654, 5.893, 0.0480, 4.273,
+ 1.343, -2.104]).reshape(4, 4)
+ B = np.array([0, 5.679, 1.136, 1.136, 0, 0, -3.146, 0, 1, 2, 3, 4,
+ 5, 6, 7, 8]).reshape(4, 4)
+
+ # KNV or YT are not called here, it's a specific case with only
+ # one unique solution
+ P = np.array([-0.2, -0.5, -5.0566, -8.6659])
+ fsf = self._check(A, B, P)
+ # rtol and nb_iter should be set to np.nan as the identity can be
+ # used as transfer matrix
+ assert np.isnan(fsf.rtol)
+ assert np.isnan(fsf.nb_iter)
+
+ # check with complex poles too as they trigger a specific case in
+ # the specific case :-)
+ P = np.array((-2+1j,-2-1j,-3,-2))
+ fsf = self._check(A, B, P)
+ assert np.isnan(fsf.rtol)
+ assert np.isnan(fsf.nb_iter)
+
+ #now test with a B matrix with only one column (no optimisation)
+ B = B[:,0].reshape(4,1)
+ P = np.array((-2+1j,-2-1j,-3,-2))
+ fsf = self._check(A, B, P)
+
+ # we can't optimize anything, check they are set to 0 as expected
+ assert fsf.rtol == 0
+ assert fsf.nb_iter == 0
+
+ def test_errors(self):
+ # Test input mistakes from user
+ A = np.array([0,7,0,0,0,0,0,7/3.,0,0,0,0,0,0,0,0]).reshape(4,4)
+ B = np.array([0,0,0,0,1,0,0,1]).reshape(4,2)
+
+ #should fail as the method keyword is invalid
+ assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4),
+ method="foo")
+
+ #should fail as poles are not 1D array
+ assert_raises(ValueError, place_poles, A, B,
+ np.array((-2.1,-2.2,-2.3,-2.4)).reshape(4,1))
+
+ #should fail as A is not a 2D array
+ assert_raises(ValueError, place_poles, A[:,:,np.newaxis], B,
+ (-2.1,-2.2,-2.3,-2.4))
+
+ #should fail as B is not a 2D array
+ assert_raises(ValueError, place_poles, A, B[:,:,np.newaxis],
+ (-2.1,-2.2,-2.3,-2.4))
+
+ #should fail as there are too many poles
+ assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4,-3))
+
+ #should fail as there are not enough poles
+ assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3))
+
+ #should fail as the rtol is greater than 1
+ assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4),
+ rtol=42)
+
+ #should fail as maxiter is smaller than 1
+ assert_raises(ValueError, place_poles, A, B, (-2.1,-2.2,-2.3,-2.4),
+ maxiter=-42)
+
+ # should fail as ndim(B) is two
+ assert_raises(ValueError, place_poles, A, B, (-2,-2,-2,-2))
+
+ # uncontrollable system
+ assert_raises(ValueError, place_poles, np.ones((4,4)),
+ np.ones((4,2)), (1,2,3,4))
+
+ # Should not raise ValueError as the poles can be placed but should
+ # raise a warning as the convergence is not reached
+ with warnings.catch_warnings(record=True) as w:
+ warnings.simplefilter("always")
+ fsf = place_poles(A, B, (-1,-2,-3,-4), rtol=1e-16, maxiter=42)
+ assert len(w) == 1
+ assert issubclass(w[-1].category, UserWarning)
+ assert ("Convergence was not reached after maxiter iterations"
+ in str(w[-1].message))
+ assert fsf.nb_iter == 42
+
+ # should fail as a complex misses its conjugate
+ assert_raises(ValueError, place_poles, A, B, (-2+1j,-2-1j,-2+3j,-2))
+
+ # should fail as A is not square
+ assert_raises(ValueError, place_poles, A[:,:3], B, (-2,-3,-4,-5))
+
+ # should fail as B has not the same number of lines as A
+ assert_raises(ValueError, place_poles, A, B[:3,:], (-2,-3,-4,-5))
+
+ # should fail as KNV0 does not support complex poles
+ assert_raises(ValueError, place_poles, A, B,
+ (-2+1j,-2-1j,-2+3j,-2-3j), method="KNV0")
+
+
+class TestSS2TF:
+
+ def check_matrix_shapes(self, p, q, r):
+ ss2tf(np.zeros((p, p)),
+ np.zeros((p, q)),
+ np.zeros((r, p)),
+ np.zeros((r, q)), 0)
+
+ def test_shapes(self):
+ # Each tuple holds:
+ # number of states, number of inputs, number of outputs
+ for p, q, r in [(3, 3, 3), (1, 3, 3), (1, 1, 1)]:
+ self.check_matrix_shapes(p, q, r)
+
+ def test_basic(self):
+ # Test a round trip through tf2ss and ss2tf.
+ b = np.array([1.0, 3.0, 5.0])
+ a = np.array([1.0, 2.0, 3.0])
+
+ A, B, C, D = tf2ss(b, a)
+ xp_assert_close(A, [[-2., -3], [1, 0]], rtol=1e-13)
+ xp_assert_close(B, [[1.], [0]], rtol=1e-13)
+ xp_assert_close(C, [[1., 2]], rtol=1e-13)
+ xp_assert_close(D, [[1.]], rtol=1e-14)
+
+ bb, aa = ss2tf(A, B, C, D)
+ xp_assert_close(bb[0], b, rtol=1e-13)
+ xp_assert_close(aa, a, rtol=1e-13)
+
+ def test_zero_order_round_trip(self):
+ # See gh-5760
+ tf = (2, 1)
+ A, B, C, D = tf2ss(*tf)
+ xp_assert_close(A, [[0.]], rtol=1e-13)
+ xp_assert_close(B, [[0.]], rtol=1e-13)
+ xp_assert_close(C, [[0.]], rtol=1e-13)
+ xp_assert_close(D, [[2.]], rtol=1e-13)
+
+ num, den = ss2tf(A, B, C, D)
+ xp_assert_close(num, [[2., 0]], rtol=1e-13)
+ xp_assert_close(den, [1., 0], rtol=1e-13)
+
+ tf = ([[5], [2]], 1)
+ A, B, C, D = tf2ss(*tf)
+ xp_assert_close(A, [[0.]], rtol=1e-13)
+ xp_assert_close(B, [[0.]], rtol=1e-13)
+ xp_assert_close(C, [[0.], [0]], rtol=1e-13)
+ xp_assert_close(D, [[5.], [2]], rtol=1e-13)
+
+ num, den = ss2tf(A, B, C, D)
+ xp_assert_close(num, [[5., 0], [2, 0]], rtol=1e-13)
+ xp_assert_close(den, [1., 0], rtol=1e-13)
+
+ def test_simo_round_trip(self):
+ # See gh-5753
+ tf = ([[1, 2], [1, 1]], [1, 2])
+ A, B, C, D = tf2ss(*tf)
+ xp_assert_close(A, [[-2.]], rtol=1e-13)
+ xp_assert_close(B, [[1.]], rtol=1e-13)
+ xp_assert_close(C, [[0.], [-1.]], rtol=1e-13)
+ xp_assert_close(D, [[1.], [1.]], rtol=1e-13)
+
+ num, den = ss2tf(A, B, C, D)
+ xp_assert_close(num, [[1., 2.], [1., 1.]], rtol=1e-13)
+ xp_assert_close(den, [1., 2.], rtol=1e-13)
+
+ tf = ([[1, 0, 1], [1, 1, 1]], [1, 1, 1])
+ A, B, C, D = tf2ss(*tf)
+ xp_assert_close(A, [[-1., -1.], [1., 0.]], rtol=1e-13)
+ xp_assert_close(B, [[1.], [0.]], rtol=1e-13)
+ xp_assert_close(C, [[-1., 0.], [0., 0.]], rtol=1e-13)
+ xp_assert_close(D, [[1.], [1.]], rtol=1e-13)
+
+ num, den = ss2tf(A, B, C, D)
+ xp_assert_close(num, [[1., 0., 1.], [1., 1., 1.]], rtol=1e-13)
+ xp_assert_close(den, [1., 1., 1.], rtol=1e-13)
+
+ tf = ([[1, 2, 3], [1, 2, 3]], [1, 2, 3, 4])
+ A, B, C, D = tf2ss(*tf)
+ xp_assert_close(A, [[-2., -3, -4], [1, 0, 0], [0, 1, 0]], rtol=1e-13)
+ xp_assert_close(B, [[1.], [0], [0]], rtol=1e-13)
+ xp_assert_close(C, [[1., 2, 3], [1, 2, 3]], rtol=1e-13)
+ xp_assert_close(D, [[0.], [0]], rtol=1e-13)
+
+ num, den = ss2tf(A, B, C, D)
+ xp_assert_close(num, [[0., 1, 2, 3], [0, 1, 2, 3]], rtol=1e-13)
+ xp_assert_close(den, [1., 2, 3, 4], rtol=1e-13)
+
+ tf = (np.array([1, [2, 3]], dtype=object), [1, 6])
+ A, B, C, D = tf2ss(*tf)
+ xp_assert_close(A, [[-6.]], rtol=1e-31)
+ xp_assert_close(B, [[1.]], rtol=1e-31)
+ xp_assert_close(C, [[1.], [-9]], rtol=1e-31)
+ xp_assert_close(D, [[0.], [2]], rtol=1e-31)
+
+ num, den = ss2tf(A, B, C, D)
+ xp_assert_close(num, [[0., 1], [2, 3]], rtol=1e-13)
+ xp_assert_close(den, [1., 6], rtol=1e-13)
+
+ tf = (np.array([[1, -3], [1, 2, 3]], dtype=object), [1, 6, 5])
+ A, B, C, D = tf2ss(*tf)
+ xp_assert_close(A, [[-6., -5], [1, 0]], rtol=1e-13)
+ xp_assert_close(B, [[1.], [0]], rtol=1e-13)
+ xp_assert_close(C, [[1., -3], [-4, -2]], rtol=1e-13)
+ xp_assert_close(D, [[0.], [1]], rtol=1e-13)
+
+ num, den = ss2tf(A, B, C, D)
+ xp_assert_close(num, [[0., 1, -3], [1, 2, 3]], rtol=1e-13)
+ xp_assert_close(den, [1., 6, 5], rtol=1e-13)
+
+ def test_all_int_arrays(self):
+ A = [[0, 1, 0], [0, 0, 1], [-3, -4, -2]]
+ B = [[0], [0], [1]]
+ C = [[5, 1, 0]]
+ D = [[0]]
+ num, den = ss2tf(A, B, C, D)
+ xp_assert_close(num, [[0.0, 0.0, 1.0, 5.0]], rtol=1e-13, atol=1e-14)
+ xp_assert_close(den, [1.0, 2.0, 4.0, 3.0], rtol=1e-13)
+
+ def test_multioutput(self):
+ # Regression test for gh-2669.
+
+ # 4 states
+ A = np.array([[-1.0, 0.0, 1.0, 0.0],
+ [-1.0, 0.0, 2.0, 0.0],
+ [-4.0, 0.0, 3.0, 0.0],
+ [-8.0, 8.0, 0.0, 4.0]])
+
+ # 1 input
+ B = np.array([[0.3],
+ [0.0],
+ [7.0],
+ [0.0]])
+
+ # 3 outputs
+ C = np.array([[0.0, 1.0, 0.0, 0.0],
+ [0.0, 0.0, 0.0, 1.0],
+ [8.0, 8.0, 0.0, 0.0]])
+
+ D = np.array([[0.0],
+ [0.0],
+ [1.0]])
+
+ # Get the transfer functions for all the outputs in one call.
+ b_all, a = ss2tf(A, B, C, D)
+
+ # Get the transfer functions for each output separately.
+ b0, a0 = ss2tf(A, B, C[0], D[0])
+ b1, a1 = ss2tf(A, B, C[1], D[1])
+ b2, a2 = ss2tf(A, B, C[2], D[2])
+
+ # Check that we got the same results.
+ xp_assert_close(a0, a, rtol=1e-13)
+ xp_assert_close(a1, a, rtol=1e-13)
+ xp_assert_close(a2, a, rtol=1e-13)
+ xp_assert_close(b_all, np.vstack((b0, b1, b2)), rtol=1e-13, atol=1e-14)
+
+
+class TestLsim:
+ digits_accuracy = 7
+
+ def lti_nowarn(self, *args):
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", BadCoefficients)
+ system = lti(*args)
+ return system
+
+ def test_first_order(self):
+ # y' = -y
+ # exact solution is y(t) = exp(-t)
+ system = self.lti_nowarn(-1.,1.,1.,0.)
+ t = np.linspace(0,5)
+ u = np.zeros_like(t)
+ tout, y, x = lsim(system, u, t, X0=[1.0])
+ expected_x = np.exp(-tout)
+ assert_almost_equal(x, expected_x)
+ assert_almost_equal(y, expected_x)
+
+ def test_second_order(self):
+ t = np.linspace(0, 10, 1001)
+ u = np.zeros_like(t)
+ # Second order system with a repeated root: x''(t) + 2*x(t) + x(t) = 0.
+ # With initial conditions x(0)=1.0 and x'(t)=0.0, the exact solution
+ # is (1-t)*exp(-t).
+ system = self.lti_nowarn([1.0], [1.0, 2.0, 1.0])
+ tout, y, x = lsim(system, u, t, X0=[1.0, 0.0])
+ expected_x = (1.0 - tout) * np.exp(-tout)
+ assert_almost_equal(x[:, 0], expected_x)
+
+ def test_integrator(self):
+ # integrator: y' = u
+ system = self.lti_nowarn(0., 1., 1., 0.)
+ t = np.linspace(0,5)
+ u = t
+ tout, y, x = lsim(system, u, t)
+ expected_x = 0.5 * tout**2
+ assert_almost_equal(x, expected_x, decimal=self.digits_accuracy)
+ assert_almost_equal(y, expected_x, decimal=self.digits_accuracy)
+
+ def test_two_states(self):
+ # A system with two state variables, two inputs, and one output.
+ A = np.array([[-1.0, 0.0], [0.0, -2.0]])
+ B = np.array([[1.0, 0.0], [0.0, 1.0]])
+ C = np.array([1.0, 0.0])
+ D = np.zeros((1, 2))
+
+ system = self.lti_nowarn(A, B, C, D)
+
+ t = np.linspace(0, 10.0, 21)
+ u = np.zeros((len(t), 2))
+ tout, y, x = lsim(system, U=u, T=t, X0=[1.0, 1.0])
+ expected_y = np.exp(-tout)
+ expected_x0 = np.exp(-tout)
+ expected_x1 = np.exp(-2.0 * tout)
+ assert_almost_equal(y, expected_y)
+ assert_almost_equal(x[:, 0], expected_x0)
+ assert_almost_equal(x[:, 1], expected_x1)
+
+ def test_double_integrator(self):
+ # double integrator: y'' = 2u
+ A = np.array([[0., 1.], [0., 0.]])
+ B = np.array([[0.], [1.]])
+ C = np.array([[2., 0.]])
+ system = self.lti_nowarn(A, B, C, 0.)
+ t = np.linspace(0,5)
+ u = np.ones_like(t)
+ tout, y, x = lsim(system, u, t)
+ expected_x = np.transpose(np.array([0.5 * tout**2, tout]))
+ expected_y = tout**2
+ assert_almost_equal(x, expected_x, decimal=self.digits_accuracy)
+ assert_almost_equal(y, expected_y, decimal=self.digits_accuracy)
+
+ def test_jordan_block(self):
+ # Non-diagonalizable A matrix
+ # x1' + x1 = x2
+ # x2' + x2 = u
+ # y = x1
+ # Exact solution with u = 0 is y(t) = t exp(-t)
+ A = np.array([[-1., 1.], [0., -1.]])
+ B = np.array([[0.], [1.]])
+ C = np.array([[1., 0.]])
+ system = self.lti_nowarn(A, B, C, 0.)
+ t = np.linspace(0,5)
+ u = np.zeros_like(t)
+ tout, y, x = lsim(system, u, t, X0=[0.0, 1.0])
+ expected_y = tout * np.exp(-tout)
+ assert_almost_equal(y, expected_y)
+
+ def test_miso(self):
+ # A system with two state variables, two inputs, and one output.
+ A = np.array([[-1.0, 0.0], [0.0, -2.0]])
+ B = np.array([[1.0, 0.0], [0.0, 1.0]])
+ C = np.array([1.0, 0.0])
+ D = np.zeros((1,2))
+ system = self.lti_nowarn(A, B, C, D)
+
+ t = np.linspace(0, 5.0, 101)
+ u = np.zeros((len(t), 2))
+ tout, y, x = lsim(system, u, t, X0=[1.0, 1.0])
+ expected_y = np.exp(-tout)
+ expected_x0 = np.exp(-tout)
+ expected_x1 = np.exp(-2.0*tout)
+ assert_almost_equal(y, expected_y)
+ assert_almost_equal(x[:,0], expected_x0)
+ assert_almost_equal(x[:,1], expected_x1)
+
+ def test_nonzero_initial_time(self):
+ system = self.lti_nowarn(-1.,1.,1.,0.)
+ t = np.linspace(1,2)
+ u = np.zeros_like(t)
+ tout, y, x = lsim(system, u, t, X0=[1.0])
+ expected_y = np.exp(-tout)
+ assert_almost_equal(y, expected_y)
+
+ def test_nonequal_timesteps(self):
+ t = np.array([0.0, 1.0, 1.0, 3.0])
+ u = np.array([0.0, 0.0, 1.0, 1.0])
+ # Simple integrator: x'(t) = u(t)
+ system = ([1.0], [1.0, 0.0])
+ with assert_raises(ValueError,
+ match="Time steps are not equally spaced."):
+ tout, y, x = lsim(system, u, t, X0=[1.0])
+
+
+class TestImpulse:
+ def test_first_order(self):
+ # First order system: x'(t) + x(t) = u(t)
+ # Exact impulse response is x(t) = exp(-t).
+ system = ([1.0], [1.0,1.0])
+ tout, y = impulse(system)
+ expected_y = np.exp(-tout)
+ assert_almost_equal(y, expected_y)
+
+ def test_first_order_fixed_time(self):
+ # Specify the desired time values for the output.
+
+ # First order system: x'(t) + x(t) = u(t)
+ # Exact impulse response is x(t) = exp(-t).
+ system = ([1.0], [1.0,1.0])
+ n = 21
+ t = np.linspace(0, 2.0, n)
+ tout, y = impulse(system, T=t)
+ assert tout.shape == (n,)
+ assert_almost_equal(tout, t)
+ expected_y = np.exp(-t)
+ assert_almost_equal(y, expected_y)
+
+ def test_first_order_initial(self):
+ # Specify an initial condition as a scalar.
+
+ # First order system: x'(t) + x(t) = u(t), x(0)=3.0
+ # Exact impulse response is x(t) = 4*exp(-t).
+ system = ([1.0], [1.0,1.0])
+ tout, y = impulse(system, X0=3.0)
+ expected_y = 4.0 * np.exp(-tout)
+ assert_almost_equal(y, expected_y)
+
+ def test_first_order_initial_list(self):
+ # Specify an initial condition as a list.
+
+ # First order system: x'(t) + x(t) = u(t), x(0)=3.0
+ # Exact impulse response is x(t) = 4*exp(-t).
+ system = ([1.0], [1.0,1.0])
+ tout, y = impulse(system, X0=[3.0])
+ expected_y = 4.0 * np.exp(-tout)
+ assert_almost_equal(y, expected_y)
+
+ def test_integrator(self):
+ # Simple integrator: x'(t) = u(t)
+ system = ([1.0], [1.0,0.0])
+ tout, y = impulse(system)
+ expected_y = np.ones_like(tout)
+ assert_almost_equal(y, expected_y)
+
+ def test_second_order(self):
+ # Second order system with a repeated root:
+ # x''(t) + 2*x(t) + x(t) = u(t)
+ # The exact impulse response is t*exp(-t).
+ system = ([1.0], [1.0, 2.0, 1.0])
+ tout, y = impulse(system)
+ expected_y = tout * np.exp(-tout)
+ assert_almost_equal(y, expected_y)
+
+ def test_array_like(self):
+ # Test that function can accept sequences, scalars.
+ system = ([1.0], [1.0, 2.0, 1.0])
+ # TODO: add meaningful test where X0 is a list
+ tout, y = impulse(system, X0=[3], T=[5, 6])
+ tout, y = impulse(system, X0=[3], T=[5])
+
+ def test_array_like2(self):
+ system = ([1.0], [1.0, 2.0, 1.0])
+ tout, y = impulse(system, X0=3, T=5)
+
+
+class TestStep:
+ def test_first_order(self):
+ # First order system: x'(t) + x(t) = u(t)
+ # Exact step response is x(t) = 1 - exp(-t).
+ system = ([1.0], [1.0,1.0])
+ tout, y = step(system)
+ expected_y = 1.0 - np.exp(-tout)
+ assert_almost_equal(y, expected_y)
+
+ def test_first_order_fixed_time(self):
+ # Specify the desired time values for the output.
+
+ # First order system: x'(t) + x(t) = u(t)
+ # Exact step response is x(t) = 1 - exp(-t).
+ system = ([1.0], [1.0,1.0])
+ n = 21
+ t = np.linspace(0, 2.0, n)
+ tout, y = step(system, T=t)
+ assert tout.shape == (n,)
+ assert_almost_equal(tout, t)
+ expected_y = 1 - np.exp(-t)
+ assert_almost_equal(y, expected_y)
+
+ def test_first_order_initial(self):
+ # Specify an initial condition as a scalar.
+
+ # First order system: x'(t) + x(t) = u(t), x(0)=3.0
+ # Exact step response is x(t) = 1 + 2*exp(-t).
+ system = ([1.0], [1.0,1.0])
+ tout, y = step(system, X0=3.0)
+ expected_y = 1 + 2.0*np.exp(-tout)
+ assert_almost_equal(y, expected_y)
+
+ def test_first_order_initial_list(self):
+ # Specify an initial condition as a list.
+
+ # First order system: x'(t) + x(t) = u(t), x(0)=3.0
+ # Exact step response is x(t) = 1 + 2*exp(-t).
+ system = ([1.0], [1.0,1.0])
+ tout, y = step(system, X0=[3.0])
+ expected_y = 1 + 2.0*np.exp(-tout)
+ assert_almost_equal(y, expected_y)
+
+ def test_integrator(self):
+ # Simple integrator: x'(t) = u(t)
+ # Exact step response is x(t) = t.
+ system = ([1.0],[1.0,0.0])
+ tout, y = step(system)
+ expected_y = tout
+ assert_almost_equal(y, expected_y)
+
+ def test_second_order(self):
+ # Second order system with a repeated root:
+ # x''(t) + 2*x(t) + x(t) = u(t)
+ # The exact step response is 1 - (1 + t)*exp(-t).
+ system = ([1.0], [1.0, 2.0, 1.0])
+ tout, y = step(system)
+ expected_y = 1 - (1 + tout) * np.exp(-tout)
+ assert_almost_equal(y, expected_y)
+
+ def test_array_like(self):
+ # Test that function can accept sequences, scalars.
+ system = ([1.0], [1.0, 2.0, 1.0])
+ # TODO: add meaningful test where X0 is a list
+ tout, y = step(system, T=[5, 6])
+
+ def test_complex_input(self):
+ # Test that complex input doesn't raise an error.
+ # `step` doesn't seem to have been designed for complex input, but this
+ # works and may be used, so add regression test. See gh-2654.
+ step(([], [-1], 1+0j))
+
+
+class TestLti:
+ def test_lti_instantiation(self):
+ # Test that lti can be instantiated with sequences, scalars.
+ # See PR-225.
+
+ # TransferFunction
+ s = lti([1], [-1])
+ assert isinstance(s, TransferFunction)
+ assert isinstance(s, lti)
+ assert not isinstance(s, dlti)
+ assert s.dt is None
+
+ # ZerosPolesGain
+ s = lti(np.array([]), np.array([-1]), 1)
+ assert isinstance(s, ZerosPolesGain)
+ assert isinstance(s, lti)
+ assert not isinstance(s, dlti)
+ assert s.dt is None
+
+ # StateSpace
+ s = lti([], [-1], 1)
+ s = lti([1], [-1], 1, 3)
+ assert isinstance(s, StateSpace)
+ assert isinstance(s, lti)
+ assert not isinstance(s, dlti)
+ assert s.dt is None
+
+
+class TestStateSpace:
+ def test_initialization(self):
+ # Check that all initializations work
+ StateSpace(1, 1, 1, 1)
+ StateSpace([1], [2], [3], [4])
+ StateSpace(np.array([[1, 2], [3, 4]]), np.array([[1], [2]]),
+ np.array([[1, 0]]), np.array([[0]]))
+
+ def test_conversion(self):
+ # Check the conversion functions
+ s = StateSpace(1, 2, 3, 4)
+ assert isinstance(s.to_ss(), StateSpace)
+ assert isinstance(s.to_tf(), TransferFunction)
+ assert isinstance(s.to_zpk(), ZerosPolesGain)
+
+ # Make sure copies work
+ assert StateSpace(s) is not s
+ assert s.to_ss() is not s
+
+ def test_properties(self):
+ # Test setters/getters for cross class properties.
+ # This implicitly tests to_tf() and to_zpk()
+
+ # Getters
+ s = StateSpace(1, 1, 1, 1)
+ xp_assert_equal(s.poles, [1.])
+ xp_assert_equal(s.zeros, [0.])
+ assert s.dt is None
+
+ def test_operators(self):
+ # Test +/-/* operators on systems
+
+ class BadType:
+ pass
+
+ s1 = StateSpace(np.array([[-0.5, 0.7], [0.3, -0.8]]),
+ np.array([[1], [0]]),
+ np.array([[1, 0]]),
+ np.array([[0]]),
+ )
+
+ s2 = StateSpace(np.array([[-0.2, -0.1], [0.4, -0.1]]),
+ np.array([[1], [0]]),
+ np.array([[1, 0]]),
+ np.array([[0]])
+ )
+
+ s_discrete = s1.to_discrete(0.1)
+ s2_discrete = s2.to_discrete(0.2)
+ s3_discrete = s2.to_discrete(0.1)
+
+ # Impulse response
+ t = np.linspace(0, 1, 100)
+ u = np.zeros_like(t)
+ u[0] = 1
+
+ # Test multiplication
+ for typ in (int, float, complex, np.float32, np.complex128, np.array):
+ xp_assert_close(lsim(typ(2) * s1, U=u, T=t)[1],
+ typ(2) * lsim(s1, U=u, T=t)[1])
+
+ xp_assert_close(lsim(s1 * typ(2), U=u, T=t)[1],
+ lsim(s1, U=u, T=t)[1] * typ(2))
+
+ xp_assert_close(lsim(s1 / typ(2), U=u, T=t)[1],
+ lsim(s1, U=u, T=t)[1] / typ(2))
+
+ with assert_raises(TypeError):
+ typ(2) / s1
+
+ xp_assert_close(lsim(s1 * 2, U=u, T=t)[1],
+ lsim(s1, U=2 * u, T=t)[1])
+
+ xp_assert_close(lsim(s1 * s2, U=u, T=t)[1],
+ lsim(s1, U=lsim(s2, U=u, T=t)[1], T=t)[1],
+ atol=1e-5)
+
+ with assert_raises(TypeError):
+ s1 / s1
+
+ with assert_raises(TypeError):
+ s1 * s_discrete
+
+ with assert_raises(TypeError):
+ # Check different discretization constants
+ s_discrete * s2_discrete
+
+ with assert_raises(TypeError):
+ s1 * BadType()
+
+ with assert_raises(TypeError):
+ BadType() * s1
+
+ with assert_raises(TypeError):
+ s1 / BadType()
+
+ with assert_raises(TypeError):
+ BadType() / s1
+
+ # Test addition
+ xp_assert_close(lsim(s1 + 2, U=u, T=t)[1],
+ 2 * u + lsim(s1, U=u, T=t)[1])
+
+ # Check for dimension mismatch
+ with assert_raises(ValueError):
+ s1 + np.array([1, 2])
+
+ with assert_raises(ValueError):
+ np.array([1, 2]) + s1
+
+ with assert_raises(TypeError):
+ s1 + s_discrete
+
+ with assert_raises(ValueError):
+ s1 / np.array([[1, 2], [3, 4]])
+
+ with assert_raises(TypeError):
+ # Check different discretization constants
+ s_discrete + s2_discrete
+
+ with assert_raises(TypeError):
+ s1 + BadType()
+
+ with assert_raises(TypeError):
+ BadType() + s1
+
+ xp_assert_close(lsim(s1 + s2, U=u, T=t)[1],
+ lsim(s1, U=u, T=t)[1] + lsim(s2, U=u, T=t)[1])
+
+ # Test subtraction
+ xp_assert_close(lsim(s1 - 2, U=u, T=t)[1],
+ -2 * u + lsim(s1, U=u, T=t)[1])
+
+ xp_assert_close(lsim(2 - s1, U=u, T=t)[1],
+ 2 * u + lsim(-s1, U=u, T=t)[1])
+
+ xp_assert_close(lsim(s1 - s2, U=u, T=t)[1],
+ lsim(s1, U=u, T=t)[1] - lsim(s2, U=u, T=t)[1])
+
+ with assert_raises(TypeError):
+ s1 - BadType()
+
+ with assert_raises(TypeError):
+ BadType() - s1
+
+ s = s_discrete + s3_discrete
+ assert s.dt == 0.1
+
+ s = s_discrete * s3_discrete
+ assert s.dt == 0.1
+
+ s = 3 * s_discrete
+ assert s.dt == 0.1
+
+ s = -s_discrete
+ assert s.dt == 0.1
+
+class TestTransferFunction:
+ def test_initialization(self):
+ # Check that all initializations work
+ TransferFunction(1, 1)
+ TransferFunction([1], [2])
+ TransferFunction(np.array([1]), np.array([2]))
+
+ def test_conversion(self):
+ # Check the conversion functions
+ s = TransferFunction([1, 0], [1, -1])
+ assert isinstance(s.to_ss(), StateSpace)
+ assert isinstance(s.to_tf(), TransferFunction)
+ assert isinstance(s.to_zpk(), ZerosPolesGain)
+
+ # Make sure copies work
+ assert TransferFunction(s) is not s
+ assert s.to_tf() is not s
+
+ def test_properties(self):
+ # Test setters/getters for cross class properties.
+ # This implicitly tests to_ss() and to_zpk()
+
+ # Getters
+ s = TransferFunction([1, 0], [1, -1])
+ xp_assert_equal(s.poles, [1.])
+ xp_assert_equal(s.zeros, [0.])
+
+
+class TestZerosPolesGain:
+ def test_initialization(self):
+ # Check that all initializations work
+ ZerosPolesGain(1, 1, 1)
+ ZerosPolesGain([1], [2], 1)
+ ZerosPolesGain(np.array([1]), np.array([2]), 1)
+
+ def test_conversion(self):
+ #Check the conversion functions
+ s = ZerosPolesGain(1, 2, 3)
+ assert isinstance(s.to_ss(), StateSpace)
+ assert isinstance(s.to_tf(), TransferFunction)
+ assert isinstance(s.to_zpk(), ZerosPolesGain)
+
+ # Make sure copies work
+ assert ZerosPolesGain(s) is not s
+ assert s.to_zpk() is not s
+
+
+@make_xp_test_case(abcd_normalize)
+class Test_abcd_normalize:
+ A = [[1.0, 2.0], [3.0, 4.0]]
+ B = [[-1.0], [5.0]]
+ C = [[4.0, 5.0]]
+ D = [[2.5]]
+
+ def test_no_matrix_fails(self):
+ assert_raises(ValueError, abcd_normalize)
+
+ def test_A_nosquare_fails(self, xp):
+ assert_raises(ValueError, abcd_normalize, xp.asarray([1, -1]),
+ xp.asarray(self.B), xp.asarray(self.C), xp.asarray(self.D))
+
+ def test_AB_mismatch_fails(self, xp):
+ assert_raises(ValueError, abcd_normalize, xp.asarray(self.A),
+ xp.asarray([-1, 5]), xp.asarray(self.C), xp.asarray(self.D))
+
+ def test_AC_mismatch_fails(self, xp):
+ assert_raises(ValueError, abcd_normalize, xp.asarray(self.A),
+ xp.asarray(self.B), xp.asarray([[4.0], [5.0]]),
+ xp.asarray(self.D))
+
+ def test_CD_mismatch_fails(self, xp):
+ assert_raises(ValueError, abcd_normalize, xp.asarray(self.A),
+ xp.asarray(self.B), xp.asarray(self.C), xp.asarray([2.5, 0]))
+
+ def test_BD_mismatch_fails(self, xp):
+ assert_raises(ValueError, abcd_normalize, xp.asarray(self.A),
+ xp.asarray([-1, 5]), xp.asarray(self.C), xp.asarray(self.D))
+
+ def test_normalized_matrices_unchanged(self, xp):
+ A_, B_, C_, D_ = map(xp.asarray, (self.A, self.B, self.C, self.D))
+ A, B, C, D = abcd_normalize(A=A_, B=B_, C=C_, D=D_)
+ xp_assert_equal(A, A_)
+ xp_assert_equal(B, B_)
+ xp_assert_equal(C, C_)
+ xp_assert_equal(D, D_)
+
+ def test_shapes(self, xp):
+ A, B, C, D = abcd_normalize(xp.asarray(self.A), xp.asarray(self.B),
+ xp.asarray([1, 0]), xp.asarray(0))
+ assert A.shape[0] == A.shape[1]
+ assert A.shape[0] == B.shape[0]
+ assert A.shape[0] == C.shape[1]
+ assert C.shape[0] == D.shape[0]
+ assert B.shape[1] == D.shape[1]
+
+ def test_zero_dimension_is_not_none1(self, xp):
+ A_ = xp.asarray(self.A)
+ B_ = xp.zeros((2, 0))
+ D_ = xp.zeros((0, 0))
+ A, B, C, D = abcd_normalize(A=A_, B=B_, D=D_)
+ xp_assert_equal(A, A_)
+ xp_assert_equal(B, B_)
+ xp_assert_equal(D, D_)
+ assert C.shape[0] == D_.shape[0]
+ assert C.shape[1] == A_.shape[0]
+
+ def test_zero_dimension_is_not_none2(self, xp):
+ A_ = xp.asarray(self.A)
+ B_ = xp.zeros((2, 0))
+ C_ = xp.zeros((0, 2))
+ A, B, C, D = abcd_normalize(A=A_, B=B_, C=C_)
+ xp_assert_equal(A, A_)
+ xp_assert_equal(B, B_)
+ xp_assert_equal(C, C_)
+ assert D.shape[0] == C_.shape[0]
+ assert D.shape[1] == B_.shape[1]
+
+ def test_missing_A(self, xp):
+ B_, C_, D_ = map(xp.asarray, (self.B, self.C, self.D))
+ A, B, C, D = abcd_normalize(B=B_, C=C_, D=D_)
+ assert A.shape[0] == A.shape[1]
+ assert A.shape[0] == B.shape[0]
+ assert A.shape == (B_.shape[0], B_.shape[0])
+
+ def test_missing_B(self, xp):
+ A_, C_, D_ = map(xp.asarray, (self.A, self.C, self.D))
+ A, B, C, D = abcd_normalize(A=A_, C=C_, D=D_)
+ assert B.shape[0] == A.shape[0]
+ assert B.shape[1] == D.shape[1]
+ assert B.shape == (A_.shape[0], D_.shape[1])
+
+ def test_missing_C(self, xp):
+ A_, B_, D_ = map(xp.asarray, (self.A, self.B, self.D))
+ A, B, C, D = abcd_normalize(A=A_, B=B_, D=D_)
+ assert C.shape[0] == D.shape[0]
+ assert C.shape[1] == A.shape[0]
+ assert C.shape == (D_.shape[0], A_.shape[0])
+
+ def test_missing_D(self, xp):
+ A_, B_, C_ = map(xp.asarray, (self.A, self.B, self.C))
+ A, B, C, D = abcd_normalize(A=A_, B=B_, C=C_)
+ assert D.shape[0] == C.shape[0]
+ assert D.shape[1] == B.shape[1]
+ assert D.shape == (C_.shape[0], B_.shape[1])
+
+ def test_missing_AB(self, xp):
+ C_, D_ = map(xp.asarray, (self.C, self.D))
+ A, B, C, D = abcd_normalize(C=C_, D=D_)
+ assert A.shape[0] == A.shape[1]
+ assert A.shape[0] == B.shape[0]
+ assert B.shape[1] == D.shape[1]
+ assert A.shape == (C_.shape[1], C_.shape[1])
+ assert B.shape == (C_.shape[1], D_.shape[1])
+
+ def test_missing_AC(self, xp):
+ B_, D_ = map(xp.asarray, (self.B, self.D))
+ A, B, C, D = abcd_normalize(B=B_, D=D_)
+ assert A.shape[0] == A.shape[1]
+ assert A.shape[0] == B.shape[0]
+ assert C.shape[0] == D.shape[0]
+ assert C.shape[1] == A.shape[0]
+ assert A.shape == (B_.shape[0], B_.shape[0])
+ assert C.shape == (D_.shape[0], B_.shape[0])
+
+ def test_missing_AD(self, xp):
+ B_, C_ = map(xp.asarray, (self.B, self.C))
+ A, B, C, D = abcd_normalize(B=B_, C=C_)
+ assert A.shape[0] == A.shape[1]
+ assert A.shape[0] == B.shape[0]
+ assert D.shape[0] == C.shape[0]
+ assert D.shape[1] == B.shape[1]
+ assert A.shape == (B_.shape[0], B_.shape[0])
+ assert D.shape == (C_.shape[0], B_.shape[1])
+
+ def test_missing_BC(self, xp):
+ A_, D_ = map(xp.asarray, (self.A, self.D))
+ A, B, C, D = abcd_normalize(A=A_, D=D_)
+ assert B.shape[0] == A.shape[0]
+ assert B.shape[1] == D.shape[1]
+ assert C.shape[0] == D.shape[0]
+ assert C.shape[1] == A.shape[0]
+ assert B.shape == (A_.shape[0], D_.shape[1])
+ assert C.shape == (D_.shape[0], A_.shape[0])
+
+ def test_missing_ABC_fails(self, xp):
+ assert_raises(ValueError, abcd_normalize, D=xp.asarray(self.D))
+
+ def test_missing_BD_fails(self, xp):
+ assert_raises(ValueError, abcd_normalize, A=xp.asarray(self.A),
+ C=xp.asarray(self.C))
+
+ def test_missing_CD_fails(self, xp):
+ assert_raises(ValueError, abcd_normalize, A=xp.asarray(self.A),
+ B=xp.asarray(self.B))
+
+
+class Test_bode:
+
+ def test_01(self):
+ # Test bode() magnitude calculation (manual sanity check).
+ # 1st order low-pass filter: H(s) = 1 / (s + 1),
+ # cutoff: 1 rad/s, slope: -20 dB/decade
+ # H(s=0.1) ~= 0 dB
+ # H(s=1) ~= -3 dB
+ # H(s=10) ~= -20 dB
+ # H(s=100) ~= -40 dB
+ system = lti([1], [1, 1])
+ w = [0.1, 1, 10, 100]
+ w, mag, phase = bode(system, w=w)
+ expected_mag = [0, -3, -20, -40]
+ assert_almost_equal(mag, expected_mag, decimal=1)
+
+ def test_02(self):
+ # Test bode() phase calculation (manual sanity check).
+ # 1st order low-pass filter: H(s) = 1 / (s + 1),
+ # angle(H(s=0.1)) ~= -5.7 deg
+ # angle(H(s=1)) ~= -45 deg
+ # angle(H(s=10)) ~= -84.3 deg
+ system = lti([1], [1, 1])
+ w = [0.1, 1, 10]
+ w, mag, phase = bode(system, w=w)
+ expected_phase = [-5.7, -45, -84.3]
+ assert_almost_equal(phase, expected_phase, decimal=1)
+
+ def test_03(self):
+ # Test bode() magnitude calculation.
+ # 1st order low-pass filter: H(s) = 1 / (s + 1)
+ system = lti([1], [1, 1])
+ w = [0.1, 1, 10, 100]
+ w, mag, phase = bode(system, w=w)
+ jw = w * 1j
+ y = np.polyval(system.num, jw) / np.polyval(system.den, jw)
+ expected_mag = 20.0 * np.log10(abs(y))
+ assert_almost_equal(mag, expected_mag)
+
+ def test_04(self):
+ # Test bode() phase calculation.
+ # 1st order low-pass filter: H(s) = 1 / (s + 1)
+ system = lti([1], [1, 1])
+ w = [0.1, 1, 10, 100]
+ w, mag, phase = bode(system, w=w)
+ jw = w * 1j
+ y = np.polyval(system.num, jw) / np.polyval(system.den, jw)
+ expected_phase = np.arctan2(y.imag, y.real) * 180.0 / np.pi
+ assert_almost_equal(phase, expected_phase)
+
+ def test_05(self):
+ # Test that bode() finds a reasonable frequency range.
+ # 1st order low-pass filter: H(s) = 1 / (s + 1)
+ system = lti([1], [1, 1])
+ n = 10
+ # Expected range is from 0.01 to 10.
+ expected_w = np.logspace(-2, 1, n)
+ w, mag, phase = bode(system, n=n)
+ assert_almost_equal(w, expected_w)
+
+ def test_06(self):
+ # Test that bode() doesn't fail on a system with a pole at 0.
+ # integrator, pole at zero: H(s) = 1 / s
+ system = lti([1], [1, 0])
+ w, mag, phase = bode(system, n=2)
+ assert w[0] == 0.01 # a fail would give not-a-number
+
+ def test_07(self):
+ # bode() should not fail on a system with pure imaginary poles.
+ # The test passes if bode doesn't raise an exception.
+ system = lti([1], [1, 0, 100])
+ w, mag, phase = bode(system, n=2)
+
+ def test_08(self):
+ # Test that bode() return continuous phase, issues/2331.
+ system = lti([], [-10, -30, -40, -60, -70], 1)
+ w, mag, phase = system.bode(w=np.logspace(-3, 40, 100))
+ assert_almost_equal(min(phase), -450, decimal=15)
+
+ def test_from_state_space(self):
+ # Ensure that bode works with a system that was created from the
+ # state space representation matrices A, B, C, D. In this case,
+ # system.num will be a 2-D array with shape (1, n+1), where (n,n)
+ # is the shape of A.
+ # A Butterworth lowpass filter is used, so we know the exact
+ # frequency response.
+ a = np.array([1.0, 2.0, 2.0, 1.0])
+ A = linalg.companion(a).T
+ B = np.array([[0.0], [0.0], [1.0]])
+ C = np.array([[1.0, 0.0, 0.0]])
+ D = np.array([[0.0]])
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", BadCoefficients)
+ system = lti(A, B, C, D)
+ w, mag, phase = bode(system, n=100)
+
+ expected_magnitude = 20 * np.log10(np.sqrt(1.0 / (1.0 + w**6)))
+ assert_almost_equal(mag, expected_magnitude)
+
+
+class Test_freqresp:
+
+ def test_output_manual(self):
+ # Test freqresp() output calculation (manual sanity check).
+ # 1st order low-pass filter: H(s) = 1 / (s + 1),
+ # re(H(s=0.1)) ~= 0.99
+ # re(H(s=1)) ~= 0.5
+ # re(H(s=10)) ~= 0.0099
+ system = lti([1], [1, 1])
+ w = [0.1, 1, 10]
+ w, H = freqresp(system, w=w)
+ expected_re = [0.99, 0.5, 0.0099]
+ expected_im = [-0.099, -0.5, -0.099]
+ assert_almost_equal(H.real, expected_re, decimal=1)
+ assert_almost_equal(H.imag, expected_im, decimal=1)
+
+ def test_output(self):
+ # Test freqresp() output calculation.
+ # 1st order low-pass filter: H(s) = 1 / (s + 1)
+ system = lti([1], [1, 1])
+ w = [0.1, 1, 10, 100]
+ w, H = freqresp(system, w=w)
+ s = w * 1j
+ expected = np.polyval(system.num, s) / np.polyval(system.den, s)
+ assert_almost_equal(H.real, expected.real)
+ assert_almost_equal(H.imag, expected.imag)
+
+ def test_freq_range(self):
+ # Test that freqresp() finds a reasonable frequency range.
+ # 1st order low-pass filter: H(s) = 1 / (s + 1)
+ # Expected range is from 0.01 to 10.
+ system = lti([1], [1, 1])
+ n = 10
+ expected_w = np.logspace(-2, 1, n)
+ w, H = freqresp(system, n=n)
+ assert_almost_equal(w, expected_w)
+
+ def test_pole_zero(self):
+ # Test that freqresp() doesn't fail on a system with a pole at 0.
+ # integrator, pole at zero: H(s) = 1 / s
+ system = lti([1], [1, 0])
+ w, H = freqresp(system, n=2)
+ assert w[0] == 0.01 # a fail would give not-a-number
+
+ def test_from_state_space(self):
+ # Ensure that freqresp works with a system that was created from the
+ # state space representation matrices A, B, C, D. In this case,
+ # system.num will be a 2-D array with shape (1, n+1), where (n,n) is
+ # the shape of A.
+ # A Butterworth lowpass filter is used, so we know the exact
+ # frequency response.
+ a = np.array([1.0, 2.0, 2.0, 1.0])
+ A = linalg.companion(a).T
+ B = np.array([[0.0],[0.0],[1.0]])
+ C = np.array([[1.0, 0.0, 0.0]])
+ D = np.array([[0.0]])
+ with warnings.catch_warnings():
+ warnings.simplefilter("ignore", BadCoefficients)
+ system = lti(A, B, C, D)
+ w, H = freqresp(system, n=100)
+ s = w * 1j
+ expected = (1.0 / (1.0 + 2*s + 2*s**2 + s**3))
+ assert_almost_equal(H.real, expected.real)
+ assert_almost_equal(H.imag, expected.imag)
+
+ def test_from_zpk(self):
+ # 4th order low-pass filter: H(s) = 1 / (s + 1)
+ system = lti([],[-1]*4,[1])
+ w = [0.1, 1, 10, 100]
+ w, H = freqresp(system, w=w)
+ s = w * 1j
+ expected = 1 / (s + 1)**4
+ assert_almost_equal(H.real, expected.real)
+ assert_almost_equal(H.imag, expected.imag)
+
+@pytest.mark.parametrize(
+ "cls", [StateSpace, TransferFunction, ZerosPolesGain, lti, dlti]
+)
+def test_subscriptable_generic_types(cls):
+ assert isinstance(cls[np.float64], GenericAlias)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_max_len_seq.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_max_len_seq.py
new file mode 100644
index 0000000000000000000000000000000000000000..7610b3f898571d10d75a64f00d900168c7142fbe
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_max_len_seq.py
@@ -0,0 +1,71 @@
+import numpy as np
+from pytest import raises as assert_raises
+from scipy._lib._array_api import xp_assert_close, xp_assert_equal
+
+from numpy.fft import fft, ifft
+
+from scipy.signal import max_len_seq
+
+
+class TestMLS:
+
+ def test_mls_inputs(self):
+ # can't all be zero state
+ assert_raises(ValueError, max_len_seq,
+ 10, state=np.zeros(10))
+ # wrong size state
+ assert_raises(ValueError, max_len_seq, 10,
+ state=np.ones(3))
+ # wrong length
+ assert_raises(ValueError, max_len_seq, 10, length=-1)
+ xp_assert_equal(max_len_seq(10, length=0)[0],
+ np.asarray([], dtype=np.int8)
+ )
+ # unknown taps
+ assert_raises(ValueError, max_len_seq, 64)
+ # bad taps
+ assert_raises(ValueError, max_len_seq, 10, taps=[-1, 1])
+
+ def test_mls_output(self):
+ # define some alternate working taps
+ alt_taps = {2: [1], 3: [2], 4: [3], 5: [4, 3, 2], 6: [5, 4, 1], 7: [4],
+ 8: [7, 5, 3]}
+ # assume the other bit levels work, too slow to test higher orders...
+ for nbits in range(2, 8):
+ for state in [None, np.round(np.random.rand(nbits))]:
+ for taps in [None, alt_taps[nbits]]:
+ if state is not None and np.all(state == 0):
+ state[0] = 1 # they can't all be zero
+ orig_m = max_len_seq(nbits, state=state,
+ taps=taps)[0]
+ m = 2. * orig_m - 1. # convert to +/- 1 representation
+ # First, make sure we got all 1's or -1
+ err_msg = "mls had non binary terms"
+ xp_assert_equal(np.abs(m), np.ones_like(m),
+ err_msg=err_msg)
+ # Test via circular cross-correlation, which is just mult.
+ # in the frequency domain with one signal conjugated
+ tester = np.real(ifft(fft(m) * np.conj(fft(m))))
+ out_len = 2**nbits - 1
+ # impulse amplitude == test_len
+ err_msg = "mls impulse has incorrect value"
+ xp_assert_close(tester[0],
+ float(out_len),
+ err_msg=err_msg
+ )
+ # steady-state is -1
+ err_msg = "mls steady-state has incorrect value"
+ xp_assert_close(tester[1:],
+ np.full(out_len - 1, -1, dtype=tester.dtype),
+ err_msg=err_msg)
+ # let's do the split thing using a couple options
+ for n in (1, 2**(nbits - 1)):
+ m1, s1 = max_len_seq(nbits, state=state, taps=taps,
+ length=n)
+ m2, s2 = max_len_seq(nbits, state=s1, taps=taps,
+ length=1)
+ m3, s3 = max_len_seq(nbits, state=s2, taps=taps,
+ length=out_len - n - 1)
+ new_m = np.concatenate((m1, m2, m3))
+ xp_assert_equal(orig_m, new_m)
+
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_peak_finding.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_peak_finding.py
new file mode 100644
index 0000000000000000000000000000000000000000..8118c505e83f51417fa895056fcd799011cd98df
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_peak_finding.py
@@ -0,0 +1,913 @@
+import copy
+
+import numpy as np
+import pytest
+from pytest import raises, warns
+from scipy._lib._array_api import xp_assert_close, xp_assert_equal
+
+from scipy.signal._peak_finding import (
+ argrelmax,
+ argrelmin,
+ peak_prominences,
+ peak_widths,
+ _unpack_condition_args,
+ find_peaks,
+ find_peaks_cwt,
+ _identify_ridge_lines
+)
+from scipy.signal.windows import gaussian
+from scipy.signal._peak_finding_utils import _local_maxima_1d, PeakPropertyWarning
+
+
+def _gen_gaussians(center_locs, sigmas, total_length):
+ xdata = np.arange(0, total_length).astype(float)
+ out_data = np.zeros(total_length, dtype=float)
+ for ind, sigma in enumerate(sigmas):
+ tmp = (xdata - center_locs[ind]) / sigma
+ out_data += np.exp(-(tmp**2))
+ return out_data
+
+
+def _gen_gaussians_even(sigmas, total_length):
+ num_peaks = len(sigmas)
+ delta = total_length / (num_peaks + 1)
+ center_locs = np.linspace(delta, total_length - delta, num=num_peaks).astype(int)
+ out_data = _gen_gaussians(center_locs, sigmas, total_length)
+ return out_data, center_locs
+
+
+def _gen_ridge_line(start_locs, max_locs, length, distances, gaps):
+ """
+ Generate coordinates for a ridge line.
+
+ Will be a series of coordinates, starting a start_loc (length 2).
+ The maximum distance between any adjacent columns will be
+ `max_distance`, the max distance between adjacent rows
+ will be `map_gap'.
+
+ `max_locs` should be the size of the intended matrix. The
+ ending coordinates are guaranteed to be less than `max_locs`,
+ although they may not approach `max_locs` at all.
+ """
+
+ def keep_bounds(num, max_val):
+ out = max(num, 0)
+ out = min(out, max_val)
+ return out
+
+ gaps = copy.deepcopy(gaps)
+ distances = copy.deepcopy(distances)
+
+ locs = np.zeros([length, 2], dtype=int)
+ locs[0, :] = start_locs
+ total_length = max_locs[0] - start_locs[0] - sum(gaps)
+ if total_length < length:
+ raise ValueError('Cannot generate ridge line according to constraints')
+ dist_int = length / len(distances) - 1
+ gap_int = length / len(gaps) - 1
+ for ind in range(1, length):
+ nextcol = locs[ind - 1, 1]
+ nextrow = locs[ind - 1, 0] + 1
+ if (ind % dist_int == 0) and (len(distances) > 0):
+ nextcol += ((-1)**ind)*distances.pop()
+ if (ind % gap_int == 0) and (len(gaps) > 0):
+ nextrow += gaps.pop()
+ nextrow = keep_bounds(nextrow, max_locs[0])
+ nextcol = keep_bounds(nextcol, max_locs[1])
+ locs[ind, :] = [nextrow, nextcol]
+
+ return [locs[:, 0], locs[:, 1]]
+
+
+class TestLocalMaxima1d:
+
+ def test_empty(self):
+ """Test with empty signal."""
+ x = np.array([], dtype=np.float64)
+ for array in _local_maxima_1d(x):
+ xp_assert_equal(array, np.array([]), check_dtype=False)
+ assert array.base is None
+
+ def test_linear(self):
+ """Test with linear signal."""
+ x = np.linspace(0, 100)
+ for array in _local_maxima_1d(x):
+ xp_assert_equal(array, np.array([], dtype=np.intp))
+ assert array.base is None
+
+ def test_simple(self):
+ """Test with simple signal."""
+ x = np.linspace(-10, 10, 50)
+ x[2::3] += 1
+ expected = np.arange(2, 50, 3, dtype=np.intp)
+ for array in _local_maxima_1d(x):
+ # For plateaus of size 1, the edges are identical with the
+ # midpoints
+ xp_assert_equal(array, expected, check_dtype=False)
+ assert array.base is None
+
+ def test_flat_maxima(self):
+ """Test if flat maxima are detected correctly."""
+ x = np.array([-1.3, 0, 1, 0, 2, 2, 0, 3, 3, 3, 2.99, 4, 4, 4, 4, -10,
+ -5, -5, -5, -5, -5, -10])
+ midpoints, left_edges, right_edges = _local_maxima_1d(x)
+ xp_assert_equal(midpoints, np.array([2, 4, 8, 12, 18]), check_dtype=False)
+ xp_assert_equal(left_edges, np.array([2, 4, 7, 11, 16]), check_dtype=False)
+ xp_assert_equal(right_edges, np.array([2, 5, 9, 14, 20]), check_dtype=False)
+
+ @pytest.mark.parametrize('x', [
+ np.array([1., 0, 2]),
+ np.array([3., 3, 0, 4, 4]),
+ np.array([5., 5, 5, 0, 6, 6, 6]),
+ ])
+ def test_signal_edges(self, x):
+ """Test if behavior on signal edges is correct."""
+ for array in _local_maxima_1d(x):
+ xp_assert_equal(array, np.array([], dtype=np.intp))
+ assert array.base is None
+
+ def test_exceptions(self):
+ """Test input validation and raised exceptions."""
+ with raises(ValueError, match="wrong number of dimensions"):
+ _local_maxima_1d(np.ones((1, 1)))
+ with raises(ValueError, match="expected 'const float64_t'"):
+ _local_maxima_1d(np.ones(1, dtype=int))
+ with raises(TypeError, match="list"):
+ _local_maxima_1d([1., 2.])
+ with raises(TypeError, match="'x' must not be None"):
+ _local_maxima_1d(None)
+
+
+class TestRidgeLines:
+
+ def test_empty(self):
+ test_matr = np.zeros([20, 100])
+ lines = _identify_ridge_lines(test_matr, np.full(20, 2), 1)
+ assert len(lines) == 0
+
+ def test_minimal(self):
+ test_matr = np.zeros([20, 100])
+ test_matr[0, 10] = 1
+ lines = _identify_ridge_lines(test_matr, np.full(20, 2), 1)
+ assert len(lines) == 1
+
+ test_matr = np.zeros([20, 100])
+ test_matr[0:2, 10] = 1
+ lines = _identify_ridge_lines(test_matr, np.full(20, 2), 1)
+ assert len(lines) == 1
+
+ def test_single_pass(self):
+ distances = [0, 1, 2, 5]
+ gaps = [0, 1, 2, 0, 1]
+ test_matr = np.zeros([20, 50]) + 1e-12
+ length = 12
+ line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps)
+ test_matr[line[0], line[1]] = 1
+ max_distances = np.full(20, max(distances))
+ identified_lines = _identify_ridge_lines(test_matr,
+ max_distances,
+ max(gaps) + 1)
+ assert len(identified_lines) == 1
+ for iline_, line_ in zip(identified_lines[0], line):
+ xp_assert_equal(iline_, line_, check_dtype=False)
+
+ def test_single_bigdist(self):
+ distances = [0, 1, 2, 5]
+ gaps = [0, 1, 2, 4]
+ test_matr = np.zeros([20, 50])
+ length = 12
+ line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps)
+ test_matr[line[0], line[1]] = 1
+ max_dist = 3
+ max_distances = np.full(20, max_dist)
+ #This should get 2 lines, since the distance is too large
+ identified_lines = _identify_ridge_lines(test_matr,
+ max_distances,
+ max(gaps) + 1)
+ assert len(identified_lines) == 2
+
+ for iline in identified_lines:
+ adists = np.diff(iline[1])
+ np.testing.assert_array_less(np.abs(adists), max_dist)
+
+ agaps = np.diff(iline[0])
+ np.testing.assert_array_less(np.abs(agaps), max(gaps) + 0.1)
+
+ def test_single_biggap(self):
+ distances = [0, 1, 2, 5]
+ max_gap = 3
+ gaps = [0, 4, 2, 1]
+ test_matr = np.zeros([20, 50])
+ length = 12
+ line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps)
+ test_matr[line[0], line[1]] = 1
+ max_dist = 6
+ max_distances = np.full(20, max_dist)
+ #This should get 2 lines, since the gap is too large
+ identified_lines = _identify_ridge_lines(test_matr, max_distances, max_gap)
+ assert len(identified_lines) == 2
+
+ for iline in identified_lines:
+ adists = np.diff(iline[1])
+ np.testing.assert_array_less(np.abs(adists), max_dist)
+
+ agaps = np.diff(iline[0])
+ np.testing.assert_array_less(np.abs(agaps), max(gaps) + 0.1)
+
+ def test_single_biggaps(self):
+ distances = [0]
+ max_gap = 1
+ gaps = [3, 6]
+ test_matr = np.zeros([50, 50])
+ length = 30
+ line = _gen_ridge_line([0, 25], test_matr.shape, length, distances, gaps)
+ test_matr[line[0], line[1]] = 1
+ max_dist = 1
+ max_distances = np.full(50, max_dist)
+ #This should get 3 lines, since the gaps are too large
+ identified_lines = _identify_ridge_lines(test_matr, max_distances, max_gap)
+ assert len(identified_lines) == 3
+
+ for iline in identified_lines:
+ adists = np.diff(iline[1])
+ np.testing.assert_array_less(np.abs(adists), max_dist)
+
+ agaps = np.diff(iline[0])
+ np.testing.assert_array_less(np.abs(agaps), max(gaps) + 0.1)
+
+
+class TestArgrel:
+
+ def test_empty(self):
+ # Regression test for gh-2832.
+ # When there are no relative extrema, make sure that
+ # the number of empty arrays returned matches the
+ # dimension of the input.
+
+ empty_array = np.array([], dtype=int)
+
+ z1 = np.zeros(5)
+
+ i = argrelmin(z1)
+ xp_assert_equal(len(i), 1)
+ xp_assert_equal(i[0], empty_array, check_dtype=False)
+
+ z2 = np.zeros((3, 5))
+
+ row, col = argrelmin(z2, axis=0)
+ xp_assert_equal(row, empty_array, check_dtype=False)
+ xp_assert_equal(col, empty_array, check_dtype=False)
+
+ row, col = argrelmin(z2, axis=1)
+ xp_assert_equal(row, empty_array, check_dtype=False)
+ xp_assert_equal(col, empty_array, check_dtype=False)
+
+ def test_basic(self):
+ # Note: the docstrings for the argrel{min,max,extrema} functions
+ # do not give a guarantee of the order of the indices, so we'll
+ # sort them before testing.
+
+ x = np.array([[1, 2, 2, 3, 2],
+ [2, 1, 2, 2, 3],
+ [3, 2, 1, 2, 2],
+ [2, 3, 2, 1, 2],
+ [1, 2, 3, 2, 1]])
+
+ row, col = argrelmax(x, axis=0)
+ order = np.argsort(row)
+ xp_assert_equal(row[order], [1, 2, 3], check_dtype=False)
+ xp_assert_equal(col[order], [4, 0, 1], check_dtype=False)
+
+ row, col = argrelmax(x, axis=1)
+ order = np.argsort(row)
+ xp_assert_equal(row[order], [0, 3, 4], check_dtype=False)
+ xp_assert_equal(col[order], [3, 1, 2], check_dtype=False)
+
+ row, col = argrelmin(x, axis=0)
+ order = np.argsort(row)
+ xp_assert_equal(row[order], [1, 2, 3], check_dtype=False)
+ xp_assert_equal(col[order], [1, 2, 3], check_dtype=False)
+
+ row, col = argrelmin(x, axis=1)
+ order = np.argsort(row)
+ xp_assert_equal(row[order], [1, 2, 3], check_dtype=False)
+ xp_assert_equal(col[order], [1, 2, 3], check_dtype=False)
+
+ def test_highorder(self):
+ order = 2
+ sigmas = [1.0, 2.0, 10.0, 5.0, 15.0]
+ test_data, act_locs = _gen_gaussians_even(sigmas, 500)
+ test_data[act_locs + order] = test_data[act_locs]*0.99999
+ test_data[act_locs - order] = test_data[act_locs]*0.99999
+ rel_max_locs = argrelmax(test_data, order=order, mode='clip')[0]
+
+ assert len(rel_max_locs) == len(act_locs)
+ assert (rel_max_locs == act_locs).all()
+
+ def test_2d_gaussians(self):
+ sigmas = [1.0, 2.0, 10.0]
+ test_data, act_locs = _gen_gaussians_even(sigmas, 100)
+ rot_factor = 20
+ rot_range = np.arange(0, len(test_data)) - rot_factor
+ test_data_2 = np.vstack([test_data, test_data[rot_range]])
+ rel_max_rows, rel_max_cols = argrelmax(test_data_2, axis=1, order=1)
+
+ for rw in range(0, test_data_2.shape[0]):
+ inds = (rel_max_rows == rw)
+
+ assert len(rel_max_cols[inds]) == len(act_locs)
+ assert (act_locs == (rel_max_cols[inds] - rot_factor*rw)).all()
+
+
+class TestPeakProminences:
+
+ def test_empty(self):
+ """
+ Test if an empty array is returned if no peaks are provided.
+ """
+ out = peak_prominences([1, 2, 3], [])
+ for arr, dtype in zip(out, [np.float64, np.intp, np.intp]):
+ assert arr.size == 0
+ assert arr.dtype == dtype
+
+ out = peak_prominences([], [])
+ for arr, dtype in zip(out, [np.float64, np.intp, np.intp]):
+ assert arr.size == 0
+ assert arr.dtype == dtype
+
+ def test_basic(self):
+ """
+ Test if height of prominences is correctly calculated in signal with
+ rising baseline (peak widths are 1 sample).
+ """
+ # Prepare basic signal
+ x = np.array([-1, 1.2, 1.2, 1, 3.2, 1.3, 2.88, 2.1])
+ peaks = np.array([1, 2, 4, 6])
+ lbases = np.array([0, 0, 0, 5])
+ rbases = np.array([3, 3, 5, 7])
+ proms = x[peaks] - np.max([x[lbases], x[rbases]], axis=0)
+ # Test if calculation matches handcrafted result
+ out = peak_prominences(x, peaks)
+ xp_assert_equal(out[0], proms, check_dtype=False)
+ xp_assert_equal(out[1], lbases, check_dtype=False)
+ xp_assert_equal(out[2], rbases, check_dtype=False)
+
+ def test_edge_cases(self):
+ """
+ Test edge cases.
+ """
+ # Peaks have same height, prominence and bases
+ x = [0, 2, 1, 2, 1, 2, 0]
+ peaks = [1, 3, 5]
+ proms, lbases, rbases = peak_prominences(x, peaks)
+ xp_assert_equal(proms, np.asarray([2.0, 2, 2]), check_dtype=False)
+ xp_assert_equal(lbases, [0, 0, 0], check_dtype=False)
+ xp_assert_equal(rbases, [6, 6, 6], check_dtype=False)
+
+ # Peaks have same height & prominence but different bases
+ x = [0, 1, 0, 1, 0, 1, 0]
+ peaks = np.array([1, 3, 5])
+ proms, lbases, rbases = peak_prominences(x, peaks)
+ xp_assert_equal(proms, np.asarray([1.0, 1, 1]))
+ xp_assert_equal(lbases, peaks - 1, check_dtype=False)
+ xp_assert_equal(rbases, peaks + 1, check_dtype=False)
+
+ def test_non_contiguous(self):
+ """
+ Test with non-C-contiguous input arrays.
+ """
+ x = np.repeat([-9, 9, 9, 0, 3, 1], 2)
+ peaks = np.repeat([1, 2, 4], 2)
+ proms, lbases, rbases = peak_prominences(x[::2], peaks[::2])
+ xp_assert_equal(proms, np.asarray([9.0, 9, 2]))
+ xp_assert_equal(lbases, [0, 0, 3], check_dtype=False)
+ xp_assert_equal(rbases, [3, 3, 5], check_dtype=False)
+
+ def test_wlen(self):
+ """
+ Test if wlen actually shrinks the evaluation range correctly.
+ """
+ x = [0, 1, 2, 3, 1, 0, -1]
+ peak = [3]
+ # Test rounding behavior of wlen
+ proms = peak_prominences(x, peak)
+ for prom, val in zip(proms, [3.0, 0, 6]):
+ assert prom == val
+
+ for wlen, i in [(8, 0), (7, 0), (6, 0), (5, 1), (3.2, 1), (3, 2), (1.1, 2)]:
+ proms = peak_prominences(x, peak, wlen)
+ for prom, val in zip(proms, [3. - i, 0 + i, 6 - i]):
+ assert prom == val
+
+ def test_exceptions(self):
+ """
+ Verify that exceptions and warnings are raised.
+ """
+ # x with dimension > 1
+ with raises(ValueError, match='1-D array'):
+ peak_prominences([[0, 1, 1, 0]], [1, 2])
+ # peaks with dimension > 1
+ with raises(ValueError, match='1-D array'):
+ peak_prominences([0, 1, 1, 0], [[1, 2]])
+ # x with dimension < 1
+ with raises(ValueError, match='1-D array'):
+ peak_prominences(3, [0,])
+
+ # empty x with supplied
+ with raises(ValueError, match='not a valid index'):
+ peak_prominences([], [0])
+ # invalid indices with non-empty x
+ for p in [-100, -1, 3, 1000]:
+ with raises(ValueError, match='not a valid index'):
+ peak_prominences([1, 0, 2], [p])
+
+ # peaks is not cast-able to np.intp
+ with raises(TypeError, match='cannot safely cast'):
+ peak_prominences([0, 1, 1, 0], [1.1, 2.3])
+
+ # wlen < 3
+ with raises(ValueError, match='wlen'):
+ peak_prominences(np.arange(10), [3, 5], wlen=1)
+
+ def test_warnings(self):
+ """
+ Verify that appropriate warnings are raised.
+ """
+ msg = "some peaks have a prominence of 0"
+ for p in [0, 1, 2]:
+ with warns(PeakPropertyWarning, match=msg):
+ peak_prominences([1, 0, 2], [p,])
+ with warns(PeakPropertyWarning, match=msg):
+ peak_prominences([0, 1, 1, 1, 0], [2], wlen=2)
+
+
+class TestPeakWidths:
+
+ def test_empty(self):
+ """
+ Test if an empty array is returned if no peaks are provided.
+ """
+ widths = peak_widths([], [])[0]
+ assert isinstance(widths, np.ndarray)
+ assert widths.size == 0
+ widths = peak_widths([1, 2, 3], [])[0]
+ assert isinstance(widths, np.ndarray)
+ assert widths.size == 0
+ out = peak_widths([], [])
+ for arr in out:
+ assert isinstance(arr, np.ndarray)
+ assert arr.size == 0
+
+ @pytest.mark.filterwarnings("ignore:some peaks have a width of 0")
+ def test_basic(self):
+ """
+ Test a simple use case with easy to verify results at different relative
+ heights.
+ """
+ x = np.array([1, 0, 1, 2, 1, 0, -1])
+ prominence = 2
+ for rel_height, width_true, lip_true, rip_true in [
+ (0., 0., 3., 3.), # raises warning
+ (0.25, 1., 2.5, 3.5),
+ (0.5, 2., 2., 4.),
+ (0.75, 3., 1.5, 4.5),
+ (1., 4., 1., 5.),
+ (2., 5., 1., 6.),
+ (3., 5., 1., 6.)
+ ]:
+ width_calc, height, lip_calc, rip_calc = peak_widths(
+ x, [3], rel_height)
+ xp_assert_close(width_calc, np.asarray([width_true]))
+ xp_assert_close(height, np.asarray([2 - rel_height * prominence]))
+ xp_assert_close(lip_calc, np.asarray([lip_true]))
+ xp_assert_close(rip_calc, np.asarray([rip_true]))
+
+ def test_non_contiguous(self):
+ """
+ Test with non-C-contiguous input arrays.
+ """
+ x = np.repeat([0, 100, 50], 4)
+ peaks = np.repeat([1], 3)
+ result = peak_widths(x[::4], peaks[::3])
+ xp_assert_equal(result,
+ np.asarray([[0.75], [75], [0.75], [1.5]])
+ )
+
+ def test_exceptions(self):
+ """
+ Verify that argument validation works as intended.
+ """
+ with raises(ValueError, match='1-D array'):
+ # x with dimension > 1
+ peak_widths(np.zeros((3, 4)), np.ones(3))
+ with raises(ValueError, match='1-D array'):
+ # x with dimension < 1
+ peak_widths(3, [0])
+ with raises(ValueError, match='1-D array'):
+ # peaks with dimension > 1
+ peak_widths(np.arange(10), np.ones((3, 2), dtype=np.intp))
+ with raises(ValueError, match='1-D array'):
+ # peaks with dimension < 1
+ peak_widths(np.arange(10), 3)
+ with raises(ValueError, match='not a valid index'):
+ # peak pos exceeds x.size
+ peak_widths(np.arange(10), [8, 11])
+ with raises(ValueError, match='not a valid index'):
+ # empty x with peaks supplied
+ peak_widths([], [1, 2])
+ with raises(TypeError, match='cannot safely cast'):
+ # peak cannot be safely cast to intp
+ peak_widths(np.arange(10), [1.1, 2.3])
+ with raises(ValueError, match='rel_height'):
+ # rel_height is < 0
+ peak_widths([0, 1, 0, 1, 0], [1, 3], rel_height=-1)
+ with raises(TypeError, match='None'):
+ # prominence data contains None
+ peak_widths([1, 2, 1], [1], prominence_data=(None, None, None))
+
+ def test_warnings(self):
+ """
+ Verify that appropriate warnings are raised.
+ """
+ msg = "some peaks have a width of 0"
+ with warns(PeakPropertyWarning, match=msg):
+ # Case: rel_height is 0
+ peak_widths([0, 1, 0], [1], rel_height=0)
+ with warns(PeakPropertyWarning, match=msg):
+ # Case: prominence is 0 and bases are identical
+ peak_widths(
+ [0, 1, 1, 1, 0], [2],
+ prominence_data=(np.array([0.], np.float64),
+ np.array([2], np.intp),
+ np.array([2], np.intp))
+ )
+
+ def test_mismatching_prominence_data(self):
+ """Test with mismatching peak and / or prominence data."""
+ x = [0, 1, 0]
+ peak = [1]
+ for i, (prominences, left_bases, right_bases) in enumerate([
+ ((1.,), (-1,), (2,)), # left base not in x
+ ((1.,), (0,), (3,)), # right base not in x
+ ((1.,), (2,), (0,)), # swapped bases same as peak
+ ((1., 1.), (0, 0), (2, 2)), # array shapes don't match peaks
+ ((1., 1.), (0,), (2,)), # arrays with different shapes
+ ((1.,), (0, 0), (2,)), # arrays with different shapes
+ ((1.,), (0,), (2, 2)) # arrays with different shapes
+ ]):
+ # Make sure input is matches output of signal.peak_prominences
+ prominence_data = (np.array(prominences, dtype=np.float64),
+ np.array(left_bases, dtype=np.intp),
+ np.array(right_bases, dtype=np.intp))
+ # Test for correct exception
+ if i < 3:
+ match = "prominence data is invalid for peak"
+ else:
+ match = "arrays in `prominence_data` must have the same shape"
+ with raises(ValueError, match=match):
+ peak_widths(x, peak, prominence_data=prominence_data)
+
+ @pytest.mark.filterwarnings("ignore:some peaks have a width of 0")
+ def test_intersection_rules(self):
+ """Test if x == eval_height counts as an intersection."""
+ # Flatt peak with two possible intersection points if evaluated at 1
+ x = [0, 1, 2, 1, 3, 3, 3, 1, 2, 1, 0]
+ # relative height is 0 -> width is 0 as well, raises warning
+ xp_assert_close(peak_widths(x, peaks=[5], rel_height=0),
+ [(0.,), (3.,), (5.,), (5.,)])
+ # width_height == x counts as intersection -> nearest 1 is chosen
+ xp_assert_close(peak_widths(x, peaks=[5], rel_height=2/3),
+ [(4.,), (1.,), (3.,), (7.,)])
+
+
+def test_unpack_condition_args():
+ """
+ Verify parsing of condition arguments for `scipy.signal.find_peaks` function.
+ """
+ x = np.arange(10)
+ amin_true = x
+ amax_true = amin_true + 10
+ peaks = amin_true[1::2]
+
+ # Test unpacking with None or interval
+ assert (None, None) == _unpack_condition_args((None, None), x, peaks)
+ assert (1, None) == _unpack_condition_args(1, x, peaks)
+ assert (1, None) == _unpack_condition_args((1, None), x, peaks)
+ assert (None, 2) == _unpack_condition_args((None, 2), x, peaks)
+ assert (3., 4.5) == _unpack_condition_args((3., 4.5), x, peaks)
+
+ # Test if borders are correctly reduced with `peaks`
+ amin_calc, amax_calc = _unpack_condition_args((amin_true, amax_true), x, peaks)
+ xp_assert_equal(amin_calc, amin_true[peaks])
+ xp_assert_equal(amax_calc, amax_true[peaks])
+
+ # Test raises if array borders don't match x
+ with raises(ValueError, match="array size of lower"):
+ _unpack_condition_args(amin_true, np.arange(11), peaks)
+ with raises(ValueError, match="array size of upper"):
+ _unpack_condition_args((None, amin_true), np.arange(11), peaks)
+
+
+class TestFindPeaks:
+
+ # Keys of optionally returned properties
+ property_keys = {'peak_heights', 'left_thresholds', 'right_thresholds',
+ 'prominences', 'left_bases', 'right_bases', 'widths',
+ 'width_heights', 'left_ips', 'right_ips'}
+
+ def test_constant(self):
+ """
+ Test behavior for signal without local maxima.
+ """
+ open_interval = (None, None)
+ peaks, props = find_peaks(np.ones(10),
+ height=open_interval, threshold=open_interval,
+ prominence=open_interval, width=open_interval)
+ assert peaks.size == 0
+ for key in self.property_keys:
+ assert props[key].size == 0
+
+ def test_plateau_size(self):
+ """
+ Test plateau size condition for peaks.
+ """
+ # Prepare signal with peaks with peak_height == plateau_size
+ plateau_sizes = np.array([1, 2, 3, 4, 8, 20, 111])
+ x = np.zeros(plateau_sizes.size * 2 + 1)
+ x[1::2] = plateau_sizes
+ repeats = np.ones(x.size, dtype=int)
+ repeats[1::2] = x[1::2]
+ x = np.repeat(x, repeats)
+
+ # Test full output
+ peaks, props = find_peaks(x, plateau_size=(None, None))
+ xp_assert_equal(peaks, [1, 3, 7, 11, 18, 33, 100], check_dtype=False)
+ xp_assert_equal(props["plateau_sizes"], plateau_sizes, check_dtype=False)
+ xp_assert_equal(props["left_edges"], peaks - (plateau_sizes - 1) // 2,
+ check_dtype=False)
+ xp_assert_equal(props["right_edges"], peaks + plateau_sizes // 2,
+ check_dtype=False)
+
+ # Test conditions
+ xp_assert_equal(find_peaks(x, plateau_size=4)[0], [11, 18, 33, 100],
+ check_dtype=False)
+ xp_assert_equal(find_peaks(x, plateau_size=(None, 3.5))[0], [1, 3, 7],
+ check_dtype=False)
+ xp_assert_equal(find_peaks(x, plateau_size=(5, 50))[0], [18, 33],
+ check_dtype=False)
+
+ def test_height_condition(self):
+ """
+ Test height condition for peaks.
+ """
+ x = (0., 1/3, 0., 2.5, 0, 4., 0)
+ peaks, props = find_peaks(x, height=(None, None))
+ xp_assert_equal(peaks, np.array([1, 3, 5]), check_dtype=False)
+ xp_assert_equal(props['peak_heights'], np.array([1/3, 2.5, 4.]),
+ check_dtype=False)
+ xp_assert_equal(find_peaks(x, height=0.5)[0], np.array([3, 5]),
+ check_dtype=False)
+ xp_assert_equal(find_peaks(x, height=(None, 3))[0], np.array([1, 3]),
+ check_dtype=False)
+ xp_assert_equal(find_peaks(x, height=(2, 3))[0], np.array([3]),
+ check_dtype=False)
+
+ def test_threshold_condition(self):
+ """
+ Test threshold condition for peaks.
+ """
+ x = (0, 2, 1, 4, -1)
+ peaks, props = find_peaks(x, threshold=(None, None))
+ xp_assert_equal(peaks, np.array([1, 3]), check_dtype=False)
+ xp_assert_equal(props['left_thresholds'], np.array([2.0, 3.0]))
+ xp_assert_equal(props['right_thresholds'], np.array([1.0, 5.0]))
+ xp_assert_equal(find_peaks(x, threshold=2)[0], np.array([3]),
+ check_dtype=False)
+ xp_assert_equal(find_peaks(x, threshold=3.5)[0], np.array([], dtype=int),
+ check_dtype=False)
+ xp_assert_equal(find_peaks(x, threshold=(None, 5))[0], np.array([1, 3]),
+ check_dtype=False)
+ xp_assert_equal(find_peaks(x, threshold=(None, 4))[0], np.array([1]),
+ check_dtype=False)
+ xp_assert_equal(find_peaks(x, threshold=(2, 4))[0], np.array([], dtype=int),
+ check_dtype=False)
+
+ def test_distance_condition(self):
+ """
+ Test distance condition for peaks.
+ """
+ # Peaks of different height with constant distance 3
+ peaks_all = np.arange(1, 21, 3)
+ x = np.zeros(21)
+ x[peaks_all] += np.linspace(1, 2, peaks_all.size)
+
+ # Test if peaks with "minimal" distance are still selected (distance = 3)
+ xp_assert_equal(find_peaks(x, distance=3)[0], peaks_all, check_dtype=False)
+
+ # Select every second peak (distance > 3)
+ peaks_subset = find_peaks(x, distance=3.0001)[0]
+ # Test if peaks_subset is subset of peaks_all
+ assert np.setdiff1d(peaks_subset, peaks_all, assume_unique=True).size == 0
+
+ # Test if every second peak was removed
+ dfs = np.diff(peaks_subset)
+ xp_assert_equal(dfs, 6*np.ones_like(dfs))
+
+ # Test priority of peak removal
+ x = [-2, 1, -1, 0, -3]
+ peaks_subset = find_peaks(x, distance=10)[0] # use distance > x size
+ assert peaks_subset.size == 1 and peaks_subset[0] == 1
+
+ def test_prominence_condition(self):
+ """
+ Test prominence condition for peaks.
+ """
+ x = np.linspace(0, 10, 100)
+ peaks_true = np.arange(1, 99, 2)
+ offset = np.linspace(1, 10, peaks_true.size)
+ x[peaks_true] += offset
+ prominences = x[peaks_true] - x[peaks_true + 1]
+ interval = (3, 9)
+ keep = np.nonzero(
+ (interval[0] <= prominences) & (prominences <= interval[1]))
+
+ peaks_calc, properties = find_peaks(x, prominence=interval)
+ xp_assert_equal(peaks_calc, peaks_true[keep], check_dtype=False)
+ xp_assert_equal(properties['prominences'], prominences[keep], check_dtype=False)
+ xp_assert_equal(properties['left_bases'],
+ np.zeros_like(properties['left_bases']))
+ xp_assert_equal(properties['right_bases'], peaks_true[keep] + 1,
+ check_dtype=False)
+
+ def test_width_condition(self):
+ """
+ Test width condition for peaks.
+ """
+ x = np.array([1, 0, 1, 2, 1, 0, -1, 4, 0])
+ peaks, props = find_peaks(x, width=(None, 2), rel_height=0.75)
+ assert peaks.size == 1
+ xp_assert_equal(peaks, 7*np.ones_like(peaks))
+ xp_assert_close(props['widths'], np.asarray([1.35]))
+ xp_assert_close(props['width_heights'], np.asarray([1.]))
+ xp_assert_close(props['left_ips'], np.asarray([6.4]))
+ xp_assert_close(props['right_ips'], np.asarray([7.75]))
+
+ def test_properties(self):
+ """
+ Test returned properties.
+ """
+ open_interval = (None, None)
+ x = [0, 1, 0, 2, 1.5, 0, 3, 0, 5, 9]
+ peaks, props = find_peaks(x,
+ height=open_interval, threshold=open_interval,
+ prominence=open_interval, width=open_interval)
+ assert len(props) == len(self.property_keys)
+ for key in self.property_keys:
+ assert peaks.size == props[key].size
+
+ def test_raises(self):
+ """
+ Test exceptions raised by function.
+ """
+ with raises(ValueError, match="1-D array"):
+ find_peaks(np.array(1))
+ with raises(ValueError, match="1-D array"):
+ find_peaks(np.ones((2, 2)))
+ with raises(ValueError, match="distance"):
+ find_peaks(np.arange(10), distance=-1)
+
+ @pytest.mark.filterwarnings("ignore:some peaks have a prominence of 0",
+ "ignore:some peaks have a width of 0")
+ def test_wlen_smaller_plateau(self):
+ """
+ Test behavior of prominence and width calculation if the given window
+ length is smaller than a peak's plateau size.
+
+ Regression test for gh-9110.
+ """
+ peaks, props = find_peaks([0, 1, 1, 1, 0], prominence=(None, None),
+ width=(None, None), wlen=2)
+ xp_assert_equal(peaks, 2 * np.ones_like(peaks))
+ xp_assert_equal(props["prominences"], np.zeros_like(props["prominences"]))
+ xp_assert_equal(props["widths"], np.zeros_like(props["widths"]))
+ xp_assert_equal(props["width_heights"], np.ones_like(props["width_heights"]))
+ for key in ("left_bases", "right_bases", "left_ips", "right_ips"):
+ xp_assert_equal(props[key], peaks, check_dtype=False)
+
+ @pytest.mark.parametrize("kwargs", [
+ {},
+ {"distance": 3.0},
+ {"prominence": (None, None)},
+ {"width": (None, 2)},
+
+ ])
+ def test_readonly_array(self, kwargs):
+ """
+ Test readonly arrays are accepted.
+ """
+ x = np.linspace(0, 10, 15)
+ x_readonly = x.copy()
+ x_readonly.flags.writeable = False
+
+ peaks, _ = find_peaks(x)
+ peaks_readonly, _ = find_peaks(x_readonly, **kwargs)
+
+ xp_assert_close(peaks, peaks_readonly)
+
+
+class TestFindPeaksCwt:
+
+ def test_find_peaks_exact(self):
+ """
+ Generate a series of gaussians and attempt to find the peak locations.
+ """
+ sigmas = [5.0, 3.0, 10.0, 20.0, 10.0, 50.0]
+ num_points = 500
+ test_data, act_locs = _gen_gaussians_even(sigmas, num_points)
+ widths = np.arange(0.1, max(sigmas))
+ found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=0,
+ min_length=None)
+ xp_assert_equal(found_locs, act_locs,
+ check_dtype=False,
+ err_msg="Found maximum locations did not equal those expected"
+ )
+
+ def test_find_peaks_withnoise(self):
+ """
+ Verify that peak locations are (approximately) found
+ for a series of gaussians with added noise.
+ """
+ sigmas = [5.0, 3.0, 10.0, 20.0, 10.0, 50.0]
+ num_points = 500
+ test_data, act_locs = _gen_gaussians_even(sigmas, num_points)
+ widths = np.arange(0.1, max(sigmas))
+ noise_amp = 0.07
+ rng = np.random.default_rng(18181911)
+ test_data += (rng.random(num_points) - 0.5)*(2*noise_amp)
+ found_locs = find_peaks_cwt(test_data, widths, min_length=15,
+ gap_thresh=1, min_snr=noise_amp / 5)
+
+ err_msg ='Different number of peaks found than expected'
+ assert len(found_locs) == len(act_locs), err_msg
+ diffs = np.abs(found_locs - act_locs)
+ max_diffs = np.array(sigmas) / 5
+ np.testing.assert_array_less(diffs, max_diffs, 'Maximum location differed' +
+ f'by more than {max_diffs}')
+
+ def test_find_peaks_nopeak(self):
+ """
+ Verify that no peak is found in
+ data that's just noise.
+ """
+ noise_amp = 1.0
+ num_points = 100
+ rng = np.random.RandomState(181819141)
+ test_data = (rng.rand(num_points) - 0.5)*(2*noise_amp)
+ widths = np.arange(10, 50)
+ found_locs = find_peaks_cwt(test_data, widths, min_snr=5, noise_perc=30)
+ assert len(found_locs) == 0
+
+ def test_find_peaks_with_non_default_wavelets(self):
+ x = gaussian(200, 2)
+ widths = np.array([1, 2, 3, 4])
+ a = find_peaks_cwt(x, widths, wavelet=gaussian)
+
+ xp_assert_equal(a, np.asarray([100]), check_dtype=False)
+
+ def test_find_peaks_window_size(self):
+ """
+ Verify that window_size is passed correctly to private function and
+ affects the result.
+ """
+ sigmas = [2.0, 2.0]
+ num_points = 1000
+ test_data, act_locs = _gen_gaussians_even(sigmas, num_points)
+ widths = np.arange(0.1, max(sigmas), 0.2)
+ noise_amp = 0.05
+ rng = np.random.RandomState(18181911)
+ test_data += (rng.rand(num_points) - 0.5)*(2*noise_amp)
+
+ # Possibly contrived negative region to throw off peak finding
+ # when window_size is too large
+ test_data[250:320] -= 1
+
+ found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=3,
+ min_length=None, window_size=None)
+ with pytest.raises(AssertionError):
+ assert found_locs.size == act_locs.size
+
+ found_locs = find_peaks_cwt(test_data, widths, gap_thresh=2, min_snr=3,
+ min_length=None, window_size=20)
+ assert found_locs.size == act_locs.size
+
+ def test_find_peaks_with_one_width(self):
+ """
+ Verify that the `width` argument
+ in `find_peaks_cwt` can be a float
+ """
+ xs = np.arange(0, np.pi, 0.05)
+ test_data = np.sin(xs)
+ widths = 1
+ found_locs = find_peaks_cwt(test_data, widths)
+
+ np.testing.assert_equal(found_locs, 32)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_result_type.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_result_type.py
new file mode 100644
index 0000000000000000000000000000000000000000..a2cadd325a7e36c877df8532ba957712831c2dad
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_result_type.py
@@ -0,0 +1,51 @@
+# Regressions tests on result types of some signal functions
+
+import numpy as np
+
+from scipy.signal import (decimate,
+ lfilter_zi,
+ lfiltic,
+ sos2tf,
+ sosfilt_zi)
+
+
+def test_decimate():
+ ones_f32 = np.ones(32, dtype=np.float32)
+ assert decimate(ones_f32, 2).dtype == np.float32
+
+ ones_i64 = np.ones(32, dtype=np.int64)
+ assert decimate(ones_i64, 2).dtype == np.float64
+
+
+def test_lfilter_zi():
+ b_f32 = np.array([1, 2, 3], dtype=np.float32)
+ a_f32 = np.array([4, 5, 6], dtype=np.float32)
+ assert lfilter_zi(b_f32, a_f32).dtype == np.float32
+
+
+def test_lfiltic():
+ # this would return f32 when given a mix of f32 / f64 args
+ b_f32 = np.array([1, 2, 3], dtype=np.float32)
+ a_f32 = np.array([4, 5, 6], dtype=np.float32)
+ x_f32 = np.ones(32, dtype=np.float32)
+
+ b_f64 = b_f32.astype(np.float64)
+ a_f64 = a_f32.astype(np.float64)
+ x_f64 = x_f32.astype(np.float64)
+
+ assert lfiltic(b_f64, a_f32, x_f32).dtype == np.float64
+ assert lfiltic(b_f32, a_f64, x_f32).dtype == np.float64
+ assert lfiltic(b_f32, a_f32, x_f64).dtype == np.float64
+ assert lfiltic(b_f32, a_f32, x_f32, x_f64).dtype == np.float64
+
+
+def test_sos2tf():
+ sos_f32 = np.array([[4, 5, 6, 1, 2, 3]], dtype=np.float32)
+ b, a = sos2tf(sos_f32)
+ assert b.dtype == np.float32
+ assert a.dtype == np.float32
+
+
+def test_sosfilt_zi():
+ sos_f32 = np.array([[4, 5, 6, 1, 2, 3]], dtype=np.float32)
+ assert sosfilt_zi(sos_f32).dtype == np.float32
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_savitzky_golay.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_savitzky_golay.py
new file mode 100644
index 0000000000000000000000000000000000000000..f819910c3dbea4e83e4dbb3d1db2189cf3fa1cc0
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_savitzky_golay.py
@@ -0,0 +1,396 @@
+import pytest
+import numpy as np
+
+from scipy._lib._array_api import (
+ xp_assert_close, xp_assert_equal, xp_swapaxes, is_torch, make_xp_test_case,
+ _xp_copy_to_numpy
+)
+
+from scipy.ndimage import convolve1d # type: ignore[attr-defined]
+
+from scipy.signal import savgol_coeffs, savgol_filter
+from scipy.signal._savitzky_golay import _polyder
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+pytestmark = pytest.mark.skip_xp_backends(
+ "dask.array", reason="linalg.lstsq is missing rcond"
+)
+
+
+def check_polyder(p, m, expected, xp):
+ dp = _polyder(p, m, xp=xp)
+ xp_assert_equal(dp, expected)
+
+
+def test_polyder(xp):
+ cases = [
+ ([5], 0, [5]),
+ ([5], 1, [0]),
+ ([3, 2, 1], 0, [3, 2, 1]),
+ ([3, 2, 1], 1, [6, 2]),
+ ([3, 2, 1], 2, [6]),
+ ([3, 2, 1], 3, [0]),
+ ([[3, 2, 1], [5, 6, 7]], 0, [[3, 2, 1], [5, 6, 7]]),
+ ([[3, 2, 1], [5, 6, 7]], 1, [[6, 2], [10, 6]]),
+ ([[3, 2, 1], [5, 6, 7]], 2, [[6], [10]]),
+ ([[3, 2, 1], [5, 6, 7]], 3, [[0], [0]]),
+ ]
+ for p, m, expected in cases:
+ pp = xp.asarray(p)
+ ee = xp.asarray(expected)
+ check_polyder(
+ pp.T if pp.ndim == 2 else pp,
+ m,
+ ee.T if ee.ndim ==2 else ee,
+ xp
+ )
+
+
+#--------------------------------------------------------------------
+# savgol_coeffs tests
+#--------------------------------------------------------------------
+
+def alt_sg_coeffs(window_length, polyorder, pos, xp):
+ """This is an alternative implementation of the SG coefficients.
+
+ It uses numpy.polyfit and numpy.polyval. The results should be
+ equivalent to those of savgol_coeffs(), but this implementation
+ is slower.
+
+ window_length should be odd.
+
+ """
+ if pos is None:
+ pos = window_length // 2
+ t = np.arange(window_length)
+ unit = (t == pos).astype(int)
+ h = np.polyval(np.polyfit(t, unit, polyorder), t)
+ return xp.asarray(h)
+
+
+@make_xp_test_case(savgol_coeffs)
+def test_sg_coeffs_trivial(xp):
+ # Test a trivial case of savgol_coeffs: polyorder = window_length - 1
+ h = savgol_coeffs(1, 0, xp=xp)
+ xp_assert_close(h, xp.asarray([1.0], dtype=xp.float64))
+
+ h = savgol_coeffs(3, 2, xp=xp)
+ xp_assert_close(h, xp.asarray([0.0, 1, 0], dtype=xp.float64), atol=1e-10)
+
+ h = savgol_coeffs(5, 4, xp=xp)
+ xp_assert_close(h, xp.asarray([0.0, 0, 1, 0, 0], dtype=xp.float64), atol=1e-10)
+
+ h = savgol_coeffs(5, 4, pos=1, xp=xp)
+ xp_assert_close(h, xp.asarray([0.0, 0, 0, 1, 0], dtype=xp.float64), atol=1e-10)
+
+ h = savgol_coeffs(5, 4, pos=1, use='dot', xp=xp)
+ xp_assert_close(h, xp.asarray([0.0, 1, 0, 0, 0], dtype=xp.float64), atol=1e-10)
+
+
+def compare_coeffs_to_alt(window_length, order, xp):
+ # For the given window_length and order, compare the results
+ # of savgol_coeffs and alt_sg_coeffs for pos from 0 to window_length - 1.
+ # Also include pos=None.
+ for pos in [None] + list(range(window_length)):
+ h1 = savgol_coeffs(window_length, order, pos=pos, use='dot', xp=xp)
+ h2 = alt_sg_coeffs(window_length, order, pos=pos, xp=xp)
+ xp_assert_close(
+ h1, h2, atol=2e-10,
+ err_msg=f"window_length = {window_length}, order = {order}, pos = {pos}"
+ )
+
+
+@make_xp_test_case(savgol_coeffs)
+def test_sg_coeffs_compare(xp):
+ # Compare savgol_coeffs() to alt_sg_coeffs().
+ for window_length in range(1, 8, 2):
+ for order in range(window_length):
+ compare_coeffs_to_alt(window_length, order, xp=xp)
+
+
+@make_xp_test_case(savgol_coeffs)
+def test_sg_coeffs_exact(xp):
+ polyorder = 4
+ window_length = 9
+ halflen = window_length // 2
+
+ x = xp.linspace(0, 21, 43)
+ delta = x[1] - x[0]
+
+ # The data is a cubic polynomial. We'll use an order 4
+ # SG filter, so the filtered values should equal the input data
+ # (except within half window_length of the edges).
+ y = 0.5 * x ** 3 - x
+ h = savgol_coeffs(window_length, polyorder, xp=xp)
+ y0 = xp.asarray(convolve1d(_xp_copy_to_numpy(y), _xp_copy_to_numpy(h)))
+ xp_assert_close(y0[halflen:-halflen], y[halflen:-halflen])
+
+ # Check the same input, but use deriv=1. dy is the exact result.
+ dy = 1.5 * x ** 2 - 1
+ h = savgol_coeffs(window_length, polyorder, deriv=1, delta=delta, xp=xp)
+ y1 = xp.asarray(convolve1d(_xp_copy_to_numpy(y), _xp_copy_to_numpy(h)))
+ xp_assert_close(y1[halflen:-halflen], dy[halflen:-halflen])
+
+ # Check the same input, but use deriv=2. d2y is the exact result.
+ d2y = 3.0 * x
+ h = savgol_coeffs(window_length, polyorder, deriv=2, delta=delta, xp=xp)
+ y2 = xp.asarray(convolve1d(_xp_copy_to_numpy(y), _xp_copy_to_numpy(h)))
+ xp_assert_close(y2[halflen:-halflen], d2y[halflen:-halflen])
+
+
+@make_xp_test_case(savgol_coeffs)
+def test_sg_coeffs_deriv(xp):
+ # The data in `x` is a sampled parabola, so using savgol_coeffs with an
+ # order 2 or higher polynomial should give exact results.
+ i = xp.asarray([-2.0, 0.0, 2.0, 4.0, 6.0], dtype=xp.float64)
+ x = i ** 2 / 4
+ dx = i / 2
+ d2x = xp.full_like(i, 0.5)
+ for pos in range(x.shape[0]):
+ coeffs0 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', xp=xp)
+ xp_assert_close(coeffs0 @ x, x[pos], atol=1e-10)
+ coeffs1 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=1, xp=xp)
+ xp_assert_close(coeffs1 @ x, dx[pos], atol=1e-10)
+ coeffs2 = savgol_coeffs(5, 3, pos=pos, delta=2.0, use='dot', deriv=2, xp=xp)
+ xp_assert_close(coeffs2 @ x , d2x[pos], atol=1e-10)
+
+
+@make_xp_test_case(savgol_coeffs)
+def test_sg_coeffs_deriv_gt_polyorder(xp):
+ """
+ If deriv > polyorder, the coefficients should be all 0.
+ This is a regression test for a bug where, e.g.,
+ savgol_coeffs(5, polyorder=1, deriv=2)
+ raised an error.
+ """
+ coeffs = savgol_coeffs(5, polyorder=1, deriv=2, xp=xp)
+ xp_assert_equal(coeffs, xp.zeros(5, dtype=xp.float64))
+ coeffs = savgol_coeffs(7, polyorder=4, deriv=6, xp=xp)
+ xp_assert_equal(coeffs, xp.zeros(7, dtype=xp.float64))
+
+
+@xfail_xp_backends(
+ "torch", reason="torch loses precision (worse with f32 default dtype)"
+)
+@make_xp_test_case(savgol_coeffs)
+def test_sg_coeffs_large(xp):
+ # Test that for large values of window_length and polyorder the array of
+ # coefficients returned is symmetric. The aim is to ensure that
+ # no potential numeric overflow occurs.
+ coeffs0 = savgol_coeffs(31, 9, xp=xp)
+ xp_assert_close(
+ coeffs0, xp.flip(coeffs0), atol=5e-4 if is_torch(xp) else 1.5e-6
+ )
+
+ coeffs1 = savgol_coeffs(31, 9, deriv=1, xp=xp)
+ xp_assert_close(
+ coeffs1, -xp.flip(coeffs1), atol=1.2e-2 if is_torch(xp) else 1.5e-6
+ )
+
+# --------------------------------------------------------------------
+# savgol_coeffs tests for even window length
+# --------------------------------------------------------------------
+
+@make_xp_test_case(savgol_coeffs)
+def test_sg_coeffs_even_window_length(xp):
+ # Simple case - deriv=0, polyorder=0, 1
+ window_lengths = [4, 6, 8, 10, 12, 14, 16]
+ for length in window_lengths:
+ h_p_d = savgol_coeffs(length, 0, 0, xp=xp)
+ xp_assert_close(h_p_d, xp.ones_like(h_p_d) / length)
+
+ # Verify with closed forms
+ # deriv=1, polyorder=1, 2
+ def h_p_d_closed_form_1(k, m):
+ return 6*(k - 0.5)/((2*m + 1)*m*(2*m - 1))
+
+ # deriv=2, polyorder=2
+ def h_p_d_closed_form_2(k, m):
+ numer = 15*(-4*m**2 + 1 + 12*(k - 0.5)**2)
+ denom = 4*(2*m + 1)*(m + 1)*m*(m - 1)*(2*m - 1)
+ return numer/denom
+
+ for length in window_lengths:
+ m = length//2
+ expected_output = [h_p_d_closed_form_1(k, m)
+ for k in range(-m + 1, m + 1)][::-1]
+ expected_output = xp.asarray(expected_output, dtype=xp.float64)
+ actual_output = savgol_coeffs(length, 1, 1, xp=xp)
+ xp_assert_close(actual_output, expected_output)
+ actual_output = savgol_coeffs(length, 2, 1, xp=xp)
+ xp_assert_close(actual_output, expected_output)
+
+ expected_output = [h_p_d_closed_form_2(k, m)
+ for k in range(-m + 1, m + 1)][::-1]
+ expected_output = xp.asarray(expected_output, dtype=xp.float64)
+ actual_output = savgol_coeffs(length, 2, 2, xp=xp)
+ xp_assert_close(actual_output, expected_output)
+ actual_output = savgol_coeffs(length, 3, 2, xp=xp)
+ xp_assert_close(actual_output, expected_output)
+
+#--------------------------------------------------------------------
+# savgol_filter tests
+#--------------------------------------------------------------------
+
+@make_xp_test_case(savgol_filter)
+def test_sg_filter_trivial(xp):
+ """ Test some trivial edge cases for savgol_filter()."""
+ x = xp.asarray([1.0])
+ y = savgol_filter(x, 1, 0)
+ xp_assert_equal(y, xp.asarray([1.0]))
+
+ # Input is a single value. With a window length of 3 and polyorder 1,
+ # the value in y is from the straight-line fit of (-1,0), (0,3) and
+ # (1, 0) at 0. This is just the average of the three values, hence 1.0.
+ x = xp.asarray([3.0])
+ y = savgol_filter(x, 3, 1, mode='constant')
+ xp_assert_close(y, xp.asarray([1.0]), atol=1.5e-15)
+
+ x = xp.asarray([3.0])
+ y = savgol_filter(x, 3, 1, mode='nearest')
+ xp_assert_close(y, xp.asarray([3.0]), atol=1.5e-15)
+
+ x = xp.asarray([1.0] * 3)
+ y = savgol_filter(x, 3, 1, mode='wrap')
+ xp_assert_close(y, xp.asarray([1.0, 1.0, 1.0]), atol=1.5e-15)
+
+
+@make_xp_test_case(savgol_filter)
+def test_sg_filter_basic(xp):
+ # Some basic test cases for savgol_filter().
+ x = xp.asarray([1.0, 2.0, 1.0])
+ y = savgol_filter(x, 3, 1, mode='constant')
+ xp_assert_close(y, xp.asarray([1.0, 4.0 / 3, 1.0]))
+
+ y = savgol_filter(x, 3, 1, mode='mirror')
+ xp_assert_close(y, xp.asarray([5.0 / 3, 4.0 / 3, 5.0 / 3]))
+
+ y = savgol_filter(x, 3, 1, mode='wrap')
+ xp_assert_close(y, xp.asarray([4.0 / 3, 4.0 / 3, 4.0 / 3]))
+
+
+@make_xp_test_case(savgol_filter)
+def test_sg_filter_2d(xp):
+ x = xp.asarray([[1.0, 2.0, 1.0],
+ [2.0, 4.0, 2.0]])
+ expected = xp.asarray([[1.0, 4.0 / 3, 1.0],
+ [2.0, 8.0 / 3, 2.0]])
+ y = savgol_filter(x, 3, 1, mode='constant')
+ xp_assert_close(y, expected)
+
+ y = savgol_filter(x.T, 3, 1, mode='constant', axis=0)
+ xp_assert_close(y, expected.T)
+
+
+@make_xp_test_case(savgol_filter)
+def test_sg_filter_interp_edges(xp):
+ # Another test with low degree polynomial data, for which we can easily
+ # give the exact results. In this test, we use mode='interp', so
+ # savgol_filter should match the exact solution for the entire data set,
+ # including the edges.
+ t = xp.linspace(-5, 5, 21, dtype=xp.float64)
+ delta = t[1] - t[0]
+ # Polynomial test data.
+ x = xp.stack([t,
+ 3 * t ** 2,
+ t ** 3 - t])
+ dx = xp.stack([xp.ones_like(t),
+ 6 * t,
+ 3 * t ** 2 - 1.0])
+ d2x = xp.stack([xp.zeros_like(t),
+ xp.full_like(t, 6),
+ 6 * t])
+
+ window_length = 7
+
+ y = savgol_filter(x, window_length, 3, axis=-1, mode='interp')
+ xp_assert_close(y, x, atol=1e-12)
+
+ y1 = savgol_filter(x, window_length, 3, axis=-1, mode='interp',
+ deriv=1, delta=delta)
+ xp_assert_close(y1, dx, atol=1e-12)
+
+ y2 = savgol_filter(x, window_length, 3, axis=-1, mode='interp',
+ deriv=2, delta=delta)
+ xp_assert_close(y2, d2x, atol=1e-12)
+
+ # Transpose everything, and test again with axis=0.
+
+ x = x.T
+ dx = dx.T
+ d2x = d2x.T
+
+ y = savgol_filter(x, window_length, 3, axis=0, mode='interp')
+ xp_assert_close(y, x, atol=1e-12)
+
+ y1 = savgol_filter(x, window_length, 3, axis=0, mode='interp',
+ deriv=1, delta=delta)
+ xp_assert_close(y1, dx, atol=1e-12)
+
+ y2 = savgol_filter(x, window_length, 3, axis=0, mode='interp',
+ deriv=2, delta=delta)
+ xp_assert_close(y2, d2x, atol=1e-12)
+
+
+@make_xp_test_case(savgol_filter)
+def test_sg_filter_interp_edges_3d(xp):
+ # Test mode='interp' with a 3-D array.
+ t = xp.linspace(-5, 5, 21)
+ delta = t[1] - t[0]
+ x1 = xp.stack([t, -t])
+ x2 = xp.stack([t ** 2, 3 * t ** 2 + 5])
+ x3 = xp.stack([t ** 3, 2 * t ** 3 + t ** 2 - 0.5 * t])
+ dx1 = xp.stack([xp.ones_like(t), -xp.ones_like(t)])
+ dx2 = xp.stack([2 * t, 6 * t])
+ dx3 = xp.stack([3 * t ** 2, 6 * t ** 2 + 2 * t - 0.5])
+
+ # z has shape (3, 2, 21)
+ z = xp.stack([x1, x2, x3])
+ dz = xp.stack([dx1, dx2, dx3])
+
+ y = savgol_filter(z, 7, 3, axis=-1, mode='interp', delta=delta)
+ xp_assert_close(y, z, atol=1e-10)
+
+ dy = savgol_filter(z, 7, 3, axis=-1, mode='interp', deriv=1, delta=delta)
+ xp_assert_close(dy, dz, atol=1e-10)
+
+ # z has shape (3, 21, 2)
+ z = xp.stack([x1.T, x2.T, x3.T])
+ dz = xp.stack([dx1.T, dx2.T, dx3.T])
+
+ y = savgol_filter(z, 7, 3, axis=1, mode='interp', delta=delta)
+ xp_assert_close(y, z, atol=1e-10)
+
+ dy = savgol_filter(z, 7, 3, axis=1, mode='interp', deriv=1, delta=delta)
+ xp_assert_close(dy, dz, atol=1e-10)
+
+ # z has shape (21, 3, 2)
+ z = xp.asarray(xp_swapaxes(z, 0, 1, xp=xp), copy=True)
+ dz = xp.asarray(xp_swapaxes(dz, 0, 1, xp=xp), copy=True)
+
+ y = savgol_filter(z, 7, 3, axis=0, mode='interp', delta=delta)
+ xp_assert_close(y, z, atol=1e-10)
+
+ dy = savgol_filter(z, 7, 3, axis=0, mode='interp', deriv=1, delta=delta)
+ xp_assert_close(dy, dz, atol=1e-10)
+
+
+@make_xp_test_case(savgol_filter)
+def test_sg_filter_valid_window_length_3d(xp):
+ """Tests that the window_length check is using the correct axis."""
+
+ x = xp.ones((10, 20, 30))
+
+ savgol_filter(x, window_length=29, polyorder=3, mode='interp')
+
+ with pytest.raises(ValueError, match='window_length must be less than'):
+ # window_length is more than x.shape[-1].
+ savgol_filter(x, window_length=31, polyorder=3, mode='interp')
+
+ savgol_filter(x, window_length=9, polyorder=3, axis=0, mode='interp')
+
+ with pytest.raises(ValueError, match='window_length must be less than'):
+ # window_length is more than x.shape[0].
+ savgol_filter(x, window_length=11, polyorder=3, axis=0, mode='interp')
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_short_time_fft.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_short_time_fft.py
new file mode 100644
index 0000000000000000000000000000000000000000..063f44f66d896e7c714d487abcc32654ee11d4b7
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_short_time_fft.py
@@ -0,0 +1,1116 @@
+"""Unit tests for module `_short_time_fft`.
+
+This file's structure loosely groups the tests into the following sequential
+categories:
+
+1. Test function `_calc_dual_canonical_window`.
+2. Test for invalid parameters and exceptions in `ShortTimeFFT` (until the
+ `test_from_window` function).
+3. Test algorithmic properties of STFT/ISTFT. Some tests were ported from
+ ``test_spectral.py``.
+
+Notes
+-----
+* Mypy 0.990 does interpret the line::
+
+ from scipy.stats import norm as normal_distribution
+
+ incorrectly (but the code works), hence a ``type: ignore`` was appended.
+"""
+import math
+from itertools import product
+from types import GenericAlias
+from typing import cast, get_args, Literal
+
+import numpy as np
+import pytest
+from scipy._lib._array_api import xp_assert_close, xp_assert_equal
+from scipy.fft import fftshift
+from scipy.stats import norm as normal_distribution # type: ignore
+from scipy.signal import check_COLA, get_window, welch, stft, istft, spectrogram
+
+from scipy.signal._short_time_fft import FFT_MODE_TYPE, \
+ _calc_dual_canonical_window, closest_STFT_dual_window, ShortTimeFFT, PAD_TYPE
+from scipy.signal.windows import blackman, gaussian, hamming, nuttall, triang
+
+
+def test__calc_dual_canonical_window_roundtrip():
+ """Test dual window calculation with a round trip to verify duality.
+
+ Note that this works only for canonical window pairs (having minimal
+ energy) like a Gaussian.
+
+ The window is the same as in the example of `from ShortTimeFFT.from_dual`.
+ """
+ win = gaussian(51, std=10, sym=True)
+ d_win = _calc_dual_canonical_window(win, 10)
+ win2 = _calc_dual_canonical_window(d_win, 10)
+ xp_assert_close(win2, win)
+
+
+def test__calc_dual_canonical_window_exceptions():
+ """Raise all exceptions in `_calc_dual_canonical_window`."""
+ # Verify that calculation can fail:
+ with pytest.raises(ValueError, match="hop=5 is larger than window len.*"):
+ _calc_dual_canonical_window(np.ones(4), 5)
+ with pytest.raises(ValueError, match=".* Transform not invertible!"):
+ _calc_dual_canonical_window(np.array([.1, .2, .3, 0]), 4)
+
+ # Verify that parameter `win` may not be integers:
+ with pytest.raises(ValueError, match="Parameter 'win' cannot be of int.*"):
+ _calc_dual_canonical_window(np.ones(4, dtype=int), 1)
+
+def test_closest_STFT_dual_window_exceptions():
+ """Raise all exceptions in `closest_STFT_dual_window`."""
+ with pytest.raises(ValueError, match="Parameters `win` and `desired_dual` are.*"):
+ closest_STFT_dual_window(np.ones(4), 2, np.ones(5))
+ with pytest.raises(ValueError, match="Parameters `win` and `desired_dual` are.*"):
+ closest_STFT_dual_window(np.ones((4, 1)), 2, np.ones(4))
+ with pytest.raises(ValueError, match="Parameter win must have finite entries!"):
+ closest_STFT_dual_window(np.ones(4)*np.nan, 2, np.ones(4))
+ with pytest.raises(ValueError, match="Parameter desired_dual must have finite.*"):
+ closest_STFT_dual_window(np.ones(4), 2, np.ones(4)*np.nan)
+ with pytest.raises(ValueError, match="Parameter hop=20 is not an integer.*"):
+ closest_STFT_dual_window(np.ones(4), 20, np.ones(4))
+ with pytest.raises(ValueError, match="Parameter hop=2.0 is not an integer.*"):
+ # noinspection PyTypeChecker
+ closest_STFT_dual_window(np.ones(4), 2., np.ones(4))
+
+ with pytest.raises(ValueError, match="Unable to calculate scaled closest dual.*"):
+ closest_STFT_dual_window(np.ones(4), 2, np.zeros(4), scaled=True)
+
+
+@pytest.mark.parametrize("scaled", (True, False))
+@pytest.mark.parametrize('sym_win', (False, True))
+@pytest.mark.parametrize('hop', (8, 9))
+@pytest.mark.parametrize('m', (16, 17))
+@pytest.mark.parametrize('win_name', ('hann', 'hamming'))
+def test_closest_STFT_dual_window_roundtrip(win_name, m, hop, sym_win, scaled):
+ """Do roundtrip, i.e., compare dual of dual windows.
+
+ The default for parameter `desired_dual` is also verified.
+ """
+ win = get_window(win_name, m, not sym_win)
+ d1, s1 = closest_STFT_dual_window(win, hop, np.ones_like(win), scaled=scaled)
+ d2, s2 = closest_STFT_dual_window(win, hop, scaled=scaled) # equals d1, s1
+ d3, s3 = closest_STFT_dual_window(d1, hop, win * s1, scaled=True) # roundtrip
+
+ # (d1, s1) == (d2, s2) should hold, but the BLAS backend used to calculate the inner
+ # product in `closest_STFT_dual_window` does not guarantee exact reproducibility
+ # due to indeterministic summation order during parallel execution. Hence, only
+ # approximate equality is verified. Consult NumPy 29873 issue for discussion.
+ res = np.finfo(win.dtype).resolution # 1e-15 for float64
+ err_msg = "Default for parameter `desired_dual` is not ok!"
+ xp_assert_close(d2, d1, atol=res, err_msg=err_msg)
+ xp_assert_close(s2, s1, atol=res, err_msg=err_msg)
+
+ xp_assert_close(s1*s3, 1., atol=res*5, err_msg="Invalid Scale factors")
+ xp_assert_close(d3, win, atol=res*5, err_msg="Roundtrip failed!")
+
+ if scaled: # check that scaling factor is correct:
+ d3, _ = closest_STFT_dual_window(win, hop, np.ones(m) * s1, scaled=False)
+ xp_assert_close(d3, d1, atol=res, err_msg="Roundtrip failed!")
+
+
+@pytest.mark.parametrize('scaled', (False, True))
+def test_closest_STFT_dual_window_STFT_roundtrip(scaled):
+ """STFT Roundtrip correctness of closest dual window. """
+ np.random.seed(5613830)
+ n, m_num, hop = 15, 7, 3
+ w, desires_dual = hamming(m_num), triang(m_num)
+ d, _ = closest_STFT_dual_window(w, hop, desires_dual, scaled=scaled)
+
+ SFT = ShortTimeFFT(w, hop=hop, dual_win=d, fs=1, scale_to=None, phase_shift=None)
+ x = 10 * np.random.randn(n)
+ Sx = SFT.stft(x)
+ y = SFT.istft(Sx, 0, n)
+
+ atol = np.finfo(w.dtype).resolution * 10
+ xp_assert_close(y, x, atol=atol, err_msg="Invalid closest window")
+
+
+@pytest.mark.parametrize('scaled', (False, True))
+def test_closest_STFT_dual_window_STFT_roundtrip_complex(scaled):
+ """STFT Roundtrip correctness of closest dual window with complex values. """
+ np.random.seed(34905436)
+ n, m_num, hop = 15, 7, 3
+ win = 1j*hamming(m_num) + nuttall(m_num)
+ desires_dual = 1j*triang(m_num) + blackman(m_num)
+ dual, s = closest_STFT_dual_window(win, hop, desires_dual, scaled=scaled)
+
+ SFT = ShortTimeFFT(win, hop=hop, dual_win=dual, fs=1, fft_mode='twosided',
+ scale_to=None, phase_shift=None)
+ x = 10 * np.random.randn(n) + 10j * np.random.randn(n)
+ Sx = SFT.stft(x)
+ y = SFT.istft(Sx, 0, n)
+
+ atol = np.finfo(win.dtype).resolution * 10
+ xp_assert_close(y, x, atol=atol, err_msg=f"Invalid complex closest window ({s=})")
+
+
+@pytest.mark.parametrize("win_name, nperseg, noverlap, scale_fac", ([
+ ('boxcar', 16, 8, 1/2),
+ ('boxcar', 18, 12, 1/3),
+ ('boxcar', 16, 12, 1/4),
+ ('bartlett', 16, 8, 1.),
+ ('bartlett', 16, 12, 1/2),
+ ('bartlett', 30, 25, 1/3),
+ ('hann', 16, 8, 1.),
+ ('hann', 18, 12, 2/3),
+ ('hann', 16, 12, 1/2),
+ ('blackman', 9, 6, 50/63),
+ ('boxcar', 8, 7, 1/8)])) # hop = 1
+def test_closest_STFT_dual_window_cola(win_name, nperseg, noverlap, scale_fac):
+ """Test if `closest_STFT_dual_window` generalizes `check_COLA`.
+
+ The parameters were taken from the `check_COLA` documentation.
+ Note that `check_COLA` only guarantees the existence of a dual window with constant
+ values but not that those values are unity (which is clear, when investigating the
+ 'boxcar' examples). The values for `scale_fac` were determined empirically.
+ """
+ desired_dual = get_window(win_name, nperseg, fftbins=True)
+ assert check_COLA(desired_dual, nperseg, noverlap), "COLA cond. violated!"
+
+ win = np.ones(nperseg) # check scaled window:
+ d_s, s = closest_STFT_dual_window(win, nperseg-noverlap, desired_dual, scaled=True)
+
+ res = np.finfo(desired_dual.dtype).resolution
+ rel_tol_d = max(abs(d_s))*res*3
+ xp_assert_close(s, scale_fac, atol=res*10,
+ err_msg=f"Scale factor off by {s/scale_fac}")
+ xp_assert_close(d_s, desired_dual*scale_fac, atol=res*10, rtol=rel_tol_d,
+ err_msg="Calculated incorrect scaled window!")
+
+ # check unscaled window:
+ d_u, u = closest_STFT_dual_window(win * scale_fac, nperseg - noverlap,
+ desired_dual, scaled=False)
+
+ # this should be hard-coded not computed, so no need for allclose
+ assert u == 1., "Scaling factor not 1 for parameter `scaled=True`!"
+ xp_assert_close(d_u, desired_dual, atol=res*10, rtol=rel_tol_d,
+ err_msg="Calculated incorrect unscaled window!")
+
+
+def test_invalid_initializer_parameters():
+ """Verify that exceptions get raised on invalid parameters when
+ instantiating ShortTimeFFT. """
+ with pytest.raises(ValueError, match=r"Parameter win must be 1d, " +
+ r"but win.shape=\(2, 2\)!"):
+ ShortTimeFFT(np.ones((2, 2)), hop=4, fs=1)
+ with pytest.raises(ValueError, match="Parameter win must have " +
+ "finite entries"):
+ ShortTimeFFT(np.array([1, np.inf, 2, 3]), hop=4, fs=1)
+ with pytest.raises(ValueError, match="Parameter hop=0 is not " +
+ "an integer >= 1!"):
+ ShortTimeFFT(np.ones(4), hop=0, fs=1)
+ with pytest.raises(ValueError, match="Parameter hop=2.0 is not " +
+ "an integer >= 1!"):
+ # noinspection PyTypeChecker
+ ShortTimeFFT(np.ones(4), hop=2.0, fs=1)
+ with pytest.raises(ValueError, match=r"dual_win.shape=\(5,\) must equal " +
+ r"win.shape=\(4,\)!"):
+ ShortTimeFFT(np.ones(4), hop=2, fs=1, dual_win=np.ones(5))
+ with pytest.raises(ValueError, match="Parameter dual_win must be " +
+ "a finite array!"):
+ ShortTimeFFT(np.ones(3), hop=2, fs=1,
+ dual_win=np.array([np.nan, 2, 3]))
+
+
+def test_exceptions_properties_methods():
+ """Verify that exceptions get raised when setting properties or calling
+ method of ShortTimeFFT to/with invalid values."""
+ SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1)
+ with pytest.raises(ValueError, match="Sampling interval T=-1 must be " +
+ "positive!"):
+ SFT.T = -1
+ with pytest.raises(ValueError, match="Sampling frequency fs=-1 must be " +
+ "positive!"):
+ SFT.fs = -1
+ with pytest.raises(ValueError, match="fft_mode='invalid_typ' not in " +
+ r"\('twosided', 'centered', " +
+ r"'onesided', 'onesided2X'\)!"):
+ SFT.fft_mode = 'invalid_typ'
+ with pytest.raises(ValueError, match="For scaling is None, " +
+ "fft_mode='onesided2X' is invalid.*"):
+ SFT.fft_mode = 'onesided2X'
+ with pytest.raises(ValueError, match="Attribute mfft=7 needs to be " +
+ "at least the window length.*"):
+ SFT.mfft = 7
+ with pytest.raises(ValueError, match="scaling='invalid' not in.*"):
+ # noinspection PyTypeChecker
+ SFT.scale_to('invalid')
+ with pytest.raises(ValueError, match="phase_shift=3.0 has the unit .*"):
+ SFT.phase_shift = 3.0
+ with pytest.raises(ValueError, match="-mfft < phase_shift < mfft " +
+ "does not hold.*"):
+ SFT.phase_shift = 2*SFT.mfft
+ with pytest.raises(ValueError, match="Parameter padding='invalid' not.*"):
+ # noinspection PyTypeChecker
+ g = SFT._x_slices(np.zeros(16), k_off=0, p0=0, p1=1, padding='invalid')
+ next(g) # execute generator
+ with pytest.raises(ValueError, match="Trend type must be 'linear' " +
+ "or 'constant'"):
+ # noinspection PyTypeChecker
+ SFT.stft_detrend(np.zeros(16), detr='invalid')
+ with pytest.raises(ValueError, match="Parameter detr=nan is not a str, " +
+ "function or None!"):
+ # noinspection PyTypeChecker
+ SFT.stft_detrend(np.zeros(16), detr=np.nan)
+ with pytest.raises(ValueError, match="Invalid Parameter p0=0, p1=200.*"):
+ SFT.p_range(100, 0, 200)
+
+ with pytest.raises(ValueError, match="f_axis=0 may not be equal to " +
+ "t_axis=0!"):
+ SFT.istft(np.zeros((SFT.f_pts, 2)), t_axis=0, f_axis=0)
+ with pytest.raises(ValueError, match=r"S.shape\[f_axis\]=2 must be equal" +
+ " to self.f_pts=5.*"):
+ SFT.istft(np.zeros((2, 2)))
+ with pytest.raises(ValueError, match=r"S.shape\[t_axis\]=1 needs to have" +
+ " at least 2 slices.*"):
+ SFT.istft(np.zeros((SFT.f_pts, 1)))
+ with pytest.raises(ValueError, match=r".*\(k1=100\) <= \(k_max=12\) " +
+ "is false!$"):
+ SFT.istft(np.zeros((SFT.f_pts, 3)), k1=100)
+ with pytest.raises(ValueError, match=r"\(k1=1\) - \(k0=0\) = 1 has to " +
+ "be at least.* length 4!"):
+ SFT.istft(np.zeros((SFT.f_pts, 3)), k0=0, k1=1)
+
+ with pytest.raises(ValueError, match=r"Parameter axes_seq='invalid' " +
+ r"not in \['tf', 'ft'\]!"):
+ # noinspection PyTypeChecker
+ SFT.extent(n=100, axes_seq='invalid')
+ with pytest.raises(ValueError, match="Attribute fft_mode=twosided must.*"):
+ SFT.fft_mode = 'twosided'
+ SFT.extent(n=100)
+
+
+@pytest.mark.parametrize('m', ('onesided', 'onesided2X'))
+def test_exceptions_fft_mode_complex_win(m: FFT_MODE_TYPE):
+ """Verify that one-sided spectra are not allowed with complex-valued
+ windows or with complex-valued signals.
+
+ The reason being, the `rfft` function only accepts real-valued input.
+ """
+ with pytest.raises(ValueError,
+ match=f"One-sided spectra, i.e., fft_mode='{m}'.*"):
+ ShortTimeFFT(np.ones(8)*1j, hop=4, fs=1, fft_mode=m)
+
+ SFT = ShortTimeFFT(np.ones(8)*1j, hop=4, fs=1, fft_mode='twosided')
+ with pytest.raises(ValueError,
+ match=f"One-sided spectra, i.e., fft_mode='{m}'.*"):
+ SFT.fft_mode = m
+
+ SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1, scale_to='psd', fft_mode='onesided')
+ with pytest.raises(ValueError, match="Complex-valued `x` not allowed for self.*"):
+ SFT.stft(np.ones(8)*1j)
+ SFT.fft_mode = 'onesided2X'
+ with pytest.raises(ValueError, match="Complex-valued `x` not allowed for self.*"):
+ SFT.stft(np.ones(8)*1j)
+
+
+def test_invalid_fft_mode_RuntimeError():
+ """Ensure exception gets raised when property `fft_mode` is invalid. """
+ SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1)
+ # noinspection PyTypeChecker
+ SFT._fft_mode = 'invalid_typ'
+
+ with pytest.raises(RuntimeError):
+ _ = SFT.f
+ with pytest.raises(RuntimeError):
+ SFT._fft_func(np.ones(8))
+ with pytest.raises(RuntimeError):
+ SFT._ifft_func(np.ones(8))
+
+
+@pytest.mark.parametrize('win_params, Nx', [(('gaussian', 2.), 9), # in docstr
+ ('triang', 7),
+ (('kaiser', 4.0), 9),
+ (('exponential', None, 1.), 9),
+ (4.0, 9)])
+def test_from_window(win_params, Nx: int):
+ """Verify that `from_window()` handles parameters correctly.
+
+ The window parameterizations are documented in the `get_window` docstring.
+ """
+ w_sym, fs = get_window(win_params, Nx, fftbins=False), 16.
+ w_per = get_window(win_params, Nx, fftbins=True)
+ SFT0 = ShortTimeFFT(w_sym, hop=3, fs=fs, fft_mode='twosided',
+ scale_to='psd', phase_shift=1)
+ nperseg = len(w_sym)
+ noverlap = nperseg - SFT0.hop
+ SFT1 = ShortTimeFFT.from_window(win_params, fs, nperseg, noverlap,
+ symmetric_win=True, fft_mode='twosided',
+ scale_to='psd', phase_shift=1)
+ # periodic window:
+ SFT2 = ShortTimeFFT.from_window(win_params, fs, nperseg, noverlap,
+ symmetric_win=False, fft_mode='twosided',
+ scale_to='psd', phase_shift=1)
+ # Be informative when comparing instances:
+ xp_assert_equal(SFT1.win, SFT0.win)
+ xp_assert_close(SFT2.win, w_per / np.sqrt(sum(w_per**2) * fs))
+ for n_ in ('hop', 'T', 'fft_mode', 'mfft', 'scaling', 'phase_shift'):
+ v0, v1, v2 = (getattr(SFT_, n_) for SFT_ in (SFT0, SFT1, SFT2))
+ assert v1 == v0, f"SFT1.{n_}={v1} does not equal SFT0.{n_}={v0}"
+ assert v2 == v0, f"SFT2.{n_}={v2} does not equal SFT0.{n_}={v0}"
+
+
+def test_from_win_equals_dual_exceptions():
+ """Raise all occurring exceptions in `ShortTimeFFT.from_closest_win_equals_dual`.
+ """
+ with pytest.raises(ValueError, match="Parameter desired_win is not 1d, but.*"):
+ ShortTimeFFT.from_win_equals_dual(np.ones((3, 4)), hop=1, fs=1)
+ with pytest.raises(ValueError, match="Parameter desired_win cannot be of int.*"):
+ ShortTimeFFT.from_win_equals_dual(np.ones(4, dtype=int), hop=1, fs=1)
+ with pytest.raises(ValueError, match="Parameter desired_win is not 1d, but.*"):
+ ShortTimeFFT.from_win_equals_dual(np.array([]), hop=1, fs=1)
+ with pytest.raises(ValueError, match="Parameter desired_win must have finite.*"):
+ ShortTimeFFT.from_win_equals_dual(np.ones(3) * np.inf, hop=1, fs=1)
+ with pytest.raises(ValueError, match="Parameter hop=0 is not an integer .*"):
+ ShortTimeFFT.from_win_equals_dual(np.ones(4), hop=0, fs=1)
+ with pytest.raises(ValueError, match="Parameter hop=5 is not an integer .*"):
+ ShortTimeFFT.from_win_equals_dual(np.ones(4), hop=5, fs=1)
+
+ with pytest.raises(ValueError, match="P.+ desired_win does not have valid.*"):
+ w = np.array([1, 0, 1, 0, 1], dtype=float)
+ ShortTimeFFT.from_win_equals_dual(w, hop=2, fs=1)
+ with pytest.raises(ValueError, match="Parameter scale_to='invalid' not in.*"):
+ # noinspection PyTypeChecker
+ ShortTimeFFT.from_win_equals_dual(w, hop=2, fs=1, scale_to='invalid')
+
+@pytest.mark.parametrize('fft_bins', (True, False))
+@pytest.mark.parametrize('m, hop', [(16, 8), (16, 7), (17, 8), (17, 9), (16, 16)])
+def test_from_win_equals_dual_params(m, hop, fft_bins):
+ """Test windows parameterizations for `ShortTimeFFT.from_closest_win_equals_dual`.
+
+ The flattop window is used since it also has negative values.
+ """
+ desired_win = get_window('flattop', m, fftbins=fft_bins)
+ SFT0 = ShortTimeFFT.from_win_equals_dual(desired_win, hop, fs=1)
+ xp_assert_close(SFT0.dual_win, SFT0.win, err_msg="win must equals dual window!")
+
+ SFT1 = ShortTimeFFT(SFT0.win, hop, fs=1)
+ xp_assert_close(SFT1.dual_win, SFT0.win, err_msg="dual win isn't canonical win!")
+
+
+@pytest.mark.parametrize('fft_bins', (True, False))
+@pytest.mark.parametrize('m, hop', [(16, 8), (16, 7), (17, 8), (17, 9), (16, 16)])
+@pytest.mark.parametrize('scale_to', (None, 'unitary'))
+def test_from_win_equals_dual_roundtrip(m, hop, fft_bins, scale_to):
+ """Testing roundtrip verifies that the dual window is correct.
+ """
+ desired_win = get_window('flattop', m, fftbins=fft_bins)
+ SFT0 = ShortTimeFFT.from_win_equals_dual(desired_win, hop, fs=1)
+
+ x = np.cos(np.arange(2*m)**2)
+ x1 = SFT0.istft(SFT0.stft(x), 0, len(x))
+ xp_assert_close(x1, x, err_msg="Roundtrip for win equaling its dual failed!")
+
+
+def test_from_win_equals_dual_unitary():
+ """Check that STFT can be unitary mapping. """
+ m, hop = 8, 4
+ des_win = get_window('hann', m)
+ SFT = ShortTimeFFT.from_win_equals_dual(des_win, hop, 1, fft_mode='twosided',
+ scale_to='unitary')
+ # Orthogonal signals:
+ x, y = np.tile([-1, -1, 1, 1], 4), np.tile([1, -1, -1, 1], 4)
+ Sxx, Sxy = SFT.spectrogram(x), SFT.spectrogram(x, y)
+
+ atol = np.finfo(Sxx.dtype).resolution
+ assert sum(x * y) == 0
+ xp_assert_close(np.sum(Sxx), np.sum(x ** 2, dtype=Sxx.dtype), atol=atol,
+ err_msg="Energies do not match!")
+ xp_assert_close(np.sum(Sxy), 0.0j, atol=atol,
+ err_msg="STFT scalar product of Sx and Sy not 0!")
+ xp_assert_close(SFT.dual_win, SFT.win*SFT.m_num, atol=atol,
+ err_msg="Wrong factor for dual_win/win!")
+
+
+def test_dual_win_roundtrip():
+ """Verify the duality of `win` and `dual_win`.
+
+ Note that this test does not work for arbitrary windows, since dual windows
+ are not unique. It always works for invertible STFTs if the windows do not
+ overlap.
+ """
+ # Non-standard values for keyword arguments (except for `scale_to`):
+ kw = dict(hop=4, fs=1, fft_mode='twosided', mfft=8, scale_to=None,
+ phase_shift=2)
+ SFT0 = ShortTimeFFT(np.ones(4), **kw)
+ SFT1 = ShortTimeFFT.from_dual(SFT0.dual_win, **kw)
+ xp_assert_close(SFT1.dual_win, SFT0.win)
+
+
+@pytest.mark.parametrize('scale_to, fac_psd, fac_mag',
+ [(None, 0.25, 0.125),
+ ('magnitude', 2.0, 1),
+ ('psd', 1, 0.5)])
+def test_scaling(scale_to: Literal['magnitude', 'psd'], fac_psd, fac_mag):
+ """Verify scaling calculations.
+
+ * Verify passing `scale_to`parameter to ``__init__().
+ * Roundtrip while changing scaling factor.
+ """
+ SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=scale_to)
+ assert SFT.fac_psd == fac_psd
+ assert SFT.fac_magnitude == fac_mag
+ # increase coverage by accessing properties twice:
+ assert SFT.fac_psd == fac_psd
+ assert SFT.fac_magnitude == fac_mag
+
+ x = np.fft.irfft([0, 0, 7, 0, 0, 0, 0]) # periodic signal
+ Sx = SFT.stft(x)
+ Sx_mag, Sx_psd = Sx * SFT.fac_magnitude, Sx * SFT.fac_psd
+
+ SFT.scale_to('magnitude')
+ x_mag = SFT.istft(Sx_mag, k1=len(x))
+ xp_assert_close(x_mag, x)
+
+ SFT.scale_to('psd')
+ x_psd = SFT.istft(Sx_psd, k1=len(x))
+ xp_assert_close(x_psd, x)
+
+
+def test_scale_to():
+ """Verify `scale_to()` method."""
+ SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=None)
+
+ SFT.scale_to('magnitude')
+ assert SFT.scaling == 'magnitude'
+ assert SFT.fac_psd == 2.0
+ assert SFT.fac_magnitude == 1
+
+ SFT.scale_to('psd')
+ assert SFT.scaling == 'psd'
+ assert SFT.fac_psd == 1
+ assert SFT.fac_magnitude == 0.5
+
+ SFT.scale_to('psd') # needed for coverage
+
+ for scale, s_fac in zip(('magnitude', 'psd'), (8, 4)):
+ SFT = ShortTimeFFT(np.ones(4) * 2, hop=4, fs=1, scale_to=None)
+ dual_win = SFT.dual_win.copy()
+
+ SFT.scale_to(cast(Literal['magnitude', 'psd'], scale))
+ xp_assert_close(SFT.dual_win, dual_win * s_fac)
+
+
+def test_x_slices_padding():
+ """Verify padding.
+
+ The reference arrays were taken from the docstrings of `zero_ext`,
+ `const_ext`, `odd_ext()`, and `even_ext()` from the _array_tools module.
+ """
+ SFT = ShortTimeFFT(np.ones(5), hop=4, fs=1)
+ x = np.array([[1, 2, 3, 4, 5], [0, 1, 4, 9, 16]], dtype=float)
+ d = {'zeros': [[[0, 0, 1, 2, 3], [0, 0, 0, 1, 4]],
+ [[3, 4, 5, 0, 0], [4, 9, 16, 0, 0]]],
+ 'edge': [[[1, 1, 1, 2, 3], [0, 0, 0, 1, 4]],
+ [[3, 4, 5, 5, 5], [4, 9, 16, 16, 16]]],
+ 'even': [[[3, 2, 1, 2, 3], [4, 1, 0, 1, 4]],
+ [[3, 4, 5, 4, 3], [4, 9, 16, 9, 4]]],
+ 'odd': [[[-1, 0, 1, 2, 3], [-4, -1, 0, 1, 4]],
+ [[3, 4, 5, 6, 7], [4, 9, 16, 23, 28]]]}
+ for p_, xx in d.items():
+ gen = SFT._x_slices(np.array(x), 0, 0, 2, padding=cast(PAD_TYPE, p_))
+ yy = np.array([y_.copy() for y_ in gen]) # due to inplace copying
+ xx = np.asarray(xx, dtype=np.float64)
+ xp_assert_equal(yy, xx, err_msg=f"Failed '{p_}' padding.")
+
+
+def test_invertible():
+ """Verify `invertible` property. """
+ SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1)
+ assert SFT.invertible
+ SFT = ShortTimeFFT(np.ones(8), hop=9, fs=1)
+ assert not SFT.invertible
+
+
+def test_border_values():
+ """Ensure that minimum and maximum values of slices are correct."""
+ SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1)
+ assert SFT.p_min == 0
+ assert SFT.k_min == -4
+ assert SFT.lower_border_end == (4, 1)
+ assert SFT.lower_border_end == (4, 1) # needed to test caching
+ assert SFT.p_max(10) == 4
+ assert SFT.k_max(10) == 16
+ assert SFT.upper_border_begin(10) == (4, 2)
+ assert SFT.upper_border_begin(10) == (4, 2) # needed to test caching
+ # Raise exceptions:
+ with pytest.raises(ValueError, match="^Parameter n must be"):
+ SFT.upper_border_begin(3)
+ with pytest.raises(ValueError, match="^Parameter n must be"):
+ SFT._post_padding(3)
+ with pytest.raises(RuntimeError):
+ SFT._hop = -1 # illegal hop interval
+ SFT.upper_border_begin(8)
+
+def test_border_values_exotic():
+ """Ensure that the border calculations are correct for windows with
+ zeros. """
+ w = np.array([0, 0, 0, 0, 0, 0, 0, 1.])
+ SFT = ShortTimeFFT(w, hop=1, fs=1)
+ assert SFT.lower_border_end == (0, 0)
+
+ SFT = ShortTimeFFT(np.flip(w), hop=20, fs=1)
+ assert SFT.upper_border_begin(4) == (16, 1)
+ assert SFT.upper_border_begin(5) == (16, 1)
+ assert SFT.upper_border_begin(23) == (36, 2)
+ assert SFT.upper_border_begin(24) == (36, 2)
+ assert SFT.upper_border_begin(25) == (36, 2)
+
+ SFT._hop = -1 # provoke unreachable line
+ with pytest.raises(RuntimeError):
+ _ = SFT.k_max(4)
+ with pytest.raises(RuntimeError):
+ _ = SFT.k_min
+
+
+def test_t():
+ """Verify that the times of the slices are correct. """
+ SFT = ShortTimeFFT(np.ones(8), hop=4, fs=2)
+ assert SFT.T == 1/2
+ assert SFT.fs == 2.
+ assert SFT.delta_t == 4 * 1/2
+ t_stft = np.arange(0, SFT.p_max(10)) * SFT.delta_t
+ xp_assert_equal(SFT.t(10), t_stft)
+ xp_assert_equal(SFT.t(10, 1, 3), t_stft[1:3])
+ SFT.T = 1/4
+ assert SFT.T == 1/4
+ assert SFT.fs == 4
+ SFT.fs = 1/8
+ assert SFT.fs == 1/8
+ assert SFT.T == 8
+ with pytest.raises(ValueError):
+ # noinspection PyTypeChecker
+ SFT.t(1.5) # only integers allowed
+ with pytest.raises(ValueError):
+ SFT.t(-1) # only positive `n` allowed
+
+
+@pytest.mark.parametrize('fft_mode, f',
+ [('onesided', [0., 1., 2.]),
+ ('onesided2X', [0., 1., 2.]),
+ ('twosided', [0., 1., 2., -2., -1.]),
+ ('centered', [-2., -1., 0., 1., 2.])])
+def test_f(fft_mode: FFT_MODE_TYPE, f):
+ """Verify the frequency values property `f`."""
+ SFT = ShortTimeFFT(np.ones(5), hop=4, fs=5, fft_mode=fft_mode,
+ scale_to='psd')
+ xp_assert_equal(SFT.f, f)
+
+
+@pytest.mark.parametrize('n', [20, 21])
+@pytest.mark.parametrize('m', [5, 6])
+@pytest.mark.parametrize('fft_mode', ['onesided', 'centered'])
+def test_extent(n, m, fft_mode: FFT_MODE_TYPE):
+ """Ensure that the `extent()` method is correct. """
+ SFT = ShortTimeFFT(np.ones(m), hop=m, fs=m, fft_mode=fft_mode)
+
+ t0 = SFT.t(n)[0] # first timestamp
+ t1 = SFT.t(n)[-1] + SFT.delta_t # last timestamp + 1
+ t0c, t1c = t0 - SFT.delta_t / 2, t1 - SFT.delta_t / 2 # centered timestamps
+
+ f0 = SFT.f[0] # first frequency
+ f1 = SFT.f[-1] + SFT.delta_f # last frequency + 1
+ f0c, f1c = f0 - SFT.delta_f / 2, f1 - SFT.delta_f / 2 # centered frequencies
+
+ assert SFT.extent(n, 'tf', False) == (t0, t1, f0, f1)
+ assert SFT.extent(n, 'ft', False) == (f0, f1, t0, t1)
+ assert SFT.extent(n, 'tf', True) == (t0c, t1c, f0c, f1c)
+ assert SFT.extent(n, 'ft', True) == (f0c, f1c, t0c, t1c)
+
+
+def test_spectrogram():
+ """Verify spectrogram and cross-spectrogram methods. """
+ SFT = ShortTimeFFT(np.ones(8), hop=4, fs=1)
+ x, y = np.ones(10), np.arange(10)
+ X, Y = SFT.stft(x), SFT.stft(y)
+ xp_assert_close(SFT.spectrogram(x), X.real**2+X.imag**2)
+ xp_assert_close(SFT.spectrogram(x, y), X * Y.conj())
+
+
+@pytest.mark.parametrize('n', [8, 9])
+def test_fft_func_roundtrip(n: int):
+ """Test roundtrip `ifft_func(fft_func(x)) == x` for all permutations of
+ relevant parameters. """
+ np.random.seed(2394795)
+ x0 = np.random.rand(n)
+ w, h_n = np.ones(n), 4
+
+ pp = dict(
+ fft_mode=get_args(FFT_MODE_TYPE),
+ mfft=[None, n, n+1, n+2],
+ scaling=[None, 'magnitude', 'psd'],
+ phase_shift=[None, -n+1, 0, n // 2, n-1])
+ for f_typ, mfft, scaling, phase_shift in product(*pp.values()):
+ if f_typ == 'onesided2X' and scaling is None:
+ continue # this combination is forbidden
+ SFT = ShortTimeFFT(w, h_n, fs=n, fft_mode=f_typ, mfft=mfft,
+ scale_to=scaling, phase_shift=phase_shift)
+ X0 = SFT._fft_func(x0)
+ x1 = SFT._ifft_func(X0)
+ xp_assert_close(x0.astype(x1.dtype), x1,
+ err_msg="_fft_func() roundtrip failed for " +
+ f"{f_typ=}, {mfft=}, {scaling=}, {phase_shift=}")
+
+ SFT = ShortTimeFFT(w, h_n, fs=1)
+ SFT._fft_mode = 'invalid_fft' # type: ignore
+ with pytest.raises(RuntimeError):
+ SFT._fft_func(x0)
+ with pytest.raises(RuntimeError):
+ SFT._ifft_func(x0)
+
+
+@pytest.mark.parametrize('i', range(19))
+def test_impulse_roundtrip(i):
+ """Roundtrip for an impulse being at different positions `i`."""
+ n = 19
+ w, h_n = np.ones(8), 3
+ x = np.zeros(n)
+ x[i] = 1
+
+ SFT = ShortTimeFFT(w, hop=h_n, fs=1, scale_to=None, phase_shift=None)
+ Sx = SFT.stft(x)
+ # test slicing the input signal into two parts:
+ n_q = SFT.nearest_k_p(n // 2)
+ Sx0 = SFT.stft(x[:n_q], padding='zeros')
+ Sx1 = SFT.stft(x[n_q:], padding='zeros')
+ q0_ub = SFT.upper_border_begin(n_q)[1] - SFT.p_min
+ q1_le = SFT.lower_border_end[1] - SFT.p_min
+ xp_assert_close(Sx0[:, :q0_ub], Sx[:, :q0_ub], err_msg=f"{i=}")
+ xp_assert_close(Sx1[:, q1_le:], Sx[:, q1_le-Sx1.shape[1]:],
+ err_msg=f"{i=}")
+
+ Sx01 = np.hstack((Sx0[:, :q0_ub],
+ Sx0[:, q0_ub:] + Sx1[:, :q1_le],
+ Sx1[:, q1_le:]))
+ xp_assert_close(Sx, Sx01, atol=1e-8, err_msg=f"{i=}")
+
+ y = SFT.istft(Sx, 0, n)
+ xp_assert_close(y, x, atol=1e-8, err_msg=f"{i=}")
+ y0 = SFT.istft(Sx, 0, n//2)
+ xp_assert_close(x[:n//2], y0, atol=1e-8, err_msg=f"{i=}")
+ y1 = SFT.istft(Sx, n // 2, n)
+ xp_assert_close(x[n // 2:], y1, atol=1e-8, err_msg=f"{i=}")
+
+
+@pytest.mark.parametrize('hop', [1, 7, 8])
+def test_asymmetric_window_roundtrip(hop: int):
+ """An asymmetric window could uncover indexing problems. """
+ np.random.seed(23371)
+
+ w = np.arange(16) / 8 # must be of type float
+ w[len(w)//2:] = 1
+ SFT = ShortTimeFFT(w, hop, fs=1)
+
+ x = 10 * np.random.randn(64)
+ Sx = SFT.stft(x)
+ x1 = SFT.istft(Sx, k1=len(x))
+ xp_assert_close(x1, x1, err_msg="Roundtrip for asymmetric window with " +
+ f" {hop=} failed!")
+
+
+@pytest.mark.parametrize('m_num', [6, 7])
+def test_minimal_length_signal(m_num):
+ """Verify that the shortest allowed signal works. """
+ SFT = ShortTimeFFT(np.ones(m_num), m_num//2, fs=1)
+ n = math.ceil(m_num/2)
+ x = np.ones(n)
+ Sx = SFT.stft(x)
+ x1 = SFT.istft(Sx, k1=n)
+ xp_assert_close(x1, x, err_msg=f"Roundtrip minimal length signal ({n=})" +
+ f" for {m_num} sample window failed!")
+ with pytest.raises(ValueError, match=rf"len\(x\)={n-1} must be >= ceil.*"):
+ SFT.stft(x[:-1])
+ with pytest.raises(ValueError, match=rf"S.shape\[t_axis\]={Sx.shape[1]-1}"
+ f" needs to have at least {Sx.shape[1]} slices"):
+ SFT.istft(Sx[:, :-1], k1=n)
+
+
+def test_compare_stft_detrend():
+ """Test the detrending in `ShortTimeFFT.stft_detrend()`. """
+ SFT = ShortTimeFFT(np.ones(4), 4, fs=1)
+ x0 = np.zeros(4) # signal without trend
+ x1 = x0 + 3 # signal with constant trend
+ x2 = x0 + np.arange(len(x0)) # signal with linear trend
+
+ kw = dict(k_offset=2, p1=1) # we want only one slice
+ Sx0 = SFT.stft(x0, **kw) # no trend
+ Sx1 = SFT.stft_detrend(x1, detr='constant', **kw)
+ Sx2 = SFT.stft_detrend(x2, detr='linear', **kw)
+ Sx3 = SFT.stft_detrend(x1, detr=lambda x: x - np.mean(x), **kw)
+
+ atol = np.finfo(Sx0.dtype).resolution * 5 # needed to compare with array of zeros
+ xp_assert_close(Sx1, Sx0, atol=atol, err_msg="Constant detrending failed!")
+ xp_assert_close(Sx0, Sx2, atol=atol, err_msg="Linear detrending failed!")
+ xp_assert_close(Sx0, Sx3, atol=atol, err_msg="Detrending using a function failed!")
+
+
+def test_tutorial_stft_sliding_win():
+ """Verify example in "Sliding Windows" subsection from the "User Guide".
+
+ In :ref:`tutorial_stft_sliding_win` (file ``signal.rst``) of the
+ :ref:`user_guide` the behavior the border behavior of
+ ``ShortTimeFFT(np.ones(6), 2, fs=1)`` with a 50 sample signal is discussed.
+ This test verifies the presented indexes.
+ """
+ SFT = ShortTimeFFT(np.ones(6), 2, fs=1)
+
+ # Lower border:
+ assert SFT.m_num_mid == 3, f"Slice middle is not 3 but {SFT.m_num_mid=}"
+ assert SFT.p_min == -1, f"Lowest slice {SFT.p_min=} is not -1"
+ assert SFT.k_min == -5, f"Lowest slice sample {SFT.p_min=} is not -5"
+ k_lb, p_lb = SFT.lower_border_end
+ assert p_lb == 2, f"First unaffected slice {p_lb=} is not 2"
+ assert k_lb == 5, f"First unaffected sample {k_lb=} is not 5"
+
+ n = 50 # upper signal border
+ assert (p_max := SFT.p_max(n)) == 27, f"Last slice {p_max=} must be 27"
+ assert (k_max := SFT.k_max(n)) == 55, f"Last sample {k_max=} must be 55"
+ k_ub, p_ub = SFT.upper_border_begin(n)
+ assert p_ub == 24, f"First upper border slice {p_ub=} must be 24"
+ assert k_ub == 45, f"First upper border slice {k_ub=} must be 45"
+
+
+def test_tutorial_stft_legacy_stft():
+ """Verify STFT example in "Comparison with Legacy Implementation" from the
+ "User Guide".
+
+ In :ref:`tutorial_stft_legacy_stft` (file ``signal.rst``) of the
+ :ref:`user_guide` the legacy and the new implementation are compared.
+ """
+ fs, N = 200, 1001 # # 200 Hz sampling rate for 5 s signal
+ t_z = np.arange(N) / fs # time indexes for signal
+ z = np.exp(2j*np.pi * 70 * (t_z - 0.2 * t_z ** 2)) # complex-valued chirp
+
+ nperseg, noverlap = 50, 40
+ win = ('gaussian', 1e-2 * fs) # Gaussian with 0.01 s standard deviation
+
+ # Legacy STFT:
+ f0_u, t0, Sz0_u = stft(z, fs, win, nperseg, noverlap,
+ return_onesided=False, scaling='spectrum')
+ Sz0 = fftshift(Sz0_u, axes=0)
+
+ # New STFT:
+ SFT = ShortTimeFFT.from_window(win, fs, nperseg, noverlap,
+ fft_mode='centered',
+ scale_to='magnitude', phase_shift=None)
+ Sz1 = SFT.stft(z)
+
+ xp_assert_close(Sz0, Sz1[:, 2:-1])
+
+ xp_assert_close((abs(Sz1[:, 1]).min(), abs(Sz1[:, 1]).max()),
+ (6.925060911593139e-07, 8.00271269218721e-07))
+
+ t0_r, z0_r = istft(Sz0_u, fs, win, nperseg, noverlap, input_onesided=False,
+ scaling='spectrum')
+ z1_r = SFT.istft(Sz1, k1=N)
+ assert len(z0_r) == N + 9
+ xp_assert_close(z0_r[:N], z)
+ xp_assert_close(z1_r, z)
+
+ # Spectrogram is just the absolute square of th STFT:
+ xp_assert_close(SFT.spectrogram(z), abs(Sz1) ** 2)
+
+
+def test_tutorial_stft_legacy_spectrogram():
+ """Verify spectrogram example in "Comparison with Legacy Implementation"
+ from the "User Guide".
+
+ In :ref:`tutorial_stft_legacy_stft` (file ``signal.rst``) of the
+ :ref:`user_guide` the legacy and the new implementation are compared.
+ """
+ fs, N = 200, 1001 # 200 Hz sampling rate for almost 5 s signal
+ t_z = np.arange(N) / fs # time indexes for signal
+ z = np.exp(2j*np.pi*70 * (t_z - 0.2*t_z**2)) # complex-valued sweep
+
+ nperseg, noverlap = 50, 40
+ win = ('gaussian', 1e-2 * fs) # Gaussian with 0.01 s standard dev.
+
+ # Legacy spectrogram:
+ f2_u, t2, Sz2_u = spectrogram(z, fs, win, nperseg, noverlap, detrend=None,
+ return_onesided=False, scaling='spectrum',
+ mode='complex')
+
+ f2, Sz2 = fftshift(f2_u), fftshift(Sz2_u, axes=0)
+
+ # New STFT:
+ SFT = ShortTimeFFT.from_window(win, fs, nperseg, noverlap,
+ fft_mode='centered', scale_to='magnitude',
+ phase_shift=None)
+ Sz3 = SFT.stft(z, p0=0, p1=(N-noverlap) // SFT.hop, k_offset=nperseg // 2)
+ t3 = SFT.t(N, p0=0, p1=(N-noverlap) // SFT.hop, k_offset=nperseg // 2)
+
+ xp_assert_close(t2, t3)
+ xp_assert_close(f2, SFT.f)
+ xp_assert_close(Sz2, Sz3)
+
+
+def test_permute_axes():
+ """Verify correctness of four-dimensional signal by permuting its
+ shape. """
+ n = 25
+ SFT = ShortTimeFFT(np.ones(8)/8, hop=3, fs=n)
+ x0 = np.arange(n, dtype=np.float64)
+ Sx0 = SFT.stft(x0)
+ Sx0 = Sx0.reshape((Sx0.shape[0], 1, 1, 1, Sx0.shape[-1]))
+ SxT = np.moveaxis(Sx0, (0, -1), (-1, 0))
+
+ atol = 2 * np.finfo(SFT.win.dtype).resolution
+ for i in range(4):
+ y = np.reshape(x0, np.roll((n, 1, 1, 1), i))
+ Sy = SFT.stft(y, axis=i)
+ xp_assert_close(Sy, np.moveaxis(Sx0, 0, i))
+
+ yb0 = SFT.istft(Sy, k1=n, f_axis=i)
+ xp_assert_close(yb0, y, atol=atol)
+ # explicit t-axis parameter (for coverage):
+ yb1 = SFT.istft(Sy, k1=n, f_axis=i, t_axis=Sy.ndim-1)
+ xp_assert_close(yb1, y, atol=atol)
+
+ SyT = np.moveaxis(Sy, (i, -1), (-1, i))
+ xp_assert_close(SyT, np.moveaxis(SxT, 0, i))
+
+ ybT = SFT.istft(SyT, k1=n, t_axis=i, f_axis=-1)
+ xp_assert_close(ybT, y, atol=atol)
+
+
+@pytest.mark.parametrize("fft_mode",
+ ('twosided', 'centered', 'onesided', 'onesided2X'))
+def test_roundtrip_multidimensional(fft_mode: FFT_MODE_TYPE):
+ """Test roundtrip of a multidimensional input signal versus its components.
+
+ This test can uncover potential problems with `fftshift()`.
+ """
+ n = 9
+ x = np.arange(4*n*2, dtype=np.float64).reshape(4, n, 2)
+ SFT = ShortTimeFFT(get_window('hann', 4), hop=2, fs=1,
+ scale_to='magnitude', fft_mode=fft_mode)
+ Sx = SFT.stft(x, axis=1)
+ y = SFT.istft(Sx, k1=n, f_axis=1, t_axis=-1)
+ xp_assert_close(y, x.astype(y.dtype), err_msg='Multidim. roundtrip failed!')
+
+ for i, j in product(range(x.shape[0]), range(x.shape[2])):
+ y_ = SFT.istft(Sx[i, :, j, :], k1=n)
+ xp_assert_close(y_, x[i, :, j].astype(y_.dtype),
+ err_msg="Multidim. roundtrip for component " +
+ f"x[{i}, :, {j}] and {fft_mode=} failed!")
+
+@pytest.mark.parametrize("phase_shift", (0, 4, None))
+def test_roundtrip_two_dimensional(phase_shift: int|None):
+ """Test roundtrip of a 2 channel input signal with `mfft` set with different
+ values for `phase_shift`
+
+ Tests for Issue https://github.com/scipy/scipy/issues/21671
+ """
+ n = 21
+ SFT = ShortTimeFFT.from_window('hann', fs=1, nperseg=13, noverlap=7,
+ mfft=16, phase_shift=phase_shift)
+ x = np.arange(2*n, dtype=float).reshape(2, n)
+ Sx = SFT.stft(x)
+ y = SFT.istft(Sx, k1=n)
+ xp_assert_close(y, x, atol=2 * np.finfo(SFT.win.dtype).resolution,
+ err_msg='2-dim. roundtrip failed!')
+
+
+@pytest.mark.parametrize('window, n, nperseg, noverlap',
+ [('boxcar', 100, 10, 0), # Test no overlap
+ ('boxcar', 100, 10, 9), # Test high overlap
+ ('bartlett', 101, 51, 26), # Test odd nperseg
+ ('hann', 1024, 256, 128), # Test defaults
+ (('tukey', 0.5), 1152, 256, 64), # Test Tukey
+ ('hann', 1024, 256, 255), # Test overlapped hann
+ ('boxcar', 100, 10, 3), # NOLA True, COLA False
+ ('bartlett', 101, 51, 37), # NOLA True, COLA False
+ ('hann', 1024, 256, 127), # NOLA True, COLA False
+ # NOLA True, COLA False:
+ (('tukey', 0.5), 1152, 256, 14),
+ ('hann', 1024, 256, 5)]) # NOLA True, COLA False
+def test_roundtrip_windows(window, n: int, nperseg: int, noverlap: int):
+ """Roundtrip test adapted from `test_spectral.TestSTFT`.
+
+ The parameters are taken from the methods test_roundtrip_real(),
+ test_roundtrip_nola_not_cola(), test_roundtrip_float32(),
+ test_roundtrip_complex().
+ """
+ np.random.seed(2394655)
+
+ w = get_window(window, nperseg)
+ SFT = ShortTimeFFT(w, nperseg - noverlap, fs=1, fft_mode='twosided',
+ phase_shift=None)
+
+ z = 10 * np.random.randn(n) + 10j * np.random.randn(n)
+ Sz = SFT.stft(z)
+ z1 = SFT.istft(Sz, k1=len(z))
+ xp_assert_close(z, z1, err_msg="Roundtrip for complex values failed")
+
+ x = 10 * np.random.randn(n)
+ Sx = SFT.stft(x)
+ x1 = SFT.istft(Sx, k1=len(z))
+ xp_assert_close(x.astype(np.complex128), x1,
+ err_msg="Roundtrip for float values failed")
+
+ x32 = x.astype(np.float32)
+ Sx32 = SFT.stft(x32)
+ x32_1 = SFT.istft(Sx32, k1=len(x32))
+ x32_1_r = x32_1.real
+ xp_assert_close(x32, x32_1_r.astype(np.float32),
+ err_msg="Roundtrip for 32 Bit float values failed")
+ xp_assert_close(x32.imag, np.zeros_like(x32.imag),
+ err_msg="Roundtrip for 32 Bit float values failed")
+
+
+@pytest.mark.parametrize('signal_type', ('real', 'complex'))
+def test_roundtrip_complex_window(signal_type):
+ """Test roundtrip for complex-valued window function
+
+ The purpose of this test is to check if the dual window is calculated
+ correctly for complex-valued windows.
+ """
+ np.random.seed(1354654)
+ win = np.exp(2j*np.linspace(0, np.pi, 8))
+ SFT = ShortTimeFFT(win, 3, fs=1, fft_mode='twosided')
+
+ z = 10 * np.random.randn(11)
+ if signal_type == 'complex':
+ z = z + 2j * z
+ Sz = SFT.stft(z)
+ z1 = SFT.istft(Sz, k1=len(z))
+ xp_assert_close(z.astype(np.complex128), z1,
+ err_msg="Roundtrip for complex-valued window failed")
+
+
+def test_average_all_segments():
+ """Compare `welch` function with stft mean.
+
+ Ported from `TestSpectrogram.test_average_all_segments` from file
+ ``test__spectral.py``.
+ """
+ x = np.random.randn(1024)
+
+ fs = 1.0
+ window = ('tukey', 0.25)
+ nperseg, noverlap = 16, 2
+ fw, Pw = welch(x, fs, window, nperseg, noverlap)
+ SFT = ShortTimeFFT.from_window(window, fs, nperseg, noverlap,
+ fft_mode='onesided2X', scale_to='psd',
+ phase_shift=None)
+ # `welch` positions the window differently than the STFT:
+ P = SFT.spectrogram(x, detr='constant', p0=0,
+ p1=(len(x)-noverlap)//SFT.hop, k_offset=nperseg//2)
+
+ xp_assert_close(SFT.f, fw)
+ xp_assert_close(np.mean(P, axis=-1), Pw)
+
+
+@pytest.mark.parametrize('window, N, nperseg, noverlap, mfft',
+ # from test_roundtrip_padded_FFT:
+ [('hann', 1024, 256, 128, 512),
+ ('hann', 1024, 256, 128, 501),
+ ('boxcar', 100, 10, 0, 33),
+ (('tukey', 0.5), 1152, 256, 64, 1024),
+ # from test_roundtrip_padded_signal:
+ ('boxcar', 101, 10, 0, None),
+ ('hann', 1000, 256, 128, None),
+ # from test_roundtrip_boundary_extension:
+ ('boxcar', 100, 10, 0, None),
+ ('boxcar', 100, 10, 9, None)])
+@pytest.mark.parametrize('padding', get_args(PAD_TYPE))
+def test_stft_padding_roundtrip(window, N: int, nperseg: int, noverlap: int,
+ mfft: int, padding):
+ """Test the parameter 'padding' of `stft` with roundtrips.
+
+ The STFT parametrizations were taken from the methods
+ `test_roundtrip_padded_FFT`, `test_roundtrip_padded_signal` and
+ `test_roundtrip_boundary_extension` from class `TestSTFT` in file
+ ``test_spectral.py``. Note that the ShortTimeFFT does not need the
+ concept of "boundary extension".
+ """
+ x = normal_distribution.rvs(size=N, random_state=2909) # real signal
+ z = x * np.exp(1j * np.pi / 4) # complex signal
+
+ SFT = ShortTimeFFT.from_window(window, 1, nperseg, noverlap,
+ fft_mode='twosided', mfft=mfft)
+ Sx = SFT.stft(x, padding=padding)
+ x1 = SFT.istft(Sx, k1=N)
+ xp_assert_close(x1, x.astype(np.complex128),
+ err_msg=f"Failed real roundtrip with '{padding}' padding")
+
+ Sz = SFT.stft(z, padding=padding)
+ z1 = SFT.istft(Sz, k1=N)
+ xp_assert_close(z1, z, err_msg="Failed complex roundtrip with " +
+ f" '{padding}' padding")
+
+
+@pytest.mark.parametrize('N_x', (128, 129, 255, 256, 1337)) # signal length
+@pytest.mark.parametrize('w_size', (128, 256)) # window length
+@pytest.mark.parametrize('t_step', (4, 64)) # SFT time hop
+@pytest.mark.parametrize('f_c', (7., 23.)) # frequency of input sine
+def test_energy_conservation(N_x: int, w_size: int, t_step: int, f_c: float):
+ """Test if a `psd`-scaled STFT conserves the L2 norm.
+
+ This test is adapted from MNE-Python [1]_. Besides being battle-tested,
+ this test has the benefit of using non-standard window including
+ non-positive values and a 2d input signal.
+
+ Since `ShortTimeFFT` requires the signal length `N_x` to be at least the
+ window length `w_size`, the parameter `N_x` was changed from
+ ``(127, 128, 255, 256, 1337)`` to ``(128, 129, 255, 256, 1337)`` to be
+ more useful.
+
+ .. [1] File ``test_stft.py`` of MNE-Python
+ https://github.com/mne-tools/mne-python/blob/main/mne/time_frequency/tests/test_stft.py
+ """
+ window = np.sin(np.arange(.5, w_size + .5) / w_size * np.pi)
+ SFT = ShortTimeFFT(window, t_step, fs=1000, fft_mode='onesided2X',
+ scale_to='psd')
+ atol = 2*np.finfo(window.dtype).resolution
+ N_x = max(N_x, w_size) # minimal sing
+ # Test with low frequency signal
+ t = np.arange(N_x).astype(np.float64)
+ x = np.sin(2 * np.pi * f_c * t * SFT.T)
+ x = np.array([x, x + 1.])
+ X = SFT.stft(x)
+ xp = SFT.istft(X, k1=N_x)
+
+ max_freq = SFT.f[np.argmax(np.sum(np.abs(X[0]) ** 2, axis=1))]
+
+ assert X.shape[1] == SFT.f_pts
+ assert np.all(SFT.f >= 0.)
+ assert np.abs(max_freq - f_c) < 1.
+ xp_assert_close(x, xp, atol=atol)
+
+ # check L2-norm squared (i.e., energy) conservation:
+ E_x = np.sum(x**2, axis=-1) * SFT.T # numerical integration
+ aX2 = X.real**2 + X.imag.real**2
+ E_X = np.sum(np.sum(aX2, axis=-1) * SFT.delta_t, axis=-1) * SFT.delta_f
+ xp_assert_close(E_X, E_x, atol=atol)
+
+ # Test with random signal
+ np.random.seed(2392795)
+ x = np.random.randn(2, N_x)
+ X = SFT.stft(x)
+ xp = SFT.istft(X, k1=N_x)
+
+ assert X.shape[1] == SFT.f_pts
+ assert np.all(SFT.f >= 0.)
+ assert np.abs(max_freq - f_c) < 1.
+ xp_assert_close(x, xp, atol=atol)
+
+ # check L2-norm squared (i.e., energy) conservation:
+ E_x = np.sum(x**2, axis=-1) * SFT.T # numeric integration
+ aX2 = X.real ** 2 + X.imag.real ** 2
+ E_X = np.sum(np.sum(aX2, axis=-1) * SFT.delta_t, axis=-1) * SFT.delta_f
+ xp_assert_close(E_X, E_x, atol=atol)
+
+ # Try with empty array
+ x = np.zeros((0, N_x))
+ X = SFT.stft(x)
+ xp = SFT.istft(X, k1=N_x)
+ assert xp.shape == x.shape
+
+
+def test_subscriptable_generic_type():
+ assert isinstance(ShortTimeFFT[np.float64], GenericAlias)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_signaltools.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_signaltools.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc9ea2b62687c205d792332a8e2a3ea0a79fe501
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_signaltools.py
@@ -0,0 +1,4766 @@
+import sys
+import math
+import warnings
+
+from concurrent.futures import ThreadPoolExecutor, as_completed
+from itertools import product
+from math import gcd
+
+import pytest
+from pytest import raises as assert_raises
+import numpy as np
+from numpy.exceptions import ComplexWarning
+
+from scipy import fft as sp_fft
+from scipy.ndimage import correlate1d
+from scipy.optimize import fmin, linear_sum_assignment
+from scipy import signal
+from scipy.signal import (
+ correlate, correlate2d, correlation_lags, convolve, convolve2d,
+ fftconvolve, oaconvolve, choose_conv_method, envelope,
+ hilbert, hilbert2, lfilter, lfilter_zi, filtfilt, butter, zpk2tf, zpk2sos,
+ invres, invresz, vectorstrength, lfiltic, tf2sos, sosfilt, sosfiltfilt,
+ sosfilt_zi, tf2zpk, BadCoefficients, detrend, unique_roots, residue,
+ residuez)
+from scipy.signal.windows import hann
+from scipy.signal._signaltools import _filtfilt_gust, _compute_factors, _group_poles
+from scipy.signal._upfirdn import _upfirdn_modes
+from scipy._lib import _testutils
+
+from scipy._lib._array_api import (
+ xp_assert_close, xp_assert_equal, is_numpy, is_torch, is_jax, is_cupy,
+ assert_array_almost_equal, assert_almost_equal,
+ xp_copy, xp_size, xp_default_dtype, array_namespace, make_xp_test_case,
+ make_xp_pytest_param, SCIPY_DEVICE, _xp_copy_to_numpy
+)
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+lazy_xp_modules = [signal]
+
+
+@make_xp_test_case(convolve)
+class TestConvolve:
+
+ @skip_xp_backends("jax.numpy",
+ reason="jax returns floats; scipy returns ints; cf gh-6076")
+ def test_basic(self, xp):
+ a = xp.asarray([3, 4, 5, 6, 5, 4])
+ b = xp.asarray([1, 2, 3])
+ c = convolve(a, b)
+ xp_assert_equal(c, xp.asarray([3, 10, 22, 28, 32, 32, 23, 12]))
+
+ @skip_xp_backends("jax.numpy",
+ reason="jax returns floats; scipy returns ints; cf gh-6076")
+ def test_same(self, xp):
+ a = xp.asarray([3, 4, 5])
+ b = xp.asarray([1, 2, 3, 4])
+ c = convolve(a, b, mode="same")
+ xp_assert_equal(c, xp.asarray([10, 22, 34]))
+
+ @skip_xp_backends("jax.numpy",
+ reason="jax returns floats; scipy returns ints; cf gh-6076")
+ def test_same_eq(self, xp):
+ a = xp.asarray([3, 4, 5])
+ b = xp.asarray([1, 2, 3])
+ c = convolve(a, b, mode="same")
+ xp_assert_equal(c, xp.asarray([10, 22, 22]))
+
+ def test_complex(self, xp):
+ x = xp.asarray([1 + 1j, 2 + 1j, 3 + 1j])
+ y = xp.asarray([1 + 1j, 2 + 1j])
+ z = convolve(x, y)
+ xp_assert_equal(z, xp.asarray([2j, 2 + 6j, 5 + 8j, 5 + 5j]))
+
+ @xfail_xp_backends("jax.numpy", reason="wrong output dtype")
+ def test_zero_rank(self, xp):
+ a = xp.asarray(1289)
+ b = xp.asarray(4567)
+ c = convolve(a, b)
+ xp_assert_equal(c, a * b)
+
+ @skip_xp_backends(np_only=True, reason="pure python")
+ def test_zero_rank_python_scalars(self, xp):
+ a = 1289
+ b = 4567
+ c = convolve(a, b)
+ assert c == a * b
+
+ @xfail_xp_backends("jax.numpy", reason="disagreement between methods")
+ def test_broadcastable(self, xp):
+ a = xp.reshape(xp.arange(27), (3, 3, 3))
+ b = xp.arange(3)
+ for i in range(3):
+ b_shape = [1]*3
+ b_shape[i] = 3
+
+ x = convolve(a, xp.reshape(b, tuple(b_shape)), method='direct')
+ y = convolve(a, xp.reshape(b, tuple(b_shape)), method='fft')
+ xp_assert_close(x, y, atol=1e-14)
+
+ @xfail_xp_backends("jax.numpy", reason="wrong output dtype")
+ def test_single_element(self, xp):
+ a = xp.asarray([4967])
+ b = xp.asarray([3920])
+ c = convolve(a, b)
+ xp_assert_equal(c, a * b)
+
+ @skip_xp_backends("jax.numpy",)
+ @skip_xp_backends("cupy")
+ def test_2d_arrays(self, xp):
+ a = xp.asarray([[1, 2, 3], [3, 4, 5]])
+ b = xp.asarray([[2, 3, 4], [4, 5, 6]])
+ c = convolve(a, b)
+ d = xp.asarray([[2, 7, 16, 17, 12],
+ [10, 30, 62, 58, 38],
+ [12, 31, 58, 49, 30]])
+ xp_assert_equal(c, d)
+
+ @skip_xp_backends("torch")
+ @skip_xp_backends("cupy")
+ def test_input_swapping(self, xp):
+ small = xp.reshape(xp.arange(8), (2, 2, 2))
+ big = 1j * xp.reshape(xp.arange(27, dtype=xp.complex128), (3, 3, 3))
+ big += xp.reshape(xp.arange(27, dtype=xp.complex128)[::-1], (3, 3, 3))
+
+ out_array = xp.asarray(
+ [[[0 + 0j, 26 + 0j, 25 + 1j, 24 + 2j],
+ [52 + 0j, 151 + 5j, 145 + 11j, 93 + 11j],
+ [46 + 6j, 133 + 23j, 127 + 29j, 81 + 23j],
+ [40 + 12j, 98 + 32j, 93 + 37j, 54 + 24j]],
+
+ [[104 + 0j, 247 + 13j, 237 + 23j, 135 + 21j],
+ [282 + 30j, 632 + 96j, 604 + 124j, 330 + 86j],
+ [246 + 66j, 548 + 180j, 520 + 208j, 282 + 134j],
+ [142 + 66j, 307 + 161j, 289 + 179j, 153 + 107j]],
+
+ [[68 + 36j, 157 + 103j, 147 + 113j, 81 + 75j],
+ [174 + 138j, 380 + 348j, 352 + 376j, 186 + 230j],
+ [138 + 174j, 296 + 432j, 268 + 460j, 138 + 278j],
+ [70 + 138j, 145 + 323j, 127 + 341j, 63 + 197j]],
+
+ [[32 + 72j, 68 + 166j, 59 + 175j, 30 + 100j],
+ [68 + 192j, 139 + 433j, 117 + 455j, 57 + 255j],
+ [38 + 222j, 73 + 499j, 51 + 521j, 21 + 291j],
+ [12 + 144j, 20 + 318j, 7 + 331j, 0 + 182j]]])
+
+ xp_assert_equal(convolve(small, big, 'full'), out_array)
+ xp_assert_equal(convolve(big, small, 'full'), out_array)
+ xp_assert_equal(convolve(small, big, 'same'),
+ out_array[1:3, 1:3, 1:3])
+ xp_assert_equal(convolve(big, small, 'same'),
+ out_array[0:3, 0:3, 0:3])
+ xp_assert_equal(convolve(small, big, 'valid'),
+ out_array[1:3, 1:3, 1:3])
+ xp_assert_equal(convolve(big, small, 'valid'),
+ out_array[1:3, 1:3, 1:3])
+
+ def test_invalid_params(self, xp):
+ a = xp.asarray([3, 4, 5])
+ b = xp.asarray([1, 2, 3])
+ assert_raises(ValueError, convolve, a, b, mode='spam')
+ assert_raises(ValueError, convolve, a, b, mode='eggs', method='fft')
+ assert_raises(ValueError, convolve, a, b, mode='ham', method='direct')
+ assert_raises(ValueError, convolve, a, b, mode='full', method='bacon')
+ assert_raises(ValueError, convolve, a, b, mode='same', method='bacon')
+
+ @skip_xp_backends("jax.numpy", reason="dtypes do not match")
+ def test_valid_mode2(self, xp):
+ # See gh-5897
+ a = xp.asarray([1, 2, 3, 6, 5, 3])
+ b = xp.asarray([2, 3, 4, 5, 3, 4, 2, 2, 1])
+ expected = xp.asarray([70, 78, 73, 65])
+
+ out = convolve(a, b, 'valid')
+ xp_assert_equal(out, expected)
+
+ out = convolve(b, a, 'valid')
+ xp_assert_equal(out, expected)
+
+ a = xp.asarray([1 + 5j, 2 - 1j, 3 + 0j])
+ b = xp.asarray([2 - 3j, 1 + 0j])
+ expected = xp.asarray([2 - 3j, 8 - 10j])
+
+ out = convolve(a, b, 'valid')
+ xp_assert_equal(out, expected)
+
+ out = convolve(b, a, 'valid')
+ xp_assert_equal(out, expected)
+
+ @skip_xp_backends("jax.numpy", reason="dtypes do not match")
+ def test_same_mode(self, xp):
+ a = xp.asarray([1, 2, 3, 3, 1, 2])
+ b = xp.asarray([1, 4, 3, 4, 5, 6, 7, 4, 3, 2, 1, 1, 3])
+ c = convolve(a, b, 'same')
+ d = xp.asarray([57, 61, 63, 57, 45, 36])
+ xp_assert_equal(c, d)
+
+ @skip_xp_backends("cupy", reason="different exception")
+ def test_invalid_shapes(self, xp):
+ # By "invalid," we mean that no one
+ # array has dimensions that are all at
+ # least as large as the corresponding
+ # dimensions of the other array. This
+ # setup should throw a ValueError.
+ a = xp.reshape(xp.arange(1, 7), (2, 3))
+ b = xp.reshape(xp.arange(-6, 0), (3, 2))
+
+ assert_raises(ValueError, convolve, *(a, b), **{'mode': 'valid'})
+ assert_raises(ValueError, convolve, *(b, a), **{'mode': 'valid'})
+
+ @skip_xp_backends(np_only=True, reason="TODO: convert this test")
+ def test_convolve_method(self, xp, n=100):
+ # this types data structure was manually encoded instead of
+ # using custom filters on the soon-to-be-removed np.sctypes
+ types = {'uint16', 'uint64', 'int64', 'int32',
+ 'complex128', 'float64', 'float16',
+ 'complex64', 'float32', 'int16',
+ 'uint8', 'uint32', 'int8', 'bool'}
+ args = [(t1, t2, mode) for t1 in types for t2 in types
+ for mode in ['valid', 'full', 'same']]
+
+ # These are random arrays, which means test is much stronger than
+ # convolving testing by convolving two np.ones arrays
+ rng = np.random.RandomState(42)
+ array_types = {'i': rng.choice([0, 1], size=n),
+ 'f': rng.randn(n)}
+ array_types['b'] = array_types['u'] = array_types['i']
+ array_types['c'] = array_types['f'] + 0.5j*array_types['f']
+
+ for t1, t2, mode in args:
+ x1 = array_types[np.dtype(t1).kind].astype(t1)
+ x2 = array_types[np.dtype(t2).kind].astype(t2)
+
+ results = {key: convolve(x1, x2, method=key, mode=mode)
+ for key in ['fft', 'direct']}
+
+ assert results['fft'].dtype == results['direct'].dtype
+
+ if 'bool' in t1 and 'bool' in t2:
+ assert choose_conv_method(x1, x2) == 'direct'
+ continue
+
+ # Found by experiment. Found approx smallest value for (rtol, atol)
+ # threshold to have tests pass.
+ if any([t in {'complex64', 'float32'} for t in [t1, t2]]):
+ kwargs = {'rtol': 1.0e-4, 'atol': 1e-6}
+ elif 'float16' in [t1, t2]:
+ # atol is default for np.allclose
+ kwargs = {'rtol': 1e-3, 'atol': 1e-3}
+ else:
+ # defaults for np.allclose (different from assert_allclose)
+ kwargs = {'rtol': 1e-5, 'atol': 1e-8}
+
+ xp_assert_close(results['fft'], results['direct'], **kwargs)
+
+ @skip_xp_backends("jax.numpy", reason="dtypes do not match")
+ def test_convolve_method_large_input(self, xp):
+ # This is really a test that convolving two large integers goes to the
+ # direct method even if they're in the fft method.
+ for n in [10, 20, 50, 51, 52, 53, 54, 60, 62]:
+ z = xp.asarray([2**n], dtype=xp.int64)
+ fft = convolve(z, z, method='fft')
+ direct = convolve(z, z, method='direct')
+
+ # this is the case when integer precision gets to us
+ # issue #6076 has more detail, hopefully more tests after resolved
+ # # XXX: revisit check_dtype under np 2.0: 32bit linux & windows
+ if n < 50:
+ val = xp.asarray([2**(2*n)])
+ xp_assert_equal(fft, direct)
+ xp_assert_equal(fft, val, check_dtype=False)
+ xp_assert_equal(direct, val, check_dtype=False)
+
+ @skip_xp_backends(np_only=True)
+ def test_mismatched_dims(self, xp):
+ # Input arrays should have the same number of dimensions
+ assert_raises(ValueError, convolve, [1], 2, method='direct')
+ assert_raises(ValueError, convolve, 1, [2], method='direct')
+ assert_raises(ValueError, convolve, [1], 2, method='fft')
+ assert_raises(ValueError, convolve, 1, [2], method='fft')
+ assert_raises(ValueError, convolve, [1], [[2]])
+ assert_raises(ValueError, convolve, [3], 2)
+
+
+@make_xp_test_case(convolve2d)
+class TestConvolve2d:
+
+ @skip_xp_backends("jax.numpy", reason="dtypes do not match")
+ def test_2d_arrays(self, xp):
+ a = xp.asarray([[1, 2, 3], [3, 4, 5]])
+ b = xp.asarray([[2, 3, 4], [4, 5, 6]])
+ d = xp.asarray([[2, 7, 16, 17, 12],
+ [10, 30, 62, 58, 38],
+ [12, 31, 58, 49, 30]])
+ e = convolve2d(a, b)
+ xp_assert_equal(e, d)
+
+ @skip_xp_backends("jax.numpy", reason="dtypes do not match")
+ def test_valid_mode(self, xp):
+ e = xp.asarray([[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]])
+ f = xp.asarray([[1, 2, 3], [3, 4, 5]])
+ h = xp.asarray([[62, 80, 98, 116, 134]])
+
+ g = convolve2d(e, f, 'valid')
+ xp_assert_equal(g, h)
+
+ # See gh-5897
+ g = convolve2d(f, e, 'valid')
+ xp_assert_equal(g, h)
+
+ @skip_xp_backends("torch", reason="dtypes do not match")
+ def test_valid_mode_complx(self, xp):
+ e = xp.asarray([[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]])
+ f = xp.asarray([[1, 2, 3], [3, 4, 5]], dtype=xp.complex128) + 1j
+ h = xp.asarray([[62.+24.j, 80.+30.j, 98.+36.j, 116.+42.j, 134.+48.j]])
+
+ g = convolve2d(e, f, 'valid')
+ xp_assert_close(g, h)
+
+ # See gh-5897
+ g = convolve2d(f, e, 'valid')
+ xp_assert_equal(g, h)
+
+ @skip_xp_backends("jax.numpy", reason="jax only allows fillvalue=0")
+ def test_fillvalue(self, xp):
+ a = xp.asarray([[1, 2, 3], [3, 4, 5]])
+ b = xp.asarray([[2, 3, 4], [4, 5, 6]])
+ fillval = 1
+ c = convolve2d(a, b, 'full', 'fill', fillval)
+ d = xp.asarray([[24, 26, 31, 34, 32],
+ [28, 40, 62, 64, 52],
+ [32, 46, 67, 62, 48]])
+ xp_assert_equal(c, d)
+
+ def test_fillvalue_errors(self, xp):
+ msg = "could not cast `fillvalue` directly to the output "
+ with warnings.catch_warnings():
+ warnings.filterwarnings("ignore", "Casting complex values", ComplexWarning)
+ with assert_raises(ValueError, match=msg):
+ convolve2d([[1]], [[1, 2]], fillvalue=1j)
+
+ msg = "`fillvalue` must be scalar or an array with "
+ with assert_raises(ValueError, match=msg):
+ convolve2d([[1]], [[1, 2]], fillvalue=[1, 2])
+
+ def test_fillvalue_empty(self, xp):
+ # Check that fillvalue being empty raises an error:
+ assert_raises(ValueError, convolve2d, [[1]], [[1, 2]],
+ fillvalue=[])
+
+ @skip_xp_backends("jax.numpy", reason="jax only supports boundary='fill'")
+ def test_wrap_boundary(self, xp):
+ a = xp.asarray([[1, 2, 3], [3, 4, 5]])
+ b = xp.asarray([[2, 3, 4], [4, 5, 6]])
+ c = convolve2d(a, b, 'full', 'wrap')
+ d = xp.asarray([[80, 80, 74, 80, 80],
+ [68, 68, 62, 68, 68],
+ [80, 80, 74, 80, 80]])
+ xp_assert_equal(c, d)
+
+ @skip_xp_backends("jax.numpy", reason="jax only supports boundary='fill'")
+ def test_sym_boundary(self, xp):
+ a = xp.asarray([[1, 2, 3], [3, 4, 5]])
+ b = xp.asarray([[2, 3, 4], [4, 5, 6]])
+ c = convolve2d(a, b, 'full', 'symm')
+ d = xp.asarray([[34, 30, 44, 62, 66],
+ [52, 48, 62, 80, 84],
+ [82, 78, 92, 110, 114]])
+ xp_assert_equal(c, d)
+
+ @skip_xp_backends("jax.numpy", reason="jax only supports boundary='fill'")
+ @pytest.mark.parametrize('func', [convolve2d, correlate2d])
+ @pytest.mark.parametrize('boundary, expected',
+ [('symm', [[37.0, 42.0, 44.0, 45.0]]),
+ ('wrap', [[43.0, 44.0, 42.0, 39.0]])])
+ def test_same_with_boundary(self, func, boundary, expected, xp):
+ # Test boundary='symm' and boundary='wrap' with a "long" kernel.
+ # The size of the kernel requires that the values in the "image"
+ # be extended more than once to handle the requested boundary method.
+ # This is a regression test for gh-8684 and gh-8814.
+ image = xp.asarray([[2.0, -1.0, 3.0, 4.0]])
+ kernel = xp.ones((1, 21))
+ result = func(image, kernel, mode='same', boundary=boundary)
+ # The expected results were calculated "by hand". Because the
+ # kernel is all ones, the same result is expected for convolve2d
+ # and correlate2d.
+ xp_assert_equal(result, xp.asarray(expected))
+
+ @skip_xp_backends("jax.numpy", reason="jax only supports boundary='fill'")
+ def test_boundary_extension_same(self, xp):
+ # Regression test for gh-12686.
+ # Use ndimage.convolve with appropriate arguments to create the
+ # expected result.
+ import scipy.ndimage as ndi
+ a = xp.reshape(xp.arange(1, 10*3+1, dtype=xp.float64), (10, 3))
+ b = xp.reshape(xp.arange(1, 10*10+1, dtype=xp.float64), (10, 10))
+ c = convolve2d(a, b, mode='same', boundary='wrap')
+ xp_assert_equal(c, ndi.convolve(a, b, mode='wrap', origin=(-1, -1)))
+
+ @skip_xp_backends("jax.numpy", reason="jax only supports boundary='fill'")
+ def test_boundary_extension_full(self, xp):
+ # Regression test for gh-12686.
+ # Use ndimage.convolve with appropriate arguments to create the
+ # expected result.
+ import scipy.ndimage as ndi
+ a = xp.reshape(xp.arange(1, 3*3+1, dtype=xp.float64), (3, 3))
+ b = xp.reshape(xp.arange(1, 6*6+1, dtype=xp.float64), (6, 6))
+ c = convolve2d(a, b, mode='full', boundary='wrap')
+
+ a_np = np.arange(1, 3*3 +1, dtype=float).reshape(3, 3)
+ apad_np = np.pad(a_np, ((3, 3), (3, 3)), 'wrap')
+ apad = xp.asarray(apad_np)
+ xp_assert_equal(c, xp.asarray(ndi.convolve(apad, b, mode='wrap')[:-1, :-1]))
+
+ def test_invalid_shapes(self, xp):
+ # By "invalid," we mean that no one
+ # array has dimensions that are all at
+ # least as large as the corresponding
+ # dimensions of the other array. This
+ # setup should throw a ValueError.
+ a = xp.reshape(xp.arange(1, 7), (2, 3))
+ b = xp.reshape(xp.arange(-6, 0), (3, 2))
+
+ assert_raises(ValueError, convolve2d, *(a, b), **{'mode': 'valid'})
+ assert_raises(ValueError, convolve2d, *(b, a), **{'mode': 'valid'})
+
+ @skip_xp_backends("jax.numpy",
+ reason="jax returns floats; scipy returns ints; cf gh-6076")
+ def test_same_mode(self, xp):
+ e = xp.asarray([[1, 2, 3], [3, 4, 5]])
+ f = xp.asarray([[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]])
+ g = convolve2d(e, f, 'same')
+ h = xp.asarray([[22, 28, 34],
+ [80, 98, 116]])
+ xp_assert_equal(g, h)
+
+ @skip_xp_backends("jax.numpy",
+ reason="jax returns floats; scipy returns ints; cf gh-6076")
+ def test_valid_mode2(self, xp):
+ # See gh-5897
+ e = xp.asarray([[1, 2, 3], [3, 4, 5]])
+ f = xp.asarray([[2, 3, 4, 5, 6, 7, 8], [4, 5, 6, 7, 8, 9, 10]])
+ expected = xp.asarray([[62, 80, 98, 116, 134]])
+
+ out = convolve2d(e, f, 'valid')
+ xp_assert_equal(out, expected)
+
+ out = convolve2d(f, e, 'valid')
+ xp_assert_equal(out, expected)
+
+ e = xp.asarray([[1 + 1j, 2 - 3j], [3 + 1j, 4 + 0j]])
+ f = xp.asarray([[2 - 1j, 3 + 2j, 4 + 0j], [4 - 0j, 5 + 1j, 6 - 3j]])
+ expected = xp.asarray([[27 - 1j, 46. + 2j]])
+
+ out = convolve2d(e, f, 'valid')
+ xp_assert_equal(out, expected)
+
+ # See gh-5897
+ out = convolve2d(f, e, 'valid')
+ xp_assert_equal(out, expected)
+
+ @skip_xp_backends("torch",
+ reason="only integer tensors of a single element can be converted"
+ )
+ def test_consistency_convolve_funcs(self, xp):
+ # Compare np.convolve, signal.convolve, signal.convolve2d
+ a = xp.arange(5)
+ b = xp.asarray([3.2, 1.4, 3])
+ a_np = _xp_copy_to_numpy(a)
+ b_np = _xp_copy_to_numpy(b)
+
+ for mode in ['full', 'valid', 'same']:
+ xp_assert_close(
+ xp.asarray(np.convolve(a_np, b_np, mode=mode)),
+ signal.convolve(a, b, mode=mode)
+ )
+ xp_assert_close(
+ xp.squeeze(
+ signal.convolve2d(a[None, :], b[None, :], mode=mode),
+ axis=0
+ ),
+ signal.convolve(a, b, mode=mode)
+ )
+
+ def test_invalid_dims(self, xp):
+ assert_raises(ValueError, convolve2d, 3, 4)
+ assert_raises(ValueError, convolve2d, [3], [4])
+ assert_raises(ValueError, convolve2d, [[[3]]], [[[4]]])
+
+ @pytest.mark.slow
+ @pytest.mark.xfail_on_32bit("Can't create large array for test")
+ @skip_xp_backends(np_only=True, reason="stride_tricks")
+ def test_large_array(self, xp):
+ # Test indexing doesn't overflow an int (gh-10761)
+ n = 2**31 // (1000 * xp.int64().itemsize)
+ _testutils.check_free_memory(2 * n * 1001 * np.int64().itemsize / 1e6)
+
+ # Create a chequered pattern of 1s and 0s
+ a = xp.zeros(1001 * n, dtype=xp.int64)
+ a[::2] = 1
+ a = np.lib.stride_tricks.as_strided(a, shape=(n, 1000), strides=(8008, 8))
+
+ count = signal.convolve2d(a, [[1, 1]])
+ fails = np.where(count > 1)
+ assert fails[0].size == 0
+
+
+@make_xp_test_case(fftconvolve)
+class TestFFTConvolve:
+
+ @skip_xp_backends("torch", reason="dtypes do not match")
+ @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]])
+ def test_real(self, axes, xp):
+ a = xp.asarray([1, 2, 3])
+ expected = xp.asarray([1, 4, 10, 12, 9.])
+
+ if axes == '':
+ out = fftconvolve(a, a)
+ else:
+ if isinstance(axes, list):
+ axes = tuple(axes)
+ out = fftconvolve(a, a, axes=axes)
+
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ @skip_xp_backends("torch", reason="dtypes do not match")
+ @pytest.mark.parametrize('axes', [1, [1], -1, [-1]])
+ def test_real_axes(self, axes, xp):
+ a = xp.asarray([1, 2, 3])
+ expected = xp.asarray([1, 4, 10, 12, 9.])
+
+ a = xp.asarray(np.tile(a, [2, 1]))
+ expected = xp.asarray(np.tile(expected, [2, 1]))
+
+ if isinstance(axes, list):
+ axes = tuple(axes)
+
+ out = fftconvolve(a, a, axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]])
+ def test_complex(self, axes, xp):
+ a = xp.asarray([1 + 1j, 2 + 2j, 3 + 3j])
+ expected = xp.asarray([0 + 2j, 0 + 8j, 0 + 20j, 0 + 24j, 0 + 18j])
+
+ if axes == '':
+ out = fftconvolve(a, a)
+ else:
+ if isinstance(axes, list):
+ axes = tuple(axes)
+ out = fftconvolve(a, a, axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ @pytest.mark.parametrize('axes', [1, [1], -1, [-1]])
+ def test_complex_axes(self, axes, xp):
+ a = xp.asarray([1 + 1j, 2 + 2j, 3 + 3j])
+ expected = xp.asarray([0 + 2j, 0 + 8j, 0 + 20j, 0 + 24j, 0 + 18j])
+
+ a = xp.asarray(np.tile(a, [2, 1]))
+ expected = xp.asarray(np.tile(expected, [2, 1]))
+
+ if isinstance(axes, list):
+ axes = tuple(axes)
+
+ out = fftconvolve(a, a, axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ @pytest.mark.parametrize('axes', ['',
+ None,
+ [0, 1],
+ [1, 0],
+ [0, -1],
+ [-1, 0],
+ [-2, 1],
+ [1, -2],
+ [-2, -1],
+ [-1, -2]])
+ def test_2d_real_same(self, axes, xp):
+ a = xp.asarray([[1.0, 2, 3],
+ [4, 5, 6]])
+ expected = xp.asarray([[1.0, 4, 10, 12, 9],
+ [8, 26, 56, 54, 36],
+ [16, 40, 73, 60, 36]])
+
+ if axes == '':
+ out = fftconvolve(a, a)
+ else:
+ if isinstance(axes, list):
+ axes = tuple(axes)
+ out = fftconvolve(a, a, axes=axes)
+ xp_assert_close(out, expected)
+
+ @pytest.mark.parametrize('axes', [[1, 2],
+ [2, 1],
+ [1, -1],
+ [-1, 1],
+ [-2, 2],
+ [2, -2],
+ [-2, -1],
+ [-1, -2]])
+ def test_2d_real_same_axes(self, axes, xp):
+ a = xp.asarray([[1, 2, 3],
+ [4, 5, 6]])
+ expected = xp.asarray([[1, 4, 10, 12, 9],
+ [8, 26, 56, 54, 36],
+ [16, 40, 73, 60, 36]])
+
+ a = xp.asarray(np.tile(a, [2, 1, 1]))
+ expected = xp.asarray(np.tile(expected, [2, 1, 1]))
+
+ if isinstance(axes, list):
+ axes = tuple(axes)
+
+ out = fftconvolve(a, a, axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6, check_dtype=False)
+
+ @pytest.mark.parametrize('axes', ['',
+ None,
+ [0, 1],
+ [1, 0],
+ [0, -1],
+ [-1, 0],
+ [-2, 1],
+ [1, -2],
+ [-2, -1],
+ [-1, -2]])
+ def test_2d_complex_same(self, axes, xp):
+ a = xp.asarray([[1 + 2j, 3 + 4j, 5 + 6j],
+ [2 + 1j, 4 + 3j, 6 + 5j]])
+ expected = xp.asarray([
+ [-3 + 4j, -10 + 20j, -21 + 56j, -18 + 76j, -11 + 60j],
+ [10j, 44j, 118j, 156j, 122j],
+ [3 + 4j, 10 + 20j, 21 + 56j, 18 + 76j, 11 + 60j]
+ ])
+
+ if axes == '':
+ out = fftconvolve(a, a)
+ else:
+ if isinstance(axes, list):
+ axes = tuple(axes)
+ out = fftconvolve(a, a, axes=axes)
+
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ @pytest.mark.parametrize('axes', [[1, 2],
+ [2, 1],
+ [1, -1],
+ [-1, 1],
+ [-2, 2],
+ [2, -2],
+ [-2, -1],
+ [-1, -2]])
+ def test_2d_complex_same_axes(self, axes, xp):
+ a = xp.asarray([[1 + 2j, 3 + 4j, 5 + 6j],
+ [2 + 1j, 4 + 3j, 6 + 5j]])
+ expected = xp.asarray([
+ [-3 + 4j, -10 + 20j, -21 + 56j, -18 + 76j, -11 + 60j],
+ [10j, 44j, 118j, 156j, 122j],
+ [3 + 4j, 10 + 20j, 21 + 56j, 18 + 76j, 11 + 60j]
+ ])
+
+ a = xp.asarray(np.tile(a, [2, 1, 1]))
+ expected = xp.asarray(np.tile(expected, [2, 1, 1]))
+
+ if isinstance(axes, list):
+ axes = tuple(axes)
+
+ out = fftconvolve(a, a, axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ @skip_xp_backends("torch", reason="dtypes do not match")
+ @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]])
+ def test_real_same_mode(self, axes, xp):
+ a = xp.asarray([1, 2, 3])
+ b = xp.asarray([3, 3, 5, 6, 8, 7, 9, 0, 1])
+ expected_1 = xp.asarray([35., 41., 47.])
+ expected_2 = xp.asarray([9., 20., 25., 35., 41., 47., 39., 28., 2.])
+
+ if axes == '':
+ out = fftconvolve(a, b, 'same')
+ else:
+ if isinstance(axes, list):
+ axes = tuple(axes)
+ out = fftconvolve(a, b, 'same', axes=axes)
+ xp_assert_close(out, expected_1)
+
+ if axes == '':
+ out = fftconvolve(b, a, 'same')
+ else:
+ if isinstance(axes, list):
+ axes = tuple(axes)
+ out = fftconvolve(b, a, 'same', axes=axes)
+ xp_assert_close(out, expected_2, atol=1.5e-6)
+
+ @skip_xp_backends("torch", reason="dtypes do not match")
+ @pytest.mark.parametrize('axes', [1, -1, [1], [-1]])
+ def test_real_same_mode_axes(self, axes, xp):
+ a = xp.asarray([1, 2, 3])
+ b = xp.asarray([3, 3, 5, 6, 8, 7, 9, 0, 1])
+ expected_1 = xp.asarray([35., 41., 47.])
+ expected_2 = xp.asarray([9., 20., 25., 35., 41., 47., 39., 28., 2.])
+
+ a = xp.asarray(np.tile(a, [2, 1]))
+ b = xp.asarray(np.tile(b, [2, 1]))
+ expected_1 = xp.asarray(np.tile(expected_1, [2, 1]))
+ expected_2 = xp.asarray(np.tile(expected_2, [2, 1]))
+
+ if isinstance(axes, list):
+ axes = tuple(axes)
+
+ out = fftconvolve(a, b, 'same', axes=axes)
+ xp_assert_close(out, expected_1, atol=1.5e-6)
+
+ out = fftconvolve(b, a, 'same', axes=axes)
+ xp_assert_close(out, expected_2, atol=1.5e-6)
+
+ @skip_xp_backends("torch", reason="dtypes do not match")
+ @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]])
+ def test_valid_mode_real(self, axes, xp):
+ # See gh-5897
+ a = xp.asarray([3, 2, 1])
+ b = xp.asarray([3, 3, 5, 6, 8, 7, 9, 0, 1])
+ expected = xp.asarray([24., 31., 41., 43., 49., 25., 12.])
+
+ if axes == '':
+ out = fftconvolve(a, b, 'valid')
+ else:
+ if isinstance(axes, list):
+ axes = tuple(axes)
+ out = fftconvolve(a, b, 'valid', axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ if axes == '':
+ out = fftconvolve(b, a, 'valid')
+ else:
+ if isinstance(axes, list):
+ axes = tuple(axes)
+ out = fftconvolve(b, a, 'valid', axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ @skip_xp_backends("torch", reason="dtypes do not match")
+ @pytest.mark.parametrize('axes', [1, [1]])
+ def test_valid_mode_real_axes(self, axes, xp):
+ # See gh-5897
+ a = xp.asarray([3, 2, 1])
+ b = xp.asarray([3, 3, 5, 6, 8, 7, 9, 0, 1])
+ expected = xp.asarray([24., 31., 41., 43., 49., 25., 12.])
+
+ a = xp.asarray(np.tile(a, [2, 1]))
+ b = xp.asarray(np.tile(b, [2, 1]))
+ expected = xp.asarray(np.tile(expected, [2, 1]))
+
+ if isinstance(axes, list):
+ axes = tuple(axes)
+
+ out = fftconvolve(a, b, 'valid', axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]])
+ def test_valid_mode_complex(self, axes, xp):
+ a = xp.asarray([3 - 1j, 2 + 7j, 1 + 0j])
+ b = xp.asarray([3 + 2j, 3 - 3j, 5 + 0j, 6 - 1j, 8 + 0j])
+ expected = xp.asarray([45. + 12.j, 30. + 23.j, 48 + 32.j])
+
+ if axes == '':
+ out = fftconvolve(a, b, 'valid')
+ else:
+ if isinstance(axes, list):
+ axes = tuple(axes)
+ out = fftconvolve(a, b, 'valid', axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ if axes == '':
+ out = fftconvolve(b, a, 'valid')
+ else:
+ if isinstance(axes, list):
+ axes = tuple(axes)
+ out = fftconvolve(b, a, 'valid', axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ @pytest.mark.parametrize('axes', [1, [1], -1, [-1]])
+ def test_valid_mode_complex_axes(self, axes, xp):
+ a = xp.asarray([3 - 1j, 2 + 7j, 1 + 0j])
+ b = xp.asarray([3 + 2j, 3 - 3j, 5 + 0j, 6 - 1j, 8 + 0j])
+ expected = xp.asarray([45. + 12.j, 30. + 23.j, 48 + 32.j])
+
+ a = xp.asarray(np.tile(a, [2, 1]))
+ b = xp.asarray(np.tile(b, [2, 1]))
+ expected = xp.asarray(np.tile(expected, [2, 1]))
+
+ if isinstance(axes, list):
+ axes = tuple(axes)
+
+ out = fftconvolve(a, b, 'valid', axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ out = fftconvolve(b, a, 'valid', axes=axes)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ @skip_xp_backends("jax.numpy", reason="mapped axes must have same shape")
+ @skip_xp_backends("torch", reason="dtypes do not match")
+ def test_valid_mode_ignore_nonaxes(self, xp):
+ # See gh-5897
+ a = xp.asarray([3, 2, 1])
+ b = xp.asarray([3, 3, 5, 6, 8, 7, 9, 0, 1])
+ expected = xp.asarray([24., 31., 41., 43., 49., 25., 12.])
+
+ a = xp.asarray(np.tile(a, [2, 1]))
+ b = xp.asarray(np.tile(b, [1, 1]))
+ expected = xp.asarray(np.tile(expected, [2, 1]))
+
+ out = fftconvolve(a, b, 'valid', axes=1)
+ xp_assert_close(out, expected, atol=1.5e-6)
+
+ @xfail_xp_backends("cupy", reason="dtypes do not match")
+ @xfail_xp_backends("jax.numpy", reason="assorted error messages")
+ @pytest.mark.parametrize("a,b", [([], []), ([5, 6], []), ([], [7])])
+ def test_empty(self, a, b, xp):
+ # Regression test for #1745: crashes with 0-length input.
+ xp_assert_equal(
+ fftconvolve(xp.asarray(a), xp.asarray(b)),
+ xp.asarray([]),
+ )
+
+ @skip_xp_backends("jax.numpy", reason="jnp.pad: pad_width with nd=0")
+ def test_zero_rank(self, xp):
+ a = xp.asarray(4967)
+ b = xp.asarray(3920)
+ out = fftconvolve(a, b)
+ xp_assert_equal(out, a * b)
+
+ def test_single_element(self, xp):
+ a = xp.asarray([4967])
+ b = xp.asarray([3920])
+ out = fftconvolve(a, b)
+ xp_assert_equal(out,
+ xp.asarray(a * b, dtype=out.dtype))
+
+ @pytest.mark.parametrize('axes', ['', None, 0, [0], -1, [-1]])
+ def test_random_data(self, axes, xp):
+ rng = np.random.default_rng(1234)
+ a_np = np.random.rand(1233) + 1j * rng.random(1233)
+ b_np = np.random.rand(1321) + 1j * rng.random(1321)
+ expected = xp.asarray(np.convolve(a_np, b_np, 'full'))
+ a = xp.asarray(a_np)
+ b = xp.asarray(b_np)
+
+ if axes == '':
+ out = fftconvolve(a, b, 'full')
+ else:
+ if isinstance(axes, list):
+ axes = tuple(axes)
+ out = fftconvolve(a, b, 'full', axes=axes)
+ xp_assert_close(out, expected, rtol=1e-10)
+
+ @pytest.mark.parametrize('axes', [1, [1], -1, [-1]])
+ def test_random_data_axes(self, axes, xp):
+ rng = np.random.default_rng(1234)
+ a_np = np.random.rand(1233) + 1j * rng.random(1233)
+ b_np = np.random.rand(1321) + 1j * rng.random(1321)
+ expected = np.convolve(a_np, b_np, 'full')
+ a_np = np.tile(a_np, [2, 1])
+ b_np = np.tile(b_np, [2, 1])
+ expected = xp.asarray(np.tile(expected, [2, 1]))
+
+ a = xp.asarray(a_np)
+ b = xp.asarray(b_np)
+
+ if isinstance(axes, list):
+ axes = tuple(axes)
+
+ out = fftconvolve(a, b, 'full', axes=axes)
+ xp_assert_close(out, expected, rtol=1e-10)
+
+ @xfail_xp_backends(np_only=True, reason="TODO: swapaxes")
+ @pytest.mark.parametrize('axes', [[1, 4],
+ [4, 1],
+ [1, -1],
+ [-1, 1],
+ [-4, 4],
+ [4, -4],
+ [-4, -1],
+ [-1, -4]])
+ def test_random_data_multidim_axes(self, axes, xp):
+ a_shape, b_shape = (123, 22), (132, 11)
+ rng = np.random.default_rng(1234)
+ a = xp.asarray(np.random.rand(*a_shape) + 1j * rng.random(a_shape))
+ b = xp.asarray(np.random.rand(*b_shape) + 1j * rng.random(b_shape))
+ expected = convolve2d(a, b, 'full')
+
+ a = a[:, :, None, None, None]
+ b = b[:, :, None, None, None]
+ expected = expected[:, :, None, None, None]
+
+ a = xp.moveaxis(a.swapaxes(0, 2), 1, 4)
+ b = xp.moveaxis(b.swapaxes(0, 2), 1, 4)
+ expected = xp.moveaxis(expected.swapaxes(0, 2), 1, 4)
+
+ # use 1 for dimension 2 in a and 3 in b to test broadcasting
+ a = xp.asarray(np.tile(a, [2, 1, 3, 1, 1]))
+ b = xp.asarray(np.tile(b, [2, 1, 1, 4, 1]))
+ expected = xp.asarray(np.tile(expected, [2, 1, 3, 4, 1]))
+
+ out = fftconvolve(a, b, 'full', axes=axes)
+ xp_assert_close(out, expected, rtol=1e-10, atol=1e-10)
+
+ @pytest.mark.slow
+ @pytest.mark.parametrize(
+ 'n',
+ list(range(1, 100)) +
+ list(range(1000, 1500)) +
+ np.random.RandomState(1234).randint(1001, 10000, 5).tolist())
+ def test_many_sizes(self, n, xp):
+ a_np = np.random.rand(n) + 1j * np.random.rand(n)
+ b_np = np.random.rand(n) + 1j * np.random.rand(n)
+ expected = xp.asarray(np.convolve(a_np, b_np, 'full'))
+ a = xp.asarray(a_np)
+ b = xp.asarray(b_np)
+
+ out = fftconvolve(a, b, 'full')
+ xp_assert_close(out, expected, atol=1e-10)
+
+ out = fftconvolve(a, b, 'full', axes=(0,))
+ xp_assert_close(out, expected, atol=1e-10)
+
+ @skip_xp_backends(np_only=True)
+ def test_fft_nan(self, xp):
+ n = 1000
+ rng = np.random.default_rng(43876432987)
+ sig_nan = xp.asarray(rng.standard_normal(n))
+
+ for val in [np.nan, np.inf]:
+ sig_nan[100] = val
+ coeffs = xp.asarray(signal.firwin(200, 0.2))
+
+ msg = "Use of fft convolution.*|invalid value encountered.*"
+ with pytest.warns(RuntimeWarning, match=msg):
+ signal.convolve(sig_nan, coeffs, mode='same', method='fft')
+
+
+def fftconvolve_err(*args, **kwargs):
+ raise RuntimeError('Fell back to fftconvolve')
+
+
+def gen_oa_shapes(sizes):
+ return [(a, b) for a, b in product(sizes, repeat=2)
+ if abs(a - b) > 3]
+
+
+def gen_oa_shapes_2d(sizes):
+ shapes0 = gen_oa_shapes(sizes)
+ shapes1 = gen_oa_shapes(sizes)
+ shapes = [ishapes0+ishapes1 for ishapes0, ishapes1 in
+ zip(shapes0, shapes1)]
+
+ modes = ['full', 'valid', 'same']
+ return [ishapes+(imode,) for ishapes, imode in product(shapes, modes)
+ if imode != 'valid' or
+ (ishapes[0] > ishapes[1] and ishapes[2] > ishapes[3]) or
+ (ishapes[0] < ishapes[1] and ishapes[2] < ishapes[3])]
+
+
+def gen_oa_shapes_eq(sizes):
+ return [(a, b) for a, b in product(sizes, repeat=2)
+ if a >= b]
+
+
+@make_xp_test_case(oaconvolve)
+class TestOAConvolve:
+ @pytest.mark.slow()
+ @pytest.mark.parametrize('shape_a_0, shape_b_0',
+ gen_oa_shapes_eq(list(range(1, 100, 1)) +
+ list(range(100, 1000, 23)))
+ )
+ def test_real_manylens(self, shape_a_0, shape_b_0, xp):
+ a = np.random.rand(shape_a_0)
+ b = np.random.rand(shape_b_0)
+ expected = xp.asarray(fftconvolve(a, b))
+ a = xp.asarray(a)
+ b = xp.asarray(b)
+
+ out = oaconvolve(a, b)
+
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('shape_a_0, shape_b_0',
+ gen_oa_shapes([50, 47, 6, 4, 1]))
+ @pytest.mark.parametrize('is_complex', [True, False])
+ @pytest.mark.parametrize('mode', ['full', 'valid', 'same'])
+ def test_1d_noaxes(self, shape_a_0, shape_b_0,
+ is_complex, mode, monkeypatch, xp):
+ a = np.random.rand(shape_a_0)
+ b = np.random.rand(shape_b_0)
+ if is_complex:
+ a = a + 1j*np.random.rand(shape_a_0)
+ b = b + 1j*np.random.rand(shape_b_0)
+ expected = xp.asarray(fftconvolve(a, b, mode=mode))
+ a = xp.asarray(a)
+ b = xp.asarray(b)
+
+ monkeypatch.setattr(signal._signaltools, 'fftconvolve',
+ fftconvolve_err)
+ out = oaconvolve(a, b, mode=mode)
+
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('axes', [0, 1])
+ @pytest.mark.parametrize('shape_a_0, shape_b_0',
+ gen_oa_shapes([50, 47, 6, 4]))
+ @pytest.mark.parametrize('shape_a_extra', [1, 3])
+ @pytest.mark.parametrize('shape_b_extra', [1, 3])
+ @pytest.mark.parametrize('is_complex', [True, False])
+ @pytest.mark.parametrize('mode', ['full', 'valid', 'same'])
+ def test_1d_axes(self, axes, shape_a_0, shape_b_0,
+ shape_a_extra, shape_b_extra,
+ is_complex, mode, monkeypatch, xp):
+ ax_a = [shape_a_extra]*2
+ ax_b = [shape_b_extra]*2
+ ax_a[axes] = shape_a_0
+ ax_b[axes] = shape_b_0
+
+ a = np.random.rand(*ax_a)
+ b = np.random.rand(*ax_b)
+ if is_complex:
+ a = a + 1j*np.random.rand(*ax_a)
+ b = b + 1j*np.random.rand(*ax_b)
+
+ expected = xp.asarray(fftconvolve(a, b, mode=mode, axes=axes))
+ a = xp.asarray(a)
+ b = xp.asarray(b)
+
+ monkeypatch.setattr(signal._signaltools, 'fftconvolve',
+ fftconvolve_err)
+ out = oaconvolve(a, b, mode=mode, axes=axes)
+
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('shape_a_0, shape_b_0, '
+ 'shape_a_1, shape_b_1, mode',
+ gen_oa_shapes_2d([50, 47, 6, 4]))
+ @pytest.mark.parametrize('is_complex', [True, False])
+ def test_2d_noaxes(self, shape_a_0, shape_b_0,
+ shape_a_1, shape_b_1, mode,
+ is_complex, monkeypatch, xp):
+ a = np.random.rand(shape_a_0, shape_a_1)
+ b = np.random.rand(shape_b_0, shape_b_1)
+ if is_complex:
+ a = a + 1j*np.random.rand(shape_a_0, shape_a_1)
+ b = b + 1j*np.random.rand(shape_b_0, shape_b_1)
+
+ expected = xp.asarray(fftconvolve(a, b, mode=mode))
+ a = xp.asarray(a)
+ b = xp.asarray(b)
+
+ monkeypatch.setattr(signal._signaltools, 'fftconvolve',
+ fftconvolve_err)
+ out = oaconvolve(a, b, mode=mode)
+
+ assert_array_almost_equal(out, expected)
+
+ @pytest.mark.parametrize('axes', [[0, 1], [0, 2], [1, 2]])
+ @pytest.mark.parametrize('shape_a_0, shape_b_0, '
+ 'shape_a_1, shape_b_1, mode',
+ gen_oa_shapes_2d([50, 47, 6, 4]))
+ @pytest.mark.parametrize('shape_a_extra', [1, 3])
+ @pytest.mark.parametrize('shape_b_extra', [1, 3])
+ @pytest.mark.parametrize('is_complex', [True, False])
+ def test_2d_axes(self, axes, shape_a_0, shape_b_0,
+ shape_a_1, shape_b_1, mode,
+ shape_a_extra, shape_b_extra,
+ is_complex, monkeypatch, xp):
+ ax_a = [shape_a_extra]*3
+ ax_b = [shape_b_extra]*3
+ ax_a[axes[0]] = shape_a_0
+ ax_b[axes[0]] = shape_b_0
+ ax_a[axes[1]] = shape_a_1
+ ax_b[axes[1]] = shape_b_1
+
+ a = np.random.rand(*ax_a)
+ b = np.random.rand(*ax_b)
+ if is_complex:
+ a = a + 1j*np.random.rand(*ax_a)
+ b = b + 1j*np.random.rand(*ax_b)
+
+ axes = tuple(axes) # XXX for CuPy
+ expected = xp.asarray(fftconvolve(a, b, mode=mode, axes=axes))
+ a = xp.asarray(a)
+ b = xp.asarray(b)
+
+ monkeypatch.setattr(signal._signaltools, 'fftconvolve',
+ fftconvolve_err)
+ out = oaconvolve(a, b, mode=mode, axes=axes)
+
+ assert_array_almost_equal(out, expected)
+
+ @xfail_xp_backends("torch", reason="ValueError: Target length must be positive")
+ @pytest.mark.parametrize("a,b", [([], []), ([5, 6], []), ([], [7])])
+ def test_empty(self, a, b, xp):
+ # Regression test for #1745: crashes with 0-length input.
+ xp_assert_equal(
+ oaconvolve(xp.asarray(a), xp.asarray(b)),
+ xp.asarray([]), check_dtype=False
+ )
+
+ def test_zero_rank(self, xp):
+ a = xp.asarray(4967)
+ b = xp.asarray(3920)
+ out = oaconvolve(a, b)
+ xp_assert_equal(out, a * b)
+
+ def test_single_element(self, xp):
+ a = xp.asarray([4967])
+ b = xp.asarray([3920])
+ out = oaconvolve(a, b)
+ xp_assert_equal(out, a * b)
+
+
+@skip_xp_backends(np_only=True, reason="assertions may differ on backends")
+@pytest.mark.parametrize('convapproach',
+ [make_xp_pytest_param(fftconvolve),
+ make_xp_pytest_param(oaconvolve)])
+class TestAllFreqConvolves:
+
+ def test_invalid_shapes(self, convapproach, xp):
+ a = np.arange(1, 7).reshape((2, 3))
+ b = np.arange(-6, 0).reshape((3, 2))
+ with assert_raises(ValueError,
+ match="For 'valid' mode, one must be at least "
+ "as large as the other in every dimension"):
+ convapproach(a, b, mode='valid')
+
+ def test_invalid_shapes_axes(self, convapproach, xp):
+ a = np.zeros([5, 6, 2, 1])
+ b = np.zeros([5, 6, 3, 1])
+ with assert_raises(ValueError,
+ match=r"incompatible shapes for in1 and in2:"
+ r" \(5L?, 6L?, 2L?, 1L?\) and"
+ r" \(5L?, 6L?, 3L?, 1L?\)"):
+ convapproach(a, b, axes=[0, 1])
+
+ @pytest.mark.parametrize('a,b',
+ [([1], 2),
+ (1, [2]),
+ ([3], [[2]])])
+ def test_mismatched_dims(self, a, b, convapproach, xp):
+ with assert_raises(ValueError,
+ match="in1 and in2 should have the same"
+ " dimensionality"):
+ convapproach(a, b)
+
+ def test_invalid_flags(self, convapproach, xp):
+ with assert_raises(ValueError,
+ match="acceptable mode flags are 'valid',"
+ " 'same', or 'full'"):
+ convapproach([1], [2], mode='chips')
+
+ with assert_raises(ValueError,
+ match="when provided, axes cannot be empty"):
+ convapproach([1], [2], axes=[])
+
+ with assert_raises(ValueError, match="axes must be a scalar or "
+ "iterable of integers"):
+ convapproach([1], [2], axes=[[1, 2], [3, 4]])
+
+ with assert_raises(ValueError, match="axes must be a scalar or "
+ "iterable of integers"):
+ convapproach([1], [2], axes=[1., 2., 3., 4.])
+
+ with assert_raises(ValueError,
+ match="axes exceeds dimensionality of input"):
+ convapproach([1], [2], axes=[1])
+
+ with assert_raises(ValueError,
+ match="axes exceeds dimensionality of input"):
+ convapproach([1], [2], axes=[-2])
+
+ with assert_raises(ValueError,
+ match="all axes must be unique"):
+ convapproach([1], [2], axes=[0, 0])
+
+
+@skip_xp_backends(np_only=True, reason="assertions may differ on backends")
+@pytest.mark.filterwarnings('ignore::DeprecationWarning')
+@pytest.mark.parametrize('dtype', [np.longdouble, np.clongdouble])
+@make_xp_test_case(convolve, fftconvolve)
+def test_convolve_longdtype_input(dtype, xp):
+ x = np.random.random((27, 27)).astype(dtype)
+ y = np.random.random((4, 4)).astype(dtype)
+ if np.iscomplexobj(dtype()):
+ x += .1j
+ y -= .1j
+
+ res = fftconvolve(x, y)
+ xp_assert_close(res, convolve(x, y, method='direct'))
+ assert res.dtype == dtype
+
+
+class TestMedFilt:
+
+ IN = [[50, 50, 50, 50, 50, 92, 18, 27, 65, 46],
+ [50, 50, 50, 50, 50, 0, 72, 77, 68, 66],
+ [50, 50, 50, 50, 50, 46, 47, 19, 64, 77],
+ [50, 50, 50, 50, 50, 42, 15, 29, 95, 35],
+ [50, 50, 50, 50, 50, 46, 34, 9, 21, 66],
+ [70, 97, 28, 68, 78, 77, 61, 58, 71, 42],
+ [64, 53, 44, 29, 68, 32, 19, 68, 24, 84],
+ [3, 33, 53, 67, 1, 78, 74, 55, 12, 83],
+ [7, 11, 46, 70, 60, 47, 24, 43, 61, 26],
+ [32, 61, 88, 7, 39, 4, 92, 64, 45, 61]]
+
+ OUT = [[0, 50, 50, 50, 42, 15, 15, 18, 27, 0],
+ [0, 50, 50, 50, 50, 42, 19, 21, 29, 0],
+ [50, 50, 50, 50, 50, 47, 34, 34, 46, 35],
+ [50, 50, 50, 50, 50, 50, 42, 47, 64, 42],
+ [50, 50, 50, 50, 50, 50, 46, 55, 64, 35],
+ [33, 50, 50, 50, 50, 47, 46, 43, 55, 26],
+ [32, 50, 50, 50, 50, 47, 46, 45, 55, 26],
+ [7, 46, 50, 50, 47, 46, 46, 43, 45, 21],
+ [0, 32, 33, 39, 32, 32, 43, 43, 43, 0],
+ [0, 7, 11, 7, 4, 4, 19, 19, 24, 0]]
+
+ KERNEL_SIZE = [7,3]
+
+ @make_xp_test_case(signal.medfilt, signal.medfilt2d)
+ def test_basic(self, xp):
+
+ in_ = xp.asarray(self.IN)
+ out_ = xp.asarray(self.OUT)
+ kernel_size = xp.asarray(self.KERNEL_SIZE)
+
+ d = signal.medfilt(in_, kernel_size)
+ e = signal.medfilt2d(xp.asarray(in_, dtype=xp.float64), kernel_size)
+ xp_assert_equal(d, out_)
+ xp_assert_equal(d, e, check_dtype=False)
+
+ @pytest.mark.parametrize('dtype', ["uint8", "int8", "uint16", "int16",
+ "uint32", "int32", "uint64", "int64",
+ "float32", "float64"])
+ @make_xp_test_case(signal.medfilt, signal.medfilt2d)
+ def test_types(self, dtype, xp):
+ # volume input and output types match
+ if is_torch(xp) and dtype in ["uint16", "uint32", "uint64"]:
+ pytest.skip("torch does not support unisigned ints")
+
+ dtype = getattr(xp, dtype)
+ in_typed = xp.asarray(self.IN, dtype=dtype)
+ assert signal.medfilt(in_typed).dtype == dtype
+ assert signal.medfilt2d(in_typed).dtype == dtype
+
+ @skip_xp_backends(np_only=True, reason="assertions may differ")
+ @pytest.mark.parametrize('dtype', [np.bool_, np.complex64, np.complex128,
+ np.clongdouble, np.float16,
+ "float96", "float128"])
+ @make_xp_test_case(signal.medfilt, signal.medfilt2d)
+ def test_invalid_dtypes(self, dtype, xp):
+ # We can only test this on platforms that support a native type of float96 or
+ # float128; comparing to np.longdouble allows us to filter out non-native types
+ if (dtype in ["float96", "float128"]
+ and np.finfo(np.longdouble).dtype != dtype):
+ pytest.skip(f"Platform does not support {dtype}")
+
+ in_typed = np.array(self.IN, dtype=dtype)
+ with pytest.raises(ValueError, match="not supported"):
+ signal.medfilt(in_typed)
+
+ with pytest.raises(ValueError, match="not supported"):
+ signal.medfilt2d(in_typed)
+
+ @skip_xp_backends(np_only=True, reason="object arrays")
+ @make_xp_test_case(signal.medfilt)
+ def test_none(self, xp):
+ # gh-1651, trac #1124. Ensure this does not segfault.
+ with assert_raises((ValueError, TypeError)):
+ signal.medfilt(None)
+
+ @skip_xp_backends(np_only=True, reason="strides are only writeable in NumPy")
+ @make_xp_test_case(signal.medfilt)
+ def test_odd_strides(self, xp):
+ # Avoid a regression with possible contiguous
+ # numpy arrays that have odd strides. The stride value below gets
+ # us into wrong memory if used (but it does not need to be used)
+ dummy = xp.arange(10, dtype=xp.float64)
+ a = dummy[5:6]
+ a = np.lib.stride_tricks.as_strided(a, strides=(16,))
+ xp_assert_close(signal.medfilt(a, 1), xp.asarray([5.]))
+
+ @skip_xp_backends(
+ "jax.numpy",
+ reason="chunk assignment does not work on jax immutable arrays"
+ )
+ @pytest.mark.parametrize("dtype", ["uint8", "float32", "float64"])
+ @make_xp_test_case(signal.medfilt2d)
+ def test_medfilt2d_parallel(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ in_typed = xp.asarray(self.IN, dtype=dtype)
+ expected = xp.asarray(self.OUT, dtype=dtype)
+
+ # This is used to simplify the indexing calculations.
+ assert in_typed.shape == expected.shape
+
+ # We'll do the calculation in four chunks. M1 and N1 are the dimensions
+ # of the first output chunk. We have to extend the input by half the
+ # kernel size to be able to calculate the full output chunk.
+ M1 = expected.shape[0] // 2
+ N1 = expected.shape[1] // 2
+ offM = self.KERNEL_SIZE[0] // 2 + 1
+ offN = self.KERNEL_SIZE[1] // 2 + 1
+
+ def apply(chunk):
+ # in = slice of in_typed to use.
+ # sel = slice of output to crop it to the correct region.
+ # out = slice of output array to store in.
+ M, N = chunk
+ if M == 0:
+ Min = slice(0, M1 + offM)
+ Msel = slice(0, -offM)
+ Mout = slice(0, M1)
+ else:
+ Min = slice(M1 - offM, None)
+ Msel = slice(offM, None)
+ Mout = slice(M1, None)
+ if N == 0:
+ Nin = slice(0, N1 + offN)
+ Nsel = slice(0, -offN)
+ Nout = slice(0, N1)
+ else:
+ Nin = slice(N1 - offN, None)
+ Nsel = slice(offN, None)
+ Nout = slice(N1, None)
+
+ # Do the calculation, but do not write to the output in the threads.
+ chunk_data = in_typed[Min, Nin]
+ med = signal.medfilt2d(chunk_data, self.KERNEL_SIZE)
+ return med[Msel, Nsel], Mout, Nout
+
+ # Give each chunk to a different thread.
+ output = xp.zeros_like(expected)
+ with ThreadPoolExecutor(max_workers=4) as pool:
+ chunks = {(0, 0), (0, 1), (1, 0), (1, 1)}
+ futures = {pool.submit(apply, chunk) for chunk in chunks}
+
+ # Store each result in the output as it arrives.
+ for future in as_completed(futures):
+ data, Mslice, Nslice = future.result()
+ output[Mslice, Nslice] = data
+
+ xp_assert_equal(output, expected)
+
+
+@make_xp_test_case(signal.wiener)
+class TestWiener:
+
+ @skip_xp_backends("cupy", reason="XXX: can_cast in cupy <= 13.2")
+ def test_basic(self, xp):
+ g = xp.asarray([[5, 6, 4, 3],
+ [3, 5, 6, 2],
+ [2, 3, 5, 6],
+ [1, 6, 9, 7]], dtype=xp.float64)
+ h = xp.asarray([[2.16374269, 3.2222222222, 2.8888888889, 1.6666666667],
+ [2.666666667, 4.33333333333, 4.44444444444, 2.8888888888],
+ [2.222222222, 4.4444444444, 5.4444444444, 4.801066874837],
+ [1.33333333333, 3.92735042735, 6.0712560386, 5.0404040404]])
+ assert_array_almost_equal(signal.wiener(g), h, decimal=6)
+ assert_array_almost_equal(signal.wiener(g, mysize=3), h, decimal=6)
+
+
+padtype_options = ["mean", "median", "minimum", "maximum", "line"]
+padtype_options += _upfirdn_modes
+
+
+class TestResample:
+
+ @make_xp_test_case(signal.resample, signal.resample_poly)
+ @xfail_xp_backends("cupy", reason="does not raise with non-int upsampling factor")
+ def test_basic(self, xp):
+ # Some basic tests
+
+ # Regression test for issue #3603.
+ # window.shape must equal to sig.shape[0]
+ sig = xp.arange(128, dtype=xp.float64)
+ num = 256
+ win = signal.get_window(('kaiser', 8.0), 160, xp=xp)
+ assert_raises(ValueError, signal.resample, sig, num, window=win)
+ assert_raises(ValueError, signal.resample, sig, num, domain='INVALID')
+
+ # Other degenerate conditions
+ assert_raises(ValueError, signal.resample_poly, sig, 'yo', 1)
+ assert_raises(ValueError, signal.resample_poly, sig, 1, 0)
+ assert_raises(ValueError, signal.resample_poly, sig, 1.3, 2)
+ assert_raises(ValueError, signal.resample_poly, sig, 2, 1.3)
+ assert_raises(ValueError, signal.resample_poly, sig, 2, 1, padtype='')
+ assert_raises(ValueError, signal.resample_poly, sig, 2, 1,
+ padtype='mean', cval=10)
+ assert_raises(ValueError, signal.resample_poly, sig, 2, 1, window=xp.eye(2))
+
+ # test for issue #6505 - should not modify window.shape when axis ≠0
+ sig2 = xp.tile(xp.arange(160, dtype=xp.float64), (2, 1))
+ signal.resample(sig2, num, axis=-1, window=win)
+ assert win.shape == (160,)
+
+ # Ensure coverage for parameter cval=None and cval != None:
+ x_ref = signal.resample_poly(sig, 2, 1)
+ x0 = signal.resample_poly(sig, 2, 1, padtype='constant')
+ x1 = signal.resample_poly(sig, 2, 1, padtype='constant', cval=0)
+ xp_assert_equal(x1, x_ref)
+ xp_assert_equal(x0, x_ref)
+
+ @pytest.mark.parametrize('window', (None, 'hamming'))
+ @pytest.mark.parametrize('N', (20, 19))
+ @pytest.mark.parametrize('num', (100, 101, 10, 11))
+ @make_xp_test_case(signal.resample)
+ def test_rfft(self, N, num, window, xp):
+ # Make sure the speed up using rfft gives the same result as the normal
+ # way using fft
+ dt_r = xp_default_dtype(xp)
+ dt_c = xp.complex64 if dt_r == xp.float32 else xp.complex128
+
+ x = xp.linspace(0, 10, N, endpoint=False)
+ y = xp.cos(-x**2/6.0)
+ desired = signal.resample(xp.astype(y, dt_c), num, window=window)
+ xp_assert_close(signal.resample(y, num, window=window),
+ xp.real(desired))
+
+ y = xp.stack([xp.cos(-x**2/6.0), xp.sin(-x**2/6.0)])
+ y_complex = xp.astype(y, dt_c)
+ resampled = signal.resample(y_complex, num, axis=1, window=window)
+
+ atol = 1e-9 if dt_r == xp.float64 else 3e-7
+
+ xp_assert_close(
+ signal.resample(y, num, axis=1, window=window),
+ xp.real(resampled),
+ atol=atol)
+
+ @make_xp_test_case(signal.resample)
+ def test_input_domain(self, xp):
+ # Test if both input domain modes produce the same results.
+ tsig = xp.astype(xp.arange(256), xp.complex128)
+ fsig = sp_fft.fft(tsig)
+ num = 256
+ xp_assert_close(
+ signal.resample(fsig, num, domain='freq'),
+ signal.resample(tsig, num, domain='time'),
+ atol=1e-9)
+
+ @pytest.mark.parametrize('nx', (1, 2, 3, 5, 8))
+ @pytest.mark.parametrize('ny', (1, 2, 3, 5, 8))
+ @pytest.mark.parametrize('dtype', ('float64', 'complex128'))
+ @make_xp_test_case(signal.resample)
+ def test_dc(self, nx, ny, dtype, xp):
+ dtype = getattr(xp, dtype)
+ x = xp.asarray([1] * nx, dtype=dtype)
+ y = signal.resample(x, ny)
+ xp_assert_close(y, xp.asarray([1] * ny, dtype=y.dtype))
+
+ @skip_xp_backends("cupy", reason="padtype not supported by upfirdn")
+ @pytest.mark.parametrize('padtype', padtype_options)
+ @make_xp_test_case(signal.resample_poly)
+ def test_mutable_window(self, padtype, xp):
+ # Test that a mutable window is not modified
+ impulse = xp.zeros(3)
+ window = xp.asarray(np.random.RandomState(0).randn(2))
+ window_orig = xp.asarray(window, copy=True)
+ signal.resample_poly(impulse, 5, 1, window=window, padtype=padtype)
+ xp_assert_equal(window, window_orig)
+
+ @skip_xp_backends("cupy", reason="padtype not supported by upfirdn")
+ @make_xp_test_case(signal.resample_poly)
+ @pytest.mark.parametrize('padtype', padtype_options)
+ def test_output_float32(self, padtype, xp):
+ # Test that float32 inputs yield a float32 output
+ x = xp.arange(10, dtype=xp.float32)
+ h = xp.asarray([1, 1, 1], dtype=xp.float32)
+ y = signal.resample_poly(x, 1, 2, window=h, padtype=padtype)
+ assert y.dtype == xp.float32
+
+ @pytest.mark.parametrize('padtype', padtype_options)
+ @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+ @skip_xp_backends("cupy", reason="padtype not supported by upfirdn")
+ @make_xp_test_case(signal.resample_poly)
+ def test_output_match_dtype(self, padtype, dtype, xp):
+ # Test that the dtype of x is preserved per issue #14733
+ dtype = getattr(xp, dtype)
+ x = xp.arange(10, dtype=dtype)
+ y = signal.resample_poly(x, 1, 2, padtype=padtype)
+ assert y.dtype == x.dtype
+
+ @skip_xp_backends("cupy", reason="padtype not supported by upfirdn")
+ @pytest.mark.parametrize(
+ "method, ext, padtype",
+ [("fft", False, None)]
+ + list(
+ product(
+ ["polyphase"], [False, True], padtype_options,
+ )
+ ),
+ )
+ @make_xp_test_case(signal.resample, signal.resample_poly)
+ def test_resample_methods(self, method, ext, padtype, xp):
+ # Test resampling of sinusoids and random noise (1-sec)
+ rate = 100
+ rates_to = [49, 50, 51, 99, 100, 101, 199, 200, 201]
+
+ # Sinusoids, windowed to avoid edge artifacts
+ t = xp.arange(rate, dtype=xp.float64) / float(rate)
+ freqs = xp.asarray((1., 10., 40.))[:, xp.newaxis]
+ x = xp.sin(2 * xp.pi * freqs * t) * hann(rate, xp=xp)
+
+ for rate_to in rates_to:
+ t_to = xp.arange(rate_to, dtype=xp.float64) / float(rate_to)
+ y_tos = xp.sin(2 * xp.pi * freqs * t_to) * hann(rate_to, xp=xp)
+ if method == 'fft':
+ y_resamps = signal.resample(x, rate_to, axis=-1)
+ else:
+ if ext and rate_to != rate:
+ # Match default window design
+ g = gcd(rate_to, rate)
+ up = rate_to // g
+ down = rate // g
+ max_rate = max(up, down)
+ f_c = 1. / max_rate
+ half_len = 10 * max_rate
+ window = signal.firwin(2 * half_len + 1, f_c,
+ window=('kaiser', 5.0))
+ window = xp.asarray(window)
+ polyargs = {'window': window, 'padtype': padtype}
+ else:
+ polyargs = {'padtype': padtype}
+
+ y_resamps = signal.resample_poly(x, rate_to, rate, axis=-1,
+ **polyargs)
+
+ for i in range(y_tos.shape[0]):
+ y_to = y_tos[i, :]
+ y_resamp = y_resamps[i, :]
+ freq = float(freqs[i, 0])
+ if freq >= 0.5 * rate_to:
+ #y_to.fill(0.) # mostly low-passed away
+ y_to = xp.zeros_like(y_to) # mostly low-passed away
+ if padtype in ['minimum', 'maximum']:
+ xp_assert_close(y_resamp, y_to, atol=3e-1)
+ else:
+ xp_assert_close(y_resamp, y_to, atol=1e-3)
+ else:
+ assert y_to.shape == y_resamp.shape
+ corr = np.corrcoef(y_to, y_resamp)[0, 1]
+ assert corr > 0.99, (corr, rate, rate_to)
+
+ # Random data
+ rng = np.random.RandomState(0)
+ x = hann(rate) * np.cumsum(rng.randn(rate)) # low-pass, wind
+ x = xp.asarray(x)
+ for rate_to in rates_to:
+ # random data
+ t_to = xp.arange(rate_to, dtype=xp.float64) / float(rate_to)
+ y_to = np.interp(t_to, t, x)
+ if method == 'fft':
+ y_resamp = signal.resample(x, rate_to)
+ else:
+ y_resamp = signal.resample_poly(x, rate_to, rate,
+ padtype=padtype)
+ assert y_to.shape == y_resamp.shape
+ corr = xp.asarray(np.corrcoef(y_to, y_resamp)[0, 1])
+ assert corr > 0.99, corr
+
+ # More tests of fft method (Master 0.18.1 fails these)
+ if method == 'fft':
+ x1 = xp.asarray([1.+0.j, 0.+0.j])
+ y1_test = signal.resample(x1, 4)
+ # upsampling a complex array
+ y1_true = xp.asarray([1.+0.j, 0.5+0.j, 0.+0.j, 0.5+0.j])
+ xp_assert_close(y1_test, y1_true, atol=1e-12)
+ x2 = xp.asarray([1., 0.5, 0., 0.5])
+ y2_test = signal.resample(x2, 2) # downsampling a real array
+ y2_true = xp.asarray([1., 0.])
+ xp_assert_close(y2_test, y2_true, atol=1e-12)
+
+ @pytest.mark.parametrize("n_in", (8, 9))
+ @pytest.mark.parametrize("n_out", (3, 4))
+ @make_xp_test_case(signal.resample)
+ def test_resample_win_func(self, n_in, n_out):
+ """Test callable window function. """
+ x_in = np.ones(n_in)
+
+ def win(freqs):
+ """Scale input by 1/2"""
+ return 0.5 * np.ones_like(freqs)
+
+ y0 = signal.resample(x_in, n_out)
+ y1 = signal.resample(x_in, n_out, window=win)
+
+ xp_assert_close(2*y1, y0, atol=1e-12)
+
+ @pytest.mark.parametrize("n_in", (6, 12))
+ @pytest.mark.parametrize("n_out", (3, 4))
+ @make_xp_test_case(signal.resample)
+ def test__resample_param_t(self, n_in, n_out):
+ """Verify behavior for parameter `t`.
+
+ Note that only `t[0]` and `t[1]` are utilized.
+ """
+ t0, dt = 10, 2
+ x_in = np.ones(n_in)
+
+ y0 = signal.resample(x_in, n_out)
+ y1, t1 = signal.resample(x_in, n_out, t=[t0, t0+dt])
+ t_ref = 10 + np.arange(len(y0)) * dt * n_in / n_out
+
+ xp_assert_equal(y1, y0) # no influence of `t`
+ xp_assert_close(t1, t_ref, atol=1e-12)
+
+ @pytest.mark.parametrize("n1", (2, 3, 7, 8))
+ @pytest.mark.parametrize("n0", (2, 3, 7, 8))
+ @make_xp_test_case(signal.resample)
+ def test_resample_nyquist(self, n0, n1):
+ """Test behavior at Nyquist frequency to ensure issue #14569 is fixed. """
+ f_ny = min(n0, n1) // 2
+ tt = (np.arange(n_) / n_ for n_ in (n0, n1))
+ x0, x1 = (np.cos(2 * np.pi * f_ny * t_) for t_ in tt)
+
+ y1_r = signal.resample(x0, n1)
+ y1_c = signal.resample(x0 + 0j, n1)
+
+ xp_assert_close(y1_r, x1, atol=1e-12)
+ xp_assert_close(y1_c.real, x1, atol=1e-12)
+
+ @pytest.mark.parametrize('down_factor', [2, 11, 79])
+ @pytest.mark.parametrize("dtype", [int, np.float32, np.complex64, float, complex])
+ @make_xp_test_case(signal.resample_poly)
+ def test_poly_vs_filtfilt(self, down_factor, dtype, xp):
+ # Check that up=1.0 gives same answer as filtfilt + slicing
+ random_state = np.random.RandomState(17)
+ size = 10000
+
+ x = random_state.randn(size).astype(dtype)
+ if dtype in (np.complex64, np.complex128):
+ x += 1j * random_state.randn(size)
+
+ # resample_poly assumes zeros outside of signl, whereas filtfilt
+ # can only constant-pad. Make them equivalent:
+ x[0] = 0
+ x[-1] = 0
+
+ h = signal.firwin(31, 1. / down_factor, window='hamming')
+ yf = filtfilt(h, 1.0, x, padtype='constant')[::down_factor]
+
+ # Need to pass convolved version of filter to resample_poly,
+ # since filtfilt does forward and backward, but resample_poly
+ # only goes forward
+ hc = convolve(h, np.flip(h))
+
+ # Use yf.copy() to avoid negative strides, which are unsupported
+ # in torch.
+ x, hc, yf = map(xp.asarray, (x, hc, yf.copy()))
+ y = signal.resample_poly(x, 1, down_factor, window=hc)
+ xp_assert_close(yf, y, atol=3e-7, rtol=6e-7)
+
+ @make_xp_test_case(signal.resample_poly)
+ def test_correlate1d(self, xp):
+ for down in [2, 4]:
+ for nx in range(1, 40, down):
+ for nweights in (32, 33):
+ x = np.random.random((nx,))
+ weights = np.random.random((nweights,))
+ y_g = correlate1d(x, np.flip(weights), mode='constant')
+ x, weights, y_g = map(xp.asarray, (x, weights, y_g))
+ y_s = signal.resample_poly(
+ x, up=1, down=down, window=weights)
+ xp_assert_close(y_g[::down], y_s)
+
+ @make_xp_test_case(signal.resample_poly)
+ @pytest.mark.parametrize('dtype', ['int32', 'float32'])
+ @skip_xp_backends("cupy", reason="padtype not supported by upfirdn")
+ def test_gh_15620(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ data = xp.asarray([0, 1, 2, 3, 2, 1, 0], dtype=dtype)
+ actual = signal.resample_poly(data,
+ up=2,
+ down=1,
+ padtype='smooth')
+ assert np.count_nonzero(actual) > 0
+
+
+@make_xp_test_case(signal.cspline1d_eval)
+class TestCSpline1DEval:
+
+ def test_basic(self, xp):
+ y = np.asarray([1, 2, 3, 4, 3, 2, 1, 2, 3.0])
+ x = np.arange(y.shape[0])
+ dx = x[1] - x[0]
+ cj = xp.asarray(signal.cspline1d(y))
+ x2 = xp.arange(len(y) * 10.0) / 10.0
+ y2 = signal.cspline1d_eval(cj, x2, dx=dx, x0=x[0])
+
+ # make sure interpolated values are on knot points
+ assert_array_almost_equal(y2[::10], xp.asarray(y), decimal=5)
+
+ def test_complex(self, xp):
+ # create some smoothly varying complex signal to interpolate
+ x = np.arange(2.0)
+ y = np.zeros(x.shape, dtype=np.complex64)
+ T = 10.0
+ f = 1.0 / T
+ y = np.exp(2.0J * np.pi * f * x)
+
+ # get the cspline transform
+ cy = xp.asarray(signal.cspline1d(y))
+
+ # determine new test x value and interpolate
+ xnew = xp.asarray([0.5])
+ ynew = signal.cspline1d_eval(cy, xnew)
+
+ assert ynew.dtype == xp.asarray(y).dtype
+
+
+@make_xp_test_case(signal.order_filter)
+class TestOrderFilt:
+
+ def test_basic(self, xp):
+ actual = signal.order_filter(xp.asarray([1, 2, 3]), xp.asarray([1, 0, 1]), 1)
+ expect = xp.asarray([2, 3, 2])
+ xp_assert_equal(actual, expect)
+
+ def test_doc_example(self, xp):
+ x = xp.reshape(xp.arange(25, dtype=xp_default_dtype(xp)), (5, 5))
+ domain = xp.eye(3, dtype=xp_default_dtype(xp))
+
+ # minimum of elements 1,3,9 (zero-padded) on phone pad
+ # 7,5,3 on numpad
+ expected = xp.asarray(
+ [[0., 0., 0., 0., 0.],
+ [0., 0., 1., 2., 0.],
+ [0., 5., 6., 7., 0.],
+ [0., 10., 11., 12., 0.],
+ [0., 0., 0., 0., 0.]],
+ dtype=xp_default_dtype(xp)
+ )
+ xp_assert_close(signal.order_filter(x, domain, 0), expected)
+
+ # maximum of elements 1,3,9 (zero-padded) on phone pad
+ # 7,5,3 on numpad
+ expected = xp.asarray(
+ [[6., 7., 8., 9., 4.],
+ [11., 12., 13., 14., 9.],
+ [16., 17., 18., 19., 14.],
+ [21., 22., 23., 24., 19.],
+ [20., 21., 22., 23., 24.]],
+ )
+ xp_assert_close(signal.order_filter(x, domain, 2), expected)
+
+ # and, just to complete the set, median of zero-padded elements
+ expected = xp.asarray(
+ [[0, 1, 2, 3, 0],
+ [5, 6, 7, 8, 3],
+ [10, 11, 12, 13, 8],
+ [15, 16, 17, 18, 13],
+ [0, 15, 16, 17, 18]],
+ dtype=xp_default_dtype(xp)
+ )
+ xp_assert_close(signal.order_filter(x, domain, 1), expected)
+
+ @xfail_xp_backends('dask.array', reason='repeat requires an axis')
+ @xfail_xp_backends('torch', reason='array-api-compat#292')
+ @make_xp_test_case(signal.medfilt)
+ def test_medfilt_order_filter(self, xp):
+ x = xp.reshape(xp.arange(25), (5, 5))
+
+ # median of zero-padded elements 1,5,9 on phone pad
+ # 7,5,3 on numpad
+ expected = xp.asarray(
+ [[0, 1, 2, 3, 0],
+ [1, 6, 7, 8, 4],
+ [6, 11, 12, 13, 9],
+ [11, 16, 17, 18, 14],
+ [0, 16, 17, 18, 0]],
+ )
+ xp_assert_close(signal.medfilt(x, 3), expected)
+
+ xp_assert_close(
+ signal.order_filter(x, xp.ones((3, 3)), 4),
+ expected
+ )
+
+ def test_order_filter_asymmetric(self, xp):
+ x = xp.reshape(xp.arange(25), (5, 5))
+ domain = xp.asarray(
+ [[1, 1, 0],
+ [0, 1, 0],
+ [0, 0, 0]],
+ )
+
+ expected = xp.asarray(
+ [[0, 0, 0, 0, 0],
+ [0, 0, 1, 2, 3],
+ [0, 5, 6, 7, 8],
+ [0, 10, 11, 12, 13],
+ [0, 15, 16, 17, 18]]
+ )
+ xp_assert_close(signal.order_filter(x, domain, 0), expected)
+
+ expected = xp.asarray(
+ [[0, 0, 0, 0, 0],
+ [0, 1, 2, 3, 4],
+ [5, 6, 7, 8, 9],
+ [10, 11, 12, 13, 14],
+ [15, 16, 17, 18, 19]]
+ )
+ xp_assert_close(signal.order_filter(x, domain, 1), expected)
+
+
+@make_xp_test_case(lfilter)
+class _TestLinearFilter:
+ def generate(self, shape, xp):
+ prodshape = shape if isinstance(shape, int) else math.prod(shape)
+ x = xp.linspace(0, prodshape - 1, prodshape)
+ if not isinstance(shape, int):
+ x = xp.reshape(x, shape)
+ return self.convert_dtype(x, xp)
+
+ def convert_dtype(self, arr, xp):
+ if self.dtype == np.dtype('O'):
+ arr = np.asarray(arr)
+ out = np.empty(arr.shape, self.dtype)
+ iter = np.nditer([arr, out], ['refs_ok','zerosize_ok'],
+ [['readonly'],['writeonly']])
+ for x, y in iter:
+ y[...] = self.type(x[()])
+ return out
+ else:
+ dtype = (getattr(xp, self.dtype)
+ if isinstance(self.dtype, str)
+ else self.dtype)
+ return xp.asarray(arr, dtype=dtype)
+
+ @skip_xp_backends('cupy', reason='XXX https://github.com/scipy/scipy/issues/23539')
+ def test_invalid_params(self, xp):
+ """Verify all exceptions are raised. """
+ b, a, x = xp.asarray([1]), xp.asarray([2]), xp.asarray([3, 4])
+ with pytest.raises(ValueError, match="^Parameter b is not"):
+ lfilter(xp.eye(2), a, x) # b not one-dimensional
+ with pytest.raises(ValueError, match="^Parameter b is not"):
+ lfilter(xp.asarray([]), a, x) # b empty
+ with pytest.raises(ValueError, match="^Parameter a is not"):
+ lfilter(b, xp.eye(2), x) # a not one-dimensional
+ with pytest.raises(ValueError, match="^Parameter a is not"):
+ lfilter(b, xp.asarray([]), x) # a empty
+ with pytest.raises(NotImplementedError, match="^Parameter's dtypes produced "):
+ b, a, x = (xp.astype(v_, xp.uint64, copy=False) for v_ in (b, a, x))
+ lfilter(b, a, x) # fails with uint64 dtype
+
+ def test_rank_1_IIR(self, xp):
+ x = self.generate((6,), xp)
+ b = self.convert_dtype([1, -1], xp)
+ a = self.convert_dtype([0.5, -0.5], xp)
+ y_r = self.convert_dtype([0, 2, 4, 6, 8, 10.], xp)
+ assert_array_almost_equal(lfilter(b, a, x), y_r)
+
+ def test_rank_1_FIR(self, xp):
+ x = self.generate((6,), xp)
+ b = self.convert_dtype([1, 1], xp)
+ a = self.convert_dtype([1], xp)
+ y_r = self.convert_dtype([0, 1, 3, 5, 7, 9.], xp)
+ assert_array_almost_equal(lfilter(b, a, x), y_r)
+
+ @skip_xp_backends('cupy', reason='XXX https://github.com/cupy/cupy/pull/8677')
+ def test_rank_1_IIR_init_cond(self, xp):
+ x = self.generate((6,), xp)
+ b = self.convert_dtype([1, 0, -1], xp)
+ a = self.convert_dtype([0.5, -0.5], xp)
+ zi = self.convert_dtype([1, 2], xp)
+ y_r = self.convert_dtype([1, 5, 9, 13, 17, 21], xp)
+ zf_r = self.convert_dtype([13, -10], xp)
+ y, zf = lfilter(b, a, x, zi=zi)
+ assert_array_almost_equal(y, y_r)
+ assert_array_almost_equal(zf, zf_r)
+
+ @skip_xp_backends('cupy', reason='XXX https://github.com/cupy/cupy/pull/8677')
+ def test_rank_1_FIR_init_cond(self, xp):
+ x = self.generate((6,), xp)
+ b = self.convert_dtype([1, 1, 1], xp)
+ a = self.convert_dtype([1], xp)
+ zi = self.convert_dtype([1, 1], xp)
+ y_r = self.convert_dtype([1, 2, 3, 6, 9, 12.], xp)
+ zf_r = self.convert_dtype([9, 5], xp)
+ y, zf = lfilter(b, a, x, zi=zi)
+ assert_array_almost_equal(y, y_r)
+ assert_array_almost_equal(zf, zf_r)
+
+ def test_rank_2_IIR_axis_0(self, xp):
+ x = self.generate((4, 3), xp)
+ b = self.convert_dtype([1, -1], xp)
+ a = self.convert_dtype([0.5, 0.5], xp)
+ y_r2_a0 = self.convert_dtype([[0, 2, 4], [6, 4, 2], [0, 2, 4],
+ [6, 4, 2]], xp)
+ y = lfilter(b, a, x, axis=0)
+ assert_array_almost_equal(y_r2_a0, y)
+
+ def test_rank_2_IIR_axis_1(self, xp):
+ x = self.generate((4, 3), xp)
+ b = self.convert_dtype([1, -1], xp)
+ a = self.convert_dtype([0.5, 0.5], xp)
+ y_r2_a1 = self.convert_dtype([[0, 2, 0], [6, -4, 6], [12, -10, 12],
+ [18, -16, 18]], xp)
+ y = lfilter(b, a, x, axis=1)
+ assert_array_almost_equal(y_r2_a1, y)
+
+ @skip_xp_backends('cupy', reason='XXX https://github.com/cupy/cupy/pull/8677')
+ def test_rank_2_IIR_axis_0_init_cond(self, xp):
+ x = self.generate((4, 3), xp)
+ b = self.convert_dtype([1, -1], xp)
+ a = self.convert_dtype([0.5, 0.5], xp)
+ zi = self.convert_dtype(np.ones((4,1)), xp)
+
+ y_r2_a0_1 = self.convert_dtype([[1, 1, 1], [7, -5, 7], [13, -11, 13],
+ [19, -17, 19]], xp)
+ zf_r = self.convert_dtype([-5, -17, -29, -41], xp)[:, np.newaxis]
+ y, zf = lfilter(b, a, x, axis=1, zi=zi)
+ assert_array_almost_equal(y_r2_a0_1, y)
+ assert_array_almost_equal(zf, zf_r)
+
+ @skip_xp_backends('cupy', reason='XXX https://github.com/cupy/cupy/pull/8677')
+ def test_rank_2_IIR_axis_1_init_cond(self, xp):
+ x = self.generate((4, 3), xp)
+ b = self.convert_dtype([1, -1], xp)
+ a = self.convert_dtype([0.5, 0.5], xp)
+ zi = self.convert_dtype(np.ones((1, 3)), xp)
+
+ y_r2_a0_0 = self.convert_dtype([[1, 3, 5], [5, 3, 1],
+ [1, 3, 5], [5, 3, 1]], xp)
+ zf_r = self.convert_dtype([[-23, -23, -23]], xp)
+ y, zf = lfilter(b, a, x, axis=0, zi=zi)
+ assert_array_almost_equal(y_r2_a0_0, y)
+ assert_array_almost_equal(zf, zf_r)
+
+ def test_rank_3_IIR(self, xp):
+ x = self.generate((4, 3, 2), xp)
+ b = self.convert_dtype([1, -1], xp)
+ a = self.convert_dtype([0.5, 0.5], xp)
+ a_np, b_np, x_np = map(_xp_copy_to_numpy, (a, b, x))
+ for axis in range(x.ndim):
+ y = lfilter(b, a, x, axis)
+ y_r = np.apply_along_axis(lambda w: lfilter(b_np, a_np, w), axis, x_np)
+ assert_array_almost_equal(y, xp.asarray(y_r))
+
+ @xfail_xp_backends("cupy", reason="inaccurate")
+ def test_rank_3_IIR_init_cond(self, xp):
+ x = self.generate((4, 3, 2), xp)
+ b = self.convert_dtype([1, -1], xp)
+ a = self.convert_dtype([0.5, 0.5], xp)
+
+ for axis in range(x.ndim):
+ zi_shape = list(x.shape)
+ zi_shape[axis] = 1
+ zi = self.convert_dtype(xp.ones(zi_shape), xp)
+ zi1 = self.convert_dtype([1], xp)
+ y, zf = lfilter(b, a, x, axis, zi)
+ b_np, a_np, zi1_np = map(_xp_copy_to_numpy, (b, a, zi1))
+ def lf0(w):
+ return lfilter(b_np, a_np, w, zi=zi1_np)[0]
+ def lf1(w):
+ return lfilter(b_np, a_np, w, zi=zi1_np)[1]
+ y_r = np.apply_along_axis(lf0, axis, _xp_copy_to_numpy(x))
+ zf_r = np.apply_along_axis(lf1, axis, _xp_copy_to_numpy(x))
+ assert_array_almost_equal(y, xp.asarray(y_r))
+ assert_array_almost_equal(zf, xp.asarray(zf_r))
+
+ def test_rank_3_FIR(self, xp):
+ x = self.generate((4, 3, 2), xp)
+ b = self.convert_dtype([1, 0, -1], xp)
+ a = self.convert_dtype([1], xp)
+
+ a_np, b_np, x_np = map(_xp_copy_to_numpy, (a, b, x))
+ for axis in range(x.ndim):
+ y = lfilter(b, a, x, axis)
+ y_r = np.apply_along_axis(lambda w: lfilter(b_np, a_np, w), axis, x_np)
+ assert_array_almost_equal(y, xp.asarray(y_r))
+
+ @xfail_xp_backends("cupy", reason="inaccurate")
+ def test_rank_3_FIR_init_cond(self, xp):
+ x = self.generate((4, 3, 2), xp)
+ b = self.convert_dtype([1, 0, -1], xp)
+ a = self.convert_dtype([1], xp)
+
+ x_np, b_np, a_np = map(_xp_copy_to_numpy, (x, b, a))
+ for axis in range(x.ndim):
+ zi_shape = list(x.shape)
+ zi_shape[axis] = 2
+ zi = self.convert_dtype(xp.ones(zi_shape), xp)
+ zi1 = self.convert_dtype([1, 1], xp)
+ zi1_np = _xp_copy_to_numpy(zi1)
+ y, zf = lfilter(b, a, x, axis, zi)
+ b_np, a_np, zi1_np = map(_xp_copy_to_numpy, (b, a, zi1))
+ def lf0(w):
+ return lfilter(b_np, a_np, w, zi=zi1_np)[0]
+ def lf1(w):
+ return lfilter(b_np, a_np, w, zi=zi1_np)[1]
+ y_r = np.apply_along_axis(lf0, axis, x_np)
+ zf_r = np.apply_along_axis(lf1, axis, x_np)
+ assert_array_almost_equal(y, xp.asarray(y_r))
+ assert_array_almost_equal(zf, xp.asarray(zf_r))
+
+ @skip_xp_backends('cupy', reason='XXX https://github.com/cupy/cupy/pull/8677')
+ def test_zi_pseudobroadcast(self, xp):
+ x = self.generate((4, 5, 20), xp)
+ b, a = signal.butter(8, 0.2, output='ba')
+ b = self.convert_dtype(b, xp)
+ a = self.convert_dtype(a, xp)
+ zi_size = b.shape[0] - 1
+
+ # lfilter requires x.ndim == zi.ndim exactly. However, zi can have
+ # length 1 dimensions.
+ zi_full = self.convert_dtype(xp.ones((4, 5, zi_size)), xp)
+ zi_sing = self.convert_dtype(xp.ones((1, 1, zi_size)), xp)
+
+ y_full, zf_full = lfilter(b, a, x, zi=zi_full)
+ y_sing, zf_sing = lfilter(b, a, x, zi=zi_sing)
+
+ assert_array_almost_equal(y_sing, y_full)
+ assert_array_almost_equal(zf_full, zf_sing)
+
+ # lfilter does not prepend ones
+ assert_raises(ValueError, lfilter, b, a, x, -1, xp.ones(zi_size))
+
+ @skip_xp_backends('cupy', reason='XXX https://github.com/cupy/cupy/pull/8677')
+ def test_scalar_a(self, xp):
+ # a can be a scalar.
+ x = self.generate(6, xp)
+ b = self.convert_dtype([1, 0, -1], xp)
+ a = self.convert_dtype([1], xp)
+ y_r = self.convert_dtype([0, 1, 2, 2, 2, 2], xp)
+
+ y = lfilter(b, a[0], x)
+ assert_array_almost_equal(y, y_r)
+
+ @skip_xp_backends('cupy', reason='XXX https://github.com/cupy/cupy/pull/8677')
+ def test_zi_some_singleton_dims(self, xp):
+ # lfilter doesn't really broadcast (no prepending of 1's). But does
+ # do singleton expansion if x and zi have the same ndim. This was
+ # broken only if a subset of the axes were singletons (gh-4681).
+ x = self.convert_dtype(xp.zeros((3, 2, 5), dtype=xp.int64), xp)
+ b = self.convert_dtype(xp.ones(5, dtype=xp.int64), xp)
+ a = self.convert_dtype(xp.asarray([1, 0, 0]), xp)
+ zi = np.ones((3, 1, 4), dtype=np.int64)
+ zi[1, :, :] *= 2
+ zi[2, :, :] *= 3
+ zi = xp.asarray(zi)
+ zi = self.convert_dtype(zi, xp)
+
+ zf_expected = self.convert_dtype(xp.zeros((3, 2, 4), dtype=xp.int64), xp)
+ y_expected = np.zeros((3, 2, 5), dtype=np.int64)
+ y_expected[:, :, :4] = [[[1]], [[2]], [[3]]]
+ y_expected = xp.asarray(y_expected)
+ y_expected = self.convert_dtype(y_expected, xp)
+
+ # IIR
+ y_iir, zf_iir = lfilter(b, a, x, -1, zi)
+ assert_array_almost_equal(y_iir, y_expected)
+ assert_array_almost_equal(zf_iir, zf_expected)
+
+ # FIR
+ y_fir, zf_fir = lfilter(b, a[0], x, -1, zi)
+ assert_array_almost_equal(y_fir, y_expected)
+ assert_array_almost_equal(zf_fir, zf_expected)
+
+ def base_bad_size_zi(self, b, a, x, axis, zi, xp):
+ b = self.convert_dtype(b, xp)
+ a = self.convert_dtype(a, xp)
+ x = self.convert_dtype(x, xp)
+ zi = self.convert_dtype(zi, xp)
+ assert_raises(ValueError, lfilter, b, a, x, axis, zi)
+
+ @skip_xp_backends('cupy', reason='cupy does not raise')
+ def test_bad_size_zi(self, xp):
+ # rank 1
+ x1 = xp.arange(6)
+ self.base_bad_size_zi([1], [1], x1, -1, [1], xp)
+ self.base_bad_size_zi([1, 1], [1], x1, -1, [0, 1], xp)
+ self.base_bad_size_zi([1, 1], [1], x1, -1, [[0]], xp)
+ self.base_bad_size_zi([1, 1], [1], x1, -1, [0, 1, 2], xp)
+ self.base_bad_size_zi([1, 1, 1], [1], x1, -1, [[0]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1], x1, -1, [0, 1, 2], xp)
+ self.base_bad_size_zi([1], [1, 1], x1, -1, [0, 1], xp)
+ self.base_bad_size_zi([1], [1, 1], x1, -1, [[0]], xp)
+ self.base_bad_size_zi([1], [1, 1], x1, -1, [0, 1, 2], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [[0], [1]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0, 1, 2], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x1, -1, [0, 1, 2, 3], xp)
+ self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0], xp)
+ self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [[0], [1]], xp)
+ self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0, 1, 2], xp)
+ self.base_bad_size_zi([1, 1], [1, 1, 1], x1, -1, [0, 1, 2, 3], xp)
+
+ # rank 2
+ x2 = np.arange(12).reshape((4,3))
+ x2 = xp.asarray(x2)
+ # for axis=0 zi.shape should == (max(len(a),len(b))-1, 3)
+ self.base_bad_size_zi([1], [1], x2, 0, [0], xp)
+
+ # for each of these there are 5 cases tested (in this order):
+ # 1. not deep enough, right # elements
+ # 2. too deep, right # elements
+ # 3. right depth, right # elements, transposed
+ # 4. right depth, too few elements
+ # 5. right depth, too many elements
+
+ self.base_bad_size_zi([1, 1], [1], x2, 0, [0, 1, 2], xp)
+ self.base_bad_size_zi([1, 1], [1], x2, 0, [[[0, 1, 2]]], xp)
+ self.base_bad_size_zi([1, 1], [1], x2, 0, [[0], [1], [2]], xp)
+ self.base_bad_size_zi([1, 1], [1], x2, 0, [[0, 1]], xp)
+ self.base_bad_size_zi([1, 1], [1], x2, 0, [[0, 1, 2, 3]], xp)
+
+ self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [0, 1, 2, 3, 4, 5], xp)
+ self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[[0, 1, 2], [3, 4, 5]]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0, 1], [2, 3], [4, 5]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0, 1], [2, 3]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1], x2, 0, [[0, 1, 2, 3], [4, 5, 6, 7]], xp)
+
+ self.base_bad_size_zi([1], [1, 1], x2, 0, [0, 1, 2], xp)
+ self.base_bad_size_zi([1], [1, 1], x2, 0, [[[0, 1, 2]]], xp)
+ self.base_bad_size_zi([1], [1, 1], x2, 0, [[0], [1], [2]], xp)
+ self.base_bad_size_zi([1], [1, 1], x2, 0, [[0, 1]], xp)
+ self.base_bad_size_zi([1], [1, 1], x2, 0, [[0, 1, 2, 3]], xp)
+
+ self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [0, 1, 2, 3, 4, 5], xp)
+ self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[[0, 1, 2], [3, 4, 5]]], xp)
+ self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0, 1], [2, 3], [4, 5]], xp)
+ self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0, 1], [2, 3]], xp)
+ self.base_bad_size_zi([1], [1, 1, 1], x2, 0, [[0, 1, 2, 3], [4, 5, 6, 7]], xp)
+
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [0, 1, 2, 3, 4, 5], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[[0, 1, 2], [3, 4, 5]]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[0, 1], [2, 3], [4, 5]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0, [[0, 1], [2, 3]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 0,
+ [[0, 1, 2, 3], [4, 5, 6, 7]], xp)
+
+ # for axis=1 zi.shape should == (4, max(len(a),len(b))-1)
+ self.base_bad_size_zi([1], [1], x2, 1, [0], xp)
+
+ self.base_bad_size_zi([1, 1], [1], x2, 1, [0, 1, 2, 3], xp)
+ self.base_bad_size_zi([1, 1], [1], x2, 1, [[[0], [1], [2], [3]]], xp)
+ self.base_bad_size_zi([1, 1], [1], x2, 1, [[0, 1, 2, 3]], xp)
+ self.base_bad_size_zi([1, 1], [1], x2, 1, [[0], [1], [2]], xp)
+ self.base_bad_size_zi([1, 1], [1], x2, 1, [[0], [1], [2], [3], [4]], xp)
+
+ self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [0, 1, 2, 3, 4, 5, 6, 7], xp)
+ self.base_bad_size_zi([1, 1, 1], [1], x2, 1,
+ [[[0, 1], [2, 3], [4, 5], [6, 7]]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[0, 1, 2, 3], [4, 5, 6, 7]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1], x2, 1, [[0, 1], [2, 3], [4, 5]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1], x2, 1,
+ [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]], xp)
+
+ self.base_bad_size_zi([1], [1, 1], x2, 1, [0, 1, 2, 3], xp)
+ self.base_bad_size_zi([1], [1, 1], x2, 1, [[[0], [1], [2], [3]]], xp)
+ self.base_bad_size_zi([1], [1, 1], x2, 1, [[0, 1, 2, 3]], xp)
+ self.base_bad_size_zi([1], [1, 1], x2, 1, [[0], [1], [2]], xp)
+ self.base_bad_size_zi([1], [1, 1], x2, 1, [[0], [1], [2], [3], [4]], xp)
+
+ self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [0, 1, 2, 3, 4, 5, 6, 7], xp)
+ self.base_bad_size_zi([1], [1, 1, 1], x2, 1,
+ [[[0, 1], [2, 3], [4, 5], [6, 7]]], xp)
+ self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0, 1, 2, 3], [4, 5, 6, 7]], xp)
+ self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0, 1], [2, 3], [4, 5]], xp)
+ self.base_bad_size_zi([1], [1, 1, 1], x2, 1, [[0, 1],
+ [2, 3], [4, 5], [6, 7], [8, 9]], xp)
+
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [0, 1, 2, 3, 4, 5, 6, 7], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1,
+ [[[0, 1], [2, 3], [4, 5], [6, 7]]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1,
+ [[0, 1, 2, 3], [4, 5, 6, 7]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1, [[0, 1], [2, 3], [4, 5]], xp)
+ self.base_bad_size_zi([1, 1, 1], [1, 1], x2, 1,
+ [[0, 1], [2, 3], [4, 5], [6, 7], [8, 9]], xp)
+
+ def test_empty_zi(self, xp):
+ # Regression test for #880: empty array for zi crashes.
+ x = self.generate((5,), xp)
+ a = self.convert_dtype([1], xp)
+ b = self.convert_dtype([1], xp)
+ zi = self.convert_dtype([], xp)
+ y, zf = lfilter(b, a, x, zi=zi)
+ assert_array_almost_equal(y, x)
+ assert zf.dtype == (getattr(xp, self.dtype)
+ if isinstance(self.dtype, str)
+ else self.dtype)
+ assert xp_size(zf) == 0
+
+ @skip_xp_backends('jax.numpy', reason='jax does not support inplace ops')
+ @pytest.mark.parametrize('a', (1, [1], [1, .5, 1.5], 2, [2], [2, 1, 3]),
+ ids=str)
+ @make_xp_test_case(lfiltic)
+ def test_lfiltic(self, a, xp):
+ # Test for #22470: lfiltic does not handle `a[0] != 1`
+ # and, more in general, test that lfiltic behaves consistently with lfilter
+ if is_cupy(xp) and isinstance(a, int | float):
+ pytest.skip('cupy does not supoprt scalar filter coefficients')
+ x = self.generate(6, xp) # arbitrary input
+ b = self.convert_dtype([.5, 1., .2], xp) # arbitrary b
+ a = self.convert_dtype(a, xp)
+ N = xp_size(a) - 1
+ M = xp_size(b) - 1
+ K = M + N if is_cupy(xp) else max(N, M)
+ # compute reference initial conditions as final conditions of lfilter
+ y1, zi_1 = lfilter(b, a, x, zi=self.generate(K, xp))
+ # copute initial conditions from lfiltic
+ zi_2 = lfiltic(b, a, xp.flip(y1), xp.flip(x))
+ # compare lfiltic's output with reference
+ assert_array_almost_equal(zi_1, zi_2)
+
+ @make_xp_test_case(lfiltic)
+ def test_lfiltic_bad_coeffs(xp):
+ # Test for invalid filter coefficients (wrong shape or zero `a[0]`)
+ assert_raises(ValueError, lfiltic, [1, 2], [], [0, 0], [0, 1])
+ assert_raises(ValueError, lfiltic, [1, 2], [0, 2], [0, 0], [0, 1])
+ assert_raises(ValueError, lfiltic, [1, 2], [[1], [2]], [0, 0], [0, 1])
+ assert_raises(ValueError, lfiltic, [[1], [2]], [1], [0, 0], [0, 1])
+
+ @skip_xp_backends(
+ 'array_api_strict', reason='int64 and float64 cannot be promoted together'
+ )
+ @skip_xp_backends('jax.numpy', reason='jax dtype defaults differ')
+ @make_xp_test_case(lfiltic)
+ def test_lfiltic_bad_zi(self, xp):
+ # Regression test for #3699: bad initial conditions
+ a = self.convert_dtype([1], xp)
+ b = self.convert_dtype([1], xp)
+ # "y" sets the datatype of zi, so it truncates if int
+ zi = lfiltic(b, a, xp.asarray([1., 0]))
+ zi_1 = lfiltic(b, a, xp.asarray([1.0, 0]))
+ zi_2 = lfiltic(b, a, xp.asarray([True, False]))
+ xp_assert_equal(zi, zi_1)
+
+ check_dtype_arg = {} if self.dtype == object else {'check_dtype': False}
+ xp_assert_equal(zi, zi_2, **check_dtype_arg)
+
+ @skip_xp_backends('cupy', reason='XXX https://github.com/cupy/cupy/pull/8677')
+ def test_short_x_FIR(self, xp):
+ # regression test for #5116
+ # x shorter than b, with non None zi fails
+ a = self.convert_dtype([1], xp)
+ b = self.convert_dtype([1, 0, -1], xp)
+ zi = self.convert_dtype([2, 7], xp)
+ x = self.convert_dtype([72], xp)
+ ye = self.convert_dtype([74], xp)
+ zfe = self.convert_dtype([7, -72], xp)
+ y, zf = lfilter(b, a, x, zi=zi)
+ assert_array_almost_equal(y, ye)
+ assert_array_almost_equal(zf, zfe)
+
+ @skip_xp_backends('cupy', reason='XXX https://github.com/cupy/cupy/pull/8677')
+ def test_short_x_IIR(self, xp):
+ # regression test for #5116
+ # x shorter than b, with non None zi fails
+ a = self.convert_dtype([1, 1], xp)
+ b = self.convert_dtype([1, 0, -1], xp)
+ zi = self.convert_dtype([2, 7], xp)
+ x = self.convert_dtype([72], xp)
+ ye = self.convert_dtype([74], xp)
+ zfe = self.convert_dtype([-67, -72], xp)
+ y, zf = lfilter(b, a, x, zi=zi)
+ assert_array_almost_equal(y, ye)
+ assert_array_almost_equal(zf, zfe)
+
+ def test_do_not_modify_a_b_IIR(self, xp):
+ x = self.generate((6,), xp)
+ b = self.convert_dtype([1, -1], xp)
+ b0 = xp_copy(b, xp=xp)
+ a = self.convert_dtype([0.5, -0.5], xp)
+ a0 = xp_copy(a, xp=xp)
+ y_r = self.convert_dtype([0, 2, 4, 6, 8, 10.], xp)
+ y_f = lfilter(b, a, x)
+ assert_array_almost_equal(y_f, y_r)
+ xp_assert_equal(b, b0)
+ xp_assert_equal(a, a0)
+
+ def test_do_not_modify_a_b_FIR(self, xp):
+ x = self.generate((6,), xp)
+ b = self.convert_dtype([1, 0, 1], xp)
+ b0 = xp_copy(b, xp=xp)
+ a = self.convert_dtype([2], xp)
+ a0 = xp_copy(a, xp=xp)
+ y_r = self.convert_dtype([0, 0.5, 1, 2, 3, 4.], xp)
+ y_f = lfilter(b, a, x)
+ assert_array_almost_equal(y_f, y_r)
+ xp_assert_equal(b, b0)
+ xp_assert_equal(a, a0)
+
+ @skip_xp_backends(np_only=True)
+ @pytest.mark.parametrize("a", [1.0, [1.0], np.array(1.0)])
+ @pytest.mark.parametrize("b", [1.0, [1.0], np.array(1.0)])
+ def test_scalar_input(self, a, b, xp):
+ data = np.random.randn(10)
+ data = xp.asarray(data)
+ xp_assert_close(
+ lfilter(xp.asarray([1.0]), xp.asarray([1.0]), data),
+ lfilter(b, a, data)
+ )
+
+
+class TestLinearFilterFloat32(_TestLinearFilter):
+ dtype = 'float32'
+
+
+class TestLinearFilterFloat64(_TestLinearFilter):
+ dtype = 'float64'
+
+
+@skip_xp_backends(np_only=True)
+class TestLinearFilterFloatExtended(_TestLinearFilter):
+ dtype = np.dtype('g')
+
+
+class TestLinearFilterComplex64(_TestLinearFilter):
+ dtype = 'complex64'
+
+
+class TestLinearFilterComplex128(_TestLinearFilter):
+ dtype = 'complex128'
+
+
+@skip_xp_backends(np_only=True)
+class TestLinearFilterComplexExtended(_TestLinearFilter):
+ dtype = np.dtype('G')
+
+
+@make_xp_test_case(lfilter)
+def test_lfilter_bad_object(xp):
+ # lfilter: object arrays with non-numeric objects raise TypeError.
+ # Regression test for ticket #1452.
+ if hasattr(sys, 'abiflags') and 'd' in sys.abiflags:
+ pytest.skip('test is flaky when run with python3-dbg')
+ assert_raises(TypeError, lfilter, [1.0], [1.0], [1.0, None, 2.0])
+ assert_raises(TypeError, lfilter, [1.0], [None], [1.0, 2.0, 3.0])
+ assert_raises(TypeError, lfilter, [None], [1.0], [1.0, 2.0, 3.0])
+
+
+@make_xp_test_case(lfilter)
+def test_lfilter_notimplemented_input(xp):
+ # Should not crash, gh-7991
+ assert_raises(NotImplementedError, lfilter, [2,3], [4,5], [1,2,3,4,5])
+
+
+@pytest.mark.parametrize('dt', ["uint8", "int8", "uint16", "int16",
+ "uint32", "int32",
+ "uint64", "int64",
+ "float32", "float64",
+ ])
+
+@xfail_xp_backends("jax.numpy", reason="fails all around")
+@make_xp_test_case(correlate)
+class TestCorrelateReal:
+ def _setup_rank1(self, dt, xp):
+ a = xp.linspace(0, 3, 4, dtype=dt)
+ b = xp.linspace(1, 2, 2, dtype=dt)
+
+ y_r = xp.asarray([0, 2, 5, 8, 3], dtype=dt)
+ return a, b, y_r
+
+ def equal_tolerance(self, res_dt):
+ # default value of keyword
+ decimal = 6
+ try:
+ dt_info = np.finfo(res_dt)
+ if hasattr(dt_info, 'resolution'):
+ decimal = int(-0.5*np.log10(dt_info.resolution))
+ except Exception:
+ pass
+ return decimal
+
+ def equal_tolerance_fft(self, res_dt):
+ # FFT implementations convert longdouble arguments down to
+ # double so don't expect better precision, see gh-9520
+ if res_dt == np.longdouble:
+ return self.equal_tolerance(np.float64)
+ else:
+ return self.equal_tolerance(res_dt)
+
+ @skip_xp_backends(np_only=True, reason="order='F'")
+ def test_method(self, dt, xp):
+ dt = getattr(xp, dt)
+
+ a, b, y_r = self._setup_rank3(dt, xp)
+ y_fft = correlate(a, b, method='fft')
+ y_direct = correlate(a, b, method='direct')
+
+ assert_array_almost_equal(y_r, y_fft,
+ decimal=self.equal_tolerance_fft(y_fft.dtype),)
+ assert_array_almost_equal(y_r, y_direct,
+ decimal=self.equal_tolerance(y_direct.dtype),)
+ assert y_fft.dtype == dt
+ assert y_direct.dtype == dt
+
+ def test_rank1_valid(self, dt, xp):
+ if is_torch(xp) and dt in ["uint16", "uint32", "uint64"]:
+ pytest.skip("torch does not support unsigned ints")
+
+ dt = getattr(xp, dt) if isinstance(dt, str) else dt
+ a, b, y_r = self._setup_rank1(dt, xp)
+ y = correlate(a, b, 'valid')
+ assert_array_almost_equal(y, y_r[1:4])
+ assert y.dtype == dt
+
+ # See gh-5897
+ y = correlate(b, a, 'valid')
+ assert_array_almost_equal(y, xp.flip(y_r[1:4]))
+ assert y.dtype == dt
+
+ def test_rank1_same(self, dt, xp):
+ if is_torch(xp) and dt in ["uint16", "uint32", "uint64"]:
+ pytest.skip("torch does not support unsigned ints")
+
+ dt = getattr(xp, dt) if isinstance(dt, str) else dt
+
+ a, b, y_r = self._setup_rank1(dt, xp)
+ y = correlate(a, b, 'same')
+ assert_array_almost_equal(y, y_r[:-1])
+ assert y.dtype == dt
+
+ def test_rank1_full(self, dt, xp):
+ if is_torch(xp) and dt in ["uint16", "uint32", "uint64"]:
+ pytest.skip("torch does not support unsigned ints")
+
+ dt = getattr(xp, dt) if isinstance(dt, str) else dt
+
+ a, b, y_r = self._setup_rank1(dt, xp)
+ y = correlate(a, b, 'full')
+ assert_array_almost_equal(y, y_r)
+ assert y.dtype == dt
+
+ def _setup_rank3(self, dt, xp):
+ a = np.linspace(0, 39, 40).reshape((2, 4, 5), order='F').astype(
+ dt)
+ b = np.linspace(0, 23, 24).reshape((2, 3, 4), order='F').astype(
+ dt)
+
+ y_r = np.array([[[0., 184., 504., 912., 1360., 888., 472., 160.],
+ [46., 432., 1062., 1840., 2672., 1698., 864., 266.],
+ [134., 736., 1662., 2768., 3920., 2418., 1168., 314.],
+ [260., 952., 1932., 3056., 4208., 2580., 1240., 332.],
+ [202., 664., 1290., 1984., 2688., 1590., 712., 150.],
+ [114., 344., 642., 960., 1280., 726., 296., 38.]],
+
+ [[23., 400., 1035., 1832., 2696., 1737., 904., 293.],
+ [134., 920., 2166., 3680., 5280., 3306., 1640., 474.],
+ [325., 1544., 3369., 5512., 7720., 4683., 2192., 535.],
+ [571., 1964., 3891., 6064., 8272., 4989., 2324., 565.],
+ [434., 1360., 2586., 3920., 5264., 3054., 1312., 230.],
+ [241., 700., 1281., 1888., 2496., 1383., 532., 39.]],
+
+ [[22., 214., 528., 916., 1332., 846., 430., 132.],
+ [86., 484., 1098., 1832., 2600., 1602., 772., 206.],
+ [188., 802., 1698., 2732., 3788., 2256., 1018., 218.],
+ [308., 1006., 1950., 2996., 4052., 2400., 1078., 230.],
+ [230., 692., 1290., 1928., 2568., 1458., 596., 78.],
+ [126., 354., 636., 924., 1212., 654., 234., 0.]]],
+ dtype=np.float64).astype(dt)
+
+ return a, b, y_r
+
+ @skip_xp_backends(np_only=True, reason="order='F'")
+ def test_rank3_valid(self, dt, xp):
+ dt = getattr(xp, dt) if isinstance(dt, str) else dt
+ a, b, y_r = self._setup_rank3(dt, xp)
+ y = correlate(a, b, "valid")
+ assert_array_almost_equal(y, y_r[1:2, 2:4, 3:5])
+ assert y.dtype == dt
+
+ # See gh-5897
+ y = correlate(b, a, "valid")
+ assert_array_almost_equal(y, y_r[1:2, 2:4, 3:5][::-1, ::-1, ::-1])
+ assert y.dtype == dt
+
+ @skip_xp_backends(np_only=True, reason="order='F'")
+ def test_rank3_same(self, dt, xp):
+ dt = getattr(xp, dt) if isinstance(dt, str) else dt
+ a, b, y_r = self._setup_rank3(dt, xp)
+ y = correlate(a, b, "same")
+ xp_assert_close(y, y_r[0:-1, 1:-1, 1:-2])
+ assert y.dtype == dt
+
+ @skip_xp_backends(np_only=True, reason="order='F'")
+ def test_rank3_all(self, dt, xp):
+ dt = getattr(xp, dt) if isinstance(dt, str) else dt
+ a, b, y_r = self._setup_rank3(dt, xp)
+ y = correlate(a, b)
+ xp_assert_close(y, y_r)
+ assert y.dtype == dt
+
+
+@make_xp_test_case(correlate)
+class TestCorrelate:
+ # Tests that don't depend on dtype
+
+ @skip_xp_backends(np_only=True)
+ def test_invalid_shapes(self, xp):
+ # By "invalid," we mean that no one
+ # array has dimensions that are all at
+ # least as large as the corresponding
+ # dimensions of the other array. This
+ # setup should throw a ValueError.
+ a = np.arange(1, 7).reshape((2, 3))
+ b = np.arange(-6, 0).reshape((3, 2))
+
+ assert_raises(ValueError, correlate, *(a, b), **{'mode': 'valid'})
+ assert_raises(ValueError, correlate, *(b, a), **{'mode': 'valid'})
+
+ @skip_xp_backends(np_only=True)
+ def test_invalid_params(self, xp):
+ a = [3, 4, 5]
+ b = [1, 2, 3]
+ assert_raises(ValueError, correlate, a, b, mode='spam')
+ assert_raises(ValueError, correlate, a, b, mode='eggs', method='fft')
+ assert_raises(ValueError, correlate, a, b, mode='ham', method='direct')
+ assert_raises(ValueError, correlate, a, b, mode='full', method='bacon')
+ assert_raises(ValueError, correlate, a, b, mode='same', method='bacon')
+
+ @skip_xp_backends(np_only=True)
+ def test_mismatched_dims(self, xp):
+ # Input arrays should have the same number of dimensions
+ assert_raises(ValueError, correlate, [1], 2, method='direct')
+ assert_raises(ValueError, correlate, 1, [2], method='direct')
+ assert_raises(ValueError, correlate, [1], 2, method='fft')
+ assert_raises(ValueError, correlate, 1, [2], method='fft')
+ assert_raises(ValueError, correlate, [1], [[2]])
+ assert_raises(ValueError, correlate, [3], 2)
+
+ @skip_xp_backends(cpu_only=True, exceptions=['cupy'])
+ @skip_xp_backends("jax.numpy", reason="dtype differs")
+ def test_numpy_fastpath(self, xp):
+ a = xp.asarray([1, 2, 3])
+ b = xp.asarray([4, 5])
+ xp_assert_close(correlate(a, b, mode='same'), xp.asarray([5, 14, 23]))
+
+ a = xp.asarray([1, 2, 3])
+ b = xp.asarray([4, 5, 6])
+ xp_assert_close(correlate(a, b, mode='same'), xp.asarray([17, 32, 23]))
+ xp_assert_close(correlate(a, b, mode='full'), xp.asarray([6, 17, 32, 23, 12]))
+ xp_assert_close(correlate(a, b, mode='valid'), xp.asarray([32]))
+
+
+@make_xp_test_case(correlation_lags)
+@pytest.mark.parametrize("mode", ["valid", "same", "full"])
+@pytest.mark.parametrize("behind", [True, False])
+@pytest.mark.parametrize("input_size", [100, 101, 1000, 1001,
+ pytest.param(10000, marks=[pytest.mark.slow]),
+ pytest.param(10001, marks=[pytest.mark.slow])]
+)
+def test_correlation_lags(mode, behind, input_size, xp):
+ # generate random data
+ rng = np.random.RandomState(0)
+ in1 = rng.standard_normal(input_size)
+ offset = int(input_size/10)
+ # generate offset version of array to correlate with
+ if behind:
+ # y is behind x
+ in2 = np.concatenate([rng.standard_normal(offset), in1])
+ expected = -offset
+ else:
+ # y is ahead of x
+ in2 = in1[offset:]
+ expected = offset
+ # cross correlate, returning lag information
+ correlation = correlate(in1, in2, mode=mode)
+ lags = correlation_lags(in1.size, in2.size, mode=mode)
+ # identify the peak
+ lag_index = np.argmax(correlation)
+ # Check as expected
+ xp_assert_equal(lags[lag_index], expected)
+ # Correlation and lags shape should match
+ assert lags.shape == correlation.shape
+
+
+@make_xp_test_case(correlation_lags)
+def test_correlation_lags_invalid_mode(xp):
+ with pytest.raises(ValueError, match="Mode asdfgh is invalid"):
+ correlation_lags(100, 100, mode="asdfgh")
+
+
+@make_xp_test_case(correlate)
+@pytest.mark.parametrize('dt_name', ['complex64', 'complex128'])
+class TestCorrelateComplex:
+ # The decimal precision to be used for comparing results.
+ # This value will be passed as the 'decimal' keyword argument of
+ # assert_array_almost_equal().
+ # Since correlate may chose to use FFT method which converts
+ # longdoubles to doubles internally don't expect better precision
+ # for longdouble than for double (see gh-9520).
+
+ def decimal(self, dt, xp):
+ if is_numpy(xp) and dt == np.clongdouble:
+ dt = np.cdouble
+
+ # emulate np.finfo(dt).precision for complex64 and complex128
+ prec = {64: 15, 32: 6}[xp.finfo(dt).bits]
+ return int(2 * prec / 3)
+
+ def _setup_rank1(self, dt, mode, xp):
+ rng = np.random.default_rng(9)
+ a = np.random.randn(10).astype(dt)
+ a += 1j * rng.standard_normal(10).astype(dt)
+ b = np.random.randn(8).astype(dt)
+ b += 1j * rng.standard_normal(8).astype(dt)
+
+ y_r = (correlate(a.real, b.real, mode=mode) +
+ correlate(a.imag, b.imag, mode=mode)).astype(dt)
+ y_r += 1j * (-correlate(a.real, b.imag, mode=mode) +
+ correlate(a.imag, b.real, mode=mode))
+
+ a, b, y_r = xp.asarray(a), xp.asarray(b), xp.asarray(y_r)
+ return a, b, y_r
+
+ def test_rank1_valid(self, dt_name, xp):
+ a, b, y_r = self._setup_rank1(dt_name, 'valid', xp)
+ dt = getattr(xp, dt_name)
+ y = correlate(a, b, 'valid')
+ assert_array_almost_equal(y, y_r, decimal=self.decimal(dt, xp))
+ assert y.dtype == dt
+
+ # See gh-5897
+ y = correlate(b, a, 'valid')
+ assert_array_almost_equal(y, xp.conj(xp.flip(y_r)),
+ decimal=self.decimal(dt, xp))
+ assert y.dtype == dt
+
+ def test_rank1_same(self, dt_name, xp):
+ a, b, y_r = self._setup_rank1(dt_name, 'same', xp)
+ dt = getattr(xp, dt_name)
+
+ y = correlate(a, b, 'same')
+ assert_array_almost_equal(y, y_r, decimal=self.decimal(dt, xp))
+ assert y.dtype == dt
+
+ def test_rank1_full(self, dt_name, xp):
+ a, b, y_r = self._setup_rank1(dt_name, 'full', xp)
+ dt = getattr(xp, dt_name)
+ y = correlate(a, b, 'full')
+ assert_array_almost_equal(y, y_r, decimal=self.decimal(dt, xp))
+ assert y.dtype == dt
+
+ def test_swap_full(self, dt_name, xp):
+ dt = getattr(xp, dt_name)
+ d = xp.asarray([0.+0.j, 1.+1.j, 2.+2.j], dtype=dt)
+ k = xp.asarray([1.+3.j, 2.+4.j, 3.+5.j, 4.+6.j], dtype=dt)
+ y = correlate(d, k)
+ xp_assert_close(
+ y, xp.asarray([0.+0.j, 10.-2.j, 28.-6.j, 22.-6.j, 16.-6.j, 8.-4.j]),
+ atol=1e-6, check_dtype=False
+ )
+
+ def test_swap_same(self, dt_name, xp):
+ d = xp.asarray([0.+0.j, 1.+1.j, 2.+2.j])
+ k = xp.asarray([1.+3.j, 2.+4.j, 3.+5.j, 4.+6.j])
+ y = correlate(d, k, mode="same")
+ xp_assert_close(y, xp.asarray([10.-2.j, 28.-6.j, 22.-6.j]))
+
+ @skip_xp_backends("cupy", reason="notimplementederror")
+ def test_rank3(self, dt_name, xp):
+ if is_jax(xp) and SCIPY_DEVICE != "cpu":
+ pytest.xfail(reason="error tolerances exceeded with JAX on gpu")
+ a = np.random.randn(10, 8, 6).astype(dt_name)
+ a += 1j * np.random.randn(10, 8, 6).astype(dt_name)
+ b = np.random.randn(8, 6, 4).astype(dt_name)
+ b += 1j * np.random.randn(8, 6, 4).astype(dt_name)
+
+ y_r = (correlate(a.real, b.real)
+ + correlate(a.imag, b.imag)).astype(dt_name)
+ y_r += 1j * (-correlate(a.real, b.imag) + correlate(a.imag, b.real))
+
+ a, b, y_r = xp.asarray(a), xp.asarray(b), xp.asarray(y_r)
+ dt = getattr(xp, dt_name)
+
+ y = correlate(a, b, 'full')
+ assert_array_almost_equal(y, y_r, decimal=self.decimal(dt, xp) - 1)
+ assert y.dtype == dt
+
+ @skip_xp_backends(np_only=True) # XXX: check 0D/scalars on backends.
+ def test_rank0(self, dt_name, xp):
+ a = np.array(np.random.randn()).astype(dt_name)
+ a += 1j * np.array(np.random.randn()).astype(dt_name)
+ b = np.array(np.random.randn()).astype(dt_name)
+ b += 1j * np.array(np.random.randn()).astype(dt_name)
+ dt = getattr(xp, dt_name)
+
+ y_r = (correlate(a.real, b.real)
+ + correlate(a.imag, b.imag)).astype(dt)
+ y_r += 1j * np.array(-correlate(a.real, b.imag) +
+ correlate(a.imag, b.real))
+
+ a, b = xp.asarray(a), xp.asarray(b)
+
+ y = correlate(a, b, 'full')
+ assert_array_almost_equal(y, y_r, decimal=self.decimal(dt, xp) - 1)
+ assert y.dtype == dt
+
+ xp_assert_equal(correlate([1], [2j]), np.asarray(correlate(1, 2j)),
+ check_shape=False)
+ xp_assert_equal(correlate([2j], [3j]), np.asarray(correlate(2j, 3j)),
+ check_shape=False)
+ xp_assert_equal(correlate([3j], [4]), np.asarray(correlate(3j, 4)),
+ check_shape=False)
+
+
+
+class TestCorrelate2d:
+
+ @make_xp_test_case(signal.correlate)
+ def test_consistency_correlate_funcs(self, xp):
+ # Compare np.correlate, signal.correlate, signal.correlate2d
+ a = np.arange(5)
+ b = np.array([3.2, 1.4, 3])
+ for mode in ['full', 'valid', 'same']:
+ a_xp, b_xp = xp.asarray(a), xp.asarray(b)
+ np_corr_result = np.correlate(a, b, mode=mode)
+ assert_almost_equal(signal.correlate(a_xp, b_xp, mode=mode),
+ xp.asarray(np_corr_result))
+
+ # See gh-5897
+ if mode == 'valid':
+ np_corr_result = np.correlate(b, a, mode=mode)
+ assert_almost_equal(signal.correlate(b_xp, a_xp, mode=mode),
+ xp.asarray(np_corr_result))
+
+ @skip_xp_backends(np_only=True)
+ @make_xp_test_case(signal.correlate2d)
+ def test_consistency_correlate_funcs_2(self, xp):
+ # Compare np.correlate, signal.correlate, signal.correlate2d
+ a = np.arange(5)
+ b = np.array([3.2, 1.4, 3])
+ for mode in ['full', 'valid', 'same']:
+ assert_almost_equal(np.squeeze(signal.correlate2d([a], [b],
+ mode=mode)),
+ signal.correlate(a, b, mode=mode))
+
+ # See gh-5897
+ if mode == 'valid':
+ assert_almost_equal(np.squeeze(signal.correlate2d([b], [a],
+ mode=mode)),
+ signal.correlate(b, a, mode=mode))
+
+
+ @skip_xp_backends(np_only=True)
+ @make_xp_test_case(signal.correlate2d)
+ def test_invalid_shapes(self, xp):
+ # By "invalid," we mean that no one
+ # array has dimensions that are all at
+ # least as large as the corresponding
+ # dimensions of the other array. This
+ # setup should throw a ValueError.
+ a = np.arange(1, 7).reshape((2, 3))
+ b = np.arange(-6, 0).reshape((3, 2))
+
+ assert_raises(ValueError, signal.correlate2d, *(a, b), **{'mode': 'valid'})
+ assert_raises(ValueError, signal.correlate2d, *(b, a), **{'mode': 'valid'})
+
+ @make_xp_test_case(signal.correlate2d)
+ def test_complex_input(self, xp):
+ xp_assert_equal(signal.correlate2d(xp.asarray([[1]]), xp.asarray([[2j]])),
+ xp.asarray([-2j]), check_shape=False, check_dtype=False)
+ xp_assert_equal(signal.correlate2d(xp.asarray([[2j]]), xp.asarray([[3j]])),
+ xp.asarray([6+0j]), check_shape=False, check_dtype=False)
+ xp_assert_equal(signal.correlate2d(xp.asarray([[3j]]), xp.asarray([[4]])),
+ xp.asarray([12j]), check_shape=False, check_dtype=False)
+
+
+@make_xp_test_case(lfilter_zi)
+class TestLFilterZI:
+
+ @skip_xp_backends(np_only=True, reason='list inputs are numpy specific')
+ def test_array_like(self, xp):
+ zi_expected = xp.asarray([5.0, -1.0])
+ zi = lfilter_zi([1.0, 0.0, 2.0], [1.0, -1.0, 0.5])
+ assert_array_almost_equal(zi, zi_expected)
+
+ def test_basic(self, xp):
+ a = xp.asarray([1.0, -1.0, 0.5])
+ b = xp.asarray([1.0, 0.0, 2.0])
+ zi_expected = xp.asarray([5.0, -1.0])
+ zi = lfilter_zi(b, a)
+ assert_array_almost_equal(zi, zi_expected)
+
+ def test_scale_invariance(self, xp):
+ # Regression test. There was a bug in which b was not correctly
+ # rescaled when a[0] was nonzero.
+ b = xp.asarray([2.0, 8, 5])
+ a = xp.asarray([1.0, 1, 8])
+ zi1 = lfilter_zi(b, a)
+ zi2 = lfilter_zi(2*b, 2*a)
+ xp_assert_close(zi2, zi1, rtol=1e-12)
+
+ @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+ def test_types(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ b = xp.zeros((8), dtype=dtype)
+ a = xp.asarray([1], dtype=dtype)
+ assert signal.lfilter_zi(b, a).dtype == dtype
+
+
+@make_xp_test_case(filtfilt, sosfiltfilt)
+class TestFiltFilt:
+ filtfilt_kind = 'tf'
+
+ def filtfilt(self, zpk, x, axis=-1, padtype='odd', padlen=None,
+ method='pad', irlen=None, xp=None):
+ if self.filtfilt_kind == 'tf':
+ b, a = zpk2tf(*zpk)
+ b, a = xp.asarray(b), xp.asarray(a)
+ return filtfilt(b, a, x, axis, padtype, padlen, method, irlen)
+ elif self.filtfilt_kind == 'sos':
+ sos = zpk2sos(*zpk)
+ sos = xp.asarray(sos)
+ return sosfiltfilt(sos, x, axis, padtype, padlen)
+
+ @skip_xp_backends('torch', reason='negative strides')
+ def test_basic(self, xp):
+ if is_jax(xp) and self.filtfilt_kind == 'sos':
+ pytest.skip(reason='sosfilt works in-place')
+
+ zpk = tf2zpk(xp.asarray([1., 2, 3]), xp.asarray([1., 2, 3]))
+ out = self.filtfilt(zpk, xp.arange(12), xp=xp)
+ atol= 4e-9 if is_cupy(xp) else 5.28e-11
+ xp_assert_close(out, xp.arange(12, dtype=xp.float64), atol=atol)
+
+ @skip_xp_backends('torch', reason='negative strides')
+ def test_sine(self, xp):
+ if is_jax(xp) and self.filtfilt_kind == 'sos':
+ pytest.skip(reason='sosfilt works in-place')
+
+ rate = 2000
+ t = xp.linspace(0, 1.0, rate + 1)
+ # A signal with low frequency and a high frequency.
+ xlow = xp.sin(5 * 2 * np.pi * t)
+ xhigh = xp.sin(250 * 2 * np.pi * t)
+ x = xlow + xhigh
+
+ zpk = butter(8, xp.asarray(0.125), output='zpk')
+ # r is the magnitude of the largest pole.
+ r = np.abs(zpk[1]).max()
+ eps = 1e-5
+ # n estimates the number of steps for the
+ # transient to decay by a factor of eps.
+ n = int(np.ceil(np.log(eps) / np.log(r)))
+
+ # High order lowpass filter...
+ y = self.filtfilt(zpk, x, padlen=n, xp=xp)
+ # Result should be just xlow.
+ err = np.abs(y - xlow).max()
+ assert err < 1e-4
+
+ # A 2D case.
+ x2d = xp.asarray(np.vstack([xlow, xlow + xhigh]))
+ y2d = self.filtfilt(zpk, x2d, padlen=n, axis=1, xp=xp)
+ assert y2d.shape == x2d.shape
+ err = np.abs(y2d - xlow).max()
+ assert err < 1e-4
+
+ # Use the previous result to check the use of the axis keyword.
+ # (Regression test for ticket #1620)
+ y2dt = self.filtfilt(zpk, x2d.T, padlen=n, axis=0, xp=xp)
+ xp_assert_equal(y2d, y2dt.T)
+
+ @skip_xp_backends('torch', reason='negative strides')
+ def test_axis(self, xp):
+ if is_jax(xp) and self.filtfilt_kind == 'sos':
+ pytest.skip(reason='sosfilt works in-place')
+
+ # Test the 'axis' keyword on a 3D array.
+ x = np.arange(10.0 * 11.0 * 12.0).reshape(10, 11, 12)
+ x = xp.asarray(x)
+ zpk = butter(3, xp.asarray(0.125), output='zpk')
+ y0 = self.filtfilt(zpk, x, padlen=0, axis=0, xp=xp)
+ y1 = self.filtfilt(
+ zpk, xp.asarray(np.swapaxes(x, 0, 1)), padlen=0, axis=1, xp=xp
+ )
+ xp_assert_equal(y0, xp.asarray(np.swapaxes(y1, 0, 1)))
+ y2 = self.filtfilt(
+ zpk, xp.asarray(np.swapaxes(x, 0, 2)), padlen=0, axis=2, xp=xp
+ )
+ xp_assert_equal(y0, xp.asarray(np.swapaxes(y2, 0, 2)))
+
+ @skip_xp_backends(np_only=True,
+ reason='python scalars in array_namespace are np-only')
+ def test_acoeff(self, xp):
+ if self.filtfilt_kind != 'tf':
+ return # only necessary for TF
+ # test for 'a' coefficient as single number
+ out = signal.filtfilt(
+ xp.asarray([.5, .5]), 1, xp.arange(10, dtype=xp.float64)
+ )
+ xp_assert_close(out, xp.arange(10, dtype=xp.float64), rtol=1e-14, atol=1e-14)
+
+ @skip_xp_backends(np_only=True, reason='_filtfilt_gust is np-only')
+ def test_gust_simple(self, xp):
+ if self.filtfilt_kind != 'tf':
+ pytest.skip('gust only implemented for TF systems')
+ # The input array has length 2. The exact solution for this case
+ # was computed "by hand".
+ x = xp.asarray([1.0, 2.0])
+ b = xp.asarray([0.5])
+ a = xp.asarray([1.0, -0.5])
+ y, z1, z2 = _filtfilt_gust(b, a, x)
+ xp_assert_close(z1[0], 0.3*x[0] + 0.2*x[1])
+ xp_assert_close(z2[0], 0.2*x[0] + 0.3*x[1])
+ xp_assert_close(y,
+ xp.asarray([z1[0] + 0.25*z2[0] + 0.25*x[0] + 0.125*x[1],
+ 0.25*z1[0] + z2[0] + 0.125*x[0] + 0.25*x[1]])
+ )
+
+ @skip_xp_backends(np_only=True,
+ reason='python scalars in array_namespace are np-only')
+ def test_gust_scalars(self, xp):
+ if self.filtfilt_kind != 'tf':
+ pytest.skip('gust only implemented for TF systems')
+ # The filter coefficients are both scalars, so the filter simply
+ # multiplies its input by b/a. When it is used in filtfilt, the
+ # factor is (b/a)**2.
+ x = xp.arange(12)
+ b = 3.0
+ a = 2.0
+ y = filtfilt(b, a, x, method="gust")
+ expected = (b/a)**2 * x
+ xp_assert_close(y, expected)
+
+
+@make_xp_test_case(sosfiltfilt, filtfilt)
+class TestSOSFiltFilt(TestFiltFilt):
+ filtfilt_kind = 'sos'
+
+ @skip_xp_backends('jax.numpy', reason='sosfilt works in-place')
+ @skip_xp_backends('torch', reason='negative strides')
+ def test_equivalence(self, xp):
+ """Test equivalence between sosfiltfilt and filtfilt"""
+ x = np.random.RandomState(0).randn(1000)
+ x = xp.asarray(x)
+ for order in range(1, 6):
+ zpk = signal.butter(order, 0.35, output='zpk')
+ b, a = zpk2tf(*zpk)
+ sos = zpk2sos(*zpk)
+
+ b, a, sos = map(xp.asarray, (b, a, sos))
+ y = filtfilt(b, a, x)
+ y_sos = sosfiltfilt(sos, x)
+ xp_assert_close(y, y_sos, atol=1e-12, err_msg=f'order={order}')
+
+
+def filtfilt_gust_opt(b, a, x):
+ """
+ An alternative implementation of filtfilt with Gustafsson edges.
+
+ This function computes the same result as
+ `scipy.signal._signaltools._filtfilt_gust`, but only 1-d arrays
+ are accepted. The problem is solved using `fmin` from `scipy.optimize`.
+ `_filtfilt_gust` is significantly faster than this implementation.
+ """
+ def filtfilt_gust_opt_func(ics, b, a, x):
+ """Objective function used in filtfilt_gust_opt."""
+ m = max(len(a), len(b)) - 1
+ z0f = ics[:m]
+ z0b = ics[m:]
+ y_f = lfilter(b, a, x, zi=z0f)[0]
+ y_fb = lfilter(b, a, y_f[::-1], zi=z0b)[0][::-1]
+
+ y_b = lfilter(b, a, x[::-1], zi=z0b)[0][::-1]
+ y_bf = lfilter(b, a, y_b, zi=z0f)[0]
+ value = np.sum((y_fb - y_bf)**2)
+ return value
+
+ m = max(len(a), len(b)) - 1
+ zi = lfilter_zi(b, a)
+ ics = np.concatenate((x[:m].mean()*zi, x[-m:].mean()*zi))
+ result = fmin(filtfilt_gust_opt_func, ics, args=(b, a, x),
+ xtol=1e-10, ftol=1e-12,
+ maxfun=10000, maxiter=10000,
+ full_output=True, disp=False)
+ opt, fopt, niter, funcalls, warnflag = result
+ if warnflag > 0:
+ raise RuntimeError(
+ f"minimization failed in filtfilt_gust_opt: warnflag={warnflag}"
+ )
+ z0f = opt[:m]
+ z0b = opt[m:]
+
+ # Apply the forward-backward filter using the computed initial
+ # conditions.
+ y_b = lfilter(b, a, x[::-1], zi=z0b)[0][::-1]
+ y = lfilter(b, a, y_b, zi=z0f)[0]
+
+ return y, z0f, z0b
+
+
+def check_filtfilt_gust(b, a, shape, axis, irlen=None):
+ # Generate x, the data to be filtered.
+ rng = np.random.default_rng(123)
+ x = rng.standard_normal(shape)
+
+ # Apply filtfilt to x. This is the main calculation to be checked.
+ y = filtfilt(b, a, x, axis=axis, method="gust", irlen=irlen)
+
+ # Also call the private function so we can test the ICs.
+ yg, zg1, zg2 = _filtfilt_gust(b, a, x, axis=axis, irlen=irlen)
+
+ # filtfilt_gust_opt is an independent implementation that gives the
+ # expected result, but it only handles 1-D arrays, so use some looping
+ # and reshaping shenanigans to create the expected output arrays.
+ xx = np.swapaxes(x, axis, -1)
+ out_shape = xx.shape[:-1]
+ yo = np.empty_like(xx)
+ m = max(len(a), len(b)) - 1
+ zo1 = np.empty(out_shape + (m,))
+ zo2 = np.empty(out_shape + (m,))
+ for indx in product(*[range(d) for d in out_shape]):
+ yo[indx], zo1[indx], zo2[indx] = filtfilt_gust_opt(b, a, xx[indx])
+ yo = np.swapaxes(yo, -1, axis)
+ zo1 = np.swapaxes(zo1, -1, axis)
+ zo2 = np.swapaxes(zo2, -1, axis)
+
+ xp_assert_close(y, yo, rtol=1e-8, atol=1e-9)
+ xp_assert_close(yg, yo, rtol=1e-8, atol=1e-9)
+ xp_assert_close(zg1, zo1, rtol=1e-8, atol=1e-9)
+ xp_assert_close(zg2, zo2, rtol=1e-8, atol=1e-9)
+
+
+@make_xp_test_case(choose_conv_method)
+@pytest.mark.fail_slow(10)
+def test_choose_conv_method(xp):
+ for mode in ['valid', 'same', 'full']:
+ for ndim in [1, 2]:
+ n, k, true_method = 8, 6, 'direct'
+ x = np.random.randn(*((n,) * ndim))
+ h = np.random.randn(*((k,) * ndim))
+
+ method = choose_conv_method(x, h, mode=mode)
+ assert method == true_method
+
+ method_try, times = choose_conv_method(x, h, mode=mode, measure=True)
+ assert method_try in {'fft', 'direct'}
+ assert isinstance(times, dict)
+ assert 'fft' in times.keys() and 'direct' in times.keys()
+
+ n = 10
+ for not_fft_conv_supp in ["complex256", "complex192"]:
+ if hasattr(np, not_fft_conv_supp):
+ x = np.ones(n, dtype=not_fft_conv_supp)
+ h = x.copy()
+ assert choose_conv_method(x, h, mode=mode) == 'direct'
+
+ x = np.array([2**51], dtype=np.int64)
+ h = x.copy()
+ assert choose_conv_method(x, h, mode=mode) == 'direct'
+
+
+@make_xp_test_case(choose_conv_method)
+def test_choose_conv_method_2(xp):
+ for mode in ['valid', 'same', 'full']:
+ n = 10
+ for not_fft_conv_supp in ["complex256", "complex192"]:
+ if hasattr(np, not_fft_conv_supp):
+ x = np.ones(n, dtype=not_fft_conv_supp)
+ h = x.copy()
+ assert choose_conv_method(x, h, mode=mode) == 'direct'
+
+
+@skip_xp_backends(np_only=True)
+@pytest.mark.fail_slow(10)
+def test_filtfilt_gust(xp):
+ # Design a filter.
+ z, p, k = signal.ellip(3, 0.01, 120, 0.0875, output='zpk')
+
+ # Find the approximate impulse response length of the filter.
+ eps = 1e-10
+ r = np.max(np.abs(p))
+ approx_impulse_len = int(np.ceil(np.log(eps) / np.log(r)))
+
+ b, a = zpk2tf(z, p, k)
+ for irlen in [None, approx_impulse_len]:
+ signal_len = 5 * approx_impulse_len
+
+ # 1-d test case
+ check_filtfilt_gust(b, a, (signal_len,), 0, irlen)
+
+ # 3-d test case; test each axis.
+ for axis in range(3):
+ shape = [2, 2, 2]
+ shape[axis] = signal_len
+ check_filtfilt_gust(b, a, shape, axis, irlen)
+
+ # Test case with length less than 2*approx_impulse_len.
+ # In this case, `filtfilt_gust` should behave the same as if
+ # `irlen=None` was given.
+ length = 2*approx_impulse_len - 50
+ check_filtfilt_gust(b, a, (length,), 0, approx_impulse_len)
+
+
+@make_xp_test_case(signal.decimate)
+class TestDecimate:
+ def test_bad_args(self, xp):
+ x = xp.arange(12)
+ assert_raises(TypeError, signal.decimate, x, q=0.5, n=1)
+ assert_raises(TypeError, signal.decimate, x, q=2, n=0.5)
+
+ def test_basic_IIR(self, xp):
+ x = xp.arange(12)
+ y = signal.decimate(x, 2, n=1, ftype='iir', zero_phase=False).round()
+ xp_assert_equal(y, x[::2].astype(float))
+
+ def test_basic_FIR(self, xp):
+ x = xp.arange(12)
+ y = signal.decimate(x, 2, n=1, ftype='fir', zero_phase=False).round()
+ xp_assert_equal(y, x[::2].astype(float))
+
+ def test_shape(self, xp):
+ # Regression test for ticket #1480.
+ z = xp.zeros((30, 30))
+ d0 = signal.decimate(z, 2, axis=0, zero_phase=False)
+ assert d0.shape == (15, 30)
+ d1 = signal.decimate(z, 2, axis=1, zero_phase=False)
+ assert d1.shape == (30, 15)
+
+ @skip_xp_backends(np_only=True, reason="test code is NumPy specific")
+ def test_phaseshift_FIR(self, xp):
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Badly conditioned filter", BadCoefficients)
+ self._test_phaseshift(method='fir', zero_phase=False)
+
+ @skip_xp_backends(np_only=True, reason="test code is NumPy specific")
+ def test_zero_phase_FIR(self, xp):
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "Badly conditioned filter", BadCoefficients)
+ self._test_phaseshift(method='fir', zero_phase=True)
+
+ @skip_xp_backends(np_only=True, reason="test code is NumPy specific")
+ def test_phaseshift_IIR(self, xp):
+ self._test_phaseshift(method='iir', zero_phase=False)
+
+ @skip_xp_backends(np_only=True, reason="test code is NumPy specific")
+ def test_zero_phase_IIR(self, xp):
+ self._test_phaseshift(method='iir', zero_phase=True)
+
+ def _test_phaseshift(self, method, zero_phase):
+ # TODO. Look into making tests using this work for CuPy.
+ rate = 120
+ rates_to = [15, 20, 30, 40] # q = 8, 6, 4, 3
+
+ t_tot = 100 # Need to let antialiasing filters settle
+ t = np.arange(rate*t_tot+1) / float(rate)
+
+ # Sinusoids at 0.8*nyquist, windowed to avoid edge artifacts
+ freqs = np.array(rates_to) * 0.8 / 2
+ d = (np.exp(1j * 2 * np.pi * freqs[:, np.newaxis] * t)
+ * signal.windows.tukey(t.size, 0.1))
+
+ for rate_to in rates_to:
+ q = rate // rate_to
+ t_to = np.arange(rate_to*t_tot+1) / float(rate_to)
+ d_tos = (np.exp(1j * 2 * np.pi * freqs[:, np.newaxis] * t_to)
+ * signal.windows.tukey(t_to.size, 0.1))
+
+ # Set up downsampling filters, match v0.17 defaults
+ if method == 'fir':
+ n = 30
+ system = signal.dlti(signal.firwin(n + 1, 1. / q,
+ window='hamming'), 1.)
+ elif method == 'iir':
+ n = 8
+ wc = 0.8*np.pi/q
+ system = signal.dlti(*signal.cheby1(n, 0.05, wc/np.pi))
+
+ # Calculate expected phase response, as unit complex vector
+ if zero_phase is False:
+ _, h_resps = signal.freqz(system.num, system.den,
+ freqs/rate*2*np.pi)
+ h_resps /= np.abs(h_resps)
+ else:
+ h_resps = np.ones_like(freqs)
+
+ y_resamps = signal.decimate(d.real, q, n, ftype=system,
+ zero_phase=zero_phase)
+
+ # Get phase from complex inner product, like CSD
+ h_resamps = np.sum(d_tos.conj() * y_resamps, axis=-1)
+ h_resamps /= np.abs(h_resamps)
+ subnyq = freqs < 0.5*rate_to
+
+ # Complex vectors should be aligned, only compare below nyquist
+ result = np.angle(h_resps.conj()*h_resamps)[subnyq]
+ xp_assert_close(result, np.zeros_like(result),
+ atol=1e-3, rtol=1e-3)
+
+ def test_auto_n(self, xp):
+ # Test that our value of n is a reasonable choice (depends on
+ # the downsampling factor)
+ sfreq = 100.
+ n = 1000
+ t = xp.arange(n) / sfreq
+ # will alias for decimations (>= 15)
+ x = xp.asarray(xp.sqrt(2. / n) * xp.sin(2 * xp.pi * (sfreq / 30.) * t))
+ # Use xp.sqrt(x.dot(x)) instead of xp.linalg.vector_norm(x) because
+ # linear algebra extension is not universally available.
+ xp_assert_close(xp.sqrt(x.dot(x)), xp.asarray(1.), rtol=1e-3, check_0d=False)
+ x_out = signal.decimate(x, 30, ftype='fir')
+ assert xp.sqrt(x_out.dot(x_out)) < 0.01
+
+ def test_long_float32(self, xp):
+ # regression: gh-15072. With 32-bit float and either lfilter
+ # or filtfilt, this is numerically unstable
+ x = signal.decimate(xp.ones(10_000, dtype=xp.float32), 10)
+ assert not any(xp.isnan(x))
+
+ def test_float16_upcast(self):
+ # float16 must be upcast to float64
+ x = signal.decimate(np.ones(100, dtype=np.float16), 10)
+ assert x.dtype.type == np.float64
+
+ @skip_xp_backends(np_only=True, reason="dlti")
+ def test_complex_iir_dlti(self, xp):
+ # regression: gh-17845
+ # centre frequency for filter [Hz]
+ fcentre = 50
+ # filter passband width [Hz]
+ fwidth = 5
+ # sample rate [Hz]
+ fs = 1e3
+
+ z, p, k = signal.butter(2, xp.asarray(2*xp.pi*fwidth/2),
+ output='zpk', fs=fs)
+ z = z.astype(complex) * xp.exp(xp.asarray(2j * xp.pi * fcentre/fs))
+ p = p.astype(complex) * xp.exp(xp.asarray(2j * xp.pi * fcentre/fs))
+ system = signal.dlti(z, p, k)
+
+ t = xp.arange(200) / fs
+
+ # input
+ u = (xp.exp(2j * xp.pi * fcentre * t)
+ + 0.5 * xp.exp(-2j * xp.pi * fcentre * t))
+
+ ynzp = signal.decimate(u, 2, ftype=system, zero_phase=False)
+ ynzpref = signal.lfilter(*signal.zpk2tf(z, p, k),
+ u)[::2]
+
+ xp_assert_equal(ynzp, ynzpref)
+
+ yzp = signal.decimate(u, 2, ftype=system, zero_phase=True)
+ yzpref = signal.filtfilt(*signal.zpk2tf(z, p, k),
+ u)[::2]
+
+ xp_assert_close(yzp, yzpref, rtol=1e-10, atol=1e-13)
+
+ @skip_xp_backends(np_only=True, reason="dlti")
+ def test_complex_fir_dlti(self, xp):
+ # centre frequency for filter [Hz]
+ fcentre = 50
+ # filter passband width [Hz]
+ fwidth = 5
+ # sample rate [Hz]
+ fs = 1e3
+ numtaps = 20
+
+ # FIR filter about 0Hz
+ bbase = signal.firwin(numtaps, fwidth/2, fs=fs)
+
+ # rotate these to desired frequency
+ zbase = np.roots(bbase)
+ zrot = zbase * np.exp(2j * np.pi * fcentre/fs)
+ # FIR filter about 50Hz, maintaining passband gain of 0dB
+ bz = bbase[0] * np.poly(zrot)
+
+ system = signal.dlti(bz, 1)
+
+ t = np.arange(200) / fs
+
+ # input
+ u = (np.exp(2j * np.pi * fcentre * t)
+ + 0.5 * np.exp(-2j * np.pi * fcentre * t))
+
+ ynzp = signal.decimate(u, 2, ftype=system, zero_phase=False)
+ ynzpref = signal.upfirdn(bz, u, up=1, down=2)[:100]
+
+ xp_assert_equal(ynzp, ynzpref)
+
+ yzp = signal.decimate(u, 2, ftype=system, zero_phase=True)
+ yzpref = signal.resample_poly(u, 1, 2, window=bz)
+
+ xp_assert_equal(yzp, yzpref)
+
+@make_xp_test_case(hilbert)
+class TestHilbert:
+
+ def test_bad_args(self, xp):
+ x = xp.asarray([1.0 + 0.0j])
+ assert_raises(ValueError, hilbert, x)
+ x = xp.arange(8.0)
+ assert_raises(ValueError, hilbert, x, N=0)
+
+ def test_hilbert_theoretical(self, xp):
+ # test cases by Ariel Rokem
+ decimal = 14
+
+ pi = xp.pi
+ t = xp.arange(0, 2 * pi, pi / 256, dtype=xp.float64)
+ a0 = xp.sin(t)
+ a1 = xp.cos(t)
+ a2 = xp.sin(2 * t)
+ a3 = xp.cos(2 * t)
+ a = xp.stack([a0, a1, a2, a3])
+
+ h = hilbert(a)
+ h_abs = xp.abs(h)
+
+ h_angle = xp.atan2(xp.imag(h), xp.real(h)) # np.angle(h)
+ h_real = xp.real(h)
+
+ # The real part should be equal to the original signals:
+ assert_almost_equal(h_real, a, decimal)
+ # The absolute value should be one everywhere, for this input:
+ assert_almost_equal(h_abs, xp.ones(a.shape), decimal)
+ # For the 'slow' sine - the phase should go from -pi/2 to pi/2 in
+ # the first 256 bins:
+ assert_almost_equal(h_angle[0, :256],
+ xp.arange(-pi / 2, pi / 2, pi / 256, dtype=xp.float64),
+ decimal)
+ # For the 'slow' cosine - the phase should go from 0 to pi in the
+ # same interval:
+ assert_almost_equal(
+ h_angle[1, :256], xp.arange(0, pi, pi / 256, dtype=xp.float64), decimal)
+ # The 'fast' sine should make this phase transition in half the time:
+ assert_almost_equal(h_angle[2, :128],
+ xp.arange(-pi / 2, pi / 2, pi / 128, dtype=xp.float64),
+ decimal)
+ # Ditto for the 'fast' cosine:
+ assert_almost_equal(
+ h_angle[3, :128], xp.arange(0, pi, pi / 128, dtype=xp.float64), decimal)
+
+ # The imaginary part of hilbert(cos(t)) = sin(t) Wikipedia
+ assert_almost_equal(xp.imag(h[1, :]), a0, decimal)
+
+ def test_hilbert_axisN(self, xp):
+ # tests for axis and N arguments
+ a = xp.reshape(xp.arange(18, dtype=xp.float64), (3, 6))
+ # test axis
+ aa = hilbert(a, axis=-1)
+ xp_assert_equal(hilbert(a.T, axis=0), aa.T)
+ # test 1d
+ assert_almost_equal(hilbert(a[0, :]), aa[0, :], 14)
+
+ # test N
+ aan = hilbert(a, N=20, axis=-1)
+ assert aan.shape == (3, 20)
+ assert hilbert(a.T, N=20, axis=0).shape == (20, 3)
+ # the next test is just a regression test,
+ # no idea whether numbers make sense
+ a0hilb = np.array([0.000000000000000e+00 - 1.72015830311905j,
+ 1.000000000000000e+00 - 2.047794505137069j,
+ 1.999999999999999e+00 - 2.244055555687583j,
+ 3.000000000000000e+00 - 1.262750302935009j,
+ 4.000000000000000e+00 - 1.066489252384493j,
+ 5.000000000000000e+00 + 2.918022706971047j,
+ 8.881784197001253e-17 + 3.845658908989067j,
+ -9.444121133484362e-17 + 0.985044202202061j,
+ -1.776356839400251e-16 + 1.332257797702019j,
+ -3.996802888650564e-16 + 0.501905089898885j,
+ 1.332267629550188e-16 + 0.668696078880782j,
+ -1.192678053963799e-16 + 0.235487067862679j,
+ -1.776356839400251e-16 + 0.286439612812121j,
+ 3.108624468950438e-16 + 0.031676888064907j,
+ 1.332267629550188e-16 - 0.019275656884536j,
+ -2.360035624836702e-16 - 0.1652588660287j,
+ 0.000000000000000e+00 - 0.332049855010597j,
+ 3.552713678800501e-16 - 0.403810179797771j,
+ 8.881784197001253e-17 - 0.751023775297729j,
+ 9.444121133484362e-17 - 0.79252210110103j])
+ a0hilb = xp.asarray(a0hilb)
+ assert_almost_equal(aan[0, :], a0hilb, 14, err_msg='N regression')
+
+ def test_hilbert_axis_3d(self, xp):
+ a = xp.reshape(xp.arange(3 * 5 * 7, dtype=xp.float64), (3, 5, 7))
+ # test axis
+ aa = hilbert(a, axis=-1)
+ for axis in [0, 1]:
+ aap = hilbert(xp.moveaxis(a, -1, axis), axis=axis)
+ aap = xp.moveaxis(aap, axis, -1)
+ xp_assert_equal(aa, aap)
+
+ @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+ def test_hilbert_types(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ in_typed = xp.zeros(8, dtype=dtype)
+ assert xp.real(hilbert(in_typed)).dtype == dtype
+
+
+@make_xp_test_case(hilbert2)
+class TestHilbert2:
+ """Test function `signal.hilbert2`. """
+
+ @skip_xp_backends(np_only=True, reason='list inputs are numpy-specific')
+ def test_array_like(self, xp):
+ hilbert2([[1, 2, 3], [4, 5, 6]])
+
+ def test_bad_args(self, xp):
+ """Raise all exceptions in `hilbert2`. """
+ x = xp.reshape(xp.arange(16), (4, 4))
+ with pytest.raises(ValueError, match="^x must be real."):
+ hilbert2(xp.asarray([[1.0 + 0.0j]]))
+ with pytest.raises(ValueError, match="^N must be positive."):
+ hilbert2(x, N=-1)
+ with pytest.raises(ValueError, match="^When given as a tuple, N must hold"):
+ hilbert2(x, N=(1, 1, 1))
+ with pytest.raises(ValueError, match="^When given as a tuple, N must hold"):
+ hilbert2(x, N=(0, 1))
+
+ @skip_xp_backends("cupy", reason="CuPy's hilbert2 does not have axes= argument")
+ def test_bad_args2(self, xp):
+ x = xp.reshape(xp.arange(16), (4, 4))
+ with pytest.raises(ValueError, match="^axes must be a tuple of length 2"):
+ hilbert2(x, axes=(0, 1, 2))
+ with pytest.raises(ValueError, match="^axes must contain 2 distinct axes"):
+ hilbert2(x, axes=(0, 0))
+
+ @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+ def test_hilbert2_types(self, dtype, xp):
+ dtype = getattr(xp, dtype)
+ in_typed = xp.zeros((2, 32), dtype=dtype)
+ out = xp.real(signal.hilbert2(in_typed))
+ assert out.dtype == dtype
+
+ def test_1d_input(self, xp):
+ """Needed for 100% coverage """
+ x = xp.asarray([0., 1., 1., 0., -1., -1.])
+ x0a = signal.hilbert2(xp.reshape(x, (6, 1)))
+ x1a = signal.hilbert2(xp.reshape(x, (1, 6)))
+ xp_assert_close(x0a, x1a.T)
+
+ def test_parameter_N(self, xp):
+ """Compare passing tuple to single int. """
+ x = xp.zeros((5, 5))
+ x0_a = hilbert2(x, N=4)
+ x1_a = hilbert2(x, N=(4, 4))
+ xp_assert_equal(x1_a, x0_a)
+
+ @pytest.mark.parametrize('shape', [(4, 5), (5, 4), (4, 4), (5, 5)])
+ @skip_xp_backends("cupy", reason="Bug in cupy implementation, see cupy#9396")
+ def test_quadrant_values(self, shape, xp):
+ """Compare desired and calculated values in Fourier space. """
+ x_f = xp.ones(shape, dtype=xp.complex128) # FFT of input signal
+ x_f[0 , 0] += 7
+ x = xp.real(sp_fft.ifft2(x_f)) # x.imag is zero
+
+ x_as = hilbert2(x)
+ x_as_f = sp_fft.fft2(x_as)
+
+ # Create slices for bins with purely positive and purely negative frequencies
+ # (can be verified with `sp_fft.fftfreq()`):
+ f0_pos, f0_neg = slice(1, (shape[0] + 1) // 2), slice((shape[0] + 1) // 2, None)
+ f1_pos, f1_neg = slice(1, (shape[1] + 1) // 2), slice((shape[1] + 1) // 2, None)
+ # Verify all values:
+ atol = 1e-12 # for x of dtype complex128
+ xp_assert_close(x_as_f[f0_pos, f1_pos], x_f[f0_pos, f1_pos] * 4, atol=atol)
+ xp_assert_close(x_as_f[0, f1_pos], x_f[0, f1_pos] * 2, atol=atol)
+ xp_assert_close(x_as_f[f0_pos, 0], x_f[f0_pos, 0] * 2, atol=atol)
+ xp_assert_close(x_as_f[0, 0], x_f[0, 0], atol=atol)
+ zz_as_f = x_as_f[f0_neg, f1_neg] # check for zeroed orthants
+ xp_assert_close(zz_as_f, xp.zeros_like(zz_as_f), atol=atol)
+
+ @pytest.mark.parametrize('shape', [(4, 5), (5, 4), (4, 4), (5, 5)])
+ def test_zero_analytic_signal(self, shape, xp):
+ """Test that a real signal with Z[-p,-q] == np.conj(Z[p,q])
+ produces a zero analytic signal."""
+ c0 = shape[0] // 2
+ c1 = shape[1] // 2
+ x_f = xp.zeros(shape)
+ x_f[c0 - 1, c1 + 1] = 1.0
+ x_f[c0 + 1, c1 - 1] = 1.0
+ x_f = sp_fft.ifftshift(x_f)
+ x = xp.real(sp_fft.ifft2(x_f))
+ assert xp.sum(abs(x)) > 0.0
+ x_as = hilbert2(x)
+ xp_assert_close(x_as, xp.zeros_like(x_as), atol=xp.finfo(x_as.dtype).eps*16)
+
+ @pytest.mark.parametrize('sh0', [4, 5])
+ @pytest.mark.parametrize('sh1', [6, 7])
+ @pytest.mark.parametrize('sh2', [8, 9])
+ @pytest.mark.parametrize('not_axis', [0, 1, 2])
+ @skip_xp_backends("cupy", reason="cupy implementation does not have axes kwarg")
+ def test_3d_vs_slice(self, sh0, sh1, sh2, not_axis, xp):
+ """2d transform on 3d array is equal to 2d transform on 2d slices."""
+ x = xp.reshape(xp.arange(sh0 * sh1 * sh2, dtype=xp.float64), (sh0, sh1, sh2))
+ transform_axes = [0, 1, 2]
+ transform_axes.pop(not_axis)
+ x_as_3d = hilbert2(x, axes=transform_axes)
+ parts = xp.unstack(x, axis=not_axis)
+ x_as_2d = [hilbert2(p) for p in parts]
+ x_as_2d = xp.stack(x_as_2d, axis=not_axis)
+ xp_assert_close(x_as_3d, x_as_2d)
+
+ @skip_xp_backends("cupy", reason="cupy implementation does not have axes kwarg")
+ def test_3d_axis_order(self, xp):
+ """2d transform on equal arrays with moved axis are equal."""
+ x0 = xp.reshape(xp.arange(5 * 7 * 9, dtype=xp.float64), (5, 7, 9))
+ x0_as = hilbert2(x0)
+
+ x1 = xp.moveaxis(x0, 0, 1)
+ x1_as = hilbert2(x1, axes=(0, 2))
+ x1_as = xp.moveaxis(x1_as, 1, 0)
+ xp_assert_close(x0_as, x1_as)
+
+ x2 = xp.moveaxis(x0, 0, 2)
+ x2_as = hilbert2(x2, axes=(0, 1))
+ x2_as = xp.moveaxis(x2_as, 2, 0)
+ xp_assert_close(x0_as, x2_as)
+
+
+@make_xp_test_case(envelope)
+class TestEnvelope:
+ """Unit tests for function `._signaltools.envelope()`. """
+
+ @staticmethod
+ def assert_close(actual, desired, msg, xp):
+ a_r_tol = ({'atol': 1e-12, 'rtol': 1e-12}
+ if xp_default_dtype(xp) == xp.float64
+ else {'atol': 1e-5, 'rtol': 1e-5}
+ )
+
+ """Little helper to compare to arrays with proper tolerances"""
+ xp_assert_close(actual, desired, **a_r_tol, err_msg=msg)
+
+ def test_envelope_invalid_parameters(self, xp):
+ """For `envelope()` Raise all exceptions that are used to verify function
+ parameters. """
+ with pytest.raises(ValueError,
+ match=r"Invalid parameter axis=2 for z.shape=.*"):
+ envelope(np.ones(3), axis=2)
+ with pytest.raises(ValueError,
+ match=r"z.shape\[axis\] not > 0 for z.shape=.*"):
+ envelope(xp.ones((3, 0)), axis=1)
+ for bp_in in [(0, 1, 2), (0, 2.), (None, 2.)]:
+ ts = ', '.join(map(str, bp_in))
+ with pytest.raises(ValueError,
+ match=rf"bp_in=\({ts}\) isn't a 2-tuple of.*"):
+ # noinspection PyTypeChecker
+ envelope(xp.ones(4), bp_in=bp_in)
+ with pytest.raises(ValueError,
+ match="n_out=10.0 is not a positive integer or.*"):
+ # noinspection PyTypeChecker
+ envelope(xp.ones(4), n_out=10.)
+ for bp_in in [(-1, 3), (1, 1), (0, 10)]:
+ with pytest.raises(ValueError,
+ match=r"`-n//2 <= bp_in\[0\] < bp_in\[1\] <=.*"):
+ envelope(xp.ones(4), bp_in=bp_in)
+ with pytest.raises(ValueError, match="residual='undefined' not in .*"):
+ # noinspection PyTypeChecker
+ envelope(xp.ones(4), residual='undefined')
+
+ @skip_xp_backends("jax.numpy", reason="XXX: immutable arrays")
+ def test_envelope_verify_parameters(self, xp):
+ """Ensure that the various parametrizations produce compatible results. """
+ dt_r = xp_default_dtype(xp)
+ dt_c = xp.complex64 if dt_r == xp.float32 else xp.complex128
+
+ Z = xp.asarray([4.0, 2, 2, 3, 0], dtype=dt_r)
+ Zr_a = xp.asarray([4.0, 0, 0, 6, 0, 0, 0, 0], dtype=dt_r)
+ z = sp_fft.irfft(Z)
+ n = z.shape[0]
+
+ # the reference envelope:
+ ze2_0, zr_0 = xp.unstack(envelope(z, (1, 3), residual='all', squared=True))
+ self.assert_close(sp_fft.rfft(ze2_0),
+ xp.asarray([4, 2, 0, 0, 0], dtype=dt_c),
+ msg="Envelope calculation error", xp=xp)
+ self.assert_close(sp_fft.rfft(zr_0),
+ xp.asarray([4, 0, 0, 3, 0], dtype=dt_c),
+ msg="Residual calculation error", xp=xp)
+
+ ze_1, zr_1 = xp.unstack(envelope(z, (1, 3), residual='all', squared=False))
+ self.assert_close(ze_1**2, ze2_0,
+ msg="Unsquared versus Squared envelope calculation error",
+ xp=xp)
+ self.assert_close(zr_1, zr_0,
+ msg="Unsquared versus Squared residual calculation error",
+ xp=xp)
+
+ ze2_2, zr_2 = xp.unstack(
+ envelope(z, (1, 3), residual='all', squared=True, n_out=3*n)
+ )
+ self.assert_close(ze2_2[::3], ze2_0,
+ msg="3x up-sampled envelope calculation error", xp=xp)
+ self.assert_close(zr_2[::3], zr_0,
+ msg="3x up-sampled residual calculation error", xp=xp)
+
+ ze2_3, zr_3 = xp.unstack(envelope(z, (1, 3), residual='lowpass', squared=True))
+ self.assert_close(ze2_3, ze2_0,
+ msg="`residual='lowpass'` envelope calculation error", xp=xp)
+ self.assert_close(sp_fft.rfft(zr_3),
+ xp.asarray([4, 0, 0, 0, 0], dtype=dt_c),
+ msg="`residual='lowpass'` residual calculation error", xp=xp)
+
+ ze2_4 = envelope(z, (1, 3), residual=None, squared=True)
+ self.assert_close(ze2_4, ze2_0,
+ msg="`residual=None` envelope calculation error", xp=xp)
+
+ # compare complex analytic signal to real version
+ Z_a = xp.asarray(Z, copy=True)
+ Z_a[1:] *= 2
+ z_a = sp_fft.ifft(Z_a, n=n) # analytic signal of Z
+ self.assert_close(xp.real(z_a), z,
+ msg="Reference analytic signal error", xp=xp)
+ ze2_a, zr_a = xp.unstack(envelope(z_a, (1, 3), residual='all', squared=True))
+ self.assert_close(ze2_a, xp.astype(ze2_0, dt_c), # dtypes must match
+ msg="Complex envelope calculation error", xp=xp)
+ self.assert_close(sp_fft.fft(zr_a), xp.asarray(Zr_a, dtype=dt_c),
+ msg="Complex residual calculation error", xp=xp)
+
+ @skip_xp_backends("jax.numpy", reason="XXX: immutable arrays")
+ @pytest.mark.parametrize(
+ " Z, bp_in, Ze2_desired, Zr_desired",
+ [([1, 0, 2, 2, 0], (1, None), [4, 2, 0, 0, 0], [1, 0, 0, 0, 0]),
+ ([4, 0, 2, 0, 0], (0, None), [4, 0, 2, 0, 0], [0, 0, 0, 0, 0]),
+ ([4, 0, 0, 2, 0], (None, None), [4, 0, 0, 2, 0], [0, 0, 0, 0, 0]),
+ ([0, 0, 2, 2, 0], (1, 3), [2, 0, 0, 0, 0], [0, 0, 0, 2, 0]),
+ ([4, 0, 2, 2, 0], (-3, 3), [4, 0, 2, 0, 0], [0, 0, 0, 2, 0]),
+ ([4, 0, 3, 4, 0], (None, 1), [2, 0, 0, 0, 0], [0, 0, 3, 4, 0]),
+ ([4, 0, 3, 4, 0], (None, 0), [0, 0, 0, 0, 0], [4, 0, 3, 4, 0])])
+ def test_envelope_real_signals(self, Z, bp_in, Ze2_desired, Zr_desired, xp):
+ """Test envelope calculation with real-valued test signals.
+
+ The comparisons are performed in the Fourier space, since it makes evaluating
+ the bandpass filter behavior straightforward. Note that also the squared
+ envelope can be easily calculated by hand, if one recalls that coefficients of
+ a complex-valued Fourier series representing the signal can be directly
+ determined by an FFT and that the absolute square of a Fourier series is again
+ a Fourier series.
+ """
+ Z = xp.asarray(Z, dtype=xp.float64)
+ Ze2_desired = xp.asarray(Ze2_desired, dtype=xp.float64)
+ Zr_desired = xp.asarray(Zr_desired, dtype=xp.float64)
+
+ z = sp_fft.irfft(Z)
+ ze2, zr = xp.unstack(envelope(z, bp_in, residual='all', squared=True))
+ ze2_lp, zr_lp = xp.unstack(envelope(z, bp_in, residual='lowpass', squared=True))
+ Ze2, Zr, Ze2_lp, Zr_lp = (sp_fft.rfft(z_) for z_ in (ze2, zr, ze2_lp, zr_lp))
+
+ Ze2_desired = xp.asarray(Ze2_desired, dtype=xp.complex128)
+ Zr_desired = xp.asarray(Zr_desired, dtype=xp.complex128)
+ self.assert_close(Ze2, Ze2_desired,
+ msg="Envelope calculation error (residual='all')", xp=xp)
+ self.assert_close(Zr, Zr_desired,
+ msg="Residual calculation error (residual='all')", xp=xp)
+
+ if bp_in[1] is not None:
+ Zr_desired[bp_in[1]:] = 0
+ self.assert_close(Ze2_lp, Ze2_desired,
+ msg="Envelope calculation error (residual='lowpass')", xp=xp)
+ self.assert_close(Zr_lp, Zr_desired,
+ msg="Residual calculation error (residual='lowpass')", xp=xp)
+
+ @skip_xp_backends("jax.numpy", reason="XXX: immutable arrays")
+ @pytest.mark.parametrize(
+ " Z, bp_in, Ze2_desired, Zr_desired",
+ [([0, 5, 0, 5, 0], (None, None), [5, 0, 10, 0, 5], [0, 0, 0, 0, 0]),
+ ([1, 5, 0, 5, 2], (-1, 2), [5, 0, 10, 0, 5], [1, 0, 0, 0, 2]),
+ ([1, 2, 6, 0, 6, 3], (-1, 2), [0, 6, 0, 12, 0, 6], [1, 2, 0, 0, 0, 3])
+ ])
+ def test_envelope_complex_signals(self, Z, bp_in, Ze2_desired, Zr_desired, xp):
+ """Test envelope calculation with complex-valued test signals.
+
+ We only need to test for the complex envelope here, since the ``Nones``s in the
+ bandpass filter were already tested in the previous test.
+ """
+ Z = xp.asarray(Z, dtype=xp.float64)
+ Ze2_desired = xp.asarray(Ze2_desired, dtype=xp.complex128)
+ Zr_desired = xp.asarray(Zr_desired, dtype=xp.complex128)
+
+ z = sp_fft.ifft(sp_fft.ifftshift(Z))
+ ze2, zr = xp.unstack(envelope(z, bp_in, residual='all', squared=True))
+ Ze2, Zr = (sp_fft.fftshift(sp_fft.fft(z_)) for z_ in (ze2, zr))
+
+ self.assert_close(Ze2, Ze2_desired,
+ msg="Envelope calculation error", xp=xp)
+ self.assert_close(Zr, Zr_desired,
+ msg="Residual calculation error", xp=xp)
+
+ @skip_xp_backends("jax.numpy", reason="XXX: immutable arrays")
+ def test_envelope_verify_axis_parameter(self, xp):
+ """Test for multi-channel envelope calculations. """
+ dt_r = xp_default_dtype(xp)
+ dt_c = xp.complex64 if dt_r == xp.float32 else xp.complex128
+
+ z = sp_fft.irfft(xp.asarray([[1.0, 0, 2, 2, 0], [7, 0, 4, 4, 0]], dtype=dt_r))
+ Ze2_desired = xp.asarray([[4, 2, 0, 0, 0], [16, 8, 0, 0, 0]],
+ dtype=dt_c)
+ Zr_desired = xp.asarray([[1, 0, 0, 0, 0], [7, 0, 0, 0, 0]], dtype=dt_c)
+
+ ze2, zr = xp.unstack(envelope(z, squared=True, axis=1))
+ ye2T, yrT = xp.unstack(envelope(z.T, squared=True, axis=0))
+ Ze2, Ye2, Zr, Yr = (sp_fft.rfft(z_) for z_ in (ze2, ye2T.T, zr, yrT.T))
+
+ self.assert_close(Ze2, Ze2_desired, msg="2d envelope calculation error", xp=xp)
+ self.assert_close(Zr, Zr_desired, msg="2d residual calculation error", xp=xp)
+ self.assert_close(
+ Ye2, Ze2_desired, msg="Transposed 2d envelope calc. error", xp=xp
+ )
+ self.assert_close(
+ Yr, Zr_desired, msg="Transposed 2d residual calc. error", xp=xp
+ )
+
+ @skip_xp_backends("jax.numpy", reason="XXX: immutable arrays")
+ def test_envelope_verify_axis_parameter_complex(self, xp):
+ """Test for multi-channel envelope calculations with complex values. """
+ dt_r = xp_default_dtype(xp)
+ dt_c = xp.complex64 if dt_r == xp.float32 else xp.complex128
+ inp = xp.asarray([[1.0, 5, 0, 5, 2], [1, 10, 0, 10, 2]], dtype=dt_r)
+ z = sp_fft.ifft(sp_fft.ifftshift(inp, axes=1))
+ Ze2_des = xp.asarray([[5, 0, 10, 0, 5], [20, 0, 40, 0, 20],], dtype=dt_c)
+ Zr_des = xp.asarray([[1, 0, 0, 0, 2], [1, 0, 0, 0, 2]], dtype=dt_c)
+
+ kw = dict(bp_in=(-1, 2), residual='all', squared=True)
+ ze2, zr = xp.unstack(envelope(z, axis=1, **kw))
+ ye2T, yrT = xp.unstack(envelope(z.T, axis=0, **kw))
+ Ze2, Ye2, Zr, Yr = (sp_fft.fftshift(sp_fft.fft(z_), axes=1)
+ for z_ in (ze2, ye2T.T, zr, yrT.T))
+
+ self.assert_close(Ze2, Ze2_des, msg="2d envelope calculation error", xp=xp)
+ self.assert_close(Zr, Zr_des, msg="2d residual calculation error", xp=xp)
+ self.assert_close(
+ Ye2, Ze2_des, msg="Transposed 2d envelope calc. error", xp=xp
+ )
+ self.assert_close(Yr, Zr_des, msg="Transposed 2d residual calc. error", xp=xp)
+
+ @skip_xp_backends("jax.numpy", reason="XXX: immutable arrays")
+ @pytest.mark.parametrize('X', [[4, 0, 0, 1, 2], [4, 0, 0, 2, 1, 2]])
+ def test_compare_envelope_hilbert(self, X, xp):
+ """Compare output of `envelope()` and `hilbert()`. """
+ X = xp.asarray(X, dtype=xp.float64)
+ x = sp_fft.irfft(X)
+ e_hil = xp.abs(hilbert(x))
+ e_env = envelope(x, (None, None), residual=None)
+ self.assert_close(e_hil, e_env, msg="Hilbert-Envelope comparison error", xp=xp)
+
+ def test_nyquist(self):
+ """Test behavior when input is a cosine at the Nyquist frequency.
+
+ Resampling even length signals, requires accounting for unpaired bins at the
+ Nyquist frequency (consults the source code of `resample`).
+
+ Since `envelope` excludes the Nyquist frequency from the envelope calculation,
+ only the residues need to be investigated.
+ """
+ x4 = sp_fft.irfft([0, 0, 8]) # = [2, -2, 2, -2]
+ x6 = signal.resample(x4, num=6) # = [2, -1, -1, 2, -1, -1]
+ y6, y6_res = envelope(x4, n_out=6, residual='all') # real-valued case
+ z6, z6_res = envelope(x4 + 0j, n_out=6, residual='all') # complex-valued case
+
+ xp_assert_close(y6, np.zeros(6), atol=1e-12)
+ xp_assert_close(y6_res, x6, atol=1e-12)
+
+ xp_assert_close(z6, np.zeros(6, dtype=z6.dtype), atol=1e-12)
+ xp_assert_close(z6_res, x6.astype(z6.dtype), atol=1e-12)
+
+
+class TestPartialFractionExpansion:
+ @staticmethod
+ def assert_rp_almost_equal(r, p, r_true, p_true, decimal=7):
+ xp = array_namespace(r, p)
+ r_true = xp.asarray(r_true)
+ p_true = xp.asarray(p_true)
+
+ distance = xp.hypot(abs(p[:, None] - p_true),
+ abs(r[:, None] - r_true))
+
+ rows, cols = linear_sum_assignment(_xp_copy_to_numpy(distance))
+ assert_almost_equal(p[rows], p_true[cols], decimal=decimal)
+ assert_almost_equal(r[rows], r_true[cols], decimal=decimal)
+
+ @skip_xp_backends(np_only=True)
+ def test_compute_factors(self, xp):
+ factors, poly = _compute_factors([1, 2, 3], [3, 2, 1])
+ assert len(factors) == 3
+ assert_almost_equal(factors[0], np.poly([2, 2, 3]))
+ assert_almost_equal(factors[1], np.poly([1, 1, 1, 3]))
+ assert_almost_equal(factors[2], np.poly([1, 1, 1, 2, 2]))
+ assert_almost_equal(poly, np.poly([1, 1, 1, 2, 2, 3]))
+
+ factors, poly = _compute_factors([1, 2, 3], [3, 2, 1],
+ include_powers=True)
+ assert len(factors) == 6
+ assert_almost_equal(factors[0], np.poly([1, 1, 2, 2, 3]))
+ assert_almost_equal(factors[1], np.poly([1, 2, 2, 3]))
+ assert_almost_equal(factors[2], np.poly([2, 2, 3]))
+ assert_almost_equal(factors[3], np.poly([1, 1, 1, 2, 3]))
+ assert_almost_equal(factors[4], np.poly([1, 1, 1, 3]))
+ assert_almost_equal(factors[5], np.poly([1, 1, 1, 2, 2]))
+ assert_almost_equal(poly, np.poly([1, 1, 1, 2, 2, 3]))
+
+ @skip_xp_backends(np_only=True)
+ def test_group_poles(self, xp):
+ unique, multiplicity = _group_poles(
+ [1.0, 1.001, 1.003, 2.0, 2.003, 3.0], 0.1, 'min')
+ xp_assert_close(unique, [1.0, 2.0, 3.0])
+ xp_assert_close(multiplicity, [3, 2, 1])
+
+ @make_xp_test_case(residue)
+ def test_residue_general(self, xp):
+ # Test are taken from issue #4464, note that poles in scipy are
+ # in increasing by absolute value order, opposite to MATLAB.
+ r, p, k = residue(xp.asarray([5, 3, -2, 7]), xp.asarray([-4, 0, 8, 3]))
+ assert_almost_equal(r, xp.asarray([1.3320, -0.6653, -1.4167]), decimal=4)
+ assert_almost_equal(p, xp.asarray([-0.4093, -1.1644, 1.5737]), decimal=4)
+ assert_almost_equal(k, xp.asarray([-1.2500]), decimal=4)
+
+ r, p, k = residue(xp.asarray([-4, 8]), xp.asarray([1, 6, 8]))
+ assert_almost_equal(r, xp.asarray([8, -12]))
+ assert_almost_equal(p, xp.asarray([-2, -4]))
+ assert k.size == 0
+
+ r, p, k = residue(xp.asarray([4, 1]), xp.asarray([1, -1, -2]))
+ assert_almost_equal(r, xp.asarray([1, 3]))
+ assert_almost_equal(p, xp.asarray([-1, 2]))
+ assert k.size == 0
+
+ r, p, k = residue(xp.asarray([4, 3]),
+ xp.asarray([2, -3.4, 1.98, -0.406]))
+ self.assert_rp_almost_equal(
+ r, p, [-18.125 - 13.125j, -18.125 + 13.125j, 36.25],
+ [0.5 - 0.2j, 0.5 + 0.2j, 0.7])
+ assert k.size == 0
+
+ r, p, k = residue(xp.asarray([2, 1]), xp.asarray([1, 5, 8, 4]))
+ self.assert_rp_almost_equal(r, p, [-1, 1, 3],
+ [-1, -2, -2])
+ assert k.size == 0
+
+ r, p, k = residue(xp.asarray([3, -1.1, 0.88, -2.396, 1.348]),
+ xp.asarray([1, -0.7, -0.14, 0.048]))
+ assert_almost_equal(r, xp.asarray([-3, 4, 1]))
+ assert_almost_equal(p, xp.asarray([0.2, -0.3, 0.8]))
+ assert_almost_equal(k, xp.asarray([3, 1]))
+
+ r, p, k = residue(xp.asarray([1]), xp.asarray([1, 2, -3]))
+ assert_almost_equal(r, xp.asarray([0.25, -0.25]))
+ assert_almost_equal(p, xp.asarray([1, -3]))
+ assert k.size == 0
+
+ r, p, k = residue(xp.asarray([1, 0, -5]), xp.asarray([1, 0, 0, 0, -1]))
+ self.assert_rp_almost_equal(r, p,
+ [1, 1.5j, -1.5j, -1],
+ [-1, -1j, 1j, 1])
+ assert k.size == 0
+
+ r, p, k = residue(xp.asarray([3, 8, 6]), xp.asarray([1, 3, 3, 1]))
+ self.assert_rp_almost_equal(r, p, [1, 2, 3],
+ [-1, -1, -1])
+ assert k.size == 0
+
+ r, p, k = residue(xp.asarray([3, -1]), xp.asarray([1, -3, 2]))
+ assert_almost_equal(r, xp.asarray([-2, 5]))
+ assert_almost_equal(p, xp.asarray([1, 2]))
+ assert k.size == 0
+
+ r, p, k = residue(xp.asarray([2, 3, -1]), xp.asarray([1, -3, 2]))
+ assert_almost_equal(r, xp.asarray([-4, 13]))
+ assert_almost_equal(p, xp.asarray([1, 2]))
+ assert_almost_equal(k, xp.asarray([2]))
+
+ r, p, k = residue(xp.asarray([7, 2, 3, -1]), xp.asarray([1, -3, 2]))
+ assert_almost_equal(r, xp.asarray([-11, 69]))
+ assert_almost_equal(p, xp.asarray([1, 2]))
+ assert_almost_equal(k, xp.asarray([7, 23]))
+
+ r, p, k = residue(xp.asarray([2, 3, -1]), xp.asarray([1, -3, 4, -2]))
+ self.assert_rp_almost_equal(r, p, [4, -1 + 3.5j, -1 - 3.5j],
+ [1, 1 - 1j, 1 + 1j])
+ assert k.size == 0
+
+ @make_xp_test_case(residue)
+ def test_residue_leading_zeros(self, xp):
+ # Leading zeros in numerator or denominator must not affect the answer.
+ r0, p0, k0 = residue(xp.asarray([5, 3, -2, 7]), xp.asarray([-4, 0, 8, 3]))
+ r1, p1, k1 = residue(xp.asarray([0, 5, 3, -2, 7]), xp.asarray([-4, 0, 8, 3]))
+ r2, p2, k2 = residue(xp.asarray([5, 3, -2, 7]), xp.asarray([0, -4, 0, 8, 3]))
+ r3, p3, k3 = residue(xp.asarray([0, 0, 5, 3, -2, 7]),
+ xp.asarray([0, 0, 0, -4, 0, 8, 3]))
+ assert_almost_equal(r0, r1)
+ assert_almost_equal(r0, r2)
+ assert_almost_equal(r0, r3)
+ assert_almost_equal(p0, p1)
+ assert_almost_equal(p0, p2)
+ assert_almost_equal(p0, p3)
+ assert_almost_equal(k0, k1)
+ assert_almost_equal(k0, k2)
+ assert_almost_equal(k0, k3)
+
+ @make_xp_test_case(residue)
+ def test_residue_degenerate(self, xp):
+ # Several tests for zero numerator and denominator.
+ r, p, k = residue(xp.asarray([0, 0]), xp.asarray([1, 6, 8]))
+ assert_almost_equal(r, xp.asarray([0, 0]))
+ assert_almost_equal(p, xp.asarray([-2, -4]))
+ assert k.size == 0
+
+ r, p, k = residue(xp.asarray(0), xp.asarray(1))
+ assert r.size == 0
+ assert p.size == 0
+ assert k.size == 0
+
+ with pytest.raises(ValueError, match="Denominator `a` is zero."):
+ residue(1, 0)
+
+ @make_xp_test_case(residuez)
+ def test_residuez_general(self, xp):
+ r, p, k = residuez(xp.asarray([1, 6, 6, 2]),
+ xp.asarray([1, -(2 + 1j), (1 + 2j), -1j]))
+ self.assert_rp_almost_equal(r, p, [-2+2.5j, 7.5+7.5j, -4.5-12j],
+ [1j, 1, 1])
+ assert_almost_equal(k, xp.asarray([2j]))
+
+ r, p, k = residuez(xp.asarray([1, 2, 1]), xp.asarray([1, -1, 0.3561]))
+ self.assert_rp_almost_equal(r, p,
+ [-0.9041 - 5.9928j, -0.9041 + 5.9928j],
+ [0.5 + 0.3257j, 0.5 - 0.3257j],
+ decimal=4)
+ assert_almost_equal(k, xp.asarray([2.8082]), decimal=4)
+
+ r, p, k = residuez(xp.asarray([1, -1]), xp.asarray([1, -5, 6]))
+ assert_almost_equal(r, xp.asarray([-1, 2]))
+ assert_almost_equal(p, xp.asarray([2, 3]))
+ assert k.size == 0
+
+ r, p, k = residuez(xp.asarray([2, 3, 4]), xp.asarray([1, 3, 3, 1]))
+ self.assert_rp_almost_equal(r, p, [4, -5, 3], [-1, -1, -1])
+ assert k.size == 0
+
+ r, p, k = residuez(xp.asarray([1, -10, -4, 4]), xp.asarray([2, -2, -4]))
+ assert_almost_equal(r, xp.asarray([0.5, -1.5]))
+ assert_almost_equal(p, xp.asarray([-1, 2]))
+ assert_almost_equal(k, xp.asarray([1.5, -1]))
+
+ r, p, k = residuez(xp.asarray([18]), xp.asarray([18, 3, -4, -1]))
+ self.assert_rp_almost_equal(r, p,
+ [0.36, 0.24, 0.4], [0.5, -1/3, -1/3])
+ assert k.size == 0
+
+ r, p, k = residuez(xp.asarray([2, 3]),
+ xp.asarray(np.polymul([1, -1/2], [1, 1/4])))
+ assert_almost_equal(r, xp.asarray([-10/3, 16/3]))
+ assert_almost_equal(p, xp.asarray([-0.25, 0.5]))
+ assert k.size == 0
+
+ r, p, k = residuez(xp.asarray([1, -2, 1]), xp.asarray([1, -1]))
+ assert_almost_equal(r, xp.asarray([0]))
+ assert_almost_equal(p, xp.asarray([1]))
+ assert_almost_equal(k, xp.asarray([1, -1]))
+
+ r, p, k = residuez(xp.asarray(1), xp.asarray([1, -1j]))
+ assert_almost_equal(r, xp.asarray([1]))
+ assert_almost_equal(p, xp.asarray([1j]))
+ assert k.size == 0
+
+ r, p, k = residuez(xp.asarray(1), xp.asarray([1, -1, 0.25]))
+ assert_almost_equal(r, xp.asarray([0, 1]))
+ assert_almost_equal(p, xp.asarray([0.5, 0.5]))
+ assert k.size == 0
+
+ r, p, k = residuez(xp.asarray(1), xp.asarray([1, -0.75, .125]))
+ assert_almost_equal(r, xp.asarray([-1, 2]))
+ assert_almost_equal(p, xp.asarray([0.25, 0.5]))
+ assert k.size == 0
+
+ r, p, k = residuez(xp.asarray([1, 6, 2]), xp.asarray([1, -2, 1]))
+ assert_almost_equal(r, xp.asarray([-10, 9]))
+ assert_almost_equal(p, xp.asarray([1, 1]))
+ assert_almost_equal(k, xp.asarray([2]))
+
+ r, p, k = residuez(xp.asarray([6, 2]), xp.asarray([1, -2, 1]))
+ assert_almost_equal(r, xp.asarray([-2, 8]))
+ assert_almost_equal(p, xp.asarray([1, 1]))
+ assert k.size == 0
+
+ r, p, k = residuez(xp.asarray([1, 6, 6, 2]), xp.asarray([1, -2, 1]))
+ assert_almost_equal(r, xp.asarray([-24, 15]))
+ assert_almost_equal(p, xp.asarray([1, 1]))
+ assert_almost_equal(k, xp.asarray([10, 2]))
+
+ r, p, k = residuez(xp.asarray([1, 0, 1]), xp.asarray([1, 0, 0, 0, 0, -1]))
+ self.assert_rp_almost_equal(r, p,
+ [0.2618 + 0.1902j, 0.2618 - 0.1902j,
+ 0.4, 0.0382 - 0.1176j, 0.0382 + 0.1176j],
+ [-0.8090 + 0.5878j, -0.8090 - 0.5878j,
+ 1.0, 0.3090 + 0.9511j, 0.3090 - 0.9511j],
+ decimal=4)
+ assert k.size == 0
+
+ @make_xp_test_case(residuez)
+ def test_residuez_trailing_zeros(self, xp):
+ # Trailing zeros in numerator or denominator must not affect the
+ # answer.
+ r0, p0, k0 = residuez(xp.asarray([5, 3, -2, 7]),
+ xp.asarray([-4, 0, 8, 3]))
+ r1, p1, k1 = residuez(xp.asarray([5, 3, -2, 7, 0]),
+ xp.asarray([-4, 0, 8, 3]))
+ r2, p2, k2 = residuez(xp.asarray([5, 3, -2, 7]),
+ xp.asarray([-4, 0, 8, 3, 0]))
+ r3, p3, k3 = residuez(xp.asarray([5, 3, -2, 7, 0, 0]),
+ xp.asarray([-4, 0, 8, 3, 0, 0, 0]))
+ assert_almost_equal(r0, r1)
+ assert_almost_equal(r0, r2)
+ assert_almost_equal(r0, r3)
+ assert_almost_equal(p0, p1)
+ assert_almost_equal(p0, p2)
+ assert_almost_equal(p0, p3)
+ assert_almost_equal(k0, k1)
+ assert_almost_equal(k0, k2)
+ assert_almost_equal(k0, k3)
+
+ @make_xp_test_case(residuez)
+ def test_residuez_degenerate(self, xp):
+ r, p, k = residuez(xp.asarray([0, 0]), xp.asarray([1, 6, 8]))
+ assert_almost_equal(r, xp.asarray([0, 0]))
+ assert_almost_equal(p, xp.asarray([-2, -4]))
+ assert k.size == 0
+
+ r, p, k = residuez(xp.asarray(0), xp.asarray(1))
+ assert r.size == 0
+ assert p.size == 0
+ assert k.size == 0
+
+ with pytest.raises(ValueError, match="Denominator `a` is zero."):
+ residuez(xp.asarray(1), xp.asarray(0))
+
+ with pytest.raises(ValueError,
+ match="First coefficient of determinant `a` must "
+ "be non-zero."):
+ residuez(xp.asarray(1), xp.asarray([0, 1, 2, 3]))
+
+ @make_xp_test_case(invres, invresz)
+ def test_inverse_unique_roots_different_rtypes(self, xp):
+ # This test was inspired by github issue 2496.
+ r = xp.asarray([3 / 10, -1 / 6, -2 / 15])
+ p = xp.asarray([0, -2, -5])
+ k = xp.asarray([])
+ b_expected = xp.asarray([0.0, 1, 3])
+ a_expected = xp.asarray([1, 7, 10, 0])
+
+ # With the default tolerance, the rtype does not matter
+ # for this example.
+ for rtype in ('avg', 'mean', 'min', 'minimum', 'max', 'maximum'):
+ b, a = invres(r, p, k, rtype=rtype)
+ xp_assert_close(b, b_expected, atol=5e-16)
+ xp_assert_close(a, a_expected, check_dtype=False, atol=5e-16)
+
+ b, a = invresz(r, p, k, rtype=rtype)
+ xp_assert_close(b, b_expected, atol=5e-16)
+ xp_assert_close(a, a_expected, check_dtype=False, atol=5e-16)
+
+ @make_xp_test_case(invres, invresz)
+ def test_inverse_repeated_roots_different_rtypes(self, xp):
+ r = xp.asarray([3 / 20, -7 / 36, -1 / 6, 2 / 45])
+ p = xp.asarray([0, -2, -2, -5])
+ k = xp.asarray([])
+ b_expected = xp.asarray([0.0, 0, 1, 3])
+ b_expected_z = xp.asarray([-1/6, -2/3, 11/6, 3])
+ a_expected = xp.asarray([1, 9, 24, 20, 0])
+
+ for rtype in ('avg', 'mean', 'min', 'minimum', 'max', 'maximum'):
+ b, a = invres(r, p, k, rtype=rtype)
+ xp_assert_close(b, b_expected, atol=1e-14)
+ xp_assert_close(a, a_expected, check_dtype=False)
+
+ b, a = invresz(r, p, k, rtype=rtype)
+ xp_assert_close(b, b_expected_z, atol=1e-14)
+ xp_assert_close(a, a_expected, check_dtype=False)
+
+ @make_xp_test_case(invres, invresz)
+ def test_inverse_bad_rtype(self, xp):
+ r = xp.asarray([3 / 20, -7 / 36, -1 / 6, 2 / 45])
+ p = xp.asarray([0, -2, -2, -5])
+ k = xp.asarray([])
+ with pytest.raises(ValueError, match="`rtype` must be one of"):
+ invres(r, p, k, rtype='median')
+ with pytest.raises(ValueError, match="`rtype` must be one of"):
+ invresz(r, p, k, rtype='median')
+
+ @make_xp_test_case(invresz)
+ def test_invresz_one_coefficient_bug(self, xp):
+ # Regression test for issue in gh-4646.
+ r = xp.asarray([1])
+ p = xp.asarray([2])
+ k = xp.asarray([0])
+ b, a = invresz(r, p, k)
+ xp_assert_close(b, xp.asarray([1]))
+ xp_assert_close(a, xp.asarray([1.0, -2.0]))
+
+ @make_xp_test_case(invres)
+ def test_invres(self, xp):
+ b, a = invres(xp.asarray([1]), xp.asarray([1]), xp.asarray([]))
+ assert_almost_equal(b, xp.asarray([1]))
+ assert_almost_equal(a, xp.asarray([1, -1]))
+
+ b, a = invres(xp.asarray([1 - 1j, 2, 0.5 - 3j]),
+ xp.asarray([1, 0.5j, 1 + 1j]), xp.asarray([]))
+ assert_almost_equal(b, xp.asarray([3.5 - 4j, -8.5 + 0.25j, 3.5 + 3.25j]))
+ assert_almost_equal(a, xp.asarray([1, -2 - 1.5j, 0.5 + 2j, 0.5 - 0.5j]))
+
+ b, a = invres(xp.asarray([0.5, 1]), xp.asarray([1 - 1j, 2 + 2j]),
+ xp.asarray([1, 2, 3]))
+ assert_almost_equal(b, xp.asarray([1, -1 - 1j, 1 - 2j, 0.5 - 3j, 10]))
+ assert_almost_equal(a, xp.asarray([1, -3 - 1j, 4]))
+
+ b, a = invres(xp.asarray([-1, 2, 1j, 3 - 1j, 4, -2]),
+ xp.asarray([-1, 2 - 1j, 2 - 1j, 3, 3, 3]), xp.asarray([]))
+ assert_almost_equal(b,
+ xp.asarray([4 - 1j, -28 + 16j, 40 - 62j, 100 + 24j,
+ -292 + 219j, 192 - 268j]))
+ assert_almost_equal(a,
+ xp.asarray([1, -12 + 2j, 53 - 20j, -96 + 68j, 27 - 72j,
+ 108 - 54j, -81 + 108j]))
+
+ b, a = invres(xp.asarray([-1, 1j]), xp.asarray([1, 1]), xp.asarray([1, 2]))
+ assert_almost_equal(b, xp.asarray([1, 0, -4, 3 + 1j]))
+ assert_almost_equal(a, xp.asarray([1, -2, 1]))
+
+ @make_xp_test_case(invresz)
+ def test_invresz(self, xp):
+ b, a = invresz(xp.asarray([1]), xp.asarray([1]), xp.asarray([]))
+ assert_almost_equal(b, xp.asarray([1]))
+ assert_almost_equal(a, xp.asarray([1, -1]))
+
+ b, a = invresz(xp.asarray([1 - 1j, 2, 0.5 - 3j]),
+ xp.asarray([1, 0.5j, 1 + 1j]), xp.asarray([]))
+ assert_almost_equal(b, xp.asarray([3.5 - 4j, -8.5 + 0.25j, 3.5 + 3.25j]))
+ assert_almost_equal(a, xp.asarray([1, -2 - 1.5j, 0.5 + 2j, 0.5 - 0.5j]))
+
+ b, a = invresz(xp.asarray([0.5, 1]),
+ xp.asarray([1 - 1j, 2 + 2j]),
+ xp.asarray([1, 2, 3]))
+ assert_almost_equal(b, xp.asarray([2.5, -3 - 1j, 1 - 2j, -1 - 3j, 12]))
+ assert_almost_equal(a, xp.asarray([1, -3 - 1j, 4]))
+
+ b, a = invresz(xp.asarray([-1, 2, 1j, 3 - 1j, 4, -2]),
+ xp.asarray([-1, 2 - 1j, 2 - 1j, 3, 3, 3]),
+ xp.asarray([]))
+ assert_almost_equal(b,
+ xp.asarray([6, -50 + 11j, 100 - 72j, 80 + 58j,
+ -354 + 228j, 234 - 297j]))
+ assert_almost_equal(a,
+ xp.asarray([1, -12 + 2j, 53 - 20j, -96 + 68j, 27 - 72j,
+ 108 - 54j, -81 + 108j]))
+
+ b, a = invresz(xp.asarray([-1, 1j]),
+ xp.asarray([1, 1]),
+ xp.asarray([1, 2]))
+ assert_almost_equal(b, xp.asarray([1j, 1, -3, 2]))
+ assert_almost_equal(a, xp.asarray([1, -2, 1]))
+
+ @skip_xp_backends(np_only=True)
+ @make_xp_test_case(invres, invresz)
+ def test_inverse_scalar_arguments(self, xp):
+ b, a = invres(1, 1, 1)
+ assert_almost_equal(b, [1, 0])
+ assert_almost_equal(a, [1, -1])
+
+ b, a = invresz(1, 1, 1)
+ assert_almost_equal(b, [2, -1])
+ assert_almost_equal(a, [1, -1])
+
+
+@make_xp_test_case(vectorstrength)
+class TestVectorstrength:
+
+ def test_single_1dperiod(self, xp):
+ events = xp.asarray([.5])
+ period = 5.
+ targ_strength = 1.
+ targ_phase = .1
+
+ strength, phase = vectorstrength(events, period)
+
+ assert strength.ndim == 0
+ assert phase.ndim == 0
+
+ assert math.isclose(strength, targ_strength, abs_tol=1.5e-7)
+ assert math.isclose(phase, 2 * math.pi * targ_phase, abs_tol=1.5e-7)
+
+ @xfail_xp_backends('torch', reason="phase modulo 2*pi")
+ def test_single_2dperiod(self, xp):
+ events = xp.asarray([.5])
+ period = xp.asarray([1, 2, 5.])
+ targ_strength = xp.asarray([1.] * 3)
+ targ_phase = xp.asarray([.5, .25, .1])
+
+ strength, phase = vectorstrength(events, period)
+
+ assert strength.ndim == 1
+ assert phase.ndim == 1
+ assert_array_almost_equal(strength, targ_strength)
+ assert_almost_equal(phase, 2 * xp.pi * targ_phase)
+
+ def test_equal_1dperiod(self, xp):
+ events = xp.asarray([.25, .25, .25, .25, .25, .25])
+ period = 2
+ targ_strength = 1.
+ targ_phase = .125
+
+ strength, phase = vectorstrength(events, period)
+
+ assert strength.ndim == 0
+ assert phase.ndim == 0
+
+ assert math.isclose(strength, targ_strength, abs_tol=1.5e-7)
+ assert math.isclose(phase, 2 * math.pi * targ_phase, abs_tol=1.5e-7)
+
+ def test_equal_2dperiod(self, xp):
+ events = xp.asarray([.25, .25, .25, .25, .25, .25])
+ period = xp.asarray([1, 2, ])
+ targ_strength = xp.asarray([1.] * 2)
+ targ_phase = xp.asarray([.25, .125])
+
+ strength, phase = vectorstrength(events, period)
+
+ assert strength.ndim == 1
+ assert phase.ndim == 1
+ assert_almost_equal(strength, targ_strength)
+ assert_almost_equal(phase, 2 * xp.pi * targ_phase)
+
+ def test_spaced_1dperiod(self, xp):
+ events = xp.asarray([.1, 1.1, 2.1, 4.1, 10.1])
+ period = 1
+ targ_strength = 1.
+ targ_phase = .1
+
+ strength, phase = vectorstrength(events, period)
+
+ assert strength.ndim == 0
+ assert phase.ndim == 0
+
+ assert math.isclose(strength, targ_strength, abs_tol=1.5e-7)
+ assert math.isclose(phase, 2 * math.pi * targ_phase, abs_tol=1.5e-6)
+
+ def test_spaced_2dperiod(self, xp):
+ events = xp.asarray([.1, 1.1, 2.1, 4.1, 10.1])
+ period = xp.asarray([1, .5])
+ targ_strength = xp.asarray([1.] * 2)
+ targ_phase = xp.asarray([.1, .2])
+
+ strength, phase = vectorstrength(events, period)
+
+ assert strength.ndim == 1
+ assert phase.ndim == 1
+ assert_almost_equal(strength, targ_strength)
+ rtol_kw = {'rtol': 2e-6} if xp_default_dtype(xp) == xp.float32 else {}
+ xp_assert_close(phase, 2 * xp.pi * targ_phase, **rtol_kw)
+
+ def test_partial_1dperiod(self, xp):
+ events = xp.asarray([.25, .5, .75])
+ period = 1
+ targ_strength = 1. / 3.
+ targ_phase = .5
+
+ strength, phase = vectorstrength(events, period)
+
+ assert strength.ndim == 0
+ assert phase.ndim == 0
+
+ assert math.isclose(strength, targ_strength)
+ assert math.isclose(phase, 2 * math.pi * targ_phase)
+
+
+ @xfail_xp_backends("torch", reason="phase modulo 2*pi")
+ def test_partial_2dperiod(self, xp):
+ events = xp.asarray([.25, .5, .75])
+ period = xp.asarray([1., 1., 1., 1.])
+ targ_strength = xp.asarray([1. / 3.] * 4)
+ targ_phase = xp.asarray([.5, .5, .5, .5])
+
+ strength, phase = vectorstrength(events, period)
+
+ assert strength.ndim == 1
+ assert phase.ndim == 1
+ assert_almost_equal(strength, targ_strength)
+ assert_almost_equal(phase, 2 * xp.pi * targ_phase)
+
+ def test_opposite_1dperiod(self, xp):
+ events = xp.asarray([0, .25, .5, .75])
+ period = 1.
+ targ_strength = 0
+
+ strength, phase = vectorstrength(events, period)
+
+ assert strength.ndim == 0
+ assert phase.ndim == 0
+ assert math.isclose(strength, targ_strength, abs_tol=1.5e-7)
+
+ def test_opposite_2dperiod(self, xp):
+ events = xp.asarray([0, .25, .5, .75])
+ period = xp.asarray([1.] * 10)
+ targ_strength = xp.asarray([0.] * 10)
+
+ strength, phase = vectorstrength(events, period)
+
+ assert strength.ndim == 1
+ assert phase.ndim == 1
+ assert_almost_equal(strength, targ_strength)
+
+ def test_2d_events_ValueError(self, xp):
+ events = xp.asarray([[1, 2]])
+ period = 1.
+ assert_raises(ValueError, vectorstrength, events, period)
+
+ def test_2d_period_ValueError(self, xp):
+ events = 1.
+ period = xp.asarray([[1]])
+ assert_raises(ValueError, vectorstrength, events, period)
+
+ def test_zero_period_ValueError(self, xp):
+ events = 1.
+ period = 0
+ assert_raises(ValueError, vectorstrength, events, period)
+
+ def test_negative_period_ValueError(self, xp):
+ events = 1.
+ period = -1
+ assert_raises(ValueError, vectorstrength, events, period)
+
+
+# XXX: restore testing on CuPy, where possible. Multiple issues in this test:
+# 1. _zi functions deliberately incompatible in cupy
+# (https://github.com/scipy/scipy/pull/21713#issuecomment-2417494443)
+# 2. a CuPy issue to be fixed in 14.0 only
+# (https://github.com/cupy/cupy/pull/8677)
+# 3. an issue with CuPy's __array__ not numpy-2.0 compatible
+@skip_xp_backends(cpu_only=True)
+@make_xp_test_case(sosfilt)
+@pytest.mark.parametrize('dt', ['float32', 'float64', 'complex64', 'complex128'])
+class TestSOSFilt:
+
+ # The test_rank* tests are pulled from _TestLinearFilter
+ @skip_xp_backends('jax.numpy', reason='buffer array is read-only')
+ def test_rank1(self, dt, xp):
+ dt = getattr(xp, dt)
+ x = xp.linspace(0, 5, 6, dtype=dt)
+ b = xp.asarray([1, -1], dtype=dt)
+ a = xp.asarray([0.5, -0.5], dtype=dt)
+
+ # Test simple IIR
+ y_r = xp.asarray([0, 2, 4, 6, 8, 10.], dtype=dt)
+ bb, aa = map(np.asarray, (b, a))
+ sos = tf2sos(bb, aa)
+ sos = xp.asarray(sos) # XXX while tf2sos is numpy only
+ assert_array_almost_equal(sosfilt(sos, x), y_r)
+
+ # Test simple FIR
+ b = xp.asarray([1, 1], dtype=dt)
+ # NOTE: This was changed (rel. to TestLinear...) to add a pole @zero:
+ a = xp.asarray([1, 0], dtype=dt)
+ y_r = xp.asarray([0, 1, 3, 5, 7, 9.], dtype=dt)
+ bb, aa = map(np.asarray, (b, a))
+ sos = tf2sos(bb, aa)
+ sos = xp.asarray(sos) # XXX while tf2sos is numpy only
+ assert_array_almost_equal(sosfilt(sos, x), y_r)
+
+ b = xp.asarray([1.0, 1, 0])
+ a = xp.asarray([1.0, 0, 0])
+ x = xp.ones(8)
+
+ sos = xp.concat((b, a))
+ sos = xp.reshape(sos, (1, 6))
+ y = sosfilt(sos, x)
+ xp_assert_close(y, xp.asarray([1.0, 2, 2, 2, 2, 2, 2, 2]))
+
+ @skip_xp_backends('jax.numpy', reason='buffer array is read-only')
+ def test_rank2(self, dt, xp):
+ dt = getattr(xp, dt)
+ shape = (4, 3)
+ prodshape = math.prod(shape)
+ x = xp.linspace(0, prodshape - 1, prodshape, dtype=dt)
+ x = xp.reshape(x, shape)
+
+ b = xp.asarray([1, -1], dtype=dt)
+ a = xp.asarray([0.5, 0.5], dtype=dt)
+
+ y_r2_a0 = xp.asarray([[0, 2, 4], [6, 4, 2], [0, 2, 4], [6, 4, 2]],
+ dtype=dt)
+
+ y_r2_a1 = xp.asarray([[0, 2, 0], [6, -4, 6], [12, -10, 12],
+ [18, -16, 18]], dtype=dt)
+
+ bb, aa = map(np.asarray, (b, a))
+ sos = tf2sos(bb, aa)
+ sos = xp.asarray(sos) # XXX
+ y = sosfilt(sos, x, axis=0)
+ assert_array_almost_equal(y_r2_a0, y)
+
+ sos = tf2sos(bb, aa)
+ sos = xp.asarray(sos) # XXX
+ y = sosfilt(sos, x, axis=1)
+ assert_array_almost_equal(y_r2_a1, y)
+
+ @skip_xp_backends('jax.numpy', reason='buffer array is read-only')
+ def test_rank3(self, dt, xp):
+ dt = getattr(xp, dt)
+ shape = (4, 3, 2)
+ prodshape = math.prod(shape)
+ x = xp.linspace(0, prodshape - 1, prodshape)
+ x = xp.reshape(x, shape)
+
+ b = xp.asarray([1, -1], dtype=dt)
+ a = xp.asarray([0.5, 0.5], dtype=dt)
+
+ # Test last axis
+ bb, aa = map(np.asarray, (b, a)) # XXX until tf2sos is array api compatible
+ sos = tf2sos(bb, aa)
+ sos = xp.asarray(sos) # XXX
+ y = sosfilt(sos, x)
+ for i in range(x.shape[0]):
+ for j in range(x.shape[1]):
+ assert_array_almost_equal(y[i, j, ...], lfilter(b, a, x[i, j, ...]))
+
+ def _get_ab_sos(self, xp):
+ b1, a1 = signal.butter(2, 0.25, 'low')
+ b2, a2 = signal.butter(2, 0.75, 'low')
+ b3, a3 = signal.butter(2, 0.75, 'low')
+ b = np.convolve(np.convolve(b1, b2), b3)
+ a = np.convolve(np.convolve(a1, a2), a3)
+ sos = np.array((np.r_[b1, a1], np.r_[b2, a2], np.r_[b3, a3]))
+
+ a, b, sos = map(xp.asarray, (a, b, sos))
+ return a, b, sos
+
+ @skip_xp_backends('jax.numpy', reason='item assignment')
+ def test_initial_conditions(self, dt, xp):
+ a, b, sos = self._get_ab_sos(xp)
+
+ x = np.random.rand(50).astype(dt)
+ x = xp.asarray(x)
+
+ dt = getattr(xp, dt)
+
+ # Stopping filtering and continuing
+ y_true, zi = lfilter(b, a, x[:20], zi=xp.zeros(6))
+ y_true = xp.concat((y_true, lfilter(b, a, x[20:], zi=zi)[0]))
+ xp_assert_close(y_true, lfilter(b, a, x))
+
+ y_sos, zi = sosfilt(sos, x[:20], zi=xp.zeros((3, 2)))
+ y_sos = xp.concat((y_sos, sosfilt(sos, x[20:], zi=zi)[0]))
+ xp_assert_close(y_true, y_sos)
+
+ # Use a step function
+ zi = sosfilt_zi(sos)
+ x = xp.ones(8, dtype=dt)
+ y, zf = sosfilt(sos, x, zi=zi)
+
+ xp_assert_close(y, xp.ones(8), check_dtype=False)
+ xp_assert_close(zf, zi, check_dtype=False)
+
+ @skip_xp_backends('jax.numpy', reason='item assignment')
+ @skip_xp_backends('array_api_strict', reason='fancy indexing not supported')
+ def test_initial_conditions_2(self, dt, xp):
+ dt = getattr(xp, dt)
+ x = xp.ones(8, dtype=dt)
+
+ _, _, sos = self._get_ab_sos(xp)
+ zi = sosfilt_zi(sos)
+
+ # Initial condition shape matching
+ x = xp.reshape(x, (1, 1) + x.shape) # 3D
+ with pytest.raises(ValueError):
+ sosfilt(sos, x, zi=zi)
+
+ zi_nd = xp_copy(zi, xp=xp)
+ zi_nd = xp.reshape(zi_nd, (zi.shape[0], 1, 1, zi.shape[-1]))
+
+ with pytest.raises(ValueError):
+ sosfilt(sos, x, zi=zi_nd[:, :, :, [0, 1, 1]])
+
+ y, zf = sosfilt(sos, x, zi=zi_nd)
+ xp_assert_close(y[0, 0], xp.ones(8), check_dtype=False)
+ xp_assert_close(zf[:, 0, 0, :], zi, check_dtype=False)
+
+ @skip_xp_backends('jax.numpy', reason='item assignment')
+ def test_initial_conditions_3d_axis1(self, dt, xp):
+ # Test the use of zi when sosfilt is applied to axis 1 of a 3-d input.
+
+ # Input array is x.
+ x = np.random.RandomState(159).randint(0, 5, size=(2, 15, 3))
+ x = x.astype(dt)
+ x = xp.asarray(x)
+
+ # Design a filter in ZPK format and convert to SOS
+ zpk = signal.butter(6, 0.35, output='zpk')
+ sos = zpk2sos(*zpk)
+ sos = xp.asarray(sos) # XXX while zpk2sos is numpy-only
+
+ nsections = sos.shape[0]
+
+ # Filter along this axis.
+ axis = 1
+
+ # Initial conditions, all zeros.
+ shp = list(x.shape)
+ shp[axis] = 2
+ shp = tuple([nsections] + shp)
+ z0 = xp.zeros(shp)
+
+ # Apply the filter to x.
+ yf, zf = sosfilt(sos, x, axis=axis, zi=z0)
+
+ # Apply the filter to x in two stages.
+ y1, z1 = sosfilt(sos, x[:, :5, :], axis=axis, zi=z0)
+ y2, z2 = sosfilt(sos, x[:, 5:, :], axis=axis, zi=z1)
+
+ # y should equal yf, and z2 should equal zf.
+ y = xp.concat((y1, y2), axis=axis)
+ xp_assert_close(y, yf, rtol=1e-10, atol=1e-13)
+ xp_assert_close(z2, zf, rtol=1e-10, atol=1e-13)
+
+ # let's try the "step" initial condition
+ zi = sosfilt_zi(sos)
+ zi = xp.reshape(zi, (nsections, 1, 2, 1))
+ zi = zi * x[:, 0:1, :]
+ y = sosfilt(sos, x, axis=axis, zi=zi)[0]
+ # check it against the TF form
+ b, a = zpk2tf(*zpk)
+ b, a = xp.asarray(b), xp.asarray(a) # XXX while zpk2tf is numpy-only
+
+ zi = lfilter_zi(b, a)
+ zi = xp.reshape(zi, (1, xp_size(zi), 1))
+ zi = zi * x[:, 0:1, :]
+ y_tf = lfilter(b, a, x, axis=axis, zi=zi)[0]
+ xp_assert_close(y, y_tf, rtol=1e-10, atol=1e-13)
+
+ @skip_xp_backends('torch', reason='issues a RuntimeWarning')
+ @skip_xp_backends('jax.numpy', reason='item assignment')
+ def test_bad_zi_shape(self, dt, xp):
+ dt = getattr(xp, dt)
+ # The shape of zi is checked before using any values in the
+ # arguments, so np.empty is fine for creating the arguments.
+ x = xp.empty((3, 15, 3), dtype=dt)
+ sos = xp.zeros((4, 6))
+ zi = xp.empty((4, 3, 3, 2)) # Correct shape is (4, 3, 2, 3)
+ with pytest.raises(ValueError, match='should be all ones'):
+ sosfilt(sos, x, zi=zi, axis=1)
+ sos[:, 3] = 1.
+ with pytest.raises(ValueError, match='Invalid zi shape'):
+ sosfilt(sos, x, zi=zi, axis=1)
+
+ @skip_xp_backends('jax.numpy', reason='item assignment')
+ def test_sosfilt_zi(self, dt, xp):
+ dt = getattr(xp, dt)
+ sos = signal.butter(6, 0.2, output='sos')
+ sos = xp.asarray(sos) # XXX while butter is np-only
+ zi = sosfilt_zi(sos)
+
+ y, zf = sosfilt(sos, xp.ones(40, dtype=dt), zi=zi)
+ xp_assert_close(zf, zi, rtol=1e-13, check_dtype=False)
+
+ # Expected steady state value of the step response of this filter:
+ ss = xp.prod(xp.sum(sos[:, :3], axis=-1) / xp.sum(sos[:, 3:], axis=-1))
+ xp_assert_close(y, ss * xp.ones_like(y), rtol=1e-13)
+
+ @skip_xp_backends(np_only=True)
+ def test_sosfilt_zi_2(self, dt, xp):
+ # zi as array-like
+ dt = getattr(xp, dt)
+ sos = signal.butter(6, 0.2, output='sos')
+ sos = xp.asarray(sos) # XXX while butter is np-only
+ zi = sosfilt_zi(sos)
+
+ _, zf = sosfilt(sos, xp.ones(40, dtype=dt), zi=zi.tolist())
+ xp_assert_close(zf, zi, rtol=1e-13, check_dtype=False)
+
+
+@make_xp_test_case(signal.deconvolve)
+class TestDeconvolve:
+
+ @skip_xp_backends(np_only=True, reason="list inputs are numpy-specific")
+ def test_array_like(self, xp):
+ # From docstring example: with lists
+ original = [0.0, 1, 0, 0, 1, 1, 0, 0]
+ impulse_response = [2, 1]
+ recorded = xp.asarray([0.0, 2, 1, 0, 2, 3, 1, 0, 0])
+ recovered, remainder = signal.deconvolve(recorded, impulse_response)
+ xp_assert_close(recovered, original)
+
+ def test_basic(self, xp):
+ # From docstring example
+ original = xp.asarray([0.0, 1, 0, 0, 1, 1, 0, 0], dtype=xp.float64)
+ impulse_response = xp.asarray([2, 1])
+ recorded = xp.asarray([0.0, 2, 1, 0, 2, 3, 1, 0, 0])
+ recovered, remainder = signal.deconvolve(recorded, impulse_response)
+ xp_assert_close(recovered, original)
+
+ @xfail_xp_backends("cupy", reason="different error message")
+ def test_n_dimensional_signal(self, xp):
+ recorded = xp.asarray([[0, 0], [0, 0]])
+ impulse_response = xp.asarray([0, 0])
+ with pytest.raises(ValueError, match="^Parameter signal must be non-empty"):
+ quotient, remainder = signal.deconvolve(recorded, impulse_response)
+
+ @xfail_xp_backends("cupy", reason="different error message")
+ def test_n_dimensional_divisor(self, xp):
+ recorded = xp.asarray([0, 0])
+ impulse_response = xp.asarray([[0, 0], [0, 0]])
+ with pytest.raises(ValueError, match="^Parameter divisor must be non-empty"):
+ quotient, remainder = signal.deconvolve(recorded, impulse_response)
+
+ def test_divisor_greater_signal(self, xp):
+ """Return signal as `remainder` when ``len(divisior) > len(signal)``. """
+ sig, div = xp.asarray([0, 1, 2]), xp.asarray([0, 1, 2, 4, 5])
+ quotient, remainder = signal.deconvolve(sig, div)
+ xp_assert_equal(remainder, sig)
+ assert xp_size(xp.asarray(quotient)) == 0
+
+
+@make_xp_test_case(detrend)
+class TestDetrend:
+
+ def test_basic(self, xp):
+ detrended = detrend(xp.asarray([1, 2, 3]))
+ detrended_exact = xp.asarray([0, 0, 0])
+ assert_array_almost_equal(detrended, detrended_exact)
+
+ @skip_xp_backends("jax.numpy", reason="overwrite_data not implemented")
+ def test_copy(self, xp):
+ x = xp.asarray([1, 1.2, 1.5, 1.6, 2.4])
+ copy_array = detrend(x, overwrite_data=False)
+ inplace = detrend(x, overwrite_data=True)
+ assert_array_almost_equal(copy_array, inplace)
+
+ @pytest.mark.parametrize('kind', ['linear', 'constant'])
+ @pytest.mark.parametrize('axis', [0, 1, 2])
+ def test_axis(self, axis, kind, xp):
+ data = xp.reshape(xp.arange(5*6*7), (5, 6, 7))
+ detrended = detrend(data, type=kind, axis=axis)
+ assert detrended.shape == data.shape
+
+ def test_bp(self, xp):
+ data = [0, 1, 2] + [5, 0, -5, -10]
+ data = xp.asarray(data)
+ detrended = detrend(data, type='linear', bp=3)
+ xp_assert_close(detrended, xp.zeros_like(detrended), atol=1e-14)
+
+ # repeat with ndim > 1 and axis
+ data = xp.asarray(data)[None, :, None]
+
+ detrended = detrend(data, type="linear", bp=3, axis=1)
+ xp_assert_close(detrended, xp.zeros_like(detrended), atol=1e-14)
+
+ # breakpoint index > shape[axis]: raises
+ with assert_raises(ValueError):
+ detrend(data, type="linear", bp=3)
+
+ @pytest.mark.parametrize('bp', [np.array([0, 2]), [0, 2]])
+ def test_detrend_array_bp(self, bp, xp):
+ # regression test for https://github.com/scipy/scipy/issues/18675
+ rng = np.random.RandomState(12345)
+ x = rng.rand(10)
+ x = xp.asarray(x, dtype=xp_default_dtype(xp))
+ if isinstance(bp, np.ndarray) and not is_jax(xp):
+ # JAX expects a static array for bp, so don't call xp.asarray
+ # for JAX.
+ bp = xp.asarray(bp)
+ else:
+ if not (is_numpy(xp) or is_jax(xp)):
+ pytest.skip("list bp is currently numpy and jax only")
+
+ res = detrend(x, bp=bp)
+ res_scipy_191 = xp.asarray([-4.44089210e-16, -2.22044605e-16,
+ -1.11128506e-01, -1.69470553e-01, 1.14710683e-01, 6.35468419e-02,
+ 3.53533144e-01, -3.67877935e-02, -2.00417675e-02, -1.94362049e-01])
+
+ atol = 3e-7 if xp_default_dtype(xp) == xp.float32 else 1e-14
+ xp_assert_close(res, res_scipy_191, atol=atol)
+
+
+@make_xp_test_case(unique_roots)
+class TestUniqueRoots:
+ def test_real_no_repeat(self, xp):
+ p = xp.asarray([-1.0, -0.5, 0.3, 1.2, 10.0])
+ unique, multiplicity = unique_roots(p)
+ assert_almost_equal(unique, p, decimal=15)
+ xp_assert_equal(multiplicity, xp.ones(len(p), dtype=int))
+
+ def test_real_repeat(self, xp):
+ p = xp.asarray([-1.0, -0.95, -0.89, -0.8, 0.5, 1.0, 1.05])
+
+ unique, multiplicity = unique_roots(p, tol=1e-1, rtype='min')
+ assert_almost_equal(unique, xp.asarray([-1.0, -0.89, 0.5, 1.0]), decimal=15)
+ xp_assert_equal(multiplicity, xp.asarray([2, 2, 1, 2]))
+
+ unique, multiplicity = unique_roots(p, tol=1e-1, rtype='max')
+ assert_almost_equal(unique, xp.asarray([-0.95, -0.8, 0.5, 1.05]), decimal=15)
+ xp_assert_equal(multiplicity, xp.asarray([2, 2, 1, 2]))
+
+ unique, multiplicity = unique_roots(p, tol=1e-1, rtype='avg')
+ assert_almost_equal(unique, xp.asarray([-0.975, -0.845, 0.5, 1.025]),
+ decimal=15)
+ xp_assert_equal(multiplicity, xp.asarray([2, 2, 1, 2]))
+
+ def test_complex_no_repeat(self, xp):
+ p = xp.asarray([-1.0, 1.0j, 0.5 + 0.5j, -1.0 - 1.0j, 3.0 + 2.0j])
+ unique, multiplicity = unique_roots(p)
+ assert_almost_equal(unique, p, decimal=15)
+ xp_assert_equal(multiplicity, xp.ones(len(p), dtype=int))
+
+ def test_complex_repeat(self, xp):
+ p = xp.asarray([-1.0, -1.0 + 0.05j, -0.95 + 0.15j, -0.90 + 0.15j, 0.0,
+ 0.5 + 0.5j, 0.45 + 0.55j])
+
+ unique, multiplicity = unique_roots(p, tol=1e-1, rtype='min')
+ assert_almost_equal(unique,
+ xp.asarray([-1.0, -0.95 + 0.15j, 0.0, 0.45 + 0.55j]),
+ decimal=15)
+ xp_assert_equal(multiplicity, xp.asarray([2, 2, 1, 2]))
+
+ unique, multiplicity = unique_roots(p, tol=1e-1, rtype='max')
+ assert_almost_equal(
+ unique,
+ xp.asarray(
+ [-1.0 + 0.05j, -0.90 + 0.15j, 0.0, 0.5 + 0.5j]
+ ),
+ decimal=15,
+ )
+ xp_assert_equal(multiplicity, xp.asarray([2, 2, 1, 2]))
+
+ unique, multiplicity = unique_roots(p, tol=1e-1, rtype='avg')
+ assert_almost_equal(
+ unique,
+ xp.asarray([-1.0 + 0.025j, -0.925 + 0.15j, 0.0, 0.475 + 0.525j]),
+ decimal=15,
+ )
+ xp_assert_equal(multiplicity, xp.asarray([2, 2, 1, 2]))
+
+ def test_gh_4915(self, xp):
+ p = xp.asarray(np.roots(np.convolve(np.ones(5), np.ones(5))))
+ true_roots = xp.asarray(
+ [-(-1)**(1/5), (-1)**(4/5), -(-1)**(3/5), (-1)**(2/5)]
+ )
+
+ unique, multiplicity = unique_roots(p)
+ unique = xp.sort(unique)
+
+ assert_almost_equal(xp.sort(unique), true_roots, decimal=7)
+ xp_assert_equal(multiplicity, xp.asarray([2, 2, 2, 2]))
+
+ def test_complex_roots_extra(self, xp):
+ unique, multiplicity = unique_roots(xp.asarray([1.0, 1.0j, 1.0]))
+ assert_almost_equal(unique, xp.asarray([1.0, 1.0j]), decimal=15)
+ xp_assert_equal(multiplicity, xp.asarray([2, 1]))
+
+ unique, multiplicity = unique_roots(
+ xp.asarray([1, 1 + 2e-9, 1e-9 + 1j]), tol=0.1
+ )
+ assert_almost_equal(unique, xp.asarray([1.0, 1e-9 + 1.0j]), decimal=15)
+ xp_assert_equal(multiplicity, xp.asarray([2, 1]))
+
+ def test_single_unique_root(self, xp):
+ p = xp.asarray(np.random.rand(100) + 1j * np.random.rand(100))
+ unique, multiplicity = unique_roots(p, 2)
+ assert_almost_equal(unique, xp.asarray([np.min(p)]), decimal=15)
+ xp_assert_equal(multiplicity, xp.asarray([100]))
+
+
+def test_gh_22684():
+ actual = signal.resample_poly(np.arange(2000, dtype=np.complex64), 6, 4)
+ assert actual.dtype == np.complex64
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_spectral.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_spectral.py
new file mode 100644
index 0000000000000000000000000000000000000000..3e1c2284a98ddcf7909a2f8398d7d014cdb7c6b6
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_spectral.py
@@ -0,0 +1,2188 @@
+import sys
+import warnings
+
+import numpy as np
+from numpy.testing import (assert_,
+ assert_allclose, assert_array_equal, assert_equal,
+ assert_array_almost_equal_nulp)
+import pytest
+from pytest import raises as assert_raises
+
+from scipy import signal
+from scipy._lib._array_api import xp_assert_close
+from scipy.fft import fftfreq, rfftfreq, fft, irfft
+from scipy.integrate import trapezoid
+from scipy.signal import (periodogram, welch, lombscargle, coherence, csd,
+ spectrogram, check_COLA, check_NOLA)
+from scipy.signal.windows import hann
+from scipy.signal._spectral_py import _spectral_helper
+
+# Compare ShortTimeFFT.stft() / ShortTimeFFT.istft() with stft() / istft():
+from scipy.signal.tests._scipy_spectral_test_shim import stft_compare as stft
+from scipy.signal.tests._scipy_spectral_test_shim import istft_compare as istft
+
+
+class TestPeriodogram:
+ def test_real_onesided_even(self):
+ x = np.zeros(16)
+ x[0] = 1
+ f, p = periodogram(x)
+ assert_allclose(f, np.linspace(0, 0.5, 9))
+ q = np.ones(9)
+ q[0] = 0
+ q[-1] /= 2.0
+ q /= 8
+ assert_allclose(p, q)
+
+ def test_real_onesided_odd(self):
+ x = np.zeros(15)
+ x[0] = 1
+ f, p = periodogram(x)
+ assert_allclose(f, np.arange(8.0)/15.0)
+ q = np.ones(8)
+ q[0] = 0
+ q *= 2.0/15.0
+ assert_allclose(p, q, atol=1e-15)
+
+ def test_real_twosided(self):
+ x = np.zeros(16)
+ x[0] = 1
+ f, p = periodogram(x, return_onesided=False)
+ assert_allclose(f, fftfreq(16, 1.0))
+ q = np.full(16, 1/16.0)
+ q[0] = 0
+ assert_allclose(p, q)
+
+ def test_real_spectrum(self):
+ x = np.zeros(16)
+ x[0] = 1
+ f, p = periodogram(x, scaling='spectrum')
+ g, q = periodogram(x, scaling='density')
+ assert_allclose(f, np.linspace(0, 0.5, 9))
+ assert_allclose(p, q/16.0)
+
+ def test_integer_even(self):
+ x = np.zeros(16, dtype=int)
+ x[0] = 1
+ f, p = periodogram(x)
+ assert_allclose(f, np.linspace(0, 0.5, 9))
+ q = np.ones(9)
+ q[0] = 0
+ q[-1] /= 2.0
+ q /= 8
+ assert_allclose(p, q)
+
+ def test_integer_odd(self):
+ x = np.zeros(15, dtype=int)
+ x[0] = 1
+ f, p = periodogram(x)
+ assert_allclose(f, np.arange(8.0)/15.0)
+ q = np.ones(8)
+ q[0] = 0
+ q *= 2.0/15.0
+ assert_allclose(p, q, atol=1e-15)
+
+ def test_integer_twosided(self):
+ x = np.zeros(16, dtype=int)
+ x[0] = 1
+ f, p = periodogram(x, return_onesided=False)
+ assert_allclose(f, fftfreq(16, 1.0))
+ q = np.full(16, 1/16.0)
+ q[0] = 0
+ assert_allclose(p, q)
+
+ def test_complex(self):
+ x = np.zeros(16, np.complex128)
+ x[0] = 1.0 + 2.0j
+ f, p = periodogram(x, return_onesided=False)
+ assert_allclose(f, fftfreq(16, 1.0))
+ q = np.full(16, 5.0/16.0)
+ q[0] = 0
+ assert_allclose(p, q)
+
+ def test_unk_scaling(self):
+ assert_raises(ValueError, periodogram, np.zeros(4, np.complex128),
+ scaling='foo')
+
+ @pytest.mark.skipif(
+ sys.maxsize <= 2**32,
+ reason="On some 32-bit tolerance issue"
+ )
+ def test_nd_axis_m1(self):
+ x = np.zeros(20, dtype=np.float64)
+ x = x.reshape((2,1,10))
+ x[:,:,0] = 1.0
+ f, p = periodogram(x)
+ assert_array_equal(p.shape, (2, 1, 6))
+ assert_array_almost_equal_nulp(p[0,0,:], p[1,0,:], 60)
+ f0, p0 = periodogram(x[0,0,:])
+ assert_array_almost_equal_nulp(p0[np.newaxis,:], p[1,:], 60)
+
+ @pytest.mark.skipif(
+ sys.maxsize <= 2**32,
+ reason="On some 32-bit tolerance issue"
+ )
+ def test_nd_axis_0(self):
+ x = np.zeros(20, dtype=np.float64)
+ x = x.reshape((10,2,1))
+ x[0,:,:] = 1.0
+ f, p = periodogram(x, axis=0)
+ assert_array_equal(p.shape, (6,2,1))
+ assert_array_almost_equal_nulp(p[:,0,0], p[:,1,0], 60)
+ f0, p0 = periodogram(x[:,0,0])
+ assert_array_almost_equal_nulp(p0, p[:,1,0])
+
+ def test_window_external(self):
+ x = np.zeros(16)
+ x[0] = 1
+ f, p = periodogram(x, 10, 'hann')
+ win = signal.get_window('hann', 16)
+ fe, pe = periodogram(x, 10, win)
+ assert_array_almost_equal_nulp(p, pe)
+ assert_array_almost_equal_nulp(f, fe)
+ win_err = signal.get_window('hann', 32)
+ assert_raises(ValueError, periodogram, x,
+ 10, win_err) # win longer than signal
+
+ def test_padded_fft(self):
+ x = np.zeros(16)
+ x[0] = 1
+ f, p = periodogram(x)
+ fp, pp = periodogram(x, nfft=32)
+ assert_allclose(f, fp[::2])
+ assert_allclose(p, pp[::2])
+ assert_array_equal(pp.shape, (17,))
+
+ def test_empty_input(self):
+ f, p = periodogram([])
+ assert_array_equal(f.shape, (0,))
+ assert_array_equal(p.shape, (0,))
+ for shape in [(0,), (3,0), (0,5,2)]:
+ f, p = periodogram(np.empty(shape))
+ assert_array_equal(f.shape, shape)
+ assert_array_equal(p.shape, shape)
+
+ def test_empty_input_other_axis(self):
+ for shape in [(3,0), (0,5,2)]:
+ f, p = periodogram(np.empty(shape), axis=1)
+ assert_array_equal(f.shape, shape)
+ assert_array_equal(p.shape, shape)
+
+ def test_short_nfft(self):
+ x = np.zeros(18)
+ x[0] = 1
+ f, p = periodogram(x, nfft=16)
+ assert_allclose(f, np.linspace(0, 0.5, 9))
+ q = np.ones(9)
+ q[0] = 0
+ q[-1] /= 2.0
+ q /= 8
+ assert_allclose(p, q)
+
+ def test_nfft_is_xshape(self):
+ x = np.zeros(16)
+ x[0] = 1
+ f, p = periodogram(x, nfft=16)
+ assert_allclose(f, np.linspace(0, 0.5, 9))
+ q = np.ones(9)
+ q[0] = 0
+ q[-1] /= 2.0
+ q /= 8
+ assert_allclose(p, q)
+
+ def test_real_onesided_even_32(self):
+ x = np.zeros(16, 'f')
+ x[0] = 1
+ f, p = periodogram(x)
+ assert_allclose(f, np.linspace(0, 0.5, 9))
+ q = np.ones(9, 'f')
+ q[0] = 0
+ q[-1] /= 2.0
+ q /= 8
+ assert_allclose(p, q)
+ assert_(p.dtype == q.dtype)
+
+ def test_real_onesided_odd_32(self):
+ x = np.zeros(15, 'f')
+ x[0] = 1
+ f, p = periodogram(x)
+ assert_allclose(f, np.arange(8.0)/15.0)
+ q = np.ones(8, 'f')
+ q[0] = 0
+ q *= 2.0/15.0
+ assert_allclose(p, q, atol=1e-7)
+ assert_(p.dtype == q.dtype)
+
+ def test_real_twosided_32(self):
+ x = np.zeros(16, 'f')
+ x[0] = 1
+ f, p = periodogram(x, return_onesided=False)
+ assert_allclose(f, fftfreq(16, 1.0))
+ q = np.full(16, 1/16.0, 'f')
+ q[0] = 0
+ assert_allclose(p, q)
+ assert_(p.dtype == q.dtype)
+
+ def test_complex_32(self):
+ x = np.zeros(16, 'F')
+ x[0] = 1.0 + 2.0j
+ f, p = periodogram(x, return_onesided=False)
+ assert_allclose(f, fftfreq(16, 1.0))
+ q = np.full(16, 5.0/16.0, 'f')
+ q[0] = 0
+ assert_allclose(p, q)
+ assert_(p.dtype == q.dtype)
+
+ def test_shorter_window_error(self):
+ x = np.zeros(16)
+ x[0] = 1
+ win = signal.get_window('hann', 10)
+ expected_msg = ('the size of the window must be the same size '
+ 'of the input on the specified axis')
+ with assert_raises(ValueError, match=expected_msg):
+ periodogram(x, window=win)
+
+
+class TestWelch:
+ def test_real_onesided_even(self):
+ x = np.zeros(16)
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, nperseg=8)
+ assert_allclose(f, np.linspace(0, 0.5, 5))
+ q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+ 0.11111111])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_real_onesided_odd(self):
+ x = np.zeros(16)
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, nperseg=9)
+ assert_allclose(f, np.arange(5.0)/9.0)
+ q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113,
+ 0.17072113])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_real_twosided(self):
+ x = np.zeros(16)
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, nperseg=8, return_onesided=False)
+ assert_allclose(f, fftfreq(8, 1.0))
+ q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111,
+ 0.11111111, 0.11111111, 0.11111111, 0.07638889])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_real_spectrum(self):
+ x = np.zeros(16)
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, nperseg=8, scaling='spectrum')
+ assert_allclose(f, np.linspace(0, 0.5, 5))
+ q = np.array([0.015625, 0.02864583, 0.04166667, 0.04166667,
+ 0.02083333])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_integer_onesided_even(self):
+ x = np.zeros(16, dtype=int)
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, nperseg=8)
+ assert_allclose(f, np.linspace(0, 0.5, 5))
+ q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+ 0.11111111])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_integer_onesided_odd(self):
+ x = np.zeros(16, dtype=int)
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, nperseg=9)
+ assert_allclose(f, np.arange(5.0)/9.0)
+ q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113,
+ 0.17072113])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_integer_twosided(self):
+ x = np.zeros(16, dtype=int)
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, nperseg=8, return_onesided=False)
+ assert_allclose(f, fftfreq(8, 1.0))
+ q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111,
+ 0.11111111, 0.11111111, 0.11111111, 0.07638889])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_complex(self):
+ x = np.zeros(16, np.complex128)
+ x[0] = 1.0 + 2.0j
+ x[8] = 1.0 + 2.0j
+ f, p = welch(x, nperseg=8, return_onesided=False)
+ assert_allclose(f, fftfreq(8, 1.0))
+ q = np.array([0.41666667, 0.38194444, 0.55555556, 0.55555556,
+ 0.55555556, 0.55555556, 0.55555556, 0.38194444])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_unk_scaling(self):
+ assert_raises(ValueError, welch, np.zeros(4, np.complex128),
+ scaling='foo', nperseg=4)
+
+ def test_detrend_linear(self):
+ x = np.arange(10, dtype=np.float64) + 0.04
+ f, p = welch(x, nperseg=10, detrend='linear')
+ assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+ def test_no_detrending(self):
+ x = np.arange(10, dtype=np.float64) + 0.04
+ f1, p1 = welch(x, nperseg=10, detrend=False)
+ f2, p2 = welch(x, nperseg=10, detrend=lambda x: x)
+ assert_allclose(f1, f2, atol=1e-15)
+ assert_allclose(p1, p2, atol=1e-15)
+
+ def test_detrend_external(self):
+ x = np.arange(10, dtype=np.float64) + 0.04
+ f, p = welch(x, nperseg=10,
+ detrend=lambda seg: signal.detrend(seg, type='l'))
+ assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+ def test_detrend_external_nd_m1(self):
+ x = np.arange(40, dtype=np.float64) + 0.04
+ x = x.reshape((2,2,10))
+ f, p = welch(x, nperseg=10,
+ detrend=lambda seg: signal.detrend(seg, type='l'))
+ assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+ def test_detrend_external_nd_0(self):
+ x = np.arange(20, dtype=np.float64) + 0.04
+ x = x.reshape((2,1,10))
+ x = np.moveaxis(x, 2, 0)
+ f, p = welch(x, nperseg=10, axis=0,
+ detrend=lambda seg: signal.detrend(seg, axis=0, type='l'))
+ assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+ def test_nd_axis_m1(self):
+ x = np.arange(20, dtype=np.float64) + 0.04
+ x = x.reshape((2,1,10))
+ f, p = welch(x, nperseg=10)
+ assert_array_equal(p.shape, (2, 1, 6))
+ assert_allclose(p[0,0,:], p[1,0,:], atol=1e-13, rtol=1e-13)
+ f0, p0 = welch(x[0,0,:], nperseg=10)
+ assert_allclose(p0[np.newaxis,:], p[1,:], atol=1e-13, rtol=1e-13)
+
+ def test_nd_axis_0(self):
+ x = np.arange(20, dtype=np.float64) + 0.04
+ x = x.reshape((10,2,1))
+ f, p = welch(x, nperseg=10, axis=0)
+ assert_array_equal(p.shape, (6,2,1))
+ assert_allclose(p[:,0,0], p[:,1,0], atol=1e-13, rtol=1e-13)
+ f0, p0 = welch(x[:,0,0], nperseg=10)
+ assert_allclose(p0, p[:,1,0], atol=1e-13, rtol=1e-13)
+
+ def test_window_external(self):
+ x = np.zeros(16)
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, 10, 'hann', nperseg=8)
+ win = signal.get_window('hann', 8)
+ fe, pe = welch(x, 10, win, nperseg=None)
+ assert_array_almost_equal_nulp(p, pe)
+ assert_array_almost_equal_nulp(f, fe)
+ assert_array_equal(fe.shape, (5,)) # because win length used as nperseg
+ assert_array_equal(pe.shape, (5,))
+ assert_raises(ValueError, welch, x,
+ 10, win, nperseg=4) # because nperseg != win.shape[-1]
+ win_err = signal.get_window('hann', 32)
+ assert_raises(ValueError, welch, x,
+ 10, win_err, nperseg=None) # win longer than signal
+
+ def test_empty_input(self):
+ f, p = welch([])
+ assert_array_equal(f.shape, (0,))
+ assert_array_equal(p.shape, (0,))
+ for shape in [(0,), (3,0), (0,5,2)]:
+ f, p = welch(np.empty(shape))
+ assert_array_equal(f.shape, shape)
+ assert_array_equal(p.shape, shape)
+
+ def test_empty_input_other_axis(self):
+ for shape in [(3,0), (0,5,2)]:
+ f, p = welch(np.empty(shape), axis=1)
+ assert_array_equal(f.shape, shape)
+ assert_array_equal(p.shape, shape)
+
+ def test_short_data(self):
+ x = np.zeros(8)
+ x[0] = 1
+ #for string-like window, input signal length < nperseg value gives
+ #UserWarning, sets nperseg to x.shape[-1]
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "nperseg=256 is greater than signal.*", UserWarning)
+ f, p = welch(x,window='hann') # default nperseg
+ f1, p1 = welch(x,window='hann', nperseg=256) # user-specified nperseg
+ f2, p2 = welch(x, nperseg=8) # valid nperseg, doesn't give warning
+ assert_allclose(f, f2)
+ assert_allclose(p, p2)
+ assert_allclose(f1, f2)
+ assert_allclose(p1, p2)
+
+ def test_window_long_or_nd(self):
+ assert_raises(ValueError, welch, np.zeros(4), 1, np.array([1,1,1,1,1]))
+ assert_raises(ValueError, welch, np.zeros(4), 1,
+ np.arange(6).reshape((2,3)))
+
+ def test_nondefault_noverlap(self):
+ x = np.zeros(64)
+ x[::8] = 1
+ f, p = welch(x, nperseg=16, noverlap=4)
+ q = np.array([0, 1./12., 1./3., 1./5., 1./3., 1./5., 1./3., 1./5.,
+ 1./6.])
+ assert_allclose(p, q, atol=1e-12)
+
+ def test_bad_noverlap(self):
+ assert_raises(ValueError, welch, np.zeros(4), 1, 'hann', 2, 7)
+
+ def test_nfft_too_short(self):
+ assert_raises(ValueError, welch, np.ones(12), nfft=3, nperseg=4)
+
+ def test_real_onesided_even_32(self):
+ x = np.zeros(16, 'f')
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, nperseg=8)
+ assert_allclose(f, np.linspace(0, 0.5, 5))
+ q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+ 0.11111111], 'f')
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+ assert_(p.dtype == q.dtype)
+
+ def test_real_onesided_odd_32(self):
+ x = np.zeros(16, 'f')
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, nperseg=9)
+ assert_allclose(f, np.arange(5.0)/9.0)
+ q = np.array([0.12477458, 0.23430935, 0.17072113, 0.17072116,
+ 0.17072113], 'f')
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+ assert_(p.dtype == q.dtype)
+
+ def test_real_twosided_32(self):
+ x = np.zeros(16, 'f')
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, nperseg=8, return_onesided=False)
+ assert_allclose(f, fftfreq(8, 1.0))
+ q = np.array([0.08333333, 0.07638889, 0.11111111,
+ 0.11111111, 0.11111111, 0.11111111, 0.11111111,
+ 0.07638889], 'f')
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+ assert_(p.dtype == q.dtype)
+
+ def test_complex_32(self):
+ x = np.zeros(16, 'F')
+ x[0] = 1.0 + 2.0j
+ x[8] = 1.0 + 2.0j
+ f, p = welch(x, nperseg=8, return_onesided=False)
+ assert_allclose(f, fftfreq(8, 1.0))
+ q = np.array([0.41666666, 0.38194442, 0.55555552, 0.55555552,
+ 0.55555558, 0.55555552, 0.55555552, 0.38194442], 'f')
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+ assert_(p.dtype == q.dtype,
+ f'dtype mismatch, {p.dtype}, {q.dtype}')
+
+ def test_padded_freqs(self):
+ x = np.zeros(12)
+
+ nfft = 24
+ f = fftfreq(nfft, 1.0)[:nfft//2+1]
+ f[-1] *= -1
+ fodd, _ = welch(x, nperseg=5, nfft=nfft)
+ feven, _ = welch(x, nperseg=6, nfft=nfft)
+ assert_allclose(f, fodd)
+ assert_allclose(f, feven)
+
+ nfft = 25
+ f = fftfreq(nfft, 1.0)[:(nfft + 1)//2]
+ fodd, _ = welch(x, nperseg=5, nfft=nfft)
+ feven, _ = welch(x, nperseg=6, nfft=nfft)
+ assert_allclose(f, fodd)
+ assert_allclose(f, feven)
+
+ def test_window_correction(self):
+ A = 20
+ fs = 1e4
+ nperseg = int(fs//10)
+ fsig = 300
+ ii = int(fsig*nperseg//fs) # Freq index of fsig
+
+ tt = np.arange(fs)/fs
+ x = A*np.sin(2*np.pi*fsig*tt)
+
+ for window in ['hann', 'bartlett', ('tukey', 0.1), 'flattop']:
+ _, p_spec = welch(x, fs=fs, nperseg=nperseg, window=window,
+ scaling='spectrum')
+ freq, p_dens = welch(x, fs=fs, nperseg=nperseg, window=window,
+ scaling='density')
+
+ # Check peak height at signal frequency for 'spectrum'
+ assert_allclose(p_spec[ii], A**2/2.0)
+ # Check integrated spectrum RMS for 'density'
+ assert_allclose(np.sqrt(trapezoid(p_dens, freq)), A*np.sqrt(2)/2,
+ rtol=1e-3)
+
+ def test_axis_rolling(self):
+ np.random.seed(1234)
+
+ x_flat = np.random.randn(1024)
+ _, p_flat = welch(x_flat)
+
+ for a in range(3):
+ newshape = [1,]*3
+ newshape[a] = -1
+ x = x_flat.reshape(newshape)
+
+ _, p_plus = welch(x, axis=a) # Positive axis index
+ _, p_minus = welch(x, axis=a-x.ndim) # Negative axis index
+
+ assert_equal(p_flat, p_plus.squeeze(), err_msg=a)
+ assert_equal(p_flat, p_minus.squeeze(), err_msg=a-x.ndim)
+
+ def test_average(self):
+ x = np.zeros(16)
+ x[0] = 1
+ x[8] = 1
+ f, p = welch(x, nperseg=8, average='median')
+ assert_allclose(f, np.linspace(0, 0.5, 5))
+ q = np.array([.1, .05, 0., 1.54074396e-33, 0.])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ assert_raises(ValueError, welch, x, nperseg=8,
+ average='unrecognised-average')
+
+ def test_ratio_scale_to(self):
+ """Verify the factor of ``sum(abs(window)**2)*fs / abs(sum(window))**2``
+ used in the `welch` and `csd` docstrs. """
+ x, win, fs = np.array([1., 0, 0, 0]), np.ones(4), 12
+ params = dict(fs=fs, window=win, return_onesided=False, detrend=None)
+ p_dens = welch(x, scaling='density', **params)[1]
+ p_spec = welch(x, scaling='spectrum', **params)[1]
+ p_fac = sum(win**2)*fs / abs(sum(win))**2
+ assert_allclose(p_spec / p_dens, p_fac)
+
+class TestCSD:
+ def test_pad_shorter_x(self):
+ x = np.zeros(8)
+ y = np.zeros(12)
+
+ f = np.linspace(0, 0.5, 7)
+ c = np.zeros(7,dtype=np.complex128)
+ f1, c1 = csd(x, y, nperseg=12)
+
+ assert_allclose(f, f1)
+ assert_allclose(c, c1)
+
+ def test_pad_shorter_y(self):
+ x = np.zeros(12)
+ y = np.zeros(8)
+
+ f = np.linspace(0, 0.5, 7)
+ c = np.zeros(7,dtype=np.complex128)
+ f1, c1 = csd(x, y, nperseg=12)
+
+ assert_allclose(f, f1)
+ assert_allclose(c, c1)
+
+ def test_unequal_length_input_1D(self):
+ """Test zero-padding for input `x.shape[axis] != y.shape[axis]` for 1d arrays.
+
+ This test ensures that issue 23036 is fixed.
+ """
+ x = np.tile([4, 0, -4, 0], 4)
+
+ kw = dict(fs=len(x), window='boxcar', nperseg=4)
+ X0 = signal.csd(x, np.copy(x), **kw)[1] # `x is x` must be False
+ X1 = signal.csd(x, x[:8], **kw)[1]
+ X2 = signal.csd(x[:8], x, **kw)[1]
+ xp_assert_close(X1, X0 / 2)
+ xp_assert_close(X2, X0 / 2)
+
+ def test_unequal_length_input_3D(self):
+ """Test zero-padding for input `x.shape[axis] != y.shape[axis]` for 3d arrays.
+
+ This test ensures that issue 23036 is fixed.
+ """
+ n = 8
+ x = np.zeros(2 * 3 * n).reshape(2, n, 3)
+ x[:, 0, :] = n
+
+ kw = dict(fs=n, window='boxcar', nperseg=n, detrend=None, axis=1)
+ X0 = signal.csd(x, x.copy(), **kw)[1] # `x is x` must be False
+ X1 = signal.csd(x, x[:, :2, :], **kw)[1]
+ X2 = signal.csd(x[:, :2, :], x, **kw)[1]
+ xp_assert_close(X1, X0)
+ xp_assert_close(X2, X0)
+
+ def test_real_onesided_even(self):
+ x = np.zeros(16)
+ x[0] = 1
+ x[8] = 1
+ f, p = csd(x, x, nperseg=8)
+ assert_allclose(f, np.linspace(0, 0.5, 5))
+ q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+ 0.11111111])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_real_onesided_odd(self):
+ x = np.zeros(16)
+ x[0] = 1
+ x[8] = 1
+ f, p = csd(x, x, nperseg=9)
+ assert_allclose(f, np.arange(5.0)/9.0)
+ q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113,
+ 0.17072113])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_real_twosided(self):
+ x = np.zeros(16)
+ x[0] = 1
+ x[8] = 1
+ f, p = csd(x, x, nperseg=8, return_onesided=False)
+ assert_allclose(f, fftfreq(8, 1.0))
+ q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111,
+ 0.11111111, 0.11111111, 0.11111111, 0.07638889])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_real_spectrum(self):
+ x = np.zeros(16)
+ x[0] = 1
+ x[8] = 1
+ f, p = csd(x, x, nperseg=8, scaling='spectrum')
+ assert_allclose(f, np.linspace(0, 0.5, 5))
+ q = np.array([0.015625, 0.02864583, 0.04166667, 0.04166667,
+ 0.02083333])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_integer_onesided_even(self):
+ x = np.zeros(16, dtype=int)
+ x[0] = 1
+ x[8] = 1
+ f, p = csd(x, x, nperseg=8)
+ assert_allclose(f, np.linspace(0, 0.5, 5))
+ q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+ 0.11111111])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_integer_onesided_odd(self):
+ x = np.zeros(16, dtype=int)
+ x[0] = 1
+ x[8] = 1
+ f, p = csd(x, x, nperseg=9)
+ assert_allclose(f, np.arange(5.0)/9.0)
+ q = np.array([0.12477455, 0.23430933, 0.17072113, 0.17072113,
+ 0.17072113])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_integer_twosided(self):
+ x = np.zeros(16, dtype=int)
+ x[0] = 1
+ x[8] = 1
+ f, p = csd(x, x, nperseg=8, return_onesided=False)
+ assert_allclose(f, fftfreq(8, 1.0))
+ q = np.array([0.08333333, 0.07638889, 0.11111111, 0.11111111,
+ 0.11111111, 0.11111111, 0.11111111, 0.07638889])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_complex(self):
+ x = np.zeros(16, np.complex128)
+ x[0] = 1.0 + 2.0j
+ x[8] = 1.0 + 2.0j
+ f, p = csd(x, x, nperseg=8, return_onesided=False)
+ assert_allclose(f, fftfreq(8, 1.0))
+ q = np.array([0.41666667, 0.38194444, 0.55555556, 0.55555556,
+ 0.55555556, 0.55555556, 0.55555556, 0.38194444])
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+
+ def test_unk_scaling(self):
+ assert_raises(ValueError, csd, np.zeros(4, np.complex128),
+ np.ones(4, np.complex128), scaling='foo', nperseg=4)
+
+ def test_detrend_linear(self):
+ x = np.arange(10, dtype=np.float64) + 0.04
+ f, p = csd(x, x, nperseg=10, detrend='linear')
+ assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+ def test_no_detrending(self):
+ x = np.arange(10, dtype=np.float64) + 0.04
+ f1, p1 = csd(x, x, nperseg=10, detrend=False)
+ f2, p2 = csd(x, x, nperseg=10, detrend=lambda x: x)
+ assert_allclose(f1, f2, atol=1e-15)
+ assert_allclose(p1, p2, atol=1e-15)
+
+ def test_detrend_external(self):
+ x = np.arange(10, dtype=np.float64) + 0.04
+ f, p = csd(x, x, nperseg=10,
+ detrend=lambda seg: signal.detrend(seg, type='l'))
+ assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+ def test_detrend_external_nd_m1(self):
+ x = np.arange(40, dtype=np.float64) + 0.04
+ x = x.reshape((2,2,10))
+ f, p = csd(x, x, nperseg=10,
+ detrend=lambda seg: signal.detrend(seg, type='l'))
+ assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+ def test_detrend_external_nd_0(self):
+ x = np.arange(20, dtype=np.float64) + 0.04
+ x = x.reshape((2,1,10))
+ x = np.moveaxis(x, 2, 0)
+ f, p = csd(x, x, nperseg=10, axis=0,
+ detrend=lambda seg: signal.detrend(seg, axis=0, type='l'))
+ assert_allclose(p, np.zeros_like(p), atol=1e-15)
+
+ def test_nd_axis_m1(self):
+ x = np.arange(20, dtype=np.float64) + 0.04
+ x = x.reshape((2,1,10))
+ f, p = csd(x, x, nperseg=10)
+ assert_array_equal(p.shape, (2, 1, 6))
+ assert_allclose(p[0,0,:], p[1,0,:], atol=1e-13, rtol=1e-13)
+ f0, p0 = csd(x[0,0,:], x[0,0,:], nperseg=10)
+ assert_allclose(p0[np.newaxis,:], p[1,:], atol=1e-13, rtol=1e-13)
+
+ def test_nd_axis_0(self):
+ x = np.arange(20, dtype=np.float64) + 0.04
+ x = x.reshape((10,2,1))
+ f, p = csd(x, x, nperseg=10, axis=0)
+ assert_array_equal(p.shape, (6,2,1))
+ assert_allclose(p[:,0,0], p[:,1,0], atol=1e-13, rtol=1e-13)
+ f0, p0 = csd(x[:,0,0], x[:,0,0], nperseg=10)
+ assert_allclose(p0, p[:,1,0], atol=1e-13, rtol=1e-13)
+
+ def test_window_external(self):
+ x = np.zeros(16)
+ x[0] = 1
+ x[8] = 1
+ f, p = csd(x, x, 10, 'hann', 8)
+ win = signal.get_window('hann', 8)
+ fe, pe = csd(x, x, 10, win, nperseg=None)
+ assert_array_almost_equal_nulp(p, pe)
+ assert_array_almost_equal_nulp(f, fe)
+ assert_array_equal(fe.shape, (5,)) # because win length used as nperseg
+ assert_array_equal(pe.shape, (5,))
+ assert_raises(ValueError, csd, x, x,
+ 10, win, nperseg=256) # because nperseg != win.shape[-1]
+ win_err = signal.get_window('hann', 32)
+ assert_raises(ValueError, csd, x, x,
+ 10, win_err, nperseg=None) # because win longer than signal
+ with pytest.raises(ValueError, match="Parameter nperseg=0.*"):
+ csd(x, x, 0, nperseg=0)
+
+ def test_empty_input(self):
+ f, p = csd([],np.zeros(10))
+ assert_array_equal(f.shape, (0,))
+ assert_array_equal(p.shape, (0,))
+
+ f, p = csd(np.zeros(10),[])
+ assert_array_equal(f.shape, (0,))
+ assert_array_equal(p.shape, (0,))
+
+ for shape in [(0,), (3,0), (0,5,2)]:
+ f, p = csd(np.empty(shape), np.empty(shape))
+ assert_array_equal(f.shape, shape)
+ assert_array_equal(p.shape, shape)
+
+ f, p = csd(np.ones(10), np.empty((5,0)))
+ assert_array_equal(f.shape, (5,0))
+ assert_array_equal(p.shape, (5,0))
+
+ f, p = csd(np.empty((5,0)), np.ones(10))
+ assert_array_equal(f.shape, (5,0))
+ assert_array_equal(p.shape, (5,0))
+
+ def test_empty_input_other_axis(self):
+ for shape in [(3,0), (0,5,2)]:
+ f, p = csd(np.empty(shape), np.empty(shape), axis=1)
+ assert_array_equal(f.shape, shape)
+ assert_array_equal(p.shape, shape)
+
+ f, p = csd(np.empty((10,10,3)), np.zeros((10,0,1)), axis=1)
+ assert_array_equal(f.shape, (10,0,3))
+ assert_array_equal(p.shape, (10,0,3))
+
+ f, p = csd(np.empty((10,0,1)), np.zeros((10,10,3)), axis=1)
+ assert_array_equal(f.shape, (10,0,3))
+ assert_array_equal(p.shape, (10,0,3))
+
+ def test_short_data(self):
+ x = np.zeros(8)
+ x[0] = 1
+
+ #for string-like window, input signal length < nperseg value gives
+ #UserWarning, sets nperseg to x.shape[-1]
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "nperseg=256 is greater than signal length.*", UserWarning)
+ f, p = csd(x, x, window='hann') # default nperseg
+ f1, p1 = csd(x, x, window='hann', nperseg=256) # user-specified nperseg
+ f2, p2 = csd(x, x, nperseg=8) # valid nperseg, doesn't give warning
+ assert_allclose(f, f2)
+ assert_allclose(p, p2)
+ assert_allclose(f1, f2)
+ assert_allclose(p1, p2)
+
+ def test_window_long_or_nd(self):
+ assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1,
+ np.array([1,1,1,1,1]))
+ assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1,
+ np.arange(6).reshape((2,3)))
+
+ def test_nondefault_noverlap(self):
+ x = np.zeros(64)
+ x[::8] = 1
+ f, p = csd(x, x, nperseg=16, noverlap=4)
+ q = np.array([0, 1./12., 1./3., 1./5., 1./3., 1./5., 1./3., 1./5.,
+ 1./6.])
+ assert_allclose(p, q, atol=1e-12)
+
+ def test_bad_noverlap(self):
+ assert_raises(ValueError, csd, np.zeros(4), np.ones(4), 1, 'hann',
+ 2, 7)
+
+ def test_nfft_too_short(self):
+ assert_raises(ValueError, csd, np.ones(12), np.zeros(12), nfft=3,
+ nperseg=4)
+
+ def test_incompatible_inputs(self):
+ with pytest.raises(ValueError, match='x and y cannot be broadcast.*'):
+ csd(np.ones((1, 8, 1)), np.ones((2, 8)), nperseg=4)
+
+
+ def test_real_onesided_even_32(self):
+ x = np.zeros(16, 'f')
+ x[0] = 1
+ x[8] = 1
+ f, p = csd(x, x, nperseg=8)
+ assert_allclose(f, np.linspace(0, 0.5, 5))
+ q = np.array([0.08333333, 0.15277778, 0.22222222, 0.22222222,
+ 0.11111111], 'f')
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+ assert_(p.dtype == q.dtype)
+
+ def test_real_onesided_odd_32(self):
+ x = np.zeros(16, 'f')
+ x[0] = 1
+ x[8] = 1
+ f, p = csd(x, x, nperseg=9)
+ assert_allclose(f, np.arange(5.0)/9.0)
+ q = np.array([0.12477458, 0.23430935, 0.17072113, 0.17072116,
+ 0.17072113], 'f')
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+ assert_(p.dtype == q.dtype)
+
+ def test_real_twosided_32(self):
+ x = np.zeros(16, 'f')
+ x[0] = 1
+ x[8] = 1
+ f, p = csd(x, x, nperseg=8, return_onesided=False)
+ assert_allclose(f, fftfreq(8, 1.0))
+ q = np.array([0.08333333, 0.07638889, 0.11111111,
+ 0.11111111, 0.11111111, 0.11111111, 0.11111111,
+ 0.07638889], 'f')
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+ assert_(p.dtype == q.dtype)
+
+ def test_complex_32(self):
+ x = np.zeros(16, 'F')
+ x[0] = 1.0 + 2.0j
+ x[8] = 1.0 + 2.0j
+ f, p = csd(x, x, nperseg=8, return_onesided=False)
+ assert_allclose(f, fftfreq(8, 1.0))
+ q = np.array([0.41666666, 0.38194442, 0.55555552, 0.55555552,
+ 0.55555558, 0.55555552, 0.55555552, 0.38194442], 'f')
+ assert_allclose(p, q, atol=1e-7, rtol=1e-7)
+ assert_(p.dtype == q.dtype,
+ f'dtype mismatch, {p.dtype}, {q.dtype}')
+
+ def test_padded_freqs(self):
+ x = np.zeros(12)
+ y = np.ones(12)
+
+ nfft = 24
+ f = fftfreq(nfft, 1.0)[:nfft//2+1]
+ f[-1] *= -1
+ fodd, _ = csd(x, y, nperseg=5, nfft=nfft)
+ feven, _ = csd(x, y, nperseg=6, nfft=nfft)
+ assert_allclose(f, fodd)
+ assert_allclose(f, feven)
+
+ nfft = 25
+ f = fftfreq(nfft, 1.0)[:(nfft + 1)//2]
+ fodd, _ = csd(x, y, nperseg=5, nfft=nfft)
+ feven, _ = csd(x, y, nperseg=6, nfft=nfft)
+ assert_allclose(f, fodd)
+ assert_allclose(f, feven)
+
+ def test_copied_data(self):
+ x = np.random.randn(64)
+ y = x.copy()
+
+ _, p_same = csd(x, x, nperseg=8, average='mean',
+ return_onesided=False)
+ _, p_copied = csd(x, y, nperseg=8, average='mean',
+ return_onesided=False)
+ assert_allclose(p_same, p_copied)
+
+ _, p_same = csd(x, x, nperseg=8, average='median',
+ return_onesided=False)
+ _, p_copied = csd(x, y, nperseg=8, average='median',
+ return_onesided=False)
+ assert_allclose(p_same, p_copied)
+
+
+class TestCoherence:
+ def test_identical_input(self):
+ x = np.random.randn(20)
+ y = np.copy(x) # So `y is x` -> False
+
+ f = np.linspace(0, 0.5, 6)
+ C = np.ones(6)
+ f1, C1 = coherence(x, y, nperseg=10)
+
+ assert_allclose(f, f1)
+ assert_allclose(C, C1)
+
+ def test_phase_shifted_input(self):
+ x = np.random.randn(20)
+ y = -x
+
+ f = np.linspace(0, 0.5, 6)
+ C = np.ones(6)
+ f1, C1 = coherence(x, y, nperseg=10)
+
+ assert_allclose(f, f1)
+ assert_allclose(C, C1)
+
+
+class TestSpectrogram:
+ def test_average_all_segments(self):
+ x = np.random.randn(1024)
+
+ fs = 1.0
+ window = ('tukey', 0.25)
+ nperseg = 16
+ noverlap = 2
+
+ f, _, P = spectrogram(x, fs, window, nperseg, noverlap)
+ fw, Pw = welch(x, fs, window, nperseg, noverlap)
+ assert_allclose(f, fw)
+ assert_allclose(np.mean(P, axis=-1), Pw)
+
+ def test_window_external(self):
+ x = np.random.randn(1024)
+
+ fs = 1.0
+ window = ('tukey', 0.25)
+ nperseg = 16
+ noverlap = 2
+ f, _, P = spectrogram(x, fs, window, nperseg, noverlap)
+
+ win = signal.get_window(('tukey', 0.25), 16)
+ fe, _, Pe = spectrogram(x, fs, win, nperseg=None, noverlap=2)
+ assert_array_equal(fe.shape, (9,)) # because win length used as nperseg
+ assert_array_equal(Pe.shape, (9,73))
+ assert_raises(ValueError, spectrogram, x,
+ fs, win, nperseg=8) # because nperseg != win.shape[-1]
+ win_err = signal.get_window(('tukey', 0.25), 2048)
+ assert_raises(ValueError, spectrogram, x,
+ fs, win_err, nperseg=None) # win longer than signal
+
+ def test_short_data(self):
+ x = np.random.randn(1024)
+ fs = 1.0
+
+ #for string-like window, input signal length < nperseg value gives
+ #UserWarning, sets nperseg to x.shape[-1]
+ f, _, p = spectrogram(x, fs, window=('tukey',0.25)) # default nperseg
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "nperseg = 1025 is greater than input length = 1024, "
+ "using nperseg = 1024",
+ UserWarning,
+ )
+ f1, _, p1 = spectrogram(x, fs, window=('tukey',0.25),
+ nperseg=1025) # user-specified nperseg
+ f2, _, p2 = spectrogram(x, fs, nperseg=256) # to compare w/default
+ f3, _, p3 = spectrogram(x, fs, nperseg=1024) # compare w/user-spec'd
+ assert_allclose(f, f2)
+ assert_allclose(p, p2)
+ assert_allclose(f1, f3)
+ assert_allclose(p1, p3)
+
+class TestLombscargle:
+ def test_frequency(self):
+ """Test if frequency location of peak corresponds to frequency of
+ generated input signal.
+ """
+
+ # Input parameters
+ ampl = 2.
+ w = 1.
+ phi = 0.5 * np.pi
+ nin = 100
+ nout = 1000
+ p = 0.7 # Fraction of points to select
+
+ # Randomly select a fraction of an array with timesteps
+ rng = np.random.RandomState(2353425)
+ r = rng.rand(nin)
+ t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+ # Plot a sine wave for the selected times
+ y = ampl * np.sin(w*t + phi)
+
+ # Define the array of frequencies for which to compute the periodogram
+ f = np.linspace(0.01, 10., nout)
+
+ # Calculate Lomb-Scargle periodogram
+ P = lombscargle(t, y, f)
+
+ # Check if difference between found frequency maximum and input
+ # frequency is less than accuracy
+ delta = f[1] - f[0]
+ assert(w - f[np.argmax(P)] < (delta/2.))
+
+ # also, check that it works with weights
+ P = lombscargle(t, y, f, weights=np.ones_like(t, dtype=f.dtype))
+
+ # Check if difference between found frequency maximum and input
+ # frequency is less than accuracy
+ delta = f[1] - f[0]
+ assert(w - f[np.argmax(P)] < (delta/2.))
+
+ def test_amplitude(self):
+ # Test if height of peak in unnormalized Lomb-Scargle periodogram
+ # corresponds to amplitude of the generated input signal.
+
+ # Input parameters
+ ampl = 2.
+ w = 1.
+ phi = 0.5 * np.pi
+ nin = 1000
+ nout = 1000
+ p = 0.7 # Fraction of points to select
+
+ # Randomly select a fraction of an array with timesteps
+ rng = np.random.RandomState(2353425)
+ r = rng.rand(nin)
+ t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+ # Plot a sine wave for the selected times
+ y = ampl * np.sin(w*t + phi)
+
+ # Define the array of frequencies for which to compute the periodogram
+ f = np.linspace(0.01, 10., nout)
+
+ # Calculate Lomb-Scargle periodogram
+ pgram = lombscargle(t, y, f)
+
+ # convert to the amplitude
+ pgram = np.sqrt(4.0 * pgram / t.shape[0])
+
+ # Check if amplitude is correct (this will not exactly match, due to
+ # numerical differences when data is removed)
+ assert_allclose(pgram[f==w], ampl, rtol=5e-2)
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_precenter(self):
+ # Test if precenter gives the same result as manually precentering
+ # (for a very simple offset)
+
+ # Input parameters
+ ampl = 2.
+ w = 1.
+ phi = 0.5 * np.pi
+ nin = 100
+ nout = 1000
+ p = 0.7 # Fraction of points to select
+ offset = 0.15 # Offset to be subtracted in pre-centering
+
+ # Randomly select a fraction of an array with timesteps
+ rng = np.random.RandomState(2353425)
+ r = rng.rand(nin)
+ t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+ # Plot a sine wave for the selected times
+ y = ampl * np.sin(w*t + phi) + offset
+
+ # Define the array of frequencies for which to compute the periodogram
+ f = np.linspace(0.01, 10., nout)
+
+ # Calculate Lomb-Scargle periodogram
+ pgram = lombscargle(t, y, f, precenter=True)
+ pgram2 = lombscargle(t, y - y.mean(), f, precenter=False)
+
+ # check if centering worked
+ assert_allclose(pgram, pgram2)
+
+ # do this again, but with floating_mean=True
+
+ # Calculate Lomb-Scargle periodogram
+ pgram = lombscargle(t, y, f, precenter=True, floating_mean=True)
+ pgram2 = lombscargle(t, y - y.mean(), f, precenter=False, floating_mean=True)
+
+ # check if centering worked
+ assert_allclose(pgram, pgram2)
+
+ def test_normalize(self):
+ # Test normalize option of Lomb-Scarge.
+
+ # Input parameters
+ ampl = 2.
+ w = 1.
+ phi = 0.5 * np.pi
+ nin = 100
+ nout = 1000
+ p = 0.7 # Fraction of points to select
+
+ # Randomly select a fraction of an array with timesteps
+ rng = np.random.RandomState(2353425)
+ r = rng.rand(nin)
+ t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+ # Plot a sine wave for the selected times
+ y = ampl * np.sin(w*t + phi)
+
+ # Define the array of frequencies for which to compute the periodogram
+ f = np.linspace(0.01, 10., nout)
+
+ # Calculate Lomb-Scargle periodogram
+ pgram = lombscargle(t, y, f)
+ pgram2 = lombscargle(t, y, f, normalize=True)
+
+ # Calculate the scale to convert from unnormalized to normalized
+ weights = np.ones_like(t)/float(t.shape[0])
+ YY_hat = (weights * y * y).sum()
+ YY = YY_hat # correct formula for floating_mean=False
+ scale_to_use = 2/(YY*t.shape[0])
+
+ # check if normalization works as expected
+ assert_allclose(pgram * scale_to_use, pgram2)
+ assert_allclose(np.max(pgram2), 1.0)
+
+ def test_wrong_shape(self):
+
+ # different length t and y
+ t = np.linspace(0, 1, 1)
+ y = np.linspace(0, 1, 2)
+ f = np.linspace(0, 1, 3) + 0.1
+ assert_raises(ValueError, lombscargle, t, y, f)
+
+ # t is 2D, with both axes length > 1
+ t = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1)
+ y = np.linspace(0, 1, 2)
+ f = np.linspace(0, 1, 3) + 0.1
+ assert_raises(ValueError, lombscargle, t, y, f)
+
+ # y is 2D, with both axes length > 1
+ t = np.linspace(0, 1, 2)
+ y = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1)
+ f = np.linspace(0, 1, 3) + 0.1
+ assert_raises(ValueError, lombscargle, t, y, f)
+
+ # f is 2D, with both axes length > 1
+ t = np.linspace(0, 1, 2)
+ y = np.linspace(0, 1, 2)
+ f = np.repeat(np.expand_dims(np.linspace(0, 1, 3), 1) + 0.1, 2, axis=1)
+ assert_raises(ValueError, lombscargle, t, y, f)
+
+ # weights is 2D, with both axes length > 1
+ t = np.linspace(0, 1, 2)
+ y = np.linspace(0, 1, 2)
+ f = np.linspace(0, 1, 3) + 0.1
+ weights = np.repeat(np.expand_dims(np.linspace(0, 1, 2), 1), 2, axis=1)
+ assert_raises(ValueError, lombscargle, t, y, f, weights=weights)
+
+ def test_lombscargle_atan_vs_atan2(self):
+ # https://github.com/scipy/scipy/issues/3787
+ # This raised a ZeroDivisionError.
+ t = np.linspace(0, 10, 1000, endpoint=False)
+ y = np.sin(4*t)
+ f = np.linspace(0, 50, 500, endpoint=False) + 0.1
+ lombscargle(t, y, f*2*np.pi)
+
+ def test_wrong_shape_weights(self):
+ # Weights must be the same shape as t
+
+ t = np.linspace(0, 1, 1)
+ y = np.linspace(0, 1, 1)
+ f = np.linspace(0, 1, 3) + 0.1
+ weights = np.linspace(1, 2, 2)
+ assert_raises(ValueError, lombscargle, t, y, f, weights=weights)
+
+ def test_zero_division_weights(self):
+ # Weights cannot sum to 0
+
+ t = np.zeros(1)
+ y = np.zeros(1)
+ f = np.ones(1)
+ weights = np.zeros(1)
+ assert_raises(ValueError, lombscargle, t, y, f, weights=weights)
+
+ def test_normalize_parameter(self):
+ # Test the validity of the normalize parameter input
+
+ # Input parameters
+ ampl = 2.
+ w = 1.
+ phi = 0
+ nin = 100
+ nout = 1000
+ p = 0.7 # Fraction of points to select
+
+ # Randomly select a fraction of an array with timesteps
+ rng = np.random.RandomState(2353425)
+ r = rng.rand(nin)
+ t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+ # Plot a sine wave for the selected times
+ y = ampl * np.sin(w*t + phi)
+
+ # Define the array of frequencies for which to compute the periodogram
+ f = np.linspace(0.01, 10., nout)
+
+ # check each of the valid inputs
+ pgram_false = lombscargle(t, y, f, normalize=False)
+ pgram_true = lombscargle(t, y, f, normalize=True)
+ pgram_power = lombscargle(t, y, f, normalize='power')
+ pgram_norm = lombscargle(t, y, f, normalize='normalize')
+ pgram_amp = lombscargle(t, y, f, normalize='amplitude')
+
+ # validate the results that should be the same
+ assert_allclose(pgram_false, pgram_power)
+ assert_allclose(pgram_true, pgram_norm)
+
+ # validate that the power and norm outputs are proper wrt each other
+ weights = np.ones_like(y)/float(y.shape[0])
+ YY_hat = (weights * y * y).sum()
+ YY = YY_hat # correct formula for floating_mean=False
+ assert_allclose(pgram_power * 2.0 / (float(t.shape[0]) * YY), pgram_norm)
+
+ # validate that the amp output is correct for the given input
+ f_i = np.where(f==w)[0][0]
+ assert_allclose(np.abs(pgram_amp[f_i]), ampl)
+
+ # check invalid inputs
+ # 1) a string that is not allowed
+ assert_raises(ValueError, lombscargle, t, y, f, normalize='lomb')
+ # 2) something besides a bool or str
+ assert_raises(ValueError, lombscargle, t, y, f, normalize=2)
+
+ def test_offset_removal(self):
+ # Verify that the amplitude is the same, even with an offset
+ # must use floating_mean=True, otherwise it will not remove an offset
+
+ # Input parameters
+ ampl = 2.
+ w = 1.
+ phi = 0.5 * np.pi
+ nin = 100
+ nout = 1000
+ p = 0.7 # Fraction of points to select
+ offset = 2.15 # Large offset
+
+ # Randomly select a fraction of an array with timesteps
+ rng = np.random.RandomState(2353425)
+ r = rng.rand(nin)
+ t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+ # Plot a sine wave for the selected times
+ y = ampl * np.sin(w*t + phi)
+
+ # Define the array of frequencies for which to compute the periodogram
+ f = np.linspace(0.01, 10., nout)
+
+ # Calculate Lomb-Scargle periodogram
+ pgram = lombscargle(t, y, f, floating_mean=True)
+ pgram_offset = lombscargle(t, y + offset, f, floating_mean=True)
+
+ # check if offset removal works as expected
+ assert_allclose(pgram, pgram_offset)
+
+ def test_floating_mean_false(self):
+ # Verify that when disabling the floating_mean, the calculations are correct
+
+ # Input parameters
+ ampl = 2.
+ w = 1.
+ phi = 0
+ nin = 1000
+ nout = 1000
+ p = 0.7 # Fraction of points to select
+ offset = 2 # Large offset
+
+ # Randomly select a fraction of an array with timesteps
+ rng = np.random.RandomState(2353425)
+ r = rng.rand(nin)
+ t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+ # Plot a cos wave for the selected times
+ y = ampl * np.cos(w*t + phi)
+
+ # Define the array of frequencies for which to compute the periodogram
+ f = np.linspace(0.01, 10., nout)
+
+ # Calculate Lomb-Scargle periodogram
+ pgram = lombscargle(t, y, f, normalize=True, floating_mean=False)
+ pgram_offset = lombscargle(t, y + offset, f, normalize=True,
+ floating_mean=False)
+
+ # check if disabling floating_mean works as expected
+ # nearly-zero for no offset, exact value will change based on seed
+ assert(pgram[0] < 0.01)
+ # significant value with offset, exact value will change based on seed
+ assert(pgram_offset[0] > 0.5)
+
+ def test_amplitude_is_correct(self):
+ # Verify that the amplitude is correct (when normalize='amplitude')
+
+ # Input parameters
+ ampl = 2.
+ w = 1.
+ phi = 0.12
+ nin = 100
+ nout = 1000
+ p = 0.7 # Fraction of points to select
+ offset = 2.15 # Large offset
+
+ # Randomly select a fraction of an array with timesteps
+ rng = np.random.RandomState(2353425)
+ r = rng.rand(nin)
+ t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+ # Plot a sine wave for the selected times
+ y = ampl * np.cos(w*t + phi) + offset
+
+ # Define the array of frequencies for which to compute the periodogram
+ f = np.linspace(0.01, 10., nout)
+
+ # Get the index of where the exact result should be
+ f_indx = np.where(f==w)[0][0]
+
+ # Calculate Lomb-Scargle periodogram (amplitude + phase)
+ pgram = lombscargle(t, y, f, normalize='amplitude', floating_mean=True)
+
+ # Check if amplitude is correct
+ assert_allclose(np.abs(pgram[f_indx]), ampl)
+
+ # Check if phase is correct
+ # (phase angle is the negative of the phase offset)
+ assert_allclose(-np.angle(pgram[f_indx]), phi)
+
+ def test_negative_weight(self):
+ # Test that a negative weight produces an error
+
+ t = np.zeros(1)
+ y = np.zeros(1)
+ f = np.ones(1)
+ weights = -np.ones(1)
+ assert_raises(ValueError, lombscargle, t, y, f, weights=weights)
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_list_input(self):
+ # Test that input can be passsed in as lists and with a numerical issue
+ # https://github.com/scipy/scipy/issues/8787
+
+ t = [1.98201652e+09, 1.98201752e+09, 1.98201852e+09, 1.98201952e+09,
+ 1.98202052e+09, 1.98202152e+09, 1.98202252e+09, 1.98202352e+09,
+ 1.98202452e+09, 1.98202552e+09, 1.98202652e+09, 1.98202752e+09,
+ 1.98202852e+09, 1.98202952e+09, 1.98203052e+09, 1.98203152e+09,
+ 1.98203252e+09, 1.98203352e+09, 1.98203452e+09, 1.98203552e+09,
+ 1.98205452e+09, 1.98205552e+09, 1.98205652e+09, 1.98205752e+09,
+ 1.98205852e+09, 1.98205952e+09, 1.98206052e+09, 1.98206152e+09,
+ 1.98206252e+09, 1.98206352e+09, 1.98206452e+09, 1.98206552e+09,
+ 1.98206652e+09, 1.98206752e+09, 1.98206852e+09, 1.98206952e+09,
+ 1.98207052e+09, 1.98207152e+09, 1.98207252e+09, 1.98207352e+09,
+ 1.98209652e+09, 1.98209752e+09, 1.98209852e+09, 1.98209952e+09,
+ 1.98210052e+09, 1.98210152e+09, 1.98210252e+09, 1.98210352e+09,
+ 1.98210452e+09, 1.98210552e+09, 1.98210652e+09, 1.98210752e+09,
+ 1.98210852e+09, 1.98210952e+09, 1.98211052e+09, 1.98211152e+09,
+ 1.98211252e+09, 1.98211352e+09, 1.98211452e+09, 1.98211552e+09,
+ 1.98217252e+09, 1.98217352e+09, 1.98217452e+09, 1.98217552e+09,
+ 1.98217652e+09, 1.98217752e+09, 1.98217852e+09, 1.98217952e+09,
+ 1.98218052e+09, 1.98218152e+09, 1.98218252e+09, 1.98218352e+09,
+ 1.98218452e+09, 1.98218552e+09, 1.98218652e+09, 1.98218752e+09,
+ 1.98218852e+09, 1.98218952e+09, 1.98219052e+09, 1.98219152e+09,
+ 1.98219352e+09, 1.98219452e+09, 1.98219552e+09, 1.98219652e+09,
+ 1.98219752e+09, 1.98219852e+09, 1.98219952e+09, 1.98220052e+09,
+ 1.98220152e+09, 1.98220252e+09, 1.98220352e+09, 1.98220452e+09,
+ 1.98220552e+09, 1.98220652e+09, 1.98220752e+09, 1.98220852e+09,
+ 1.98220952e+09, 1.98221052e+09, 1.98221152e+09, 1.98221252e+09,
+ 1.98222752e+09, 1.98222852e+09, 1.98222952e+09, 1.98223052e+09,
+ 1.98223152e+09, 1.98223252e+09, 1.98223352e+09, 1.98223452e+09,
+ 1.98223552e+09, 1.98223652e+09, 1.98223752e+09, 1.98223852e+09,
+ 1.98223952e+09, 1.98224052e+09, 1.98224152e+09, 1.98224252e+09,
+ 1.98224352e+09, 1.98224452e+09, 1.98224552e+09, 1.98224652e+09,
+ 1.98224752e+09]
+ y = [2.97600000e+03, 3.18200000e+03, 3.74900000e+03, 4.53500000e+03,
+ 5.43300000e+03, 6.38000000e+03, 7.34000000e+03, 8.29200000e+03,
+ 9.21900000e+03, 1.01120000e+04, 1.09620000e+04, 1.17600000e+04,
+ 1.25010000e+04, 1.31790000e+04, 1.37900000e+04, 1.43290000e+04,
+ 1.47940000e+04, 1.51800000e+04, 1.54870000e+04, 1.57110000e+04,
+ 5.74200000e+03, 4.82300000e+03, 3.99100000e+03, 3.33600000e+03,
+ 2.99600000e+03, 3.08400000e+03, 3.56700000e+03, 4.30700000e+03,
+ 5.18200000e+03, 6.11900000e+03, 7.07900000e+03, 8.03400000e+03,
+ 8.97000000e+03, 9.87300000e+03, 1.07350000e+04, 1.15480000e+04,
+ 1.23050000e+04, 1.30010000e+04, 1.36300000e+04, 1.41890000e+04,
+ 6.00000000e+03, 5.06800000e+03, 4.20500000e+03, 3.49000000e+03,
+ 3.04900000e+03, 3.01600000e+03, 3.40400000e+03, 4.08800000e+03,
+ 4.93500000e+03, 5.86000000e+03, 6.81700000e+03, 7.77500000e+03,
+ 8.71800000e+03, 9.63100000e+03, 1.05050000e+04, 1.13320000e+04,
+ 1.21050000e+04, 1.28170000e+04, 1.34660000e+04, 1.40440000e+04,
+ 1.32730000e+04, 1.26040000e+04, 1.18720000e+04, 1.10820000e+04,
+ 1.02400000e+04, 9.35300000e+03, 8.43000000e+03, 7.48100000e+03,
+ 6.52100000e+03, 5.57000000e+03, 4.66200000e+03, 3.85400000e+03,
+ 3.24600000e+03, 2.97900000e+03, 3.14700000e+03, 3.68800000e+03,
+ 4.45900000e+03, 5.35000000e+03, 6.29400000e+03, 7.25400000e+03,
+ 9.13800000e+03, 1.00340000e+04, 1.08880000e+04, 1.16910000e+04,
+ 1.24370000e+04, 1.31210000e+04, 1.37380000e+04, 1.42840000e+04,
+ 1.47550000e+04, 1.51490000e+04, 1.54630000e+04, 1.56950000e+04,
+ 1.58430000e+04, 1.59070000e+04, 1.58860000e+04, 1.57800000e+04,
+ 1.55910000e+04, 1.53190000e+04, 1.49650000e+04, 1.45330000e+04,
+ 3.01000000e+03, 3.05900000e+03, 3.51200000e+03, 4.23400000e+03,
+ 5.10000000e+03, 6.03400000e+03, 6.99300000e+03, 7.95000000e+03,
+ 8.88800000e+03, 9.79400000e+03, 1.06600000e+04, 1.14770000e+04,
+ 1.22400000e+04, 1.29410000e+04, 1.35770000e+04, 1.41430000e+04,
+ 1.46350000e+04, 1.50500000e+04, 1.53850000e+04, 1.56400000e+04,
+ 1.58110000e+04]
+
+ periods = np.linspace(400, 120, 1000)
+ angular_freq = 2 * np.pi / periods
+
+ lombscargle(t, y, angular_freq, precenter=True, normalize=True)
+
+ def test_zero_freq(self):
+ # Verify that function works when freqs includes 0
+ # The value at f=0 will depend on the seed
+
+ # Input parameters
+ ampl = 2.
+ w = 1.
+ phi = 0.12
+ nin = 100
+ nout = 1001
+ p = 0.7 # Fraction of points to select
+ offset = 0
+
+ # Randomly select a fraction of an array with timesteps
+ rng = np.random.RandomState(2353425)
+ r = rng.rand(nin)
+ t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+ # Plot a sine wave for the selected times
+ y = ampl * np.cos(w*t + phi) + offset
+
+ # Define the array of frequencies for which to compute the periodogram
+ f = np.linspace(0, 10., nout)
+
+ # Calculate Lomb-Scargle periodogram
+ pgram = lombscargle(t, y, f, normalize=True, floating_mean=True)
+
+ # exact value will change based on seed
+ # testing to make sure it is very small
+ assert(pgram[0] < 1e-4)
+
+ def test_simple_div_zero(self):
+ # these are bare-minimum examples that would, without the eps adjustments,
+ # cause division-by-zero errors
+
+ # first, test with example that will cause first SS sum to be 0.0
+ t = [t + 1 for t in range(0, 32)]
+ y = np.ones(len(t))
+ freqs = [2.0*np.pi] * 2 # must have 2+ elements
+ lombscargle(t, y, freqs)
+
+ # second, test with example that will cause first CC sum to be 0.0
+ t = [t*4 + 1 for t in range(0, 32)]
+ y = np.ones(len(t))
+ freqs = [np.pi/2.0] * 2 # must have 2+ elements
+
+ lombscargle(t, y, freqs)
+
+ @pytest.mark.filterwarnings("ignore::DeprecationWarning")
+ def test_input_mutation(self):
+ # this tests for mutation of the input arrays
+ # https://github.com/scipy/scipy/issues/23474
+
+ # Input parameters
+ ampl = 2.
+ w = 1.
+ phi = 0.5 * np.pi
+ nin = 100
+ nout = 1000
+ p = 0.7 # Fraction of points to select
+
+ # Randomly select a fraction of an array with timesteps
+ rng = np.random.default_rng()
+ r = rng.random(nin)
+ t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+ # Plot a sine wave for the selected times
+ y = ampl * np.sin(w*t + phi)
+
+ # Define the array of frequencies for which to compute the periodogram
+ f = np.linspace(0.01, 10., nout)
+
+ weights = np.ones_like(y)
+
+ # create original copies before passing
+ t_org = t.copy()
+ y_org = y.copy()
+ f_org = f.copy()
+ weights_org = weights.copy()
+
+ lombscargle(t, y, f, precenter=True, weights=weights)
+
+ # check all 4 array inputs
+ assert_array_equal(t, t_org)
+ assert_array_equal(y, y_org)
+ assert_array_equal(f, f_org)
+ assert_array_equal(weights, weights_org)
+
+ def test_precenter_deprecation(self):
+ # test that precenter deprecation warning is raised
+
+ # Input parameters
+ ampl = 2.
+ w = 1.
+ phi = 0.5 * np.pi
+ nin = 100
+ nout = 1000
+ p = 0.7 # Fraction of points to select
+ offset = 0.15 # Offset to be subtracted in pre-centering
+
+ # Randomly select a fraction of an array with timesteps
+ rng = np.random.default_rng()
+ r = rng.random(nin)
+ t = np.linspace(0.01*np.pi, 10.*np.pi, nin)[r >= p]
+
+ # Plot a sine wave for the selected times
+ y = ampl * np.sin(w*t + phi) + offset
+
+ # Define the array of frequencies for which to compute the periodogram
+ f = np.linspace(0.01, 10., nout)
+
+ # Calculate Lomb-Scargle periodogram
+ with pytest.deprecated_call(match="leave 'precenter' unspecified"):
+ lombscargle(t, y, f, precenter=True)
+ # Should warn for explicit `False` too
+ with pytest.deprecated_call(match="leave 'precenter' unspecified"):
+ lombscargle(t, y, f, precenter=False)
+
+ @pytest.mark.filterwarnings(
+ "ignore:.*leave 'precenter' unspecified.*:DeprecationWarning"
+ )
+ def test_positional_args_deprecation(self):
+ with pytest.deprecated_call(match="use keyword arguments"):
+ one = np.asarray([1.0])
+ lombscargle(one, one, one, False)
+
+
+class TestSTFT:
+ def test_input_validation(self):
+
+ def chk_VE(match):
+ """Assert for a ValueError matching regexp `match`.
+
+ This little wrapper allows a more concise code layout.
+ """
+ return pytest.raises(ValueError, match=match)
+
+ # Checks for check_COLA():
+ with chk_VE('nperseg must be a positive integer'):
+ check_COLA('hann', -10, 0)
+ with chk_VE('noverlap must be less than nperseg.'):
+ check_COLA('hann', 10, 20)
+ with chk_VE('window must be 1-D'):
+ check_COLA(np.ones((2, 2)), 10, 0)
+ with chk_VE('window must have length of nperseg'):
+ check_COLA(np.ones(20), 10, 0)
+
+ # Checks for check_NOLA():
+ with chk_VE('nperseg must be a positive integer'):
+ check_NOLA('hann', -10, 0)
+ with chk_VE('noverlap must be less than nperseg'):
+ check_NOLA('hann', 10, 20)
+ with chk_VE('window must be 1-D'):
+ check_NOLA(np.ones((2, 2)), 10, 0)
+ with chk_VE('window must have length of nperseg'):
+ check_NOLA(np.ones(20), 10, 0)
+ with chk_VE('noverlap must be a nonnegative integer'):
+ check_NOLA('hann', 64, -32)
+
+ x = np.zeros(1024)
+ z = stft(x)[2]
+
+ # Checks for stft():
+ with chk_VE('window must be 1-D'):
+ stft(x, window=np.ones((2, 2)))
+ with chk_VE('value specified for nperseg is different ' +
+ 'from length of window'):
+ stft(x, window=np.ones(10), nperseg=256)
+ with chk_VE('nperseg must be a positive integer'):
+ stft(x, nperseg=-256)
+ with chk_VE('noverlap must be less than nperseg.'):
+ stft(x, nperseg=256, noverlap=1024)
+ with chk_VE('nfft must be greater than or equal to nperseg.'):
+ stft(x, nperseg=256, nfft=8)
+
+ # Checks for istft():
+ with chk_VE('Input stft must be at least 2d!'):
+ istft(x)
+ with chk_VE('window must be 1-D'):
+ istft(z, window=np.ones((2, 2)))
+ with chk_VE('window must have length of 256'):
+ istft(z, window=np.ones(10), nperseg=256)
+ with chk_VE('nperseg must be a positive integer'):
+ istft(z, nperseg=-256)
+ with chk_VE('noverlap must be less than nperseg.'):
+ istft(z, nperseg=256, noverlap=1024)
+ with chk_VE('nfft must be greater than or equal to nperseg.'):
+ istft(z, nperseg=256, nfft=8)
+ with pytest.warns(UserWarning, match="NOLA condition failed, " +
+ "STFT may not be invertible"):
+ istft(z, nperseg=256, noverlap=0, window='hann')
+ with chk_VE('Must specify differing time and frequency axes!'):
+ istft(z, time_axis=0, freq_axis=0)
+
+ # Checks for _spectral_helper():
+ with chk_VE("Unknown value for mode foo, must be one of: " +
+ r"\{'psd', 'stft'\}"):
+ _spectral_helper(x, x, mode='foo')
+ with chk_VE("x and y must be equal if mode is 'stft'"):
+ _spectral_helper(x[:512], x[512:], mode='stft')
+ with chk_VE("Unknown boundary option 'foo', must be one of: " +
+ r"\['even', 'odd', 'constant', 'zeros', None\]"):
+ _spectral_helper(x, x, boundary='foo')
+
+ scaling = "not_valid"
+ with chk_VE(fr"Parameter {scaling=} not in \['spectrum', 'psd'\]!"):
+ stft(x, scaling=scaling)
+ with chk_VE(fr"Parameter {scaling=} not in \['spectrum', 'psd'\]!"):
+ istft(z, scaling=scaling)
+
+ def test_check_COLA(self):
+ settings = [
+ ('boxcar', 10, 0),
+ ('boxcar', 10, 9),
+ ('bartlett', 51, 26),
+ ('hann', 256, 128),
+ ('hann', 256, 192),
+ ('blackman', 300, 200),
+ (('tukey', 0.5), 256, 64),
+ ('hann', 256, 255),
+ ]
+
+ for setting in settings:
+ msg = '{}, {}, {}'.format(*setting)
+ assert_equal(True, check_COLA(*setting), err_msg=msg)
+
+ def test_check_NOLA(self):
+ settings_pass = [
+ ('boxcar', 10, 0),
+ ('boxcar', 10, 9),
+ ('boxcar', 10, 7),
+ ('bartlett', 51, 26),
+ ('bartlett', 51, 10),
+ ('hann', 256, 128),
+ ('hann', 256, 192),
+ ('hann', 256, 37),
+ ('blackman', 300, 200),
+ ('blackman', 300, 123),
+ (('tukey', 0.5), 256, 64),
+ (('tukey', 0.5), 256, 38),
+ ('hann', 256, 255),
+ ('hann', 256, 39),
+ ]
+ for setting in settings_pass:
+ msg = '{}, {}, {}'.format(*setting)
+ assert_equal(True, check_NOLA(*setting), err_msg=msg)
+
+ w_fail = np.ones(16)
+ w_fail[::2] = 0
+ settings_fail = [
+ (w_fail, len(w_fail), len(w_fail) // 2),
+ ('hann', 64, 0),
+ ]
+ for setting in settings_fail:
+ msg = '{}, {}, {}'.format(*setting)
+ assert_equal(False, check_NOLA(*setting), err_msg=msg)
+
+ def test_average_all_segments(self):
+ rng = np.random.RandomState(1234)
+ x = rng.randn(1024)
+
+ fs = 1.0
+ window = 'hann'
+ nperseg = 16
+ noverlap = 8
+
+ # Compare twosided, because onesided welch doubles non-DC terms to
+ # account for power at negative frequencies. stft doesn't do this,
+ # because it breaks invertibility.
+ f, _, Z = stft(x, fs, window, nperseg, noverlap, padded=False,
+ return_onesided=False, boundary=None)
+ fw, Pw = welch(x, fs, window, nperseg, noverlap, return_onesided=False,
+ scaling='spectrum', detrend=False)
+
+ assert_allclose(f, fw)
+ assert_allclose(np.mean(np.abs(Z)**2, axis=-1), Pw)
+
+ def test_permute_axes(self):
+ rng = np.random.RandomState(1234)
+ x = rng.randn(1024)
+
+ fs = 1.0
+ window = 'hann'
+ nperseg = 16
+ noverlap = 8
+
+ f1, t1, Z1 = stft(x, fs, window, nperseg, noverlap)
+ f2, t2, Z2 = stft(x.reshape((-1, 1, 1)), fs, window, nperseg, noverlap,
+ axis=0)
+
+ t3, x1 = istft(Z1, fs, window, nperseg, noverlap)
+ t4, x2 = istft(Z2.T, fs, window, nperseg, noverlap, time_axis=0,
+ freq_axis=-1)
+
+ assert_allclose(f1, f2)
+ assert_allclose(t1, t2)
+ assert_allclose(t3, t4)
+ assert_allclose(Z1, Z2[:, 0, 0, :])
+ assert_allclose(x1, x2[:, 0, 0])
+
+ @pytest.mark.parametrize('scaling', ['spectrum', 'psd'])
+ def test_roundtrip_real(self, scaling):
+ rng = np.random.RandomState(1234)
+
+ settings = [
+ ('boxcar', 100, 10, 0), # Test no overlap
+ ('boxcar', 100, 10, 9), # Test high overlap
+ ('bartlett', 101, 51, 26), # Test odd nperseg
+ ('hann', 1024, 256, 128), # Test defaults
+ (('tukey', 0.5), 1152, 256, 64), # Test Tukey
+ ('hann', 1024, 256, 255), # Test overlapped hann
+ ]
+
+ for window, N, nperseg, noverlap in settings:
+ t = np.arange(N)
+ x = 10*rng.randn(t.size)
+
+ _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+ window=window, detrend=None, padded=False,
+ scaling=scaling)
+
+ tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+ window=window, scaling=scaling)
+
+ msg = f'{window}, {noverlap}'
+ assert_allclose(t, tr, err_msg=msg)
+ assert_allclose(x, xr, err_msg=msg)
+
+ def test_roundtrip_not_nola(self):
+ rng = np.random.RandomState(1234)
+
+ w_fail = np.ones(16)
+ w_fail[::2] = 0
+ settings = [
+ (w_fail, 256, len(w_fail), len(w_fail) // 2),
+ ('hann', 256, 64, 0),
+ ]
+
+ for window, N, nperseg, noverlap in settings:
+ msg = f'{window}, {N}, {nperseg}, {noverlap}'
+ assert not check_NOLA(window, nperseg, noverlap), msg
+
+ t = np.arange(N)
+ x = 10 * rng.randn(t.size)
+
+ _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+ window=window, detrend=None, padded=True,
+ boundary='zeros')
+ with pytest.warns(UserWarning, match='NOLA'):
+ tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+ window=window, boundary=True)
+
+ assert np.allclose(t, tr[:len(t)]), msg
+ assert not np.allclose(x, xr[:len(x)]), msg
+
+ def test_roundtrip_nola_not_cola(self):
+ rng = np.random.RandomState(1234)
+
+ settings = [
+ ('boxcar', 100, 10, 3), # NOLA True, COLA False
+ ('bartlett', 101, 51, 37), # NOLA True, COLA False
+ ('hann', 1024, 256, 127), # NOLA True, COLA False
+ (('tukey', 0.5), 1152, 256, 14), # NOLA True, COLA False
+ ('hann', 1024, 256, 5), # NOLA True, COLA False
+ ]
+
+ for window, N, nperseg, noverlap in settings:
+ msg = f'{window}, {nperseg}, {noverlap}'
+ assert check_NOLA(window, nperseg, noverlap), msg
+ assert not check_COLA(window, nperseg, noverlap), msg
+
+ t = np.arange(N)
+ x = 10 * rng.randn(t.size)
+
+ _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+ window=window, detrend=None, padded=True,
+ boundary='zeros')
+
+ tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+ window=window, boundary=True)
+
+ msg = f'{window}, {noverlap}'
+ assert_allclose(t, tr[:len(t)], err_msg=msg)
+ assert_allclose(x, xr[:len(x)], err_msg=msg)
+
+ def test_roundtrip_float32(self):
+ rng = np.random.RandomState(1234)
+
+ settings = [('hann', 1024, 256, 128)]
+
+ for window, N, nperseg, noverlap in settings:
+ t = np.arange(N)
+ x = 10*rng.randn(t.size)
+ x = x.astype(np.float32)
+
+ _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+ window=window, detrend=None, padded=False)
+
+ tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+ window=window)
+
+ msg = f'{window}, {noverlap}'
+ assert_allclose(t, t, err_msg=msg)
+ assert_allclose(x, xr, err_msg=msg, rtol=1e-4, atol=1e-5)
+ assert_(x.dtype == xr.dtype)
+
+ @pytest.mark.parametrize('scaling', ['spectrum', 'psd'])
+ def test_roundtrip_complex(self, scaling):
+ rng = np.random.RandomState(1234)
+
+ settings = [
+ ('boxcar', 100, 10, 0), # Test no overlap
+ ('boxcar', 100, 10, 9), # Test high overlap
+ ('bartlett', 101, 51, 26), # Test odd nperseg
+ ('hann', 1024, 256, 128), # Test defaults
+ (('tukey', 0.5), 1152, 256, 64), # Test Tukey
+ ('hann', 1024, 256, 255), # Test overlapped hann
+ ]
+
+ for window, N, nperseg, noverlap in settings:
+ t = np.arange(N)
+ x = 10*rng.randn(t.size) + 10j*rng.randn(t.size)
+
+ _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+ window=window, detrend=None, padded=False,
+ return_onesided=False, scaling=scaling)
+
+ tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+ window=window, input_onesided=False,
+ scaling=scaling)
+
+ msg = f'{window}, {nperseg}, {noverlap}'
+ assert_allclose(t, tr, err_msg=msg)
+ assert_allclose(x, xr, err_msg=msg)
+
+ # Check that asking for onesided switches to twosided
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore",
+ "Input data is complex, switching to return_onesided=False",
+ UserWarning,
+ )
+ _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+ window=window, detrend=None, padded=False,
+ return_onesided=True, scaling=scaling)
+
+ tr, xr = istft(zz, nperseg=nperseg, noverlap=noverlap,
+ window=window, input_onesided=False, scaling=scaling)
+
+ msg = f'{window}, {nperseg}, {noverlap}'
+ assert_allclose(t, tr, err_msg=msg)
+ assert_allclose(x, xr, err_msg=msg)
+
+ def test_roundtrip_boundary_extension(self):
+ rng = np.random.RandomState(1234)
+
+ # Test against boxcar, since window is all ones, and thus can be fully
+ # recovered with no boundary extension
+
+ settings = [
+ ('boxcar', 100, 10, 0), # Test no overlap
+ ('boxcar', 100, 10, 9), # Test high overlap
+ ]
+
+ for window, N, nperseg, noverlap in settings:
+ t = np.arange(N)
+ x = 10*rng.randn(t.size)
+
+ _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+ window=window, detrend=None, padded=True,
+ boundary=None)
+
+ _, xr = istft(zz, noverlap=noverlap, window=window, boundary=False)
+
+ for boundary in ['even', 'odd', 'constant', 'zeros']:
+ _, _, zz_ext = stft(x, nperseg=nperseg, noverlap=noverlap,
+ window=window, detrend=None, padded=True,
+ boundary=boundary)
+
+ _, xr_ext = istft(zz_ext, noverlap=noverlap, window=window,
+ boundary=True)
+
+ msg = f'{window}, {noverlap}, {boundary}'
+ assert_allclose(x, xr, err_msg=msg)
+ assert_allclose(x, xr_ext, err_msg=msg)
+
+ def test_roundtrip_padded_signal(self):
+ rng = np.random.RandomState(1234)
+
+ settings = [
+ ('boxcar', 101, 10, 0),
+ ('hann', 1000, 256, 128),
+ ]
+
+ for window, N, nperseg, noverlap in settings:
+ t = np.arange(N)
+ x = 10*rng.randn(t.size)
+
+ _, _, zz = stft(x, nperseg=nperseg, noverlap=noverlap,
+ window=window, detrend=None, padded=True)
+
+ tr, xr = istft(zz, noverlap=noverlap, window=window)
+
+ msg = f'{window}, {noverlap}'
+ # Account for possible zero-padding at the end
+ assert_allclose(t, tr[:t.size], err_msg=msg)
+ assert_allclose(x, xr[:x.size], err_msg=msg)
+
+ def test_roundtrip_padded_FFT(self):
+ rng = np.random.RandomState(1234)
+
+ settings = [
+ ('hann', 1024, 256, 128, 512),
+ ('hann', 1024, 256, 128, 501),
+ ('boxcar', 100, 10, 0, 33),
+ (('tukey', 0.5), 1152, 256, 64, 1024),
+ ]
+
+ for window, N, nperseg, noverlap, nfft in settings:
+ t = np.arange(N)
+ x = 10*rng.randn(t.size)
+ xc = x*np.exp(1j*np.pi/4)
+
+ # real signal
+ _, _, z = stft(x, nperseg=nperseg, noverlap=noverlap, nfft=nfft,
+ window=window, detrend=None, padded=True)
+
+ # complex signal
+ _, _, zc = stft(xc, nperseg=nperseg, noverlap=noverlap, nfft=nfft,
+ window=window, detrend=None, padded=True,
+ return_onesided=False)
+
+ tr, xr = istft(z, nperseg=nperseg, noverlap=noverlap, nfft=nfft,
+ window=window)
+
+ tr, xcr = istft(zc, nperseg=nperseg, noverlap=noverlap, nfft=nfft,
+ window=window, input_onesided=False)
+
+ msg = f'{window}, {noverlap}'
+ assert_allclose(t, tr, err_msg=msg)
+ assert_allclose(x, xr, err_msg=msg)
+ assert_allclose(xc, xcr, err_msg=msg)
+
+ def test_axis_rolling(self):
+ rng = np.random.RandomState(1234)
+
+ x_flat = rng.randn(1024)
+ _, _, z_flat = stft(x_flat)
+
+ for a in range(3):
+ newshape = [1,]*3
+ newshape[a] = -1
+ x = x_flat.reshape(newshape)
+
+ _, _, z_plus = stft(x, axis=a) # Positive axis index
+ _, _, z_minus = stft(x, axis=a-x.ndim) # Negative axis index
+
+ assert_equal(z_flat, z_plus.squeeze(), err_msg=a)
+ assert_equal(z_flat, z_minus.squeeze(), err_msg=a-x.ndim)
+
+ # z_flat has shape [n_freq, n_time]
+
+ # Test vs. transpose
+ _, x_transpose_m = istft(z_flat.T, time_axis=-2, freq_axis=-1)
+ _, x_transpose_p = istft(z_flat.T, time_axis=0, freq_axis=1)
+
+ assert_allclose(x_flat, x_transpose_m, err_msg='istft transpose minus')
+ assert_allclose(x_flat, x_transpose_p, err_msg='istft transpose plus')
+
+ def test_roundtrip_scaling(self):
+ """Verify behavior of scaling parameter. """
+ # Create 1024 sample cosine signal with amplitude 2:
+ X = np.zeros(513, dtype=complex)
+ X[256] = 1024
+ x = np.fft.irfft(X)
+ power_x = sum(x**2) / len(x) # power of signal x is 2
+
+ # Calculate magnitude-scaled STFT:
+ Zs = stft(x, boundary='even', scaling='spectrum')[2]
+
+ # Test round trip:
+ x1 = istft(Zs, boundary=True, scaling='spectrum')[1]
+ assert_allclose(x1, x)
+
+ # For a Hann-windowed 256 sample length FFT, we expect a peak at
+ # frequency 64 (since it is 1/4 the length of X) with a height of 1
+ # (half the amplitude). A Hann window of a perfectly centered sine has
+ # the magnitude [..., 0, 0, 0.5, 1, 0.5, 0, 0, ...].
+ # Note that in this case the 'even' padding works for the beginning
+ # but not for the end of the STFT.
+ assert_allclose(abs(Zs[63, :-1]), 0.5)
+ assert_allclose(abs(Zs[64, :-1]), 1)
+ assert_allclose(abs(Zs[65, :-1]), 0.5)
+ # All other values should be zero:
+ Zs[63:66, :-1] = 0
+ # Note since 'rtol' does not have influence here, atol needs to be set:
+ assert_allclose(Zs[:, :-1], 0, atol=np.finfo(Zs.dtype).resolution)
+
+ # Calculate two-sided psd-scaled STFT:
+ # - using 'even' padding since signal is axis symmetric - this ensures
+ # stationary behavior on the boundaries
+ # - using the two-sided transform allows determining the spectral
+ # power by `sum(abs(Zp[:, k])**2) / len(f)` for the k-th time slot.
+ Zp = stft(x, return_onesided=False, boundary='even', scaling='psd')[2]
+
+ # Calculate spectral power of Zd by summing over the frequency axis:
+ psd_Zp = np.sum(Zp.real**2 + Zp.imag**2, axis=0) / Zp.shape[0]
+ # Spectral power of Zp should be equal to the signal's power:
+ assert_allclose(psd_Zp, power_x)
+
+ # Test round trip:
+ x1 = istft(Zp, input_onesided=False, boundary=True, scaling='psd')[1]
+ assert_allclose(x1, x)
+
+ # The power of the one-sided psd-scaled STFT can be determined
+ # analogously (note that the two sides are not of equal shape):
+ Zp0 = stft(x, return_onesided=True, boundary='even', scaling='psd')[2]
+
+ # Since x is real, its Fourier transform is conjugate symmetric, i.e.,
+ # the missing 'second side' can be expressed through the 'first side':
+ Zp1 = np.conj(Zp0[-2:0:-1, :]) # 'second side' is conjugate reversed
+ assert_allclose(Zp[:129, :], Zp0)
+ assert_allclose(Zp[129:, :], Zp1)
+
+ # Calculate the spectral power:
+ s2 = (np.sum(Zp0.real ** 2 + Zp0.imag ** 2, axis=0) +
+ np.sum(Zp1.real ** 2 + Zp1.imag ** 2, axis=0))
+ psd_Zp01 = s2 / (Zp0.shape[0] + Zp1.shape[0])
+ assert_allclose(psd_Zp01, power_x)
+
+ # Test round trip:
+ x1 = istft(Zp0, input_onesided=True, boundary=True, scaling='psd')[1]
+ assert_allclose(x1, x)
+
+
+class TestSampledSpectralRepresentations:
+ """Check energy/power relations from `Spectral Analysis` section in the user guide.
+
+ A 32 sample cosine signal is used to compare the numerical to the expected results
+ stated in :ref:`tutorial_SpectralAnalysis` in
+ file ``doc/source/tutorial/signal.rst``
+ """
+ n: int = 32 #: number of samples
+ T: float = 1/16 #: sampling interval
+ a_ref: float = 3 #: amplitude of reference
+ l_a: int = 3 #: index in fft for defining frequency of test signal
+
+ x_ref: np.ndarray #: reference signal
+ X_ref: np.ndarray #: two-sided FFT of x_ref
+ E_ref: float #: energy of signal
+ P_ref: float #: power of signal
+
+ def setup_method(self):
+ """Create Cosine signal with amplitude a from spectrum. """
+ f = rfftfreq(self.n, self.T)
+ X_ref = np.zeros_like(f)
+ self.l_a = 3
+ X_ref[self.l_a] = self.a_ref/2 * self.n # set amplitude
+ self.x_ref = irfft(X_ref)
+ self.X_ref = fft(self.x_ref)
+
+ # Closed form expression for continuous-time signal:
+ self.E_ref = self.tau * self.a_ref**2 / 2 # energy of signal
+ self.P_ref = self.a_ref**2 / 2 # power of signal
+
+ @property
+ def tau(self) -> float:
+ """Duration of signal. """
+ return self.n * self.T
+
+ @property
+ def delta_f(self) -> float:
+ """Bin width """
+ return 1 / (self.n * self.T)
+
+ def test_reference_signal(self):
+ """Test energy and power formulas. """
+ # Verify that amplitude is a:
+ assert_allclose(2*self.a_ref, np.ptp(self.x_ref), rtol=0.1)
+ # Verify that energy expression for sampled signal:
+ assert_allclose(self.T * sum(self.x_ref ** 2), self.E_ref)
+
+ # Verify that spectral energy and power formulas are correct:
+ sum_X_ref_squared = sum(self.X_ref.real**2 + self.X_ref.imag**2)
+ assert_allclose(self.T/self.n * sum_X_ref_squared, self.E_ref)
+ assert_allclose(1/self.n**2 * sum_X_ref_squared, self.P_ref)
+
+ def test_windowed_DFT(self):
+ """Verify spectral representations of windowed DFT.
+
+ Furthermore, the scalings of `periodogram` and `welch` are verified.
+ """
+ w = hann(self.n, sym=False)
+ c_amp, c_rms = abs(sum(w)), np.sqrt(sum(w.real**2 + w.imag**2))
+ Xw = fft(self.x_ref*w) # unnormalized windowed DFT
+
+ # Verify that the *spectrum* peak is consistent:
+ assert_allclose(self.tau * Xw[self.l_a] / c_amp, self.a_ref * self.tau / 2)
+ # Verify that the *amplitude spectrum* peak is consistent:
+ assert_allclose(Xw[self.l_a] / c_amp, self.a_ref/2)
+
+ # Verify spectral power/energy equals signal's power/energy:
+ X_ESD = self.tau * self.T * abs(Xw / c_rms)**2 # Energy Spectral Density
+ X_PSD = self.T * abs(Xw / c_rms)**2 # Power Spectral Density
+ assert_allclose(self.delta_f * sum(X_ESD), self.E_ref)
+ assert_allclose(self.delta_f * sum(X_PSD), self.P_ref)
+
+ # Verify scalings of periodogram:
+ kw = dict(fs=1/self.T, window=w, detrend=False, return_onesided=False)
+ _, P_mag = periodogram(self.x_ref, scaling='spectrum', **kw)
+ _, P_psd = periodogram(self.x_ref, scaling='density', **kw)
+
+ # Verify that periodogram calculates a squared magnitude spectrum:
+ float_res = np.finfo(P_mag.dtype).resolution
+ assert_allclose(P_mag, abs(Xw/c_amp)**2, atol=float_res*max(P_mag))
+ # Verify that periodogram calculates a PSD:
+ assert_allclose(P_psd, X_PSD, atol=float_res*max(P_psd))
+
+ # Ensure that scaling of welch is the same as of periodogram:
+ kw = dict(nperseg=len(self.x_ref), noverlap=0, **kw)
+ assert_allclose(welch(self.x_ref, scaling='spectrum', **kw)[1], P_mag,
+ atol=float_res*max(P_mag))
+ assert_allclose(welch(self.x_ref, scaling='density', **kw)[1], P_psd,
+ atol=float_res*max(P_psd))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_splines.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_splines.py
new file mode 100644
index 0000000000000000000000000000000000000000..42e352a952eaa174cd5c6d6312e4c330a2c5dd15
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_splines.py
@@ -0,0 +1,422 @@
+# pylint: disable=missing-docstring
+import math
+import numpy as np
+import pytest
+from scipy._lib._array_api import is_cupy, xp_assert_close, xp_default_dtype, concat_1d
+
+from scipy.signal._spline import (
+ symiirorder1_ic, symiirorder2_ic_fwd, symiirorder2_ic_bwd)
+from scipy.signal import symiirorder1, symiirorder2
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+
+def _compute_symiirorder2_bwd_hs(k, cs, rsq, omega):
+ cssq = cs * cs
+ k = np.abs(k)
+ rsupk = np.power(rsq, k / 2.0)
+
+ c0 = (cssq * (1.0 + rsq) / (1.0 - rsq) /
+ (1 - 2 * rsq * np.cos(2 * omega) + rsq * rsq))
+ gamma = (1.0 - rsq) / (1.0 + rsq) / np.tan(omega)
+ return c0 * rsupk * (np.cos(omega * k) + gamma * np.sin(omega * k))
+
+
+class TestSymIIR:
+
+ @skip_xp_backends(np_only=True, reason="_ic functions are private and numpy-only")
+ @pytest.mark.parametrize(
+ 'dtype', ['float32', 'float64', 'complex64', 'complex128'])
+ @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075])
+ def test_symiir1_ic(self, dtype, precision, xp):
+
+ dtype = getattr(xp, dtype)
+
+ c_precision = precision
+ if precision <= 0.0 or precision > 1.0:
+ if dtype in {xp.float32, xp.complex64}:
+ c_precision = 1e-6
+ else:
+ c_precision = 1e-11
+
+ # Symmetrical initial conditions for a IIR filter of order 1 are:
+ # x[0] + z1 * \sum{k = 0}^{n - 1} x[k] * z1^k
+
+ # Check the initial condition for a low-pass filter
+ # with coefficient b = 0.85 on a step signal. The initial condition is
+ # a geometric series: 1 + b * \sum_{k = 0}^{n - 1} u[k] b^k.
+
+ # Finding the initial condition corresponds to
+ # 1. Computing the index n such that b**n < precision, which
+ # corresponds to ceil(log(precision) / log(b))
+ # 2. Computing the geometric series until n, this can be computed
+ # using the partial sum formula: (1 - b**n) / (1 - b)
+ # This holds due to the input being a step signal.
+ b = 0.85
+ n_exp = int(math.ceil(math.log(c_precision) / math.log(b)))
+ expected = xp.asarray([[(1 - b ** n_exp) / (1 - b)]], dtype=dtype)
+ expected = 1 + b * expected
+
+ # Create a step signal of size n + 1
+ x = xp.ones(n_exp + 1, dtype=dtype)
+ xp_assert_close(symiirorder1_ic(x, b, precision), expected,
+ atol=2e-6, rtol=2e-7)
+
+ # Check the conditions for an exponential decreasing signal with base 2.
+ # Same conditions hold, as the product of 0.5^n * 0.85^n is
+ # still a geometric series
+ b_d = xp.asarray(b, dtype=dtype)
+ expected = np.asarray(
+ [[(1 - (0.5 * b_d) ** n_exp) / (1 - (0.5 * b_d))]], dtype=dtype)
+ expected = 1 + b_d * expected
+
+ # Create an exponential decreasing signal of size n + 1
+ x = 2 ** -xp.arange(n_exp + 1, dtype=dtype)
+ xp_assert_close(symiirorder1_ic(x, b, precision), expected,
+ atol=2e-6, rtol=2e-7)
+
+ @skip_xp_backends(np_only=True, reason="_ic functions are private and numpy-only")
+ def test_symiir1_ic_fails(self, xp):
+ # Test that symiirorder1_ic fails whenever \sum_{n = 1}^{n} b^n > eps
+ b = 0.85
+ # Create a step signal of size 100
+ x = xp.ones(100, dtype=xp.float64)
+
+ # Compute the closed form for the geometrical series
+ precision = 1 / (1 - b)
+ pytest.raises(ValueError, symiirorder1_ic, x, b, precision)
+
+ # Test that symiirorder1_ic fails when |z1| >= 1
+ pytest.raises(ValueError, symiirorder1_ic, x, 1.0, -1)
+ pytest.raises(ValueError, symiirorder1_ic, x, 2.0, -1)
+
+ @skip_xp_backends(
+ cpu_only=True, exceptions=["cupy"], reason="internals are numpy-only"
+ )
+ @xfail_xp_backends("cupy", reason="sum did not converge")
+ @skip_xp_backends("jax.numpy", reason="item assignment in tests")
+ @pytest.mark.parametrize(
+ 'dtype', ['float32', 'float64', 'complex64', 'complex128'])
+ @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075])
+ def test_symiir1(self, dtype, precision, xp):
+ dtype = getattr(xp, dtype)
+
+ c_precision = precision
+ if precision <= 0.0 or precision > 1.0:
+ if dtype in {xp.float32, xp.complex64}:
+ c_precision = 1e-6
+ else:
+ c_precision = 1e-11
+
+ # Test for a low-pass filter with c0 = 0.15 and z1 = 0.85
+ # using an unit step over 200 samples.
+ c0 = 0.15
+ z1 = 0.85
+ n = 200
+ signal = xp.ones(n, dtype=dtype)
+
+ # Find the initial condition. See test_symiir1_ic for a detailed
+ # explanation
+ n_exp = int(math.ceil(math.log(c_precision) / math.log(z1)))
+ initial = xp.asarray((1 - z1 ** n_exp) / (1 - z1), dtype=dtype)
+ initial = 1 + z1 * initial
+
+ # Forward pass
+ # The transfer function for the system 1 / (1 - z1 * z^-1) when
+ # applied to an unit step with initial conditions y0 is
+ # 1 / (1 - z1 * z^-1) * (z^-1 / (1 - z^-1) + y0)
+
+ # Solving the inverse Z-transform for the given expression yields:
+ # y[n] = y0 * z1**n * u[n] +
+ # -z1 / (1 - z1) * z1**(k - 1) * u[k - 1] +
+ # 1 / (1 - z1) * u[k - 1]
+ # d is the Kronecker delta function, and u is the unit step
+
+ # y0 * z1**n * u[n]
+ pos = xp.astype(xp.arange(n), dtype)
+ comp1 = initial * z1**pos
+
+ # -z1 / (1 - z1) * z1**(k - 1) * u[k - 1]
+ comp2 = xp.zeros(n, dtype=dtype)
+ comp2[1:] = -z1 / (1 - z1) * z1**pos[:-1]
+
+ # 1 / (1 - z1) * u[k - 1]
+ comp3 = xp.zeros(n, dtype=dtype)
+ comp3[1:] = 1 / (1 - z1)
+
+ expected_fwd = comp1 + comp2 + comp3
+
+ # Reverse condition
+ sym_cond = -c0 / (z1 - 1.0) * expected_fwd[-1]
+
+ # Backward pass
+ # The transfer function for the forward result is equivalent to
+ # the forward system times c0 / (1 - z1 * z).
+
+ # Computing a closed form for the complete expression is difficult
+ # The result will be computed iteratively from the difference equation
+ exp_out = xp.zeros(n, dtype=dtype)
+ exp_out[0] = sym_cond
+
+ for i in range(1, n):
+ exp_out[i] = c0 * expected_fwd[n - 1 - i] + z1 * exp_out[i - 1]
+
+ exp_out = xp.flip(exp_out)
+
+ out = symiirorder1(signal, c0, z1, precision)
+ xp_assert_close(out, exp_out, atol=4e-6, rtol=6e-7)
+
+ @xfail_xp_backends("cupy", reason="sum did not converge")
+ @skip_xp_backends(
+ cpu_only=True, exceptions=["cupy"], reason="internals are numpy-only"
+ )
+ @pytest.mark.parametrize('dtype', ['float32', 'float64'])
+ def test_symiir1_values(self, dtype, xp):
+ rng = np.random.RandomState(1234)
+ s = rng.uniform(size=16).astype(dtype)
+ dtype = getattr(xp, dtype)
+ s = xp.asarray(s)
+ res = symiirorder1(s, 0.5, 0.1)
+
+ # values from scipy 1.9.1
+ exp_res = xp.asarray([
+ 0.14387447, 0.35166047, 0.29735238, 0.46295986, 0.45174927,
+ 0.19982875, 0.20355805, 0.47378628, 0.57232247, 0.51597393,
+ 0.25935107, 0.31438554, 0.41096728, 0.4190693 , 0.25812255,
+ 0.33671467], dtype=res.dtype)
+ atol = {xp.float64: 1e-15, xp.float32: 1e-7}[dtype]
+ xp_assert_close(res, exp_res, atol=atol)
+
+ I1 = xp.asarray(
+ 1 + 1j, dtype=xp.result_type(s, xp.complex64)
+ )
+ s = s * I1
+ res = symiirorder1(s, 0.5, 0.1)
+ assert res.dtype == xp.complex64 if dtype == xp.float32 else xp.complex128
+ xp_assert_close(res, I1 * exp_res, atol=atol)
+
+ @skip_xp_backends(np_only=True,
+ reason="_initial_fwd functions are private and numpy-only")
+ @pytest.mark.parametrize(
+ 'dtype', ['float32', 'float64'])
+ @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075])
+ def test_symiir2_initial_fwd(self, dtype, precision, xp):
+ dtype = getattr(xp, dtype)
+ c_precision = precision
+ if precision <= 0.0 or precision > 1.0:
+ if dtype in {xp.float32, xp.complex64}:
+ c_precision = 1e-6
+ else:
+ c_precision = 1e-11
+
+ # Compute the initial conditions for a order-two symmetrical low-pass
+ # filter with r = 0.5 and omega = pi / 3 for an unit step input.
+ r = xp.asarray(0.5, dtype=dtype)
+ omega = xp.asarray(np.pi / 3.0, dtype=dtype)
+ cs = 1 - 2 * r * xp.cos(omega) + r**2
+
+ # The index n for the initial condition is bound from 0 to the
+ # first position where sin(omega * (n + 2)) = 0 => omega * (n + 2) = pi
+ # For omega = pi / 3, the maximum initial condition occurs when
+ # sqrt(3) / 2 * r**n < precision.
+ # => n = log(2 * sqrt(3) / 3 * precision) / log(r)
+ ub = xp.ceil(xp.log(c_precision / xp.sin(omega)) / math.log(c_precision))
+ lb = xp.ceil(math.pi / omega) - 2
+ n_exp = min(ub, lb)
+
+ # The forward initial condition for a filter of order two is:
+ # \frac{cs}{\sin(\omega)} \sum_{n = 0}^{N - 1} {
+ # r^(n + 1) \sin{\omega(n + 2)}} + cs
+ # The closed expression for this sum is:
+ # s[n] = 2 * r * np.cos(omega) -
+ # r**2 - r**(n + 2) * np.sin(omega * (n + 3)) / np.sin(omega) +
+ # r**(n + 3) * np.sin(omega * (n + 2)) / np.sin(omega) + cs
+ fwd_initial_1 = (
+ cs +
+ 2 * r * xp.cos(omega) -
+ r**2 -
+ r**(n_exp + 2) * xp.sin(omega * (n_exp + 3)) / xp.sin(omega) +
+ r**(n_exp + 3) * xp.sin(omega * (n_exp + 2)) / xp.sin(omega))
+
+ # The second initial condition is given by
+ # s[n] = 1 / np.sin(omega) * (
+ # r**2 * np.sin(3 * omega) -
+ # r**3 * np.sin(2 * omega) -
+ # r**(n + 3) * np.sin(omega * (n + 4)) +
+ # r**(n + 4) * np.sin(omega * (n + 3)))
+ ub = xp.ceil(xp.log(c_precision / xp.sin(omega)) / math.log(c_precision))
+ lb = xp.ceil(xp.pi / omega) - 3
+ n_exp = min(ub, lb)
+
+ fwd_initial_2 = (
+ cs + cs * 2 * r * xp.cos(omega) +
+ (r**2 * xp.sin(3 * omega) -
+ r**3 * xp.sin(2 * omega) -
+ r**(n_exp + 3) * xp.sin(omega * (n_exp + 4)) +
+ r**(n_exp + 4) * xp.sin(omega * (n_exp + 3))) / xp.sin(omega))
+
+ expected = concat_1d(xp, fwd_initial_1, fwd_initial_2)[None, :]
+ expected = xp.astype(expected, dtype)
+
+ n = 100
+ signal = np.ones(n, dtype=dtype)
+
+ out = symiirorder2_ic_fwd(signal, r, omega, precision)
+ xp_assert_close(out, expected, atol=4e-6, rtol=6e-7)
+
+ @skip_xp_backends(np_only=True,
+ reason="_initial_bwd functions are private and numpy-only")
+ @pytest.mark.parametrize(
+ 'dtype', ['float32', 'float64'])
+ @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075])
+ def test_symiir2_initial_bwd(self, dtype, precision, xp):
+ dtype = getattr(xp, dtype)
+
+ c_precision = precision
+ if precision <= 0.0 or precision > 1.0:
+ if dtype in {xp.float32, xp.complex64}:
+ c_precision = 1e-6
+ else:
+ c_precision = 1e-11
+
+ r = xp.asarray(0.5, dtype=dtype)
+ omega = xp.asarray(xp.pi / 3.0, dtype=dtype)
+ cs = 1 - 2 * r * xp.cos(omega) + r * r
+ a2 = 2 * r * xp.cos(omega)
+ a3 = -r * r
+
+ n = 100
+ signal = xp.ones(n, dtype=dtype)
+
+ # Compute initial forward conditions
+ ic = symiirorder2_ic_fwd(signal, r, omega, precision)
+ out = xp.zeros(n + 2, dtype=dtype)
+ out[:2] = ic[0]
+
+ # Apply the forward system cs / (1 - a2 * z^-1 - a3 * z^-2))
+ for i in range(2, n + 2):
+ out[i] = cs * signal[i - 2] + a2 * out[i - 1] + a3 * out[i - 2]
+
+ # Find the backward initial conditions
+ ic2 = xp.zeros(2, dtype=dtype)
+ idx = xp.arange(n)
+
+ diff = (_compute_symiirorder2_bwd_hs(idx, cs, r * r, omega) +
+ _compute_symiirorder2_bwd_hs(idx + 1, cs, r * r, omega))
+ ic2_0_all = np.cumsum(diff * out[:1:-1])
+ pos = xp.nonzero(diff ** 2 < c_precision)[0]
+ ic2[0] = ic2_0_all[pos[0]]
+
+ diff = (_compute_symiirorder2_bwd_hs(idx - 1, cs, r * r, omega) +
+ _compute_symiirorder2_bwd_hs(idx + 2, cs, r * r, omega))
+
+ ic2_1_all = xp.cumulative_sum(diff * out[:1:-1])
+ pos = xp.nonzero(diff ** 2 < c_precision)[0]
+ ic2[1] = ic2_1_all[pos[0]]
+
+ out_ic = symiirorder2_ic_bwd(out, r, omega, precision)[0]
+ xp_assert_close(out_ic, ic2, atol=4e-6, rtol=6e-7)
+
+ @skip_xp_backends(cpu_only=True, reason="internals are numpy-only")
+ @skip_xp_backends("jax.numpy", reason="item assignment in tests")
+ @pytest.mark.parametrize(
+ 'dtype', ['float32', 'float64'])
+ @pytest.mark.parametrize('precision', [-1.0, 0.7, 0.5, 0.25, 0.0075])
+ def test_symiir2(self, dtype, precision, xp):
+ dtype = getattr(xp, dtype)
+
+ r = 0.5
+ omega = math.pi / 3.0
+ cs = 1 - 2 * r * math.cos(omega) + r * r
+ a2 = 2 * r * math.cos(omega)
+ a3 = -r * r
+
+ n = 100
+ signal = xp.ones(n, dtype=dtype)
+
+ # Compute initial forward conditions
+ signal_np = np.asarray(signal)
+ ic = symiirorder2_ic_fwd(signal_np, r, omega, precision)
+ ic = xp.asarray(ic)
+ out1 = xp.zeros(n + 2, dtype=dtype)
+ out1[:2] = ic[0, :]
+
+ # Apply the forward system cs / (1 - a2 * z^-1 - a3 * z^-2))
+ for i in range(2, n + 2):
+ out1[i] = cs * signal[i - 2] + a2 * out1[i - 1] + a3 * out1[i - 2]
+
+ # Find the backward initial conditions
+ ic2 = symiirorder2_ic_bwd(np.asarray(out1), r, omega, precision)[0]
+ ic2 = xp.asarray(ic2)
+
+ # Apply the system cs / (1 - a2 * z - a3 * z^2)) in backwards
+ exp = xp.empty(n, dtype=dtype)
+
+ exp[-2:] = xp.flip(ic2)
+
+ for i in range(n - 3, -1, -1):
+ exp[i] = cs * out1[i] + a2 * exp[i + 1] + a3 * exp[i + 2]
+
+ out = symiirorder2(signal, r, omega, precision)
+ xp_assert_close(out, exp, atol=4e-6, rtol=6e-7)
+
+ @skip_xp_backends(cpu_only=True, exceptions=["cupy"], reason="C internals")
+ @pytest.mark.parametrize('dtyp', ['float32', 'float64'])
+ def test_symiir2_values(self, dtyp, xp):
+ rng = np.random.RandomState(1234)
+ s = rng.uniform(size=16).astype(dtyp)
+ s = xp.asarray(s)
+
+ # cupy returns f64 for f32 inputs
+ dtype = xp.float64 if is_cupy(xp) else getattr(xp, dtyp)
+
+ res = symiirorder2(s, 0.1, 0.1, precision=1e-10)
+
+ # values from scipy 1.9.1
+ exp_res = xp.asarray(
+ [0.26572609, 0.53408018, 0.51032696, 0.72115829, 0.69486885,
+ 0.3649055 , 0.37349478, 0.74165032, 0.89718521, 0.80582483,
+ 0.46758053, 0.51898709, 0.65025605, 0.65394321, 0.45273595,
+ 0.53539183], dtype=dtype
+ )
+
+ # The values in SciPy 1.14 agree with those in SciPy 1.9.1 to this
+ # accuracy only. Implementation differences are twofold:
+ # 1. boundary conditions are computed differently
+ # 2. the filter itself uses sosfilt instead of a hardcoded iteration
+ # The boundary conditions seem are tested separately (see
+ # test_symiir2_initial_{fwd,bwd} above, so the difference is likely
+ # due to a different way roundoff errors accumulate in the filter.
+ # In that respect, sosfilt is likely doing a better job.
+ xp_assert_close(res, exp_res, atol=2e-6)
+
+ I1 = xp.asarray(1 + 1j, dtype=xp.result_type(s, xp.complex64))
+ s = s * I1
+
+ with pytest.raises((TypeError, ValueError)):
+ res = symiirorder2(s, 0.5, 0.1)
+
+ @skip_xp_backends(cpu_only=True, exceptions=["cupy"], reason="C internals")
+ @xfail_xp_backends("cupy", reason="cupy does not accept integer arrays")
+ def test_symiir1_integer_input(self, xp):
+ s = xp.where(
+ xp.astype(xp.arange(100) % 2, xp.bool),
+ xp.asarray(-1),
+ xp.asarray(1),
+ )
+ expected = symiirorder1(xp.astype(s, xp_default_dtype(xp)), 0.5, 0.5)
+ out = symiirorder1(s, 0.5, 0.5)
+ xp_assert_close(out, expected)
+
+ @skip_xp_backends(cpu_only=True, exceptions=["cupy"], reason="C internals")
+ @xfail_xp_backends("cupy", reason="cupy does not accept integer arrays")
+ def test_symiir2_integer_input(self, xp):
+ s = xp.where(
+ xp.astype(xp.arange(100) % 2, xp.bool),
+ xp.asarray(-1),
+ xp.asarray(1),
+ )
+ expected = symiirorder2(xp.astype(s, xp_default_dtype(xp)), 0.5, xp.pi / 3.0)
+ out = symiirorder2(s, 0.5, xp.pi / 3.0)
+ xp_assert_close(out, expected)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_upfirdn.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_upfirdn.py
new file mode 100644
index 0000000000000000000000000000000000000000..8c96232478d7f56f16af36d0b7569a17476bd9a7
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_upfirdn.py
@@ -0,0 +1,335 @@
+# Code adapted from "upfirdn" python library with permission:
+#
+# Copyright (c) 2009, Motorola, 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:
+#
+# * 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 Motorola 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 numpy as np
+from itertools import product
+
+from pytest import raises as assert_raises
+import pytest
+
+from scipy._lib import array_api_extra as xpx
+from scipy._lib._array_api import (
+ xp_assert_close, array_namespace, _xp_copy_to_numpy, is_cupy,
+ make_xp_test_case
+)
+from scipy._lib.array_api_compat import numpy as np_compat
+from scipy.signal import upfirdn, firwin
+from scipy.signal._upfirdn import _output_len, _upfirdn_modes
+from scipy.signal._upfirdn_apply import _pad_test
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+
+
+
+def upfirdn_naive(x, h, up=1, down=1):
+ """Naive upfirdn processing in Python.
+
+ Note: arg order (x, h) differs to facilitate apply_along_axis use.
+ """
+ x = np.asarray(x)
+ h = np.asarray(h)
+ out = np.zeros(len(x) * up, x.dtype)
+ out[::up] = x
+ out = np.convolve(h, out)[::down][:_output_len(len(h), len(x), up, down)]
+ return out
+
+
+class UpFIRDnCase:
+ """Test _UpFIRDn object"""
+ def __init__(self, up, down, h, x_dtype, *, xp=None):
+ if xp is None:
+ xp = np_compat
+ self.up = up
+ self.down = down
+ self.h = np.atleast_1d(h)
+ self.x_dtype = x_dtype
+ self.rng = np.random.RandomState(17)
+ self.xp = xp
+
+ def __call__(self):
+ # tiny signal
+ self.scrub(np.ones(1, self.x_dtype))
+ # ones
+ self.scrub(np.ones(10, self.x_dtype)) # ones
+ # randn
+ x = self.rng.randn(10).astype(self.x_dtype)
+ if self.x_dtype in (np.complex64, np.complex128):
+ x += 1j * self.rng.randn(10)
+ self.scrub(x)
+ # ramp
+ self.scrub(np.arange(10).astype(self.x_dtype))
+ # 3D, random
+ if is_cupy(self.xp):
+ # ndim > 2 is unsupported in CuPy.
+ return
+ size = (2, 3, 5)
+ x = self.rng.randn(*size).astype(self.x_dtype)
+ if self.x_dtype in (np.complex64, np.complex128):
+ x += 1j * self.rng.randn(*size)
+ for axis in range(len(size)):
+ self.scrub(x, axis=axis)
+ x = x[:, ::2, 1::3].T
+ for axis in range(len(size)):
+ self.scrub(x, axis=axis)
+
+ def scrub(self, x, axis=-1):
+ xp = self.xp
+ yr = np.apply_along_axis(upfirdn_naive, axis, x,
+ self.h, self.up, self.down)
+ want_len = _output_len(len(self.h), x.shape[axis], self.up, self.down)
+ assert yr.shape[axis] == want_len
+ y = upfirdn(xp.asarray(self.h), xp.asarray(x), self.up, self.down,
+ axis=axis)
+ assert y.shape[axis] == want_len
+ assert y.shape == yr.shape
+ dtypes = (self.h.dtype, x.dtype)
+ if all(d == np.complex64 for d in dtypes):
+ assert y.dtype == xp.complex64
+ elif np.complex64 in dtypes and np.float32 in dtypes:
+ assert y.dtype == xp.complex64
+ elif all(d == np.float32 for d in dtypes):
+ assert y.dtype == xp.float32
+ elif np.complex128 in dtypes or np.complex64 in dtypes:
+ assert y.dtype == xp.complex128
+ else:
+ assert y.dtype == xp.float64
+ yr = xp.asarray(yr, dtype=y.dtype)
+ xp_assert_close(yr, y)
+
+
+_UPFIRDN_TYPES = ("int64", "float32", "complex64", "float64", "complex128")
+
+
+@make_xp_test_case(upfirdn)
+class TestUpfirdn:
+
+ @skip_xp_backends(np_only=True, reason="enough to only test on numpy")
+ def test_valid_input(self, xp):
+ assert_raises(ValueError, upfirdn, [1], [1], 1, 0) # up or down < 1
+ assert_raises(ValueError, upfirdn, [], [1], 1, 1) # h.ndim != 1
+ assert_raises(ValueError, upfirdn, [[1]], [1], 1, 1)
+
+ @pytest.mark.parametrize('len_h', [1, 2, 3, 4, 5])
+ @pytest.mark.parametrize('len_x', [1, 2, 3, 4, 5])
+ def test_singleton(self, len_h, len_x, xp):
+ # gh-9844: lengths producing expected outputs
+ h = xp.zeros(len_h)
+ h = xpx.at(h)[len_h // 2].set(1.) # make h a delta
+ x = xp.ones(len_x)
+ y = upfirdn(h, x, 1, 1)
+ want = xpx.pad(x, (len_h // 2, (len_h - 1) // 2), 'constant', xp=xp)
+ xp_assert_close(y, want)
+
+ def test_shift_x(self, xp):
+ # gh-9844: shifted x can change values?
+ y = upfirdn(xp.asarray([1, 1]), xp.asarray([1.]), 1, 1)
+ xp_assert_close(
+ y, xp.asarray([1.0, 1.0], dtype=xp.float64) # was [0, 1] in the issue
+ )
+ y = upfirdn(xp.asarray([1, 1]), xp.asarray([0., 1.]), 1, 1)
+ xp_assert_close(y, xp.asarray([0.0, 1.0, 1.0], dtype=xp.float64))
+
+ # A bunch of lengths/factors chosen because they exposed differences
+ # between the "old way" and new way of computing length, and then
+ # got `expected` from MATLAB
+ @pytest.mark.parametrize('len_h, len_x, up, down, expected', [
+ (2, 2, 5, 2, [1, 0, 0, 0]),
+ (2, 3, 6, 3, [1, 0, 1, 0, 1]),
+ (2, 4, 4, 3, [1, 0, 0, 0, 1]),
+ (3, 2, 6, 2, [1, 0, 0, 1, 0]),
+ (4, 11, 3, 5, [1, 0, 0, 1, 0, 0, 1]),
+ ])
+ def test_length_factors(self, len_h, len_x, up, down, expected, xp):
+ # gh-9844: weird factors
+ h = xp.zeros(len_h)
+ h = xpx.at(h)[0].set(1.)
+ x = xp.ones(len_x, dtype=xp.float64)
+ y = upfirdn(h, x, up, down)
+ expected = xp.asarray(expected, dtype=xp.float64)
+ xp_assert_close(y, expected)
+
+ @pytest.mark.parametrize(
+ 'dtype', ["int64", "float32", "complex64", "float64", "complex128"]
+ )
+ @pytest.mark.parametrize('down, want_len', [ # lengths from MATLAB
+ (2, 5015),
+ (11, 912),
+ (79, 127),
+ ])
+ def test_vs_convolve(self, down, want_len, dtype, xp):
+ # Check that up=1.0 gives same answer as convolve + slicing
+ random_state = np.random.RandomState(17)
+ size = 10000
+
+ np_dtype = getattr(np, dtype)
+ x = random_state.randn(size).astype(np_dtype)
+ if np_dtype in (np.complex64, np.complex128):
+ x += 1j * random_state.randn(size)
+
+ dtype = getattr(xp, dtype)
+ x = xp.asarray(x, dtype=dtype)
+
+ h = xp.asarray(firwin(31, 1. / down, window='hamming'))
+ yl = xp.asarray(
+ upfirdn_naive(_xp_copy_to_numpy(x), _xp_copy_to_numpy(h), 1, down)
+ )
+ y = upfirdn(h, x, up=1, down=down)
+ assert y.shape == (want_len,)
+ assert yl.shape[0] == y.shape[0]
+ xp_assert_close(yl, y, atol=1e-7, rtol=1e-7)
+
+ @pytest.mark.parametrize('x_dtype', _UPFIRDN_TYPES)
+ @pytest.mark.parametrize('h', (1., 1j))
+ @pytest.mark.parametrize('up, down', [(1, 1), (2, 2), (3, 2), (2, 3)])
+ def test_vs_naive_delta(self, x_dtype, h, up, down, xp):
+ UpFIRDnCase(up, down, h, x_dtype, xp=xp)()
+
+ @pytest.mark.parametrize('x_dtype', _UPFIRDN_TYPES)
+ @pytest.mark.parametrize('h_dtype', _UPFIRDN_TYPES)
+ @pytest.mark.parametrize('p_max, q_max',
+ list(product((10, 100), (10, 100))))
+ def test_vs_naive(self, x_dtype, h_dtype, p_max, q_max, xp):
+ tests = self._random_factors(p_max, q_max, h_dtype, x_dtype, xp=xp)
+ for test in tests:
+ test()
+
+ def _random_factors(self, p_max, q_max, h_dtype, x_dtype, *, xp):
+ n_rep = 3
+ longest_h = 25
+ random_state = np.random.RandomState(17)
+ tests = []
+
+ for _ in range(n_rep):
+ # Randomize the up/down factors somewhat
+ p_add = q_max if p_max > q_max else 1
+ q_add = p_max if q_max > p_max else 1
+ p = random_state.randint(p_max) + p_add
+ q = random_state.randint(q_max) + q_add
+
+ # Generate random FIR coefficients
+ len_h = random_state.randint(longest_h) + 1
+ h = np.atleast_1d(random_state.randint(len_h))
+ h = h.astype(h_dtype)
+ if h_dtype is complex:
+ h += 1j * random_state.randint(len_h)
+
+ tests.append(UpFIRDnCase(p, q, h, x_dtype, xp=xp))
+
+ return tests
+
+ @pytest.mark.parametrize('mode', _upfirdn_modes)
+ def test_extensions(self, mode, xp):
+ """Test vs. manually computed results for modes not in numpy's pad."""
+ x = np.asarray([1, 2, 3, 1], dtype=np.float64)
+ npre, npost = 6, 6
+ y = _pad_test(x, npre=npre, npost=npost, mode=mode)
+
+ x = xp.asarray(x)
+ y = xp.asarray(y)
+ if mode == 'antisymmetric':
+ y_expected = xp.asarray(
+ [3.0, 1, -1, -3, -2, -1, 1, 2, 3, 1, -1, -3, -2, -1, 1, 2])
+ elif mode == 'antireflect':
+ y_expected = xp.asarray(
+ [1.0, 2, 3, 1, -1, 0, 1, 2, 3, 1, -1, 0, 1, 2, 3, 1])
+ elif mode == 'smooth':
+ y_expected = xp.asarray(
+ [-5.0, -4, -3, -2, -1, 0, 1, 2, 3, 1, -1, -3, -5, -7, -9, -11])
+ elif mode == "line":
+ lin_slope = (x[-1] - x[0]) / (x.shape[0] - 1)
+ left = x[0] + xp.arange(-npre, 0, 1, dtype=xp.float64) * lin_slope
+ right = x[-1] + xp.arange(1, npost + 1, dtype=xp.float64) * lin_slope
+ concat = array_namespace(left).concat
+ y_expected = concat((left, x, right))
+ else:
+ y_expected = np.pad(_xp_copy_to_numpy(x), (npre, npost), mode=mode)
+ y_expected = xp.asarray(y_expected)
+
+ y_expected = xp.asarray(y_expected, dtype=xp.float64)
+ xp_assert_close(y, y_expected)
+
+ @pytest.mark.parametrize(
+ 'size, h_len, mode, dtype',
+ product(
+ [8],
+ [4, 5, 26], # include cases with h_len > 2*size
+ _upfirdn_modes,
+ ["float32", "float64", "complex64", "complex128"],
+ )
+ )
+ def test_modes(self, size, h_len, mode, dtype, xp):
+ if is_cupy(xp) and mode != "constant":
+ pytest.skip(reason="only mode='constant' supported by CuPy")
+ dtype_np = getattr(np, dtype)
+ dtype_xp = getattr(xp, dtype)
+
+ random_state = np.random.RandomState(5)
+ x = random_state.randn(size).astype(dtype_np)
+ if dtype in ("complex64", "complex128"):
+ x += 1j * random_state.randn(size)
+ h = np.arange(1, 1 + h_len, dtype=x.real.dtype)
+
+ x = xp.asarray(x, dtype=dtype_xp)
+ h = xp.asarray(h)
+
+ y = upfirdn(h, x, up=1, down=1, mode=mode)
+ # expected result: pad the input, filter with zero padding, then crop
+ npad = h_len - 1
+ if mode in ['antisymmetric', 'antireflect', 'smooth', 'line']:
+ # use _pad_test test function for modes not supported by np.pad.
+ xpad = _pad_test(_xp_copy_to_numpy(x), npre=npad, npost=npad, mode=mode)
+ else:
+ xpad = np.pad(_xp_copy_to_numpy(x), npad, mode=mode)
+
+ xpad = xp.asarray(xpad)
+ ypad = upfirdn(h, xpad, up=1, down=1, mode='constant')
+ y_expected = ypad[npad:-npad]
+
+ atol = rtol = xp.finfo(dtype_xp).eps * 1e2
+ xp_assert_close(y, y_expected, atol=atol, rtol=rtol)
+
+
+@make_xp_test_case(upfirdn)
+def test_output_len_long_input(xp):
+ # Regression test for gh-17375. On Windows, a large enough input
+ # that should have been well within the capabilities of 64 bit integers
+ # would result in a 32 bit overflow because of a bug in Cython 0.29.32.
+ len_h = 1001
+ in_len = 10**8
+ up = 320
+ down = 441
+ out_len = _output_len(len_h, in_len, up, down)
+ # The expected value was computed "by hand" from the formula
+ # (((in_len - 1) * up + len_h) - 1) // down + 1
+ assert out_len == 72562360
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_waveforms.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_waveforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..8cf181f55bfd055c21c937529ec1f42fb741d978
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_waveforms.py
@@ -0,0 +1,400 @@
+import numpy as np
+from pytest import raises as assert_raises
+from scipy._lib._array_api import (
+ assert_almost_equal, xp_assert_equal, xp_assert_close
+)
+
+import scipy.signal._waveforms as waveforms
+
+
+# These chirp_* functions are the instantaneous frequencies of the signals
+# returned by chirp().
+
+def chirp_linear(t, f0, f1, t1):
+ f = f0 + (f1 - f0) * t / t1
+ return f
+
+
+def chirp_quadratic(t, f0, f1, t1, vertex_zero=True):
+ if vertex_zero:
+ f = f0 + (f1 - f0) * t**2 / t1**2
+ else:
+ f = f1 - (f1 - f0) * (t1 - t)**2 / t1**2
+ return f
+
+
+def chirp_geometric(t, f0, f1, t1):
+ f = f0 * (f1/f0)**(t/t1)
+ return f
+
+
+def chirp_hyperbolic(t, f0, f1, t1):
+ f = f0*f1*t1 / ((f0 - f1)*t + f1*t1)
+ return f
+
+
+def compute_frequency(t, theta):
+ """
+ Compute theta'(t)/(2*pi), where theta'(t) is the derivative of theta(t).
+ """
+ # Assume theta and t are 1-D NumPy arrays.
+ # Assume that t is uniformly spaced.
+ dt = t[1] - t[0]
+ f = np.diff(theta)/(2*np.pi) / dt
+ tf = 0.5*(t[1:] + t[:-1])
+ return tf, f
+
+
+class TestChirp:
+
+ def test_linear_at_zero(self):
+ w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='linear')
+ assert_almost_equal(w, 1.0)
+
+ def test_linear_freq_01(self):
+ method = 'linear'
+ f0 = 1.0
+ f1 = 2.0
+ t1 = 1.0
+ t = np.linspace(0, t1, 100)
+ phase = waveforms._chirp_phase(t, f0, t1, f1, method)
+ tf, f = compute_frequency(t, phase)
+ abserr = np.max(np.abs(f - chirp_linear(tf, f0, f1, t1)))
+ assert abserr < 1e-6
+
+ def test_linear_freq_02(self):
+ method = 'linear'
+ f0 = 200.0
+ f1 = 100.0
+ t1 = 10.0
+ t = np.linspace(0, t1, 100)
+ phase = waveforms._chirp_phase(t, f0, t1, f1, method)
+ tf, f = compute_frequency(t, phase)
+ abserr = np.max(np.abs(f - chirp_linear(tf, f0, f1, t1)))
+ assert abserr < 1e-6
+
+ def test_linear_complex_power(self):
+ method = 'linear'
+ f0 = 1.0
+ f1 = 2.0
+ t1 = 1.0
+ t = np.linspace(0, t1, 100)
+ w_real = waveforms.chirp(t, f0, t1, f1, method, complex=False)
+ w_complex = waveforms.chirp(t, f0, t1, f1, method, complex=True)
+ w_pwr_r = np.var(w_real)
+ w_pwr_c = np.var(w_complex)
+
+ # Making sure that power of the real part is not affected with
+ # complex conversion operation
+ err = w_pwr_r - np.real(w_pwr_c)
+
+ assert(err < 1e-6)
+
+ def test_linear_complex_at_zero(self):
+ w = waveforms.chirp(t=0, f0=-10.0, f1=1.0, t1=1.0, method='linear',
+ complex=True)
+ xp_assert_close(w, 1.0+0.0j) # dtype must match
+
+ def test_quadratic_at_zero(self):
+ w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='quadratic')
+ assert_almost_equal(w, 1.0)
+
+ def test_quadratic_at_zero2(self):
+ w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='quadratic',
+ vertex_zero=False)
+ assert_almost_equal(w, 1.0)
+
+ def test_quadratic_complex_at_zero(self):
+ w = waveforms.chirp(t=0, f0=-1.0, f1=2.0, t1=1.0, method='quadratic',
+ complex=True)
+ xp_assert_close(w, 1.0+0j)
+
+ def test_quadratic_freq_01(self):
+ method = 'quadratic'
+ f0 = 1.0
+ f1 = 2.0
+ t1 = 1.0
+ t = np.linspace(0, t1, 2000)
+ phase = waveforms._chirp_phase(t, f0, t1, f1, method)
+ tf, f = compute_frequency(t, phase)
+ abserr = np.max(np.abs(f - chirp_quadratic(tf, f0, f1, t1)))
+ assert abserr < 1e-6
+
+ def test_quadratic_freq_02(self):
+ method = 'quadratic'
+ f0 = 20.0
+ f1 = 10.0
+ t1 = 10.0
+ t = np.linspace(0, t1, 2000)
+ phase = waveforms._chirp_phase(t, f0, t1, f1, method)
+ tf, f = compute_frequency(t, phase)
+ abserr = np.max(np.abs(f - chirp_quadratic(tf, f0, f1, t1)))
+ assert abserr < 1e-6
+
+ def test_logarithmic_at_zero(self):
+ w = waveforms.chirp(t=0, f0=1.0, f1=2.0, t1=1.0, method='logarithmic')
+ assert_almost_equal(w, 1.0)
+
+ def test_logarithmic_freq_01(self):
+ method = 'logarithmic'
+ f0 = 1.0
+ f1 = 2.0
+ t1 = 1.0
+ t = np.linspace(0, t1, 10000)
+ phase = waveforms._chirp_phase(t, f0, t1, f1, method)
+ tf, f = compute_frequency(t, phase)
+ abserr = np.max(np.abs(f - chirp_geometric(tf, f0, f1, t1)))
+ assert abserr < 1e-6
+
+ def test_logarithmic_freq_02(self):
+ method = 'logarithmic'
+ f0 = 200.0
+ f1 = 100.0
+ t1 = 10.0
+ t = np.linspace(0, t1, 10000)
+ phase = waveforms._chirp_phase(t, f0, t1, f1, method)
+ tf, f = compute_frequency(t, phase)
+ abserr = np.max(np.abs(f - chirp_geometric(tf, f0, f1, t1)))
+ assert abserr < 1e-6
+
+ def test_logarithmic_freq_03(self):
+ method = 'logarithmic'
+ f0 = 100.0
+ f1 = 100.0
+ t1 = 10.0
+ t = np.linspace(0, t1, 10000)
+ phase = waveforms._chirp_phase(t, f0, t1, f1, method)
+ tf, f = compute_frequency(t, phase)
+ abserr = np.max(np.abs(f - chirp_geometric(tf, f0, f1, t1)))
+ assert abserr < 1e-6
+
+ def test_hyperbolic_at_zero(self):
+ w = waveforms.chirp(t=0, f0=10.0, f1=1.0, t1=1.0, method='hyperbolic')
+ assert_almost_equal(w, 1.0)
+
+ def test_hyperbolic_freq_01(self):
+ method = 'hyperbolic'
+ t1 = 1.0
+ t = np.linspace(0, t1, 10000)
+ # f0 f1
+ cases = [[10.0, 1.0],
+ [1.0, 10.0],
+ [-10.0, -1.0],
+ [-1.0, -10.0]]
+ for f0, f1 in cases:
+ phase = waveforms._chirp_phase(t, f0, t1, f1, method)
+ tf, f = compute_frequency(t, phase)
+ expected = chirp_hyperbolic(tf, f0, f1, t1)
+ xp_assert_close(f, expected, atol=1e-7)
+
+ def test_hyperbolic_zero_freq(self):
+ # f0=0 or f1=0 must raise a ValueError.
+ method = 'hyperbolic'
+ t1 = 1.0
+ t = np.linspace(0, t1, 5)
+ assert_raises(ValueError, waveforms.chirp, t, 0, t1, 1, method)
+ assert_raises(ValueError, waveforms.chirp, t, 1, t1, 0, method)
+
+ def test_unknown_method(self):
+ method = "foo"
+ f0 = 10.0
+ f1 = 20.0
+ t1 = 1.0
+ t = np.linspace(0, t1, 10)
+ assert_raises(ValueError, waveforms.chirp, t, f0, t1, f1, method)
+
+ def test_integer_t1(self):
+ f0 = 10.0
+ f1 = 20.0
+ t = np.linspace(-1, 1, 11)
+ t1 = 3.0
+ float_result = waveforms.chirp(t, f0, t1, f1)
+ t1 = 3
+ int_result = waveforms.chirp(t, f0, t1, f1)
+ err_msg = "Integer input 't1=3' gives wrong result"
+ xp_assert_equal(int_result, float_result, err_msg=err_msg)
+
+ def test_integer_f0(self):
+ f1 = 20.0
+ t1 = 3.0
+ t = np.linspace(-1, 1, 11)
+ f0 = 10.0
+ float_result = waveforms.chirp(t, f0, t1, f1)
+ f0 = 10
+ int_result = waveforms.chirp(t, f0, t1, f1)
+ err_msg = "Integer input 'f0=10' gives wrong result"
+ xp_assert_equal(int_result, float_result, err_msg=err_msg)
+
+ def test_integer_f1(self):
+ f0 = 10.0
+ t1 = 3.0
+ t = np.linspace(-1, 1, 11)
+ f1 = 20.0
+ float_result = waveforms.chirp(t, f0, t1, f1)
+ f1 = 20
+ int_result = waveforms.chirp(t, f0, t1, f1)
+ err_msg = "Integer input 'f1=20' gives wrong result"
+ xp_assert_equal(int_result, float_result, err_msg=err_msg)
+
+ def test_integer_all(self):
+ f0 = 10
+ t1 = 3
+ f1 = 20
+ t = np.linspace(-1, 1, 11)
+ float_result = waveforms.chirp(t, float(f0), float(t1), float(f1))
+ int_result = waveforms.chirp(t, f0, t1, f1)
+ err_msg = "Integer input 'f0=10, t1=3, f1=20' gives wrong result"
+ xp_assert_equal(int_result, float_result, err_msg=err_msg)
+
+
+class TestSweepPoly:
+
+ def test_sweep_poly_quad1(self):
+ p = np.poly1d([1.0, 0.0, 1.0])
+ t = np.linspace(0, 3.0, 10000)
+ phase = waveforms._sweep_poly_phase(t, p)
+ tf, f = compute_frequency(t, phase)
+ expected = p(tf)
+ abserr = np.max(np.abs(f - expected))
+ assert abserr < 1e-6
+
+ def test_sweep_poly_const(self):
+ p = np.poly1d(2.0)
+ t = np.linspace(0, 3.0, 10000)
+ phase = waveforms._sweep_poly_phase(t, p)
+ tf, f = compute_frequency(t, phase)
+ expected = p(tf)
+ abserr = np.max(np.abs(f - expected))
+ assert abserr < 1e-6
+
+ def test_sweep_poly_linear(self):
+ p = np.poly1d([-1.0, 10.0])
+ t = np.linspace(0, 3.0, 10000)
+ phase = waveforms._sweep_poly_phase(t, p)
+ tf, f = compute_frequency(t, phase)
+ expected = p(tf)
+ abserr = np.max(np.abs(f - expected))
+ assert abserr < 1e-6
+
+ def test_sweep_poly_quad2(self):
+ p = np.poly1d([1.0, 0.0, -2.0])
+ t = np.linspace(0, 3.0, 10000)
+ phase = waveforms._sweep_poly_phase(t, p)
+ tf, f = compute_frequency(t, phase)
+ expected = p(tf)
+ abserr = np.max(np.abs(f - expected))
+ assert abserr < 1e-6
+
+ def test_sweep_poly_cubic(self):
+ p = np.poly1d([2.0, 1.0, 0.0, -2.0])
+ t = np.linspace(0, 2.0, 10000)
+ phase = waveforms._sweep_poly_phase(t, p)
+ tf, f = compute_frequency(t, phase)
+ expected = p(tf)
+ abserr = np.max(np.abs(f - expected))
+ assert abserr < 1e-6
+
+ def test_sweep_poly_cubic2(self):
+ """Use an array of coefficients instead of a poly1d."""
+ p = np.array([2.0, 1.0, 0.0, -2.0])
+ t = np.linspace(0, 2.0, 10000)
+ phase = waveforms._sweep_poly_phase(t, p)
+ tf, f = compute_frequency(t, phase)
+ expected = np.poly1d(p)(tf)
+ abserr = np.max(np.abs(f - expected))
+ assert abserr < 1e-6
+
+ def test_sweep_poly_cubic3(self):
+ """Use a list of coefficients instead of a poly1d."""
+ p = [2.0, 1.0, 0.0, -2.0]
+ t = np.linspace(0, 2.0, 10000)
+ phase = waveforms._sweep_poly_phase(t, p)
+ tf, f = compute_frequency(t, phase)
+ expected = np.poly1d(p)(tf)
+ abserr = np.max(np.abs(f - expected))
+ assert abserr < 1e-6
+
+
+class TestGaussPulse:
+
+ def test_integer_fc(self):
+ float_result = waveforms.gausspulse('cutoff', fc=1000.0)
+ int_result = waveforms.gausspulse('cutoff', fc=1000)
+ err_msg = "Integer input 'fc=1000' gives wrong result"
+ xp_assert_equal(int_result, float_result, err_msg=err_msg)
+
+ def test_integer_bw(self):
+ float_result = waveforms.gausspulse('cutoff', bw=1.0)
+ int_result = waveforms.gausspulse('cutoff', bw=1)
+ err_msg = "Integer input 'bw=1' gives wrong result"
+ xp_assert_equal(int_result, float_result, err_msg=err_msg)
+
+ def test_integer_bwr(self):
+ float_result = waveforms.gausspulse('cutoff', bwr=-6.0)
+ int_result = waveforms.gausspulse('cutoff', bwr=-6)
+ err_msg = "Integer input 'bwr=-6' gives wrong result"
+ xp_assert_equal(int_result, float_result, err_msg=err_msg)
+
+ def test_integer_tpr(self):
+ float_result = waveforms.gausspulse('cutoff', tpr=-60.0)
+ int_result = waveforms.gausspulse('cutoff', tpr=-60)
+ err_msg = "Integer input 'tpr=-60' gives wrong result"
+ xp_assert_equal(int_result, float_result, err_msg=err_msg)
+
+
+class TestUnitImpulse:
+
+ def test_no_index(self):
+ xp_assert_equal(waveforms.unit_impulse(7),
+ np.asarray([1.0, 0, 0, 0, 0, 0, 0]))
+ xp_assert_equal(waveforms.unit_impulse((3, 3)),
+ np.asarray([[1.0, 0, 0], [0, 0, 0], [0, 0, 0]]))
+
+ def test_index(self):
+ xp_assert_equal(waveforms.unit_impulse(10, 3),
+ np.asarray([0.0, 0, 0, 1, 0, 0, 0, 0, 0, 0]))
+ xp_assert_equal(waveforms.unit_impulse((3, 3), (1, 1)),
+ np.asarray([[0.0, 0, 0], [0, 1, 0], [0, 0, 0]]))
+
+ # Broadcasting
+ imp = waveforms.unit_impulse((4, 4), 2)
+ xp_assert_equal(imp, np.asarray([[0.0, 0, 0, 0],
+ [0.0, 0, 0, 0],
+ [0.0, 0, 1, 0],
+ [0.0, 0, 0, 0]]))
+
+ def test_mid(self):
+ xp_assert_equal(waveforms.unit_impulse((3, 3), 'mid'),
+ np.asarray([[0.0, 0, 0], [0, 1, 0], [0, 0, 0]]))
+ xp_assert_equal(waveforms.unit_impulse(9, 'mid'),
+ np.asarray([0.0, 0, 0, 0, 1, 0, 0, 0, 0]))
+
+ def test_dtype(self):
+ imp = waveforms.unit_impulse(7)
+ assert np.issubdtype(imp.dtype, np.floating)
+
+ imp = waveforms.unit_impulse(5, 3, dtype=int)
+ assert np.issubdtype(imp.dtype, np.integer)
+
+ imp = waveforms.unit_impulse((5, 2), (3, 1), dtype=complex)
+ assert np.issubdtype(imp.dtype, np.complexfloating)
+
+
+class TestSawtoothWaveform:
+ def test_dtype(self):
+ waveform = waveforms.sawtooth(
+ np.array(1, dtype=np.float32), width=np.float32(1)
+ )
+ assert waveform.dtype == np.float64
+
+ waveform = waveforms.sawtooth(1)
+ assert waveform.dtype == np.float64
+
+
+class TestSquareWaveform:
+ def test_dtype(self):
+ waveform = waveforms.square(np.array(1, dtype=np.float32), duty=np.float32(0.5))
+ assert waveform.dtype == np.float64
+
+ waveform = waveforms.square(1)
+ assert waveform.dtype == np.float64
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_wavelets.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_wavelets.py
new file mode 100644
index 0000000000000000000000000000000000000000..7a357d2eaf4a530930d612358b8ca69a18b5248e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_wavelets.py
@@ -0,0 +1,59 @@
+import numpy as np
+from numpy.testing import assert_array_equal, assert_array_almost_equal
+
+import scipy.signal._wavelets as wavelets
+
+
+class TestWavelets:
+ def test_ricker(self):
+ w = wavelets._ricker(1.0, 1)
+ expected = 2 / (np.sqrt(3 * 1.0) * (np.pi ** 0.25))
+ assert_array_equal(w, expected)
+
+ lengths = [5, 11, 15, 51, 101]
+ for length in lengths:
+ w = wavelets._ricker(length, 1.0)
+ assert len(w) == length
+ max_loc = np.argmax(w)
+ assert max_loc == (length // 2)
+
+ points = 100
+ w = wavelets._ricker(points, 2.0)
+ half_vec = np.arange(0, points // 2)
+ # Wavelet should be symmetric
+ assert_array_almost_equal(w[half_vec], w[-(half_vec + 1)])
+
+ # Check zeros
+ aas = [5, 10, 15, 20, 30]
+ points = 99
+ for a in aas:
+ w = wavelets._ricker(points, a)
+ vec = np.arange(0, points) - (points - 1.0) / 2
+ exp_zero1 = np.argmin(np.abs(vec - a))
+ exp_zero2 = np.argmin(np.abs(vec + a))
+ assert_array_almost_equal(w[exp_zero1], 0)
+ assert_array_almost_equal(w[exp_zero2], 0)
+
+ def test_cwt(self):
+ widths = [1.0]
+ def delta_wavelet(s, t):
+ return np.array([1])
+ len_data = 100
+ test_data = np.sin(np.pi * np.arange(0, len_data) / 10.0)
+
+ # Test delta function input gives same data as output
+ cwt_dat = wavelets._cwt(test_data, delta_wavelet, widths)
+ assert cwt_dat.shape == (len(widths), len_data)
+ assert_array_almost_equal(test_data, cwt_dat.flatten())
+
+ # Check proper shape on output
+ widths = [1, 3, 4, 5, 10]
+ cwt_dat = wavelets._cwt(test_data, wavelets._ricker, widths)
+ assert cwt_dat.shape == (len(widths), len_data)
+
+ widths = [len_data * 10]
+ # Note: this wavelet isn't defined quite right, but is fine for this test
+ def flat_wavelet(l, w):
+ return np.full(w, 1 / w)
+ cwt_dat = wavelets._cwt(test_data, flat_wavelet, widths)
+ assert_array_almost_equal(cwt_dat, np.mean(test_data))
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_windows.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..a704e3a831264765ea6c8c9481524d15c7c0972b
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/tests/test_windows.py
@@ -0,0 +1,1098 @@
+import math
+import warnings
+
+import numpy as np
+from numpy import array
+import pytest
+from pytest import raises as assert_raises
+
+from scipy.fft import fft
+from scipy.signal import windows, get_window, resample
+from scipy.signal.windows._windows import _WIN_FUNC_DATA, _WIN_FUNCS
+from scipy._lib._array_api import (
+ xp_assert_close, xp_assert_equal, array_namespace, is_torch, is_jax, is_cupy,
+ assert_array_almost_equal, SCIPY_DEVICE, is_numpy, make_xp_test_case,
+ make_xp_pytest_param, _xp_copy_to_numpy
+)
+
+skip_xp_backends = pytest.mark.skip_xp_backends
+xfail_xp_backends = pytest.mark.xfail_xp_backends
+
+lazy_xp_modules = [windows]
+
+
+window_funcs = [
+ ('boxcar', ()),
+ ('triang', ()),
+ ('parzen', ()),
+ ('bohman', ()),
+ ('blackman', ()),
+ ('nuttall', ()),
+ ('blackmanharris', ()),
+ ('flattop', ()),
+ ('bartlett', ()),
+ ('barthann', ()),
+ ('hamming', ()),
+ ('kaiser', (1,)),
+ ('dpss', (2,)),
+ ('gaussian', (0.5,)),
+ ('general_gaussian', (1.5, 2)),
+ ('chebwin', (1,)),
+ ('cosine', ()),
+ ('hann', ()),
+ ('exponential', ()),
+ ('taylor', ()),
+ ('tukey', (0.5,)),
+ ('lanczos', ()),
+ ]
+
+
+@make_xp_test_case(windows.barthann)
+class TestBartHann:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.barthann(6, sym=True, xp=xp),
+ xp.asarray([0, 0.35857354213752, 0.8794264578624801,
+ 0.8794264578624801, 0.3585735421375199, 0], dtype=xp.float64),
+ rtol=1e-15, atol=1e-15)
+ xp_assert_close(windows.barthann(7, xp=xp),
+ xp.asarray([0, 0.27, 0.73, 1.0, 0.73, 0.27, 0],
+ dtype=xp.float64),
+ rtol=1e-15, atol=1e-15)
+ xp_assert_close(windows.barthann(6, False, xp=xp),
+ xp.asarray([0, 0.27, 0.73, 1.0, 0.73, 0.27], dtype=xp.float64),
+ rtol=1e-15, atol=1e-15)
+
+
+@make_xp_test_case(windows.bartlett)
+class TestBartlett:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.bartlett(6, xp=xp),
+ xp.asarray([0, 0.4, 0.8, 0.8, 0.4, 0], dtype=xp.float64))
+ xp_assert_close(windows.bartlett(7, xp=xp),
+ xp.asarray([0, 1/3, 2/3, 1.0, 2/3, 1/3, 0], dtype=xp.float64))
+ xp_assert_close(windows.bartlett(6, False, xp=xp),
+ xp.asarray([0, 1/3, 2/3, 1.0, 2/3, 1/3], dtype=xp.float64))
+
+
+@make_xp_test_case(windows.blackman)
+class TestBlackman:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.blackman(6, sym=False, xp=xp),
+ xp.asarray([0, 0.13, 0.63, 1.0, 0.63, 0.13], dtype=xp.float64),
+ atol=1e-14)
+ xp_assert_close(windows.blackman(7, sym=False, xp=xp),
+ xp.asarray([0, 0.09045342435412804, 0.4591829575459636,
+ 0.9203636180999081, 0.9203636180999081,
+ 0.4591829575459636, 0.09045342435412804],
+ dtype=xp.float64),
+ atol=1e-8)
+ xp_assert_close(windows.blackman(6, xp=xp),
+ xp.asarray([0, 0.2007701432625305, 0.8492298567374694,
+ 0.8492298567374694, 0.2007701432625305, 0],
+ dtype=xp.float64),
+ atol=1e-14)
+ xp_assert_close(windows.blackman(7, True, xp=xp),
+ xp.asarray([0, 0.13, 0.63, 1.0, 0.63, 0.13, 0],
+ dtype=xp.float64), atol=1e-14)
+
+
+@make_xp_test_case(windows.blackmanharris)
+class TestBlackmanHarris:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.blackmanharris(6, False, xp=xp),
+ xp.asarray([6.0e-05, 0.055645, 0.520575,
+ 1.0, 0.520575, 0.055645], dtype=xp.float64))
+ xp_assert_close(windows.blackmanharris(7, sym=False, xp=xp),
+ xp.asarray([6.0e-05, 0.03339172347815117, 0.332833504298565,
+ 0.8893697722232837, 0.8893697722232838,
+ 0.3328335042985652, 0.03339172347815122],
+ dtype=xp.float64))
+ xp_assert_close(windows.blackmanharris(6, xp=xp),
+ xp.asarray([6.0e-05, 0.1030114893456638, 0.7938335106543362,
+ 0.7938335106543364, 0.1030114893456638, 6.0e-05],
+ dtype=xp.float64))
+ xp_assert_close(windows.blackmanharris(7, sym=True, xp=xp),
+ xp.asarray([6.0e-05, 0.055645, 0.520575, 1.0, 0.520575,
+ 0.055645, 6.0e-05], dtype=xp.float64))
+
+
+@make_xp_test_case(windows.taylor)
+class TestTaylor:
+
+ def test_normalized(self, xp):
+ """Tests windows of small length that are normalized to 1. See the
+ documentation for the Taylor window for more information on
+ normalization.
+ """
+ xp_assert_close(windows.taylor(1, 2, 15, xp=xp),
+ xp.asarray([1.0], dtype=xp.float64))
+ xp_assert_close(
+ windows.taylor(5, 2, 15, xp=xp),
+ xp.asarray([0.75803341, 0.90757699, 1.0, 0.90757699, 0.75803341],
+ dtype=xp.float64)
+ )
+ xp_assert_close(
+ windows.taylor(6, 2, 15, xp=xp),
+ xp.asarray([
+ 0.7504082, 0.86624416, 0.98208011, 0.98208011, 0.86624416,
+ 0.7504082
+ ], dtype=xp.float64)
+ )
+
+ def test_non_normalized(self, xp):
+ """Test windows of small length that are not normalized to 1. See
+ the documentation for the Taylor window for more information on
+ normalization.
+ """
+ xp_assert_close(
+ windows.taylor(5, 2, 15, norm=False, xp=xp),
+ xp.asarray([
+ 0.87508054, 1.04771499, 1.15440894, 1.04771499, 0.87508054
+ ], dtype=xp.float64)
+ )
+ xp_assert_close(
+ windows.taylor(6, 2, 15, norm=False, xp=xp),
+ xp.asarray([
+ 0.86627793, 1.0, 1.13372207, 1.13372207, 1.0, 0.86627793
+ ], dtype=xp.float64)
+ )
+
+ def test_correctness(self, xp):
+ """This test ensures the correctness of the implemented Taylor
+ Windowing function. A Taylor Window of 1024 points is created, its FFT
+ is taken, and the Peak Sidelobe Level (PSLL) and 3dB and 18dB bandwidth
+ are found and checked.
+
+ A publication from Sandia National Laboratories was used as reference
+ for the correctness values [1]_.
+
+ References
+ -----
+ .. [1] Armin Doerry, "Catalog of Window Taper Functions for
+ Sidelobe Control", 2017.
+ https://www.researchgate.net/profile/Armin_Doerry/publication/316281181_Catalog_of_Window_Taper_Functions_for_Sidelobe_Control/links/58f92cb2a6fdccb121c9d54d/Catalog-of-Window-Taper-Functions-for-Sidelobe-Control.pdf
+ """
+ M_win = 1024
+ N_fft = 131072
+ # Set norm=False for correctness as the values obtained from the
+ # scientific publication do not normalize the values. Normalizing
+ # changes the sidelobe level from the desired value.
+ w = windows.taylor(M_win, nbar=4, sll=35, norm=False, sym=False, xp=xp)
+ f_np = fft(_xp_copy_to_numpy(w), N_fft)
+
+ spec = 20 * np.log10(np.abs(f_np / np.max(f_np)))
+
+ first_zero = np.argmax(np.diff(spec) > 0)
+
+ PSLL = np.max(spec[first_zero:-first_zero])
+
+ BW_3dB = 2*np.argmax(spec <= -3.0102999566398121) / N_fft * M_win
+ BW_18dB = 2*np.argmax(spec <= -18.061799739838872) / N_fft * M_win
+
+ assert math.isclose(PSLL, -35.1672, abs_tol=1)
+ assert math.isclose(BW_3dB, 1.1822, abs_tol=0.1)
+ assert math.isclose(BW_18dB, 2.6112, abs_tol=0.1)
+
+
+@make_xp_test_case(windows.bohman)
+class TestBohman:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.bohman(6, xp=xp),
+ xp.asarray([0, 0.1791238937062839, 0.8343114522576858,
+ 0.8343114522576858, 0.1791238937062838, 0],
+ dtype=xp.float64))
+ xp_assert_close(windows.bohman(7, sym=True, xp=xp),
+ xp.asarray([0, 0.1089977810442293, 0.6089977810442293, 1.0,
+ 0.6089977810442295, 0.1089977810442293, 0],
+ dtype=xp.float64))
+ xp_assert_close(windows.bohman(6, False, xp=xp),
+ xp.asarray([0, 0.1089977810442293, 0.6089977810442293, 1.0,
+ 0.6089977810442295, 0.1089977810442293],
+ dtype=xp.float64))
+
+
+@make_xp_test_case(windows.boxcar)
+class TestBoxcar:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.boxcar(6, xp=xp),
+ xp.asarray([1.0, 1, 1, 1, 1, 1], dtype=xp.float64))
+ xp_assert_close(windows.boxcar(7, xp=xp),
+ xp.asarray([1.0, 1, 1, 1, 1, 1, 1], dtype=xp.float64))
+ xp_assert_close(windows.boxcar(6, False, xp=xp),
+ xp.asarray([1.0, 1, 1, 1, 1, 1], dtype=xp.float64))
+
+
+cheb_odd_true = [0.200938, 0.107729, 0.134941, 0.165348,
+ 0.198891, 0.235450, 0.274846, 0.316836,
+ 0.361119, 0.407338, 0.455079, 0.503883,
+ 0.553248, 0.602637, 0.651489, 0.699227,
+ 0.745266, 0.789028, 0.829947, 0.867485,
+ 0.901138, 0.930448, 0.955010, 0.974482,
+ 0.988591, 0.997138, 1.000000, 0.997138,
+ 0.988591, 0.974482, 0.955010, 0.930448,
+ 0.901138, 0.867485, 0.829947, 0.789028,
+ 0.745266, 0.699227, 0.651489, 0.602637,
+ 0.553248, 0.503883, 0.455079, 0.407338,
+ 0.361119, 0.316836, 0.274846, 0.235450,
+ 0.198891, 0.165348, 0.134941, 0.107729,
+ 0.200938]
+
+cheb_even_true = [0.203894, 0.107279, 0.133904,
+ 0.163608, 0.196338, 0.231986,
+ 0.270385, 0.311313, 0.354493,
+ 0.399594, 0.446233, 0.493983,
+ 0.542378, 0.590916, 0.639071,
+ 0.686302, 0.732055, 0.775783,
+ 0.816944, 0.855021, 0.889525,
+ 0.920006, 0.946060, 0.967339,
+ 0.983557, 0.994494, 1.000000,
+ 1.000000, 0.994494, 0.983557,
+ 0.967339, 0.946060, 0.920006,
+ 0.889525, 0.855021, 0.816944,
+ 0.775783, 0.732055, 0.686302,
+ 0.639071, 0.590916, 0.542378,
+ 0.493983, 0.446233, 0.399594,
+ 0.354493, 0.311313, 0.270385,
+ 0.231986, 0.196338, 0.163608,
+ 0.133904, 0.107279, 0.203894]
+
+
+@make_xp_test_case(windows.chebwin)
+class TestChebWin:
+
+ def test_basic(self, xp):
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "This window is not suitable", UserWarning)
+ xp_assert_close(windows.chebwin(6, 100, xp=xp),
+ xp.asarray([0.1046401879356917, 0.5075781475823447,
+ 1.0, 1.0,
+ 0.5075781475823447, 0.1046401879356917],
+ dtype=xp.float64),
+ atol=1e-8
+ )
+ xp_assert_close(windows.chebwin(7, 100, xp=xp),
+ xp.asarray([0.05650405062850233, 0.316608530648474,
+ 0.7601208123539079, 1.0, 0.7601208123539079,
+ 0.316608530648474, 0.05650405062850233],
+ dtype=xp.float64))
+ xp_assert_close(windows.chebwin(6, 10, xp=xp),
+ xp.asarray([1.0, 0.6071201674458373, 0.6808391469897297,
+ 0.6808391469897297, 0.6071201674458373, 1.0],
+ dtype=xp.float64))
+ xp_assert_close(windows.chebwin(7, 10, xp=xp),
+ xp.asarray([1.0, 0.5190521247588651, 0.5864059018130382,
+ 0.6101519801307441, 0.5864059018130382,
+ 0.5190521247588651, 1.0], dtype=xp.float64))
+ xp_assert_close(windows.chebwin(6, 10, False, xp=xp),
+ xp.asarray([1.0, 0.5190521247588651, 0.5864059018130382,
+ 0.6101519801307441, 0.5864059018130382,
+ 0.5190521247588651], dtype=xp.float64))
+
+ def test_cheb_odd_high_attenuation(self, xp):
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "This window is not suitable", UserWarning)
+ cheb_odd = windows.chebwin(53, at=-40, xp=xp)
+ assert_array_almost_equal(cheb_odd, xp.asarray(cheb_odd_true), decimal=4)
+
+ def test_cheb_even_high_attenuation(self, xp):
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "This window is not suitable", UserWarning)
+ cheb_even = windows.chebwin(54, at=40, xp=xp)
+ assert_array_almost_equal(cheb_even, xp.asarray(cheb_even_true), decimal=4)
+
+ def test_cheb_odd_low_attenuation(self, xp):
+ cheb_odd_low_at_true = xp.asarray([1.000000, 0.519052, 0.586405,
+ 0.610151, 0.586405, 0.519052,
+ 1.000000], dtype=xp.float64)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "This window is not suitable", UserWarning)
+ cheb_odd = windows.chebwin(7, at=10, xp=xp)
+ assert_array_almost_equal(cheb_odd, cheb_odd_low_at_true, decimal=4)
+
+ def test_cheb_even_low_attenuation(self, xp):
+ cheb_even_low_at_true = xp.asarray([1.000000, 0.451924, 0.51027,
+ 0.541338, 0.541338, 0.51027,
+ 0.451924, 1.000000], dtype=xp.float64)
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "This window is not suitable", UserWarning)
+ cheb_even = windows.chebwin(8, at=-10, xp=xp)
+ assert_array_almost_equal(cheb_even, cheb_even_low_at_true, decimal=4)
+
+
+exponential_data = {
+ (4, None, 0.2, False):
+ array([4.53999297624848542e-05,
+ 6.73794699908546700e-03, 1.00000000000000000e+00,
+ 6.73794699908546700e-03]),
+ (4, None, 0.2, True): array([0.00055308437014783, 0.0820849986238988,
+ 0.0820849986238988, 0.00055308437014783]),
+ (4, None, 1.0, False): array([0.1353352832366127, 0.36787944117144233, 1.,
+ 0.36787944117144233]),
+ (4, None, 1.0, True): array([0.22313016014842982, 0.60653065971263342,
+ 0.60653065971263342, 0.22313016014842982]),
+ (4, 2, 0.2, False):
+ array([4.53999297624848542e-05, 6.73794699908546700e-03,
+ 1.00000000000000000e+00, 6.73794699908546700e-03]),
+ (4, 2, 0.2, True): None,
+ (4, 2, 1.0, False): array([0.1353352832366127, 0.36787944117144233, 1.,
+ 0.36787944117144233]),
+ (4, 2, 1.0, True): None,
+ (5, None, 0.2, True):
+ array([4.53999297624848542e-05,
+ 6.73794699908546700e-03, 1.00000000000000000e+00,
+ 6.73794699908546700e-03, 4.53999297624848542e-05]),
+ (5, None, 1.0, True): array([0.1353352832366127, 0.36787944117144233, 1.,
+ 0.36787944117144233, 0.1353352832366127]),
+ (5, 2, 0.2, True): None,
+ (5, 2, 1.0, True): None
+}
+
+
+@make_xp_test_case(windows.exponential)
+def test_exponential(xp):
+ for k, v in exponential_data.items():
+ if v is None:
+ assert_raises(ValueError, windows.exponential, *k, xp=xp)
+ else:
+ win = windows.exponential(*k, xp=xp)
+ xp_assert_close(win, xp.asarray(v), rtol=1e-14)
+
+
+@make_xp_test_case(windows.flattop)
+class TestFlatTop:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.flattop(6, sym=False, xp=xp),
+ xp.asarray([-0.000421051, -0.051263156, 0.19821053, 1.0,
+ 0.19821053, -0.051263156], dtype=xp.float64))
+ xp_assert_close(windows.flattop(7, sym=False, xp=xp),
+ xp.asarray([-0.000421051, -0.03684078115492348,
+ 0.01070371671615342, 0.7808739149387698,
+ 0.7808739149387698, 0.01070371671615342,
+ -0.03684078115492348], dtype=xp.float64))
+ xp_assert_close(windows.flattop(6, xp=xp),
+ xp.asarray([-0.000421051, -0.0677142520762119,
+ 0.6068721525762117, 0.6068721525762117,
+ -0.0677142520762119, -0.000421051],
+ dtype=xp.float64))
+ xp_assert_close(windows.flattop(7, True, xp=xp),
+ xp.asarray([-0.000421051, -0.051263156, 0.19821053, 1.0,
+ 0.19821053, -0.051263156, -0.000421051],
+ dtype=xp.float64))
+
+
+@make_xp_test_case(windows.gaussian)
+class TestGaussian:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.gaussian(6, 1.0, xp=xp),
+ xp.asarray([0.04393693362340742, 0.3246524673583497,
+ 0.8824969025845955, 0.8824969025845955,
+ 0.3246524673583497, 0.04393693362340742],
+ dtype=xp.float64))
+ xp_assert_close(windows.gaussian(7, 1.2, xp=xp),
+ xp.asarray([0.04393693362340742, 0.2493522087772962,
+ 0.7066482778577162, 1.0, 0.7066482778577162,
+ 0.2493522087772962, 0.04393693362340742],
+ dtype=xp.float64))
+ xp_assert_close(windows.gaussian(7, 3, xp=xp),
+ xp.asarray([0.6065306597126334, 0.8007374029168081,
+ 0.9459594689067654, 1.0, 0.9459594689067654,
+ 0.8007374029168081, 0.6065306597126334],
+ dtype=xp.float64))
+ xp_assert_close(windows.gaussian(6, 3, False, xp=xp),
+ xp.asarray([0.6065306597126334, 0.8007374029168081,
+ 0.9459594689067654, 1.0, 0.9459594689067654,
+ 0.8007374029168081], dtype=xp.float64))
+
+
+@make_xp_test_case(windows.general_cosine)
+class TestGeneralCosine:
+
+ def test_basic(self, xp):
+ a = xp.asarray([0.5, 0.3, 0.2])
+ xp_assert_close(windows.general_cosine(5, a),
+ xp.asarray([0.4, 0.3, 1, 0.3, 0.4], dtype=xp.float64))
+
+ a = xp.asarray([0.5, 0.3, 0.2])
+ xp_assert_close(windows.general_cosine(4, a, sym=False),
+ xp.asarray([0.4, 0.3, 1, 0.3], dtype=xp.float64))
+
+
+@make_xp_test_case(windows.general_hamming)
+class TestGeneralHamming:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.general_hamming(5, 0.7, xp=xp),
+ xp.asarray([0.4, 0.7, 1.0, 0.7, 0.4], dtype=xp.float64))
+ xp_assert_close(windows.general_hamming(5, 0.75, sym=False, xp=xp),
+ xp.asarray([0.5, 0.6727457514, 0.9522542486,
+ 0.9522542486, 0.6727457514], dtype=xp.float64))
+ xp_assert_close(windows.general_hamming(6, 0.75, sym=True, xp=xp),
+ xp.asarray([0.5, 0.6727457514, 0.9522542486,
+ 0.9522542486, 0.6727457514, 0.5], dtype=xp.float64))
+
+
+@make_xp_test_case(windows.hamming)
+class TestHamming:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.hamming(6, False, xp=xp),
+ xp.asarray([0.08, 0.31, 0.77, 1.0, 0.77, 0.31],
+ dtype=xp.float64))
+ xp_assert_close(windows.hamming(7, sym=False, xp=xp),
+ xp.asarray([0.08, 0.2531946911449826, 0.6423596296199047,
+ 0.9544456792351128, 0.9544456792351128,
+ 0.6423596296199047, 0.2531946911449826],
+ dtype=xp.float64))
+ xp_assert_close(windows.hamming(6, xp=xp),
+ xp.asarray([0.08, 0.3978521825875242, 0.9121478174124757,
+ 0.9121478174124757, 0.3978521825875242, 0.08],
+ dtype=xp.float64))
+ xp_assert_close(windows.hamming(7, sym=True, xp=xp),
+ xp.asarray([0.08, 0.31, 0.77, 1.0, 0.77, 0.31, 0.08],
+ dtype=xp.float64))
+
+
+@make_xp_test_case(windows.hann)
+class TestHann:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.hann(6, sym=False, xp=xp),
+ xp.asarray([0, 0.25, 0.75, 1.0, 0.75, 0.25], dtype=xp.float64),
+ rtol=1e-15, atol=1e-15)
+ xp_assert_close(windows.hann(7, sym=False, xp=xp),
+ xp.asarray([0, 0.1882550990706332, 0.6112604669781572,
+ 0.9504844339512095, 0.9504844339512095,
+ 0.6112604669781572, 0.1882550990706332],
+ dtype=xp.float64),
+ rtol=1e-15, atol=1e-15)
+ xp_assert_close(windows.hann(6, True, xp=xp),
+ xp.asarray([0, 0.3454915028125263, 0.9045084971874737,
+ 0.9045084971874737, 0.3454915028125263, 0],
+ dtype=xp.float64),
+ rtol=1e-15, atol=1e-15)
+ xp_assert_close(windows.hann(7, xp=xp),
+ xp.asarray([0, 0.25, 0.75, 1.0, 0.75, 0.25, 0],
+ dtype=xp.float64),
+ rtol=1e-15, atol=1e-15)
+
+
+@make_xp_test_case(windows.kaiser)
+class TestKaiser:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.kaiser(6, 0.5, xp=xp),
+ xp.asarray([0.9403061933191572, 0.9782962393705389,
+ 0.9975765035372042, 0.9975765035372042,
+ 0.9782962393705389, 0.9403061933191572],
+ dtype=xp.float64))
+ xp_assert_close(windows.kaiser(7, 0.5, xp=xp),
+ xp.asarray([0.9403061933191572, 0.9732402256999829,
+ 0.9932754654413773, 1.0, 0.9932754654413773,
+ 0.9732402256999829, 0.9403061933191572],
+ dtype=xp.float64))
+ xp_assert_close(windows.kaiser(6, 2.7, xp=xp),
+ xp.asarray([0.2603047507678832, 0.6648106293528054,
+ 0.9582099802511439, 0.9582099802511439,
+ 0.6648106293528054, 0.2603047507678832],
+ dtype=xp.float64))
+ xp_assert_close(windows.kaiser(7, 2.7, xp=xp),
+ xp.asarray([0.2603047507678832, 0.5985765418119844,
+ 0.8868495172060835, 1.0, 0.8868495172060835,
+ 0.5985765418119844, 0.2603047507678832],
+ dtype=xp.float64))
+ xp_assert_close(windows.kaiser(6, 2.7, False, xp=xp),
+ xp.asarray([0.2603047507678832, 0.5985765418119844,
+ 0.8868495172060835, 1.0, 0.8868495172060835,
+ 0.5985765418119844], dtype=xp.float64))
+
+
+@make_xp_test_case(windows.kaiser_bessel_derived)
+class TestKaiserBesselDerived:
+
+ def test_basic(self, xp):
+ # cover case `M < 1`
+ w = windows.kaiser_bessel_derived(0.5, beta=4.0, xp=xp)
+ xp_assert_equal(w, xp.asarray([]))
+
+ M = 100
+ w = windows.kaiser_bessel_derived(M, beta=4.0, xp=xp)
+ w2 = windows.get_window(('kaiser bessel derived', 4.0),
+ M, fftbins=False, xp=xp)
+ xp_assert_close(w, w2)
+
+ # Test for Princen-Bradley condition
+ actual = w[:M // 2] ** 2 + w[-M // 2:] ** 2
+ xp_assert_close(actual, xp.ones(actual.shape, dtype=actual.dtype))
+
+ # Test actual values from other implementations
+ # M = 2: sqrt(2) / 2
+ # M = 4: 0.518562710536, 0.855039598640
+ # M = 6: 0.436168993154, 0.707106781187, 0.899864772847
+ # Ref:https://github.com/scipy/scipy/pull/4747#issuecomment-172849418
+ actual = windows.kaiser_bessel_derived(2, beta=np.pi / 2, xp=xp)[:1]
+ desired = xp.ones_like(actual) * math.sqrt(2) / 2.0
+ xp_assert_close(actual, desired)
+
+ xp_assert_close(windows.kaiser_bessel_derived(4, beta=np.pi / 2, xp=xp)[:2],
+ xp.asarray([0.518562710536, 0.855039598640], dtype=xp.float64))
+
+ xp_assert_close(windows.kaiser_bessel_derived(6, beta=np.pi / 2, xp=xp)[:3],
+ xp.asarray([0.436168993154, 0.707106781187, 0.899864772847],
+ dtype=xp.float64))
+
+ def test_exceptions(self, xp):
+ M = 100
+ # Assert ValueError for odd window length
+ msg = ("Kaiser-Bessel Derived windows are only defined for even "
+ "number of points")
+ with assert_raises(ValueError, match=msg):
+ windows.kaiser_bessel_derived(M + 1, beta=4., xp=xp)
+
+ # Assert ValueError for non-symmetric setting
+ msg = ("Kaiser-Bessel Derived windows are only defined for "
+ "symmetric shapes")
+ with assert_raises(ValueError, match=msg):
+ windows.kaiser_bessel_derived(M + 1, beta=4., sym=False, xp=xp)
+
+
+class TestNuttall:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.nuttall(6, sym=False, xp=xp),
+ xp.asarray([0.0003628, 0.0613345, 0.5292298, 1.0, 0.5292298,
+ 0.0613345], dtype=xp.float64))
+ xp_assert_close(windows.nuttall(7, sym=False, xp=xp),
+ xp.asarray([0.0003628, 0.03777576895352025,
+ 0.3427276199688195,
+ 0.8918518610776603, 0.8918518610776603,
+ 0.3427276199688196, 0.0377757689535203],
+ dtype=xp.float64))
+ xp_assert_close(windows.nuttall(6, xp=xp),
+ xp.asarray([0.0003628, 0.1105152530498718,
+ 0.7982580969501282, 0.7982580969501283,
+ 0.1105152530498719, 0.0003628], dtype=xp.float64))
+ xp_assert_close(windows.nuttall(7, True, xp=xp),
+ xp.asarray([0.0003628, 0.0613345, 0.5292298, 1.0,
+ 0.5292298, 0.0613345, 0.0003628], dtype=xp.float64))
+
+
+@make_xp_test_case(windows.parzen)
+class TestParzen:
+
+ def test_basic(self, xp):
+ xp_assert_close(windows.parzen(6, xp=xp),
+ xp.asarray([0.009259259259259254, 0.25, 0.8611111111111112,
+ 0.8611111111111112, 0.25, 0.009259259259259254],
+ dtype=xp.float64))
+ xp_assert_close(windows.parzen(7, sym=True, xp=xp),
+ xp.asarray([0.00583090379008747, 0.1574344023323616,
+ 0.6501457725947521, 1.0, 0.6501457725947521,
+ 0.1574344023323616, 0.00583090379008747],
+ dtype=xp.float64))
+ xp_assert_close(windows.parzen(6, False, xp=xp),
+ xp.asarray([0.00583090379008747, 0.1574344023323616,
+ 0.6501457725947521, 1.0, 0.6501457725947521,
+ 0.1574344023323616], dtype=xp.float64))
+
+
+@make_xp_test_case(windows.triang)
+class TestTriang:
+
+ def test_basic(self, xp):
+
+ xp_assert_close(windows.triang(6, True, xp=xp),
+ xp.asarray([1/6, 1/2, 5/6, 5/6, 1/2, 1/6], dtype=xp.float64))
+ xp_assert_close(windows.triang(7, xp=xp),
+ xp.asarray([1/4, 1/2, 3/4, 1, 3/4, 1/2, 1/4], dtype=xp.float64))
+ xp_assert_close(windows.triang(6, sym=False, xp=xp),
+ xp.asarray([1/4, 1/2, 3/4, 1, 3/4, 1/2], dtype=xp.float64))
+
+
+tukey_data = {
+ (4, 0.5, True): array([0.0, 1.0, 1.0, 0.0]),
+ (4, 0.9, True): array([0.0, 0.84312081893436686,
+ 0.84312081893436686, 0.0]),
+ (4, 1.0, True): array([0.0, 0.75, 0.75, 0.0]),
+ (4, 0.5, False): array([0.0, 1.0, 1.0, 1.0]),
+ (4, 0.9, False): array([0.0, 0.58682408883346526,
+ 1.0, 0.58682408883346526]),
+ (4, 1.0, False): array([0.0, 0.5, 1.0, 0.5]),
+ (5, 0.0, True): array([1.0, 1.0, 1.0, 1.0, 1.0]),
+ (5, 0.8, True): array([0.0, 0.69134171618254492,
+ 1.0, 0.69134171618254492, 0.0]),
+ (5, 1.0, True): array([0.0, 0.5, 1.0, 0.5, 0.0]),
+
+ (6, 0): [1.0, 1, 1, 1, 1, 1],
+ (7, 0): [1.0, 1, 1, 1, 1, 1, 1],
+ (6, .25): [0.0, 1, 1, 1, 1, 0],
+ (7, .25): [0.0, 1, 1, 1, 1, 1, 0],
+ (6,): [0, 0.9045084971874737, 1.0, 1.0, 0.9045084971874735, 0],
+ (7,): [0, 0.75, 1.0, 1.0, 1.0, 0.75, 0],
+ (6, .75): [0, 0.5522642316338269, 1.0, 1.0, 0.5522642316338267, 0],
+ (7, .75): [0, 0.4131759111665348, 0.9698463103929542, 1.0,
+ 0.9698463103929542, 0.4131759111665347, 0],
+ (6, 1): [0, 0.3454915028125263, 0.9045084971874737, 0.9045084971874737,
+ 0.3454915028125263, 0],
+ (7, 1): [0, 0.25, 0.75, 1.0, 0.75, 0.25, 0],
+}
+
+
+@make_xp_test_case(windows.tukey)
+class TestTukey:
+
+ def test_basic(self, xp):
+ # Test against hardcoded data
+ for k, v in tukey_data.items():
+ if v is None:
+ assert_raises(ValueError, windows.tukey, *k, xp=xp)
+ else:
+ if is_torch(xp) and k in [(6,), (6, .75), (7, .75), (6,1)]:
+ atol_rtol = {'rtol': 3e-8, 'atol': 1e-8}
+ else:
+ atol_rtol = {'rtol': 1e-15, 'atol': 1e-15 }
+
+ win = windows.tukey(*k, xp=xp)
+ xp_assert_close(win, xp.asarray(v),
+ check_dtype=False, **atol_rtol)
+
+ def test_extremes(self, xp):
+ # Test extremes of alpha correspond to boxcar and hann
+ tuk0 = windows.tukey(100, 0, xp=xp)
+ box0 = windows.boxcar(100, xp=xp)
+ xp_assert_close(tuk0, box0)
+
+ tuk1 = windows.tukey(100, 1, xp=xp)
+ han1 = windows.hann(100, xp=xp)
+ xp_assert_close(tuk1, han1)
+
+
+dpss_data = {
+ # All values from MATLAB:
+ # * taper[1] of (3, 1.4, 3) sign-flipped
+ # * taper[3] of (5, 1.5, 5) sign-flipped
+ (4, 0.1, 2): ([[0.497943898, 0.502047681, 0.502047681, 0.497943898], [0.670487993, 0.224601537, -0.224601537, -0.670487993]], [0.197961815, 0.002035474]), # noqa: E501
+ (3, 1.4, 3): ([[0.410233151, 0.814504464, 0.410233151], [0.707106781, 0.0, -0.707106781], [0.575941629, -0.580157287, 0.575941629]], [0.999998093, 0.998067480, 0.801934426]), # noqa: E501
+ (5, 1.5, 5): ([[0.1745071052, 0.4956749177, 0.669109327, 0.495674917, 0.174507105], [0.4399493348, 0.553574369, 0.0, -0.553574369, -0.439949334], [0.631452756, 0.073280238, -0.437943884, 0.073280238, 0.631452756], [0.553574369, -0.439949334, 0.0, 0.439949334, -0.553574369], [0.266110290, -0.498935248, 0.600414741, -0.498935248, 0.266110290147157]], [0.999728571, 0.983706916, 0.768457889, 0.234159338, 0.013947282907567]), # noqa: E501
+ (100, 2, 4): ([[0.0030914414, 0.0041266922, 0.005315076, 0.006665149, 0.008184854, 0.0098814158, 0.011761239, 0.013829809, 0.016091597, 0.018549973, 0.02120712, 0.02406396, 0.027120092, 0.030373728, 0.033821651, 0.037459181, 0.041280145, 0.045276872, 0.049440192, 0.053759447, 0.058222524, 0.062815894, 0.067524661, 0.072332638, 0.077222418, 0.082175473, 0.087172252, 0.092192299, 0.097214376, 0.1022166, 0.10717657, 0.11207154, 0.11687856, 0.12157463, 0.12613686, 0.13054266, 0.13476986, 0.13879691, 0.14260302, 0.14616832, 0.14947401, 0.1525025, 0.15523755, 0.15766438, 0.15976981, 0.16154233, 0.16297223, 0.16405162, 0.16477455, 0.16513702, 0.16513702, 0.16477455, 0.16405162, 0.16297223, 0.16154233, 0.15976981, 0.15766438, 0.15523755, 0.1525025, 0.14947401, 0.14616832, 0.14260302, 0.13879691, 0.13476986, 0.13054266, 0.12613686, 0.12157463, 0.11687856, 0.11207154, 0.10717657, 0.1022166, 0.097214376, 0.092192299, 0.087172252, 0.082175473, 0.077222418, 0.072332638, 0.067524661, 0.062815894, 0.058222524, 0.053759447, 0.049440192, 0.045276872, 0.041280145, 0.037459181, 0.033821651, 0.030373728, 0.027120092, 0.02406396, 0.02120712, 0.018549973, 0.016091597, 0.013829809, 0.011761239, 0.0098814158, 0.008184854, 0.006665149, 0.005315076, 0.0041266922, 0.0030914414], [0.018064449, 0.022040342, 0.026325013, 0.030905288, 0.035764398, 0.040881982, 0.046234148, 0.051793558, 0.057529559, 0.063408356, 0.069393216, 0.075444716, 0.081521022, 0.087578202, 0.093570567, 0.099451049, 0.10517159, 0.11068356, 0.11593818, 0.12088699, 0.12548227, 0.12967752, 0.1334279, 0.13669069, 0.13942569, 0.1415957, 0.14316686, 0.14410905, 0.14439626, 0.14400686, 0.14292389, 0.1411353, 0.13863416, 0.13541876, 0.13149274, 0.12686516, 0.12155045, 0.1155684, 0.10894403, 0.10170748, 0.093893752, 0.08554251, 0.076697768, 0.067407559, 0.057723559, 0.04770068, 0.037396627, 0.026871428, 0.016186944, 0.0054063557, -0.0054063557, -0.016186944, -0.026871428, -0.037396627, -0.04770068, -0.057723559, -0.067407559, -0.076697768, -0.08554251, -0.093893752, -0.10170748, -0.10894403, -0.1155684, -0.12155045, -0.12686516, -0.13149274, -0.13541876, -0.13863416, -0.1411353, -0.14292389, -0.14400686, -0.14439626, -0.14410905, -0.14316686, -0.1415957, -0.13942569, -0.13669069, -0.1334279, -0.12967752, -0.12548227, -0.12088699, -0.11593818, -0.11068356, -0.10517159, -0.099451049, -0.093570567, -0.087578202, -0.081521022, -0.075444716, -0.069393216, -0.063408356, -0.057529559, -0.051793558, -0.046234148, -0.040881982, -0.035764398, -0.030905288, -0.026325013, -0.022040342, -0.018064449], [0.064817553, 0.072567801, 0.080292992, 0.087918235, 0.095367076, 0.10256232, 0.10942687, 0.1158846, 0.12186124, 0.12728523, 0.13208858, 0.13620771, 0.13958427, 0.14216587, 0.14390678, 0.14476863, 0.1447209, 0.14374148, 0.14181704, 0.13894336, 0.13512554, 0.13037812, 0.1247251, 0.11819984, 0.11084487, 0.10271159, 0.093859853, 0.084357497, 0.074279719, 0.063708406, 0.052731374, 0.041441525, 0.029935953, 0.018314987, 0.0066811877, -0.0048616765, -0.016209689, -0.027259848, -0.037911124, -0.048065512, -0.05762905, -0.066512804, -0.0746338, -0.081915903, -0.088290621, -0.09369783, -0.098086416, -0.10141482, -0.10365146, -0.10477512, -0.10477512, -0.10365146, -0.10141482, -0.098086416, -0.09369783, -0.088290621, -0.081915903, -0.0746338, -0.066512804, -0.05762905, -0.048065512, -0.037911124, -0.027259848, -0.016209689, -0.0048616765, 0.0066811877, 0.018314987, 0.029935953, 0.041441525, 0.052731374, 0.063708406, 0.074279719, 0.084357497, 0.093859853, 0.10271159, 0.11084487, 0.11819984, 0.1247251, 0.13037812, 0.13512554, 0.13894336, 0.14181704, 0.14374148, 0.1447209, 0.14476863, 0.14390678, 0.14216587, 0.13958427, 0.13620771, 0.13208858, 0.12728523, 0.12186124, 0.1158846, 0.10942687, 0.10256232, 0.095367076, 0.087918235, 0.080292992, 0.072567801, 0.064817553], [0.14985551, 0.15512305, 0.15931467, 0.16236806, 0.16423291, 0.16487165, 0.16426009, 0.1623879, 0.1592589, 0.15489114, 0.14931693, 0.14258255, 0.13474785, 0.1258857, 0.11608124, 0.10543095, 0.094041635, 0.082029213, 0.069517411, 0.056636348, 0.043521028, 0.030309756, 0.017142511, 0.0041592774, -0.0085016282, -0.020705223, -0.032321494, -0.043226982, -0.053306291, -0.062453515, -0.070573544, -0.077583253, -0.083412547, -0.088005244, -0.091319802, -0.093329861, -0.094024602, -0.093408915, -0.091503383, -0.08834406, -0.08398207, -0.078483012, -0.071926192, -0.064403681, -0.056019215, -0.046886954, -0.037130106, -0.026879442, -0.016271713, -0.005448, 0.005448, 0.016271713, 0.026879442, 0.037130106, 0.046886954, 0.056019215, 0.064403681, 0.071926192, 0.078483012, 0.08398207, 0.08834406, 0.091503383, 0.093408915, 0.094024602, 0.093329861, 0.091319802, 0.088005244, 0.083412547, 0.077583253, 0.070573544, 0.062453515, 0.053306291, 0.043226982, 0.032321494, 0.020705223, 0.0085016282, -0.0041592774, -0.017142511, -0.030309756, -0.043521028, -0.056636348, -0.069517411, -0.082029213, -0.094041635, -0.10543095, -0.11608124, -0.1258857, -0.13474785, -0.14258255, -0.14931693, -0.15489114, -0.1592589, -0.1623879, -0.16426009, -0.16487165, -0.16423291, -0.16236806, -0.15931467, -0.15512305, -0.14985551]], [0.999943140, 0.997571533, 0.959465463, 0.721862496]), # noqa: E501
+}
+
+
+@make_xp_test_case(windows.dpss)
+class TestDPSS:
+
+ def test_basic(self, xp):
+ # Test against hardcoded data
+ for k, v in dpss_data.items():
+ win, ratios = windows.dpss(*k, return_ratios=True, xp=xp)
+ xp_assert_close(win, v[0], atol=1e-7, err_msg=k)
+ xp_assert_close(ratios, v[1], rtol=1e-5, atol=1e-7, err_msg=k)
+
+ def test_unity(self, xp):
+ # Test unity value handling (gh-2221)
+ for M in range(1, 21):
+ # corrected w/approximation (default)
+ win = windows.dpss(M, M / 2.1, xp=xp)
+ expected = M % 2 # one for odd, none for even
+ xp_assert_equal(np.isclose(win, 1.).sum(), expected,
+ err_msg=f'{win}')
+ # corrected w/subsample delay (slower)
+ win_sub = windows.dpss(M, M / 2.1, norm='subsample', xp=xp)
+ if M > 2:
+ # @M=2 the subsample doesn't do anything
+ xp_assert_equal(np.isclose(win_sub, 1.).sum(), expected,
+ err_msg=f'{win_sub}')
+ xp_assert_close(win, win_sub, rtol=0.03) # within 3%
+ # not the same, l2-norm
+ win_2 = windows.dpss(M, M / 2.1, norm=2, xp=xp)
+ expected = 1 if M == 1 else 0
+ xp_assert_equal(np.isclose(win_2, 1.).sum(), expected,
+ err_msg=f'{win_2}')
+
+ def test_extremes(self, xp):
+ # Test extremes of alpha
+ lam = windows.dpss(31, 6, 4, return_ratios=True, xp=xp)[1]
+ xp_assert_close(lam, xp.ones_like(lam))
+ lam = windows.dpss(31, 7, 4, return_ratios=True, xp=xp)[1]
+ xp_assert_close(lam, xp.ones_like(lam))
+ lam = windows.dpss(31, 8, 4, return_ratios=True, xp=xp)[1]
+ xp_assert_close(lam, xp.ones_like(lam))
+
+ def test_degenerate(self, xp):
+ # Test failures
+ assert_raises(ValueError, windows.dpss, 4, 1.5, -1) # Bad Kmax
+ assert_raises(ValueError, windows.dpss, 4, 1.5, -5)
+ assert_raises(TypeError, windows.dpss, 4, 1.5, 1.1)
+ assert_raises(ValueError, windows.dpss, 3, 1.5, 3) # NW must be < N/2.
+ assert_raises(ValueError, windows.dpss, 3, -1, 3) # NW must be pos
+ assert_raises(ValueError, windows.dpss, 3, 0, 3)
+ assert_raises(ValueError, windows.dpss, -1, 1, 3) # negative M
+
+ @skip_xp_backends(np_only=True)
+ def test_degenerate_signle_samples(self, xp):
+ # Single samples
+ w = windows.dpss(1, 1.)
+ xp_assert_equal(w, [1.])
+ w, ratio = windows.dpss(1, 1., return_ratios=True)
+ xp_assert_equal(w, [1.])
+ assert ratio == 1.
+ w, ratio = windows.dpss(1, 1., Kmax=4, return_ratios=True)
+ xp_assert_equal(w, [1.])
+ assert isinstance(ratio, np.ndarray)
+ xp_assert_equal(ratio, [1.])
+
+ assert_raises(ValueError, windows.dpss, 4, 1.5, -1, xp=xp) # Bad Kmax
+ assert_raises(ValueError, windows.dpss, 4, 1.5, -5, xp=xp)
+ assert_raises(TypeError, windows.dpss, 4, 1.5, 1.1, xp=xp)
+ assert_raises(ValueError, windows.dpss, 3, 1.5, 3, xp=xp) # NW must be < N/2.
+ assert_raises(ValueError, windows.dpss, 3, -1, 3, xp=xp) # NW must be pos
+ assert_raises(ValueError, windows.dpss, 3, 0, 3, xp=xp)
+ assert_raises(ValueError, windows.dpss, -1, 1, 3, xp=xp) # negative M
+
+
+@make_xp_test_case(windows.lanczos)
+class TestLanczos:
+
+ def test_basic(self, xp):
+ # Analytical results:
+ # sinc(x) = sinc(-x)
+ # sinc(pi) = 0, sinc(0) = 1
+ # Hand computation on WolframAlpha:
+ # sinc(2 pi / 3) = 0.413496672
+ # sinc(pi / 3) = 0.826993343
+ # sinc(3 pi / 5) = 0.504551152
+ # sinc(pi / 5) = 0.935489284
+ xp_assert_close(windows.lanczos(6, sym=False, xp=xp),
+ xp.asarray([0., 0.413496672,
+ 0.826993343, 1., 0.826993343,
+ 0.413496672], dtype=xp.float64),
+ atol=1e-9)
+ xp_assert_close(windows.lanczos(6, xp=xp),
+ xp.asarray([0., 0.504551152,
+ 0.935489284, 0.935489284,
+ 0.504551152, 0.], dtype=xp.float64),
+ atol=1e-9)
+ xp_assert_close(windows.lanczos(7, sym=True, xp=xp),
+ xp.asarray([0., 0.413496672,
+ 0.826993343, 1., 0.826993343,
+ 0.413496672, 0.], dtype=xp.float64),
+ atol=1e-9)
+
+ def test_array_size(self, xp):
+ for n in [0, 10, 11]:
+ assert windows.lanczos(n, sym=False, xp=xp).shape[0] == n
+ assert windows.lanczos(n, sym=True, xp=xp).shape[0] == n
+
+
+@make_xp_test_case(windows.get_window)
+class TestGetWindow:
+ """Unit test for `scipy.signal.get_windows`. """
+
+ def test_WIN_FUNC_DATA_integrity(self):
+ """Verify that the `_windows._WIN_FUNC_DATA` dict is consistent.
+
+ The keys of _WIN_FUNC_DATA are made of tuples of strings of allowed window
+ names. Its values are 2-tuples made up of the window function and a
+ entry characterizing the existence of window parameters as ``True``,
+ ``False`` or ``'OPTIONAL'``.
+
+
+ It is verified that the correct window name (i.e., corresponding to the
+ function in the value tuple) is included in the key tuple. It is also checked
+ that the second entry in the value tuple is either ``True``, ``False`` or
+ ``'OPTIONAL'``.
+ """
+ for nn_, v_ in _WIN_FUNC_DATA.items():
+ func_name = v_[0].__name__
+ msg = f"Function name in {nn_} does not contain name of actual function!"
+ assert func_name in nn_, msg
+ assert v_[1] in (True, False, 'OPTIONAL')
+
+ @make_xp_test_case(windows.boxcar)
+ def test_boxcar(self, xp):
+ w = windows.get_window('boxcar', 12, xp=xp)
+ xp_assert_equal(w, xp.ones_like(w))
+
+ # window is a tuple of len 1
+ w = windows.get_window(('boxcar',), 16, xp=xp)
+ xp_assert_equal(w, xp.ones_like(w))
+
+ @make_xp_test_case(windows.chebwin)
+ def test_cheb_odd(self, xp):
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "This window is not suitable", UserWarning)
+ w = windows.get_window(('chebwin', -40), 53, fftbins=False, xp=xp)
+ assert_array_almost_equal(
+ w, xp.asarray(cheb_odd_true, dtype=xp.float64), decimal=4
+ )
+
+ @make_xp_test_case(windows.chebwin)
+ def test_cheb_even(self, xp):
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "This window is not suitable", UserWarning)
+ w = windows.get_window(('chebwin', 40), 54, fftbins=False, xp=xp)
+ assert_array_almost_equal(w, xp.asarray(cheb_even_true), decimal=4)
+
+ @make_xp_test_case(windows.dpss)
+ def test_dpss(self, xp):
+ win1 = windows.get_window(('dpss', 3), 64, fftbins=False, xp=xp)
+ win2 = windows.dpss(64, 3, xp=xp)
+ xp_assert_equal(win1, win2)
+
+ @make_xp_test_case(windows.kaiser)
+ def test_kaiser_float(self, xp):
+ win1 = windows.get_window(7.2, 64, xp=xp)
+ win2 = windows.kaiser(64, 7.2, False, xp=xp)
+ if is_jax(xp):
+ # On JAX with jit enabled, there is a very small discrepancy
+ # in the results.
+ xp_assert_close(win1, win2, rtol=xp.finfo(win1.dtype).eps)
+ else:
+ xp_assert_equal(win1, win2)
+
+ @pytest.mark.parametrize('Nx', [-1, 3.0, np.float64(3)])
+ @make_xp_test_case(windows.hann)
+ def test_invalid_parameter_NX(self, Nx, xp):
+ with pytest.raises(ValueError, match="^Parameter Nx=.*"):
+ windows.get_window('hann', Nx, xp=xp)
+
+ # noinspection PyTypeChecker
+ def test_invalid_inputs(self, xp):
+ """Raise all exceptions (except those concerning parameter `Nx`). """
+ with pytest.raises(ValueError, match="^Parameter fftbins=.*"):
+ windows.get_window('hann', 5, fftbins=1, xp=xp)
+ with pytest.raises(ValueError, match="^Parameter window=.*"):
+ windows.get_window(['hann',], 5, xp=xp)
+ with pytest.raises(ValueError, match="^First tuple entry of parameter win.*"):
+ windows.get_window((42,), 5, xp=xp)
+ with pytest.raises(ValueError, match="^Invalid window name 'INVALID'.*"):
+ windows.get_window('INVALID', 5, xp=xp)
+ with pytest.raises(ValueError, match="^'hann' does not allow parameters.*"):
+ windows.get_window(('hann', 1), 5, xp=xp)
+ with pytest.raises(ValueError, match="^'kaiser' must have parameters.*"):
+ windows.get_window('kaiser', 5, xp=xp)
+ with pytest.raises(ValueError, match="^Window dpss must have one.*"):
+ windows.get_window(('dpss', 1, 2), 5, xp=xp)
+ with pytest.raises(ValueError, match="^'general_cosine' does not accept.*"):
+ xp_ = xp or np # ensure parameter xp_ is not None
+ windows.get_window(('general cosine', [1, 2]), 5, xp=xp_)
+
+ @make_xp_test_case(windows.bartlett)
+ def test_symmetric_periodic(self, xp):
+ """Ensure that suffixes `_periodic` and `_symmetric` work for window names. """
+ w_sym = windows.bartlett(5, sym=True, xp=xp)
+ xp_assert_close(get_window('bartlett', 5, fftbins=False, xp=xp), w_sym)
+ xp_assert_close(get_window('bartlett_symmetric', 5, xp=xp), w_sym)
+ # overwrite parameter `fftbins`:
+ xp_assert_close(get_window('bartlett_symmetric', 5, fftbins=True, xp=xp), w_sym)
+
+ w_per = windows.bartlett(5, sym=False, xp=xp)
+ xp_assert_close(get_window('bartlett', 5, xp=xp), w_per)
+ xp_assert_close(get_window('bartlett', 5, fftbins=True, xp=xp), w_per)
+ xp_assert_close(get_window('bartlett_periodic', 5, xp=xp), w_per)
+ # overwrite parameter `fftbins`:
+ xp_assert_close(get_window('bartlett_periodic', 5, fftbins=False, xp=xp),
+ w_per)
+
+ @make_xp_test_case(windows.kaiser)
+ def test_array_as_window(self, xp):
+ # github issue 3603
+ osfactor = 128
+ sig = xp.arange(128)
+
+ win = windows.get_window(('kaiser', 8.0), osfactor // 2, xp=xp)
+ mesg = "^window must" if is_cupy(xp) else "^window.shape="
+ with assert_raises(ValueError, match=mesg):
+ resample(sig, sig.shape[0] * osfactor, window=win)
+
+ @make_xp_test_case(windows.general_cosine)
+ def test_general_cosine(self, xp):
+ xp_assert_close(get_window(('general_cosine', xp.asarray([0.5, 0.3, 0.2])), 4),
+ xp.asarray([0.4, 0.3, 1, 0.3], dtype=xp.float64))
+ xp_assert_close(get_window(('general_cosine', xp.asarray([0.5, 0.3, 0.2])), 4,
+ fftbins=False),
+ xp.asarray([0.4, 0.55, 0.55, 0.4], dtype=xp.float64))
+
+ with pytest.raises(ValueError):
+ get_window(('general_cosine', [0.5, 0.3, 0.2]), 4, xp=xp)
+
+ @make_xp_test_case(windows.general_hamming)
+ def test_general_hamming(self, xp):
+ xp_assert_close(get_window(('general_hamming', 0.7), 5, xp=xp),
+ xp.asarray([0.4, 0.6072949, 0.9427051, 0.9427051, 0.6072949],
+ dtype=xp.float64))
+ xp_assert_close(get_window(('general_hamming', 0.7), 5, fftbins=False, xp=xp),
+ xp.asarray([0.4, 0.7, 1.0, 0.7, 0.4], dtype=xp.float64))
+
+ @make_xp_test_case(windows.lanczos)
+ def test_lanczos(self, xp):
+ xp_assert_close(get_window('lanczos', 6, xp=xp),
+ xp.asarray([0., 0.413496672, 0.826993343, 1., 0.826993343,
+ 0.413496672], dtype=xp.float64), atol=1e-9)
+ xp_assert_close(get_window('lanczos', 6, fftbins=False, xp=xp),
+ xp.asarray([0., 0.504551152, 0.935489284, 0.935489284,
+ 0.504551152, 0.], dtype=xp.float64), atol=1e-9)
+ xp_assert_close(get_window('lanczos', 6, xp=xp),
+ get_window('sinc', 6, xp=xp))
+
+ def test_xp_default(self, xp):
+ # no explicit xp= argument, default to numpy
+ win = get_window('lanczos', 6)
+ assert isinstance(win, np.ndarray)
+
+ win = get_window('lanczos', 6, xp=xp)
+ if not is_numpy(xp):
+ assert not isinstance(win, np.ndarray)
+
+
+@skip_xp_backends("dask.array", reason="https://github.com/dask/dask/issues/2620")
+@pytest.mark.parametrize(
+ "window,window_name,params",
+ [
+ make_xp_pytest_param(getattr(windows, window_name), window_name, params)
+ for window_name, params in window_funcs
+ ]
+)
+def test_windowfunc_basics(window, window_name, params, xp):
+ window = getattr(windows, window_name)
+ if is_jax(xp) and window_name in ['taylor', 'chebwin']:
+ pytest.skip(reason=f'{window_name = }: item assignment')
+ if window_name in ['dpss']:
+ if is_cupy(xp):
+ pytest.skip(reason='dpss window is not implemented for cupy')
+ if is_torch(xp) and SCIPY_DEVICE != 'cpu':
+ pytest.skip(reason='needs eight_tridiagonal which is CPU only')
+
+ with warnings.catch_warnings():
+ warnings.filterwarnings(
+ "ignore", "This window is not suitable", UserWarning)
+ # Check symmetry for odd and even lengths
+ w1 = window(8, *params, sym=True, xp=xp)
+ w2 = window(7, *params, sym=False, xp=xp)
+ xp_assert_close(w1[:-1], w2)
+
+ w1 = window(9, *params, sym=True, xp=xp)
+ w2 = window(8, *params, sym=False, xp=xp)
+ xp_assert_close(w1[:-1], w2)
+
+ # Check that functions run and output lengths are correct
+ assert window(6, *params, sym=True, xp=xp).shape[0] == 6
+ assert window(6, *params, sym=False, xp=xp).shape[0] == 6
+ assert window(7, *params, sym=True, xp=xp).shape[0] == 7
+ assert window(7, *params, sym=False, xp=xp).shape[0] == 7
+
+ # Check invalid lengths
+ assert_raises(ValueError, window, 5.5, *params, xp=xp)
+ assert_raises(ValueError, window, -7, *params, xp=xp)
+
+ # Check degenerate cases
+ xp_assert_equal(window(0, *params, sym=True, xp=xp),
+ xp.asarray([], dtype=xp.float64))
+ xp_assert_equal(window(0, *params, sym=False, xp=xp),
+ xp.asarray([], dtype=xp.float64))
+ xp_assert_equal(window(1, *params, sym=True, xp=xp),
+ xp.asarray([1.], dtype=xp.float64))
+ xp_assert_equal(window(1, *params, sym=False, xp=xp),
+ xp.asarray([1.], dtype=xp.float64))
+
+ # Check dtype
+ assert window(0, *params, sym=True, xp=xp).dtype == xp.float64
+ assert window(0, *params, sym=False, xp=xp).dtype == xp.float64
+ assert window(1, *params, sym=True, xp=xp).dtype == xp.float64
+ assert window(1, *params, sym=False, xp=xp).dtype == xp.float64
+ assert window(6, *params, sym=True, xp=xp).dtype == xp.float64
+ assert window(6, *params, sym=False, xp=xp).dtype == xp.float64
+
+ # Check normalization
+ assert xp.all(window(10, *params, sym=True, xp=xp) < 1.01)
+ assert xp.all(window(10, *params, sym=False, xp=xp) < 1.01)
+ assert xp.all(window(9, *params, sym=True, xp=xp) < 1.01)
+ assert xp.all(window(9, *params, sym=False, xp=xp) < 1.01)
+
+ # Check that DFT-even spectrum is purely real for odd and even
+ res = fft(window(10, *params, sym=False, xp=xp))
+ res = xp.imag(res)
+ xp_assert_close(res, xp.zeros_like(res), atol=1e-14)
+
+ res = fft(window(11, *params, sym=False, xp=xp))
+ res = xp.imag(res)
+ xp_assert_close(res, xp.zeros_like(res), atol=1e-14)
+
+
+@make_xp_test_case(get_window)
+def test_needs_params(xp):
+ for winstr in ['kaiser', 'ksr', 'kaiser_bessel_derived', 'kbd',
+ 'gaussian', 'gauss', 'gss',
+ 'general gaussian', 'general_gaussian',
+ 'general gauss', 'general_gauss', 'ggs',
+ 'dss', 'dpss', 'general cosine', 'general_cosine',
+ 'chebwin', 'cheb', 'general hamming', 'general_hamming',
+ ]:
+ assert_raises(ValueError, get_window, winstr, 7, xp=xp)
+
+
+_winstr = ['barthann',
+ 'bartlett',
+ 'blackman',
+ 'blackmanharris',
+ 'bohman',
+ 'boxcar',
+ 'cosine',
+ 'flattop',
+ 'hamming',
+ 'nuttall',
+ 'parzen',
+ 'taylor',
+ 'exponential',
+ 'poisson',
+ 'tukey',
+ 'tuk',
+ 'triangle',
+ 'lanczos',
+ 'sinc',
+]
+
+
+@pytest.mark.parametrize(
+ 'window,winstr',
+ [
+ make_xp_pytest_param(_WIN_FUNCS[winstr][0], winstr)
+ for winstr in _winstr
+ ]
+)
+@make_xp_test_case(get_window)
+def test_not_needs_params(xp, window, winstr):
+ if is_jax(xp) and winstr in ['taylor']:
+ pytest.skip(reason=f'{winstr}: item assignment')
+ win = get_window(winstr, 7, xp=xp)
+ assert win.shape[0] == 7
+
+
+@make_xp_test_case(windows.lanczos)
+def test_symmetric(xp):
+
+ for win in [windows.lanczos]:
+ # Even sampling points
+ w = win(4096, xp=xp)
+ flip = array_namespace(w).flip
+ error = xp.max(xp.abs(w - flip(w)))
+ xp_assert_equal(error, xp.asarray(0.0), check_dtype=False, check_0d=False)
+
+ # Odd sampling points
+ w = win(4097, xp=xp)
+ error = xp.max(xp.abs(w - flip(w)))
+ xp_assert_equal(error, xp.asarray(0.0), check_dtype=False, check_0d=False)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/waveforms.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/waveforms.py
new file mode 100644
index 0000000000000000000000000000000000000000..30e71348d04276a66470a4053d97cefc60f7136e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/waveforms.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.signal` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [ # noqa: F822
+ 'sawtooth', 'square', 'gausspulse', 'chirp', 'sweep_poly',
+ 'unit_impulse',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="signal", module="waveforms",
+ private_modules=["_waveforms"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/wavelets.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/wavelets.py
new file mode 100644
index 0000000000000000000000000000000000000000..fc897a2483536df7e995faaa29af621e25fe38c7
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/wavelets.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.signal` 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="signal", module="wavelets",
+ private_modules=["_wavelets"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/.__windows.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/.__windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/.__windows.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/._windows.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/._windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/._windows.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..f260df1367a5f9457b1f6e916def853c6c461924
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/__init__.py
@@ -0,0 +1,52 @@
+"""
+Window functions (:mod:`scipy.signal.windows`)
+==============================================
+
+The suite of window functions for filtering and spectral estimation.
+
+.. currentmodule:: scipy.signal.windows
+
+.. autosummary::
+ :toctree: generated/
+
+ get_window -- Convenience function for creating various windows.
+
+ barthann -- Bartlett-Hann window
+ bartlett -- Bartlett window
+ blackman -- Blackman window
+ blackmanharris -- Minimum 4-term Blackman-Harris window
+ bohman -- Bohman window
+ boxcar -- Boxcar window
+ chebwin -- Dolph-Chebyshev window
+ cosine -- Cosine window
+ dpss -- Discrete prolate spheroidal sequences
+ exponential -- Exponential window
+ flattop -- Flat top window
+ gaussian -- Gaussian window
+ general_cosine -- Generalized Cosine window
+ general_gaussian -- Generalized Gaussian window
+ general_hamming -- Generalized Hamming window
+ hamming -- Hamming window
+ hann -- Hann window
+ kaiser -- Kaiser window
+ kaiser_bessel_derived -- Kaiser-Bessel derived window
+ lanczos -- Lanczos window also known as a sinc window
+ nuttall -- Nuttall's minimum 4-term Blackman-Harris window
+ parzen -- Parzen window
+ taylor -- Taylor window
+ triang -- Triangular window
+ tukey -- Tukey window
+
+"""
+
+from ._windows import *
+
+# Deprecated namespaces, to be removed in v2.0.0
+from . import windows
+
+__all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall',
+ 'blackmanharris', 'flattop', 'bartlett', 'barthann',
+ 'hamming', 'kaiser', 'kaiser_bessel_derived', 'gaussian',
+ 'general_gaussian', 'general_cosine', 'general_hamming',
+ 'chebwin', 'cosine', 'hann', 'exponential', 'tukey', 'taylor',
+ 'get_window', 'dpss', 'lanczos']
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/_windows.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/_windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..e3d341a1cecddccee740e1399f635c0994c86520
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/_windows.py
@@ -0,0 +1,2608 @@
+"""The suite of window functions."""
+
+import math
+import numbers
+import operator
+import warnings
+from scipy._lib import doccer
+
+from scipy import linalg, special, fft as sp_fft
+from scipy._lib.array_api_compat import numpy as np_compat
+from scipy._lib._array_api import array_namespace, xp_device
+from scipy._lib._array_api import xp_capabilities
+from scipy._lib import array_api_extra as xpx
+
+__all__ = ['boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall',
+ 'blackmanharris', 'flattop', 'bartlett', 'barthann',
+ 'hamming', 'kaiser', 'kaiser_bessel_derived', 'gaussian',
+ 'general_cosine', 'general_gaussian', 'general_hamming',
+ 'chebwin', 'cosine', 'hann', 'exponential', 'tukey', 'taylor',
+ 'dpss', 'get_window', 'lanczos']
+
+
+def _len_guards(M):
+ """Handle small or incorrect window lengths"""
+ if int(M) != M or M < 0:
+ raise ValueError('Window length M must be a non-negative integer')
+ return M <= 1
+
+
+def _extend(M, sym):
+ """Extend window by 1 sample if needed for DFT-even symmetry"""
+ if not sym:
+ return M + 1, True
+ else:
+ return M, False
+
+
+def _truncate(w, needed):
+ """Truncate window by 1 sample if needed for DFT-even symmetry"""
+ if needed:
+ return w[:-1]
+ else:
+ return w
+
+
+def _namespace(xp):
+ """A shim for the `device` arg of `np.asarray(x, device=device)` and acos/arccos.
+
+ Will be able to replace with `np_compat if xp is None else xp` when we drop
+ support for numpy 1.x and cupy 13.x
+ """
+ return np_compat if xp is None else array_namespace(xp.empty(0))
+
+
+def _general_cosine_impl(M, a, xp, device, sym=True):
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ fac = xp.linspace(-xp.pi, xp.pi, M, dtype=xp.float64, device=device)
+ w = xp.zeros(M, dtype=xp.float64, device=device)
+ for k in range(a.shape[0]):
+ w += a[k] * xp.cos(k * fac)
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def general_cosine(M, a, sym=True):
+ r"""
+ Generic weighted sum of cosine terms window
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window
+ a : array_like
+ Sequence of weighting coefficients. This uses the convention of being
+ centered on the origin, so these will typically all be positive
+ numbers, not alternating sign.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+
+ Returns
+ -------
+ w : ndarray
+ The array of window values.
+
+ References
+ ----------
+ .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE
+ Transactions on Acoustics, Speech, and Signal Processing, vol. 29,
+ no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`.
+ .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the
+ Discrete Fourier transform (DFT), including a comprehensive list of
+ window functions and some new flat-top windows", February 15, 2002
+ https://holometer.fnal.gov/GH_FFT.pdf
+
+ Examples
+ --------
+ Heinzel describes a flat-top window named "HFT90D" with formula: [2]_
+
+ .. math:: w_j = 1 - 1.942604 \cos(z) + 1.340318 \cos(2z)
+ - 0.440811 \cos(3z) + 0.043097 \cos(4z)
+
+ where
+
+ .. math:: z = \frac{2 \pi j}{N}, j = 0...N - 1
+
+ Since this uses the convention of starting at the origin, to reproduce the
+ window, we need to convert every other coefficient to a positive number:
+
+ >>> HFT90D = [1, 1.942604, 1.340318, 0.440811, 0.043097]
+
+ The paper states that the highest sidelobe is at -90.2 dB. Reproduce
+ Figure 42 by plotting the window and its frequency response, and confirm
+ the sidelobe level in red:
+
+ >>> import numpy as np
+ >>> from scipy.signal.windows import general_cosine
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = general_cosine(1000, HFT90D, sym=False)
+ >>> plt.plot(window)
+ >>> plt.title("HFT90D window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 10000) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = np.abs(fftshift(A / abs(A).max()))
+ >>> response = 20 * np.log10(np.maximum(response, 1e-10))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-50/1000, 50/1000, -140, 0])
+ >>> plt.title("Frequency response of the HFT90D window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+ >>> plt.axhline(-90.2, color='red')
+ >>> plt.show()
+ """
+ xp = array_namespace(a)
+ a = xp.asarray(a)
+ device = xp_device(a)
+ return _general_cosine_impl(M, a, xp, device, sym=sym)
+
+
+@xp_capabilities()
+def boxcar(M, sym=True, *, xp=None, device=None):
+ """Return a boxcar or rectangular window.
+
+ Also known as a rectangular window or Dirichlet window, this is equivalent
+ to no window at all.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ Whether the window is symmetric. (Has no effect for boxcar.)
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1.
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.boxcar(51)
+ >>> plt.plot(window)
+ >>> plt.title("Boxcar window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the boxcar window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ w = xp.ones(M, dtype=xp.float64, device=device)
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def triang(M, sym=True, *, xp=None, device=None):
+ """Return a triangular window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ See Also
+ --------
+ bartlett : A triangular window that touches zero
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.triang(51)
+ >>> plt.plot(window)
+ >>> plt.title("Triangular window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = np.abs(fftshift(A / abs(A).max()))
+ >>> response = 20 * np.log10(np.maximum(response, 1e-10))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the triangular window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ n = xp.arange(1, (M + 1) // 2 + 1, dtype=xp.float64, device=device)
+ if M % 2 == 0:
+ w = (2 * n - 1.0) / M
+ w = xp.concat([w, xp.flip(w)])
+ else:
+ w = 2 * n / (M + 1.0)
+ w = xp.concat([w, xp.flip(w[:-1])])
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def parzen(M, sym=True, *, xp=None, device=None):
+ """Return a Parzen window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ References
+ ----------
+ .. [1] E. Parzen, "Mathematical Considerations in the Estimation of
+ Spectra", Technometrics, Vol. 3, No. 2 (May, 1961), pp. 167-190
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.parzen(51)
+ >>> plt.plot(window)
+ >>> plt.title("Parzen window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Parzen window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ n = xp.arange(-(M - 1) / 2.0, (M - 1) / 2.0 + 0.5, 1.0,
+ dtype=xp.float64, device=device)
+ w = xp.where(abs(n) <= (M - 1) / 4.0,
+ (1 - 6 * (abs(n) / (M / 2.0)) ** 2.0 +
+ 6 * (abs(n) / (M / 2.0)) ** 3.0),
+ 2 * (1 - abs(n) / (M / 2.0)) ** 3.0)
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def bohman(M, sym=True, *, xp=None, device=None):
+ """Return a Bohman window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.bohman(51)
+ >>> plt.plot(window)
+ >>> plt.title("Bohman window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2047) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Bohman window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ fac = abs(xp.linspace(-1, 1, M, dtype=xp.float64, device=device)[1:-1])
+ w = (1 - fac) * xp.cos(xp.pi * fac) + 1.0 / xp.pi * xp.sin(xp.pi * fac)
+ one = xp.zeros(1, dtype=xp.float64, device=device)
+ w = xp.concat([one, w, one])
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def blackman(M, sym=True, *, xp=None, device=None):
+ r"""
+ Return a Blackman window.
+
+ The Blackman window is a taper formed by using the first three terms of
+ a summation of cosines. It was designed to have close to the minimal
+ leakage possible. It is close to optimal, only slightly worse than a
+ Kaiser window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Notes
+ -----
+ The Blackman window is defined as
+
+ .. math:: w(n) = 0.42 - 0.5 \cos(2\pi n/M) + 0.08 \cos(4\pi n/M)
+
+ The "exact Blackman" window was designed to null out the third and fourth
+ sidelobes, but has discontinuities at the boundaries, resulting in a
+ 6 dB/oct fall-off. This window is an approximation of the "exact" window,
+ which does not null the sidelobes as well, but is smooth at the edges,
+ improving the fall-off rate to 18 dB/oct. [3]_
+
+ Most references to the Blackman window come from the signal processing
+ literature, where it is used as one of many windowing functions for
+ smoothing values. It is also known as an apodization (which means
+ "removing the foot", i.e. smoothing discontinuities at the beginning
+ and end of the sampled signal) or tapering function. It is known as a
+ "near optimal" tapering function, almost as good (by some measures)
+ as the Kaiser window.
+
+ References
+ ----------
+ .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
+ spectra, Dover Publications, New York.
+ .. [2] Oppenheim, A.V., and R.W. Schafer. Discrete-Time Signal Processing.
+ Upper Saddle River, NJ: Prentice-Hall, 1999, pp. 468-471.
+ .. [3] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic
+ Analysis with the Discrete Fourier Transform". Proceedings of the
+ IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837`.
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.blackman(51)
+ >>> plt.plot(window)
+ >>> plt.title("Blackman window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = np.abs(fftshift(A / abs(A).max()))
+ >>> response = 20 * np.log10(np.maximum(response, 1e-10))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Blackman window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ # Docstring adapted from NumPy's blackman function
+ xp = _namespace(xp)
+ a = xp.asarray([0.42, 0.50, 0.08], dtype=xp.float64, device=device)
+ device = xp_device(a)
+ return _general_cosine_impl(M, a, xp, device, sym=sym)
+
+
+@xp_capabilities()
+def nuttall(M, sym=True, *, xp=None, device=None):
+ """Return a minimum 4-term Blackman-Harris window according to Nuttall.
+
+ This variation is called "Nuttall4c" by Heinzel. [2]_
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ References
+ ----------
+ .. [1] A. Nuttall, "Some windows with very good sidelobe behavior," IEEE
+ Transactions on Acoustics, Speech, and Signal Processing, vol. 29,
+ no. 1, pp. 84-91, Feb 1981. :doi:`10.1109/TASSP.1981.1163506`.
+ .. [2] Heinzel G. et al., "Spectrum and spectral density estimation by the
+ Discrete Fourier transform (DFT), including a comprehensive list of
+ window functions and some new flat-top windows", February 15, 2002
+ https://holometer.fnal.gov/GH_FFT.pdf
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.nuttall(51)
+ >>> plt.plot(window)
+ >>> plt.title("Nuttall window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Nuttall window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+ a = xp.asarray(
+ [0.3635819, 0.4891775, 0.1365995, 0.0106411], dtype=xp.float64, device=device
+ )
+ device = xp_device(a)
+ return _general_cosine_impl(M, a, xp, device, sym=sym)
+
+
+@xp_capabilities()
+def blackmanharris(M, sym=True, *, xp=None, device=None):
+ """Return a minimum 4-term Blackman-Harris window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.blackmanharris(51)
+ >>> plt.plot(window)
+ >>> plt.title("Blackman-Harris window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Blackman-Harris window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+ a = xp.asarray(
+ [0.35875, 0.48829, 0.14128, 0.01168], dtype=xp.float64, device=device
+ )
+ device = xp_device(a)
+ return _general_cosine_impl(M, a, xp, device, sym=sym)
+
+
+@xp_capabilities()
+def flattop(M, sym=True, *, xp=None, device=None):
+ """Return a flat top window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Notes
+ -----
+ Flat top windows are used for taking accurate measurements of signal
+ amplitude in the frequency domain, with minimal scalloping error from the
+ center of a frequency bin to its edges, compared to others. This is a
+ 5th-order cosine window, with the 5 terms optimized to make the main lobe
+ maximally flat. [1]_
+
+ References
+ ----------
+ .. [1] D'Antona, Gabriele, and A. Ferrero, "Digital Signal Processing for
+ Measurement Systems", Springer Media, 2006, p. 70
+ :doi:`10.1007/0-387-28666-7`.
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.flattop(51)
+ >>> plt.plot(window)
+ >>> plt.title("Flat top window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the flat top window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+ a = xp.asarray(
+ [0.21557895, 0.41663158, 0.277263158, 0.083578947, 0.006947368],
+ dtype=xp.float64, device=device
+ )
+ device = xp_device(a)
+ return _general_cosine_impl(M, a, xp, device, sym=sym)
+
+
+@xp_capabilities()
+def bartlett(M, sym=True, *, xp=None, device=None):
+ r"""
+ Return a Bartlett window.
+
+ The Bartlett window is very similar to a triangular window, except
+ that the end points are at zero. It is often used in signal
+ processing for tapering a signal, without generating too much
+ ripple in the frequency domain.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The triangular window, with the first and last samples equal to zero
+ and the maximum value normalized to 1 (though the value 1 does not
+ appear if `M` is even and `sym` is True).
+
+ See Also
+ --------
+ triang : A triangular window that does not touch zero at the ends
+
+ Notes
+ -----
+ The Bartlett window is defined as
+
+ .. math:: w(n) = \frac{2}{M-1} \left(
+ \frac{M-1}{2} - \left|n - \frac{M-1}{2}\right|
+ \right)
+
+ Most references to the Bartlett window come from the signal
+ processing literature, where it is used as one of many windowing
+ functions for smoothing values. Note that convolution with this
+ window produces linear interpolation. It is also known as an
+ apodization (which means"removing the foot", i.e. smoothing
+ discontinuities at the beginning and end of the sampled signal) or
+ tapering function. The Fourier transform of the Bartlett is the product
+ of two sinc functions.
+ Note the excellent discussion in Kanasewich. [2]_
+
+ References
+ ----------
+ .. [1] M.S. Bartlett, "Periodogram Analysis and Continuous Spectra",
+ Biometrika 37, 1-16, 1950.
+ .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
+ The University of Alberta Press, 1975, pp. 109-110.
+ .. [3] A.V. Oppenheim and R.W. Schafer, "Discrete-Time Signal
+ Processing", Prentice-Hall, 1999, pp. 468-471.
+ .. [4] Wikipedia, "Window function",
+ https://en.wikipedia.org/wiki/Window_function
+ .. [5] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
+ "Numerical Recipes", Cambridge University Press, 1986, page 429.
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.bartlett(51)
+ >>> plt.plot(window)
+ >>> plt.title("Bartlett window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Bartlett window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ # Docstring adapted from NumPy's bartlett function
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ n = xp.arange(0, M, dtype=xp.float64, device=device)
+
+ # cf https://github.com/data-apis/array-api-strict/issues/77
+ w = xp.where(n <= (M - 1) / 2.0,
+ 2.0 * n / (M - 1), 2.0 - 2.0 * n / (M - 1))
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def hann(M, sym=True, *, xp=None, device=None):
+ r"""
+ Return a Hann window.
+
+ The Hann window is a taper formed by using a raised cosine or sine-squared
+ with ends that touch zero.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Notes
+ -----
+ The Hann window is defined as
+
+ .. math:: w(n) = 0.5 - 0.5 \cos\left(\frac{2\pi{n}}{M-1}\right)
+ \qquad 0 \leq n \leq M-1
+
+ The window was named for Julius von Hann, an Austrian meteorologist. It is
+ also known as the Cosine Bell. It is sometimes erroneously referred to as
+ the "Hanning" window, from the use of "hann" as a verb in the original
+ paper and confusion with the very similar Hamming window.
+
+ Most references to the Hann window come from the signal processing
+ literature, where it is used as one of many windowing functions for
+ smoothing values. It is also known as an apodization (which means
+ "removing the foot", i.e. smoothing discontinuities at the beginning
+ and end of the sampled signal) or tapering function.
+
+ References
+ ----------
+ .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
+ spectra, Dover Publications, New York.
+ .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics",
+ The University of Alberta Press, 1975, pp. 106-108.
+ .. [3] Wikipedia, "Window function",
+ https://en.wikipedia.org/wiki/Window_function
+ .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
+ "Numerical Recipes", Cambridge University Press, 1986, page 425.
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.hann(51)
+ >>> plt.plot(window)
+ >>> plt.title("Hann window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = np.abs(fftshift(A / abs(A).max()))
+ >>> response = 20 * np.log10(np.maximum(response, 1e-10))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Hann window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ # Docstring adapted from NumPy's hanning function
+ return general_hamming(M, 0.5, sym, xp=xp, device=device)
+
+
+@xp_capabilities()
+def tukey(M, alpha=0.5, sym=True, *, xp=None, device=None):
+ r"""Return a Tukey window, also known as a tapered cosine window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ alpha : float, optional
+ Shape parameter of the Tukey window, representing the fraction of the
+ window inside the cosine tapered region.
+ If zero, the Tukey window is equivalent to a rectangular window.
+ If one, the Tukey window is equivalent to a Hann window.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ References
+ ----------
+ .. [1] Harris, Fredric J. (Jan 1978). "On the use of Windows for Harmonic
+ Analysis with the Discrete Fourier Transform". Proceedings of the
+ IEEE 66 (1): 51-83. :doi:`10.1109/PROC.1978.10837`
+ .. [2] Wikipedia, "Window function",
+ https://en.wikipedia.org/wiki/Window_function#Tukey_window
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.tukey(51)
+ >>> plt.plot(window)
+ >>> plt.title("Tukey window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+ >>> plt.ylim([0, 1.1])
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Tukey window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+
+ if alpha <= 0:
+ return xp.ones(M, dtype=xp.float64, device=device)
+ elif alpha >= 1.0:
+ return hann(M, sym=sym, xp=xp, device=device)
+
+ M, needs_trunc = _extend(M, sym)
+
+ n = xp.arange(0, M, dtype=xp.float64, device=device)
+ width = int(math.floor(alpha*(M-1)/2.0))
+ n1 = n[0:width+1]
+ n2 = n[width+1:M-width-1]
+ n3 = n[M-width-1:]
+
+ w1 = 0.5 * (1 + xp.cos(xp.pi * (-1 + 2.0*n1/alpha/(M-1))))
+ w2 = xp.ones(n2.shape, device=device)
+ w3 = 0.5 * (1 + xp.cos(xp.pi * (-2.0/alpha + 1 + 2.0*n3/alpha/(M-1))))
+
+ w = xp.concat((w1, w2, w3))
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def barthann(M, sym=True, *, xp=None, device=None):
+ """Return a modified Bartlett-Hann window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.barthann(51)
+ >>> plt.plot(window)
+ >>> plt.title("Bartlett-Hann window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Bartlett-Hann window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ n = xp.arange(0, M, dtype=xp.float64, device=device)
+ fac = abs(n / (M - 1.0) - 0.5)
+ w = 0.62 - 0.48 * fac + 0.38 * xp.cos(2 * xp.pi * fac)
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def general_hamming(M, alpha, sym=True, *, xp=None, device=None):
+ r"""Return a generalized Hamming window.
+
+ The generalized Hamming window is constructed by multiplying a rectangular
+ window by one period of a cosine function [1]_.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ alpha : float
+ The window coefficient, :math:`\alpha`
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ See Also
+ --------
+ hamming, hann
+
+ Notes
+ -----
+ The generalized Hamming window is defined as
+
+ .. math:: w(n) = \alpha - \left(1 - \alpha\right)
+ \cos\left(\frac{2\pi{n}}{M-1}\right) \qquad 0 \leq n \leq M-1
+
+ Both the common Hamming window and Hann window are special cases of the
+ generalized Hamming window with :math:`\alpha` = 0.54 and :math:`\alpha` =
+ 0.5, respectively [2]_.
+
+ References
+ ----------
+ .. [1] DSPRelated, "Generalized Hamming Window Family",
+ https://www.dsprelated.com/freebooks/sasp/Generalized_Hamming_Window_Family.html
+ .. [2] Wikipedia, "Window function",
+ https://en.wikipedia.org/wiki/Window_function
+ .. [3] Riccardo Piantanida ESA, "Sentinel-1 Level 1 Detailed Algorithm
+ Definition",
+ https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Level-1-Detailed-Algorithm-Definition
+ .. [4] Matthieu Bourbigot ESA, "Sentinel-1 Product Definition",
+ https://sentinel.esa.int/documents/247904/1877131/Sentinel-1-Product-Definition
+
+ Examples
+ --------
+ The Sentinel-1A/B Instrument Processing Facility uses generalized Hamming
+ windows in the processing of spaceborne Synthetic Aperture Radar (SAR)
+ data [3]_. The facility uses various values for the :math:`\alpha`
+ parameter based on operating mode of the SAR instrument. Some common
+ :math:`\alpha` values include 0.75, 0.7 and 0.52 [4]_. As an example, we
+ plot these different windows.
+
+ >>> import numpy as np
+ >>> from scipy.signal.windows import general_hamming
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> fig1, spatial_plot = plt.subplots()
+ >>> spatial_plot.set_title("Generalized Hamming Windows")
+ >>> spatial_plot.set_ylabel("Amplitude")
+ >>> spatial_plot.set_xlabel("Sample")
+
+ >>> fig2, freq_plot = plt.subplots()
+ >>> freq_plot.set_title("Frequency Responses")
+ >>> freq_plot.set_ylabel("Normalized magnitude [dB]")
+ >>> freq_plot.set_xlabel("Normalized frequency [cycles per sample]")
+
+ >>> for alpha in [0.75, 0.7, 0.52]:
+ ... window = general_hamming(41, alpha)
+ ... spatial_plot.plot(window, label="{:.2f}".format(alpha))
+ ... A = fft(window, 2048) / (len(window)/2.0)
+ ... freq = np.linspace(-0.5, 0.5, len(A))
+ ... response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ ... freq_plot.plot(freq, response, label="{:.2f}".format(alpha))
+ >>> freq_plot.legend(loc="upper right")
+ >>> spatial_plot.legend(loc="upper right")
+
+ """
+ xp = _namespace(xp)
+ a = xp.asarray([alpha, 1. - alpha], dtype=xp.float64, device=device)
+ device = xp_device(a)
+ return _general_cosine_impl(M, a, xp, device, sym=sym)
+
+
+@xp_capabilities()
+def hamming(M, sym=True, *, xp=None, device=None):
+ r"""Return a Hamming window.
+
+ The Hamming window is a taper formed by using a raised cosine with
+ non-zero endpoints, optimized to minimize the nearest side lobe.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Notes
+ -----
+ The Hamming window is defined as
+
+ .. math:: w(n) = 0.54 - 0.46 \cos\left(\frac{2\pi{n}}{M-1}\right)
+ \qquad 0 \leq n \leq M-1
+
+ The Hamming was named for R. W. Hamming, an associate of J. W. Tukey and
+ is described in Blackman and Tukey. It was recommended for smoothing the
+ truncated autocovariance function in the time domain.
+ Most references to the Hamming window come from the signal processing
+ literature, where it is used as one of many windowing functions for
+ smoothing values. It is also known as an apodization (which means
+ "removing the foot", i.e. smoothing discontinuities at the beginning
+ and end of the sampled signal) or tapering function.
+
+ References
+ ----------
+ .. [1] Blackman, R.B. and Tukey, J.W., (1958) The measurement of power
+ spectra, Dover Publications, New York.
+ .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
+ University of Alberta Press, 1975, pp. 109-110.
+ .. [3] Wikipedia, "Window function",
+ https://en.wikipedia.org/wiki/Window_function
+ .. [4] W.H. Press, B.P. Flannery, S.A. Teukolsky, and W.T. Vetterling,
+ "Numerical Recipes", Cambridge University Press, 1986, page 425.
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.hamming(51)
+ >>> plt.plot(window)
+ >>> plt.title("Hamming window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Hamming window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ # Docstring adapted from NumPy's hamming function
+ return general_hamming(M, 0.54, sym, xp=xp, device=device)
+
+
+@xp_capabilities()
+def kaiser(M, beta, sym=True, *, xp=None, device=None):
+ r"""Return a Kaiser window.
+
+ The Kaiser window is a taper formed by using a Bessel function.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ beta : float
+ Shape parameter, determines trade-off between main-lobe width and
+ side lobe level. As beta gets large, the window narrows.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Notes
+ -----
+ The Kaiser window is defined as
+
+ .. math:: w(n) = I_0\left( \beta \sqrt{1-\frac{4n^2}{(M-1)^2}}
+ \right)/I_0(\beta)
+
+ with
+
+ .. math:: \quad -\frac{M-1}{2} \leq n \leq \frac{M-1}{2},
+
+ where :math:`I_0` is the modified zeroth-order Bessel function.
+
+ The Kaiser was named for Jim Kaiser, who discovered a simple approximation
+ to the DPSS window based on Bessel functions.
+ The Kaiser window is a very good approximation to the discrete prolate
+ spheroidal sequence, or Slepian window, which is the transform which
+ maximizes the energy in the main lobe of the window relative to total
+ energy.
+
+ The Kaiser can approximate other windows by varying the beta parameter.
+ (Some literature uses alpha = beta/pi.) [4]_
+
+ ==== =======================
+ beta Window shape
+ ==== =======================
+ 0 Rectangular
+ 5 Similar to a Hamming
+ 6 Similar to a Hann
+ 8.6 Similar to a Blackman
+ ==== =======================
+
+ A beta value of 14 is probably a good starting point. Note that as beta
+ gets large, the window narrows, and so the number of samples needs to be
+ large enough to sample the increasingly narrow spike, otherwise NaNs will
+ be returned.
+
+ Most references to the Kaiser window come from the signal processing
+ literature, where it is used as one of many windowing functions for
+ smoothing values. It is also known as an apodization (which means
+ "removing the foot", i.e. smoothing discontinuities at the beginning
+ and end of the sampled signal) or tapering function.
+
+ References
+ ----------
+ .. [1] J. F. Kaiser, "Digital Filters" - Ch 7 in "Systems analysis by
+ digital computer", Editors: F.F. Kuo and J.F. Kaiser, p 218-285.
+ John Wiley and Sons, New York, (1966).
+ .. [2] E.R. Kanasewich, "Time Sequence Analysis in Geophysics", The
+ University of Alberta Press, 1975, pp. 177-178.
+ .. [3] Wikipedia, "Window function",
+ https://en.wikipedia.org/wiki/Window_function
+ .. [4] F. J. Harris, "On the use of windows for harmonic analysis with the
+ discrete Fourier transform," Proceedings of the IEEE, vol. 66,
+ no. 1, pp. 51-83, Jan. 1978. :doi:`10.1109/PROC.1978.10837`.
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.kaiser(51, beta=14)
+ >>> plt.plot(window)
+ >>> plt.title(r"Kaiser window ($\beta$=14)")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title(r"Frequency response of the Kaiser window ($\beta$=14)")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+
+ # Docstring adapted from NumPy's kaiser function
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ n = xp.arange(0, M, dtype=xp.float64, device=device)
+ alpha = (M - 1) / 2.0
+ w = (special.i0(beta * xp.sqrt(1 - ((n - alpha) / alpha) ** 2.0)) /
+ special.i0(xp.asarray(beta, dtype=xp.float64)))
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def kaiser_bessel_derived(M, beta, *, sym=True, xp=None, device=None):
+ """Return a Kaiser-Bessel derived window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ Note that this window is only defined for an even
+ number of points.
+ beta : float
+ Kaiser window shape parameter.
+ sym : bool, optional
+ This parameter only exists to comply with the interface offered by
+ the other window functions and to be callable by `get_window`.
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, normalized to fulfil the Princen-Bradley condition.
+
+ See Also
+ --------
+ kaiser
+
+ Notes
+ -----
+ It is designed to be suitable for use with the modified discrete cosine
+ transform (MDCT) and is mainly used in audio signal processing and
+ audio coding.
+
+ .. versionadded:: 1.9.0
+
+ References
+ ----------
+ .. [1] Bosi, Marina, and Richard E. Goldberg. Introduction to Digital
+ Audio Coding and Standards. Dordrecht: Kluwer, 2003.
+ .. [2] Wikipedia, "Kaiser window",
+ https://en.wikipedia.org/wiki/Kaiser_window
+
+ Examples
+ --------
+ Plot the Kaiser-Bessel derived window based on the wikipedia
+ reference [2]_:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> import matplotlib.pyplot as plt
+ >>> fig, ax = plt.subplots()
+ >>> N = 50
+ >>> for alpha in [0.64, 2.55, 7.64, 31.83]:
+ ... ax.plot(signal.windows.kaiser_bessel_derived(2*N, np.pi*alpha),
+ ... label=f"{alpha=}")
+ >>> ax.grid(True)
+ >>> ax.set_title("Kaiser-Bessel derived window")
+ >>> ax.set_ylabel("Amplitude")
+ >>> ax.set_xlabel("Sample")
+ >>> ax.set_xticks([0, N, 2*N-1])
+ >>> ax.set_xticklabels(["0", "N", "2N+1"]) # doctest: +SKIP
+ >>> ax.set_yticks([0.0, 0.2, 0.4, 0.6, 0.707, 0.8, 1.0])
+ >>> fig.legend(loc="center")
+ >>> fig.tight_layout()
+ >>> fig.show()
+ """
+ xp = _namespace(xp)
+
+ if not sym:
+ raise ValueError(
+ "Kaiser-Bessel Derived windows are only defined for symmetric "
+ "shapes"
+ )
+ elif M < 1:
+ return xp.asarray([])
+ elif M % 2:
+ raise ValueError(
+ "Kaiser-Bessel Derived windows are only defined for even number "
+ "of points"
+ )
+
+ kaiser_window = kaiser(M // 2 + 1, beta, xp=xp, device=device)
+ csum = xp.cumulative_sum(kaiser_window)
+ half_window = xp.sqrt(csum[:-1] / csum[-1])
+ w = xp.concat((half_window, xp.flip(half_window)), axis=0)
+ return xp.asarray(w, device=device)
+
+
+@xp_capabilities()
+def gaussian(M, std, sym=True, *, xp=None, device=None):
+ r"""Return a Gaussian window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ std : float
+ The standard deviation, sigma.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Notes
+ -----
+ The Gaussian window is defined as
+
+ .. math:: w(n) = e^{ -\frac{1}{2}\left(\frac{n}{\sigma}\right)^2 }
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.gaussian(51, std=7)
+ >>> plt.plot(window)
+ >>> plt.title(r"Gaussian window ($\sigma$=7)")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title(r"Frequency response of the Gaussian window ($\sigma$=7)")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ n = xp.arange(0, M, dtype=xp.float64, device=device) - (M - 1.0) / 2.0
+ sig2 = 2 * std * std
+ w = xp.exp(-n ** 2 / sig2)
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def general_gaussian(M, p, sig, sym=True, *, xp=None, device=None):
+ r"""Return a window with a generalized Gaussian shape.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ p : float
+ Shape parameter. p = 1 is identical to `gaussian`, p = 0.5 is
+ the same shape as the Laplace distribution.
+ sig : float
+ The standard deviation, sigma.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Notes
+ -----
+ The generalized Gaussian window is defined as
+
+ .. math:: w(n) = e^{ -\frac{1}{2}\left|\frac{n}{\sigma}\right|^{2p} }
+
+ the half-power point is at
+
+ .. math:: (2 \log(2))^{1/(2 p)} \sigma
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.general_gaussian(51, p=1.5, sig=7)
+ >>> plt.plot(window)
+ >>> plt.title(r"Generalized Gaussian window (p=1.5, $\sigma$=7)")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title(r"Freq. resp. of the gen. Gaussian "
+ ... r"window (p=1.5, $\sigma$=7)")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ n = xp.arange(0, M, dtype=xp.float64, device=device) - (M - 1.0) / 2.0
+ w = xp.exp(-0.5 * abs(n / sig) ** (2 * p))
+
+ return _truncate(w, needs_trunc)
+
+
+# `chebwin` contributed by Kumar Appaiah.
+@xp_capabilities(skip_backends=(("jax.numpy", "item assignment"),
+ ("dask.array", "data-dependent output shapes")))
+def chebwin(M, at, sym=True, *, xp=None, device=None):
+ r"""Return a Dolph-Chebyshev window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ at : float
+ Attenuation (in dB).
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value always normalized to 1
+
+ Notes
+ -----
+ This window optimizes for the narrowest main lobe width for a given order
+ `M` and sidelobe equiripple attenuation `at`, using Chebyshev
+ polynomials. It was originally developed by Dolph to optimize the
+ directionality of radio antenna arrays.
+
+ Unlike most windows, the Dolph-Chebyshev is defined in terms of its
+ frequency response:
+
+ .. math:: W(k) = \frac
+ {\cos\{M \cos^{-1}[\beta \cos(\frac{\pi k}{M})]\}}
+ {\cosh[M \cosh^{-1}(\beta)]}
+
+ where
+
+ .. math:: \beta = \cosh \left [\frac{1}{M}
+ \cosh^{-1}(10^\frac{A}{20}) \right ]
+
+ and 0 <= abs(k) <= M-1. A is the attenuation in decibels (`at`).
+
+ The time domain window is then generated using the IFFT, so
+ power-of-two `M` are the fastest to generate, and prime number `M` are
+ the slowest.
+
+ The equiripple condition in the frequency domain creates impulses in the
+ time domain, which appear at the ends of the window.
+
+ References
+ ----------
+ .. [1] C. Dolph, "A current distribution for broadside arrays which
+ optimizes the relationship between beam width and side-lobe level",
+ Proceedings of the IEEE, Vol. 34, Issue 6
+ .. [2] Peter Lynch, "The Dolph-Chebyshev Window: A Simple Optimal Filter",
+ American Meteorological Society (April 1997)
+ http://mathsci.ucd.ie/~plynch/Publications/Dolph.pdf
+ .. [3] F. J. Harris, "On the use of windows for harmonic analysis with the
+ discrete Fourier transforms", Proceedings of the IEEE, Vol. 66,
+ No. 1, January 1978
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.chebwin(51, at=100)
+ >>> plt.plot(window)
+ >>> plt.title("Dolph-Chebyshev window (100 dB)")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Dolph-Chebyshev window (100 dB)")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """
+ xp = _namespace(xp)
+
+ if abs(at) < 45:
+ warnings.warn("This window is not suitable for spectral analysis "
+ "for attenuation values lower than about 45dB because "
+ "the equivalent noise bandwidth of a Chebyshev window "
+ "does not grow monotonically with increasing sidelobe "
+ "attenuation when the attenuation is smaller than "
+ "about 45 dB.",
+ stacklevel=2)
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ # compute the parameter beta
+ order = M - 1.0
+ _val = xp.asarray(10 ** (abs(at) / 20.), dtype=xp.float64, device=device)
+ beta = xp.cosh(1.0 / order * xp.acosh(_val))
+ k = xp.arange(M, dtype=xp.float64, device=device)
+ x = beta * xp.cos(xp.pi * k / M)
+ # Find the window's DFT coefficients
+ # Use analytic definition of Chebyshev polynomial instead of expansion
+ # from scipy.special. Using the expansion in scipy.special leads to errors.
+ p = xp.zeros_like(x)
+ p[x > 1] = xp.cosh(order * xp.acosh(x[x > 1]))
+ p[x < -1] = (2 * (M % 2) - 1) * xp.cosh(order * xp.acosh(-x[x < -1]))
+ p[abs(x) <= 1] = xp.cos(order * xp.acos(x[abs(x) <= 1]))
+
+ # Appropriate IDFT and filling up
+ # depending on even/odd M
+ if M % 2:
+ w = xp.real(sp_fft.fft(p))
+ n = (M + 1) // 2
+ w = w[:n]
+ w = xp.concat((xp.flip(w[1:n]), w))
+ else:
+ p = p * xp.exp(1j * xp.pi / M * xp.arange(M, dtype=xp.float64, device=device))
+ w = xp.real(sp_fft.fft(p))
+ n = M // 2 + 1
+ w = xp.concat((xp.flip(w[1:n]), w[1:n]))
+ w = w / xp.max(w)
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def cosine(M, sym=True, *, xp=None, device=None):
+ """Return a window with a simple cosine shape.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Notes
+ -----
+
+ .. versionadded:: 0.13.0
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.cosine(51)
+ >>> plt.plot(window)
+ >>> plt.title("Cosine window")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2047) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the cosine window")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+ >>> plt.show()
+
+ """
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ w = xp.sin(xp.pi / M * (xp.arange(M, dtype=xp.float64, device=device) + .5))
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities()
+def exponential(M, center=None, tau=1., sym=True, *, xp=None, device=None):
+ r"""Return an exponential (or Poisson) window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ center : float, optional
+ Parameter defining the center location of the window function.
+ The default value if not given is ``center = (M-1) / 2``. This
+ parameter must take its default value for symmetric windows.
+ tau : float, optional
+ Parameter defining the decay. For ``center = 0`` use
+ ``tau = -(M-1) / ln(x)`` if ``x`` is the fraction of the window
+ remaining at the end.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Notes
+ -----
+ The Exponential window is defined as
+
+ .. math:: w(n) = e^{-|n-center| / \tau}
+
+ References
+ ----------
+ .. [1] S. Gade and H. Herlufsen, "Windows to FFT analysis (Part I)",
+ Technical Review 3, Bruel & Kjaer, 1987.
+
+ Examples
+ --------
+ Plot the symmetric window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> M = 51
+ >>> tau = 3.0
+ >>> window = signal.windows.exponential(M, tau=tau)
+ >>> plt.plot(window)
+ >>> plt.title("Exponential Window (tau=3.0)")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -35, 0])
+ >>> plt.title("Frequency response of the Exponential window (tau=3.0)")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ This function can also generate non-symmetric windows:
+
+ >>> tau2 = -(M-1) / np.log(0.01)
+ >>> window2 = signal.windows.exponential(M, 0, tau2, False)
+ >>> plt.figure()
+ >>> plt.plot(window2)
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+ """
+ xp = _namespace(xp)
+
+ if sym and center is not None:
+ raise ValueError("If sym==True, center must be None.")
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ if center is None:
+ center = (M-1) / 2
+
+ n = xp.arange(0, M, dtype=xp.float64, device=device)
+ w = xp.exp(-abs(n-center) / tau)
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities(skip_backends=[("jax.numpy", "item assignment")])
+def taylor(M, nbar=4, sll=30, norm=True, sym=True, *, xp=None, device=None):
+ """
+ Return a Taylor window.
+
+ The Taylor window taper function approximates the Dolph-Chebyshev window's
+ constant sidelobe level for a parameterized number of near-in sidelobes,
+ but then allows a taper beyond [2]_.
+
+ The SAR (synthetic aperture radar) community commonly uses Taylor
+ weighting for image formation processing because it provides strong,
+ selectable sidelobe suppression with minimum broadening of the
+ mainlobe [1]_.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ nbar : int, optional
+ Number of nearly constant level sidelobes adjacent to the mainlobe.
+ sll : float, optional
+ Desired suppression of sidelobe level in decibels (dB) relative to the
+ DC gain of the mainlobe. This should be a positive number.
+ norm : bool, optional
+ When True (default), divides the window by the largest (middle) value
+ for odd-length windows or the value that would occur between the two
+ repeated middle values for even-length windows such that all values
+ are less than or equal to 1. When False the DC gain will remain at 1
+ (0 dB) and the sidelobes will be `sll` dB down.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ out : array
+ The window. When `norm` is True (default), the maximum value is
+ normalized to 1 (though the value 1 does not appear if `M` is
+ even and `sym` is True).
+
+ See Also
+ --------
+ chebwin, kaiser, bartlett, blackman, hamming, hann
+
+ References
+ ----------
+ .. [1] W. Carrara, R. Goodman, and R. Majewski, "Spotlight Synthetic
+ Aperture Radar: Signal Processing Algorithms" Pages 512-513,
+ July 1995.
+ .. [2] Armin Doerry, "Catalog of Window Taper Functions for
+ Sidelobe Control", 2017.
+ https://www.researchgate.net/profile/Armin_Doerry/publication/316281181_Catalog_of_Window_Taper_Functions_for_Sidelobe_Control/links/58f92cb2a6fdccb121c9d54d/Catalog-of-Window-Taper-Functions-for-Sidelobe-Control.pdf
+
+ Examples
+ --------
+ Plot the window and its frequency response:
+
+ >>> import numpy as np
+ >>> from scipy import signal
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+
+ >>> window = signal.windows.taylor(51, nbar=20, sll=100, norm=False)
+ >>> plt.plot(window)
+ >>> plt.title("Taylor window (100 dB)")
+ >>> plt.ylabel("Amplitude")
+ >>> plt.xlabel("Sample")
+
+ >>> plt.figure()
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> plt.plot(freq, response)
+ >>> plt.axis([-0.5, 0.5, -120, 0])
+ >>> plt.title("Frequency response of the Taylor window (100 dB)")
+ >>> plt.ylabel("Normalized magnitude [dB]")
+ >>> plt.xlabel("Normalized frequency [cycles per sample]")
+
+ """ # noqa: E501
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ # Original text uses a negative sidelobe level parameter and then negates
+ # it in the calculation of B. To keep consistent with other methods we
+ # assume the sidelobe level parameter to be positive.
+ B = xp.asarray(10**(sll / 20), device=device)
+ A = xp.acosh(B) / xp.pi
+ s2 = nbar**2 / (A**2 + (nbar - 0.5)**2)
+ ma = xp.arange(1, nbar, dtype=xp.float64, device=device)
+
+ Fm = xp.empty(nbar - 1, dtype=xp.float64, device=device)
+ signs = xp.empty_like(ma)
+ signs[::2] = 1
+ signs[1::2] = -1
+ m2 = ma*ma
+ for mi, m in enumerate(ma):
+ numer = signs[mi] * xp.prod(1 - m2[mi]/s2/(A**2 + (ma - 0.5)**2))
+ denom = 2 * xp.prod(1 - m2[mi]/m2[:mi]) * xp.prod(1 - m2[mi]/m2[mi+1:])
+ Fm[mi] = numer / denom
+
+ def W(n):
+ return 1 + 2*xp.matmul(Fm, xp.cos(
+ 2*xp.pi*ma[:, xp.newaxis]*(n-M/2.+0.5)/M))
+
+ w = W(xp.arange(M, dtype=xp.float64, device=device))
+
+ # normalize (Note that this is not described in the original text [1])
+ if norm:
+ scale = 1.0 / W((M - 1) / 2)
+ w *= scale
+
+ return _truncate(w, needs_trunc)
+
+
+@xp_capabilities(np_only=True, reason='banded linear algebra is numpy-only')
+def dpss(M, NW, Kmax=None, sym=True, norm=None, return_ratios=False,
+ *, xp=None, device=None):
+ """
+ Compute the Discrete Prolate Spheroidal Sequences (DPSS).
+
+ DPSS (or Slepian sequences) are often used in multitaper power spectral
+ density estimation (see [1]_). The first window in the sequence can be
+ used to maximize the energy concentration in the main lobe, and is also
+ called the Slepian window.
+
+ Parameters
+ ----------
+ M : int
+ Window length.
+ NW : float
+ Standardized half bandwidth corresponding to ``2*NW = BW/f0 = BW*M*dt``
+ where ``dt`` is taken as 1.
+ Kmax : int | None, optional
+ Number of DPSS windows to return (orders ``0`` through ``Kmax-1``).
+ If None (default), return only a single window of shape ``(M,)``
+ instead of an array of windows of shape ``(Kmax, M)``.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ norm : {2, 'approximate', 'subsample'} | None, optional
+ If 'approximate' or 'subsample', then the windows are normalized by the
+ maximum, and a correction scale-factor for even-length windows
+ is applied either using ``M**2/(M**2+NW)`` ("approximate") or
+ a FFT-based subsample shift ("subsample"), see Notes for details.
+ If None, then "approximate" is used when ``Kmax=None`` and 2 otherwise
+ (which uses the l2 norm).
+ return_ratios : bool, optional
+ If True, also return the concentration ratios in addition to the
+ windows.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ v : ndarray, shape (Kmax, M) or (M,)
+ The DPSS windows. Will be 1D if `Kmax` is None.
+ r : ndarray, shape (Kmax,) or float, optional
+ The concentration ratios for the windows. Only returned if
+ `return_ratios` evaluates to True. Will be 0D if `Kmax` is None.
+
+ Notes
+ -----
+ This computation uses the tridiagonal eigenvector formulation given
+ in [2]_.
+
+ The default normalization for ``Kmax=None``, i.e. window-generation mode,
+ simply using the l-infinity norm would create a window with two unity
+ values, which creates slight normalization differences between even and odd
+ orders. The approximate correction of ``M**2/float(M**2+NW)`` for even
+ sample numbers is used to counteract this effect (see Examples below).
+
+ For very long signals (e.g., 1e6 elements), it can be useful to compute
+ windows orders of magnitude shorter and use interpolation (e.g.,
+ `scipy.interpolate.interp1d`) to obtain tapers of length `M`,
+ but this in general will not preserve orthogonality between the tapers.
+
+ .. versionadded:: 1.1
+
+ References
+ ----------
+ .. [1] Percival DB, Walden WT. Spectral Analysis for Physical Applications:
+ Multitaper and Conventional Univariate Techniques.
+ Cambridge University Press; 1993.
+ .. [2] Slepian, D. Prolate spheroidal wave functions, Fourier analysis, and
+ uncertainty V: The discrete case. Bell System Technical Journal,
+ Volume 57 (1978), 1371430.
+ .. [3] Kaiser, JF, Schafer RW. On the Use of the I0-Sinh Window for
+ Spectrum Analysis. IEEE Transactions on Acoustics, Speech and
+ Signal Processing. ASSP-28 (1): 105-107; 1980.
+
+ Examples
+ --------
+ We can compare the window to `kaiser`, which was invented as an alternative
+ that was easier to calculate [3]_ (example adapted from
+ `here `_):
+
+ >>> import numpy as np
+ >>> import matplotlib.pyplot as plt
+ >>> from scipy.signal import windows, freqz
+ >>> M = 51
+ >>> fig, axes = plt.subplots(3, 2, figsize=(5, 7))
+ >>> for ai, alpha in enumerate((1, 3, 5)):
+ ... win_dpss = windows.dpss(M, alpha)
+ ... beta = alpha*np.pi
+ ... win_kaiser = windows.kaiser(M, beta)
+ ... for win, c in ((win_dpss, 'k'), (win_kaiser, 'r')):
+ ... win /= win.sum()
+ ... axes[ai, 0].plot(win, color=c, lw=1.)
+ ... axes[ai, 0].set(xlim=[0, M-1], title=rf'$\\alpha$ = {alpha}',
+ ... ylabel='Amplitude')
+ ... w, h = freqz(win)
+ ... axes[ai, 1].plot(w, 20 * np.log10(np.abs(h)), color=c, lw=1.)
+ ... axes[ai, 1].set(xlim=[0, np.pi],
+ ... title=rf'$\\beta$ = {beta:0.2f}',
+ ... ylabel='Magnitude (dB)')
+ >>> for ax in axes.ravel():
+ ... ax.grid(True)
+ >>> axes[2, 1].legend(['DPSS', 'Kaiser'])
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ And here are examples of the first four windows, along with their
+ concentration ratios:
+
+ >>> M = 512
+ >>> NW = 2.5
+ >>> win, eigvals = windows.dpss(M, NW, 4, return_ratios=True)
+ >>> fig, ax = plt.subplots(1)
+ >>> ax.plot(win.T, linewidth=1.)
+ >>> ax.set(xlim=[0, M-1], ylim=[-0.1, 0.1], xlabel='Samples',
+ ... title=f'DPSS, {M:d}, {NW:0.1f}')
+ >>> ax.legend([f'win[{ii}] ({ratio:0.4f})'
+ ... for ii, ratio in enumerate(eigvals)])
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ Using a standard :math:`l_{\\infty}` norm would produce two unity values
+ for even `M`, but only one unity value for odd `M`. This produces uneven
+ window power that can be counteracted by the approximate correction
+ ``M**2/float(M**2+NW)``, which can be selected by using
+ ``norm='approximate'`` (which is the same as ``norm=None`` when
+ ``Kmax=None``, as is the case here). Alternatively, the slower
+ ``norm='subsample'`` can be used, which uses subsample shifting in the
+ frequency domain (FFT) to compute the correction:
+
+ >>> Ms = np.arange(1, 41)
+ >>> factors = (50, 20, 10, 5, 2.0001)
+ >>> energy = np.empty((3, len(Ms), len(factors)))
+ >>> for mi, M in enumerate(Ms):
+ ... for fi, factor in enumerate(factors):
+ ... NW = M / float(factor)
+ ... # Corrected using empirical approximation (default)
+ ... win = windows.dpss(M, NW)
+ ... energy[0, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
+ ... # Corrected using subsample shifting
+ ... win = windows.dpss(M, NW, norm='subsample')
+ ... energy[1, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
+ ... # Uncorrected (using l-infinity norm)
+ ... win /= win.max()
+ ... energy[2, mi, fi] = np.sum(win ** 2) / np.sqrt(M)
+ >>> fig, ax = plt.subplots(1)
+ >>> hs = ax.plot(Ms, energy[2], '-o', markersize=4,
+ ... markeredgecolor='none')
+ >>> leg = [hs[-1]]
+ >>> for hi, hh in enumerate(hs):
+ ... h1 = ax.plot(Ms, energy[0, :, hi], '-o', markersize=4,
+ ... color=hh.get_color(), markeredgecolor='none',
+ ... alpha=0.66)
+ ... h2 = ax.plot(Ms, energy[1, :, hi], '-o', markersize=4,
+ ... color=hh.get_color(), markeredgecolor='none',
+ ... alpha=0.33)
+ ... if hi == len(hs) - 1:
+ ... leg.insert(0, h1[0])
+ ... leg.insert(0, h2[0])
+ >>> ax.set(xlabel='M (samples)', ylabel=r'Power / $\\sqrt{M}$')
+ >>> ax.legend(leg, ['Uncorrected', r'Corrected: $\\frac{M^2}{M^2+NW}$',
+ ... 'Corrected (subsample)'])
+ >>> fig.tight_layout()
+
+ """
+ xp = _namespace(xp)
+
+ if norm is None:
+ norm = 'approximate' if Kmax is None else 2
+ known_norms = (2, 'approximate', 'subsample')
+ if norm not in known_norms:
+ raise ValueError(f'norm must be one of {known_norms}, got {norm}')
+ if Kmax is None:
+ singleton = True
+ Kmax = 1
+ else:
+ singleton = False
+ if _len_guards(M):
+ if not return_ratios:
+ return xp.ones(M, dtype=xp.float64)
+ elif singleton:
+ return xp.ones(M, dtype=xp.float64), 1.
+ else:
+ return xp.ones(M, dtype=xp.float64), xp.ones(1, dtype=xp.float64)
+ Kmax = operator.index(Kmax)
+ if not 0 < Kmax <= M:
+ raise ValueError('Kmax must be greater than 0 and less than M')
+ if NW >= M/2.:
+ raise ValueError('NW must be less than M/2.')
+ if NW <= 0:
+ raise ValueError('NW must be positive')
+ M, needs_trunc = _extend(M, sym)
+ W = float(NW) / M
+ nidx = xp.arange(M, dtype=xp.float64, device=device)
+
+ # Here we want to set up an optimization problem to find a sequence
+ # whose energy is maximally concentrated within band [-W,W].
+ # Thus, the measure lambda(T,W) is the ratio between the energy within
+ # that band, and the total energy. This leads to the eigen-system
+ # (A - (l1)I)v = 0, where the eigenvector corresponding to the largest
+ # eigenvalue is the sequence with maximally concentrated energy. The
+ # collection of eigenvectors of this system are called Slepian
+ # sequences, or discrete prolate spheroidal sequences (DPSS). Only the
+ # first K, K = 2NW/dt orders of DPSS will exhibit good spectral
+ # concentration
+ # [see https://en.wikipedia.org/wiki/Spectral_concentration_problem]
+
+ # Here we set up an alternative symmetric tri-diagonal eigenvalue
+ # problem such that
+ # (B - (l2)I)v = 0, and v are our DPSS (but eigenvalues l2 != l1)
+ # the main diagonal = ([M-1-2*t]/2)**2 cos(2PIW), t=[0,1,2,...,M-1]
+ # and the first off-diagonal = t(M-t)/2, t=[1,2,...,M-1]
+ # [see Percival and Walden, 1993]
+ d = ((M - 1 - 2 * nidx) / 2.) ** 2 * xp.cos(xp.asarray(2 * xp.pi * W))
+ e = nidx[1:] * (M - nidx[1:]) / 2.
+
+ # only calculate the highest Kmax eigenvalues
+ w, windows = linalg.eigh_tridiagonal(
+ d, e, select='i', select_range=(M - Kmax, M - 1))
+ w = w[::-1]
+ windows = windows[:, ::-1].T
+
+ # By convention (Percival and Walden, 1993 pg 379)
+ # * symmetric tapers (k=0,2,4,...) should have a positive average.
+ fix_even = (windows[::2, ...].sum(axis=1) < 0)
+ for i, f in enumerate(fix_even):
+ if f:
+ windows[2 * i] *= -1
+ # * antisymmetric tapers should begin with a positive lobe
+ # (this depends on the definition of "lobe", here we'll take the first
+ # point above the numerical noise, which should be good enough for
+ # sufficiently smooth functions, and more robust than relying on an
+ # algorithm that uses max(abs(w)), which is susceptible to numerical
+ # noise problems)
+ thresh = max(1e-7, 1. / M)
+ for i, w in enumerate(windows[1::2, ...]):
+ if w[w * w > thresh][0] < 0:
+ windows[2 * i + 1] *= -1
+
+ # Now find the eigenvalues of the original spectral concentration problem
+ # Use the autocorr sequence technique from Percival and Walden, 1993 pg 390
+ if return_ratios:
+ dpss_rxx = _fftautocorr(xp.asarray(windows))
+ r = 4 * W * xpx.sinc(xp.asarray(2 * W * nidx), xp=xp)
+ r[0] = 2 * W
+ ratios = xp.matmul(dpss_rxx, r)
+ if singleton:
+ ratios = ratios[0]
+ ratios = xp.asarray(ratios, device=device)
+ # Deal with sym and Kmax=None
+ if norm != 2:
+ windows /= windows.max()
+ if M % 2 == 0:
+ if norm == 'approximate':
+ correction = M**2 / float(M**2 + NW)
+ else:
+ s = sp_fft.rfft(windows[0])
+ shift = -(1 - 1./M) * xp.arange(1, M//2 + 1, dtype=xp.float64)
+ s[1:] *= 2 * xp.exp(-1j * xp.pi * shift)
+ correction = M / s.real.sum()
+ windows *= correction
+ # else we're already l2 normed, so do nothing
+ if needs_trunc:
+ windows = windows[:, :-1]
+ if singleton:
+ windows = windows[0]
+ windows = xp.asarray(windows, device=device)
+ return (windows, ratios) if return_ratios else windows
+
+
+@xp_capabilities()
+def lanczos(M, *, sym=True, xp=None, device=None):
+ r"""Return a Lanczos window also known as a sinc window.
+
+ Parameters
+ ----------
+ M : int
+ Number of points in the output window. If zero, an empty array
+ is returned. An exception is thrown when it is negative.
+ sym : bool, optional
+ When True (default), generates a symmetric window, for use in filter
+ design.
+ When False, generates a periodic window, for use in spectral analysis.
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ w : ndarray
+ The window, with the maximum value normalized to 1 (though the value 1
+ does not appear if `M` is even and `sym` is True).
+
+ Notes
+ -----
+ The Lanczos window is defined as
+
+ .. math:: w(n) = sinc \left( \frac{2n}{M - 1} - 1 \right)
+
+ where
+
+ .. math:: sinc(x) = \frac{\sin(\pi x)}{\pi x}
+
+ The Lanczos window has reduced Gibbs oscillations and is widely used for
+ filtering climate timeseries with good properties in the physical and
+ spectral domains.
+
+ .. versionadded:: 1.10
+
+ References
+ ----------
+ .. [1] Lanczos, C., and Teichmann, T. (1957). Applied analysis.
+ Physics Today, 10, 44.
+ .. [2] Duchon C. E. (1979) Lanczos Filtering in One and Two Dimensions.
+ Journal of Applied Meteorology, Vol 18, pp 1016-1022.
+ .. [3] Thomson, R. E. and Emery, W. J. (2014) Data Analysis Methods in
+ Physical Oceanography (Third Edition), Elsevier, pp 593-637.
+ .. [4] Wikipedia, "Window function",
+ http://en.wikipedia.org/wiki/Window_function
+
+ Examples
+ --------
+ Plot the window
+
+ >>> import numpy as np
+ >>> from scipy.signal.windows import lanczos
+ >>> from scipy.fft import fft, fftshift
+ >>> import matplotlib.pyplot as plt
+ >>> fig, ax = plt.subplots(1)
+ >>> window = lanczos(51)
+ >>> ax.plot(window)
+ >>> ax.set_title("Lanczos window")
+ >>> ax.set_ylabel("Amplitude")
+ >>> ax.set_xlabel("Sample")
+ >>> fig.tight_layout()
+ >>> plt.show()
+
+ and its frequency response:
+
+ >>> fig, ax = plt.subplots(1)
+ >>> A = fft(window, 2048) / (len(window)/2.0)
+ >>> freq = np.linspace(-0.5, 0.5, len(A))
+ >>> response = 20 * np.log10(np.abs(fftshift(A / abs(A).max())))
+ >>> ax.plot(freq, response)
+ >>> ax.set_xlim(-0.5, 0.5)
+ >>> ax.set_ylim(-120, 0)
+ >>> ax.set_title("Frequency response of the lanczos window")
+ >>> ax.set_ylabel("Normalized magnitude [dB]")
+ >>> ax.set_xlabel("Normalized frequency [cycles per sample]")
+ >>> fig.tight_layout()
+ >>> plt.show()
+ """
+ xp = _namespace(xp)
+
+ if _len_guards(M):
+ return xp.ones(M, dtype=xp.float64, device=device)
+ M, needs_trunc = _extend(M, sym)
+
+ # To make sure that the window is symmetric, we concatenate the right hand
+ # half of the window and the flipped one which is the left hand half of
+ # the window.
+ def _calc_right_side_lanczos(n, m):
+ return xpx.sinc(2. * xp.arange(n, m, dtype=xp.float64) / (m - 1) - 1.0, xp=xp)
+
+ if M % 2 == 0:
+ wh = _calc_right_side_lanczos(M/2, M)
+ w = xp.concat([xp.flip(wh), wh])
+ else:
+ wh = _calc_right_side_lanczos((M+1)/2, M)
+ w = xp.concat([xp.flip(wh), xp.ones(1), wh])
+
+ return _truncate(w, needs_trunc)
+
+
+def _fftautocorr(x):
+ """Compute the autocorrelation of a real array and crop the result."""
+ N = x.shape[-1]
+ use_N = sp_fft.next_fast_len(2*N-1)
+ x_fft = sp_fft.rfft(x, use_N, axis=-1)
+ cxy = sp_fft.irfft(x_fft * x_fft.conj(), n=use_N)[:, :N]
+ # Or equivalently (but in most cases slower):
+ # cxy = xp.asarray([xp.convolve(xx, yy[::-1], mode='full')
+ # for xx, yy in zip(x, x)])[:, N-1:2*N-1]
+ return cxy
+
+_WIN_FUNC_DATA = { # Format: {(name0, name1, ...): (function, needs parameters)
+ ('barthann', 'brthan', 'bth'): (barthann, False),
+ ('bartlett', 'bart', 'brt'): (bartlett, False),
+ ('blackman', 'black', 'blk'): (blackman, False),
+ ('blackmanharris', 'blackharr', 'bkh'): (blackmanharris, False),
+ ('bohman', 'bman', 'bmn'): (bohman, False),
+ ('boxcar', 'box', 'ones', 'rect', 'rectangular'): (boxcar, False),
+ ('chebwin', 'cheb'): (chebwin, True),
+ ('cosine', 'halfcosine'): (cosine, False),
+ ('dpss',): (dpss, True),
+ ('exponential', 'poisson'): (exponential, 'OPTIONAL'),
+ ('flattop', 'flat', 'flt'): (flattop, False),
+ ('gaussian', 'gauss', 'gss'): (gaussian, True),
+ ('general cosine', 'general_cosine'): (general_cosine, True),
+ ('general gaussian', 'general_gaussian', 'general gauss',
+ 'general_gauss', 'ggs'): (general_gaussian, True),
+ ('general hamming', 'general_hamming'): (general_hamming, True),
+ ('hamming', 'hamm', 'ham'): (hamming, False),
+ ('hann', 'han'): (hann, False),
+ ('kaiser', 'ksr'): (kaiser, True),
+ ('kaiser bessel derived', 'kaiser_bessel_derived',
+ 'kbd'): (kaiser_bessel_derived, True),
+ ('lanczos', 'sinc'): (lanczos, False),
+ ('nuttall', 'nutl', 'nut'): (nuttall, False),
+ ('parzen', 'parz', 'par'): (parzen, False),
+ ('taylor', 'taylorwin'): (taylor, 'OPTIONAL'),
+ ('triangle', 'triang', 'tri'): (triang, False),
+ ('tukey', 'tuk'): (tukey, 'OPTIONAL'), }
+_WIN_FUNCS = dict()
+for nn_, v_ in _WIN_FUNC_DATA.items():
+ _WIN_FUNCS.update({n_: v_ for n_ in nn_})
+
+
+@xp_capabilities()
+def get_window(window, Nx, fftbins=True, *, xp=None, device=None):
+ r"""Convenience function for creating various windows.
+
+ This function is a wrapper for the window functions provided in the
+ `scipy.signal.windows` namespace.
+
+ Parameters
+ ----------
+ window : str | tuple | float
+ Either a string with the window name or a tuple consisting of window name and
+ window parameters. If it is a float, a `~scipy.singal.kaiser` window is
+ created with `window` being the shape parameter. Consult the Notes below for
+ more details.
+ Nx : int
+ The number of samples in the window.
+ fftbins : bool, optional
+ If ``True`` (default), create a periodic window, ready to use with `ifftshift`
+ and be multiplied by the result of an FFT (see also
+ :func:`~scipy.fft.fftfreq`). If ``False``, create a symmetric window, for use
+ in filter design. This parameter is ignored, if the window name in the
+ `window` parameter has a suffix ``'_periodic'`` or ``'_symmetric'`` appended to
+ it (e.g., ``'hann_symmetric'``).
+ %(xp_device_snippet)s
+
+ Returns
+ -------
+ get_window : ndarray
+ Returns the created window as a one-dimensional array made of `Nx` samples.
+
+ Raises
+ ------
+ ValueError
+ If the provided parameters do not allow to choose a valid window function
+ with valid parameters.
+
+ Notes
+ -----
+ Note that by default this function returns a periodic window, whereas the wrapped
+ window functions return a symmetric window by default. This is caused by the
+ `fftbins` parameter having the inverse meaning of the `sym` parameter of the
+ wrapped function, which are both ``True`` by default.
+
+ .. currentmodule:: scipy.signal.windows
+
+ The following list shows the wrapped window functions with the respective settings
+ of the `window` parameter followed by a short description. Aliases for alternative
+ window names are given in parenthesis.
+
+ `barthann` / ``'barthann'``:
+ Modified Bartlett-Hann window (aliases: ``'brthan', 'bth'``)
+ `bartlett` / ``'bartlett'``:
+ Bartlett window (aliases: ``'bart', 'brt'``)
+ `blackman`/ ``'blackman'``:
+ Blackman window (aliases: ``'black', 'blk'``)
+ `blackmanharris` / ``'blackmanharris'``:
+ 4-term Blackman-Harris window (aliases: ``'blackharr', 'bkh'``)
+ `bohman` / ``'bohman'``:
+ Bohman window (aliases: ``'bman', 'bmn'``)
+ `boxcar` / ``'boxcar'``:
+ Rectangular window (aliases: ``'box', 'ones', 'rect', 'rectangular'``)
+ `chebwin` / ``('chebwin', at)``:
+ Dolph-Chebyshev window with `at` dB attenuation (aliases: ``'cheb'``)
+ `cosine` / ``'cosine'``:
+ Cosine window (aliases: ``'halfcosine'``)
+ `dpss` / ``('dpss', NW)``:
+ First window of discrete prolate spheroidal sequence with standardized half
+ bandwidth ``NW`` and "approximate" norm.
+ `exponential` / ``'exponential'`` / ``('exponential', center, tau)``:
+ Exponential / Poisson window centered at ``center`` (default: ``None``) with
+ deacy ``tau`` (default: ``1``) (aliases: ``'poisson'``)
+ `flattop`/ ``'flattop'``:
+ Flat top window (aliases: ``'flat', 'flt'``)
+ `gaussian` / ``('gaussian', std)``:
+ Gaussian with standard deviation `std` (aliases: ``'gauss', 'gss'``)
+ `general_cosine` / ``('general cosine', a)``:
+ Generic weighted sum of cosine terms with weighting coefficients ``a``
+ (aliases: ``'general_cosine'``)
+ `general_gaussian` / ``('general gaussian', p, sig)``:
+ Generalized Gaussian with shape parameter ``p`` and standard deviation ``sig``
+ (aliases: ``'general_gaussian', 'general gauss', 'general_gauss', 'ggs'``)
+ `general_hamming` / ``('general hamming', alpha)``:
+ Generalized Hamming window with coefficent ``alpha``
+ (aliases: ``'general_hamming'``)
+ `hamming` / ``'hamming'``:
+ Hamming window (aliases: ``'hamm', 'ham'``)
+ `hann` / ``'hann'``:
+ Hann window (aliases: ``'han'``)
+ `kaiser` / ``('kaiser', beta)``:
+ Kaiser window with shape parameter ``beta`` (aliases: ``'ksr'``)
+ `kaiser_bessel_derived` / ``('kaiser bessel derived', beta)``:
+ Kaiser-Bessel derived window with shape parameter ``beta``
+ (aliases: ``'kaiser_bessel_derived', 'kbd'``)
+ `lanczos` / ``'lanczos'``:
+ Lanczos / sinc window (aliases: ``'sinc'``)
+ `nuttall`/ ``'nuttall'``:
+ Minimum 4-term Blackman-Harris window according to Nuttall
+ (aliases: ``'nutl', 'nut'``)
+ `parzen` / ``'parzen'``:
+ Parzen window (aliases: ``'parz', 'par'``)
+ `taylor` / ``'taylor'`` / (``'taylor', nbar, sll, norm)``:
+ Taylor window with ``nbar`` adjascent sidelobes (default: ``4``)), ``sll`` dB
+ suppression level (default: ``30``) and boolean value ``norm``
+ (default: ``True``) (aliases: ``taylorwin``)
+ `triang`/ ``'triangle'``:
+ Triangle window (aliases: ``'triang', 'tri'``)
+ `tukey` / ``'tukey'`` / ``('tukey', alpha)``:
+ Tukey window with shape parameter ``alpha`` (default: ``0.5``)
+ (aliases: ``'tuk'``)
+
+
+ Examples
+ --------
+ This example shows different usages of the `window` parameter:
+
+ >>> from scipy.signal import get_window
+ >>> get_window('triang', 7)
+ array([ 0.125, 0.375, 0.625, 0.875, 0.875, 0.625, 0.375])
+ >>> get_window(('exponential', None, 1.), 9)
+ array([ 0.011109 , 0.03019738, 0.082085 , 0.22313016, 0.60653066,
+ 0.60653066, 0.22313016, 0.082085 , 0.03019738])
+ >>> get_window(('kaiser', 4.0), 9)
+ array([ 0.08848053, 0.29425961, 0.56437221, 0.82160913, 0.97885093,
+ 0.97885093, 0.82160913, 0.56437221, 0.29425961])
+ >>> get_window(4.0, 9) # same as previous call
+ array([ 0.08848053, 0.29425961, 0.56437221, 0.82160913, 0.97885093,
+ 0.97885093, 0.82160913, 0.56437221, 0.29425961])
+
+ The following snippet shows different ways to create identical symmetric and
+ periodic Bartlett windows:
+
+ >>> from scipy.signal import get_window, windows
+ >>> # Symmetric window:
+ >>> windows.bartlett(5) # Parameter `sym` defaults to True
+ array([0. , 0.5, 1. , 0.5, 0. ])
+ >>> get_window('bartlett', 5, fftbins=False)
+ array([0. , 0.5, 1. , 0.5, 0. ])
+ >>> get_window('bartlett_symmetric', 5)
+ array([0. , 0.5, 1. , 0.5, 0. ])
+ >>> # Periodic window:
+ >>> windows.bartlett(4, sym=False)
+ array([0. , 0.5, 1. , 0.5])
+ >>> get_window('bartlett', 4) # Parameter `fftbins` defaults to True
+ array([0. , 0.5, 1. , 0.5])
+ >>> get_window('bartlett_periodic', 4)
+ array([0. , 0.5, 1. , 0.5])
+ >>> # `_periodic' suffix overrides `fftbins` parameter:
+ >>> get_window('bartlett_periodic', 4, fftbins=False)
+ array([0. , 0.5, 1. , 0.5])
+
+ Note that a periodic window can be created out of a symmetric window by discarding
+ the last sample.
+ """
+ if not (Nx > 0 and isinstance(Nx, numbers.Integral)):
+ raise ValueError(f"Parameter {Nx=} is not a positive integer")
+ if not isinstance(fftbins, bool):
+ raise ValueError(f"Parameter {fftbins=} is not of type bool!")
+
+ if not isinstance(window, str | tuple):
+ try: # if parameter window can be converted to a float, return kaiser window:
+ beta = float(window)
+ except Exception as float_exception:
+ err_msg = f"Parameter {window=} must be a tuple, a string or a float!"
+ raise ValueError(err_msg) from float_exception
+ return kaiser(Nx, beta, not fftbins, xp=xp, device=device)
+
+ if isinstance(window, tuple) and not isinstance(window[0], str):
+ raise ValueError(f"First tuple entry of parameter {window=} is not a str!")
+
+ sym = not fftbins
+ win_name = window if isinstance(window, str) else window[0]
+ if win_name.endswith('_symmetric'): # overwrite `fftbins` / `sym` if needed
+ sym, win_name = True, win_name[:-10] # remove '_symmetric' from `win_name`
+ elif win_name.endswith('_periodic'):
+ sym, win_name = False, win_name[:-9] # remove '_periodic' from `win_name`
+
+ if win_name not in _WIN_FUNCS:
+ raise ValueError(f"Invalid window name '{win_name}' in parameter {window=}!")
+
+ func, has_args = _WIN_FUNCS[win_name]
+ args = window[1:] if isinstance(window, tuple) else tuple()
+ if len(args) > 0 and has_args is False:
+ raise ValueError(f"'{win_name}' does not allow parameters, but {window=}!")
+ if len(args) == 0 and has_args is True:
+ raise ValueError(f"'{win_name}' must have parameters, but {window=}!")
+ # has_args == 'OPTIONAL' allows len(args) == 0 as well as len(args) > 0
+
+ if not has_args:
+ return func(Nx, sym=sym, xp=xp, device=device)
+
+ # special cases taken from original implementation:
+ if func is dpss:
+ if len(args) != 1:
+ raise ValueError(f"Window {win_name} must have one parameter but {window=}")
+ return dpss(Nx, args[0], Kmax=None, sym=sym, xp=xp, device=device)
+ if func is general_cosine:
+ if not (xp is None and device is None):
+ raise ValueError("'general_cosine' does not accept the parameters xp " +
+ "and device not being None!")
+ return general_cosine(Nx, *args, sym=sym)
+
+ return func(Nx, *args, sym=sym, xp=xp, device=device)
+
+
+########## complete the docstrings, on import
+_xp_device_snippet = {'xp_device_snippet':
+"""\
+xp : array_namespace, optional
+ Optional array namespace.
+ Should be compatible with the array API standard, or supported by array-api-compat.
+ Default: ``numpy``
+device: any
+ optional device specification for output. Should match one of the
+ supported device specification in ``xp``.
+"""
+}
+
+
+_names = [x for x in __all__ if x != 'general_cosine']
+for name in _names:
+ window = vars()[name]
+ window.__doc__ = doccer.docformat(window.__doc__, _xp_device_snippet)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/windows.py b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/windows.py
new file mode 100644
index 0000000000000000000000000000000000000000..6858f71aceeb29ca6110864d01fb250e8c8ce403
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/signal/windows/windows.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.signal.windows` namespace for importing the functions
+# included below.
+
+from scipy._lib.deprecation import _sub_module_deprecation
+
+__all__ = [ # noqa: F822
+ 'boxcar', 'triang', 'parzen', 'bohman', 'blackman', 'nuttall',
+ 'blackmanharris', 'flattop', 'bartlett', 'barthann',
+ 'hamming', 'kaiser', 'gaussian', 'general_cosine',
+ 'general_gaussian', 'general_hamming', 'chebwin', 'cosine',
+ 'hann', 'exponential', 'tukey', 'taylor', 'dpss', 'get_window',
+]
+
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ return _sub_module_deprecation(sub_package="signal.windows", module="windows",
+ private_modules=["_windows"], all=__all__,
+ attribute=name)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.___init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.___init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.___init__.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.___pycache__ b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.___pycache__
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.___pycache__ differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__base.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__base.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__base.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__bsr.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__bsr.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__bsr.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__compressed.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__compressed.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__compressed.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__construct.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__construct.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__construct.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__coo.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__coo.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__coo.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__csc.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__csc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__csc.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__csparsetools.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__csparsetools.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__csparsetools.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__csr.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__csr.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__csr.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__data.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__data.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__data.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__dia.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__dia.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__dia.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__dok.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__dok.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__dok.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__extract.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__extract.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__index.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__index.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__index.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__lil.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__lil.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__lil.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__matrix.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__matrix.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__matrix.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__matrix_io.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__matrix_io.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__matrix_io.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__sparsetools.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__sparsetools.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__sparsetools.cpython-312-darwin.so differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__spfuncs.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__spfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__spfuncs.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__sputils.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__sputils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/.__sputils.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._base.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._base.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._base.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._bsr.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._bsr.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._bsr.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._compressed.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._compressed.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._compressed.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._construct.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._construct.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._construct.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._coo.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._coo.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._coo.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._csc.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._csc.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._csc.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._csgraph b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._csgraph
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._csgraph differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._csr.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._csr.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._csr.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._data.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._data.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._data.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._dia.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._dia.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._dia.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._dok.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._dok.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._dok.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._extract.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._extract.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._lil.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._lil.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._lil.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._linalg b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._linalg
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._linalg differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._sparsetools.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._sparsetools.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._sparsetools.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._spfuncs.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._spfuncs.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._spfuncs.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._sputils.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._sputils.py
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._sputils.py differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._tests b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._tests
new file mode 100644
index 0000000000000000000000000000000000000000..ee537d225f1b1eed0d0f4ed0b171fdc63ca71d82
Binary files /dev/null and b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/._tests differ
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/__init__.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/__init__.py
new file mode 100644
index 0000000000000000000000000000000000000000..aa8a6aa12cb4ff4b4f11831550cdf5aa951a46c9
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/__init__.py
@@ -0,0 +1,353 @@
+"""
+===================================
+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]]``.
+ - All index arrays for a given sparse array should be of same dtype.
+ For example, for CSR format, ``indices`` and ``indptr`` should have
+ the same dtype. For COO, each array in `coords` should have same dtype.
+
+ 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)
+ swapaxes - swap two axes of a sparse array
+ expand_dims - add a new (trivial) axis to a sparse array
+ permute_dims - reorder the axes of a sparse array
+
+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-9
+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
+import importlib as _importlib
+
+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
+
+
+# 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
+)
+
+_submodules = ["csgraph", "linalg"]
+
+__all__ = [s for s in dir() if not s.startswith('_')] + _submodules
+
+# Filter PendingDeprecationWarning for np.matrix introduced with numpy 1.15
+msg = 'the matrix subclass is not the recommended way'
+_warnings.filterwarnings('ignore', message=msg)
+
+def __dir__():
+ return __all__
+
+
+def __getattr__(name):
+ if name in _submodules:
+ return _importlib.import_module(f'scipy.sparse.{name}')
+ else:
+ try:
+ return globals()[name]
+ except KeyError:
+ raise AttributeError(
+ f"Module 'scipy.sparse' has no attribute '{name}'"
+ )
+
+from scipy._lib._testutils import PytestTester
+test = PytestTester(__name__)
+del PytestTester
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_base.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_base.py
new file mode 100644
index 0000000000000000000000000000000000000000..fa1ec6bf2600aab0d633cf93bf88187a2bba4a5f
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_base.py
@@ -0,0 +1,1606 @@
+"""Base class for sparse matrices"""
+
+from warnings import warn
+import math
+import numpy as np
+import operator
+
+from ._sputils import (asmatrix, check_reshape_kwargs, check_shape,
+ get_sum_dtype, isdense, isscalarlike, _todata,
+ matrix, validateaxis, getdtype, is_pydata_spmatrix)
+from scipy._lib._sparse import SparseABC, issparse
+
+from ._matrix import spmatrix
+
+__all__ = ['isspmatrix', 'issparse', 'sparray',
+ 'SparseWarning', 'SparseEfficiencyWarning']
+
+
+class SparseWarning(Warning):
+ """General warning for :mod:`scipy.sparse`."""
+ pass
+
+
+class SparseFormatWarning(SparseWarning):
+ pass
+
+
+class SparseEfficiencyWarning(SparseWarning):
+ """The warning emitted when the operation is
+ inefficient for sparse matrices.
+ """
+ pass
+
+
+# The formats that we might potentially understand.
+_formats = {'csc': [0, "Compressed Sparse Column"],
+ 'csr': [1, "Compressed Sparse Row"],
+ 'dok': [2, "Dictionary Of Keys"],
+ 'lil': [3, "List of Lists"],
+ 'dod': [4, "Dictionary of Dictionaries"],
+ 'sss': [5, "Symmetric Sparse Skyline"],
+ 'coo': [6, "COOrdinate"],
+ 'lba': [7, "Linpack BAnded"],
+ 'egd': [8, "Ellpack-itpack Generalized Diagonal"],
+ 'dia': [9, "DIAgonal"],
+ 'bsr': [10, "Block Sparse Row"],
+ 'msr': [11, "Modified compressed Sparse Row"],
+ 'bsc': [12, "Block Sparse Column"],
+ 'msc': [13, "Modified compressed Sparse Column"],
+ 'ssk': [14, "Symmetric SKyline"],
+ 'nsk': [15, "Nonsymmetric SKyline"],
+ 'jad': [16, "JAgged Diagonal"],
+ 'uss': [17, "Unsymmetric Sparse Skyline"],
+ 'vbr': [18, "Variable Block Row"],
+ 'und': [19, "Undefined"]
+ }
+
+
+# These univariate ufuncs preserve zeros.
+_ufuncs_with_fixed_point_at_zero = frozenset([
+ np.sin, np.tan, np.arcsin, np.arctan, np.sinh, np.tanh, np.arcsinh,
+ np.arctanh, np.rint, np.sign, np.expm1, np.log1p, np.deg2rad,
+ np.rad2deg, np.floor, np.ceil, np.trunc, np.sqrt])
+
+
+MAXPRINT = 50
+
+
+# helper dicts to manipulate comparison operators
+# We negate operators (with warning) when all implicit values would be True
+op_neg = {operator.eq: operator.ne, operator.ne: operator.eq,
+ operator.lt: operator.ge, operator.ge: operator.lt,
+ operator.gt: operator.le, operator.le: operator.gt}
+
+
+# We use symbolic version of operators in warning messages.
+op_sym = {operator.eq: '==', operator.ge: '>=', operator.le: '<=',
+ operator.ne: '!=', operator.gt: '>', operator.lt: '<'}
+
+
+# `_spbase` is a subclass of `SparseABC`.
+# This allows other submodules to check for instances of sparse subclasses
+# via `scipy._lib._sparse.issparse`, without introducing
+# an import dependency on `scipy.sparse`.
+class _spbase(SparseABC):
+ """ This class provides a base class for all sparse arrays. It
+ cannot be instantiated. Most of the work is provided by subclasses.
+ """
+
+ __array_priority__ = 10.1
+ _format = 'und' # undefined
+ _allow_nd = (2,)
+
+ @property
+ def ndim(self) -> int:
+ return len(self._shape)
+
+ @property
+ def _shape_as_2d(self):
+ s = self._shape
+ return (1, s[-1]) if len(s) == 1 else s
+
+ @property
+ def _bsr_container(self):
+ from ._bsr import bsr_array
+ return bsr_array
+
+ @property
+ def _coo_container(self):
+ from ._coo import coo_array
+ return coo_array
+
+ @property
+ def _csc_container(self):
+ from ._csc import csc_array
+ return csc_array
+
+ @property
+ def _csr_container(self):
+ from ._csr import csr_array
+ return csr_array
+
+ @property
+ def _dia_container(self):
+ from ._dia import dia_array
+ return dia_array
+
+ @property
+ def _dok_container(self):
+ from ._dok import dok_array
+ return dok_array
+
+ @property
+ def _lil_container(self):
+ from ._lil import lil_array
+ return lil_array
+
+ def __init__(self, arg1, *, maxprint=None):
+ self._shape = None
+ if self.__class__.__name__ == '_spbase':
+ raise ValueError("This class is not intended"
+ " to be instantiated directly.")
+ if isinstance(self, sparray) and np.isscalar(arg1):
+ raise ValueError(
+ "scipy sparse array classes do not support instantiation from a scalar"
+ )
+ self.maxprint = MAXPRINT if maxprint is None else maxprint
+
+ @property
+ def shape(self):
+ return self._shape
+
+ def reshape(self, *args, **kwargs):
+ """reshape(self, shape, order='C', copy=False)
+
+ Gives a new shape to a sparse array/matrix without changing its data.
+
+ Parameters
+ ----------
+ shape : tuple of ints
+ The new shape should be compatible with the original shape.
+ order : {'C', 'F'}, optional
+ Read the elements using this index order. 'C' means to read and
+ write the elements using C-like index order; e.g., read entire first
+ row, then second row, etc. 'F' means to read and write the elements
+ using Fortran-like index order; e.g., read entire first column, then
+ second column, etc.
+ copy : bool, optional
+ Indicates whether or not attributes of self should be copied
+ whenever possible. The degree to which attributes are copied varies
+ depending on the type of sparse array being used.
+
+ Returns
+ -------
+ reshaped : sparse array/matrix
+ A sparse array/matrix with the given `shape`, not necessarily of the same
+ format as the current object.
+
+ See Also
+ --------
+ numpy.reshape : NumPy's implementation of 'reshape' for ndarrays
+ """
+ # If the shape already matches, don't bother doing an actual reshape
+ # Otherwise, the default is to convert to COO and use its reshape
+ # Don't restrict ndim on this first call. That happens in constructor
+ shape = check_shape(args, self.shape, allow_nd=range(1, 65))
+ order, copy = check_reshape_kwargs(kwargs)
+ if shape == self.shape:
+ if copy:
+ return self.copy()
+ else:
+ return self
+
+ return self.tocoo(copy=copy).reshape(shape, order=order, copy=False)
+
+ def resize(self, shape):
+ """Resize the array/matrix in-place to dimensions given by ``shape``
+
+ Any elements that lie within the new shape will remain at the same
+ indices, while non-zero elements lying outside the new shape are
+ removed.
+
+ Parameters
+ ----------
+ shape : (int, int)
+ number of rows and columns in the new array/matrix
+
+ Notes
+ -----
+ The semantics are not identical to `numpy.ndarray.resize` or
+ `numpy.resize`. Here, the same data will be maintained at each index
+ before and after reshape, if that index is within the new bounds. In
+ numpy, resizing maintains contiguity of the array, moving elements
+ around in the logical array but not within a flattened representation.
+
+ We give no guarantees about whether the underlying data attributes
+ (arrays, etc.) will be modified in place or replaced with new objects.
+ """
+ # As an inplace operation, this requires implementation in each format.
+ raise NotImplementedError(
+ f'{type(self).__name__}.resize is not implemented')
+
+ def astype(self, dtype, casting='unsafe', copy=True):
+ """Cast the array/matrix elements to a specified type.
+
+ Parameters
+ ----------
+ dtype : string or numpy dtype
+ Typecode or data-type to which to cast the data.
+ casting : {'no', 'equiv', 'safe', 'same_kind', 'unsafe'}, optional
+ Controls what kind of data casting may occur.
+ Defaults to 'unsafe' for backwards compatibility.
+ 'no' means the data types should not be cast at all.
+ 'equiv' means only byte-order changes are allowed.
+ 'safe' means only casts which can preserve values are allowed.
+ 'same_kind' means only safe casts or casts within a kind,
+ like float64 to float32, are allowed.
+ 'unsafe' means any data conversions may be done.
+ copy : bool, optional
+ If `copy` is `False`, the result might share some memory with this
+ array/matrix. If `copy` is `True`, it is guaranteed that the result and
+ this array/matrix do not share any memory.
+ """
+
+ dtype = getdtype(dtype)
+ if self.dtype != dtype:
+ return self.tocsr().astype(
+ dtype, casting=casting, copy=copy).asformat(self.format)
+ elif copy:
+ return self.copy()
+ else:
+ return self
+
+ @classmethod
+ def _ascontainer(cls, X, **kwargs):
+ if issubclass(cls, sparray):
+ return np.asarray(X, **kwargs)
+ else:
+ return asmatrix(X, **kwargs)
+
+ @classmethod
+ def _container(cls, X, **kwargs):
+ if issubclass(cls, sparray):
+ return np.array(X, **kwargs)
+ else:
+ return matrix(X, **kwargs)
+
+ def _asfptype(self):
+ """Upcast array to a floating point format (if necessary)"""
+
+ fp_types = ['f', 'd', 'F', 'D']
+
+ if self.dtype.char in fp_types:
+ return self
+ else:
+ for fp_type in fp_types:
+ if self.dtype <= np.dtype(fp_type):
+ return self.astype(fp_type, copy=False)
+
+ raise TypeError(
+ f'cannot upcast [{self.dtype.name}] to a floating point format'
+ )
+
+ def __iter__(self):
+ for r in range(self.shape[0]):
+ yield self[r]
+
+ def _getmaxprint(self):
+ """Maximum number of elements to display when printed."""
+ return self.maxprint
+
+ def count_nonzero(self, axis=None):
+ """Number of non-zero entries, equivalent to
+
+ np.count_nonzero(a.toarray(), axis=axis)
+
+ Unlike the nnz property, which return the number of stored
+ entries (the length of the data attribute), this method counts the
+ actual number of non-zero entries in data.
+
+ Duplicate entries are summed before counting.
+
+ Parameters
+ ----------
+ axis : {-2, -1, 0, 1, None} optional
+ Count nonzeros for the whole array, or along a specified axis.
+
+ .. versionadded:: 1.15.0
+
+ Returns
+ -------
+ numpy array
+ A reduced array (no axis `axis`) holding the number of nonzero values
+ for each of the indices of the nonaxis dimensions.
+
+ Notes
+ -----
+ If you want to count nonzero and explicit zero stored values (e.g. nnz)
+ along an axis, two fast idioms are provided by `numpy` functions for the
+ common CSR, CSC, COO formats.
+
+ For the major axis in CSR (rows) and CSC (cols) use `np.diff`:
+
+ >>> import numpy as np
+ >>> import scipy as sp
+ >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
+ >>> major_axis_stored_values = np.diff(A.indptr) # -> np.array([2, 1])
+
+ For the minor axis in CSR (cols) and CSC (rows) use `numpy.bincount` with
+ minlength ``A.shape[1]`` for CSR and ``A.shape[0]`` for CSC:
+
+ >>> csr_minor_stored_values = np.bincount(A.indices, minlength=A.shape[1])
+
+ For COO, use the minor axis approach for either `axis`:
+
+ >>> A = A.tocoo()
+ >>> coo_axis0_stored_values = np.bincount(A.coords[0], minlength=A.shape[1])
+ >>> coo_axis1_stored_values = np.bincount(A.coords[1], minlength=A.shape[0])
+
+ Examples
+ --------
+
+ >>> A = sp.sparse.csr_array([[4, 5, 0], [7, 0, 0]])
+ >>> A.count_nonzero(axis=0)
+ array([2, 1, 0])
+ """
+ clsname = self.__class__.__name__
+ raise NotImplementedError(f"count_nonzero not implemented for {clsname}.")
+
+ def _getnnz(self, axis=None):
+ """Number of stored values, including explicit zeros.
+
+ Parameters
+ ----------
+ axis : {-2, -1, 0, 1, None} optional
+ Report stored values for the whole array, or along a specified axis.
+
+ See also
+ --------
+ count_nonzero : Number of non-zero entries
+ """
+ clsname = self.__class__.__name__
+ raise NotImplementedError(f"getnnz not implemented for {clsname}.")
+
+ @property
+ def nnz(self) -> int:
+ """Number of stored values, including explicit zeros.
+
+ See also
+ --------
+ count_nonzero : Number of non-zero entries
+ """
+ return self._getnnz()
+
+ @property
+ def size(self) -> int:
+ """Number of stored values.
+
+ See also
+ --------
+ count_nonzero : Number of non-zero values.
+ """
+ return self._getnnz()
+
+ @property
+ def format(self) -> str:
+ """Format string for matrix."""
+ return self._format
+
+ @property
+ def T(self):
+ """Transpose."""
+ return self.transpose()
+
+ @property
+ def real(self):
+ return self._real()
+
+ @property
+ def imag(self):
+ return self._imag()
+
+ def __repr__(self):
+ _, format_name = _formats[self.format]
+ sparse_cls = 'array' if isinstance(self, sparray) else 'matrix'
+ return (
+ f"<{format_name} sparse {sparse_cls} of dtype '{self.dtype}'\n"
+ f"\twith {self.nnz} stored elements and shape {self.shape}>"
+ )
+
+ def __str__(self):
+ maxprint = self._getmaxprint()
+
+ A = self.tocoo()
+
+ # helper function, outputs "(i,j) v"
+ def tostr(coords, data):
+ pairs = zip(zip(*(c.tolist() for c in coords)), data)
+ return '\n'.join(f' {idx}\t{val}' for idx, val in pairs)
+
+ out = repr(self)
+ if self.nnz == 0:
+ return out
+
+ out += '\n Coords\tValues\n'
+ if self.nnz > maxprint:
+ half = maxprint // 2
+ out += tostr(tuple(c[:half] for c in A.coords), A.data[:half])
+ out += "\n :\t:\n"
+ half = maxprint - half
+ out += tostr(tuple(c[-half:] for c in A.coords), A.data[-half:])
+ else:
+ out += tostr(A.coords, A.data)
+
+ return out
+
+ def __bool__(self): # Simple -- other ideas?
+ if self.shape == (1, 1):
+ return self.nnz != 0
+ else:
+ raise ValueError("The truth value of an array with more than one "
+ "element is ambiguous. Use a.any() or a.all().")
+
+ # What should len(sparse) return? For consistency with dense matrices,
+ # perhaps it should be the number of rows? But for some uses the number of
+ # non-zeros is more important. For now, raise an exception!
+ def __len__(self):
+ raise TypeError("sparse array length is ambiguous; use getnnz()"
+ " or shape[0]")
+
+ def asformat(self, format, copy=False):
+ """Return this array/matrix in the passed format.
+
+ Parameters
+ ----------
+ format : {str, None}
+ The desired sparse format ("csr", "csc", "lil", "dok", "array", ...)
+ or None for no conversion.
+ copy : bool, optional
+ If True, the result is guaranteed to not share data with self.
+
+ Returns
+ -------
+ A : This array/matrix in the passed format.
+ """
+ if format is None or format == self.format:
+ if copy:
+ return self.copy()
+ else:
+ return self
+ else:
+ try:
+ convert_method = getattr(self, 'to' + format)
+ except AttributeError as e:
+ raise ValueError(f'Format {format} is unknown.') from e
+
+ # Forward the copy kwarg, if it's accepted.
+ try:
+ return convert_method(copy=copy)
+ except TypeError:
+ return convert_method()
+
+ ###################################################################
+ # NOTE: All arithmetic operations use csr_matrix by default.
+ # Therefore a new sparse array format just needs to define a
+ # .tocsr() method to provide arithmetic support. Any of these
+ # methods can be overridden for efficiency.
+ ####################################################################
+
+ def multiply(self, other):
+ """Element-wise multiplication by another array/matrix."""
+ if isscalarlike(other):
+ return self._mul_scalar(other)
+
+ if self.ndim < 3:
+ try:
+ return self._multiply_2d_with_broadcasting(other)
+ except AttributeError:
+ return self.tocsr()._multiply_2d_with_broadcasting(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_:
+ # numpy creates a 0d object array if all else fails.
+ # Not interpretable as an array; return NotImplemented so
+ # other's __rmul__ can kick in if that's implemented.
+ return NotImplemented
+ # Allow custom sparse class indicated by attr sparse gh-6520
+ try:
+ other.shape
+ except AttributeError:
+ other = other_a
+
+ if self.shape != other.shape:
+ raise ValueError("inconsistent shapes: >2D multiply() does not yet "
+ "support broadcasting")
+
+ # self is >2D so must be COO
+ if isdense(other):
+ data = np.multiply(self.data, other[self.coords])
+ result = self.copy()
+ result.data = data.view(np.ndarray).ravel()
+ return result
+
+ elif issparse(other):
+ csr_self = self.reshape(1, -1).tocsr()
+ csr_other = other.reshape(1, -1).tocsr()
+ return csr_self._binopt(csr_other, '_elmul_').reshape(self.shape)
+
+ else:
+ # Not scalar, dense or sparse. Return NotImplemented so that
+ # other's __rmul__ can kick in if that's implemented.
+ return NotImplemented
+
+ def _maximum_minimum(self, other, np_op):
+ if not (issparse(other) or isdense(other) or isscalarlike(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_:
+ # numpy creates a 0d object array if all else fails.
+ # We don't know how to handle it either.
+ raise NotImplementedError('maximum or minimum with an unrecognized '
+ 'array type is not supported')
+ # Allow custom sparse class indicated by attr sparse gh-6520
+ try:
+ other.shape
+ except AttributeError:
+ other = other_a
+
+ if isscalarlike(other):
+ if np_op(0, other):
+ pos_neg = 'positive' if np_op == np.maximum else 'negative'
+ warn(f"Taking {np_op.__name__} with a {pos_neg} number results in a"
+ " dense matrix.", SparseEfficiencyWarning, stacklevel=3)
+ return self.__class__(np_op(self.toarray(), other))
+ else:
+ if self.ndim < 3:
+ cs_self = self if self.format in ('csr', 'csc') else self.tocsr()
+ return cs_self._scalar_binopt(other, np_op)
+ csr_self = self.reshape(1, -1).tocsr()
+ result = csr_self._scalar_binopt(other, np_op)
+ return result.tocoo().reshape(self.shape)
+ elif isdense(other):
+ return np_op(self.todense(), other)
+ elif issparse(other):
+ if self.shape != other.shape:
+ raise ValueError(f"inconsistent shapes {self.shape=} {other.shape=}")
+ if self.ndim < 3: # shape is same so other.ndim < 3
+ cs_self = self if self.format in ('csr', 'csc') else self.tocsr()
+ return cs_self._binopt(other, f'_{np_op.__name__}_')
+ csr_self = self.reshape(1, -1).tocsr()
+ csr_other = other.reshape(1, -1).tocsr()
+ result = csr_self._binopt(csr_other, f'_{np_op.__name__}_')
+ return result.tocoo().reshape(self.shape)
+ else:
+ raise ValueError("Operands not compatible.")
+
+ def maximum(self, other):
+ """Element-wise maximum between this and another array/matrix."""
+ return self._maximum_minimum(other, np.maximum)
+
+ def minimum(self, other):
+ """Element-wise minimum between this and another array/matrix."""
+ return self._maximum_minimum(other, np.minimum)
+
+ def dot(self, other):
+ """Ordinary dot product
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.sparse import csr_array
+ >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+ >>> v = np.array([1, 0, -1])
+ >>> A.dot(v)
+ array([ 1, -3, -1], dtype=int64)
+
+ """
+ if np.isscalar(other):
+ return self * other
+ else:
+ return self @ other
+
+ def power(self, n, dtype=None):
+ """Element-wise power."""
+ return self.tocsr().power(n, dtype=dtype)
+
+ def _broadcast_to(self, shape, copy=False):
+ if self.shape == shape:
+ return self.copy() if copy else self
+ else:
+ return self.tocsr()._broadcast_to(shape, copy)
+
+ def _comparison(self, other, op):
+ # We convert to CSR format and use methods _binopt or _scalar_binopt
+ # If ndim>2 we reshape to 2D, compare and then reshape back to nD
+ if not (issparse(other) or isdense(other) or isscalarlike(other)):
+ if is_pydata_spmatrix(other):
+ # cannot compare with pydata other, but it might compare with us.
+ return NotImplemented
+ # 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_:
+ # numpy creates a 0d object array if all else fails.
+ # Not interpretable as an array; return NotImplemented so
+ # other's dunder methods can kick in if implemented.
+ return NotImplemented
+ # Allow custom sparse class indicated by attr sparse gh-6520
+ try:
+ other.shape
+ except AttributeError:
+ other = other_a
+
+ if isscalarlike(other):
+ if not op(0, other):
+ if np.isnan(other): # op is not `ne`, so results are all False.
+ return self.__class__(self.shape, dtype=np.bool_)
+ if self.ndim < 3:
+ cs_self = self if self.format in ('csc', 'csr') else self.tocsr()
+ return cs_self._scalar_binopt(other, op)
+ csr_self = self.reshape(1, -1).tocsr()
+ result = csr_self._scalar_binopt(other, op)
+ return result.tocoo().reshape(self.shape)
+ else:
+ warn(f"Comparing a sparse matrix with {other} using {op_sym[op]} "
+ f"is inefficient. Try using {op_sym[op_neg[op]]} instead.",
+ SparseEfficiencyWarning, stacklevel=3)
+ if np.isnan(other):
+ # op is `ne` cuz op(0, other) and isnan(other). Return all True.
+ return self.__class__(np.ones(self.shape, dtype=np.bool_))
+
+ # op is eq, le, or ge. Use negated op and then negate.
+ if self.ndim < 3:
+ cs_self = self if self.format in ('csc', 'csr') else self.tocsr()
+ inv = cs_self._scalar_binopt(other, op_neg[op])
+ all_true = cs_self.__class__(np.ones(cs_self.shape, dtype=np.bool_))
+ return all_true - inv
+
+ csr_self = self.reshape(1, -1).tocsr()
+ inv = csr_self._scalar_binopt(other, op_neg[op])
+ all_true = csr_self.__class__(np.ones(csr_self.shape, dtype=np.bool_))
+ result = all_true - inv
+ return result.tocoo().reshape(self.shape)
+
+ elif isdense(other):
+ return op(self.todense(), other)
+
+ elif issparse(other):
+ # TODO sparse broadcasting
+ if self.shape != other.shape:
+ # eq and ne return True or False instead of an array when the shapes
+ # don't match. Numpy doesn't do this. Is this what we want?
+ if op in (operator.eq, operator.ne):
+ return op is operator.ne
+ raise ValueError("inconsistent shape")
+
+ if self.ndim < 3:
+ cs_self = self if self.format in ('csc', 'csr') else self.tocsr()
+ cs_other = other
+ else:
+ cs_self = self.reshape(1, -1).tocsr()
+ cs_other = other.reshape(1, -1).tocsr()
+ if not op(0, 0):
+ result = cs_self._binopt(cs_other, f'_{op.__name__}_')
+ return result if self.ndim < 3 else result.tocoo().reshape(self.shape)
+ else:
+ # result will not be sparse. Use negated op and then negate.
+ warn(f"Comparing two sparse matrices using {op_sym[op]} "
+ f"is inefficient. Try using {op_sym[op_neg[op]]} instead.",
+ SparseEfficiencyWarning, stacklevel=3)
+ inv = cs_self._binopt(cs_other, f'_{op_neg[op].__name__}_')
+ all_true = cs_self.__class__(np.ones(cs_self.shape, dtype=np.bool_))
+ result = all_true - inv
+ return result if self.ndim < 3 else result.tocoo().reshape(self.shape)
+ else:
+ # cannot compare with other, but it might compare with us.
+ return NotImplemented
+
+ def __eq__(self, other):
+ return self._comparison(other, operator.eq)
+
+ def __ne__(self, other):
+ return self._comparison(other, operator.ne)
+
+ def __lt__(self, other):
+ return self._comparison(other, operator.lt)
+
+ def __gt__(self, other):
+ return self._comparison(other, operator.gt)
+
+ def __le__(self, other):
+ return self._comparison(other, operator.le)
+
+ def __ge__(self, other):
+ return self._comparison(other, operator.ge)
+
+ def __abs__(self):
+ return abs(self.tocsr())
+
+ def __round__(self, ndigits=0):
+ return round(self.tocsr(), ndigits=ndigits)
+
+ def _add_sparse(self, other):
+ return self.tocsr()._add_sparse(other)
+
+ def _add_dense(self, other):
+ return self.tocoo()._add_dense(other)
+
+ def _sub_sparse(self, other):
+ return self.tocsr()._sub_sparse(other)
+
+ def _sub_dense(self, other):
+ return self.todense() - other
+
+ def _rsub_dense(self, other):
+ # note: this can't be replaced by other + (-self) for unsigned types
+ return other - self.todense()
+
+ def __add__(self, other): # self + other
+ if isscalarlike(other):
+ if other == 0:
+ return self.copy()
+ # Now we would add this scalar to every element.
+ raise NotImplementedError('adding a nonzero scalar to a '
+ 'sparse array is not supported')
+ elif issparse(other):
+ if other.shape != self.shape:
+ raise ValueError("inconsistent shapes")
+ return self._add_sparse(other)
+ elif isdense(other):
+ other = np.broadcast_to(other, self.shape)
+ return self._add_dense(other)
+ else:
+ return NotImplemented
+
+ def __radd__(self,other): # other + self
+ return self.__add__(other)
+
+ def __sub__(self, other): # self - other
+ if isscalarlike(other):
+ if other == 0:
+ return self.copy()
+ raise NotImplementedError('subtracting a nonzero scalar from a '
+ 'sparse array is not supported')
+ elif issparse(other):
+ if other.shape != self.shape:
+ raise ValueError("inconsistent shapes")
+ return self._sub_sparse(other)
+ elif isdense(other):
+ other = np.broadcast_to(other, self.shape)
+ return self._sub_dense(other)
+ else:
+ return NotImplemented
+
+ def __rsub__(self,other): # other - self
+ if isscalarlike(other):
+ if other == 0:
+ return -self.copy()
+ raise NotImplementedError('subtracting a sparse array from a '
+ 'nonzero scalar is not supported')
+ elif isdense(other):
+ other = np.broadcast_to(other, self.shape)
+ return self._rsub_dense(other)
+ else:
+ return NotImplemented
+
+ def _matmul_dispatch(self, other):
+ """np.array-like matmul & `np.matrix`-like mul, i.e. `dot` or `NotImplemented`
+
+ interpret other and call one of the following
+ self._mul_scalar()
+ self._matmul_vector()
+ self._matmul_multivector()
+ self._matmul_sparse()
+ """
+ # This method has to be different from `__matmul__` because it is also
+ # called by sparse matrix classes.
+
+ # Currently matrix multiplication is only supported
+ # for 2D arrays. Hence we unpacked and use only the
+ # two last axes' lengths.
+ M, N = self._shape_as_2d
+
+ if other.__class__ is np.ndarray:
+ # Fast path for the most common case
+ if other.shape == (N,):
+ return self._matmul_vector(other)
+ elif other.shape == (N, 1):
+ result = self._matmul_vector(other.ravel())
+ if self.ndim == 1:
+ return result.reshape(1)
+ return result.reshape(M, 1)
+ elif other.ndim == 2 and other.shape[0] == N:
+ return self._matmul_multivector(other)
+
+ if isscalarlike(other):
+ # scalar value
+ return self._mul_scalar(other)
+
+ err_prefix = "matmul: dimension mismatch with signature"
+ if issparse(other):
+ if N != other.shape[0]:
+ raise ValueError(
+ f"{err_prefix} (n,k={N}),(k={other.shape[0]},m)->(n,m)"
+ )
+ return self._matmul_sparse(other)
+
+ # If it's a list or whatever, treat it like an array
+ other_a = np.asanyarray(other)
+ if other_a.ndim == 0 and other_a.dtype == np.object_:
+ # numpy creates a 0d object array if all else fails.
+ # Not interpretable as an array; return NotImplemented so that
+ # other's __rmatmul__ can kick in if that's implemented.
+ return NotImplemented
+ # Allow custom sparse class indicated by attr sparse gh-6520
+ try:
+ other.shape
+ except AttributeError:
+ other = other_a
+
+ if other.ndim == 1 or other.ndim == 2 and other.shape[1] == 1:
+ # dense row or column vector
+ if other.shape[0] != N:
+ raise ValueError(
+ f"{err_prefix} (n,k={N}),(k={other.shape[0]},1?)->(n,1?)"
+ )
+
+ result = self._matmul_vector(np.ravel(other))
+
+ if isinstance(other, np.matrix):
+ result = self._ascontainer(result)
+
+ if other.ndim == 2 and other.shape[1] == 1:
+ # If 'other' was an (nx1) column vector, reshape the result
+ if self.ndim == 1:
+ result = result.reshape(1)
+ else:
+ result = result.reshape(-1, 1)
+
+ return result
+
+ elif other.ndim == 2:
+ ##
+ # dense 2D array or matrix ("multivector")
+
+ if other.shape[0] != N:
+ raise ValueError(
+ f"{err_prefix} (n,k={N}),(k={other.shape[0]},m)->(n,m)"
+ )
+
+ result = self._matmul_multivector(np.asarray(other))
+
+ if isinstance(other, np.matrix):
+ result = self._ascontainer(result)
+
+ return result
+
+ else:
+ raise ValueError('could not interpret dimensions')
+
+ def __mul__(self, other):
+ return self.multiply(other)
+
+ def __rmul__(self, other): # other * self
+ return self.multiply(other)
+
+ # by default, use CSR for __mul__ handlers
+ def _mul_scalar(self, other):
+ return self.tocsr()._mul_scalar(other)
+
+ def _matmul_vector(self, other):
+ return self.tocsr()._matmul_vector(other)
+
+ def _matmul_multivector(self, other):
+ return self.tocsr()._matmul_multivector(other)
+
+ def _matmul_sparse(self, other):
+ return self.tocsr()._matmul_sparse(other)
+
+ def _rmatmul_dispatch(self, other):
+ if isscalarlike(other):
+ return self._mul_scalar(other)
+ else:
+ # Don't use asarray unless we have to
+ try:
+ tr = other.transpose()
+ except AttributeError:
+ tr = np.asarray(other).transpose()
+ ret = self.transpose()._matmul_dispatch(tr)
+ if ret is NotImplemented:
+ return NotImplemented
+ return ret.transpose()
+
+ #######################
+ # matmul (@) operator #
+ #######################
+
+ def __matmul__(self, other):
+ if isscalarlike(other):
+ raise ValueError("Scalar operands are not allowed, "
+ "use '*' instead")
+ return self._matmul_dispatch(other)
+
+ def __rmatmul__(self, other):
+ if isscalarlike(other):
+ raise ValueError("Scalar operands are not allowed, "
+ "use '*' instead")
+ return self._rmatmul_dispatch(other)
+
+ ####################
+ # Other Arithmetic #
+ ####################
+
+ def _divide(self, other, *, rdivide=False):
+ if not (issparse(other) or isdense(other) or isscalarlike(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_:
+ # numpy creates a 0d object array if all else fails.
+ # Not interpretable as an array; return NotImplemented so that
+ # other's __rtruediv__ can kick in if that's implemented.
+ return NotImplemented
+ # Allow custom sparse class indicated by attr sparse gh-6520
+ try:
+ other.shape
+ except AttributeError:
+ other = other_a
+
+ if isscalarlike(other):
+ if rdivide:
+ return np.divide(other, self.todense())
+
+ if np.can_cast(self.dtype, np.float64):
+ return self.astype(np.float64, copy=False)._mul_scalar(1 / other)
+ else:
+ r = self._mul_scalar(1 / other)
+
+ scalar_dtype = np.asarray(other).dtype
+ if (np.issubdtype(self.dtype, np.integer) and
+ np.issubdtype(scalar_dtype, np.integer)):
+ return r.astype(self.dtype, copy=False)
+ else:
+ return r
+
+ elif isdense(other):
+ if rdivide:
+ return np.divide(other, self.todense())
+
+ return self.multiply(np.divide(1, other))
+
+ elif issparse(other):
+ if rdivide:
+ return other._divide(self, rdivide=False)
+
+ csr_self = (self if self.ndim < 3 else self.reshape(1, -1)).tocsr()
+ csr_other = (other if self.ndim < 3 else other.reshape(1, -1)).tocsr()
+ if np.can_cast(self.dtype, np.float64):
+ csr_self = csr_self.astype(np.float64, copy=False)
+ result = csr_self._divide_sparse(csr_other)
+ return result if self.ndim < 3 else result.reshape(self.shape)
+ else:
+ # not scalar, dense or sparse. Return NotImplemented so
+ # other's __rtruediv__ can kick in if that's implemented.
+ return NotImplemented
+
+ def __truediv__(self, other):
+ return self._divide(other)
+
+ def __rtruediv__(self, other):
+ # Implementing this as the inverse would be too magical -- bail out
+ return NotImplemented
+
+ def __neg__(self):
+ return -self.tocsr()
+
+ def __iadd__(self, other):
+ return NotImplemented
+
+ def __isub__(self, other):
+ return NotImplemented
+
+ def __imul__(self, other):
+ return NotImplemented
+
+ def __itruediv__(self, other):
+ return NotImplemented
+
+ def __pow__(self, *args, **kwargs):
+ return self.power(*args, **kwargs)
+
+ def transpose(self, axes=None, copy=False):
+ """
+ Reverses the dimensions of the sparse array/matrix.
+
+ Parameters
+ ----------
+ axes : None, optional
+ This argument is in the signature *solely* for NumPy
+ compatibility reasons. Do not pass in anything except
+ for the default value.
+ copy : bool, optional
+ Indicates whether or not attributes of `self` should be
+ copied whenever possible. The degree to which attributes
+ are copied varies depending on the type of sparse array/matrix
+ being used.
+
+ Returns
+ -------
+ p : `self` with the dimensions reversed.
+
+ Notes
+ -----
+ If `self` is a `csr_array` or a `csc_array`, then this will return a
+ `csc_array` or a `csr_array`, respectively.
+
+ See Also
+ --------
+ numpy.transpose : NumPy's implementation of 'transpose' for ndarrays
+ """
+ return self.tocsr(copy=copy).transpose(axes=axes, copy=False)
+
+ def conjugate(self, copy=True):
+ """Element-wise complex conjugation.
+
+ If the array/matrix is of non-complex data type and `copy` is False,
+ this method does nothing and the data is not copied.
+
+ Parameters
+ ----------
+ copy : bool, optional
+ If True, the result is guaranteed to not share data with self.
+
+ Returns
+ -------
+ A : The element-wise complex conjugate.
+
+ """
+ if np.issubdtype(self.dtype, np.complexfloating):
+ return self.tocsr(copy=copy).conjugate(copy=False)
+ elif copy:
+ return self.copy()
+ else:
+ return self
+
+ def conj(self, copy=True):
+ return self.conjugate(copy=copy)
+
+ conj.__doc__ = conjugate.__doc__
+
+ def _real(self):
+ return self.tocsr()._real()
+
+ def _imag(self):
+ return self.tocsr()._imag()
+
+ def nonzero(self):
+ """Nonzero indices of the array/matrix.
+
+ Returns a tuple of arrays (row,col) containing the indices
+ of the non-zero elements of the array.
+
+ Examples
+ --------
+ >>> from scipy.sparse import csr_array
+ >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+ >>> A.nonzero()
+ (array([0, 0, 1, 2, 2], dtype=int32), array([0, 1, 2, 0, 2], dtype=int32))
+
+ """
+
+ # convert to COOrdinate format
+ A = self.tocoo()
+ nz_mask = A.data != 0
+ return tuple(idx[nz_mask] for idx in A.coords)
+
+ def _getcol(self, j):
+ """Returns a copy of column j of the array, as an (m x 1) sparse
+ array (column vector).
+ """
+ if self.ndim == 1:
+ raise ValueError("getcol not provided for 1d arrays. Use indexing A[j]")
+ # Subclasses should override this method for efficiency.
+ # Post-multiply by a (n x 1) column vector 'a' containing all zeros
+ # except for a_j = 1
+ N = self.shape[-1]
+ if j < 0:
+ j += N
+ if j < 0 or j >= N:
+ raise IndexError("index out of bounds")
+ col_selector = self._csc_container(([1], [[j], [0]]),
+ shape=(N, 1), dtype=self.dtype)
+ result = self @ col_selector
+ return result
+
+ def _getrow(self, i):
+ """Returns a copy of row i of the array, as a (1 x n) sparse
+ array (row vector).
+ """
+ if self.ndim == 1:
+ raise ValueError("getrow not meaningful for a 1d array")
+ # Subclasses should override this method for efficiency.
+ # Pre-multiply by a (1 x m) row vector 'a' containing all zeros
+ # except for a_i = 1
+ M = self.shape[0]
+ if i < 0:
+ i += M
+ if i < 0 or i >= M:
+ raise IndexError("index out of bounds")
+ row_selector = self._csr_container(([1], [[0], [i]]),
+ shape=(1, M), dtype=self.dtype)
+ return row_selector @ self
+
+ # The following dunder methods cannot be implemented.
+ #
+ # def __array__(self):
+ # # Sparse matrices rely on NumPy wrapping them in object arrays under
+ # # the hood to make unary ufuncs work on them. So we cannot raise
+ # # TypeError here - which would be handy to not give users object
+ # # arrays they probably don't want (they're looking for `.toarray()`).
+ # #
+ # # Conversion with `toarray()` would also break things because of the
+ # # behavior discussed above, plus we want to avoid densification by
+ # # accident because that can too easily blow up memory.
+ #
+ # def __array_ufunc__(self):
+ # # We cannot implement __array_ufunc__ due to mismatching semantics.
+ # # See gh-7707 and gh-7349 for details.
+ #
+ # def __array_function__(self):
+ # # We cannot implement __array_function__ due to mismatching semantics.
+ # # See gh-10362 for details.
+
+ def todense(self, order=None, out=None):
+ """
+ Return a dense representation of this sparse array.
+
+ Parameters
+ ----------
+ order : {'C', 'F'}, optional
+ Whether to store multi-dimensional data in C (row-major)
+ or Fortran (column-major) order in memory. The default
+ is 'None', which provides no ordering guarantees.
+ Cannot be specified in conjunction with the `out`
+ argument.
+
+ out : ndarray, 2-D, optional
+ If specified, uses this array as the output buffer
+ instead of allocating a new array to return. The
+ provided array must have the same shape and dtype as
+ the sparse array on which you are calling the method.
+
+ Returns
+ -------
+ arr : ndarray, 2-D
+ An array with the same shape and containing the same
+ data represented by the sparse array, with the requested
+ memory order. If `out` was passed, the same object is
+ returned after being modified in-place to contain the
+ appropriate values.
+ """
+ return self._ascontainer(self.toarray(order=order, out=out))
+
+ def toarray(self, order=None, out=None):
+ """
+ Return a dense ndarray representation of this sparse array/matrix.
+
+ Parameters
+ ----------
+ order : {'C', 'F'}, optional
+ Whether to store multidimensional data in C (row-major)
+ or Fortran (column-major) order in memory. The default
+ is 'None', which provides no ordering guarantees.
+ Cannot be specified in conjunction with the `out`
+ argument.
+
+ out : ndarray, 2-D, optional
+ If specified, uses this array as the output buffer
+ instead of allocating a new array to return. The provided
+ array must have the same shape and dtype as the sparse
+ array/matrix on which you are calling the method. For most
+ sparse types, `out` is required to be memory contiguous
+ (either C or Fortran ordered).
+
+ Returns
+ -------
+ arr : ndarray, 2-D
+ An array with the same shape and containing the same
+ data represented by the sparse array/matrix, with the requested
+ memory order. If `out` was passed, the same object is
+ returned after being modified in-place to contain the
+ appropriate values.
+ """
+ return self.tocoo(copy=False).toarray(order=order, out=out)
+
+ # Any sparse array format deriving from _spbase must define one of
+ # tocsr or tocoo. The other conversion methods may be implemented for
+ # efficiency, but are not required.
+ def tocsr(self, copy=False):
+ """Convert this array/matrix to Compressed Sparse Row format.
+
+ With copy=False, the data/indices may be shared between this array/matrix and
+ the resultant csr_array/matrix.
+ """
+ return self.tocoo(copy=copy).tocsr(copy=False)
+
+ def todok(self, copy=False):
+ """Convert this array/matrix to Dictionary Of Keys format.
+
+ With copy=False, the data/indices may be shared between this array/matrix and
+ the resultant dok_array/matrix.
+ """
+ return self.tocoo(copy=copy).todok(copy=False)
+
+ def tocoo(self, copy=False):
+ """Convert this array/matrix to COOrdinate format.
+
+ With copy=False, the data/indices may be shared between this array/matrix and
+ the resultant coo_array/matrix.
+ """
+ return self.tocsr(copy=False).tocoo(copy=copy)
+
+ def tolil(self, copy=False):
+ """Convert this array/matrix to List of Lists format.
+
+ With copy=False, the data/indices may be shared between this array/matrix and
+ the resultant lil_array/matrix.
+ """
+ return self.tocsr(copy=False).tolil(copy=copy)
+
+ def todia(self, copy=False):
+ """Convert this array/matrix to sparse DIAgonal format.
+
+ With copy=False, the data/indices may be shared between this array/matrix and
+ the resultant dia_array/matrix.
+ """
+ return self.tocoo(copy=copy).todia(copy=False)
+
+ def tobsr(self, blocksize=None, copy=False):
+ """Convert this array/matrix to Block Sparse Row format.
+
+ With copy=False, the data/indices may be shared between this array/matrix and
+ the resultant bsr_array/matrix.
+
+ When blocksize=(R, C) is provided, it will be used for construction of
+ the bsr_array/matrix.
+ """
+ return self.tocsr(copy=False).tobsr(blocksize=blocksize, copy=copy)
+
+ def tocsc(self, copy=False):
+ """Convert this array/matrix to Compressed Sparse Column format.
+
+ With copy=False, the data/indices may be shared between this array/matrix and
+ the resultant csc_array/matrix.
+ """
+ return self.tocsr(copy=copy).tocsc(copy=False)
+
+ def copy(self):
+ """Returns a copy of this array/matrix.
+
+ No data/indices will be shared between the returned value and current
+ array/matrix.
+ """
+ return self.__class__(self, copy=True)
+
+ def sum(self, axis=None, dtype=None, out=None):
+ """
+ Sum the array/matrix elements over a given axis.
+
+ Parameters
+ ----------
+ axis : {-2, -1, 0, 1, None} optional
+ Axis along which the sum is computed. The default is to
+ compute the sum of all the array/matrix elements, returning a scalar
+ (i.e., `axis` = `None`).
+ dtype : dtype, optional
+ The type of the returned array/matrix and of the accumulator in which
+ the elements are summed. The dtype of `a` is used by default
+ unless `a` has an integer dtype of less precision than the default
+ platform integer. In that case, if `a` is signed then the platform
+ integer is used while if `a` is unsigned then an unsigned integer
+ of the same precision as the platform integer is used.
+
+ .. versionadded:: 0.18.0
+
+ out : np.matrix, optional
+ Alternative output matrix in which to place the result. It must
+ have the same shape as the expected output, but the type of the
+ output values will be cast if necessary.
+
+ .. versionadded:: 0.18.0
+
+ Returns
+ -------
+ sum_along_axis : np.matrix
+ A matrix with the same shape as `self`, with the specified
+ axis removed.
+
+ See Also
+ --------
+ numpy.matrix.sum : NumPy's implementation of 'sum' for matrices
+
+ """
+ axis = validateaxis(axis, ndim=self.ndim)
+
+ # Mimic numpy's casting.
+ res_dtype = get_sum_dtype(self.dtype)
+
+ # Note: all valid 1D axis values are canonically `None`.
+ if axis is None:
+ if self.nnz == 0:
+ return np.sum(self._ascontainer([0]), dtype=dtype or res_dtype, out=out)
+ return np.sum(self._ascontainer(_todata(self)), dtype=dtype, out=out)
+ elif isspmatrix(self):
+ # Ensure spmatrix sums stay 2D
+ new_shape = (1, self.shape[1]) if axis == (0,) else (self.shape[0], 1)
+ else:
+ new_shape = tuple(self.shape[i] for i in range(self.ndim) if i not in axis)
+
+ if out is None:
+ # create out array with desired dtype
+ out = self._ascontainer(np.zeros(new_shape, dtype=dtype or res_dtype))
+ else:
+ if out.shape != new_shape:
+ raise ValueError("out dimensions do not match shape")
+
+ if self.ndim > 2:
+ return self._sum_nd(axis, res_dtype, out)
+
+ # We use multiplication by a matrix of ones to sum.
+ # For some sparse array formats more efficient methods are
+ # possible -- these should override this function.
+ if axis == (0,):
+ ones = self._ascontainer(np.ones((1, self.shape[0]), dtype=res_dtype))
+ # sets dtype while loading into out
+ out[...] = (ones @ self).reshape(new_shape)
+ else: # axis == (1,)
+ ones = self._ascontainer(np.ones((self.shape[1], 1), dtype=res_dtype))
+ # sets dtype while loading into out
+ out[...] = (self @ ones).reshape(new_shape)
+ return out
+
+ def mean(self, axis=None, dtype=None, out=None):
+ """
+ Compute the arithmetic mean along the specified axis.
+
+ Returns the average of the array/matrix elements. The average is taken
+ over all elements in the array/matrix by default, otherwise over the
+ specified axis. `float64` intermediate and return values are used
+ for integer inputs.
+
+ Parameters
+ ----------
+ axis : {-2, -1, 0, 1, None} optional
+ Axis along which the mean is computed. The default is to compute
+ the mean of all elements in the array/matrix (i.e., `axis` = `None`).
+ dtype : data-type, optional
+ Type to use in computing the mean. For integer inputs, the default
+ is `float64`; for floating point inputs, it is the same as the
+ input dtype.
+
+ .. versionadded:: 0.18.0
+
+ out : np.matrix, optional
+ Alternative output matrix in which to place the result. It must
+ have the same shape as the expected output, but the type of the
+ output values will be cast if necessary.
+
+ .. versionadded:: 0.18.0
+
+ Returns
+ -------
+ m : np.matrix
+
+ See Also
+ --------
+ numpy.matrix.mean : NumPy's implementation of 'mean' for matrices
+
+ """
+ axis = validateaxis(axis, ndim=self.ndim)
+
+ integral = (np.issubdtype(self.dtype, np.integer) or
+ np.issubdtype(self.dtype, np.bool_))
+
+ # intermediate dtype for summation
+ inter_dtype = np.float64 if integral else self.dtype
+ inter_self = self.astype(inter_dtype, copy=False)
+
+ if axis is None:
+ denom = math.prod(self.shape)
+ else:
+ denom = math.prod(self.shape[ax] for ax in axis)
+ res = (inter_self * (1.0 / denom)).sum(axis=axis, dtype=inter_dtype, out=out)
+ if dtype is not None and out is None:
+ return res.astype(dtype, copy=False)
+ return res
+
+
+ def diagonal(self, k=0):
+ """Returns the kth diagonal of the array/matrix.
+
+ Parameters
+ ----------
+ k : int, optional
+ Which diagonal to get, corresponding to elements a[i, i+k].
+ Default: 0 (the main diagonal).
+
+ .. versionadded:: 1.0
+
+ See also
+ --------
+ numpy.diagonal : Equivalent numpy function.
+
+ Examples
+ --------
+ >>> from scipy.sparse import csr_array
+ >>> A = csr_array([[1, 2, 0], [0, 0, 3], [4, 0, 5]])
+ >>> A.diagonal()
+ array([1, 0, 5])
+ >>> A.diagonal(k=1)
+ array([2, 3])
+ """
+ return self.tocsr().diagonal(k=k)
+
+ def trace(self, offset=0):
+ """Returns the sum along diagonals of the sparse array/matrix.
+
+ Parameters
+ ----------
+ offset : int, optional
+ Which diagonal to get, corresponding to elements a[i, i+offset].
+ Default: 0 (the main diagonal).
+
+ """
+ return self.diagonal(k=offset).sum()
+
+ def setdiag(self, values, k=0):
+ """
+ Set diagonal or off-diagonal elements of the array/matrix.
+
+ Parameters
+ ----------
+ values : array_like
+ New values of the diagonal elements.
+
+ Values may have any length. If the diagonal is longer than values,
+ then the remaining diagonal entries will not be set. If values are
+ longer than the diagonal, then the remaining values are ignored.
+
+ If a scalar value is given, all of the diagonal is set to it.
+
+ k : int, optional
+ Which off-diagonal to set, corresponding to elements a[i,i+k].
+ Default: 0 (the main diagonal).
+
+ """
+ M, N = self.shape
+ if (k > 0 and k >= N) or (k < 0 and -k >= M):
+ raise ValueError("k exceeds array dimensions")
+ self._setdiag(np.asarray(values), k)
+
+ def _setdiag(self, values, k):
+ """This part of the implementation gets overridden by the
+ different formats.
+ """
+ M, N = self.shape
+ if k < 0:
+ if values.ndim == 0:
+ # broadcast
+ max_index = min(M+k, N)
+ for i in range(max_index):
+ self[i - k, i] = values
+ else:
+ max_index = min(M+k, N, len(values))
+ if max_index <= 0:
+ return
+ for i, v in enumerate(values[:max_index]):
+ self[i - k, i] = v
+ else:
+ if values.ndim == 0:
+ # broadcast
+ max_index = min(M, N-k)
+ for i in range(max_index):
+ self[i, i + k] = values
+ else:
+ max_index = min(M, N-k, len(values))
+ if max_index <= 0:
+ return
+ for i, v in enumerate(values[:max_index]):
+ self[i, i + k] = v
+
+ def _process_toarray_args(self, order, out):
+ if out is not None:
+ if order is not None:
+ raise ValueError('order cannot be specified if out '
+ 'is not None')
+ if out.shape != self.shape or out.dtype != self.dtype:
+ raise ValueError('out array must be same dtype and shape as '
+ 'sparse array')
+ out[...] = 0.
+ return out
+ else:
+ return np.zeros(self.shape, dtype=self.dtype, order=order)
+
+ def _get_index_dtype(self, arrays=(), maxval=None, check_contents=False):
+ """
+ Determine index dtype for array.
+
+ This wraps _sputils.get_index_dtype, providing compatibility for both
+ array and matrix API sparse matrices. Matrix API sparse matrices would
+ attempt to downcast the indices - which can be computationally
+ expensive and undesirable for users. The array API changes this
+ behaviour.
+
+ See discussion: https://github.com/scipy/scipy/issues/16774
+
+ The get_index_dtype import is due to implementation details of the test
+ suite. It allows the decorator ``with_64bit_maxval_limit`` to mock a
+ lower int32 max value for checks on the matrix API's downcasting
+ behaviour.
+ """
+ from ._sputils import get_index_dtype
+
+ # Don't check contents for array API
+ return get_index_dtype(arrays,
+ maxval,
+ (check_contents and not isinstance(self, sparray)))
+
+
+class sparray:
+ """A namespace class to separate sparray from spmatrix"""
+
+ @classmethod
+ def __class_getitem__(cls, arg, /):
+ """
+ Return a parametrized wrapper around the `~scipy.sparse.sparray` type.
+
+ .. versionadded:: 1.16.0
+
+ Returns
+ -------
+ alias : types.GenericAlias
+ A parametrized `~scipy.sparse.sparray` type.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.sparse import coo_array
+
+ >>> coo_array[np.int8, tuple[int]]
+ scipy.sparse._coo.coo_array[numpy.int8, tuple[int]]
+ """
+ from types import GenericAlias
+ return GenericAlias(cls, arg)
+
+
+sparray.__doc__ = _spbase.__doc__
+
+
+def isspmatrix(x):
+ """Is `x` of a sparse matrix type?
+
+ Parameters
+ ----------
+ x
+ object to check for being a sparse matrix
+
+ Returns
+ -------
+ bool
+ True if `x` is a sparse matrix, False otherwise
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.sparse import csr_array, csr_matrix, isspmatrix
+ >>> isspmatrix(csr_matrix([[5]]))
+ True
+ >>> isspmatrix(csr_array([[5]]))
+ False
+ >>> isspmatrix(np.array([[5]]))
+ False
+ >>> isspmatrix(5)
+ False
+ """
+ return isinstance(x, spmatrix)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_bsr.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_bsr.py
new file mode 100644
index 0000000000000000000000000000000000000000..b996f5ccef20a5aa73a9b9346525cf2187bded1c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_bsr.py
@@ -0,0 +1,882 @@
+"""Compressed Block Sparse Row format"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['bsr_array', 'bsr_matrix', 'isspmatrix_bsr']
+
+from warnings import warn
+
+import numpy as np
+
+from scipy._lib._util import copy_if_needed
+from ._matrix import spmatrix
+from ._data import _data_matrix, _minmax_mixin
+from ._compressed import _cs_matrix
+from ._base import issparse, _formats, _spbase, sparray
+from ._sputils import (isshape, getdtype, getdata, to_native, upcast,
+ check_shape)
+from . import _sparsetools
+from ._sparsetools import (bsr_matvec, bsr_matvecs, csr_matmat_maxnnz,
+ bsr_matmat, bsr_transpose, bsr_sort_indices,
+ bsr_tocsr)
+
+
+class _bsr_base(_cs_matrix, _minmax_mixin):
+ _format = 'bsr'
+
+ def __init__(self, arg1, shape=None, dtype=None, copy=False,
+ blocksize=None, *, maxprint=None):
+ _data_matrix.__init__(self, arg1, maxprint=maxprint)
+
+ if issparse(arg1):
+ if arg1.format == self.format and copy:
+ arg1 = arg1.copy()
+ else:
+ arg1 = arg1.tobsr(blocksize=blocksize)
+ self.indptr, self.indices, self.data, self._shape = (
+ arg1.indptr, arg1.indices, arg1.data, arg1._shape
+ )
+
+ elif isinstance(arg1,tuple):
+ if isshape(arg1):
+ # it's a tuple of matrix dimensions (M,N)
+ self._shape = check_shape(arg1)
+ M,N = self.shape
+ # process blocksize
+ if blocksize is None:
+ blocksize = (1,1)
+ else:
+ if not isshape(blocksize):
+ raise ValueError(f'invalid blocksize={blocksize}')
+ blocksize = tuple(blocksize)
+ self.data = np.zeros((0,) + blocksize, getdtype(dtype, default=float))
+
+ R,C = blocksize
+ if (M % R) != 0 or (N % C) != 0:
+ raise ValueError('shape must be multiple of blocksize')
+
+ # Select index dtype large enough to pass array and
+ # scalar parameters to sparsetools
+ idx_dtype = self._get_index_dtype(maxval=max(M//R, N//C, R, C))
+ self.indices = np.zeros(0, dtype=idx_dtype)
+ self.indptr = np.zeros(M//R + 1, dtype=idx_dtype)
+
+ elif len(arg1) == 2:
+ # (data,(row,col)) format
+ coo = self._coo_container(arg1, dtype=dtype, shape=shape)
+ bsr = coo.tobsr(blocksize=blocksize)
+ self.indptr, self.indices, self.data, self._shape = (
+ bsr.indptr, bsr.indices, bsr.data, bsr._shape
+ )
+
+ elif len(arg1) == 3:
+ # (data,indices,indptr) format
+ (data, indices, indptr) = arg1
+
+ # Select index dtype large enough to pass array and
+ # scalar parameters to sparsetools
+ maxval = 1
+ if shape is not None:
+ maxval = max(shape)
+ if blocksize is not None:
+ maxval = max(maxval, max(blocksize))
+ idx_dtype = self._get_index_dtype((indices, indptr), maxval=maxval,
+ check_contents=True)
+ if not copy:
+ copy = copy_if_needed
+ self.indices = np.array(indices, copy=copy, dtype=idx_dtype)
+ self.indptr = np.array(indptr, copy=copy, dtype=idx_dtype)
+ self.data = getdata(data, copy=copy, dtype=dtype)
+ if self.data.ndim != 3:
+ raise ValueError(
+ f'BSR data must be 3-dimensional, got shape={self.data.shape}'
+ )
+ if blocksize is not None:
+ if not isshape(blocksize):
+ raise ValueError(f'invalid blocksize={blocksize}')
+ if tuple(blocksize) != self.data.shape[1:]:
+ raise ValueError(
+ f'mismatching blocksize={blocksize}'
+ f' vs {self.data.shape[1:]}'
+ )
+ else:
+ raise ValueError('unrecognized bsr_array constructor usage')
+ else:
+ # must be dense
+ try:
+ arg1 = np.asarray(arg1)
+ except Exception as e:
+ raise ValueError("unrecognized form for "
+ f"{self.format}_matrix constructor") from e
+ if isinstance(self, sparray) and arg1.ndim != 2:
+ raise ValueError(f"BSR arrays don't support {arg1.ndim}D input. Use 2D")
+ arg1 = self._coo_container(arg1, dtype=dtype).tobsr(blocksize=blocksize)
+ self.indptr, self.indices, self.data, self._shape = (
+ arg1.indptr, arg1.indices, arg1.data, arg1._shape
+ )
+
+ if shape is not None:
+ self._shape = check_shape(shape)
+ else:
+ if self.shape is None:
+ # shape not already set, try to infer dimensions
+ try:
+ M = len(self.indptr) - 1
+ N = self.indices.max() + 1
+ except Exception as e:
+ raise ValueError('unable to infer matrix dimensions') from e
+ else:
+ R,C = self.blocksize
+ self._shape = check_shape((M*R,N*C))
+
+ if self.shape is None:
+ if shape is None:
+ # TODO infer shape here
+ raise ValueError('need to infer shape')
+ else:
+ self._shape = check_shape(shape)
+
+ if dtype is not None:
+ self.data = self.data.astype(getdtype(dtype, self.data), copy=False)
+
+ self.check_format(full_check=False)
+
+ def check_format(self, full_check=True):
+ """Check whether the array/matrix respects the BSR format.
+
+ Parameters
+ ----------
+ full_check : bool, optional
+ If `True`, run rigorous check, scanning arrays for valid values.
+ Note that activating those check might copy arrays for casting,
+ modifying indices and index pointers' inplace.
+ If `False`, run basic checks on attributes. O(1) operations.
+ Default is `True`.
+ """
+ M,N = self.shape
+ R,C = self.blocksize
+
+ # index arrays should have integer data types
+ if self.indptr.dtype.kind != 'i':
+ warn(f"indptr array has non-integer dtype ({self.indptr.dtype.name})",
+ stacklevel=2)
+ if self.indices.dtype.kind != 'i':
+ warn(f"indices array has non-integer dtype ({self.indices.dtype.name})",
+ stacklevel=2)
+
+ # check array shapes
+ if self.indices.ndim != 1 or self.indptr.ndim != 1:
+ raise ValueError("indices, and indptr should be 1-D")
+ if self.data.ndim != 3:
+ raise ValueError("data should be 3-D")
+
+ # check index pointer
+ if (len(self.indptr) != M//R + 1):
+ raise ValueError(
+ f"index pointer size ({len(self.indptr)}) should be ({M//R + 1})"
+ )
+ if (self.indptr[0] != 0):
+ raise ValueError("index pointer should start with 0")
+
+ # check index and data arrays
+ if (len(self.indices) != len(self.data)):
+ raise ValueError("indices and data should have the same size")
+ if (self.indptr[-1] > len(self.indices)):
+ raise ValueError("Last value of index pointer should be less than "
+ "the size of index and data arrays")
+
+ self.prune()
+
+ if full_check:
+ # check format validity (more expensive)
+ if self.nnz > 0:
+ if self.indices.max() >= N//C:
+ raise ValueError(
+ f"column index values must be < {N//C}"
+ f" (now max {self.indices.max()})"
+ )
+ if self.indices.min() < 0:
+ raise ValueError("column index values must be >= 0")
+ if np.diff(self.indptr).min() < 0:
+ raise ValueError("index pointer values must form a "
+ "non-decreasing sequence")
+
+ idx_dtype = self._get_index_dtype((self.indices, self.indptr))
+ self.indptr = np.asarray(self.indptr, dtype=idx_dtype)
+ self.indices = np.asarray(self.indices, dtype=idx_dtype)
+ self.data = to_native(self.data)
+ # if not self.has_sorted_indices():
+ # warn('Indices were not in sorted order. Sorting indices.')
+ # self.sort_indices(check_first=False)
+
+ @property
+ def blocksize(self) -> tuple:
+ """Block size of the matrix."""
+ return self.data.shape[1:]
+
+ def _getnnz(self, axis=None):
+ if axis is not None:
+ raise NotImplementedError("_getnnz over an axis is not implemented "
+ "for BSR format")
+ R, C = self.blocksize
+ return int(self.indptr[-1]) * R * C
+
+ _getnnz.__doc__ = _spbase._getnnz.__doc__
+
+ def count_nonzero(self, axis=None):
+ if axis is not None:
+ raise NotImplementedError(
+ "count_nonzero over axis is not implemented for BSR format."
+ )
+ return np.count_nonzero(self._deduped_data())
+
+ count_nonzero.__doc__ = _spbase.count_nonzero.__doc__
+
+ def __repr__(self):
+ _, fmt = _formats[self.format]
+ sparse_cls = 'array' if isinstance(self, sparray) else 'matrix'
+ b = 'x'.join(str(x) for x in self.blocksize)
+ return (
+ f"<{fmt} sparse {sparse_cls} of dtype '{self.dtype}'\n"
+ f"\twith {self.nnz} stored elements (blocksize={b}) and shape {self.shape}>"
+ )
+
+ def diagonal(self, k=0):
+ rows, cols = self.shape
+ if k <= -rows or k >= cols:
+ return np.empty(0, dtype=self.data.dtype)
+ R, C = self.blocksize
+ y = np.zeros(min(rows + min(k, 0), cols - max(k, 0)),
+ dtype=upcast(self.dtype))
+ _sparsetools.bsr_diagonal(k, rows // R, cols // C, R, C,
+ self.indptr, self.indices,
+ np.ravel(self.data), y)
+ return y
+
+ diagonal.__doc__ = _spbase.diagonal.__doc__
+
+ ##########################
+ # NotImplemented methods #
+ ##########################
+
+ def __getitem__(self,key):
+ raise NotImplementedError
+
+ def __setitem__(self,key,val):
+ raise NotImplementedError
+
+ ######################
+ # Arithmetic methods #
+ ######################
+
+ def _add_dense(self, other):
+ return self.tocoo(copy=False)._add_dense(other)
+
+ def _matmul_vector(self, other):
+ M,N = self.shape
+ R,C = self.blocksize
+
+ result = np.zeros(self.shape[0], dtype=upcast(self.dtype, other.dtype))
+
+ bsr_matvec(M//R, N//C, R, C,
+ self.indptr, self.indices, self.data.ravel(),
+ other, result)
+
+ return result
+
+ def _matmul_multivector(self,other):
+ R,C = self.blocksize
+ M,N = self.shape
+ n_vecs = other.shape[1] # number of column vectors
+
+ result = np.zeros((M,n_vecs), dtype=upcast(self.dtype,other.dtype))
+
+ bsr_matvecs(M//R, N//C, n_vecs, R, C,
+ self.indptr, self.indices, self.data.ravel(),
+ other.ravel(), result.ravel())
+
+ return result
+
+ def _matmul_sparse(self, other):
+ M, K1 = self.shape
+ K2, N = other.shape
+
+ R,n = self.blocksize
+
+ # convert to this format
+ if other.format == "bsr":
+ C = other.blocksize[1]
+ else:
+ C = 1
+
+ if other.format == "csr" and n == 1:
+ other = other.tobsr(blocksize=(n,C), copy=False) # lightweight conversion
+ else:
+ other = other.tobsr(blocksize=(n,C))
+
+ idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+ other.indptr, other.indices))
+
+ n_brow = M // R
+ n_bcol = N // C
+ bnnz = csr_matmat_maxnnz(n_brow, n_bcol,
+ self.indptr.astype(idx_dtype, copy=False),
+ self.indices.astype(idx_dtype, copy=False),
+ other.indptr.astype(idx_dtype, copy=False),
+ other.indices.astype(idx_dtype, copy=False))
+
+ idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+ other.indptr, other.indices),
+ maxval=bnnz)
+ indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
+ indices = np.empty(bnnz, dtype=idx_dtype)
+ data = np.empty(R*C*bnnz, dtype=upcast(self.dtype,other.dtype))
+
+ bsr_matmat(bnnz, n_brow, n_bcol, R, C, n,
+ self.indptr.astype(idx_dtype, copy=False),
+ self.indices.astype(idx_dtype, copy=False),
+ np.ravel(self.data),
+ other.indptr.astype(idx_dtype, copy=False),
+ other.indices.astype(idx_dtype, copy=False),
+ np.ravel(other.data),
+ indptr,
+ indices,
+ data)
+
+ data = data.reshape(-1,R,C)
+
+ # TODO eliminate zeros
+
+ return self._bsr_container(
+ (data, indices, indptr), shape=(M, N), blocksize=(R, C)
+ )
+
+ ######################
+ # Conversion methods #
+ ######################
+
+ def tobsr(self, blocksize=None, copy=False):
+ """Convert this array/matrix into Block Sparse Row Format.
+
+ With copy=False, the data/indices may be shared between this
+ array/matrix and the resultant bsr_array/bsr_matrix.
+
+ If blocksize=(R, C) is provided, it will be used for determining
+ block size of the bsr_array/bsr_matrix.
+ """
+ if blocksize not in [None, self.blocksize]:
+ return self.tocsr().tobsr(blocksize=blocksize)
+ if copy:
+ return self.copy()
+ else:
+ return self
+
+ def tocsr(self, copy=False):
+ M, N = self.shape
+ R, C = self.blocksize
+ nnz = self.nnz
+ idx_dtype = self._get_index_dtype((self.indptr, self.indices),
+ maxval=max(nnz, N))
+ indptr = np.empty(M + 1, dtype=idx_dtype)
+ indices = np.empty(nnz, dtype=idx_dtype)
+ data = np.empty(nnz, dtype=upcast(self.dtype))
+
+ bsr_tocsr(M // R, # n_brow
+ N // C, # n_bcol
+ R, C,
+ self.indptr.astype(idx_dtype, copy=False),
+ self.indices.astype(idx_dtype, copy=False),
+ self.data,
+ indptr,
+ indices,
+ data)
+ return self._csr_container((data, indices, indptr), shape=self.shape)
+
+ tocsr.__doc__ = _spbase.tocsr.__doc__
+
+ def tocsc(self, copy=False):
+ return self.tocsr(copy=False).tocsc(copy=copy)
+
+ tocsc.__doc__ = _spbase.tocsc.__doc__
+
+ def tocoo(self, copy=True):
+ """Convert this array/matrix to COOrdinate format.
+
+ When copy=False the data array will be shared between
+ this array/matrix and the resultant coo_array/coo_matrix.
+ """
+
+ M,N = self.shape
+ R,C = self.blocksize
+
+ indptr_diff = np.diff(self.indptr)
+ if indptr_diff.dtype.itemsize > np.dtype(np.intp).itemsize:
+ # Check for potential overflow
+ indptr_diff_limited = indptr_diff.astype(np.intp)
+ if np.any(indptr_diff_limited != indptr_diff):
+ raise ValueError("Matrix too big to convert")
+ indptr_diff = indptr_diff_limited
+
+ idx_dtype = self._get_index_dtype(maxval=max(M, N))
+ row = (R * np.arange(M//R, dtype=idx_dtype)).repeat(indptr_diff)
+ row = row.repeat(R*C).reshape(-1,R,C)
+ row += np.tile(np.arange(R, dtype=idx_dtype).reshape(-1,1), (1,C))
+ row = row.reshape(-1)
+
+ col = ((C * self.indices).astype(idx_dtype, copy=False)
+ .repeat(R*C).reshape(-1,R,C))
+ col += np.tile(np.arange(C, dtype=idx_dtype), (R,1))
+ col = col.reshape(-1)
+
+ data = self.data.reshape(-1)
+
+ if copy:
+ data = data.copy()
+
+ return self._coo_container(
+ (data, (row, col)), shape=self.shape
+ )
+
+ def toarray(self, order=None, out=None):
+ return self.tocoo(copy=False).toarray(order=order, out=out)
+
+ toarray.__doc__ = _spbase.toarray.__doc__
+
+ def transpose(self, axes=None, copy=False):
+ if axes is not None and axes != (1, 0):
+ raise ValueError("Sparse matrices do not support "
+ "an 'axes' parameter because swapping "
+ "dimensions is the only logical permutation.")
+
+ R, C = self.blocksize
+ M, N = self.shape
+ NBLK = self.nnz//(R*C)
+
+ if self.nnz == 0:
+ return self._bsr_container((N, M), blocksize=(C, R),
+ dtype=self.dtype, copy=copy)
+
+ indptr = np.empty(N//C + 1, dtype=self.indptr.dtype)
+ indices = np.empty(NBLK, dtype=self.indices.dtype)
+ data = np.empty((NBLK, C, R), dtype=self.data.dtype)
+
+ bsr_transpose(M//R, N//C, R, C,
+ self.indptr, self.indices, self.data.ravel(),
+ indptr, indices, data.ravel())
+
+ return self._bsr_container((data, indices, indptr),
+ shape=(N, M), copy=copy)
+
+ transpose.__doc__ = _spbase.transpose.__doc__
+
+ ##############################################################
+ # methods that examine or modify the internal data structure #
+ ##############################################################
+
+ def eliminate_zeros(self):
+ """Remove zero elements in-place."""
+
+ if not self.nnz:
+ return # nothing to do
+
+ R,C = self.blocksize
+ M,N = self.shape
+
+ mask = (self.data != 0).reshape(-1,R*C).sum(axis=1) # nonzero blocks
+
+ nonzero_blocks = mask.nonzero()[0]
+
+ self.data[:len(nonzero_blocks)] = self.data[nonzero_blocks]
+
+ # modifies self.indptr and self.indices *in place*
+ _sparsetools.csr_eliminate_zeros(M//R, N//C, self.indptr,
+ self.indices, mask)
+ self.prune()
+
+ def sum_duplicates(self):
+ """Eliminate duplicate array/matrix entries by adding them together
+
+ The is an *in place* operation
+ """
+ if self.has_canonical_format:
+ return
+ self.sort_indices()
+ R, C = self.blocksize
+ M, N = self.shape
+
+ # port of _sparsetools.csr_sum_duplicates
+ n_row = M // R
+ nnz = 0
+ row_end = 0
+ for i in range(n_row):
+ jj = row_end
+ row_end = self.indptr[i+1]
+ while jj < row_end:
+ j = self.indices[jj]
+ x = self.data[jj]
+ jj += 1
+ while jj < row_end and self.indices[jj] == j:
+ x += self.data[jj]
+ jj += 1
+ self.indices[nnz] = j
+ self.data[nnz] = x
+ nnz += 1
+ self.indptr[i+1] = nnz
+
+ self.prune() # nnz may have changed
+ self.has_canonical_format = True
+
+ def sort_indices(self):
+ """Sort the indices of this array/matrix *in place*
+ """
+ if self.has_sorted_indices:
+ return
+
+ R,C = self.blocksize
+ M,N = self.shape
+
+ bsr_sort_indices(M//R, N//C, R, C, self.indptr, self.indices, self.data.ravel())
+
+ self.has_sorted_indices = True
+
+ def prune(self):
+ """Remove empty space after all non-zero elements.
+ """
+
+ R,C = self.blocksize
+ M,N = self.shape
+
+ if len(self.indptr) != M//R + 1:
+ raise ValueError("index pointer has invalid length")
+
+ bnnz = self.indptr[-1]
+
+ if len(self.indices) < bnnz:
+ raise ValueError("indices array has too few elements")
+ if len(self.data) < bnnz:
+ raise ValueError("data array has too few elements")
+
+ self.data = self.data[:bnnz]
+ self.indices = self.indices[:bnnz]
+
+ # utility functions
+ def _binopt(self, other, op, in_shape=None, out_shape=None):
+ """Apply the binary operation fn to two sparse matrices."""
+
+ # Ideally we'd take the GCDs of the blocksize dimensions
+ # and explode self and other to match.
+ other = self.__class__(other, blocksize=self.blocksize)
+
+ # e.g. bsr_plus_bsr, etc.
+ fn = getattr(_sparsetools, self.format + op + self.format)
+
+ R,C = self.blocksize
+
+ max_bnnz = len(self.data) + len(other.data)
+ idx_dtype = self._get_index_dtype((self.indptr, self.indices,
+ other.indptr, other.indices),
+ maxval=max_bnnz)
+ indptr = np.empty(self.indptr.shape, dtype=idx_dtype)
+ indices = np.empty(max_bnnz, dtype=idx_dtype)
+
+ bool_ops = ['_ne_', '_lt_', '_gt_', '_le_', '_ge_']
+ if op in bool_ops:
+ data = np.empty(R*C*max_bnnz, dtype=np.bool_)
+ else:
+ data = np.empty(R*C*max_bnnz, dtype=upcast(self.dtype,other.dtype))
+
+ fn(self.shape[0]//R, self.shape[1]//C, R, C,
+ self.indptr.astype(idx_dtype, copy=False),
+ self.indices.astype(idx_dtype, copy=False),
+ self.data,
+ other.indptr.astype(idx_dtype, copy=False),
+ other.indices.astype(idx_dtype, copy=False),
+ np.ravel(other.data),
+ indptr,
+ indices,
+ data)
+
+ actual_bnnz = indptr[-1]
+ indices = indices[:actual_bnnz]
+ data = data[:R*C*actual_bnnz]
+
+ if actual_bnnz < max_bnnz/2:
+ indices = indices.copy()
+ data = data.copy()
+
+ data = data.reshape(-1,R,C)
+
+ return self.__class__((data, indices, indptr), shape=self.shape)
+
+ # needed by _data_matrix
+ def _with_data(self,data,copy=True):
+ """Returns a matrix with the same sparsity structure as self,
+ but with different data. By default the structure arrays
+ (i.e. .indptr and .indices) are copied.
+ """
+ if copy:
+ return self.__class__((data,self.indices.copy(),self.indptr.copy()),
+ shape=self.shape,dtype=data.dtype)
+ else:
+ return self.__class__((data,self.indices,self.indptr),
+ shape=self.shape,dtype=data.dtype)
+
+# # these functions are used by the parent class
+# # to remove redundancy between bsc_matrix and bsr_matrix
+# def _swap(self,x):
+# """swap the members of x if this is a column-oriented matrix
+# """
+# return (x[0],x[1])
+
+ def _broadcast_to(self, shape, copy=False):
+ return _spbase._broadcast_to(self, shape, copy)
+
+
+def isspmatrix_bsr(x):
+ """Is `x` of a bsr_matrix type?
+
+ Parameters
+ ----------
+ x
+ object to check for being a bsr matrix
+
+ Returns
+ -------
+ bool
+ True if `x` is a bsr matrix, False otherwise
+
+ Examples
+ --------
+ >>> from scipy.sparse import bsr_array, bsr_matrix, csr_matrix, isspmatrix_bsr
+ >>> isspmatrix_bsr(bsr_matrix([[5]]))
+ True
+ >>> isspmatrix_bsr(bsr_array([[5]]))
+ False
+ >>> isspmatrix_bsr(csr_matrix([[5]]))
+ False
+ """
+ return isinstance(x, bsr_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class bsr_array(_bsr_base, sparray):
+ """
+ Block Sparse Row format sparse array.
+
+ This can be instantiated in several ways:
+ bsr_array(D, [blocksize=(R,C)])
+ where D is a 2-D ndarray.
+
+ bsr_array(S, [blocksize=(R,C)])
+ with another sparse array or matrix S (equivalent to S.tobsr())
+
+ bsr_array((M, N), [blocksize=(R,C), dtype])
+ to construct an empty sparse array with shape (M, N)
+ dtype is optional, defaulting to dtype='d'.
+
+ bsr_array((data, ij), [blocksize=(R,C), shape=(M, N)])
+ where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``
+
+ bsr_array((data, indices, indptr), [shape=(M, N)])
+ is the standard BSR representation where the block column
+ indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]``
+ and their corresponding block values are stored in
+ ``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not
+ supplied, the array dimensions are inferred from the index arrays.
+
+ Attributes
+ ----------
+ dtype : dtype
+ Data type of the array
+ shape : 2-tuple
+ Shape of the array
+ ndim : int
+ Number of dimensions (this is always 2)
+ nnz
+ size
+ data
+ BSR format data array of the array
+ indices
+ BSR format index array of the array
+ indptr
+ BSR format index pointer array of the array
+ blocksize
+ Block size
+ has_sorted_indices : bool
+ Whether indices are sorted
+ has_canonical_format : bool
+ T
+
+ Notes
+ -----
+ Sparse arrays can be used in arithmetic operations: they support
+ addition, subtraction, multiplication, division, and matrix power.
+
+ **Summary of BSR format**
+
+ The Block Sparse Row (BSR) format is very similar to the Compressed
+ Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense
+ sub matrices like the last example below. Such sparse block matrices often
+ arise in vector-valued finite element discretizations. In such cases, BSR is
+ considerably more efficient than CSR and CSC for many sparse arithmetic
+ operations.
+
+ **Blocksize**
+
+ The blocksize (R,C) must evenly divide the shape of the sparse array (M,N).
+ That is, R and C must satisfy the relationship ``M % R = 0`` and
+ ``N % C = 0``.
+
+ If no blocksize is specified, a simple heuristic is applied to determine
+ an appropriate blocksize.
+
+ **Canonical Format**
+
+ In canonical format, there are no duplicate blocks and indices are sorted
+ per row.
+
+ **Limitations**
+
+ Block Sparse Row format sparse arrays do not support slicing.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.sparse import bsr_array
+ >>> bsr_array((3, 4), dtype=np.int8).toarray()
+ array([[0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]], dtype=int8)
+
+ >>> row = np.array([0, 0, 1, 2, 2, 2])
+ >>> col = np.array([0, 2, 2, 0, 1, 2])
+ >>> data = np.array([1, 2, 3 ,4, 5, 6])
+ >>> bsr_array((data, (row, col)), shape=(3, 3)).toarray()
+ array([[1, 0, 2],
+ [0, 0, 3],
+ [4, 5, 6]])
+
+ >>> indptr = np.array([0, 2, 3, 6])
+ >>> indices = np.array([0, 2, 2, 0, 1, 2])
+ >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
+ >>> bsr_array((data,indices,indptr), shape=(6, 6)).toarray()
+ array([[1, 1, 0, 0, 2, 2],
+ [1, 1, 0, 0, 2, 2],
+ [0, 0, 0, 0, 3, 3],
+ [0, 0, 0, 0, 3, 3],
+ [4, 4, 5, 5, 6, 6],
+ [4, 4, 5, 5, 6, 6]])
+
+ """
+
+
+class bsr_matrix(spmatrix, _bsr_base):
+ """
+ Block Sparse Row format sparse matrix.
+
+ This can be instantiated in several ways:
+ bsr_matrix(D, [blocksize=(R,C)])
+ where D is a 2-D ndarray.
+
+ bsr_matrix(S, [blocksize=(R,C)])
+ with another sparse array or matrix S (equivalent to S.tobsr())
+
+ bsr_matrix((M, N), [blocksize=(R,C), dtype])
+ to construct an empty sparse matrix with shape (M, N)
+ dtype is optional, defaulting to dtype='d'.
+
+ bsr_matrix((data, ij), [blocksize=(R,C), shape=(M, N)])
+ where ``data`` and ``ij`` satisfy ``a[ij[0, k], ij[1, k]] = data[k]``
+
+ bsr_matrix((data, indices, indptr), [shape=(M, N)])
+ is the standard BSR representation where the block column
+ indices for row i are stored in ``indices[indptr[i]:indptr[i+1]]``
+ and their corresponding block values are stored in
+ ``data[ indptr[i]: indptr[i+1] ]``. If the shape parameter is not
+ supplied, the matrix dimensions are inferred from the index arrays.
+
+ Attributes
+ ----------
+ dtype : dtype
+ Data type of the matrix
+ shape : 2-tuple
+ Shape of the matrix
+ ndim : int
+ Number of dimensions (this is always 2)
+ nnz
+ size
+ data
+ BSR format data array of the matrix
+ indices
+ BSR format index array of the matrix
+ indptr
+ BSR format index pointer array of the matrix
+ blocksize
+ Block size
+ has_sorted_indices : bool
+ Whether indices are sorted
+ has_canonical_format : bool
+ T
+
+ Notes
+ -----
+ Sparse matrices can be used in arithmetic operations: they support
+ addition, subtraction, multiplication, division, and matrix power.
+
+ **Summary of BSR format**
+
+ The Block Sparse Row (BSR) format is very similar to the Compressed
+ Sparse Row (CSR) format. BSR is appropriate for sparse matrices with dense
+ sub matrices like the last example below. Such sparse block matrices often
+ arise in vector-valued finite element discretizations. In such cases, BSR is
+ considerably more efficient than CSR and CSC for many sparse arithmetic
+ operations.
+
+ **Blocksize**
+
+ The blocksize (R,C) must evenly divide the shape of the sparse matrix (M,N).
+ That is, R and C must satisfy the relationship ``M % R = 0`` and
+ ``N % C = 0``.
+
+ If no blocksize is specified, a simple heuristic is applied to determine
+ an appropriate blocksize.
+
+ **Canonical Format**
+
+ In canonical format, there are no duplicate blocks and indices are sorted
+ per row.
+
+ **Limitations**
+
+ Block Sparse Row format sparse matrices do not support slicing.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.sparse import bsr_matrix
+ >>> bsr_matrix((3, 4), dtype=np.int8).toarray()
+ array([[0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]], dtype=int8)
+
+ >>> row = np.array([0, 0, 1, 2, 2, 2])
+ >>> col = np.array([0, 2, 2, 0, 1, 2])
+ >>> data = np.array([1, 2, 3 ,4, 5, 6])
+ >>> bsr_matrix((data, (row, col)), shape=(3, 3)).toarray()
+ array([[1, 0, 2],
+ [0, 0, 3],
+ [4, 5, 6]])
+
+ >>> indptr = np.array([0, 2, 3, 6])
+ >>> indices = np.array([0, 2, 2, 0, 1, 2])
+ >>> data = np.array([1, 2, 3, 4, 5, 6]).repeat(4).reshape(6, 2, 2)
+ >>> bsr_matrix((data,indices,indptr), shape=(6, 6)).toarray()
+ array([[1, 1, 0, 0, 2, 2],
+ [1, 1, 0, 0, 2, 2],
+ [0, 0, 0, 0, 3, 3],
+ [0, 0, 0, 0, 3, 3],
+ [4, 4, 5, 5, 6, 6],
+ [4, 4, 5, 5, 6, 6]])
+
+ """
+
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_compressed.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_compressed.py
new file mode 100644
index 0000000000000000000000000000000000000000..f2d19f200aebcc77c3b413716d08d73bfe2d80d0
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_compressed.py
@@ -0,0 +1,1337 @@
+"""Base class for sparse matrix formats using compressed storage."""
+__all__ = []
+
+from warnings import warn
+import itertools
+
+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, csr_diagonal,
+ expandptr, csr_has_canonical_format, csr_eliminate_zeros,
+ csr_sum_duplicates, csr_has_sorted_indices, csr_sort_indices,
+ csr_matmat_maxnnz, csr_matmat)
+from ._index import IndexMixin
+from ._sputils import (upcast, upcast_char, to_native, isshape,
+ getdtype, isintlike, downcast_intp_index,
+ get_sum_dtype, check_shape, get_index_dtype, broadcast_shapes)
+
+
+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
+
+ #################################
+ # 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_2d_with_broadcasting(self, other):
+ """Element-wise multiplication by array/matrix, vector, or scalar."""
+ # Called after checking that other is not scalarlike and self.ndim <=2
+ 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(f"inconsistent shapes {self.shape} and {other.shape}")
+
+ # 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(f"inconsistent shapes {self.shape} and {other.shape}")
+ 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(f"inconsistent shapes {self.shape} and {other.shape}")
+ 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(f"inconsistent shapes {self.shape} and {other.shape}")
+ 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)
+
+ other = self.__class__(other) # convert to this format
+ index_arrays = (self.indptr, self.indices, other.indptr, other.indices)
+
+ M, N = self._swap((M, N))
+ s, o = self._swap((self, other))
+
+ idx_dtype = self._get_index_dtype(index_arrays)
+ s_indptr = np.asarray(s.indptr, dtype=idx_dtype)
+ s_indices = np.asarray(s.indices, dtype=idx_dtype)
+ o_indptr = np.asarray(o.indptr, dtype=idx_dtype)
+ o_indices = np.asarray(o.indices, dtype=idx_dtype)
+
+ nnz = csr_matmat_maxnnz(M, N, s_indptr, s_indices, o_indptr, o_indices)
+ 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))
+
+ new_idx_dtype = self._get_index_dtype(index_arrays, maxval=nnz)
+ if new_idx_dtype != idx_dtype:
+ idx_dtype = new_idx_dtype
+ s_indptr = np.asarray(s.indptr, dtype=idx_dtype)
+ s_indices = np.asarray(s.indices, dtype=idx_dtype)
+ o_indptr = np.asarray(o.indptr, dtype=idx_dtype)
+ o_indices = np.asarray(o.indices, dtype=idx_dtype)
+
+ indptr = np.empty(M + 1, dtype=idx_dtype)
+ indices = np.empty(nnz, dtype=idx_dtype)
+ data = np.empty(nnz, dtype=upcast(self.dtype, other.dtype))
+
+ csr_matmat(M, N,
+ s_indptr, s_indices, s.data,
+ o_indptr, o_indices, o.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):
+ M, N = self._swap(self.shape)
+ k, _ = self._swap((k, -k))
+
+ if k <= -M or k >= N:
+ return np.empty(0, dtype=self.data.dtype)
+ y = np.empty(min(M + min(k, 0), N - max(k, 0)), dtype=upcast(self.dtype))
+ csr_diagonal(k, M, N, self.indptr, self.indices, self.data, y)
+ return y
+
+ diagonal.__doc__ = _spbase.diagonal.__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=None and major axis efficiently
+ # so we only do the case axis= minor axis
+ 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:
+ 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)
+
+ self_indptr = self.indptr.astype(idx_dtype, copy=False)
+ self_indices = self.indices.astype(idx_dtype, copy=False)
+
+ row_nnz = self_indptr[indices + 1] - self_indptr[indices]
+ 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,
+ self_indices,
+ 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
+
+ is_existing = (offsets >= 0)
+ N_new = len(is_existing) - np.count_nonzero(is_existing)
+
+ # Boundary between csc and convert to coo
+ # The value 0.001 is justified in gh-19962#issuecomment-1920499678
+ if N_new < self.nnz * 0.001:
+ # replace existing entries
+ self.data[offsets[is_existing]] = x[is_existing]
+ # create new entries
+ is_new = np.logical_not(is_existing, out=is_existing)
+ del is_existing
+ self._insert_many(i[is_new], j[is_new], x[is_new])
+ else:
+ # convert to coo for _set_diag
+ do_sort = self.has_sorted_indices
+ coo = self.tocoo()
+ coo._setdiag(values, k)
+ arrays = coo._coo_to_compressed(self._swap)
+ self.indptr, self.indices, self.data, _ = arrays
+ # Sort the indices (like in _insert_many)
+ if do_sort:
+ self.has_sorted_indices = False # force a sort
+ self.sort_indices()
+
+ 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)
+ 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)
+ 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'):
+ M = len(self.indptr) - 1
+ self.has_canonical_format = bool(
+ csr_has_canonical_format(M, 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)
+ 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'):
+ M = len(self.indptr) - 1
+ self._has_sorted_indices = bool(
+ csr_has_sorted_indices(M, 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:
+ M = len(self.indptr) - 1
+ csr_sort_indices(M, 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, "csr" + op + "csr")
+
+ 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._swap(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(f"inconsistent shapes {self.shape} and {other.shape}")
+
+ r = self._binopt(other, '_eldiv_')
+
+ if np.issubdtype(r.dtype, np.inexact):
+ # Eldiv leaves entries outside the combined sparsity
+ # pattern empty, so they must be filled manually.
+ # Everything outside of other's sparsity is NaN, and everything
+ # inside it is either zero or defined by eldiv.
+ out = np.empty(self.shape, dtype=self.dtype)
+ out.fill(np.nan)
+ coords = other.nonzero()
+ if self.ndim == 1:
+ coords = (coords[-1],)
+ out[coords] = 0
+ r = r.tocoo()
+ out[r.coords] = r.data
+ return self._container(out)
+ else:
+ # integers types go with nan <-> 0
+ out = r
+ return out
+
+ def _broadcast_to(self, shape, copy=False):
+ if self.shape == shape:
+ return self.copy() if copy else self
+
+ shape = check_shape(shape, allow_nd=(self._allow_nd))
+
+ if broadcast_shapes(self.shape, shape) != shape:
+ raise ValueError("cannot be broadcast")
+
+ if len(self.shape) == 1 and len(shape) == 1:
+ self.sum_duplicates()
+ if self.nnz == 0: # array has no non zero elements
+ return self.__class__(shape, dtype=self.dtype, copy=False)
+
+ N = shape[0]
+ data = np.full(N, self.data[0])
+ indices = np.arange(0,N)
+ indptr = np.array([0, N])
+ return self._csr_container((data, indices, indptr), shape=shape, copy=False)
+
+ # treat 1D as a 2D row
+ old_shape = self._shape_as_2d
+
+ if len(shape) != 2:
+ ndim = len(shape)
+ raise ValueError(f'CSR/CSC broadcast_to cannot have shape >2D. Got {ndim}D')
+
+ if self.nnz == 0: # array has no non zero elements
+ return self.__class__(shape, dtype=self.dtype, copy=False)
+
+ self.sum_duplicates()
+ M, N = self._swap(shape)
+ oM, oN = self._swap(old_shape)
+ if all(s == 1 for s in old_shape):
+ # Broadcast a single element to the entire shape
+ data = np.full(M * N, self.data[0])
+ indices = np.tile(np.arange(N), M)
+ indptr = np.arange(0, len(data) + 1, N)
+ elif oM == 1 and oN == N:
+ # Broadcast row-wise (columns for CSC)
+ data = np.tile(self.data, M)
+ indices = np.tile(self.indices, M)
+ indptr = np.arange(0, len(data) + 1, len(self.data))
+ elif oN == 1 and oM == M:
+ # Broadcast column-wise (rows for CSC)
+ data = np.repeat(self.data, N)
+ indices = np.tile(np.arange(N), len(self.data))
+ indptr = self.indptr * N
+ return self.__class__((data, indices, indptr), shape=shape, copy=False)
+
+
+def _make_diagonal_csr(data, is_array=False):
+ """build diagonal csc_array/csr_array => self._csr_container
+
+ Parameter `data` should be a raveled numpy array holding the
+ values on the diagonal of the resulting sparse matrix.
+ """
+ from ._csr import csr_array, csr_matrix
+ csr_array = csr_array if is_array else csr_matrix
+
+ N = len(data)
+ idx_dtype = get_index_dtype(maxval=N)
+ indptr = np.arange(N + 1, dtype=idx_dtype)
+ indices = indptr[:-1]
+
+ return csr_array((data, indices, indptr), shape=(N, N))
+
+
+def _process_slice(sl, num):
+ if sl is None:
+ i0, i1 = 0, num
+ elif isinstance(sl, slice):
+ i0, i1, stride = sl.indices(num)
+ if stride != 1:
+ raise ValueError('slicing with step != 1 not supported')
+ i0 = min(i0, i1) # give an empty slice when i0 > i1
+ elif isintlike(sl):
+ if sl < 0:
+ sl += num
+ i0, i1 = sl, sl + 1
+ if i0 < 0 or i1 > num:
+ raise IndexError(f'index out of bounds: 0 <= {i0} < {i1} <= {num}')
+ else:
+ raise TypeError('expected slice or scalar')
+
+ return i0, i1
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_construct.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_construct.py
new file mode 100644
index 0000000000000000000000000000000000000000..9ad3674cfcd9b0fde050a54792d25a267cf82481
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_construct.py
@@ -0,0 +1,1709 @@
+"""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',
+ 'expand_dims', 'permute_dims', 'swapaxes']
+
+import numbers
+import math
+import os
+import sys
+import warnings
+import numpy as np
+
+from scipy._lib._util import check_random_state, rng_integers, _transition_to_rng
+from scipy._lib.deprecation import _NoValue
+from ._sputils import upcast, get_index_dtype, isscalarlike, isintlike
+
+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 expand_dims(A, /, *, axis=0):
+ """
+ Add trivial axes to an array. Shape gets a ``1`` inserted at position `axis`.
+
+ Parameters
+ ----------
+ A : sparse array
+
+ axis : int
+ Position in the expanded axes where the new axis (or axes) is placed.
+ For a dimension ``N`` array, a valid axis is an integer on the
+ closed-interval ``[-N-1, N]``. Negative values work from the end of
+ the shape. ``0`` prepends an axis, as does ``-N-1``. ``-1`` appends
+ an axis, as does ``N``. The new axis has shape ``1`` and indices are
+ created with the value ``0``.
+
+ Returns
+ -------
+ out : sparse array
+ A expanded copy output in COO format with the same dtype as `A`.
+
+ Raises
+ ------
+ ValueError
+ If provided a non-integer or out of range ``[-N-1, N]`` axis,
+ where ``N`` is ``A.ndim``.
+
+ Examples
+ --------
+ >>> from scipy.sparse import csr_array, expand_dims
+ >>> A = csr_array([[1, 2], [2, 0]])
+ >>> A.shape
+ (2, 2)
+ >>> expand_dims(A, axis=1).shape
+ (2, 1, 2)
+
+ """
+ if not isintlike(axis):
+ raise ValueError(f"Invalid axis {axis}. Must be an integer.")
+ idx = axis if axis >= 0 else axis + A.ndim + 1
+ if idx < 0 or idx > A.ndim:
+ raise ValueError(f"Invalid axis {axis} for N={A.ndim}. Must be in [-N-1, N].")
+
+ newA = A.tocoo(copy=True)
+ new_coord = np.zeros_like(newA.coords[0])
+
+ newA.coords = newA.coords[:idx] + (new_coord,) + newA.coords[idx:]
+ newA._shape = newA.shape[:idx] + (1,) + newA.shape[idx:]
+ if A.format == "coo":
+ newA.has_canonical_format = A.has_canonical_format
+ return newA
+
+
+def swapaxes(A, axis1, axis2):
+ """Interchange two axes of an array.
+
+ Parameters
+ ----------
+ A : sparse array
+ axis1 : int
+ First axis.
+ axis2 : int
+ Second axis.
+
+ Returns
+ -------
+ a_swapped : sparse array in COO format
+ A copy of the input array with the two identified axes swapped.
+
+ Raises
+ ------
+ ValueError
+ If provided a non-integer or out of range ``[-N, N-1]`` axis,
+ where ``N`` is ``A.ndim``.
+
+ Examples
+ --------
+ >>> from scipy.sparse import coo_array, swapaxes
+ >>> A = coo_array([[[1, 2, 3], [2, 0, 0]]])
+ >>> A.shape
+ (1, 2, 3)
+ >>> swapaxes(A, 1, 2).shape
+ (1, 3, 2)
+
+ """
+ axes = np.arange(A.ndim)
+ try:
+ axes[[axis1, axis2]] = axes[[axis2, axis1]]
+ except IndexError as err:
+ # original msg looks like: "index -4 is out of bounds for axis 0 with size 2"
+ msg = str(err)
+ msg = msg.removeprefix('index ').split(' axis ', 1)[0]
+ # Final error is: "Invalid axis: -4 is out of bounds for ndim=2"
+ raise ValueError(f"Invalid axis: {msg} ndim={A.ndim}")
+
+ axes = tuple(axes)
+ return permute_dims(A, axes=axes, copy=True)
+
+
+def permute_dims(A, axes=None, copy=False):
+ """Permute the axes of the sparse array `A` to the order `axes`.
+
+ Parameters
+ ----------
+ A : sparse array
+ axes : tuple or list of ints, optional
+ If specified, it must be a tuple or list which contains a permutation
+ of ``[0, 1, ..., N-1]`` where ``N`` is ``A.ndim``. The ith
+ axis of the returned array will correspond to the axis numbered ``axes[i]``
+ of the input. If not specified, defaults to ``range(A.ndim)[::-1]``,
+ which reverses the order of the axes.
+ copy : bool, optional (default: False)
+ Whether to return the permutation as a copy. If False, an in-place
+ permutation is provided if possible depending on format.
+
+ Returns
+ -------
+ out : sparse array in COO format
+ A copy of `A` with permuted axes.
+
+ Raises
+ ------
+ ValueError
+ If provided a non-integer or out of range ``[-N, N-1]`` axis,
+ where ``N`` is ``A.ndim``.
+
+ Examples
+ --------
+ >>> from scipy.sparse import coo_array, permute_dims
+ >>> A = coo_array([[[1, 2, 3], [2, 0, 0]]])
+ >>> A.shape
+ (1, 2, 3)
+ >>> permute_dims(A, axes=(1, 2, 0)).shape
+ (2, 3, 1)
+
+ """
+ ndim = A.ndim
+ if axes is None:
+ axes = tuple(range(ndim)[::-1])
+ elif len(axes) != ndim:
+ raise ValueError(f"Incorrect number of axes: {ndim} instead of {A.ndim}")
+
+ # -------------This is from _sputils.validateaxis which almost does what we want
+ # TODO stop _sputils.validateaxis from returning `None` when len(axes)==ndim
+ if not isinstance(axes, (tuple, list)):
+ # If not a tuple, check that the provided axes is actually
+ # an integer and raise a TypeError similar to NumPy's
+ if not np.issubdtype(np.dtype(type(axes)), np.integer):
+ raise TypeError(f'axis must be an integer/tuple of ints, not {type(axes)}')
+ axes = (axes,)
+
+ canon_axes = []
+ for ax in axes:
+ if not isintlike(ax):
+ raise TypeError(f"axis must be an integer. (given {ax})")
+ if ax < 0:
+ ax += ndim
+ if ax < 0 or ax >= ndim:
+ raise ValueError("axis out of range for ndim")
+ canon_axes.append(ax)
+
+ if len(canon_axes) != len(set(canon_axes)):
+ raise ValueError("duplicate value in axis")
+ # -------------End of code from _sputils.validateaxis
+ axes = canon_axes
+ if axes == list(range(ndim)):
+ return A if not copy else A.copy()
+
+ A = A.tocoo(copy=copy)
+ A._shape = tuple(A.shape[idx] for idx in axes)
+ A.coords = tuple(A.coords[idx] for idx in axes)
+ A.has_canonical_format = False # data usually no longer sorted
+ return A
+
+
+def spdiags(data, diags, m=None, n=None, format=None):
+ """
+ Return a sparse matrix from diagonals.
+
+ .. 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. (See Notes below.)
+
+ 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.
+
+ Returns
+ -------
+ new_matrix : sparse matrix
+ `dia_matrix` format with values in ``data`` on diagonals from ``diags``.
+
+ 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=_NoValue):
+ """
+ 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. If `dtype` is None, the output
+ data type is determined by the data type of the input diagonals.
+
+ Up until SciPy 1.19, the default behavior will be to return an array
+ with an inexact (floating point) data type. In particular, integer
+ input will be converted to double precision floating point. This
+ behavior is deprecated, and in SciPy 1.19, the default behavior
+ will be changed to return an array with the same data type as the
+ input diagonals. To adopt this behavior before version 1.19, use
+ `dtype=None`.
+
+ Returns
+ -------
+ new_array : dia_array
+ `dia_array` holding the values in `diagonals` offset from the main diagonal
+ as indicated in `offsets`.
+
+ 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
+
+ See Also
+ --------
+ dia_array : constructor for the sparse DIAgonal format.
+
+ Examples
+ --------
+ >>> from scipy.sparse import diags_array
+ >>> diagonals = [[1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 3.0], [1.0, 2.0]]
+ >>> 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.0, -2.0, 1.0], 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.0, 2.0, 3.0], 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.result_type(*diagonals)
+ elif dtype is _NoValue:
+ # This is the old deprecated behavior that uses np.common_type().
+ # After the deprecation period, this elif branch can be removed,
+ # and the default for the `dtype` parameter changed back to `None`.
+ dtype = np.dtype(np.common_type(*diagonals))
+ future_dtype = np.result_type(*diagonals)
+ if sys.version_info < (3, 12):
+ warn_kwargs = {'stacklevel': 2}
+ extra_msg = ("\nNote: In Python 3.11, this warning can be generated by "
+ "a call of scipy.sparse.diags(), but the code indicated in "
+ "the warning message will refer to an internal call of "
+ "scipy.sparse.diags_array(). If that happens, check your "
+ "code for the use of diags().")
+ else:
+ warn_kwargs = {'skip_file_prefixes': (os.path.dirname(__file__),)}
+ extra_msg = ""
+ if (dtype != future_dtype):
+ warnings.warn(
+ f"Input has data type {future_dtype}, but the output has been cast "
+ f"to {dtype}. In the future, the output data type will match the "
+ "input. To avoid this warning, set the `dtype` parameter to `None` "
+ "to have the output dtype match the input, or set it to the "
+ "desired output data type."
+ + extra_msg,
+ FutureWarning,
+ **warn_kwargs
+ )
+
+ # 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=_NoValue):
+ """
+ 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. If `dtype` is None, the output
+ data type is determined by the data type of the input diagonals.
+
+ Up until SciPy 1.19, the default behavior will be to return a matrix
+ with an inexact (floating point) data type. In particular, integer
+ input will be converted to double precision floating point. This
+ behavior is deprecated, and in SciPy 1.19, the default behavior
+ will be changed to return a matrix with the same data type as the
+ input diagonals. To adopt this behavior before version 1.19, use
+ `dtype=None`.
+
+ Returns
+ -------
+ new_matrix : dia_matrix
+ `dia_matrix` holding the values in `diagonals` offset from the main diagonal
+ as indicated in `offsets`.
+
+ 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
+
+ See Also
+ --------
+ spdiags : construct matrix from diagonals
+ diags_array : construct sparse array instead of sparse matrix
+
+ Examples
+ --------
+ >>> from scipy.sparse import diags
+ >>> diagonals = [[1.0, 2.0, 3.0, 4.0], [1.0, 2.0, 3.0], [1.0, 2.0]]
+ >>> 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.0, -2.0, 1.0], [-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.0, 2.0, 3.0], 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.
+
+ Returns
+ -------
+ new_matrix : sparse matrix
+ A square sparse matrix with ones on the main diagonal and zeros elsewhere.
+
+ See Also
+ --------
+ eye_array : Sparse array of chosen shape with ones on a specified diagonal.
+ eye : Sparse matrix of chosen shape with ones on a specified diagonal.
+
+ 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):
+ """Sparse array of chosen shape with ones on the kth diagonal and zeros elsewhere.
+
+ 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.
+
+ Returns
+ -------
+ new_array : sparse array
+ Sparse array of chosen shape with ones on the kth diagonal and zeros elsewhere.
+
+ 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 of chosen shape with ones on the kth diagonal and zeros elsewhere.
+
+ Returns a sparse matrix (m x n) where the kth diagonal
+ is all ones and everything else is zeros.
+
+ .. 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
+ ----------
+ 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.
+
+ Returns
+ -------
+ new_matrix : sparse matrix
+ Sparse matrix of chosen shape with ones on the kth diagonaland zeros elsewhere.
+
+ See Also
+ --------
+ eye_array : Sparse array of chosen shape with ones on a specified diagonal.
+
+ 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):
+ """Sparse representation of the Kronecker product of `A` and `B`
+
+ Computes the Kronecker product, a composite sparse array
+ made of blocks consisting of the second input array multiplied
+ by each element of the first input array.
+
+ Parameters
+ ----------
+ A : sparse or dense array
+ first array of the product
+ B : sparse or dense array
+ second array of the product
+ format : str, optional (default: 'bsr' or 'coo')
+ format of the result (e.g. "csr")
+ If None, choose 'bsr' for relatively dense 2D arrays and 'coo' for others
+
+ Returns
+ -------
+ sparse matrix or array
+ 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)
+
+ # B is 2D and fairly dense, and format aligns with bsr, compute using BSR
+ if (
+ (format is None or format == "bsr") and
+ B.ndim == 2 and 2*B.nnz >= math.prod(B.shape)
+ ):
+ if not hasattr(A, 'ndim') or A.ndim != 2:
+ # CSR routes thru COO in constructor so can make COO to check ndim
+ A = coo_sparse(A)
+ if A.ndim == 2:
+ A = csr_sparse(A, copy=True)
+ 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:
+ A = coo_sparse(A) # no copy needed as we use np.repeat below
+
+ # compute using COO (convert to desired format just before return)
+ if coo_sparse is coo_matrix:
+ output_shape = (A.shape[0] * B.shape[0], A.shape[1] * B.shape[1])
+ ndim_diff = 0
+ else:
+ ndim_diff = A.ndim - B.ndim
+ A_shape = A.shape if ndim_diff >= 0 else (1,) * (-ndim_diff) + A.shape
+ B_shape = B.shape if ndim_diff <= 0 else (1,) * ndim_diff + B.shape
+ output_shape = tuple(a * b for a, b in zip(A_shape, B_shape))
+
+ 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
+ data = A.data.repeat(B.nnz)
+ idx_dtype = get_index_dtype(A.coords, maxval=max(output_shape))
+ coords = [np.asarray(co, dtype=idx_dtype).repeat(B.nnz) for co in A.coords]
+ if ndim_diff < 0:
+ new_co = np.zeros_like(coords[0])
+ coords = [new_co] + [new_co.copy() for _ in range(-ndim_diff - 1)] + coords
+
+ # The last B.ndim coords need to be updated. Any previous columns in B are from
+ # prepending (1,)s, so coord from A is what we need (B coord axis is all 0)
+ for co, B_shape_i in zip(coords[-B.ndim:], B.shape):
+ co *= B_shape_i
+
+ # increment block indices
+ coords[-B.ndim:] = [(co.reshape(-1, B.nnz) + Bco).ravel()
+ for co, Bco in zip(coords[-B.ndim:], B.coords)]
+ # compute block entries
+ data = (data.reshape(-1, B.nnz) * B.data).ravel()
+
+ return coo_sparse((data, tuple(coords)), 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 : sparse matrix or array
+ Square matrix
+ B : sparse array or array
+ Square matrix
+ format : str
+ format of the result (e.g. "csr")
+
+ Returns
+ -------
+ sparse matrix or array
+ kronecker sum 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
+ --------
+ `kronsum` can be used to construct a finite difference discretization of the 2D
+ Laplacian from a 1D discretization.
+
+ >>> from scipy.sparse import diags_array, kronsum
+ >>> from matplotlib import pyplot as plt
+ >>> import numpy as np
+ >>> ex = np.ones(10)
+ >>> D_x = diags_array([ex, -ex[1:]], offsets=[0, -1]) # 1D first derivative
+ >>> D_xx = D_x.T @ D_x # 1D second derivative
+ >>> L = kronsum(D_xx, D_xx) # 2D Laplacian
+ >>> plt.spy(L.toarray())
+ >>> plt.show()
+
+ """
+ # 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`` returns a deprecated sparse matrix when none of the
+ inputs are sparse arrays.
+
+ .. warning::
+
+ This function returns a sparse matrix when no inputs are sparse arrays.
+ 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 : tuple of int
+ 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.]])
+
+ Providing a sampler for uint values:
+
+ >>> def random_uint32_to_100(size=None):
+ ... return rng.integers(100, size=size, dtype=np.uint32)
+ >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng,
+ ... data_sampler=random_uint32_to_100)
+
+ Building a custom distribution.
+ This example builds a squared normal from np.random:
+
+ >>> def np_normal_squared(size=None, rng=rng):
+ ... return rng.standard_normal(size) ** 2
+ >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng,
+ ... data_sampler=np_normal_squared)
+
+ Or we can build it from sp.stats style rvs functions:
+
+ >>> def sp_stats_normal_squared(size=None, rng=rng):
+ ... std_normal = sp.stats.distributions.norm_gen().rvs
+ ... return std_normal(size=size, random_state=rng) ** 2
+ >>> S = sp.sparse.random_array((3, 4), density=0.25, rng=rng,
+ ... data_sampler=sp_stats_normal_squared)
+
+ Or we can subclass sp.stats rv_continuous or rv_discrete:
+
+ >>> class NormalSquared(sp.stats.rv_continuous):
+ ... def _rvs(self, size=None, random_state=rng):
+ ... return rng.standard_normal(size) ** 2
+ >>> X = NormalSquared()
+ >>> Y = X().rvs
+ >>> S = sp.sparse.random_array((3, 4), density=0.25,
+ ... rng=rng, data_sampler=Y)
+ """
+ data, ind = _random(shape, density, format, dtype, rng, data_sampler)
+
+ # downcast, if safe, before calling coo_constructor
+ idx_dtype = get_index_dtype(maxval=max(shape))
+ ind = tuple(np.asarray(co, dtype=idx_dtype) for co in ind)
+ return coo_array((data, ind), shape=shape).asformat(format)
+
+
+def _random(shape, density=0.01, format=None, dtype=None,
+ rng=None, data_sampler=None):
+ if density < 0 or density > 1:
+ raise ValueError("density expected to be 0 <= density <= 1")
+
+ tot_prod = math.prod(shape) # use `math` for when prod is >= 2**64
+
+ # Number of non zero values
+ size = int(round(density * tot_prod))
+
+ rng = check_random_state(rng)
+
+ if data_sampler is None:
+ if np.issubdtype(dtype, np.integer):
+ def data_sampler(size):
+ return rng_integers(rng,
+ np.iinfo(dtype).min,
+ np.iinfo(dtype).max,
+ size,
+ dtype=dtype)
+ elif np.issubdtype(dtype, np.complexfloating):
+ def data_sampler(size):
+ return (rng.uniform(size=size) +
+ rng.uniform(size=size) * 1j)
+ else:
+ data_sampler = rng.uniform
+
+ idx_dtype = get_index_dtype(maxval=max(shape))
+ # rng.choice uses int64 if first arg is an int
+ if tot_prod <= np.iinfo(np.int64).max:
+ raveled_ind = rng.choice(tot_prod, size=size, replace=False)
+ ind = np.unravel_index(raveled_ind, shape=shape, order='F')
+ ind = tuple(np.asarray(co, idx_dtype) for co in ind)
+ else:
+ # for ravel indices bigger than dtype max, use sets to remove duplicates
+ ndim = len(shape)
+ seen = set()
+ while len(seen) < size:
+ dsize = size - len(seen)
+ seen.update(map(tuple, rng_integers(rng, shape, size=(dsize, ndim))))
+ ind = tuple(np.array(list(seen), dtype=idx_dtype).T)
+
+ # size kwarg allows eg data_sampler=partial(np.random.poisson, lam=5)
+ vals = data_sampler(size=size).astype(dtype, copy=False)
+ return vals, ind
+
+
+@_transition_to_rng("random_state", position_num=5)
+def random(m, n, density=0.01, format='coo', dtype=None,
+ rng=None, data_rvs=None):
+ """Generate a sparse matrix of the given shape and density with randomly
+ distributed values.
+
+ .. warning::
+
+ This function returns a sparse matrix -- not a sparse array.
+ You are encouraged to use `random_array` to take advantage of the
+ sparse array functionality.
+
+ Parameters
+ ----------
+ m, n : int
+ shape of the matrix
+ density : real, optional
+ density of the generated matrix: density equal to one means a full
+ matrix, density of 0 means a matrix with no non-zero items.
+ format : str, optional
+ sparse matrix format.
+ dtype : dtype, optional
+ type of the returned matrix values.
+ rng : `numpy.random.Generator`, optional
+ Pseudorandom number generator state. When `rng` is None, a new
+ `numpy.random.Generator` is created using entropy from the
+ operating system. Types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+ This random state will be used for sampling the sparsity structure, but
+ not necessarily for sampling the values of the structurally nonzero
+ entries of the matrix.
+ data_rvs : callable, optional
+ Samples a requested number of random values.
+ This function should take a single argument specifying the length
+ of the ndarray that it will return. The structurally nonzero entries
+ of the sparse random matrix will be taken from the array sampled
+ by this function. By default, uniform [0, 1) random values will be
+ sampled using the same random state as is used for sampling
+ the sparsity structure.
+
+ Returns
+ -------
+ res : sparse matrix
+
+ See Also
+ --------
+ random_array : constructs sparse arrays instead of sparse matrices
+
+ Examples
+ --------
+
+ Passing a ``np.random.Generator`` instance for better performance:
+
+ >>> import scipy as sp
+ >>> import numpy as np
+ >>> rng = np.random.default_rng()
+ >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng)
+
+ Providing a sampler for the values:
+
+ >>> rvs = sp.stats.poisson(25, loc=10).rvs
+ >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=rvs)
+ >>> S.toarray()
+ array([[ 36., 0., 33., 0.], # random
+ [ 0., 0., 0., 0.],
+ [ 0., 0., 36., 0.]])
+
+ Building a custom distribution.
+ This example builds a squared normal from np.random:
+
+ >>> def np_normal_squared(size=None, rng=rng):
+ ... return rng.standard_normal(size) ** 2
+ >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng,
+ ... data_rvs=np_normal_squared)
+
+ Or we can build it from sp.stats style rvs functions:
+
+ >>> def sp_stats_normal_squared(size=None, rng=rng):
+ ... std_normal = sp.stats.distributions.norm_gen().rvs
+ ... return std_normal(size=size, random_state=rng) ** 2
+ >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng,
+ ... data_rvs=sp_stats_normal_squared)
+
+ Or we can subclass sp.stats rv_continuous or rv_discrete:
+
+ >>> class NormalSquared(sp.stats.rv_continuous):
+ ... def _rvs(self, size=None, random_state=rng):
+ ... return rng.standard_normal(size) ** 2
+ >>> X = NormalSquared()
+ >>> Y = X() # get a frozen version of the distribution
+ >>> S = sp.sparse.random(3, 4, density=0.25, rng=rng, data_rvs=Y.rvs)
+ """
+ if n is None:
+ n = m
+ m, n = int(m), int(n)
+ # make keyword syntax work for data_rvs e.g. data_rvs(size=7)
+ if data_rvs is not None:
+ def data_rvs_kw(size):
+ return data_rvs(size)
+ else:
+ data_rvs_kw = None
+ vals, ind = _random((m, n), density, format, dtype, rng, data_rvs_kw)
+ return coo_matrix((vals, ind), shape=(m, n)).asformat(format)
+
+
+@_transition_to_rng("random_state", position_num=5)
+def rand(m, n, density=0.01, format="coo", dtype=None, rng=None):
+ """Generate a sparse matrix of the given shape and density with uniformly
+ distributed values.
+
+ .. warning::
+
+ This function returns a sparse matrix -- not a sparse array.
+ You are encouraged to use `random_array` to take advantage
+ of the sparse array functionality.
+
+ Parameters
+ ----------
+ m, n : int
+ shape of the matrix
+ density : real, optional
+ density of the generated matrix: density equal to one means a full
+ matrix, density of 0 means a matrix with no non-zero items.
+ format : str, optional
+ sparse matrix format.
+ dtype : dtype, optional
+ type of the returned matrix values.
+ rng : `numpy.random.Generator`, optional
+ Pseudorandom number generator state. When `rng` is None, a new
+ `numpy.random.Generator` is created using entropy from the
+ operating system. Types other than `numpy.random.Generator` are
+ passed to `numpy.random.default_rng` to instantiate a ``Generator``.
+
+ Returns
+ -------
+ res : sparse matrix
+
+ Notes
+ -----
+ Only float types are supported for now.
+
+ See Also
+ --------
+ random : Similar function allowing a custom random data sampler
+ random_array : Similar to random() but returns a sparse array
+
+ Examples
+ --------
+ >>> from scipy.sparse import rand
+ >>> matrix = rand(3, 4, density=0.25, format="csr", rng=42)
+ >>> matrix
+
+ >>> matrix.toarray()
+ array([[0.05641158, 0. , 0. , 0.65088847], # random
+ [0. , 0. , 0. , 0.14286682],
+ [0. , 0. , 0. , 0. ]])
+
+ """
+ return random(m, n, density, format, dtype, rng)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_coo.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_coo.py
new file mode 100644
index 0000000000000000000000000000000000000000..444a659ac1a99c12a01e5f8971b527802699f242
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_coo.py
@@ -0,0 +1,1890 @@
+""" 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,
+ isintlike, isdense)
+from ._index import _validate_indices, _broadcast_arrays
+
+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(copy=copy)
+ 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: # dim>2
+ 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 __getitem__(self, key):
+ index, new_shape, arr_int_pos, none_pos = _validate_indices(
+ key, self.shape, self.format
+ )
+ # handle int, slice and int-array indices
+ index_mask = np.ones(len(self.data), dtype=np.bool_)
+ slice_coords = []
+ arr_coords = []
+ arr_indices = []
+ for i, (idx, co) in enumerate(zip(index, self.coords)):
+ if isinstance(idx, int):
+ index_mask &= (co == idx)
+ elif isinstance(idx, slice):
+ if idx == slice(None):
+ slice_coords.append(co)
+ else:
+ start, stop, step = idx.indices(self.shape[i])
+ if step != 1:
+ if step < 0:
+ in_range = (co <= start) & (co > stop)
+ else:
+ in_range = (co >= start) & (co < stop)
+ new_ix, m = np.divmod(co - start, step)
+ index_mask &= (m == 0) & in_range
+ else:
+ in_range = (co >= start) & (co < stop)
+ new_ix = co - start
+ index_mask &= in_range
+ slice_coords.append(new_ix)
+ else: # array
+ arr_coords.append(co)
+ arr_indices.append(idx)
+ # shortcut for scalar output
+ if new_shape == ():
+ return self.data[index_mask].sum().astype(self.dtype, copy=False)
+
+ new_coords = [co[index_mask] for co in slice_coords]
+ new_data = self.data[index_mask]
+
+ # handle array indices
+ if arr_indices:
+ arr_indices = _broadcast_arrays(*arr_indices)
+ arr_shape = arr_indices[0].shape # already broadcast in validate_indices
+ # There are three dimensions required to check array indices against coords
+ # Their lengths are described as:
+ # a) number of indices that are arrays - arr_dim
+ # b) number of coords to check - masked_nnz (already masked by slices)
+ # c) size of the index arrays - arr_size
+ # Note for this, integer indices are treated like slices, not like arrays.
+ #
+ # Goal:
+ # Find new_coords and index positions that match across all arr_dim axes.
+ # Approach: Track matches using bool array. Size: masked_nnz by arr_size.
+ # True means all arr_indices match at that coord and index position.
+ # Equate with broadcasting and check for all equal across (arr_dim) axis 0.
+ # 1st array is "keyarr" (arr_dim by 1 by arr_size) from arr_indices.
+ # 2nd array is "arr_coords" (arr_dim by masked_nnz by 1) from arr_coords.
+ keyarr = np.array(arr_indices).reshape(len(arr_indices), 1, -1)
+ arr_coords = np.array([co[index_mask] for co in arr_coords])[:, :, None]
+ found = (keyarr == arr_coords).all(axis=0)
+ arr_co, arr_ix = found.nonzero()
+ new_data = new_data[arr_co]
+ new_coords = [co[arr_co] for co in new_coords]
+ new_arr_coords = list(np.unravel_index(arr_ix, shape=arr_shape))
+
+ # check for contiguous positions of array and int indices
+ if len(arr_int_pos) == arr_int_pos[-1] - arr_int_pos[0] + 1:
+ # Contiguous. Put all array index shape at pos of array indices
+ pos = arr_int_pos[0]
+ new_coords = new_coords[:pos] + new_arr_coords + new_coords[pos:]
+ else:
+ # Not contiguous. Put all array coords at front
+ new_coords = new_arr_coords + new_coords
+
+ if none_pos:
+ if new_coords:
+ coord_like = np.zeros_like(new_coords[0])
+ else:
+ coord_like = np.zeros(len(new_data), dtype=self.coords[0].dtype)
+ new_coords.insert(none_pos[0], coord_like)
+ for i in none_pos[1:]:
+ new_coords.insert(i, coord_like.copy())
+ return coo_array((new_data, new_coords), shape=new_shape, dtype=self.dtype)
+
+ def __setitem__(self, key, x):
+ # enact self[key] = x
+ index, new_shape, arr_int_pos, none_pos = _validate_indices(
+ key, self.shape, self.format
+ )
+
+ # remove None's at beginning of index. Should not impact indexing coords
+ # and will mistakenly align with x_coord columns if not removed.
+ if none_pos:
+ new_shape = list(new_shape)
+ for j in none_pos[::-1]:
+ new_shape.pop(j)
+ new_shape = tuple(new_shape)
+
+ # broadcast arrays
+ if arr_int_pos:
+ index = list(index)
+ arr_pos = {i: arr for i in arr_int_pos if not isintlike(arr := index[i])}
+ arr_indices = _broadcast_arrays(*arr_pos.values())
+ for i, arr in zip(arr_pos, arr_indices):
+ index[i] = arr
+
+ # get coords and data from x
+ if issparse(x):
+ if 0 in x.shape:
+ return # Nothing to set.
+ x_data, x_coords = _get_sparse_data_and_coords(x, new_shape, self.dtype)
+ else:
+ x = np.asarray(x, dtype=self.dtype)
+ if x.size == 0:
+ return # Nothing to set.
+ x_data, x_coords = _get_dense_data_and_coords(x, new_shape)
+
+ # Approach:
+ # Set indexed values to zero (drop from `self.coords` and `self.data`)
+ # create new coords and data arrays for setting nonzeros
+ # concatenate old (undropped) values with new coords and data
+
+ old_data, old_coords = self._zero_many(index)
+
+ if len(x_coords) == 1 and len(x_coords[0]) == 0:
+ self.data, self.coords = old_data, old_coords
+ # leave self.has_canonical_format unchanged
+ return
+
+ # To process array indices, need the x_coords for those axes
+ # and need to ravel the array part of x_coords to build new_coords
+ # Along the way, Find pos and shape of array-index portion of key.
+ # arr_shape is None and pos = -1 when no arrays are used as indices.
+ arr_shape = None
+ pos = -1
+ if arr_int_pos:
+ # Get arr_shape if any arrays are in the index.
+ # Also ravel the corresponding x_coords.
+ for idx in index:
+ if not isinstance(idx, slice) and not isintlike(idx):
+ arr_shape = idx.shape
+
+ # Find x_coord pos of integer and array portion of index.
+ # If contiguous put int and array axes at pos of those indices.
+ # If not contiguous, put all int and array axes at pos=0.
+ if len(arr_int_pos) == (arr_int_pos[-1] - arr_int_pos[0] + 1):
+ pos = arr_int_pos[0]
+ else:
+ pos = 0
+
+ # compute the raveled coords of the array part of x_coords.
+ # Used to build the new coords from the index arrays.
+ x_arr_coo = x_coords[pos:pos + len(arr_shape)]
+ # could use np.ravel_multi_index but _ravel_coords avoids overflow
+ x_arr_coo_ravel = _ravel_coords(x_arr_coo, arr_shape)
+ break
+
+ # find map from x_coord slice axes to index axes
+ x_ax = 0
+ x_axes = {}
+ for i, idx in enumerate(index):
+ if i == pos:
+ x_ax += len(arr_shape)
+ if isinstance(idx, slice):
+ x_axes[i] = x_ax
+ x_ax += 1
+
+ # Build new_coords and new_data
+ new_coords = [None] * self.ndim
+ new_nnz = len(x_data)
+ for i, idx in enumerate(index):
+ if isintlike(idx):
+ new_coords[i] = (np.broadcast_to(idx, (new_nnz,)))
+ continue
+ elif isinstance(idx, slice):
+ start, stop, step = idx.indices(self.shape[i])
+ new_coords[i] = (start + x_coords[x_axes[i]] * step)
+ else: # array idx
+ new_coords[i] = idx.ravel()[x_arr_coo_ravel]
+ # seems like a copy is prudent when setting data in this array
+ new_data = x_data.copy()
+
+ # deduplicate entries created by multiple coords matching in the array index
+ # NumPy does not specify which value is put into the spot (last one assigned)
+ # so only one value should appear if we want to match NumPy.
+ # If matching NumPy is not crucial, we could make dups a feature where
+ # integer array indices with repeated indices creates duplicate values.
+ # Not doing that here. We are just removing duplicates (keep 1st data found)
+ new_coords = np.array(new_coords)
+ _, ind = np.unique(new_coords, axis=1, return_index=True)
+
+ # update values with stack of old and new data and coords.
+ self.data = np.hstack([old_data, new_data[ind]])
+ self.coords = tuple(np.hstack(c) for c in zip(old_coords, new_coords[:, ind]))
+ self.has_canonical_format = False
+
+ def _zero_many(self, index):
+ # handle int, slice and integer-array indices
+ # index_mask accumulates a bool array of nonzeros that match index
+ index_mask=np.ones(len(self.data), dtype=np.bool_)
+ arr_coords = []
+ arr_indices = []
+ for i, (idx, co) in enumerate(zip(index, self.coords)):
+ if isinstance(idx, int):
+ index_mask &= (co == idx)
+ elif isinstance(idx, slice) and idx != slice(None):
+ start, stop, step = idx.indices(self.shape[i])
+ if step != 1:
+ if step < 0:
+ in_range = (co <= start) & (co > stop)
+ else:
+ in_range = (co >= start) & (co < stop)
+ m = np.mod(co - start, step)
+ index_mask &= (m == 0) & in_range
+ else:
+ in_range = (co >= start) & (co < stop)
+ index_mask &= in_range
+ elif isinstance(idx, slice) and idx == slice(None):
+ # slice is full axis so no changes to index_mask
+ pass
+ else: # array
+ arr_coords.append(co)
+ arr_indices.append(idx)
+
+ # match array indices with masked coords. See comments in __getitem__
+ if arr_indices:
+ keyarr = np.array(arr_indices).reshape(len(arr_indices), 1, -1)
+ arr_coords = np.array([co[index_mask] for co in arr_coords])[:, :, None]
+ found = (keyarr == arr_coords).all(axis=0)
+ arr_coo, _ = found.nonzero()
+ arr_index_mask = np.zeros_like(index_mask)
+ arr_index_mask[index_mask.nonzero()[0][arr_coo]] = True
+ index_mask &= arr_index_mask
+
+ # remove matching coords and data to set them to zero
+ pruned_coords = [co[~index_mask] for co in self.coords]
+ pruned_data = self.data[~index_mask]
+ return pruned_data, pruned_coords
+
+ 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
+ # Allow custom sparse class indicated by attr sparse gh-6520
+ 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)
+ """
+ # handle non-array input: lists, ints, etc
+ 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
+
+ # Handle scalar multiplication
+ if isscalarlike(other):
+ return self * other
+
+ # other.shape[-2:][0] gets last index of 1d, next to last index of >1d
+ if self.shape[-1] != other.shape[-2:][0]:
+ raise ValueError(f"shapes {self.shape} and {other.shape}"
+ " are not aligned for n-D dot")
+
+ if self.ndim < 3 and other.ndim < 3:
+ return self @ other
+ if isdense(other):
+ return self._dense_dot(other)
+ return self._sparse_dot(other.tocoo())
+
+ def _sparse_dot(self, other):
+ # already checked: at least one is >2d, neither scalar, both are coo
+ # Ravel non-reduced axes coordinates
+ self_2d, s_new_shape = _convert_to_2d(self, [self.ndim - 1])
+ other_2d, o_new_shape = _convert_to_2d(other, [max(0, other.ndim - 2)])
+
+ prod = self_2d @ other_2d.T # routes via 2-D CSR
+ prod = prod.tocoo()
+
+ # Combine the shapes of the non-contracted axes
+ combined_shape = s_new_shape + o_new_shape
+
+ # Unravel the 2D coordinates to get multi-dimensional coordinates
+ coords = []
+ new_shapes = (s_new_shape, o_new_shape) if s_new_shape else (o_new_shape,)
+ for c, s in zip(prod.coords, new_shapes):
+ coords.extend(np.unravel_index(c, s))
+
+ # Construct the resulting COO array with coords and shape
+ return coo_array((prod.data, coords), shape=combined_shape)
+
+ def _dense_dot(self, other):
+ # already checked: self is >0d, other is dense and >0d
+ # Ravel non-reduced axes coordinates
+ s_ndim = self.ndim
+ if s_ndim <= 2:
+ s_new_shape = () if s_ndim == 1 else (self.shape[0],)
+ self_2d = self
+ else:
+ self_2d, s_new_shape = _convert_to_2d(self, [self.ndim - 1])
+
+ o_ndim = other.ndim
+ if o_ndim <= 2:
+ o_new_shape = () if o_ndim == 1 else (other.shape[-1],)
+ other_2d = other
+ else:
+ o_new_shape = other.shape[:-2] + other.shape[-1:]
+ reorder_dims = (o_ndim - 2, *range(o_ndim - 2), o_ndim - 1)
+ o_reorg = np.transpose(other, reorder_dims)
+ other_2d = o_reorg.reshape((other.shape[-2], math.prod(o_new_shape)))
+
+ prod = self_2d @ other_2d # routes via 2-D CSR
+
+ # Combine the shapes of the non-contracted axes
+ combined_shape = s_new_shape + o_new_shape
+ return prod.reshape(combined_shape)
+
+
+ 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, s_axes, o_axes):
+ # Prepare the tensors for tensordot operation
+ # Ravel non-reduced axes coordinates
+ self_2d, s_new_shape = _convert_to_2d(self, s_axes)
+ other_2d, o_new_shape = _convert_to_2d(other, o_axes)
+
+ # Perform matrix multiplication (routed via 2-D CSR)
+ prod = self_2d @ other_2d.T
+ # handle case of scalar result (axis includes all axes for both)
+ if not issparse(prod):
+ return prod
+ prod = prod.tocoo()
+
+ # Combine the shapes of the non-contracted axes
+ combined_shape = s_new_shape + o_new_shape
+
+ # Unravel the 2D coordinates to get multi-dimensional coordinates
+ coords = []
+ new_shapes = (s_new_shape, o_new_shape) if s_new_shape else (o_new_shape,)
+ for c, s in zip(prod.coords, new_shapes):
+ if s:
+ coords.extend(np.unravel_index(c, s))
+
+ # Construct the resulting COO array with coords and shape
+ return coo_array((prod.data, coords), shape=combined_shape)
+
+ def _dense_tensordot(self, other, s_axes, o_axes):
+ s_ndim = len(self.shape)
+ o_ndim = len(other.shape)
+
+ s_non_axes = [i for i in range(s_ndim) if i not in s_axes]
+ s_axes_shape = [self.shape[i] for i in s_axes]
+ s_non_axes_shape = [self.shape[i] for i in s_non_axes]
+
+ o_non_axes = [i for i in range(o_ndim) if i not in o_axes]
+ o_axes_shape = [other.shape[i] for i in o_axes]
+ o_non_axes_shape = [other.shape[i] for i in o_non_axes]
+
+ left = self.transpose(s_non_axes + s_axes)
+ right = np.transpose(other, o_non_axes[:-1] + o_axes + o_non_axes[-1:])
+
+ reshape_left = (*s_non_axes_shape, math.prod(s_axes_shape))
+ reshape_right = (*o_non_axes_shape[:-1], math.prod(o_axes_shape),
+ *o_non_axes_shape[-1:])
+
+ return left.reshape(reshape_left).dot(right.reshape(reshape_right))
+
+ 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 _sum_nd(self, axis, res_dtype, out):
+ # axis and out are preprocessed. out.shape is new_shape
+ A2d, new_shape = _convert_to_2d(self, axis)
+ ones = np.ones((A2d.shape[1], 1), dtype=res_dtype)
+ # sets dtype while loading into out
+ out[...] = (A2d @ ones).reshape(new_shape)
+ return out
+
+ def _min_or_max_axis_nd(self, axis, min_or_max, explicit):
+ A2d, new_shape = _convert_to_2d(self, axis)
+ res = A2d._min_or_max_axis(1, min_or_max, explicit)
+ unraveled_coords = np.unravel_index(res.coords[0], new_shape)
+
+ return coo_array((res.data, unraveled_coords), new_shape)
+
+ def _argminmax_axis_nd(self, axis, argminmax, compare, explicit):
+ A2d, new_shape = _convert_to_2d(self, axis)
+ res_flat = A2d._argminmax_axis(1, argminmax, compare, explicit)
+ return res_flat.reshape(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 _get_sparse_data_and_coords(x, new_shape, dtype):
+ x = x.tocoo()
+ x.sum_duplicates()
+
+ x_coords = list(x.coords)
+ x_data = x.data.astype(dtype, copy=False)
+ x_shape = x.shape
+
+ if new_shape == x_shape:
+ return x_data, x_coords
+
+ # broadcasting needed
+ len_diff = len(new_shape) - len(x_shape)
+ if len_diff > 0:
+ # prepend ones to shape of x to match ndim
+ x_shape = [1] * len_diff + list(x_shape)
+ coord_zeros = np.zeroslike(x_coords[0])
+ x_coords = tuple([coord_zeros] * len_diff + x_coords)
+ # taking away axes (squeezing) is not part of broadcasting, but long
+ # spmatrix history of using 2d vectors in 1d space, so we manually
+ # squeeze the front and back axes here to be compatible
+ if len_diff < 0:
+ for _ in range(-len_diff):
+ if x_shape[0] == 1:
+ x_shape = x_shape[1:]
+ x_coords = x_coords[1:]
+ elif x_shape[-1] == 1:
+ x_shape = x_shape[:-1]
+ x_coords = x_coords[:-1]
+ else:
+ raise ValueError("shape mismatch in assignment")
+ # broadcast with copy (will need to copy eventually anyway)
+ tot_expand = 1
+ for i, (nn, nx) in enumerate(zip(new_shape, x_shape)):
+ if nn == nx:
+ continue
+ if nx != 1:
+ raise ValueError("shape mismatch in assignment")
+ x_nnz = len(x_coords[0])
+ x_coords[i] = np.repeat(np.arange(nn), x_nnz)
+ for j, co in enumerate(x_coords):
+ if j == i:
+ continue
+ x_coords[j] = np.tile(co, nn)
+ tot_expand *= nn
+ x_data = np.tile(x_data.ravel(), tot_expand)
+ return x_data, x_coords
+
+
+def _get_dense_data_and_coords(x, new_shape):
+ if x.shape != new_shape:
+ x = np.broadcast_to(x.squeeze(), new_shape)
+ # shift scalar input to 1d so has coords
+ if new_shape == ():
+ x_coords = tuple([np.array([0])] * len(new_shape))
+ x_data = x.ravel()
+ else:
+ x_coords = x.nonzero()
+ x_data = x[x_coords]
+ return x_data, x_coords
+
+
+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 _convert_to_2d(coo, axis):
+ axis_coords = tuple(coo.coords[i] for i in axis)
+ axis_shape = tuple(coo.shape[i] for i in axis)
+ axis_ravel = _ravel_coords(axis_coords, axis_shape)
+
+ ndim = len(coo.coords)
+ non_axis = tuple(i for i in range(ndim) if i not in axis)
+ if non_axis:
+ non_axis_coords = tuple(coo.coords[i] for i in non_axis)
+ non_axis_shape = tuple(coo.shape[i] for i in non_axis)
+ non_axis_ravel = _ravel_coords(non_axis_coords, non_axis_shape)
+ coords_2d = (non_axis_ravel, axis_ravel)
+ shape_2d = (math.prod(non_axis_shape), math.prod(axis_shape))
+ else: # all axes included in axis so result will have 1 element
+ coords_2d = (axis_ravel,)
+ shape_2d = (math.prod(axis_shape),)
+ non_axis_shape = ()
+
+ new_coo = coo_array((coo.data, coords_2d), shape=shape_2d)
+ return new_coo, non_axis_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)
+
+ def __getitem__(self, key):
+ raise TypeError("'coo_matrix' object is not subscriptable")
+
+ def __setitem__(self, key, x):
+ raise TypeError("'coo_matrix' object does not support item assignment")
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_csc.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_csc.py
new file mode 100644
index 0000000000000000000000000000000000000000..32eb9f2a1bbf53320487ce3fadfc8799600ab049
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/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 csr_tocsc, 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))
+
+ csr_tocsc(N, M,
+ self.indptr.astype(idx_dtype, copy=False),
+ self.indices.astype(idx_dtype, copy=False),
+ 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(f'index ({i}) out of range')
+ 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(f'index ({i}) out of range')
+ return self._get_submatrix(major=i, copy=True)
+
+ def _get_intXarray(self, row, col):
+ return self._major_index_fancy(col)._get_submatrix(minor=row)
+
+ def _get_intXslice(self, row, col):
+ if col.step in (1, None):
+ return self._get_submatrix(major=col, minor=row, copy=True)
+ return self._major_slice(col)._get_submatrix(minor=row)
+
+ def _get_sliceXint(self, row, col):
+ if row.step in (1, None):
+ return self._get_submatrix(major=col, minor=row, copy=True)
+ return self._get_submatrix(major=col)._minor_slice(row)
+
+ def _get_sliceXarray(self, row, col):
+ return self._major_index_fancy(col)._minor_slice(row)
+
+ def _get_arrayXint(self, row, col):
+ res = self._get_submatrix(major=col)._minor_index_fancy(row)
+ if row.ndim > 1:
+ return res.reshape(row.shape)
+ return res
+
+ def _get_arrayXslice(self, row, col):
+ return self._major_slice(col)._minor_index_fancy(row)
+
+ # these functions are used by the parent class (_cs_matrix)
+ # to remove redundancy between csc_array and csr_matrix
+ @staticmethod
+ def _swap(x):
+ """swap the members of x if this is a column-oriented matrix
+ """
+ return x[1], x[0]
+
+
+def isspmatrix_csc(x):
+ """Is `x` of csc_matrix type?
+
+ Parameters
+ ----------
+ x
+ object to check for being a csc matrix
+
+ Returns
+ -------
+ bool
+ True if `x` is a csc matrix, False otherwise
+
+ Examples
+ --------
+ >>> from scipy.sparse import csc_array, csc_matrix, coo_matrix, isspmatrix_csc
+ >>> isspmatrix_csc(csc_matrix([[5]]))
+ True
+ >>> isspmatrix_csc(csc_array([[5]]))
+ False
+ >>> isspmatrix_csc(coo_matrix([[5]]))
+ False
+ """
+ return isinstance(x, csc_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class csc_array(_csc_base, sparray):
+ """
+ Compressed Sparse Column array.
+
+ This can be instantiated in several ways:
+ csc_array(D)
+ where D is a 2-D ndarray
+
+ csc_array(S)
+ with another sparse array or matrix S (equivalent to S.tocsc())
+
+ csc_array((M, N), [dtype])
+ to construct an empty array with shape (M, N)
+ dtype is optional, defaulting to dtype='d'.
+
+ csc_array((data, (row_ind, col_ind)), [shape=(M, N)])
+ where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+ relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+ csc_array((data, indices, indptr), [shape=(M, N)])
+ is the standard CSC representation where the row indices for
+ column i are stored in ``indices[indptr[i]:indptr[i+1]]``
+ and their corresponding values are stored in
+ ``data[indptr[i]:indptr[i+1]]``. If the shape parameter is
+ not supplied, the array dimensions are inferred from
+ the index arrays.
+
+ Attributes
+ ----------
+ dtype : dtype
+ Data type of the array
+ shape : 2-tuple
+ Shape of the array
+ ndim : int
+ Number of dimensions (this is always 2)
+ nnz
+ size
+ data
+ CSC format data array of the array
+ indices
+ CSC format index array of the array
+ indptr
+ CSC format index pointer array of the array
+ has_sorted_indices
+ has_canonical_format
+ T
+
+ Notes
+ -----
+
+ Sparse arrays can be used in arithmetic operations: they support
+ addition, subtraction, multiplication, division, and matrix power.
+
+ Advantages of the CSC format
+ - efficient arithmetic operations CSC + CSC, CSC * CSC, etc.
+ - efficient column slicing
+ - fast matrix vector products (CSR, BSR may be faster)
+
+ Disadvantages of the CSC format
+ - slow row slicing operations (consider CSR)
+ - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+ Canonical format
+ - Within each column, indices are sorted by row.
+ - There are no duplicate entries.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> from scipy.sparse import csc_array
+ >>> csc_array((3, 4), dtype=np.int8).toarray()
+ array([[0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]], dtype=int8)
+
+ >>> row = np.array([0, 2, 2, 0, 1, 2])
+ >>> col = np.array([0, 0, 1, 2, 2, 2])
+ >>> data = np.array([1, 2, 3, 4, 5, 6])
+ >>> csc_array((data, (row, col)), shape=(3, 3)).toarray()
+ array([[1, 0, 4],
+ [0, 0, 5],
+ [2, 3, 6]])
+
+ >>> indptr = np.array([0, 2, 3, 6])
+ >>> indices = np.array([0, 2, 2, 0, 1, 2])
+ >>> data = np.array([1, 2, 3, 4, 5, 6])
+ >>> csc_array((data, indices, indptr), shape=(3, 3)).toarray()
+ array([[1, 0, 4],
+ [0, 0, 5],
+ [2, 3, 6]])
+
+ """
+
+
+class csc_matrix(spmatrix, _csc_base):
+ """
+ Compressed Sparse Column matrix.
+
+ This can be instantiated in several ways:
+ csc_matrix(D)
+ where D is a 2-D ndarray
+
+ csc_matrix(S)
+ with another sparse array or matrix S (equivalent to S.tocsc())
+
+ csc_matrix((M, N), [dtype])
+ to construct an empty matrix with shape (M, N)
+ dtype is optional, defaulting to dtype='d'.
+
+ csc_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
+ where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+ relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+ csc_matrix((data, indices, indptr), [shape=(M, N)])
+ is the standard CSC representation where the row indices for
+ column i are stored in ``indices[indptr[i]:indptr[i+1]]``
+ and their corresponding values are stored in
+ ``data[indptr[i]:indptr[i+1]]``. If the shape parameter is
+ not supplied, the matrix dimensions are inferred from
+ the index arrays.
+
+ Attributes
+ ----------
+ dtype : dtype
+ Data type of the matrix
+ shape : 2-tuple
+ Shape of the matrix
+ ndim : int
+ Number of dimensions (this is always 2)
+ nnz
+ size
+ data
+ CSC format data array of the matrix
+ indices
+ CSC format index array of the matrix
+ indptr
+ CSC format index pointer array of the matrix
+ has_sorted_indices
+ has_canonical_format
+ T
+
+ Notes
+ -----
+
+ Sparse matrices can be used in arithmetic operations: they support
+ addition, subtraction, multiplication, division, and matrix power.
+
+ Advantages of the CSC format
+ - efficient arithmetic operations CSC + CSC, CSC * CSC, etc.
+ - efficient column slicing
+ - fast matrix vector products (CSR, BSR may be faster)
+
+ Disadvantages of the CSC format
+ - slow row slicing operations (consider CSR)
+ - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+ Canonical format
+ - Within each column, indices are sorted by row.
+ - There are no duplicate entries.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> from scipy.sparse import csc_matrix
+ >>> csc_matrix((3, 4), dtype=np.int8).toarray()
+ array([[0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]], dtype=int8)
+
+ >>> row = np.array([0, 2, 2, 0, 1, 2])
+ >>> col = np.array([0, 0, 1, 2, 2, 2])
+ >>> data = np.array([1, 2, 3, 4, 5, 6])
+ >>> csc_matrix((data, (row, col)), shape=(3, 3)).toarray()
+ array([[1, 0, 4],
+ [0, 0, 5],
+ [2, 3, 6]])
+
+ >>> indptr = np.array([0, 2, 3, 6])
+ >>> indices = np.array([0, 2, 2, 0, 1, 2])
+ >>> data = np.array([1, 2, 3, 4, 5, 6])
+ >>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
+ array([[1, 0, 4],
+ [0, 0, 5],
+ [2, 3, 6]])
+
+ """
+
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_csparsetools.cpython-312-darwin.so b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_csparsetools.cpython-312-darwin.so
new file mode 100644
index 0000000000000000000000000000000000000000..bb4acbf910d4675e4b0b9fe2219731ef8d376c3c
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_csparsetools.cpython-312-darwin.so
@@ -0,0 +1,3 @@
+version https://git-lfs.github.com/spec/v1
+oid sha256:77a242c2937125c7b5e3aec9822299b03c6115362cb72d5a9ad94bf8d17c83fa
+size 404752
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_csr.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_csr.py
new file mode 100644
index 0000000000000000000000000000000000000000..a9938a2af88aaf0c560110b64f255673010550c3
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_csr.py
@@ -0,0 +1,568 @@
+"""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 tocoo(self, copy=False):
+ A = super().tocoo(copy=copy)
+ # CSR-to-COO conversion always preserves [non-]canonicity
+ # (indices sorting, presense of duplicate elements).
+ # Handled here instead of _cs_matrix because CSC-to-COO generally does not.
+ A.has_canonical_format = self.has_canonical_format
+ return A
+
+ tocoo.__doc__ = _spbase.tocoo.__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, copy=False),
+ self.indices.astype(idx_dtype, copy=False),
+ 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, copy=False),
+ self.indices.astype(idx_dtype, copy=False),
+ 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(f'index ({i}) out of range')
+ 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(f'index ({i}) out of range')
+ indptr, indices, data = get_csr_submatrix(
+ M, N, self.indptr, self.indices, self.data, 0, M, i, i + 1)
+ return self.__class__((data, indices, indptr), shape=(M, 1),
+ dtype=self.dtype, copy=False)
+
+ def _get_int(self, idx):
+ spot = np.flatnonzero(self.indices == idx)
+ if spot.size:
+ return self.data[spot[0]]
+ return self.data.dtype.type(0)
+
+ def _get_slice(self, idx):
+ if idx == slice(None):
+ return self.copy()
+ if idx.step in (1, None):
+ ret = self._get_submatrix(0, idx, copy=True)
+ return ret.reshape(ret.shape[-1])
+ return self._minor_slice(idx)
+
+ def _get_array(self, idx):
+ idx_dtype = self._get_index_dtype(self.indices)
+ idx = np.asarray(idx, dtype=idx_dtype)
+ if idx.size == 0:
+ return self.__class__([], dtype=self.dtype)
+
+ M, N = 1, self.shape[0]
+ row = np.zeros_like(idx, dtype=idx_dtype)
+ col = np.asarray(idx, dtype=idx_dtype)
+ val = np.empty(row.size, dtype=self.dtype)
+ csr_sample_values(M, N, self.indptr, self.indices, self.data,
+ row.size, row, col, val)
+
+ new_shape = col.shape if col.shape[0] > 1 else (col.shape[0],)
+ return self.__class__(val.reshape(new_shape))
+
+ def _get_intXarray(self, row, col):
+ return self._getrow(row)._minor_index_fancy(col)
+
+ def _get_intXslice(self, row, col):
+ if col.step in (1, None):
+ return self._get_submatrix(row, col, copy=True)
+ # TODO: uncomment this once it's faster:
+ # return self._getrow(row)._minor_slice(col)
+
+ M, N = self.shape
+ start, stop, stride = col.indices(N)
+
+ ii, jj = self.indptr[row:row+2]
+ row_indices = self.indices[ii:jj]
+ row_data = self.data[ii:jj]
+
+ if stride > 0:
+ ind = (row_indices >= start) & (row_indices < stop)
+ else:
+ ind = (row_indices <= start) & (row_indices > stop)
+
+ if abs(stride) > 1:
+ ind &= (row_indices - start) % stride == 0
+
+ row_indices = (row_indices[ind] - start) // stride
+ row_data = row_data[ind]
+ row_indptr = np.array([0, len(row_indices)])
+
+ if stride < 0:
+ row_data = row_data[::-1]
+ row_indices = abs(row_indices[::-1])
+
+ shape = (1, max(0, int(np.ceil(float(stop - start) / stride))))
+ return self.__class__((row_data, row_indices, row_indptr), shape=shape,
+ dtype=self.dtype, copy=False)
+
+ def _get_sliceXint(self, row, col):
+ if row.step in (1, None):
+ return self._get_submatrix(row, col, copy=True)
+ return self._major_slice(row)._get_submatrix(minor=col)
+
+ def _get_sliceXarray(self, row, col):
+ return self._major_slice(row)._minor_index_fancy(col)
+
+ def _get_arrayXint(self, row, col):
+ res = self._major_index_fancy(row)._get_submatrix(minor=col)
+ if row.ndim > 1:
+ return res.reshape(row.shape)
+ return res
+
+ def _get_arrayXslice(self, row, col):
+ if col.step not in (1, None):
+ col = np.arange(*col.indices(self.shape[1]))
+ return self._get_arrayXarray(row, col)
+ return self._major_index_fancy(row)._get_submatrix(minor=col)
+
+ def _set_int(self, idx, x):
+ self._set_many(0, idx, x)
+
+ def _set_array(self, idx, x):
+ x = np.broadcast_to(x, idx.shape)
+ self._set_many(np.zeros_like(idx), idx, x)
+
+
+def isspmatrix_csr(x):
+ """Is `x` of csr_matrix type?
+
+ Parameters
+ ----------
+ x
+ object to check for being a csr matrix
+
+ Returns
+ -------
+ bool
+ True if `x` is a csr matrix, False otherwise
+
+ Examples
+ --------
+ >>> from scipy.sparse import csr_array, csr_matrix, coo_matrix, isspmatrix_csr
+ >>> isspmatrix_csr(csr_matrix([[5]]))
+ True
+ >>> isspmatrix_csr(csr_array([[5]]))
+ False
+ >>> isspmatrix_csr(coo_matrix([[5]]))
+ False
+ """
+ return isinstance(x, csr_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class csr_array(_csr_base, sparray):
+ """
+ Compressed Sparse Row array.
+
+ This can be instantiated in several ways:
+ csr_array(D)
+ where D is a 2-D ndarray
+
+ csr_array(S)
+ with another sparse array or matrix S (equivalent to S.tocsr())
+
+ csr_array((M, N), [dtype])
+ to construct an empty array with shape (M, N)
+ dtype is optional, defaulting to dtype='d'.
+
+ csr_array((data, (row_ind, col_ind)), [shape=(M, N)])
+ where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+ relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+ csr_array((data, indices, indptr), [shape=(M, N)])
+ is the standard CSR representation where the column indices for
+ row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their
+ corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``.
+ If the shape parameter is not supplied, the array dimensions
+ are inferred from the index arrays.
+
+ Attributes
+ ----------
+ dtype : dtype
+ Data type of the array
+ shape : 2-tuple
+ Shape of the array
+ ndim : int
+ Number of dimensions (this is always 2)
+ nnz
+ size
+ data
+ CSR format data array of the array
+ indices
+ CSR format index array of the array
+ indptr
+ CSR format index pointer array of the array
+ has_sorted_indices
+ has_canonical_format
+ T
+
+ Notes
+ -----
+
+ Sparse arrays can be used in arithmetic operations: they support
+ addition, subtraction, multiplication, division, and matrix power.
+
+ Advantages of the CSR format
+ - efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
+ - efficient row slicing
+ - fast matrix vector products
+
+ Disadvantages of the CSR format
+ - slow column slicing operations (consider CSC)
+ - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+ Canonical Format
+ - Within each row, indices are sorted by column.
+ - There are no duplicate entries.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> from scipy.sparse import csr_array
+ >>> csr_array((3, 4), dtype=np.int8).toarray()
+ array([[0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]], dtype=int8)
+
+ >>> row = np.array([0, 0, 1, 2, 2, 2])
+ >>> col = np.array([0, 2, 2, 0, 1, 2])
+ >>> data = np.array([1, 2, 3, 4, 5, 6])
+ >>> csr_array((data, (row, col)), shape=(3, 3)).toarray()
+ array([[1, 0, 2],
+ [0, 0, 3],
+ [4, 5, 6]])
+
+ >>> indptr = np.array([0, 2, 3, 6])
+ >>> indices = np.array([0, 2, 2, 0, 1, 2])
+ >>> data = np.array([1, 2, 3, 4, 5, 6])
+ >>> csr_array((data, indices, indptr), shape=(3, 3)).toarray()
+ array([[1, 0, 2],
+ [0, 0, 3],
+ [4, 5, 6]])
+
+ Duplicate entries are summed together:
+
+ >>> row = np.array([0, 1, 2, 0])
+ >>> col = np.array([0, 1, 1, 0])
+ >>> data = np.array([1, 2, 4, 8])
+ >>> csr_array((data, (row, col)), shape=(3, 3)).toarray()
+ array([[9, 0, 0],
+ [0, 2, 0],
+ [0, 4, 0]])
+
+ As an example of how to construct a CSR array incrementally,
+ the following snippet builds a term-document array from texts:
+
+ >>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
+ >>> indptr = [0]
+ >>> indices = []
+ >>> data = []
+ >>> vocabulary = {}
+ >>> for d in docs:
+ ... for term in d:
+ ... index = vocabulary.setdefault(term, len(vocabulary))
+ ... indices.append(index)
+ ... data.append(1)
+ ... indptr.append(len(indices))
+ ...
+ >>> csr_array((data, indices, indptr), dtype=int).toarray()
+ array([[2, 1, 0, 0],
+ [0, 1, 1, 1]])
+
+ """
+
+
+class csr_matrix(spmatrix, _csr_base):
+ """
+ Compressed Sparse Row matrix.
+
+ This can be instantiated in several ways:
+ csr_matrix(D)
+ where D is a 2-D ndarray
+
+ csr_matrix(S)
+ with another sparse array or matrix S (equivalent to S.tocsr())
+
+ csr_matrix((M, N), [dtype])
+ to construct an empty matrix with shape (M, N)
+ dtype is optional, defaulting to dtype='d'.
+
+ csr_matrix((data, (row_ind, col_ind)), [shape=(M, N)])
+ where ``data``, ``row_ind`` and ``col_ind`` satisfy the
+ relationship ``a[row_ind[k], col_ind[k]] = data[k]``.
+
+ csr_matrix((data, indices, indptr), [shape=(M, N)])
+ is the standard CSR representation where the column indices for
+ row i are stored in ``indices[indptr[i]:indptr[i+1]]`` and their
+ corresponding values are stored in ``data[indptr[i]:indptr[i+1]]``.
+ If the shape parameter is not supplied, the matrix dimensions
+ are inferred from the index arrays.
+
+ Attributes
+ ----------
+ dtype : dtype
+ Data type of the matrix
+ shape : 2-tuple
+ Shape of the matrix
+ ndim : int
+ Number of dimensions (this is always 2)
+ nnz
+ size
+ data
+ CSR format data array of the matrix
+ indices
+ CSR format index array of the matrix
+ indptr
+ CSR format index pointer array of the matrix
+ has_sorted_indices
+ has_canonical_format
+ T
+
+ Notes
+ -----
+
+ Sparse matrices can be used in arithmetic operations: they support
+ addition, subtraction, multiplication, division, and matrix power.
+
+ Advantages of the CSR format
+ - efficient arithmetic operations CSR + CSR, CSR * CSR, etc.
+ - efficient row slicing
+ - fast matrix vector products
+
+ Disadvantages of the CSR format
+ - slow column slicing operations (consider CSC)
+ - changes to the sparsity structure are expensive (consider LIL or DOK)
+
+ Canonical Format
+ - Within each row, indices are sorted by column.
+ - There are no duplicate entries.
+
+ Examples
+ --------
+
+ >>> import numpy as np
+ >>> from scipy.sparse import csr_matrix
+ >>> csr_matrix((3, 4), dtype=np.int8).toarray()
+ array([[0, 0, 0, 0],
+ [0, 0, 0, 0],
+ [0, 0, 0, 0]], dtype=int8)
+
+ >>> row = np.array([0, 0, 1, 2, 2, 2])
+ >>> col = np.array([0, 2, 2, 0, 1, 2])
+ >>> data = np.array([1, 2, 3, 4, 5, 6])
+ >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
+ array([[1, 0, 2],
+ [0, 0, 3],
+ [4, 5, 6]])
+
+ >>> indptr = np.array([0, 2, 3, 6])
+ >>> indices = np.array([0, 2, 2, 0, 1, 2])
+ >>> data = np.array([1, 2, 3, 4, 5, 6])
+ >>> csr_matrix((data, indices, indptr), shape=(3, 3)).toarray()
+ array([[1, 0, 2],
+ [0, 0, 3],
+ [4, 5, 6]])
+
+ Duplicate entries are summed together:
+
+ >>> row = np.array([0, 1, 2, 0])
+ >>> col = np.array([0, 1, 1, 0])
+ >>> data = np.array([1, 2, 4, 8])
+ >>> csr_matrix((data, (row, col)), shape=(3, 3)).toarray()
+ array([[9, 0, 0],
+ [0, 2, 0],
+ [0, 4, 0]])
+
+ As an example of how to construct a CSR matrix incrementally,
+ the following snippet builds a term-document matrix from texts:
+
+ >>> docs = [["hello", "world", "hello"], ["goodbye", "cruel", "world"]]
+ >>> indptr = [0]
+ >>> indices = []
+ >>> data = []
+ >>> vocabulary = {}
+ >>> for d in docs:
+ ... for term in d:
+ ... index = vocabulary.setdefault(term, len(vocabulary))
+ ... indices.append(index)
+ ... data.append(1)
+ ... indptr.append(len(indices))
+ ...
+ >>> csr_matrix((data, indices, indptr), dtype=int).toarray()
+ array([[2, 1, 0, 0],
+ [0, 1, 1, 1]])
+
+ """
+
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_data.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_data.py
new file mode 100644
index 0000000000000000000000000000000000000000..5d5caa82a711e98b42794ad016e03d9d2db77856
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/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 = self.data.view(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, copy=False)
+ 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):
+ # already checked that self.shape[axis] is not zero
+ N = self.shape[axis]
+ 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 min/max does not support an 'out' parameter.")
+
+ axis = validateaxis(axis, ndim=self.ndim)
+
+ 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 any(self.shape[d] == 0 for d in axis):
+ raise ValueError("zero-size array to reduction operation")
+
+ if self.ndim == 2:
+ # note: 2D ensures that len(axis)==1 so we pass in the int axis[0]
+ return self._min_or_max_axis(axis[0], min_or_max, explicit)
+ return self._min_or_max_axis_nd(axis, min_or_max, explicit)
+
+ def _argminmax_axis(self, axis, argminmax, compare, explicit):
+ 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 = argminmax(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 _argminmax(self, axis, out, argminmax, compare, explicit):
+ if out is not None:
+ minmax = "argmin" if argminmax == np.argmin else "argmax"
+ raise ValueError(f"Sparse {minmax} does not support an 'out' parameter.")
+
+ axis = validateaxis(axis, ndim=self.ndim)
+
+ if axis is not None:
+ if any(self.shape[i] == 0 for i in axis):
+ minmax = "argmin" if argminmax == np.argmin else "argmax"
+ raise ValueError(f"Cannot apply {minmax} along a zero-sized dimension.")
+
+ if self.ndim == 2:
+ # note: 2D ensures that len(axis)==1 so we pass in the int axis[0]
+ return self._argminmax_axis(axis[0], argminmax, compare, explicit)
+ return self._argminmax_axis_nd(axis, argminmax, compare, explicit)
+
+ if 0 in self.shape:
+ minmax = "argmin" if argminmax == np.argmin else "argmax"
+ raise ValueError(f"Cannot apply {minmax} to an empty matrix.")
+
+ if self.nnz == 0:
+ if explicit:
+ minmax = "argmin" if argminmax == np.argmin else "argmax"
+ raise ValueError(f"Cannot apply {minmax} 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 = argminmax(mat.data)
+ if explicit:
+ return extreme_index
+ extreme_value = mat.data[extreme_index]
+
+ if mat.ndim > 2:
+ mat = mat.reshape(-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.
+ # And we use a "cheap test" for the rare case of no implicit zeros.
+ maxnnz = math.prod(self.shape)
+ if compare(extreme_value, zero) or mat.nnz == maxnnz:
+ # cast to Python int to avoid overflow and RuntimeError
+ if mat.ndim == 1: # includes nD case that was reshaped above
+ return int(mat.col[extreme_index])
+ # ndim == 2
+ num_col = mat.shape[-1]
+ 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.
+ if mat.ndim == 1: # includes nD case that was reshaped above
+ linear_indices = mat.coords[-1]
+ else: # ndim == 2
+ num_col = mat.shape[-1]
+ linear_indices = mat.row * num_col + mat.col
+ first_implicit_zero_index = _find_missing_index(linear_indices, maxnnz)
+ 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 an axis 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._argminmax(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 an axis 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._argminmax(axis, out, np.argmin, np.less, explicit)
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_dia.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_dia.py
new file mode 100644
index 0000000000000000000000000000000000000000..4b4649c533c1e2c4c494fe7208d03e74a5962162
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_dia.py
@@ -0,0 +1,653 @@
+"""Sparse DIAgonal format"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['dia_array', 'dia_matrix', 'isspmatrix_dia']
+
+import numpy as np
+
+from .._lib._util import _prune_array, copy_if_needed
+from ._matrix import spmatrix
+from ._base import issparse, _formats, _spbase, sparray
+from ._data import _data_matrix
+from ._sputils import (
+ isdense, isscalarlike, isshape, upcast_char, getdtype, get_sum_dtype,
+ validateaxis, check_shape
+)
+from ._sparsetools import dia_matmat, dia_matvec, dia_matvecs, dia_tocsr
+
+
+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, copy=False)
+
+ # 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(
+ f'number of diagonals ({self.data.shape[0]}) does not match the number '
+ f'of offsets ({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
+ L = min(self.data.shape[1], N)
+ return int(np.maximum(np.minimum(M + self.offsets, L) -
+ np.maximum(self.offsets, 0),
+ 0).sum())
+
+ _getnnz.__doc__ = _spbase._getnnz.__doc__
+
+ def sum(self, axis=None, dtype=None, out=None):
+ axis = validateaxis(axis)
+
+ 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: # axis is None or (1,)
+ 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, sub=False):
+ # 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 if sub else
+ 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)]
+ if sub:
+ new_data[other_idx, :] -= other.data
+ else:
+ new_data[other_idx, :] += other.data
+ elif self_d == other_d and len(new_offsets) == len(other.offsets):
+ if sub:
+ new_data = -other.data[_invert_index(other_idx)]
+ else:
+ 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]
+ if sub:
+ new_data[other_idx, :other_d] -= other.data[:, :d]
+ else:
+ new_data[other_idx, :other_d] += other.data[:, :d]
+ return self._dia_container((new_data, new_offsets), shape=self.shape)
+
+ def _sub_sparse(self, other):
+ # If other is not DIA format, use default handler.
+ if not isinstance(other, _dia_base):
+ return super()._sub_sparse(other)
+
+ return self._add_sparse(other, sub=True)
+
+ def _mul_scalar(self, other):
+ return self._with_data(self.data * other)
+
+ def multiply(self, other):
+ if isscalarlike(other):
+ return self._mul_scalar(other)
+
+ if isdense(other):
+ if other.ndim > 2:
+ return self.toarray() * other
+
+ # Use default handler for pathological cases.
+ if 0 in self.shape or 1 in self.shape or 0 in other.shape:
+ return super().multiply(other)
+
+ other = np.atleast_2d(other)
+ other_rows, other_cols = other.shape
+ rows, cols = self.shape
+ L = min(self.data.shape[1], cols)
+ data = self.data[:, :L].astype(np.result_type(self.data, other)) # copy
+ if other_rows == 1:
+ data *= other[0, :L]
+ elif other_rows != rows:
+ raise ValueError('inconsistent shapes')
+ else:
+ j = np.arange(L)
+ if L > rows:
+ i = (j - self.offsets[:, None]) % rows
+ else: # can use faster method
+ i = j - self.offsets[:, None] % rows
+ if other_cols == 1:
+ j = 0
+ elif other_cols != cols:
+ raise ValueError('inconsistent shapes')
+ data *= other[i, j]
+ return self._with_data(data)
+
+ # If other is not DIA format or needs broadcasting (unreasonable
+ # use case for DIA anyway), use default handler.
+ if not isinstance(other, _dia_base) or other.shape != self.shape:
+ return super().multiply(other)
+
+ # Find common offsets (unique diagonals don't contribute)
+ # and indices corresponding to them in multiplicand and multiplier.
+ offsets, self_idx, other_idx = \
+ np.intersect1d(self.offsets, other.offsets,
+ assume_unique=True, return_indices=True)
+ # Only overlapping length of diagonals can have non-zero products.
+ L = min(self.data.shape[1], other.data.shape[1])
+ data = self.data[self_idx, :L] * other.data[other_idx, :L]
+ return self._dia_container((data, offsets), shape=self.shape)
+
+ 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 _matmul_multivector(self, other):
+ res = np.zeros((self.shape[0], other.shape[1]),
+ dtype=np.result_type(self.data, other))
+ dia_matvecs(*self.shape, *self.data.shape, self.offsets, self.data,
+ other.shape[1], other, res)
+ return res
+
+ def _matmul_sparse(self, other):
+ # If other is not DIA format, use default handler.
+ if not isinstance(other, _dia_base):
+ return super()._matmul_sparse(other)
+
+ # If any dimension is zero, return empty array immediately.
+ if 0 in self.shape or 0 in other.shape:
+ return self._dia_container((self.shape[0], other.shape[1]))
+
+ offsets, data = dia_matmat(*self.shape, *self.data.shape,
+ self.offsets, self.data,
+ other.shape[1], *other.data.shape,
+ other.offsets, other.data)
+ return self._dia_container((data.reshape(len(offsets), -1), offsets),
+ (self.shape[0], other.shape[1]))
+
+ 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 tocsr(self, copy=False):
+ if 0 in self.shape or len(self.offsets) == 0:
+ return self._csr_container(self.shape, dtype=self.dtype)
+
+ n_rows, n_cols = self.shape
+ max_nnz = self.nnz
+ # np.argsort always returns dtype=int, which can cause automatic dtype
+ # expansion for everything else even if not needed (see gh19245), but
+ # CSR wants common dtype for indices, indptr and shape, so care should
+ # be taken to use appropriate indexing dtype throughout.
+ idx_dtype = self._get_index_dtype(maxval=max(max_nnz, n_rows, n_cols))
+ order = np.argsort(self.offsets).astype(idx_dtype, copy=False)
+ csr_data = np.empty(max_nnz, dtype=self.dtype)
+ indices = np.empty(max_nnz, dtype=idx_dtype)
+ indptr = np.empty(1 + n_rows, dtype=idx_dtype)
+ # Conversion eliminates explicit zeros and returns actual nnz.
+ nnz = dia_tocsr(n_rows, n_cols, *self.data.shape,
+ self.offsets.astype(idx_dtype, copy=False), self.data,
+ order, csr_data, indices, indptr)
+ # Shrink indexing dtype, if needed, and prune arrays.
+ idx_dtype = self._get_index_dtype(maxval=max(nnz, n_rows, n_cols))
+ csr_data = _prune_array(csr_data[:nnz])
+ indices = _prune_array(indices[:nnz].astype(idx_dtype, copy=False))
+ indptr = indptr.astype(idx_dtype, copy=False)
+ out = self._csr_container((csr_data, indices, indptr),
+ shape=self.shape, dtype=self.dtype)
+ out.has_canonical_format = True
+ return out
+
+ tocsr.__doc__ = _spbase.tocsr.__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/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_dok.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_dok.py
new file mode 100644
index 0000000000000000000000000000000000000000..9dcc293be195b292b34b2b56d3d096dc61c95c0e
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_dok.py
@@ -0,0 +1,695 @@
+"""Dictionary Of Keys based matrix"""
+
+__docformat__ = "restructuredtext en"
+
+__all__ = ['dok_array', 'dok_matrix', 'isspmatrix_dok']
+
+import itertools
+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, copy=False)
+ 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):
+ """Update values from a dict, sparse dok or iterable of 2-tuples like .items()
+
+ Keys of the input must be sequences of nonnegative integers less than the shape
+ for each axis.
+ """
+ if isinstance(val, dict):
+ inputs = val.items()
+ else:
+ inputs = val
+
+ for key, value in inputs:
+ index = (key,) if isintlike(key) else tuple(key)
+ if len(index) != self.ndim:
+ raise IndexError(f'Index {key} length needs to match self.shape')
+ if not all(
+ isintlike(idx) and 0 <= idx < max_idx
+ for idx, max_idx in zip(index, self.shape)
+ ):
+ # Error handling. Re-search to find which error occured
+ for idx, max_idx in zip(index, self.shape):
+ if not isintlike(idx):
+ raise IndexError(f'integer keys required for update. Got {key}')
+ if idx < 0:
+ raise IndexError(f'negative index {key} not allowed in update')
+ if idx >= max_idx:
+ raise IndexError(f'index {key} is too large for self.shape')
+ # do the update
+ self._dict.update(inputs)
+
+ 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 copy(self):
+ new = self._dok_container(self.shape, dtype=self.dtype)
+ new._dict.update(self._dict)
+ return new
+
+ copy.__doc__ = _spbase.copy.__doc__
+
+ @classmethod
+ def fromkeys(cls, iterable, value=1, /):
+ tmp = dict.fromkeys(iterable, value)
+ if isinstance(next(iter(tmp)), tuple):
+ shape = tuple(max(idx) + 1 for idx in zip(*tmp))
+ else:
+ shape = (max(tmp) + 1,)
+ result = cls(shape, dtype=type(value))
+ result._dict = tmp
+ return result
+
+ def tocoo(self, copy=False):
+ nnz = self.nnz
+ if nnz == 0:
+ return self._coo_container(self.shape, dtype=self.dtype)
+
+ idx_dtype = self._get_index_dtype(maxval=max(self.shape))
+ data = np.fromiter(self.values(), dtype=self.dtype, count=nnz)
+ # handle 1d keys specially b/c not a tuple
+ inds = zip(*self.keys()) if self.ndim > 1 else (self.keys(),)
+ coords = tuple(np.fromiter(ix, dtype=idx_dtype, count=nnz) for ix in inds)
+ A = self._coo_container((data, coords), shape=self.shape, dtype=self.dtype)
+ A.has_canonical_format = True
+ return A
+
+ tocoo.__doc__ = _spbase.tocoo.__doc__
+
+ def todok(self, copy=False):
+ if copy:
+ return self.copy()
+ return self
+
+ todok.__doc__ = _spbase.todok.__doc__
+
+ def tocsc(self, copy=False):
+ if self.ndim == 1:
+ raise NotImplementedError("tocsr() not valid for 1d sparse array")
+ return self.tocoo(copy=False).tocsc(copy=copy)
+
+ tocsc.__doc__ = _spbase.tocsc.__doc__
+
+ def resize(self, *shape):
+ shape = check_shape(shape, allow_nd=self._allow_nd)
+ if len(shape) != len(self.shape):
+ # TODO implement resize across dimensions
+ raise NotImplementedError
+
+ if self.ndim == 1:
+ newN = shape[-1]
+ for i in list(self._dict):
+ if i >= newN:
+ del self._dict[i]
+ self._shape = shape
+ return
+
+ newM, newN = shape
+ M, N = self.shape
+ if newM < M or newN < N:
+ # Remove all elements outside new dimensions
+ for i, j in list(self.keys()):
+ if i >= newM or j >= newN:
+ del self._dict[i, j]
+ self._shape = shape
+
+ resize.__doc__ = _spbase.resize.__doc__
+
+ # Added for 1d to avoid `tocsr` from _base.py
+ def astype(self, dtype, casting='unsafe', copy=True):
+ dtype = np.dtype(dtype)
+ if self.dtype != dtype:
+ result = self._dok_container(self.shape, dtype=dtype)
+ data = np.array(list(self._dict.values()), dtype=dtype)
+ result._dict = dict(zip(self._dict, data))
+ return result
+ elif copy:
+ return self.copy()
+ return self
+
+
+def isspmatrix_dok(x):
+ """Is `x` of dok_array type?
+
+ Parameters
+ ----------
+ x
+ object to check for being a dok matrix
+
+ Returns
+ -------
+ bool
+ True if `x` is a dok matrix, False otherwise
+
+ Examples
+ --------
+ >>> from scipy.sparse import dok_array, dok_matrix, coo_matrix, isspmatrix_dok
+ >>> isspmatrix_dok(dok_matrix([[5]]))
+ True
+ >>> isspmatrix_dok(dok_array([[5]]))
+ False
+ >>> isspmatrix_dok(coo_matrix([[5]]))
+ False
+ """
+ return isinstance(x, dok_matrix)
+
+
+# This namespace class separates array from matrix with isinstance
+class dok_array(_dok_base, sparray):
+ """
+ Dictionary Of Keys based sparse array.
+
+ This is an efficient structure for constructing sparse
+ arrays incrementally.
+
+ This can be instantiated in several ways:
+ dok_array(D)
+ where D is a 2-D ndarray
+
+ dok_array(S)
+ with another sparse array or matrix S (equivalent to S.todok())
+
+ dok_array((M,N), [dtype])
+ create the array with initial shape (M,N)
+ dtype is optional, defaulting to dtype='d'
+
+ Attributes
+ ----------
+ dtype : dtype
+ Data type of the array
+ shape : 2-tuple
+ Shape of the array
+ ndim : int
+ Number of dimensions (this is always 2)
+ nnz
+ Number of nonzero elements
+ size
+ T
+
+ Notes
+ -----
+
+ Sparse arrays can be used in arithmetic operations: they support
+ addition, subtraction, multiplication, division, and matrix power.
+
+ - Allows for efficient O(1) access of individual elements.
+ - Duplicates are not allowed.
+ - Can be efficiently converted to a coo_array once constructed.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.sparse import dok_array
+ >>> S = dok_array((5, 5), dtype=np.float32)
+ >>> for i in range(5):
+ ... for j in range(5):
+ ... S[i, j] = i + j # Update element
+
+ """
+
+
+class dok_matrix(spmatrix, _dok_base):
+ """
+ Dictionary Of Keys based sparse matrix.
+
+ This is an efficient structure for constructing sparse
+ matrices incrementally.
+
+ This can be instantiated in several ways:
+ dok_matrix(D)
+ where D is a 2-D ndarray
+
+ dok_matrix(S)
+ with another sparse array or matrix S (equivalent to S.todok())
+
+ dok_matrix((M,N), [dtype])
+ create the matrix with initial shape (M,N)
+ dtype is optional, defaulting to dtype='d'
+
+ Attributes
+ ----------
+ dtype : dtype
+ Data type of the matrix
+ shape : 2-tuple
+ Shape of the matrix
+ ndim : int
+ Number of dimensions (this is always 2)
+ nnz
+ Number of nonzero elements
+ size
+ T
+
+ Notes
+ -----
+
+ Sparse matrices can be used in arithmetic operations: they support
+ addition, subtraction, multiplication, division, and matrix power.
+
+ - Allows for efficient O(1) access of individual elements.
+ - Duplicates are not allowed.
+ - Can be efficiently converted to a coo_matrix once constructed.
+
+ Examples
+ --------
+ >>> import numpy as np
+ >>> from scipy.sparse import dok_matrix
+ >>> S = dok_matrix((5, 5), dtype=np.float32)
+ >>> for i in range(5):
+ ... for j in range(5):
+ ... S[i, j] = i + j # Update element
+
+ """
+
+ def set_shape(self, shape):
+ new_matrix = self.reshape(shape, copy=False).asformat(self.format)
+ self.__dict__ = new_matrix.__dict__
+
+ def get_shape(self):
+ """Get shape of a sparse matrix."""
+ return self._shape
+
+ shape = property(fget=get_shape, fset=set_shape)
+
+ def __reversed__(self):
+ return self._dict.__reversed__()
+
+ def __or__(self, other):
+ if isinstance(other, _dok_base):
+ return self._dict | other._dict
+ return self._dict | other
+
+ def __ror__(self, other):
+ if isinstance(other, _dok_base):
+ return self._dict | other._dict
+ return self._dict | other
+
+ def __ior__(self, other):
+ if isinstance(other, _dok_base):
+ self._dict |= other._dict
+ else:
+ self._dict |= other
+ return self
diff --git a/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_extract.py b/.venv_haddock/lib/python3.12/site-packages/scipy/sparse/_extract.py
new file mode 100644
index 0000000000000000000000000000000000000000..0ee1a88575926efa1d5a921edbd3d88696157dc2
--- /dev/null
+++ b/.venv_haddock/lib/python3.12/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')
+