diff --git a/.gitattributes b/.gitattributes index 3262b463908f4a9decea32ac6bcae592ccdce3ee..63da5289b7e20657025c54f01c7638096fe7c3eb 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1700,3 +1700,5 @@ vllm/lib/python3.10/site-packages/sympy/solvers/__pycache__/solveset.cpython-310 vllm/lib/python3.10/site-packages/sympy/solvers/tests/__pycache__/test_solvers.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text vllm/lib/python3.10/site-packages/sympy/logic/__pycache__/boolalg.cpython-310.pyc filter=lfs diff=lfs merge=lfs -text vllm/lib/python3.10/site-packages/tiktoken/_tiktoken.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +parrot/lib/python3.10/site-packages/scipy/cluster/_hierarchy.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text +parrot/lib/python3.10/site-packages/scipy/stats/_ansari_swilk_statistics.cpython-310-x86_64-linux-gnu.so filter=lfs diff=lfs merge=lfs -text diff --git a/parrot/lib/python3.10/site-packages/scipy/cluster/_hierarchy.cpython-310-x86_64-linux-gnu.so b/parrot/lib/python3.10/site-packages/scipy/cluster/_hierarchy.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..84ecee7d47e111e2c9dfbc4356b445d994b43878 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/cluster/_hierarchy.cpython-310-x86_64-linux-gnu.so @@ -0,0 +1,3 @@ +version https://git-lfs.github.com/spec/v1 +oid sha256:ee732614b22a8d19dbc0841e4b958699990ef7c0cee00edd2c850d58d6616b2f +size 423352 diff --git a/parrot/lib/python3.10/site-packages/scipy/ndimage/__init__.py b/parrot/lib/python3.10/site-packages/scipy/ndimage/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..4f619dded6615a284392c4273559f226a1c8c72c --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/ndimage/__init__.py @@ -0,0 +1,169 @@ +""" +========================================================= +Multidimensional image processing (:mod:`scipy.ndimage`) +========================================================= + +.. currentmodule:: scipy.ndimage + +This package contains various functions for multidimensional image +processing. + + +Filters +======= + +.. autosummary:: + :toctree: generated/ + + convolve - Multidimensional convolution + convolve1d - 1-D convolution along the given axis + correlate - Multidimensional correlation + correlate1d - 1-D correlation along the given axis + gaussian_filter + gaussian_filter1d + gaussian_gradient_magnitude + gaussian_laplace + generic_filter - Multidimensional filter using a given function + generic_filter1d - 1-D generic filter along the given axis + generic_gradient_magnitude + generic_laplace + laplace - N-D Laplace filter based on approximate second derivatives + maximum_filter + maximum_filter1d + median_filter - Calculates a multidimensional median filter + minimum_filter + minimum_filter1d + percentile_filter - Calculates a multidimensional percentile filter + prewitt + rank_filter - Calculates a multidimensional rank filter + sobel + uniform_filter - Multidimensional uniform filter + uniform_filter1d - 1-D uniform filter along the given axis + +Fourier filters +=============== + +.. autosummary:: + :toctree: generated/ + + fourier_ellipsoid + fourier_gaussian + fourier_shift + fourier_uniform + +Interpolation +============= + +.. autosummary:: + :toctree: generated/ + + affine_transform - Apply an affine transformation + geometric_transform - Apply an arbitrary geometric transform + map_coordinates - Map input array to new coordinates by interpolation + rotate - Rotate an array + shift - Shift an array + spline_filter + spline_filter1d + zoom - Zoom an array + +Measurements +============ + +.. autosummary:: + :toctree: generated/ + + center_of_mass - The center of mass of the values of an array at labels + extrema - Min's and max's of an array at labels, with their positions + find_objects - Find objects in a labeled array + histogram - Histogram of the values of an array, optionally at labels + label - Label features in an array + labeled_comprehension + maximum + maximum_position + mean - Mean of the values of an array at labels + median + minimum + minimum_position + standard_deviation - Standard deviation of an N-D image array + sum_labels - Sum of the values of the array + value_indices - Find indices of each distinct value in given array + variance - Variance of the values of an N-D image array + watershed_ift + +Morphology +========== + +.. autosummary:: + :toctree: generated/ + + binary_closing + binary_dilation + binary_erosion + binary_fill_holes + binary_hit_or_miss + binary_opening + binary_propagation + black_tophat + distance_transform_bf + distance_transform_cdt + distance_transform_edt + generate_binary_structure + grey_closing + grey_dilation + grey_erosion + grey_opening + iterate_structure + morphological_gradient + morphological_laplace + white_tophat + +""" + +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +from ._filters import * +from ._fourier import * +from ._interpolation import * +from ._measurements import * +from ._morphology import * + +# Deprecated namespaces, to be removed in v2.0.0 +from . import filters +from . import fourier +from . import interpolation +from . import measurements +from . import morphology + +__all__ = [s for s in dir() if not s.startswith('_')] + +from scipy._lib._testutils import PytestTester +test = PytestTester(__name__) +del PytestTester diff --git a/parrot/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so b/parrot/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so new file mode 100644 index 0000000000000000000000000000000000000000..0d05e123ba1f7f45c1f37795e7ba5cd0257018b4 Binary files /dev/null and b/parrot/lib/python3.10/site-packages/scipy/ndimage/_ctest.cpython-310-x86_64-linux-gnu.so differ diff --git a/parrot/lib/python3.10/site-packages/scipy/ndimage/_filters.py b/parrot/lib/python3.10/site-packages/scipy/ndimage/_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..635b2d336b343ec832b0b411149063df505c5747 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/ndimage/_filters.py @@ -0,0 +1,1858 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +from collections.abc import Iterable +import numbers +import warnings +import numpy as np +import operator + +from scipy._lib._util import normalize_axis_index +from . import _ni_support +from . import _nd_image +from . import _ni_docstrings + +__all__ = ['correlate1d', 'convolve1d', 'gaussian_filter1d', 'gaussian_filter', + 'prewitt', 'sobel', 'generic_laplace', 'laplace', + 'gaussian_laplace', 'generic_gradient_magnitude', + 'gaussian_gradient_magnitude', 'correlate', 'convolve', + 'uniform_filter1d', 'uniform_filter', 'minimum_filter1d', + 'maximum_filter1d', 'minimum_filter', 'maximum_filter', + 'rank_filter', 'median_filter', 'percentile_filter', + 'generic_filter1d', 'generic_filter'] + + +def _invalid_origin(origin, lenw): + return (origin < -(lenw // 2)) or (origin > (lenw - 1) // 2) + + +def _complex_via_real_components(func, input, weights, output, cval, **kwargs): + """Complex convolution via a linear combination of real convolutions.""" + complex_input = input.dtype.kind == 'c' + complex_weights = weights.dtype.kind == 'c' + if complex_input and complex_weights: + # real component of the output + func(input.real, weights.real, output=output.real, + cval=np.real(cval), **kwargs) + output.real -= func(input.imag, weights.imag, output=None, + cval=np.imag(cval), **kwargs) + # imaginary component of the output + func(input.real, weights.imag, output=output.imag, + cval=np.real(cval), **kwargs) + output.imag += func(input.imag, weights.real, output=None, + cval=np.imag(cval), **kwargs) + elif complex_input: + func(input.real, weights, output=output.real, cval=np.real(cval), + **kwargs) + func(input.imag, weights, output=output.imag, cval=np.imag(cval), + **kwargs) + else: + if np.iscomplexobj(cval): + raise ValueError("Cannot provide a complex-valued cval when the " + "input is real.") + func(input, weights.real, output=output.real, cval=cval, **kwargs) + func(input, weights.imag, output=output.imag, cval=cval, **kwargs) + return output + + +@_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 = weights[::-1] + origin = -origin + if not len(weights) & 1: + origin -= 1 + weights = np.asarray(weights) + 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): + """ + 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 + + 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 = list(range(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): + """N-D Laplace filter based on approximate second derivatives. + + Parameters + ---------- + %(input)s + %(output)s + %(mode_multiple)s + %(cval)s + + 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) + + +@_ni_docstrings.docfiller +def gaussian_laplace(input, sigma, output=None, mode="reflect", + cval=0.0, **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 + 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) + + return generic_laplace(input, derivative2, output, mode, cval, + extra_arguments=(sigma,), + extra_keywords=kwargs) + + +@_ni_docstrings.docfiller +def generic_gradient_magnitude(input, derivative, output=None, + mode="reflect", cval=0.0, + extra_arguments=(), extra_keywords=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 + + Returns + ------- + generic_gradient_matnitude : ndarray + Filtered array. Has the same shape as `input`. + + """ + if extra_keywords is None: + extra_keywords = {} + input = np.asarray(input) + output = _ni_support._get_output(output, input) + axes = list(range(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, **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 + 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) + + +def _correlate_or_convolve(input, weights, output, mode, cval, origin, + convolution): + 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 + ) + output = _ni_support._get_output(output, input, complex_output=True) + + return _complex_via_real_components(_correlate_or_convolve, input, + weights, output, cval, **kwargs) + + origins = _ni_support._normalize_sequence(origin, input.ndim) + weights = np.asarray(weights, dtype=np.float64) + wshape = [ii for ii in weights.shape if ii > 0] + if len(wshape) != input.ndim: + raise RuntimeError('filter weights array has incorrect shape.') + 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): + """ + 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 + + 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) + + +@_ni_docstrings.docfiller +def convolve(input, weights, output=None, mode='reflect', cval=0.0, + origin=0): + """ + 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, optional + Controls the origin of the input signal, which is where the + filter is centered to produce the first element of the output. + Positive values shift the filter to the right, and negative values + shift the filter to the left. Default is 0. + + 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) + + +@_ni_docstrings.docfiller +def uniform_filter1d(input, size, axis=-1, output=None, + mode="reflect", cval=0.0, origin=0): + """Calculate a 1-D uniform filter along the given axis. + + The lines of the array along the given axis are filtered with a + uniform filter of given size. + + Parameters + ---------- + %(input)s + size : int + length of uniform filter + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + result : ndarray + Filtered array. Has same shape as `input`. + + Examples + -------- + >>> from scipy.ndimage import uniform_filter1d + >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) + array([4, 3, 4, 1, 4, 6, 6, 3]) + """ + input = np.asarray(input) + axis = normalize_axis_index(axis, input.ndim) + if size < 1: + raise RuntimeError('incorrect filter size') + complex_output = input.dtype.kind == 'c' + output = _ni_support._get_output(output, input, + complex_output=complex_output) + if (size // 2 + origin < 0) or (size // 2 + origin >= size): + raise ValueError('invalid origin') + mode = _ni_support._extend_mode_to_code(mode) + if not complex_output: + _nd_image.uniform_filter1d(input, size, axis, output, mode, cval, + origin) + else: + _nd_image.uniform_filter1d(input.real, size, axis, output.real, mode, + np.real(cval), origin) + _nd_image.uniform_filter1d(input.imag, size, axis, output.imag, mode, + np.imag(cval), origin) + return output + + +@_ni_docstrings.docfiller +def uniform_filter(input, size=3, output=None, mode="reflect", + cval=0.0, origin=0, *, axes=None): + """Multidimensional uniform filter. + + Parameters + ---------- + %(input)s + size : int or sequence of ints, optional + The sizes of the uniform filter are given for each axis as a + sequence, or as a single number, in which case the size is + equal for all axes. + %(output)s + %(mode_multiple)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + uniform_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + The multidimensional filter is implemented as a sequence of + 1-D uniform filters. The intermediate arrays are stored + in the same data type as the output. Therefore, for output types + with a limited precision, the results may be imprecise because + intermediate results may be stored with insufficient precision. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.uniform_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + input = np.asarray(input) + output = _ni_support._get_output(output, input, + complex_output=input.dtype.kind == 'c') + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + sizes = _ni_support._normalize_sequence(size, num_axes) + origins = _ni_support._normalize_sequence(origin, num_axes) + modes = _ni_support._normalize_sequence(mode, num_axes) + axes = [(axes[ii], sizes[ii], origins[ii], modes[ii]) + for ii in range(num_axes) if sizes[ii] > 1] + if len(axes) > 0: + for axis, size, origin, mode in axes: + uniform_filter1d(input, int(size), axis, output, mode, + cval, origin) + input = output + else: + output[...] = input[...] + return output + + +@_ni_docstrings.docfiller +def minimum_filter1d(input, size, axis=-1, output=None, + mode="reflect", cval=0.0, origin=0): + """Calculate a 1-D minimum filter along the given axis. + + The lines of the array along the given axis are filtered with a + minimum filter of given size. + + Parameters + ---------- + %(input)s + size : int + length along which to calculate 1D minimum + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + result : ndarray. + Filtered image. Has the same shape as `input`. + + Notes + ----- + This function implements the MINLIST algorithm [1]_, as described by + Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being + the `input` length, regardless of filter size. + + References + ---------- + .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 + .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html + + + Examples + -------- + >>> from scipy.ndimage import minimum_filter1d + >>> minimum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) + array([2, 0, 0, 0, 1, 1, 0, 0]) + """ + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + axis = normalize_axis_index(axis, input.ndim) + if size < 1: + raise RuntimeError('incorrect filter size') + output = _ni_support._get_output(output, input) + if (size // 2 + origin < 0) or (size // 2 + origin >= size): + raise ValueError('invalid origin') + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, + origin, 1) + return output + + +@_ni_docstrings.docfiller +def maximum_filter1d(input, size, axis=-1, output=None, + mode="reflect", cval=0.0, origin=0): + """Calculate a 1-D maximum filter along the given axis. + + The lines of the array along the given axis are filtered with a + maximum filter of given size. + + Parameters + ---------- + %(input)s + size : int + Length along which to calculate the 1-D maximum. + %(axis)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin)s + + Returns + ------- + maximum1d : ndarray, None + Maximum-filtered array with same shape as input. + None if `output` is not None + + Notes + ----- + This function implements the MAXLIST algorithm [1]_, as described by + Richard Harter [2]_, and has a guaranteed O(n) performance, `n` being + the `input` length, regardless of filter size. + + References + ---------- + .. [1] http://citeseerx.ist.psu.edu/viewdoc/summary?doi=10.1.1.42.2777 + .. [2] http://www.richardhartersworld.com/cri/2001/slidingmin.html + + Examples + -------- + >>> from scipy.ndimage import maximum_filter1d + >>> maximum_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) + array([8, 8, 8, 4, 9, 9, 9, 9]) + """ + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + axis = normalize_axis_index(axis, input.ndim) + if size < 1: + raise RuntimeError('incorrect filter size') + output = _ni_support._get_output(output, input) + if (size // 2 + origin < 0) or (size // 2 + origin >= size): + raise ValueError('invalid origin') + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.min_or_max_filter1d(input, size, axis, output, mode, cval, + origin, 0) + return output + + +def _min_or_max_filter(input, size, footprint, structure, output, mode, + cval, origin, minimum, axes=None): + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=3) + if structure is None: + if footprint is None: + if size is None: + raise RuntimeError("no footprint provided") + separable = True + else: + footprint = np.asarray(footprint, dtype=bool) + if not footprint.any(): + raise ValueError("All-zero footprint is not supported.") + if footprint.all(): + size = footprint.shape + footprint = None + separable = True + else: + separable = False + else: + structure = np.asarray(structure, dtype=np.float64) + separable = False + if footprint is None: + footprint = np.ones(structure.shape, bool) + else: + footprint = np.asarray(footprint, dtype=bool) + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError("Complex type not supported") + output = _ni_support._get_output(output, input) + temp_needed = np.may_share_memory(input, output) + if temp_needed: + # input and output arrays cannot share memory + temp = output + output = _ni_support._get_output(output.dtype, input) + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + if separable: + origins = _ni_support._normalize_sequence(origin, num_axes) + sizes = _ni_support._normalize_sequence(size, num_axes) + modes = _ni_support._normalize_sequence(mode, num_axes) + axes = [(axes[ii], sizes[ii], origins[ii], modes[ii]) + for ii in range(len(axes)) if sizes[ii] > 1] + if minimum: + filter_ = minimum_filter1d + else: + filter_ = maximum_filter1d + if len(axes) > 0: + for axis, size, origin, mode in axes: + filter_(input, int(size), axis, output, mode, cval, origin) + input = output + else: + output[...] = input[...] + else: + origins = _ni_support._normalize_sequence(origin, num_axes) + if num_axes < input.ndim: + if footprint.ndim != num_axes: + raise RuntimeError("footprint array has incorrect shape") + footprint = np.expand_dims( + footprint, + tuple(ax for ax in range(input.ndim) if ax not in axes) + ) + # set origin = 0 for any axes not being filtered + origins_temp = [0,] * input.ndim + for o, ax in zip(origins, axes): + origins_temp[ax] = o + origins = origins_temp + + fshape = [ii for ii in footprint.shape if ii > 0] + if len(fshape) != input.ndim: + raise RuntimeError('footprint array has incorrect shape.') + 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) != input.ndim: + raise RuntimeError("structure array has incorrect shape") + if num_axes != structure.ndim: + structure = np.expand_dims( + structure, + tuple(ax for ax in range(structure.ndim) if ax not in axes) + ) + if not structure.flags.contiguous: + structure = structure.copy() + if not isinstance(mode, str) and isinstance(mode, Iterable): + raise RuntimeError( + "A sequence of modes is not supported for non-separable " + "footprints") + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.min_or_max_filter(input, footprint, structure, output, + mode, cval, origins, minimum) + if temp_needed: + temp[...] = output + output = temp + return output + + +@_ni_docstrings.docfiller +def minimum_filter(input, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """Calculate a multidimensional minimum filter. + + Parameters + ---------- + %(input)s + %(size_foot)s + %(output)s + %(mode_multiple)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + minimum_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + A sequence of modes (one per axis) is only supported when the footprint is + separable. Otherwise, a single mode string must be provided. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.minimum_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + return _min_or_max_filter(input, size, footprint, None, output, mode, + cval, origin, 1, axes) + + +@_ni_docstrings.docfiller +def maximum_filter(input, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, *, axes=None): + """Calculate a multidimensional maximum filter. + + Parameters + ---------- + %(input)s + %(size_foot)s + %(output)s + %(mode_multiple)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. When `axes` is + specified, any tuples used for `size`, `origin`, and/or `mode` + must match the length of `axes`. The ith entry in any of these tuples + corresponds to the ith entry in `axes`. + + Returns + ------- + maximum_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + A sequence of modes (one per axis) is only supported when the footprint is + separable. Otherwise, a single mode string must be provided. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.maximum_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + return _min_or_max_filter(input, size, footprint, None, output, mode, + cval, origin, 0, axes) + + +@_ni_docstrings.docfiller +def _rank_filter(input, rank, size=None, footprint=None, output=None, + mode="reflect", cval=0.0, origin=0, operation='rank', + axes=None): + if (size is not None) and (footprint is not None): + warnings.warn("ignoring size because footprint is set", + UserWarning, stacklevel=3) + input = np.asarray(input) + if np.iscomplexobj(input): + raise TypeError('Complex type not supported') + axes = _ni_support._check_axes(axes, input.ndim) + num_axes = len(axes) + origins = _ni_support._normalize_sequence(origin, num_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) + if num_axes < input.ndim: + # set origin = 0 for any axes not being filtered + origins_temp = [0,] * input.ndim + for o, ax in zip(origins, axes): + origins_temp[ax] = o + origins = origins_temp + + 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'] * input.ndim + for m, ax in zip(modes, axes): + modes_temp[ax] = m + mode = modes_temp + + # insert singleton dimension along any non-filtered axes + if footprint.ndim != num_axes: + raise RuntimeError("footprint array has incorrect shape") + footprint = np.expand_dims( + footprint, + tuple(ax for ax in range(input.ndim) if ax not in axes) + ) + fshape = [ii for ii in footprint.shape if ii > 0] + if len(fshape) != input.ndim: + raise RuntimeError('footprint array has incorrect shape.') + 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) + _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. + + 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. + + Returns + ------- + median_filter : ndarray + Filtered array. Has the same shape as `input`. + + See Also + -------- + scipy.signal.medfilt2d + + Notes + ----- + For 2-dimensional images with ``uint8``, ``float32`` or ``float64`` dtypes + the specialised function `scipy.signal.medfilt2d` may be faster. It is + however limited to constant mode with ``cval=0``. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure() + >>> plt.gray() # show the filtered result in grayscale + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.median_filter(ascent, size=20) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result) + >>> plt.show() + """ + return _rank_filter(input, 0, size, footprint, output, mode, cval, + origin, 'median', axes=axes) + + +@_ni_docstrings.docfiller +def percentile_filter(input, percentile, size=None, footprint=None, + output=None, mode="reflect", cval=0.0, origin=0, *, + axes=None): + """Calculate a multidimensional percentile filter. + + Parameters + ---------- + %(input)s + percentile : scalar + The percentile parameter may be less than zero, i.e., + percentile = -20 equals percentile = 80 + %(size_foot)s + %(output)s + %(mode_reflect)s + %(cval)s + %(origin_multiple)s + axes : tuple of int or None, optional + If None, `input` is filtered along all axes. Otherwise, + `input` is filtered along the specified axes. + + 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): + """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 + + Returns + ------- + generic_filter : ndarray + Filtered array. Has the same shape as `input`. + + Notes + ----- + This function also accepts low-level callback functions with one of + the following signatures and wrapped in `scipy.LowLevelCallable`: + + .. code:: c + + int callback(double *buffer, npy_intp filter_size, + double *return_value, void *user_data) + int callback(double *buffer, intptr_t filter_size, + double *return_value, void *user_data) + + The calling function iterates over the elements of the input and + output arrays, calling the callback function at each element. The + elements within the footprint of the filter at the current element are + passed through the ``buffer`` parameter, and the number of elements + within the footprint through ``filter_size``. The calculated value is + returned in ``return_value``. ``user_data`` is the data pointer provided + to `scipy.LowLevelCallable` as-is. + + The callback function must return an integer error status that is zero + if something went wrong and one otherwise. If an error occurs, you should + normally set the python error status with an informative message + before returning, otherwise a default error message is set by the + calling function. + + In addition, some other low-level function pointer specifications + are accepted, but these are for backward compatibility only and should + not be used in new code. + + Examples + -------- + Import the necessary modules and load the example image used for + filtering. + + >>> import numpy as np + >>> from scipy import datasets + >>> from scipy.ndimage import zoom, generic_filter + >>> import matplotlib.pyplot as plt + >>> ascent = zoom(datasets.ascent(), 0.5) + + Compute a maximum filter with kernel size 5 by passing a simple NumPy + aggregation function as argument to `function`. + + >>> maximum_filter_result = generic_filter(ascent, np.amax, [5, 5]) + + While a maximmum 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') + origins = _ni_support._normalize_sequence(origin, input.ndim) + if footprint is None: + if size is None: + raise RuntimeError("no footprint or filter size provided") + sizes = _ni_support._normalize_sequence(size, input.ndim) + footprint = np.ones(sizes, dtype=bool) + else: + footprint = np.asarray(footprint, dtype=bool) + fshape = [ii for ii in footprint.shape if ii > 0] + if len(fshape) != input.ndim: + raise RuntimeError('filter footprint array has incorrect shape.') + 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/parrot/lib/python3.10/site-packages/scipy/ndimage/_fourier.py b/parrot/lib/python3.10/site-packages/scipy/ndimage/_fourier.py new file mode 100644 index 0000000000000000000000000000000000000000..bb5ffa6b9287cb740611aefba5f1f322011518cf --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/ndimage/_fourier.py @@ -0,0 +1,306 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import numpy as np +from scipy._lib._util import normalize_axis_index +from . import _ni_support +from . import _nd_image + +__all__ = ['fourier_gaussian', 'fourier_uniform', 'fourier_ellipsoid', + 'fourier_shift'] + + +def _get_output_fourier(output, input): + if output is None: + if input.dtype.type in [np.complex64, np.complex128, np.float32]: + output = np.zeros(input.shape, dtype=input.dtype) + else: + output = np.zeros(input.shape, dtype=np.float64) + elif type(output) is type: + if output not in [np.complex64, np.complex128, + np.float32, np.float64]: + raise RuntimeError("output type not supported") + output = np.zeros(input.shape, dtype=output) + elif output.shape != input.shape: + raise RuntimeError("output shape not correct") + return output + + +def _get_output_fourier_complex(output, input): + if output is None: + if input.dtype.type in [np.complex64, np.complex128]: + output = np.zeros(input.shape, dtype=input.dtype) + else: + output = np.zeros(input.shape, dtype=np.complex128) + elif type(output) is type: + if output not in [np.complex64, np.complex128]: + raise RuntimeError("output type not supported") + output = np.zeros(input.shape, dtype=output) + elif output.shape != input.shape: + raise RuntimeError("output shape not correct") + return output + + +def fourier_gaussian(input, sigma, n=-1, axis=-1, output=None): + """ + Multidimensional Gaussian fourier filter. + + The array is multiplied with the fourier transform of a Gaussian + kernel. + + Parameters + ---------- + input : array_like + The input array. + sigma : float or sequence + The sigma of the Gaussian kernel. If a float, `sigma` is the same for + all axes. If a sequence, `sigma` has to contain one value for each + axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of filtering the input is placed in this array. + + Returns + ------- + fourier_gaussian : ndarray + The filtered input. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import numpy.fft + >>> import matplotlib.pyplot as plt + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_gaussian(input_, sigma=4) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + output = _get_output_fourier(output, input) + axis = normalize_axis_index(axis, input.ndim) + sigmas = _ni_support._normalize_sequence(sigma, input.ndim) + sigmas = np.asarray(sigmas, dtype=np.float64) + if not sigmas.flags.contiguous: + sigmas = sigmas.copy() + + _nd_image.fourier_filter(input, sigmas, n, axis, output, 0) + return output + + +def fourier_uniform(input, size, n=-1, axis=-1, output=None): + """ + Multidimensional uniform fourier filter. + + The array is multiplied with the Fourier transform of a box of given + size. + + Parameters + ---------- + input : array_like + The input array. + size : float or sequence + The size of the box used for filtering. + If a float, `size` is the same for all axes. If a sequence, `size` has + to contain one value for each axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of filtering the input is placed in this array. + + Returns + ------- + fourier_uniform : ndarray + The filtered input. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import numpy.fft + >>> import matplotlib.pyplot as plt + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_uniform(input_, size=20) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + output = _get_output_fourier(output, input) + axis = normalize_axis_index(axis, input.ndim) + sizes = _ni_support._normalize_sequence(size, input.ndim) + sizes = np.asarray(sizes, dtype=np.float64) + if not sizes.flags.contiguous: + sizes = sizes.copy() + _nd_image.fourier_filter(input, sizes, n, axis, output, 1) + return output + + +def fourier_ellipsoid(input, size, n=-1, axis=-1, output=None): + """ + Multidimensional ellipsoid Fourier filter. + + The array is multiplied with the fourier transform of an ellipsoid of + given sizes. + + Parameters + ---------- + input : array_like + The input array. + size : float or sequence + The size of the box used for filtering. + If a float, `size` is the same for all axes. If a sequence, `size` has + to contain one value for each axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of filtering the input is placed in this array. + + Returns + ------- + fourier_ellipsoid : ndarray + The filtered input. + + Notes + ----- + This function is implemented for arrays of rank 1, 2, or 3. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import numpy.fft + >>> import matplotlib.pyplot as plt + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_ellipsoid(input_, size=20) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + if input.ndim > 3: + raise NotImplementedError("Only 1d, 2d and 3d inputs are supported") + output = _get_output_fourier(output, input) + if output.size == 0: + # The C code has a bug that can result in a segfault with arrays + # that have size 0 (gh-17270), so check here. + return output + axis = normalize_axis_index(axis, input.ndim) + sizes = _ni_support._normalize_sequence(size, input.ndim) + sizes = np.asarray(sizes, dtype=np.float64) + if not sizes.flags.contiguous: + sizes = sizes.copy() + _nd_image.fourier_filter(input, sizes, n, axis, output, 2) + return output + + +def fourier_shift(input, shift, n=-1, axis=-1, output=None): + """ + Multidimensional Fourier shift filter. + + The array is multiplied with the Fourier transform of a shift operation. + + Parameters + ---------- + input : array_like + The input array. + shift : float or sequence + The size of the box used for filtering. + If a float, `shift` is the same for all axes. If a sequence, `shift` + has to contain one value for each axis. + n : int, optional + If `n` is negative (default), then the input is assumed to be the + result of a complex fft. + If `n` is larger than or equal to zero, the input is assumed to be the + result of a real fft, and `n` gives the length of the array before + transformation along the real transform direction. + axis : int, optional + The axis of the real transform. + output : ndarray, optional + If given, the result of shifting the input is placed in this array. + + Returns + ------- + fourier_shift : ndarray + The shifted input. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> import numpy.fft + >>> fig, (ax1, ax2) = plt.subplots(1, 2) + >>> plt.gray() # show the filtered result in grayscale + >>> ascent = datasets.ascent() + >>> input_ = numpy.fft.fft2(ascent) + >>> result = ndimage.fourier_shift(input_, shift=200) + >>> result = numpy.fft.ifft2(result) + >>> ax1.imshow(ascent) + >>> ax2.imshow(result.real) # the imaginary part is an artifact + >>> plt.show() + """ + input = np.asarray(input) + output = _get_output_fourier_complex(output, input) + axis = normalize_axis_index(axis, input.ndim) + shifts = _ni_support._normalize_sequence(shift, input.ndim) + shifts = np.asarray(shifts, dtype=np.float64) + if not shifts.flags.contiguous: + shifts = shifts.copy() + _nd_image.fourier_shift(input, shifts, n, axis, output) + return output diff --git a/parrot/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py b/parrot/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..5b8827d66ece8c6f76c58b1889f1450e9db3e924 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/ndimage/_interpolation.py @@ -0,0 +1,1001 @@ +# Copyright (C) 2003-2005 Peter J. Verveer +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions +# are met: +# +# 1. Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# +# 2. Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following +# disclaimer in the documentation and/or other materials provided +# with the distribution. +# +# 3. The name of the author may not be used to endorse or promote +# products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS +# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE +# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS +# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, +# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +import itertools +import warnings + +import numpy as np +from scipy._lib._util import normalize_axis_index + +from scipy import special +from . import _ni_support +from . import _nd_image +from ._ni_docstrings import docfiller + + +__all__ = ['spline_filter1d', 'spline_filter', 'geometric_transform', + 'map_coordinates', 'affine_transform', 'shift', 'zoom', 'rotate'] + + +@docfiller +def spline_filter1d(input, order=3, axis=-1, output=np.float64, + mode='mirror'): + """ + Calculate a 1-D spline filter along the given axis. + + The lines of the array along the given axis are filtered by a + spline filter. The order of the spline must be >= 2 and <= 5. + + Parameters + ---------- + %(input)s + order : int, optional + The order of the spline, default is 3. + axis : int, optional + The axis along which the spline filter is applied. Default is the last + axis. + output : ndarray or dtype, optional + The array in which to place the output, or the dtype of the returned + array. Default is ``numpy.float64``. + %(mode_interp_mirror)s + + Returns + ------- + spline_filter1d : ndarray + The filtered input. + + See Also + -------- + spline_filter : Multidimensional spline filter. + + Notes + ----- + All of the interpolation functions in `ndimage` do spline interpolation of + the input image. If using B-splines of `order > 1`, the input image + values have to be converted to B-spline coefficients first, which is + done by applying this 1-D filter sequentially along all + axes of the input. All functions that require B-spline coefficients + will automatically filter their inputs, a behavior controllable with + the `prefilter` keyword argument. For functions that accept a `mode` + parameter, the result will only be correct if it matches the `mode` + used when filtering. + + For complex-valued `input`, this function processes the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + We can filter an image using 1-D spline along the given axis: + + >>> from scipy.ndimage import spline_filter1d + >>> import numpy as np + >>> import matplotlib.pyplot as plt + >>> orig_img = np.eye(20) # create an image + >>> orig_img[10, :] = 1.0 + >>> sp_filter_axis_0 = spline_filter1d(orig_img, axis=0) + >>> sp_filter_axis_1 = spline_filter1d(orig_img, axis=1) + >>> f, ax = plt.subplots(1, 3, sharex=True) + >>> for ind, data in enumerate([[orig_img, "original image"], + ... [sp_filter_axis_0, "spline filter (axis=0)"], + ... [sp_filter_axis_1, "spline filter (axis=1)"]]): + ... ax[ind].imshow(data[0], cmap='gray_r') + ... ax[ind].set_title(data[1]) + >>> plt.tight_layout() + >>> plt.show() + + """ + if order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, + complex_output=complex_output) + if complex_output: + spline_filter1d(input.real, order, axis, output.real, mode) + spline_filter1d(input.imag, order, axis, output.imag, mode) + return output + if order in [0, 1]: + output[...] = np.array(input) + else: + mode = _ni_support._extend_mode_to_code(mode) + axis = normalize_axis_index(axis, input.ndim) + _nd_image.spline_filter1d(input, order, axis, output, mode) + return output + +@docfiller +def spline_filter(input, order=3, output=np.float64, mode='mirror'): + """ + Multidimensional spline filter. + + Parameters + ---------- + %(input)s + order : int, optional + The order of the spline, default is 3. + output : ndarray or dtype, optional + The array in which to place the output, or the dtype of the returned + array. Default is ``numpy.float64``. + %(mode_interp_mirror)s + + Returns + ------- + spline_filter : ndarray + Filtered array. Has the same shape as `input`. + + See Also + -------- + spline_filter1d : Calculate a 1-D spline filter along the given axis. + + Notes + ----- + The multidimensional filter is implemented as a sequence of + 1-D spline filters. The intermediate arrays are stored + in the same data type as the output. Therefore, for output types + with a limited precision, the results may be imprecise because + intermediate results may be stored with insufficient precision. + + For complex-valued `input`, this function processes the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + We can filter an image using multidimentional 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={}): + """ + 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 order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + if output_shape is None: + output_shape = input.shape + if input.ndim < 1 or len(output_shape) < 1: + raise RuntimeError('input and output rank must be > 0') + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, shape=output_shape, + complex_output=complex_output) + if complex_output: + kwargs = dict(order=order, mode=mode, prefilter=prefilter, + output_shape=output_shape, + extra_arguments=extra_arguments, + extra_keywords=extra_keywords) + geometric_transform(input.real, mapping, output=output.real, + cval=np.real(cval), **kwargs) + geometric_transform(input.imag, mapping, output=output.imag, + cval=np.imag(cval), **kwargs) + return output + + if prefilter and order > 1: + padded, npad = _prepad_for_spline_filter(input, mode, cval) + filtered = spline_filter(padded, order, output=np.float64, + mode=mode) + else: + npad = 0 + filtered = input + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.geometric_transform(filtered, mapping, None, None, None, output, + order, mode, cval, npad, extra_arguments, + extra_keywords) + return output + + +@docfiller +def map_coordinates(input, coordinates, output=None, order=3, + mode='constant', cval=0.0, prefilter=True): + """ + Map the input array to new coordinates by interpolation. + + The array of coordinates is used to find, for each point in the output, + the corresponding coordinates in the input. The value of the input at + those coordinates is determined by spline interpolation of the + requested order. + + The shape of the output is derived from that of the coordinate + array by dropping the first axis. The values of the array along + the first axis are the coordinates in the input array at which the + output value is found. + + Parameters + ---------- + %(input)s + coordinates : array_like + The coordinates at which `input` is evaluated. + %(output)s + order : int, optional + The order of the spline interpolation, default is 3. + The order has to be in the range 0-5. + %(mode_interp_constant)s + %(cval)s + %(prefilter)s + + Returns + ------- + map_coordinates : ndarray + The result of transforming the input. The shape of the output is + derived from that of `coordinates` by dropping the first axis. + + See Also + -------- + spline_filter, geometric_transform, scipy.interpolate + + Notes + ----- + For complex-valued `input`, this function maps the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + >>> from scipy import ndimage + >>> import numpy as np + >>> a = np.arange(12.).reshape((4, 3)) + >>> a + array([[ 0., 1., 2.], + [ 3., 4., 5.], + [ 6., 7., 8.], + [ 9., 10., 11.]]) + >>> ndimage.map_coordinates(a, [[0.5, 2], [0.5, 1]], order=1) + array([ 2., 7.]) + + Above, the interpolated value of a[0.5, 0.5] gives output[0], while + a[2, 1] is output[1]. + + >>> inds = np.array([[0.5, 2], [0.5, 4]]) + >>> ndimage.map_coordinates(a, inds, order=1, cval=-33.3) + array([ 2. , -33.3]) + >>> ndimage.map_coordinates(a, inds, order=1, mode='nearest') + array([ 2., 8.]) + >>> ndimage.map_coordinates(a, inds, order=1, cval=0, output=bool) + array([ True, False], dtype=bool) + + """ + if order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + coordinates = np.asarray(coordinates) + if np.iscomplexobj(coordinates): + raise TypeError('Complex type not supported') + output_shape = coordinates.shape[1:] + if input.ndim < 1 or len(output_shape) < 1: + raise RuntimeError('input and output rank must be > 0') + if coordinates.shape[0] != input.ndim: + raise RuntimeError('invalid shape for coordinate array') + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, shape=output_shape, + complex_output=complex_output) + if complex_output: + kwargs = dict(order=order, mode=mode, prefilter=prefilter) + map_coordinates(input.real, coordinates, output=output.real, + cval=np.real(cval), **kwargs) + map_coordinates(input.imag, coordinates, output=output.imag, + cval=np.imag(cval), **kwargs) + return output + if prefilter and order > 1: + padded, npad = _prepad_for_spline_filter(input, mode, cval) + filtered = spline_filter(padded, order, output=np.float64, mode=mode) + else: + npad = 0 + filtered = input + mode = _ni_support._extend_mode_to_code(mode) + _nd_image.geometric_transform(filtered, None, coordinates, None, None, + output, order, mode, cval, npad, None, None) + return output + + +@docfiller +def affine_transform(input, matrix, offset=0.0, output_shape=None, + output=None, order=3, + mode='constant', cval=0.0, prefilter=True): + """ + Apply an affine transformation. + + Given an output image pixel index vector ``o``, the pixel value + is determined from the input image at position + ``np.dot(matrix, o) + offset``. + + This does 'pull' (or 'backward') resampling, transforming the output space + to the input to locate data. Affine transformations are often described in + the 'push' (or 'forward') direction, transforming input to output. If you + have a matrix for the 'push' transformation, use its inverse + (:func:`numpy.linalg.inv`) in this function. + + Parameters + ---------- + %(input)s + matrix : ndarray + The inverse coordinate transformation matrix, mapping output + coordinates to input coordinates. If ``ndim`` is the number of + dimensions of ``input``, the given matrix must have one of the + following shapes: + + - ``(ndim, ndim)``: the linear transformation matrix for each + output coordinate. + - ``(ndim,)``: assume that the 2-D transformation matrix is + diagonal, with the diagonal specified by the given value. A more + efficient algorithm is then used that exploits the separability + of the problem. + - ``(ndim + 1, ndim + 1)``: assume that the transformation is + specified using homogeneous coordinates [1]_. In this case, any + value passed to ``offset`` is ignored. + - ``(ndim, ndim + 1)``: as above, but the bottom row of a + homogeneous transformation matrix is always ``[0, 0, ..., 1]``, + and may be omitted. + + offset : float or sequence, optional + The offset into the array where the transform is applied. If a float, + `offset` is the same for each axis. If a sequence, `offset` should + contain one value for each axis. + output_shape : tuple of ints, optional + Shape tuple. + %(output)s + order : int, optional + The order of the spline interpolation, default is 3. + The order has to be in the range 0-5. + %(mode_interp_constant)s + %(cval)s + %(prefilter)s + + Returns + ------- + affine_transform : ndarray + The transformed input. + + Notes + ----- + The given matrix and offset are used to find for each point in the + output the corresponding coordinates in the input by an affine + transformation. The value of the input at those coordinates is + determined by spline interpolation of the requested order. Points + outside the boundaries of the input are filled according to the given + mode. + + .. versionchanged:: 0.18.0 + Previously, the exact interpretation of the affine transformation + depended on whether the matrix was supplied as a 1-D or a + 2-D array. If a 1-D array was supplied + to the matrix parameter, the output pixel value at index ``o`` + was determined from the input image at position + ``matrix * (o + offset)``. + + For complex-valued `input`, this function transforms the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + References + ---------- + .. [1] https://en.wikipedia.org/wiki/Homogeneous_coordinates + """ + if order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + if output_shape is None: + if isinstance(output, np.ndarray): + output_shape = output.shape + else: + output_shape = input.shape + if input.ndim < 1 or len(output_shape) < 1: + raise RuntimeError('input and output rank must be > 0') + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, shape=output_shape, + complex_output=complex_output) + if complex_output: + kwargs = dict(offset=offset, output_shape=output_shape, order=order, + mode=mode, prefilter=prefilter) + affine_transform(input.real, matrix, output=output.real, + cval=np.real(cval), **kwargs) + affine_transform(input.imag, matrix, output=output.imag, + cval=np.imag(cval), **kwargs) + return output + if prefilter and order > 1: + padded, npad = _prepad_for_spline_filter(input, mode, cval) + filtered = spline_filter(padded, order, output=np.float64, mode=mode) + else: + npad = 0 + filtered = input + mode = _ni_support._extend_mode_to_code(mode) + matrix = np.asarray(matrix, dtype=np.float64) + if matrix.ndim not in [1, 2] or matrix.shape[0] < 1: + raise RuntimeError('no proper affine matrix provided') + if (matrix.ndim == 2 and matrix.shape[1] == input.ndim + 1 and + (matrix.shape[0] in [input.ndim, input.ndim + 1])): + if matrix.shape[0] == input.ndim + 1: + exptd = [0] * input.ndim + [1] + if not np.all(matrix[input.ndim] == exptd): + msg = (f'Expected homogeneous transformation matrix with ' + f'shape {matrix.shape} for image shape {input.shape}, ' + f'but bottom row was not equal to {exptd}') + raise ValueError(msg) + # assume input is homogeneous coordinate transformation matrix + offset = matrix[:input.ndim, input.ndim] + matrix = matrix[:input.ndim, :input.ndim] + if matrix.shape[0] != input.ndim: + raise RuntimeError('affine matrix has wrong number of rows') + if matrix.ndim == 2 and matrix.shape[1] != output.ndim: + raise RuntimeError('affine matrix has wrong number of columns') + if not matrix.flags.contiguous: + matrix = matrix.copy() + offset = _ni_support._normalize_sequence(offset, input.ndim) + offset = np.asarray(offset, dtype=np.float64) + if offset.ndim != 1 or offset.shape[0] < 1: + raise RuntimeError('no proper offset provided') + if not offset.flags.contiguous: + offset = offset.copy() + if matrix.ndim == 1: + warnings.warn( + "The behavior of affine_transform with a 1-D " + "array supplied for the matrix parameter has changed in " + "SciPy 0.18.0.", + stacklevel=2 + ) + _nd_image.zoom_shift(filtered, matrix, offset/matrix, output, order, + mode, cval, npad, False) + else: + _nd_image.geometric_transform(filtered, None, None, matrix, offset, + output, order, mode, cval, npad, None, + None) + return output + + +@docfiller +def shift(input, shift, output=None, order=3, mode='constant', cval=0.0, + prefilter=True): + """ + Shift an array. + + The array is shifted using spline interpolation of the requested order. + Points outside the boundaries of the input are filled according to the + given mode. + + Parameters + ---------- + %(input)s + shift : float or sequence + The shift along the axes. If a float, `shift` is the same for each + axis. If a sequence, `shift` should contain one value for each axis. + %(output)s + order : int, optional + The order of the spline interpolation, default is 3. + The order has to be in the range 0-5. + %(mode_interp_constant)s + %(cval)s + %(prefilter)s + + Returns + ------- + shift : ndarray + The shifted input. + + See Also + -------- + affine_transform : Affine transformations + + Notes + ----- + For complex-valued `input`, this function shifts the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + Import the necessary modules and an exemplary image. + + >>> from scipy.ndimage import shift + >>> import matplotlib.pyplot as plt + >>> from scipy import datasets + >>> image = datasets.ascent() + + Shift the image vertically by 20 pixels. + + >>> image_shifted_vertically = shift(image, (20, 0)) + + Shift the image vertically by -200 pixels and horizontally by 100 pixels. + + >>> image_shifted_both_directions = shift(image, (-200, 100)) + + Plot the original and the shifted images. + + >>> fig, axes = plt.subplots(3, 1, figsize=(4, 12)) + >>> plt.gray() # show the filtered result in grayscale + >>> top, middle, bottom = axes + >>> for ax in axes: + ... ax.set_axis_off() # remove coordinate system + >>> top.imshow(image) + >>> top.set_title("Original image") + >>> middle.imshow(image_shifted_vertically) + >>> middle.set_title("Vertically shifted image") + >>> bottom.imshow(image_shifted_both_directions) + >>> bottom.set_title("Image shifted in both directions") + >>> fig.tight_layout() + """ + if order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + if input.ndim < 1: + raise RuntimeError('input and output rank must be > 0') + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, complex_output=complex_output) + if complex_output: + # import under different name to avoid confusion with shift parameter + from scipy.ndimage._interpolation import shift as _shift + + kwargs = dict(order=order, mode=mode, prefilter=prefilter) + _shift(input.real, shift, output=output.real, cval=np.real(cval), **kwargs) + _shift(input.imag, shift, output=output.imag, cval=np.imag(cval), **kwargs) + return output + if prefilter and order > 1: + padded, npad = _prepad_for_spline_filter(input, mode, cval) + filtered = spline_filter(padded, order, output=np.float64, mode=mode) + else: + npad = 0 + filtered = input + mode = _ni_support._extend_mode_to_code(mode) + shift = _ni_support._normalize_sequence(shift, input.ndim) + shift = [-ii for ii in shift] + shift = np.asarray(shift, dtype=np.float64) + if not shift.flags.contiguous: + shift = shift.copy() + _nd_image.zoom_shift(filtered, None, shift, output, order, mode, cval, + npad, False) + return output + + +@docfiller +def zoom(input, zoom, output=None, order=3, mode='constant', cval=0.0, + prefilter=True, *, grid_mode=False): + """ + Zoom an array. + + The array is zoomed using spline interpolation of the requested order. + + Parameters + ---------- + %(input)s + zoom : float or sequence + The zoom factor along the axes. If a float, `zoom` is the same for each + axis. If a sequence, `zoom` should contain one value for each axis. + %(output)s + order : int, optional + The order of the spline interpolation, default is 3. + The order has to be in the range 0-5. + %(mode_interp_constant)s + %(cval)s + %(prefilter)s + grid_mode : bool, optional + If False, the distance from the pixel centers is zoomed. Otherwise, the + distance including the full pixel extent is used. For example, a 1d + signal of length 5 is considered to have length 4 when `grid_mode` is + False, but length 5 when `grid_mode` is True. See the following + visual illustration: + + .. code-block:: text + + | pixel 1 | pixel 2 | pixel 3 | pixel 4 | pixel 5 | + |<-------------------------------------->| + vs. + |<----------------------------------------------->| + + The starting point of the arrow in the diagram above corresponds to + coordinate location 0 in each mode. + + Returns + ------- + zoom : ndarray + The zoomed input. + + Notes + ----- + For complex-valued `input`, this function zooms the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + + >>> fig = plt.figure() + >>> ax1 = fig.add_subplot(121) # left side + >>> ax2 = fig.add_subplot(122) # right side + >>> ascent = datasets.ascent() + >>> result = ndimage.zoom(ascent, 3.0) + >>> ax1.imshow(ascent, vmin=0, vmax=255) + >>> ax2.imshow(result, vmin=0, vmax=255) + >>> plt.show() + + >>> print(ascent.shape) + (512, 512) + + >>> print(result.shape) + (1536, 1536) + """ + if order < 0 or order > 5: + raise RuntimeError('spline order not supported') + input = np.asarray(input) + if input.ndim < 1: + raise RuntimeError('input and output rank must be > 0') + zoom = _ni_support._normalize_sequence(zoom, input.ndim) + output_shape = tuple( + [int(round(ii * jj)) for ii, jj in zip(input.shape, zoom)]) + complex_output = np.iscomplexobj(input) + output = _ni_support._get_output(output, input, shape=output_shape, + complex_output=complex_output) + if complex_output: + # import under different name to avoid confusion with zoom parameter + from scipy.ndimage._interpolation import zoom as _zoom + + kwargs = dict(order=order, mode=mode, prefilter=prefilter) + _zoom(input.real, zoom, output=output.real, cval=np.real(cval), **kwargs) + _zoom(input.imag, zoom, output=output.imag, cval=np.imag(cval), **kwargs) + return output + if prefilter and order > 1: + padded, npad = _prepad_for_spline_filter(input, mode, cval) + filtered = spline_filter(padded, order, output=np.float64, mode=mode) + else: + npad = 0 + filtered = input + if grid_mode: + # warn about modes that may have surprising behavior + suggest_mode = None + if mode == 'constant': + suggest_mode = 'grid-constant' + elif mode == 'wrap': + suggest_mode = 'grid-wrap' + if suggest_mode is not None: + warnings.warn( + (f"It is recommended to use mode = {suggest_mode} instead of {mode} " + f"when grid_mode is True."), + stacklevel=2 + ) + mode = _ni_support._extend_mode_to_code(mode) + + zoom_div = np.array(output_shape) + zoom_nominator = np.array(input.shape) + if not grid_mode: + zoom_div -= 1 + zoom_nominator -= 1 + + # Zooming to infinite values is unpredictable, so just choose + # zoom factor 1 instead + zoom = np.divide(zoom_nominator, zoom_div, + out=np.ones_like(input.shape, dtype=np.float64), + where=zoom_div != 0) + zoom = np.ascontiguousarray(zoom) + _nd_image.zoom_shift(filtered, zoom, None, output, order, mode, cval, npad, + grid_mode) + return output + + +@docfiller +def rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=3, + mode='constant', cval=0.0, prefilter=True): + """ + Rotate an array. + + The array is rotated in the plane defined by the two axes given by the + `axes` parameter using spline interpolation of the requested order. + + Parameters + ---------- + %(input)s + angle : float + The rotation angle in degrees. + axes : tuple of 2 ints, optional + The two axes that define the plane of rotation. Default is the first + two axes. + reshape : bool, optional + If `reshape` is true, the output shape is adapted so that the input + array is contained completely in the output. Default is True. + %(output)s + order : int, optional + The order of the spline interpolation, default is 3. + The order has to be in the range 0-5. + %(mode_interp_constant)s + %(cval)s + %(prefilter)s + + Returns + ------- + rotate : ndarray + The rotated input. + + Notes + ----- + For complex-valued `input`, this function rotates the real and imaginary + components independently. + + .. versionadded:: 1.6.0 + Complex-valued support added. + + Examples + -------- + >>> from scipy import ndimage, datasets + >>> import matplotlib.pyplot as plt + >>> fig = plt.figure(figsize=(10, 3)) + >>> ax1, ax2, ax3 = fig.subplots(1, 3) + >>> img = datasets.ascent() + >>> img_45 = ndimage.rotate(img, 45, reshape=False) + >>> full_img_45 = ndimage.rotate(img, 45, reshape=True) + >>> ax1.imshow(img, cmap='gray') + >>> ax1.set_axis_off() + >>> ax2.imshow(img_45, cmap='gray') + >>> ax2.set_axis_off() + >>> ax3.imshow(full_img_45, cmap='gray') + >>> ax3.set_axis_off() + >>> fig.set_layout_engine('tight') + >>> plt.show() + >>> print(img.shape) + (512, 512) + >>> print(img_45.shape) + (512, 512) + >>> print(full_img_45.shape) + (724, 724) + + """ + input_arr = np.asarray(input) + ndim = input_arr.ndim + + if ndim < 2: + raise ValueError('input array should be at least 2D') + + axes = list(axes) + + if len(axes) != 2: + raise ValueError('axes should contain exactly two values') + + if not all([float(ax).is_integer() for ax in axes]): + raise ValueError('axes should contain only integer values') + + if axes[0] < 0: + axes[0] += ndim + if axes[1] < 0: + axes[1] += ndim + if axes[0] < 0 or axes[1] < 0 or axes[0] >= ndim or axes[1] >= ndim: + raise ValueError('invalid rotation plane specified') + + axes.sort() + + c, s = special.cosdg(angle), special.sindg(angle) + + rot_matrix = np.array([[c, s], + [-s, c]]) + + img_shape = np.asarray(input_arr.shape) + in_plane_shape = img_shape[axes] + if reshape: + # Compute transformed input bounds + iy, ix = in_plane_shape + out_bounds = rot_matrix @ [[0, 0, iy, iy], + [0, ix, 0, ix]] + # Compute the shape of the transformed input plane + out_plane_shape = (np.ptp(out_bounds, axis=1) + 0.5).astype(int) + else: + out_plane_shape = img_shape[axes] + + out_center = rot_matrix @ ((out_plane_shape - 1) / 2) + in_center = (in_plane_shape - 1) / 2 + offset = in_center - out_center + + output_shape = img_shape + output_shape[axes] = out_plane_shape + output_shape = tuple(output_shape) + + complex_output = np.iscomplexobj(input_arr) + output = _ni_support._get_output(output, input_arr, shape=output_shape, + complex_output=complex_output) + + if ndim <= 2: + affine_transform(input_arr, rot_matrix, offset, output_shape, output, + order, mode, cval, prefilter) + else: + # If ndim > 2, the rotation is applied over all the planes + # parallel to axes + planes_coord = itertools.product( + *[[slice(None)] if ax in axes else range(img_shape[ax]) + for ax in range(ndim)]) + + out_plane_shape = tuple(out_plane_shape) + + for coordinates in planes_coord: + ia = input_arr[coordinates] + oa = output[coordinates] + affine_transform(ia, rot_matrix, offset, out_plane_shape, + oa, order, mode, cval, prefilter) + + return output diff --git a/parrot/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py b/parrot/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py new file mode 100644 index 0000000000000000000000000000000000000000..e6469f2c75fcee1f74dfbbe049df8ca05b074505 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/ndimage/_ni_docstrings.py @@ -0,0 +1,208 @@ +"""Docstring components common to several ndimage functions.""" +from scipy._lib import doccer + +__all__ = ['docfiller'] + + +_input_doc = ( +"""input : array_like + The input array.""") +_axis_doc = ( +"""axis : int, optional + The axis of `input` along which to calculate. Default is -1.""") +_output_doc = ( +"""output : array or dtype, optional + The array in which to place the output, or the dtype of the + returned array. By default an array of the same dtype as input + will be created.""") +_size_foot_doc = ( +"""size : scalar or tuple, optional + See footprint, below. Ignored if footprint is given. +footprint : array, optional + Either `size` or `footprint` must be defined. `size` gives + the shape that is taken from the input array, at every element + position, to define the input to the filter function. + `footprint` is a boolean array that specifies (implicitly) a + shape, but also which of the elements within this shape will get + passed to the filter function. Thus ``size=(n,m)`` is equivalent + to ``footprint=np.ones((n,m))``. We adjust `size` to the number + of dimensions of the input array, so that, if the input array is + shape (10,10,10), and `size` is 2, then the actual size used is + (2,2,2). When `footprint` is given, `size` is ignored.""") +_mode_reflect_doc = ( +"""mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional + The `mode` parameter determines how the input array is extended + beyond its boundaries. Default is 'reflect'. Behavior for each valid + value is as follows: + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + For consistency with the interpolation functions, the following mode + names can also be used: + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'grid-constant' + This is a synonym for 'constant'. + + 'grid-wrap' + This is a synonym for 'wrap'.""") + +_mode_interp_constant_doc = ( +"""mode : {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', \ +'mirror', 'grid-wrap', 'wrap'}, optional + The `mode` parameter determines how the input array is extended + beyond its boundaries. Default is 'constant'. Behavior for each valid + value is as follows (see additional plots and details on + :ref:`boundary modes `): + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. No + interpolation is performed beyond the edges of the input. + + 'grid-constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. Interpolation + occurs for samples outside the input's extent as well. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'grid-wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + 'wrap' (`d b c d | a b c d | b c a b`) + The input is extended by wrapping around to the opposite edge, but in a + way such that the last point and initial point exactly overlap. In this + case it is not well defined which sample will be chosen at the point of + overlap.""") +_mode_interp_mirror_doc = ( + _mode_interp_constant_doc.replace("Default is 'constant'", + "Default is 'mirror'") +) +assert _mode_interp_mirror_doc != _mode_interp_constant_doc, \ + 'Default not replaced' + +_mode_multiple_doc = ( +"""mode : str or sequence, optional + The `mode` parameter determines how the input array is extended + when the filter overlaps a border. By passing a sequence of modes + with length equal to the number of dimensions of the input array, + different modes can be specified along each axis. Default value is + 'reflect'. The valid values and their behavior is as follows: + + 'reflect' (`d c b a | a b c d | d c b a`) + The input is extended by reflecting about the edge of the last + pixel. This mode is also sometimes referred to as half-sample + symmetric. + + 'constant' (`k k k k | a b c d | k k k k`) + The input is extended by filling all values beyond the edge with + the same constant value, defined by the `cval` parameter. + + 'nearest' (`a a a a | a b c d | d d d d`) + The input is extended by replicating the last pixel. + + 'mirror' (`d c b | a b c d | c b a`) + The input is extended by reflecting about the center of the last + pixel. This mode is also sometimes referred to as whole-sample + symmetric. + + 'wrap' (`a b c d | a b c d | a b c d`) + The input is extended by wrapping around to the opposite edge. + + For consistency with the interpolation functions, the following mode + names can also be used: + + 'grid-constant' + This is a synonym for 'constant'. + + 'grid-mirror' + This is a synonym for 'reflect'. + + 'grid-wrap' + This is a synonym for 'wrap'.""") +_cval_doc = ( +"""cval : scalar, optional + Value to fill past edges of input if `mode` is 'constant'. Default + is 0.0.""") +_origin_doc = ( +"""origin : int, optional + Controls the placement of the filter on the input array's pixels. + A value of 0 (the default) centers the filter over the pixel, with + positive values shifting the filter to the left, and negative ones + to the right.""") +_origin_multiple_doc = ( +"""origin : int or sequence, optional + Controls the placement of the filter on the input array's pixels. + A value of 0 (the default) centers the filter over the pixel, with + positive values shifting the filter to the left, and negative ones + to the right. By passing a sequence of origins with length equal to + the number of dimensions of the input array, different shifts can + be specified along each axis.""") +_extra_arguments_doc = ( +"""extra_arguments : sequence, optional + Sequence of extra positional arguments to pass to passed function.""") +_extra_keywords_doc = ( +"""extra_keywords : dict, optional + dict of extra keyword arguments to pass to passed function.""") +_prefilter_doc = ( +"""prefilter : bool, optional + Determines if the input array is prefiltered with `spline_filter` + before interpolation. The default is True, which will create a + temporary `float64` array of filtered values if `order > 1`. If + setting this to False, the output will be slightly blurred if + `order > 1`, unless the input is prefiltered, i.e. it is the result + of calling `spline_filter` on the original input.""") + +docdict = { + 'input': _input_doc, + 'axis': _axis_doc, + 'output': _output_doc, + 'size_foot': _size_foot_doc, + 'mode_interp_constant': _mode_interp_constant_doc, + 'mode_interp_mirror': _mode_interp_mirror_doc, + 'mode_reflect': _mode_reflect_doc, + 'mode_multiple': _mode_multiple_doc, + 'cval': _cval_doc, + 'origin': _origin_doc, + 'origin_multiple': _origin_multiple_doc, + 'extra_arguments': _extra_arguments_doc, + 'extra_keywords': _extra_keywords_doc, + 'prefilter': _prefilter_doc + } + +docfiller = doccer.filldoc(docdict) diff --git a/parrot/lib/python3.10/site-packages/scipy/ndimage/interpolation.py b/parrot/lib/python3.10/site-packages/scipy/ndimage/interpolation.py new file mode 100644 index 0000000000000000000000000000000000000000..a2739c60c51037487ae8892c407e2f3d7870d5da --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/ndimage/interpolation.py @@ -0,0 +1,22 @@ +# This file is not meant for public use and will be removed in SciPy v2.0.0. +# Use the `scipy.ndimage` namespace for importing the functions +# included below. + +from scipy._lib.deprecation import _sub_module_deprecation + + +__all__ = [ # noqa: F822 + 'spline_filter1d', 'spline_filter', + 'geometric_transform', 'map_coordinates', + 'affine_transform', 'shift', 'zoom', 'rotate', +] + + +def __dir__(): + return __all__ + + +def __getattr__(name): + return _sub_module_deprecation(sub_package='ndimage', module='interpolation', + private_modules=['_interpolation'], all=__all__, + attribute=name) diff --git a/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py b/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..1e40498b438bc7555960d68993447f901c3efbc8 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/__init__.py @@ -0,0 +1,13 @@ +from __future__ import annotations +import numpy as np + +# list of numarray data types +integer_types: list[type] = [ + np.int8, np.uint8, np.int16, np.uint16, + np.int32, np.uint32, np.int64, np.uint64] + +float_types: list[type] = [np.float32, np.float64] + +complex_types: list[type] = [np.complex64, np.complex128] + +types: list[type] = integer_types + float_types diff --git a/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py b/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py new file mode 100644 index 0000000000000000000000000000000000000000..ed52ed8477056176e1f5aacbf681b12b0153fee6 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/test_c_api.py @@ -0,0 +1,102 @@ +import numpy as np +from numpy.testing import assert_allclose + +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,)) + assert_allclose(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,)) + assert_allclose(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,)) + assert_allclose(res, std, err_msg=f"#{j} failed") + + for j, func in enumerate(TRANSFORM_FUNCTIONS): + check(j) diff --git a/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py b/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py new file mode 100644 index 0000000000000000000000000000000000000000..cd9382a16ada38a6d3059d54ad765c2e0f74b7c1 --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/test_datatypes.py @@ -0,0 +1,66 @@ +""" Testing data types for ndimage calls +""" +import numpy as np +from numpy.testing import assert_array_almost_equal, assert_ +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/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py b/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py new file mode 100644 index 0000000000000000000000000000000000000000..6782cf463cfffa857be731bceb5d87377084864c --- /dev/null +++ b/parrot/lib/python3.10/site-packages/scipy/ndimage/tests/test_filters.py @@ -0,0 +1,2214 @@ +''' Some tests for filters ''' +import functools +import itertools +import math +import numpy as np + +from numpy.testing import (assert_equal, assert_allclose, + assert_array_almost_equal, + assert_array_equal, assert_almost_equal, + suppress_warnings, assert_) +import pytest +from pytest import raises as assert_raises + +from scipy import ndimage +from scipy.ndimage._filters import _gaussian_kernel1d + +from . import types, float_types, complex_types + + +def sumsq(a, b): + return math.sqrt(((a - b)**2).sum()) + + +def _complex_correlate(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 = np.asarray(array) + kernel = np.asarray(kernel) + complex_array = array.dtype.kind == 'c' + complex_kernel = kernel.dtype.kind == 'c' + 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 = kernel.conj() + if complex_array and complex_kernel: + # use: real(cval) for array.real component + # imag(cval) for array.imag component + output = ( + func(array.real, kernel.real, output=real_dtype, + mode=mode, cval=np.real(cval)) - + func(array.imag, kernel.imag, output=real_dtype, + mode=mode, cval=np.imag(cval)) + + 1j * func(array.imag, kernel.real, output=real_dtype, + mode=mode, cval=np.imag(cval)) + + 1j * func(array.real, kernel.imag, output=real_dtype, + mode=mode, cval=np.real(cval)) + ) + elif complex_array: + output = ( + func(array.real, kernel, output=real_dtype, mode=mode, + cval=np.real(cval)) + + 1j * func(array.imag, kernel, output=real_dtype, mode=mode, + cval=np.imag(cval)) + ) + elif complex_kernel: + # real array so cval is real too + output = ( + func(array, kernel.real, output=real_dtype, mode=mode, cval=cval) + + 1j * func(array, kernel.imag, 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 + + +class TestNdimageFilters: + + def _validate_complex(self, array, kernel, type2, mode='reflect', cval=0): + # utility for validating complex-valued correlations + real_dtype = np.asarray([], dtype=type2).real.dtype + expected = _complex_correlate( + 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_equal(output.dtype.type, type2) + + # test correlate with pre-allocated output + output = np.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( + array, kernel, real_dtype, convolve=True, mode=mode, cval=cval, + ) + assert_array_almost_equal(expected, output) + assert_equal(output.dtype.type, type2) + + # convolve with pre-allocated output + convolve(array, kernel, output=output) + assert_array_almost_equal(expected, output) + assert_equal(output.dtype.type, type2) + + # 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 = np.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): + array = np.array([1, 2]) + weights = np.array([2]) + expected = [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) + + def test_correlate01_overlap(self): + array = np.arange(256).reshape(16, 16) + weights = np.array([2]) + expected = 2 * array + + ndimage.correlate1d(array, weights, output=array) + assert_array_almost_equal(array, expected) + + def test_correlate02(self): + array = np.array([1, 2, 3]) + kernel = np.array([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): + array = np.array([1]) + weights = np.array([1, 1]) + expected = [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): + array = np.array([1, 2]) + tcor = [2, 3] + tcov = [3, 4] + weights = np.array([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): + array = np.array([1, 2, 3]) + tcor = [2, 3, 5] + tcov = [3, 5, 6] + kernel = np.array([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): + array = np.array([1, 2, 3]) + tcor = [9, 14, 17] + tcov = [7, 10, 15] + weights = np.array([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): + array = np.array([1, 2, 3]) + expected = [5, 8, 11] + weights = np.array([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): + array = np.array([1, 2, 3]) + tcor = [1, 2, 5] + tcov = [3, 6, 7] + weights = np.array([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): + array = [] + kernel = np.array([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): + array = [[]] + kernel = np.array([[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): + array = np.array([[1, 2, 3], + [4, 5, 6]]) + kernel = np.array([[1, 1], + [1, 1]]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal([[4, 6, 10], [10, 12, 16]], output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal([[12, 16, 18], [18, 22, 24]], output) + + def test_correlate12(self): + array = np.array([[1, 2, 3], + [4, 5, 6]]) + kernel = np.array([[1, 0], + [0, 1]]) + output = ndimage.correlate(array, kernel) + assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) + output = ndimage.convolve(array, kernel) + assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_kernel', types) + def test_correlate13(self, dtype_array, dtype_kernel): + kernel = np.array([[1, 0], + [0, 1]]) + array = np.array([[1, 2, 3], + [4, 5, 6]], dtype_array) + output = ndimage.correlate(array, kernel, output=dtype_kernel) + assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) + assert_equal(output.dtype.type, dtype_kernel) + + output = ndimage.convolve(array, kernel, + output=dtype_kernel) + assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) + assert_equal(output.dtype.type, dtype_kernel) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate14(self, dtype_array, dtype_output): + kernel = np.array([[1, 0], + [0, 1]]) + array = np.array([[1, 2, 3], + [4, 5, 6]], dtype_array) + output = np.zeros(array.shape, dtype_output) + ndimage.correlate(array, kernel, output=output) + assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) + assert_equal(output.dtype.type, dtype_output) + + ndimage.convolve(array, kernel, output=output) + assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) + assert_equal(output.dtype.type, dtype_output) + + @pytest.mark.parametrize('dtype_array', types) + def test_correlate15(self, dtype_array): + kernel = np.array([[1, 0], + [0, 1]]) + array = np.array([[1, 2, 3], + [4, 5, 6]], dtype_array) + output = ndimage.correlate(array, kernel, output=np.float32) + assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) + assert_equal(output.dtype.type, np.float32) + + output = ndimage.convolve(array, kernel, output=np.float32) + assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) + assert_equal(output.dtype.type, np.float32) + + @pytest.mark.parametrize('dtype_array', types) + def test_correlate16(self, dtype_array): + kernel = np.array([[0.5, 0], + [0, 0.5]]) + array = np.array([[1, 2, 3], [4, 5, 6]], dtype_array) + output = ndimage.correlate(array, kernel, output=np.float32) + assert_array_almost_equal([[1, 1.5, 2.5], [2.5, 3, 4]], output) + assert_equal(output.dtype.type, np.float32) + + output = ndimage.convolve(array, kernel, output=np.float32) + assert_array_almost_equal([[3, 4, 4.5], [4.5, 5.5, 6]], output) + assert_equal(output.dtype.type, np.float32) + + def test_correlate17(self): + array = np.array([1, 2, 3]) + tcor = [3, 5, 6] + tcov = [2, 3, 5] + kernel = np.array([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) + + @pytest.mark.parametrize('dtype_array', types) + def test_correlate18(self, dtype_array): + kernel = np.array([[1, 0], + [0, 1]]) + array = np.array([[1, 2, 3], + [4, 5, 6]], dtype_array) + output = ndimage.correlate(array, kernel, + output=np.float32, + mode='nearest', origin=-1) + assert_array_almost_equal([[6, 8, 9], [9, 11, 12]], output) + assert_equal(output.dtype.type, np.float32) + + output = ndimage.convolve(array, kernel, + output=np.float32, + mode='nearest', origin=-1) + assert_array_almost_equal([[2, 3, 5], [5, 6, 8]], output) + assert_equal(output.dtype.type, np.float32) + + def test_correlate_mode_sequence(self): + kernel = np.ones((2, 2)) + array = np.ones((3, 3), float) + with assert_raises(RuntimeError): + ndimage.correlate(array, kernel, mode=['nearest', 'reflect']) + with assert_raises(RuntimeError): + ndimage.convolve(array, kernel, mode=['nearest', 'reflect']) + + @pytest.mark.parametrize('dtype_array', types) + def test_correlate19(self, dtype_array): + kernel = np.array([[1, 0], + [0, 1]]) + array = np.array([[1, 2, 3], + [4, 5, 6]], dtype_array) + output = ndimage.correlate(array, kernel, + output=np.float32, + mode='nearest', origin=[-1, 0]) + assert_array_almost_equal([[5, 6, 8], [8, 9, 11]], output) + assert_equal(output.dtype.type, np.float32) + + output = ndimage.convolve(array, kernel, + output=np.float32, + mode='nearest', origin=[-1, 0]) + assert_array_almost_equal([[3, 5, 6], [6, 8, 9]], output) + assert_equal(output.dtype.type, np.float32) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate20(self, dtype_array, dtype_output): + weights = np.array([1, 2, 1]) + expected = [[5, 10, 15], [7, 14, 21]] + array = np.array([[1, 2, 3], + [2, 4, 6]], dtype_array) + output = np.zeros((2, 3), 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): + array = np.array([[1, 2, 3], + [2, 4, 6]]) + expected = [[5, 10, 15], [7, 14, 21]] + weights = np.array([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) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate22(self, dtype_array, dtype_output): + weights = np.array([1, 2, 1]) + expected = [[6, 12, 18], [6, 12, 18]] + array = np.array([[1, 2, 3], + [2, 4, 6]], dtype_array) + output = np.zeros((2, 3), 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) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate23(self, dtype_array, dtype_output): + weights = np.array([1, 2, 1]) + expected = [[5, 10, 15], [7, 14, 21]] + array = np.array([[1, 2, 3], + [2, 4, 6]], dtype_array) + output = np.zeros((2, 3), 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) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate24(self, dtype_array, dtype_output): + weights = np.array([1, 2, 1]) + tcor = [[7, 14, 21], [8, 16, 24]] + tcov = [[4, 8, 12], [5, 10, 15]] + array = np.array([[1, 2, 3], + [2, 4, 6]], dtype_array) + output = np.zeros((2, 3), 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) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_correlate25(self, dtype_array, dtype_output): + weights = np.array([1, 2, 1]) + tcor = [[4, 8, 12], [5, 10, 15]] + tcov = [[7, 14, 21], [8, 16, 24]] + array = np.array([[1, 2, 3], + [2, 4, 6]], dtype_array) + output = np.zeros((2, 3), 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): + # test fix for gh-11661 (mirror extension of a length 1 signal) + y = ndimage.convolve1d(np.ones(1), np.ones(5), mode='mirror') + assert_array_equal(y, np.array(5.)) + + y = ndimage.correlate1d(np.ones(1), np.ones(5), mode='mirror') + assert_array_equal(y, np.array(5.)) + + @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): + kernel = np.array([[1, 0], + [0, 1 + 1j]], dtype_kernel) + array = np.array([[1, 2, 3], + [4, 5, 6]], dtype_input) + self._validate_complex(array, kernel, dtype_output) + + @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): + # test use of non-zero cval with complex inputs + # also verifies that mode 'grid-constant' does not segfault + kernel = np.array([[1, 0], + [0, 1 + 1j]], dtype_kernel) + array = np.array([[1, 2, 3], + [4, 5, 6]], dtype_input) + self._validate_complex(array, kernel, dtype_output, mode=mode, + cval=5.0) + + @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): + # cannot give complex cval with a real image + kernel = np.array([[1, 0], + [0, 1 + 1j]], dtype_kernel) + array = np.array([[1, 2, 3], + [4, 5, 6]], dtype_input) + for func in [ndimage.convolve, ndimage.correlate, ndimage.convolve1d, + ndimage.correlate1d]: + with pytest.raises(ValueError): + func(array, kernel, mode='constant', cval=5.0 + 1.0j, + output=np.complex64) + + @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): + kernel = np.array([1, 1 + 1j], dtype_kernel) + array = np.array([1, 2, 3, 4, 5, 6], dtype_input) + self._validate_complex(array, kernel, dtype_output) + + @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): + kernel = np.array([1, 1 + 1j], dtype_kernel) + array = np.array([1, 2, 3, 4, 5, 6], dtype_input) + self._validate_complex(array, kernel, dtype_output, mode='constant', + cval=5.0) + + @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): + kernel = np.array([[1, 0], + [0, 1]], dtype_kernel) + array = np.array([[1, 2j, 3], + [1 + 4j, 5, 6j]], dtype_input) + self._validate_complex(array, kernel, dtype_output) + + @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): + kernel = np.array([1, 0, 1], dtype_kernel) + array = np.array([1, 2j, 3, 1 + 4j, 5, 6j], dtype_input) + self._validate_complex(array, kernel, dtype_output) + + @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): + kernel = np.array([1, 0, 1], dtype_kernel) + array = np.array([1, 2j, 3, 1 + 4j, 5, 6j], dtype_input) + self._validate_complex(array, kernel, dtype_output, mode='constant', + cval=5 - 3j) + + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate_complex_input_and_kernel(self, dtype, dtype_output): + kernel = np.array([[1, 0], + [0, 1 + 1j]], dtype) + array = np.array([[1, 2j, 3], + [1 + 4j, 5, 6j]], dtype) + self._validate_complex(array, kernel, dtype_output) + + @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): + kernel = np.array([[1, 0], + [0, 1 + 1j]], dtype) + array = np.array([[1, 2, 3], + [4, 5, 6]], dtype) + self._validate_complex(array, kernel, dtype_output, mode='constant', + cval=5.0 + 2.0j) + + @pytest.mark.parametrize('dtype', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_correlate1d_complex_input_and_kernel(self, dtype, dtype_output): + kernel = np.array([1, 1 + 1j], dtype) + array = np.array([1, 2j, 3, 1 + 4j, 5, 6j], dtype) + self._validate_complex(array, kernel, dtype_output) + + @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): + kernel = np.array([1, 1 + 1j], dtype) + array = np.array([1, 2j, 3, 1 + 4j, 5, 6j], dtype) + self._validate_complex(array, kernel, dtype_output, mode='constant', + cval=5.0 + 2.0j) + + def test_gauss01(self): + input = np.array([[1, 2, 3], + [2, 4, 6]], np.float32) + output = ndimage.gaussian_filter(input, 0) + assert_array_almost_equal(output, input) + + def test_gauss02(self): + input = np.array([[1, 2, 3], + [2, 4, 6]], np.float32) + output = ndimage.gaussian_filter(input, 1.0) + assert_equal(input.dtype, output.dtype) + assert_equal(input.shape, output.shape) + + def test_gauss03(self): + # single precision data + input = np.arange(100 * 100).astype(np.float32) + input.shape = (100, 100) + output = ndimage.gaussian_filter(input, [1.0, 1.0]) + + assert_equal(input.dtype, output.dtype) + assert_equal(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. + assert_almost_equal(output.sum(dtype='d'), input.sum(dtype='d'), + decimal=0) + assert_(sumsq(input, output) > 1.0) + + def test_gauss04(self): + input = np.arange(100 * 100).astype(np.float32) + input.shape = (100, 100) + otype = np.float64 + output = ndimage.gaussian_filter(input, [1.0, 1.0], output=otype) + assert_equal(output.dtype.type, np.float64) + assert_equal(input.shape, output.shape) + assert_(sumsq(input, output) > 1.0) + + def test_gauss05(self): + input = np.arange(100 * 100).astype(np.float32) + input.shape = (100, 100) + otype = np.float64 + output = ndimage.gaussian_filter(input, [1.0, 1.0], + order=1, output=otype) + assert_equal(output.dtype.type, np.float64) + assert_equal(input.shape, output.shape) + assert_(sumsq(input, output) > 1.0) + + def test_gauss06(self): + input = np.arange(100 * 100).astype(np.float32) + input.shape = (100, 100) + otype = np.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) + + def test_gauss_memory_overlap(self): + input = np.arange(100 * 100).astype(np.float32) + input.shape = (100, 100) + output1 = ndimage.gaussian_filter(input, 1.0) + ndimage.gaussian_filter(input, 1.0, output=input) + assert_array_almost_equal(output1, input) + + @pytest.mark.parametrize(('filter_func', 'extra_args', 'size0', 'size'), + [(ndimage.gaussian_filter, (), 0, 1.0), + (ndimage.uniform_filter, (), 1, 3), + (ndimage.minimum_filter, (), 1, 3), + (ndimage.maximum_filter, (), 1, 3), + (ndimage.median_filter, (), 1, 3), + (ndimage.rank_filter, (1,), 1, 3), + (ndimage.percentile_filter, (40,), 1, 3)]) + @pytest.mark.parametrize( + 'axes', + tuple(itertools.combinations(range(-3, 3), 1)) + + tuple(itertools.combinations(range(-3, 3), 2)) + + ((0, 1, 2),)) + def test_filter_axes(self, filter_func, extra_args, size0, size, axes): + # Note: `size` is called `sigma` in `gaussian_filter` + array = np.arange(6 * 8 * 12, dtype=np.float64).reshape(6, 8, 12) + axes = np.array(axes) + + 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, *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 + all_sizes = (size if ax in (axes % array.ndim) else size0 + for ax in range(array.ndim)) + expected = filter_func(array, *extra_args, all_sizes) + assert_allclose(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)) + + @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): + array = np.arange(6 * 8 * 12, dtype=np.float64).reshape(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 + if 'origin' in kwargs: + # origin should be zero on the axis that has size 0 + origin = np.array([0, 0, 0]) + origin[axes] = reduced_kwargs['origin'] + kwargs['origin'] = origin + expected = filter_func(array, *args, size_3d, **kwargs) + assert_allclose(output, expected) + + @pytest.mark.parametrize("filter_func, kwargs", + [(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): + axes = (-2, -1) + origins = (0, 1) + array = np.arange(6 * 8 * 12, dtype=np.float64).reshape(6, 8, 12) + axes = np.array(axes) + + # weights with ndim matching len(axes) + footprint = np.ones((3, 5), dtype=bool) + footprint[0, 1] = 0 # make non-separable + + output = filter_func( + array, footprint=footprint, axes=axes, origin=origins, **kwargs) + + output0 = filter_func( + array, footprint=footprint, axes=axes, origin=0, **kwargs) + + # output has origin shift on last axis relative to output0, so + # expect shifted arrays to be equal. + np.testing.assert_array_equal(output[:, :, 1:], output0[:, :, :-1]) + + @pytest.mark.parametrize( + 'filter_func, args', + [(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): + array = np.arange(6 * 8 * 12, dtype=np.float64).reshape(6, 8, 12) + if any(isinstance(ax, float) for ax in axes): + error_class = TypeError + match = "cannot be interpreted as an integer" + else: + error_class = ValueError + match = "out of range" + with pytest.raises(error_class, match=match): + filter_func(array, *args, axes=axes) + + @pytest.mark.parametrize( + 'filter_func, kwargs', + [(ndimage.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): + array = np.arange(6 * 8 * 12, dtype=np.float64).reshape(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 + if (filter_func in [ndimage.minimum_filter, ndimage.maximum_filter] + and separable_footprint): + match = "sequence argument must have length equal to input rank" + else: + match = "footprint array has incorrect shape" + with pytest.raises(RuntimeError, match=match): + filter_func(array, **kwargs, footprint=footprint, axes=axes) + + @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): + # Test for the intended RuntimeError when a kwargs has an invalid size + array = np.arange(6 * 8 * 12, dtype=np.float64).reshape(6, 8, 12) + kwargs = dict(**kwargs, axes=(0, 1)) + kwargs[key] = (val,) * n_mismatch + 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): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) + t = ndimage.correlate1d(t, [1.0, 1.0, 1.0], 1) + output = ndimage.prewitt(array, 0) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt02(self, dtype): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) + t = ndimage.correlate1d(t, [1.0, 1.0, 1.0], 1) + output = np.zeros(array.shape, dtype) + ndimage.prewitt(array, 0, output) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_prewitt03(self, dtype): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 1) + t = ndimage.correlate1d(t, [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): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], 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): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) + t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 1) + output = ndimage.sobel(array, 0) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel02(self, dtype): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 0) + t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 1) + output = np.zeros(array.shape, dtype) + ndimage.sobel(array, 0, output) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel03(self, dtype): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.correlate1d(array, [-1.0, 0.0, 1.0], 1) + t = ndimage.correlate1d(t, [1.0, 2.0, 1.0], 0) + output = np.zeros(array.shape, dtype) + output = ndimage.sobel(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_sobel04(self, dtype): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + t = ndimage.sobel(array, -1) + output = ndimage.sobel(array, 1) + assert_array_almost_equal(t, output) + + @pytest.mark.parametrize('dtype', + [np.int32, np.float32, np.float64, + np.complex64, np.complex128]) + def test_laplace01(self, dtype): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) * 100 + tmp1 = ndimage.correlate1d(array, [1, -2, 1], 0) + tmp2 = ndimage.correlate1d(array, [1, -2, 1], 1) + output = ndimage.laplace(array) + assert_array_almost_equal(tmp1 + tmp2, output) + + @pytest.mark.parametrize('dtype', + [np.int32, np.float32, np.float64, + np.complex64, np.complex128]) + def test_laplace02(self, dtype): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) * 100 + tmp1 = ndimage.correlate1d(array, [1, -2, 1], 0) + tmp2 = ndimage.correlate1d(array, [1, -2, 1], 1) + output = np.zeros(array.shape, dtype) + ndimage.laplace(array, output=output) + assert_array_almost_equal(tmp1 + tmp2, output) + + @pytest.mark.parametrize('dtype', + [np.int32, np.float32, np.float64, + np.complex64, np.complex128]) + def test_gaussian_laplace01(self, dtype): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], 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) + + @pytest.mark.parametrize('dtype', + [np.int32, np.float32, np.float64, + np.complex64, np.complex128]) + def test_gaussian_laplace02(self, dtype): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [2, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 2]) + output = np.zeros(array.shape, dtype) + ndimage.gaussian_laplace(array, 1.0, output) + assert_array_almost_equal(tmp1 + tmp2, output) + + @pytest.mark.parametrize('dtype', types + complex_types) + def test_generic_laplace01(self, dtype): + def derivative2(input, axis, output, mode, cval, a, b): + sigma = [a, b / 2.0] + input = np.asarray(input) + order = [0] * input.ndim + order[axis] = 2 + return ndimage.gaussian_filter(input, sigma, order, + output, mode, cval) + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + output = np.zeros(array.shape, 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', + [np.int32, np.float32, np.float64, + np.complex64, np.complex128]) + def test_gaussian_gradient_magnitude01(self, dtype): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], 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 = np.sqrt(expected).astype(dtype) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', + [np.int32, np.float32, np.float64, + np.complex64, np.complex128]) + def test_gaussian_gradient_magnitude02(self, dtype): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) * 100 + tmp1 = ndimage.gaussian_filter(array, 1.0, [1, 0]) + tmp2 = ndimage.gaussian_filter(array, 1.0, [0, 1]) + output = np.zeros(array.shape, dtype) + ndimage.gaussian_gradient_magnitude(array, 1.0, output) + expected = tmp1 * tmp1 + tmp2 * tmp2 + expected = np.sqrt(expected).astype(dtype) + assert_array_almost_equal(expected, output) + + def test_generic_gradient_magnitude01(self): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], np.float64) + + def derivative(input, axis, output, mode, cval, a, b): + sigma = [a, b / 2.0] + input = np.asarray(input) + 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): + array = np.array([2, 4, 6]) + size = 2 + output = ndimage.uniform_filter1d(array, size, origin=-1) + assert_array_almost_equal([3, 5, 6], output) + + def test_uniform01_complex(self): + array = np.array([2 + 1j, 4 + 2j, 6 + 3j], dtype=np.complex128) + size = 2 + output = ndimage.uniform_filter1d(array, size, origin=-1) + assert_array_almost_equal([3, 5, 6], output.real) + assert_array_almost_equal([1.5, 2.5, 3], output.imag) + + def test_uniform02(self): + array = np.array([1, 2, 3]) + filter_shape = [0] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(array, output) + + def test_uniform03(self): + array = np.array([1, 2, 3]) + filter_shape = [1] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal(array, output) + + def test_uniform04(self): + array = np.array([2, 4, 6]) + filter_shape = [2] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal([2, 3, 5], output) + + def test_uniform05(self): + array = [] + filter_shape = [1] + output = ndimage.uniform_filter(array, filter_shape) + assert_array_almost_equal([], output) + + @pytest.mark.parametrize('dtype_array', types) + @pytest.mark.parametrize('dtype_output', types) + def test_uniform06(self, dtype_array, dtype_output): + filter_shape = [2, 2] + array = np.array([[4, 8, 12], + [16, 20, 24]], dtype_array) + output = ndimage.uniform_filter( + array, filter_shape, output=dtype_output) + assert_array_almost_equal([[4, 6, 10], [10, 12, 16]], output) + assert_equal(output.dtype.type, dtype_output) + + @pytest.mark.parametrize('dtype_array', complex_types) + @pytest.mark.parametrize('dtype_output', complex_types) + def test_uniform06_complex(self, dtype_array, dtype_output): + filter_shape = [2, 2] + array = np.array([[4, 8 + 5j, 12], + [16, 20, 24]], dtype_array) + output = ndimage.uniform_filter( + array, filter_shape, output=dtype_output) + assert_array_almost_equal([[4, 6, 10], [10, 12, 16]], output.real) + assert_equal(output.dtype.type, dtype_output) + + def test_minimum_filter01(self): + array = np.array([1, 2, 3, 4, 5]) + filter_shape = np.array([2]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal([1, 1, 2, 3, 4], output) + + def test_minimum_filter02(self): + array = np.array([1, 2, 3, 4, 5]) + filter_shape = np.array([3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal([1, 1, 2, 3, 4], output) + + def test_minimum_filter03(self): + array = np.array([3, 2, 5, 1, 4]) + filter_shape = np.array([2]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal([3, 2, 2, 1, 1], output) + + def test_minimum_filter04(self): + array = np.array([3, 2, 5, 1, 4]) + filter_shape = np.array([3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal([2, 2, 1, 1, 1], output) + + def test_minimum_filter05(self): + array = np.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = np.array([2, 3]) + output = ndimage.minimum_filter(array, filter_shape) + assert_array_almost_equal([[2, 2, 1, 1, 1], + [2, 2, 1, 1, 1], + [5, 3, 3, 1, 1]], output) + + def test_minimum_filter05_overlap(self): + array = np.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = np.array([2, 3]) + ndimage.minimum_filter(array, filter_shape, output=array) + assert_array_almost_equal([[2, 2, 1, 1, 1], + [2, 2, 1, 1, 1], + [5, 3, 3, 1, 1]], array) + + def test_minimum_filter06(self): + array = np.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 1, 1], [1, 1, 1]] + output = ndimage.minimum_filter(array, footprint=footprint) + assert_array_almost_equal([[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): + array = np.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.minimum_filter(array, footprint=footprint) + assert_array_almost_equal([[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): + array = np.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.minimum_filter(array, footprint=footprint, origin=-1) + assert_array_almost_equal([[3, 1, 3, 1, 1], + [5, 3, 3, 1, 1], + [3, 3, 1, 1, 1]], output) + + def test_minimum_filter09(self): + array = np.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.minimum_filter(array, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal([[2, 3, 1, 3, 1], + [5, 5, 3, 3, 1], + [5, 3, 3, 1, 1]], output) + + def test_maximum_filter01(self): + array = np.array([1, 2, 3, 4, 5]) + filter_shape = np.array([2]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal([1, 2, 3, 4, 5], output) + + def test_maximum_filter02(self): + array = np.array([1, 2, 3, 4, 5]) + filter_shape = np.array([3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal([2, 3, 4, 5, 5], output) + + def test_maximum_filter03(self): + array = np.array([3, 2, 5, 1, 4]) + filter_shape = np.array([2]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal([3, 3, 5, 5, 4], output) + + def test_maximum_filter04(self): + array = np.array([3, 2, 5, 1, 4]) + filter_shape = np.array([3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal([3, 5, 5, 5, 4], output) + + def test_maximum_filter05(self): + array = np.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + filter_shape = np.array([2, 3]) + output = ndimage.maximum_filter(array, filter_shape) + assert_array_almost_equal([[3, 5, 5, 5, 4], + [7, 9, 9, 9, 5], + [8, 9, 9, 9, 7]], output) + + def test_maximum_filter06(self): + array = np.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 1, 1], [1, 1, 1]] + output = ndimage.maximum_filter(array, footprint=footprint) + assert_array_almost_equal([[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): + array = np.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.maximum_filter(array, footprint=footprint) + assert_array_almost_equal([[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): + array = np.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.maximum_filter(array, footprint=footprint, origin=-1) + assert_array_almost_equal([[7, 9, 9, 5, 5], + [9, 8, 9, 7, 5], + [8, 8, 7, 7, 7]], output) + + def test_maximum_filter09(self): + array = np.array([[3, 2, 5, 1, 4], + [7, 6, 9, 3, 5], + [5, 8, 3, 7, 1]]) + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.maximum_filter(array, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal([[7, 7, 9, 9, 5], + [7, 9, 8, 9, 7], + [8, 8, 8, 7, 7]], output) + + @pytest.mark.parametrize( + 'axes', tuple(itertools.combinations(range(-3, 3), 2)) + ) + @pytest.mark.parametrize( + 'filter_func, kwargs', + [(ndimage.minimum_filter, {}), + (ndimage.maximum_filter, {}), + (ndimage.median_filter, {}), + (ndimage.rank_filter, dict(rank=3)), + (ndimage.percentile_filter, dict(percentile=60))] + ) + def test_minmax_nonseparable_axes(self, filter_func, axes, kwargs): + array = np.arange(6 * 8 * 12, dtype=np.float32).reshape(6, 8, 12) + # use 2D triangular footprint because it is non-separable + footprint = np.tri(5) + axes = np.array(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 = np.expand_dims(footprint, missing_axis) + expected = filter_func(array, footprint=footprint_3d, **kwargs) + assert_allclose(output, expected) + + def test_rank01(self): + array = np.array([1, 2, 3, 4, 5]) + output = ndimage.rank_filter(array, 1, size=2) + assert_array_almost_equal(array, output) + output = ndimage.percentile_filter(array, 100, size=2) + assert_array_almost_equal(array, output) + output = ndimage.median_filter(array, 2) + assert_array_almost_equal(array, output) + + def test_rank02(self): + array = np.array([1, 2, 3, 4, 5]) + output = ndimage.rank_filter(array, 1, size=[3]) + assert_array_almost_equal(array, output) + output = ndimage.percentile_filter(array, 50, size=3) + assert_array_almost_equal(array, output) + output = ndimage.median_filter(array, (3,)) + assert_array_almost_equal(array, output) + + def test_rank03(self): + array = np.array([3, 2, 5, 1, 4]) + output = ndimage.rank_filter(array, 1, size=[2]) + assert_array_almost_equal([3, 3, 5, 5, 4], output) + output = ndimage.percentile_filter(array, 100, size=2) + assert_array_almost_equal([3, 3, 5, 5, 4], output) + + def test_rank04(self): + array = np.array([3, 2, 5, 1, 4]) + expected = [3, 3, 2, 4, 4] + output = ndimage.rank_filter(array, 1, size=3) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 50, size=3) + assert_array_almost_equal(expected, output) + output = ndimage.median_filter(array, size=3) + assert_array_almost_equal(expected, output) + + def test_rank05(self): + array = np.array([3, 2, 5, 1, 4]) + expected = [3, 3, 2, 4, 4] + output = ndimage.rank_filter(array, -2, size=3) + assert_array_almost_equal(expected, output) + + def test_rank06(self): + array = np.array([[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]] + output = ndimage.rank_filter(array, 1, size=[2, 3]) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 17, size=(2, 3)) + assert_array_almost_equal(expected, output) + + def test_rank06_overlap(self): + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]]) + array_copy = array.copy() + expected = [[2, 2, 1, 1, 1], + [3, 3, 2, 1, 1], + [5, 5, 3, 3, 1]] + ndimage.rank_filter(array, 1, size=[2, 3], output=array) + assert_array_almost_equal(expected, array) + + ndimage.percentile_filter(array_copy, 17, size=(2, 3), + output=array_copy) + assert_array_almost_equal(expected, array_copy) + + def test_rank07(self): + array = np.array([[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]] + output = ndimage.rank_filter(array, -2, size=[2, 3]) + assert_array_almost_equal(expected, output) + + def test_rank08(self): + array = np.array([[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]] + output = ndimage.percentile_filter(array, 50.0, size=(2, 3)) + assert_array_almost_equal(expected, output) + output = ndimage.rank_filter(array, 3, size=(2, 3)) + assert_array_almost_equal(expected, output) + output = ndimage.median_filter(array, size=(2, 3)) + assert_array_almost_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): + expected = [[3, 3, 2, 4, 4], + [3, 5, 2, 5, 1], + [5, 5, 8, 3, 5]] + footprint = [[1, 0, 1], [0, 1, 0]] + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], 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): + array = np.array([[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]] + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.rank_filter(array, 0, footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 0.0, footprint=footprint) + assert_array_almost_equal(expected, output) + + def test_rank11(self): + array = np.array([[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]] + footprint = [[1, 0, 1], [1, 1, 0]] + output = ndimage.rank_filter(array, -1, footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 100.0, footprint=footprint) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank12(self, dtype): + expected = [[3, 3, 2, 4, 4], + [3, 5, 2, 5, 1], + [5, 5, 8, 3, 5]] + footprint = [[1, 0, 1], [0, 1, 0]] + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.percentile_filter(array, 50.0, + footprint=footprint) + assert_array_almost_equal(expected, output) + output = ndimage.median_filter(array, footprint=footprint) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank13(self, dtype): + expected = [[5, 2, 5, 1, 1], + [5, 8, 3, 5, 5], + [6, 6, 5, 5, 5]] + footprint = [[1, 0, 1], [0, 1, 0]] + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint, + origin=-1) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank14(self, dtype): + expected = [[3, 5, 2, 5, 1], + [5, 5, 8, 3, 5], + [5, 6, 6, 5, 5]] + footprint = [[1, 0, 1], [0, 1, 0]] + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + output = ndimage.rank_filter(array, 1, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_rank15(self, dtype): + expected = [[2, 3, 1, 4, 1], + [5, 3, 7, 1, 1], + [5, 5, 3, 3, 3]] + footprint = [[1, 0, 1], [0, 1, 0]] + array = np.array([[3, 2, 5, 1, 4], + [5, 8, 3, 7, 1], + [5, 6, 9, 3, 5]], dtype) + output = ndimage.rank_filter(array, 0, footprint=footprint, + origin=[-1, 0]) + assert_array_almost_equal(expected, output) + + @pytest.mark.parametrize('dtype', types) + def test_generic_filter1d01(self, dtype): + weights = np.array([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) + a.shape = (3, 4) + r1 = ndimage.correlate1d(a, weights / weights.sum(), 0, origin=-1) + r2 = ndimage.generic_filter1d( + a, _filter_func, 3, axis=0, origin=-1, + extra_arguments=(weights,), + extra_keywords={'total': weights.sum()}) + assert_array_almost_equal(r1, r2) + + @pytest.mark.parametrize('dtype', types) + def test_generic_filter01(self, dtype): + filter_ = np.array([[1.0, 2.0], [3.0, 4.0]]) + footprint = np.array([[1, 0], [0, 1]]) + cf = np.array([1., 4.]) + + def _filter_func(buffer, weights, total=1.0): + weights = cf / total + return (buffer * weights).sum() + + a = np.arange(12, dtype=dtype) + a.shape = (3, 4) + r1 = ndimage.correlate(a, filter_ * footprint) + if dtype in float_types: + r1 /= 5 + else: + r1 //= 5 + r2 = ndimage.generic_filter( + a, _filter_func, footprint=footprint, extra_arguments=(cf,), + extra_keywords={'total': cf.sum()}) + 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': cf.sum()}) + + @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): + array = np.array([1, 2, 3]) + weights = np.array([1, 0]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + assert_array_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): + array = np.array([1, 2, 3]) + weights = np.array([1, 0, 0, 0, 0, 0, 0, 0]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + assert_array_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): + array = np.array([1, 2, 3]) + weights = np.array([0, 0, 1]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + assert_array_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): + array = np.array([1, 2, 3]) + weights = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate1d(array, weights, 0, mode=mode, cval=0) + assert_array_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): + array = np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + weights = np.array([[1, 0], [0, 0]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_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): + array = np.array([[1, 2, 3], + [4, 5, 6], + [7, 8, 9]]) + weights = np.array([[0, 0, 0], [0, 0, 0], [0, 0, 1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_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): + array = np.array([1, 2, 3]) + weights = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_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): + array = np.array([[1], [2], [3]]) + weights = np.array([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_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): + array = np.array([1, 2, 3]) + weights = np.array([0, 0, 0, 0, 0, 0, 0, 0, 1]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_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): + array = np.array([[1], [2], [3]]) + weights = np.array([[0], [0], [0], [0], [0], [0], [0], [0], [1]]) + output = ndimage.correlate(array, weights, mode=mode, cval=0) + assert_array_equal(output, expected_value) + + +def test_ticket_701(): + # Test generic filter sizes + arr = np.arange(4).reshape((2, 2)) + def func(x): + return np.min(x) + 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) + 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_equal(out, [sigma]) + sigma = np.int64(1) + out = ndimage._ni_support._normalize_sequence(sigma, 1) + assert_equal(out, [sigma]) + # This worked before; make sure it still works + sigma = 1 + out = ndimage._ni_support._normalize_sequence(sigma, 1) + assert_equal(out, [sigma]) + # This worked before; make sure it still works + sigma = [1, 1] + out = ndimage._ni_support._normalize_sequence(sigma, 2) + assert_equal(out, sigma) + # Also include the OPs original example to make sure we fixed the issue + x = np.random.normal(size=(256, 256)) + perlin = np.zeros_like(x) + for i in 2**np.arange(6): + perlin += ndimage.gaussian_filter(x, i, mode="wrap") * i**2 + # This also fixes gh-4106, show that the OPs example now runs. + x = np.int64(21) + ndimage._ni_support._normalize_sequence(x, 0) + + +def test_gaussian_kernel1d(): + radius = 10 + sigma = 2 + sigma2 = sigma * sigma + x = np.arange(-radius, radius + 1, dtype=np.double) + phi_x = np.exp(-0.5 * x * x / sigma2) + phi_x /= phi_x.sum() + assert_allclose(phi_x, _gaussian_kernel1d(sigma, 0, radius)) + assert_allclose(-phi_x * x / sigma2, _gaussian_kernel1d(sigma, 1, radius)) + assert_allclose(phi_x * (x * x / sigma2 - 1) / sigma2, + _gaussian_kernel1d(sigma, 2, radius)) + assert_allclose(phi_x * (3 - x * x / sigma2) * x / (sigma2 * sigma2), + _gaussian_kernel1d(sigma, 3, radius)) + + +def test_orders_gauss(): + # Check order inputs to Gaussians + arr = np.zeros((1,)) + assert_equal(0, ndimage.gaussian_filter(arr, 1, order=0)) + assert_equal(0, ndimage.gaussian_filter(arr, 1, order=3)) + assert_raises(ValueError, ndimage.gaussian_filter, arr, 1, -1) + assert_equal(0, ndimage.gaussian_filter1d(arr, 1, axis=-1, order=0)) + assert_equal(0, ndimage.gaussian_filter1d(arr, 1, axis=-1, order=3)) + assert_raises(ValueError, ndimage.gaussian_filter1d, arr, 1, -1, -1) + + +def test_valid_origins(): + """Regression test for #1311.""" + def func(x): + return np.mean(x) + data = np.array([1, 2, 3, 4, 5], dtype=np.float64) + assert_raises(ValueError, ndimage.generic_filter, data, func, size=3, + origin=2) + assert_raises(ValueError, ndimage.generic_filter1d, data, func, + filter_size=3, origin=2) + assert_raises(ValueError, ndimage.percentile_filter, data, 0.2, size=3, + origin=2) + + for filter in [ndimage.uniform_filter, ndimage.minimum_filter, + ndimage.maximum_filter, ndimage.maximum_filter1d, + ndimage.median_filter, ndimage.minimum_filter1d]: + # This should work, since for size == 3, the valid range for origin is + # -1 to 1. + list(filter(data, 3, origin=-1)) + list(filter(data, 3, origin=1)) + # Just check this raises an error instead of silently accepting or + # segfaulting. + assert_raises(ValueError, filter, data, 3, origin=2) + + +def test_bad_convolve_and_correlate_origins(): + """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, + np.ones((3, 5)), np.ones((2, 2)), origin=[0, 1]) + + assert_raises(ValueError, ndimage.convolve1d, + np.arange(10), np.ones(3), origin=-2) + assert_raises(ValueError, ndimage.convolve, + np.arange(10), np.ones(3), origin=[-2]) + assert_raises(ValueError, ndimage.convolve, + np.ones((3, 5)), np.ones((2, 2)), origin=[0, -2]) + + +def test_multiple_modes(): + # Test that the filters with multiple mode cababilities for different + # dimensions give the same result as applying a single mode. + arr = np.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + mode1 = 'reflect' + mode2 = ['reflect', 'reflect'] + + assert_equal(ndimage.gaussian_filter(arr, 1, mode=mode1), + ndimage.gaussian_filter(arr, 1, mode=mode2)) + assert_equal(ndimage.prewitt(arr, mode=mode1), + ndimage.prewitt(arr, mode=mode2)) + assert_equal(ndimage.sobel(arr, mode=mode1), + ndimage.sobel(arr, mode=mode2)) + assert_equal(ndimage.laplace(arr, mode=mode1), + ndimage.laplace(arr, mode=mode2)) + assert_equal(ndimage.gaussian_laplace(arr, 1, mode=mode1), + ndimage.gaussian_laplace(arr, 1, mode=mode2)) + assert_equal(ndimage.maximum_filter(arr, size=5, mode=mode1), + ndimage.maximum_filter(arr, size=5, mode=mode2)) + assert_equal(ndimage.minimum_filter(arr, size=5, mode=mode1), + ndimage.minimum_filter(arr, size=5, mode=mode2)) + assert_equal(ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode1), + ndimage.gaussian_gradient_magnitude(arr, 1, mode=mode2)) + assert_equal(ndimage.uniform_filter(arr, 5, mode=mode1), + ndimage.uniform_filter(arr, 5, mode=mode2)) + + +def test_multiple_modes_sequentially(): + # Test that the filters with multiple mode cababilities for different + # dimensions give the same result as applying the filters with + # different modes sequentially + arr = np.array([[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]) + 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]) + 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]) + 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]) + assert_equal(expected, + ndimage.minimum_filter(arr, size=5, mode=modes)) + + +def test_multiple_modes_prewitt(): + # Test prewitt filter for multiple extrapolation modes + arr = np.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = np.array([[1., -3., 2.], + [1., -2., 1.], + [1., -1., 0.]]) + + modes = ['reflect', 'wrap'] + + assert_equal(expected, + ndimage.prewitt(arr, mode=modes)) + + +def test_multiple_modes_sobel(): + # Test sobel filter for multiple extrapolation modes + arr = np.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = np.array([[1., -4., 3.], + [2., -3., 1.], + [1., -1., 0.]]) + + modes = ['reflect', 'wrap'] + + assert_equal(expected, + ndimage.sobel(arr, mode=modes)) + + +def test_multiple_modes_laplace(): + # Test laplace filter for multiple extrapolation modes + arr = np.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = np.array([[-2., 2., 1.], + [-2., -3., 2.], + [1., 1., 0.]]) + + modes = ['reflect', 'wrap'] + + assert_equal(expected, + ndimage.laplace(arr, mode=modes)) + + +def test_multiple_modes_gaussian_laplace(): + # Test gaussian_laplace filter for multiple extrapolation modes + arr = np.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = np.array([[-0.28438687, 0.01559809, 0.19773499], + [-0.36630503, -0.20069774, 0.07483620], + [0.15849176, 0.18495566, 0.21934094]]) + + modes = ['reflect', 'wrap'] + + assert_almost_equal(expected, + ndimage.gaussian_laplace(arr, 1, mode=modes)) + + +def test_multiple_modes_gaussian_gradient_magnitude(): + # Test gaussian_gradient_magnitude filter for multiple + # extrapolation modes + arr = np.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = np.array([[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) + + +def test_multiple_modes_uniform(): + # Test uniform filter for multiple extrapolation modes + arr = np.array([[1., 0., 0.], + [1., 1., 0.], + [0., 0., 0.]]) + + expected = np.array([[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 test_gaussian_truncate(): + # 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), float) + arr[50, 50] = 1 + num_nonzeros_2 = (ndimage.gaussian_filter(arr, 5, truncate=2) > 0).sum() + assert_equal(num_nonzeros_2, 21**2) + num_nonzeros_5 = (ndimage.gaussian_filter(arr, 5, truncate=5) > 0).sum() + assert_equal(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 = fpos.any(axis=0).sum() + # n0 should be 2*int(2.5*3.5 + 0.5) + 1 + assert_equal(n0, 19) + n1 = fpos.any(axis=1).sum() + # n1 should be 2*int(0.5*3.5 + 0.5) + 1 + assert_equal(n1, 5) + + # Test gaussian_filter1d. + x = np.zeros(51) + x[25] = 1 + f = ndimage.gaussian_filter1d(x, sigma=2, truncate=3.5) + n = (f > 0).sum() + assert_equal(n, 15) + + # Test gaussian_laplace + y = ndimage.gaussian_laplace(x, sigma=2, truncate=3.5) + nonzero_indices = np.nonzero(y != 0)[0] + n = np.ptp(nonzero_indices) + 1 + assert_equal(n, 15) + + # Test gaussian_gradient_magnitude + y = ndimage.gaussian_gradient_magnitude(x, sigma=2, truncate=3.5) + nonzero_indices = np.nonzero(y != 0)[0] + n = np.ptp(nonzero_indices) + 1 + assert_equal(n, 15) + + +def test_gaussian_radius(): + # 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 + f1 = ndimage.gaussian_filter1d(x, sigma=2, truncate=1.5) + f2 = ndimage.gaussian_filter1d(x, sigma=2, radius=3) + assert_equal(f1, f2) + + # Test gaussian_filter when sigma is a number. + a = np.zeros((9, 9)) + a[4, 4] = 1 + f1 = ndimage.gaussian_filter(a, sigma=0.5, truncate=3.5) + f2 = ndimage.gaussian_filter(a, sigma=0.5, radius=2) + assert_equal(f1, f2) + + # Test gaussian_filter when sigma is a sequence. + a = np.zeros((50, 50)) + a[25, 25] = 1 + 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]) + assert_equal(f1, f2) + + +def test_gaussian_radius_invalid(): + # radius must be a nonnegative integer + with assert_raises(ValueError): + ndimage.gaussian_filter1d(np.zeros(8), sigma=1, radius=-1) + with assert_raises(ValueError): + ndimage.gaussian_filter1d(np.zeros(8), sigma=1, radius=1.1) + + +class TestThreading: + def check_func_thread(self, n, fun, args, out): + from threading import Thread + thrds = [Thread(target=fun, args=args, kwargs={'output': out[x]}) + for x in range(n)] + [t.start() for t in thrds] + [t.join() for t in thrds] + + def check_func_serial(self, n, fun, args, out): + for i in range(n): + fun(*args, output=out[i]) + + def test_correlate1d(self): + d = np.random.randn(5000) + os = np.empty((4, d.size)) + ot = np.empty_like(os) + k = np.arange(5) + self.check_func_serial(4, ndimage.correlate1d, (d, k), os) + self.check_func_thread(4, ndimage.correlate1d, (d, k), ot) + assert_array_equal(os, ot) + + def test_correlate(self): + d = np.random.randn(500, 500) + k = np.random.randn(10, 10) + os = np.empty([4] + list(d.shape)) + ot = np.empty_like(os) + self.check_func_serial(4, ndimage.correlate, (d, k), os) + self.check_func_thread(4, ndimage.correlate, (d, k), ot) + assert_array_equal(os, ot) + + def test_median_filter(self): + d = np.random.randn(500, 500) + os = np.empty([4] + list(d.shape)) + ot = np.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) + assert_array_equal(os, ot) + + def test_uniform_filter1d(self): + d = np.random.randn(5000) + os = np.empty((4, d.size)) + ot = np.empty_like(os) + self.check_func_serial(4, ndimage.uniform_filter1d, (d, 5), os) + self.check_func_thread(4, ndimage.uniform_filter1d, (d, 5), ot) + assert_array_equal(os, ot) + + def test_minmax_filter(self): + d = np.random.randn(500, 500) + os = np.empty([4] + list(d.shape)) + ot = np.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) + assert_array_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) + assert_array_equal(os, ot) + + +def test_minmaximum_filter1d(): + # Regression gh-3898 + in_ = np.arange(10) + out = ndimage.minimum_filter1d(in_, 1) + assert_equal(in_, out) + out = ndimage.maximum_filter1d(in_, 1) + assert_equal(in_, out) + # Test reflect + out = ndimage.minimum_filter1d(in_, 5, mode='reflect') + assert_equal([0, 0, 0, 1, 2, 3, 4, 5, 6, 7], out) + out = ndimage.maximum_filter1d(in_, 5, mode='reflect') + assert_equal([2, 3, 4, 5, 6, 7, 8, 9, 9, 9], out) + # Test constant + out = ndimage.minimum_filter1d(in_, 5, mode='constant', cval=-1) + assert_equal([-1, -1, 0, 1, 2, 3, 4, 5, -1, -1], out) + out = ndimage.maximum_filter1d(in_, 5, mode='constant', cval=10) + assert_equal([10, 10, 4, 5, 6, 7, 8, 9, 10, 10], out) + # Test nearest + out = ndimage.minimum_filter1d(in_, 5, mode='nearest') + assert_equal([0, 0, 0, 1, 2, 3, 4, 5, 6, 7], out) + out = ndimage.maximum_filter1d(in_, 5, mode='nearest') + assert_equal([2, 3, 4, 5, 6, 7, 8, 9, 9, 9], out) + # Test wrap + out = ndimage.minimum_filter1d(in_, 5, mode='wrap') + assert_equal([0, 0, 0, 1, 2, 3, 4, 5, 0, 0], out) + out = ndimage.maximum_filter1d(in_, 5, mode='wrap') + assert_equal([9, 9, 4, 5, 6, 7, 8, 9, 9, 9], out) + + +def test_uniform_filter1d_roundoff_errors(): + # gh-6930 + in_ = np.repeat([0, 1, 0], [9, 9, 9]) + for filter_size in range(3, 10): + out = ndimage.uniform_filter1d(in_, filter_size) + assert_equal(out.sum(), 10 - filter_size) + + +def test_footprint_all_zeros(): + # regression test for gh-6876: footprint of all zeros segfaults + arr = np.random.randint(0, 100, (100, 100)) + kernel = np.zeros((3, 3), bool) + with assert_raises(ValueError): + ndimage.maximum_filter(arr, footprint=kernel) + + +def test_gaussian_filter(): + # Test gaussian filter with np.float16 + # gh-8207 + data = np.array([1], dtype=np.float16) + sigma = 1.0 + with assert_raises(RuntimeError): + ndimage.gaussian_filter(data, sigma) + + +def test_rank_filter_noninteger_rank(): + # regression test for issue 9388: ValueError for + # non integer rank when performing rank_filter + arr = np.random.random((10, 20, 30)) + assert_raises(TypeError, ndimage.rank_filter, arr, 0.5, + footprint=np.ones((1, 1, 10), dtype=bool)) + + +def test_size_footprint_both_set(): + # test for input validation, expect user warning when + # size and footprint is set + with suppress_warnings() as sup: + sup.filter(UserWarning, + "ignoring size because footprint is set") + arr = np.random.random((10, 20, 30)) + ndimage.rank_filter(arr, 5, size=2, footprint=np.ones((1, 1, 10), dtype=bool)) + + +def test_byte_order_median(): + """Regression test for #413: median_filter does not handle bytes orders.""" + a = np.arange(9, dtype=' + +namespace torch { +namespace jit { + +TORCH_API void BatchMM(std::shared_ptr& graph); + +} +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/canonicalize_graph_fuser_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/canonicalize_graph_fuser_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..38ae569dbec31541b4ac032fb1637aead4e43204 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/canonicalize_graph_fuser_ops.h @@ -0,0 +1,11 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +TORCH_API void CanonicalizeOps(const std::shared_ptr& graph); + +} +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/clear_profiling.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/clear_profiling.h new file mode 100644 index 0000000000000000000000000000000000000000..7dee9bdb52ad6c460366953f696480140f219fb6 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/clear_profiling.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace torch { +namespace jit { + +TORCH_API void unprofileGraphInputs(const std::shared_ptr& graph); +TORCH_API void unprofileBlock(Block* start_block); +// Unprofiles all the node outputs in a block. + +TORCH_API void ClearProfilingInformation(const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/concat_opt.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/concat_opt.h new file mode 100644 index 0000000000000000000000000000000000000000..4fdd86f36a46dd0c1be0c53f1731c8e686ba1796 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/concat_opt.h @@ -0,0 +1,19 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Eliminates common inputs among `aten::cat` ops. +TORCH_API bool EliminateConcatCommonInputs(const std::shared_ptr& graph); + +// Expands `aten::cat` ops into `aten::copy` ops and eliminates redudancies +// in the buffers used for concatenation if possible. +TORCH_API void ExpandConcatAndEliminateRedundancy( + const std::shared_ptr& graph); + +TORCH_API bool CombineConcats(const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_propagation.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_propagation.h new file mode 100644 index 0000000000000000000000000000000000000000..62293c8d7abc9bc2344ccab38d3a30c18af2fe9d --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/constant_propagation.h @@ -0,0 +1,32 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Runs constant propagation on all objects unless ignore_custom_classes is +// specified as true, in which case user defined classes are skipped. This is +// useful to prevent early fusion of packing operations, which end up lowering +// away information about their constructors (e.g. packed::linear_clamp_prepack +// and prepacked::conv2d_clamp_prepack) +// Returns True if the pass made a change to the graph +TORCH_API bool ConstantPropagation( + std::shared_ptr& graph, + bool ignore_custom_classes = false); + +// runs constant propagation only on ops that have non-aliasing inputs & outputs +// Returns True if the pass made a change to the graph +TORCH_API bool ConstantPropagationImmutableTypes(std::shared_ptr& graph); + +// Runs the node if its inputs are constants. Callers of this function must +// make their own determination if constant prop is appropriate - for example +// non-deterministic ops or ops with side effects. If ignore_custom_classes is +// specified, nodes that output user defined classes are not run. +TORCH_API c10::optional runNodeIfInputsAreConstant( + const Node* node, + bool ignore_custom_classes = false, + AliasDb* db = nullptr); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_autodiff_subgraphs.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_autodiff_subgraphs.h new file mode 100644 index 0000000000000000000000000000000000000000..481b2aa352107bc74f776b7bcd3bb24251b80c0b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_autodiff_subgraphs.h @@ -0,0 +1,19 @@ +#pragma once + +#include +#include + +#include + +namespace torch { +namespace jit { + +// insert GraphExecutor nodes that group together +// subgraphs that are differentiable by the jit's autodiff passes +// threshold - minimum number of nodes that will appear in a block +// returns all differentiable blocks that have been found +TORCH_API std::vector CreateAutodiffSubgraphs( + const std::shared_ptr& graph, + size_t threshold = 2); +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_functional_graphs.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_functional_graphs.h new file mode 100644 index 0000000000000000000000000000000000000000..351816394d80c694d30a2423d8774d3585318af9 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/create_functional_graphs.h @@ -0,0 +1,14 @@ +#pragma once + +#include +#include + +namespace torch { +namespace jit { + +TORCH_API void CreateFunctionalGraphs(const std::shared_ptr& graph); + +TORCH_API void InlineFunctionalGraphs(const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dead_code_elimination.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dead_code_elimination.h new file mode 100644 index 0000000000000000000000000000000000000000..780c11f95a9bb9dcaa4fd07aec92409d0f2cd527 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/dead_code_elimination.h @@ -0,0 +1,42 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// If given a top-level graph, DCE will construct do alias analysis that allows +// for "smarter" dead code elimination (we will eliminate mutable ops if we can +// prove the mutated values are not used). Otherwise, we will not allow DCE to +// eliminate mutable ops. +// +// So, prefer to use the graph version if you can. +enum class DCESideEffectPolicy : uint8_t { + // default behavior: dead code elimination will check if a node has side + // effects + // and not delete it if it does. + DONT_DELETE_NODES_WITH_SIDE_EFFECTS, + // with this flag, dead code elimination will not check if a node has side + // effects and treat nodes with side effects like any other node, + // i.e. delete them if their outputs aren't used anywhere. + ALLOW_DELETING_NODES_WITH_SIDE_EFFECTS +}; + +TORCH_API void EliminateDeadCode( + const std::shared_ptr& graph, + DCESideEffectPolicy sideEffectPolicy = + DCESideEffectPolicy::DONT_DELETE_NODES_WITH_SIDE_EFFECTS); +TORCH_API void EliminateDeadCode( + Block* block, + bool recurse = true, + DCESideEffectPolicy sideEffectPolicy = + DCESideEffectPolicy::DONT_DELETE_NODES_WITH_SIDE_EFFECTS); + +// Invoke the user-provided callback on all live values before deleting anything +TORCH_API void EliminateDeadCode( + Block* block, + std::function&)> cb, + DCESideEffectPolicy sideEffectPolicy = + DCESideEffectPolicy::DONT_DELETE_NODES_WITH_SIDE_EFFECTS); +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/decompose_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/decompose_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..400e5997d6368d08edfacc76c969c07828a2c17b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/decompose_ops.h @@ -0,0 +1,11 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +TORCH_API void DecomposeOps(std::shared_ptr& graph); + +} +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/eliminate_no_ops.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/eliminate_no_ops.h new file mode 100644 index 0000000000000000000000000000000000000000..0087d306c23bc9b4580d669ec8009ec8b83b9e79 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/eliminate_no_ops.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Remove ops that do nothing on the forward pass (like aten::detach). +// This pass is invoked as a part of freeze_module. +// This function also takes a set of custom ops to eliminate. All ops in this +// set must take their output as their first input, i.e. x = f(x, ...) +TORCH_API bool EliminateNoOps( + std::shared_ptr& graph, + std::unordered_set custom_ops = {}); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/erase_number_types.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/erase_number_types.h new file mode 100644 index 0000000000000000000000000000000000000000..4aef1f5570694d20141ecc2e04a37eaf2ef0d3b6 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/erase_number_types.h @@ -0,0 +1,23 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Erase NumberType information. This is necessary for and only used in +// exporting to ONNX. This pass ensures that no remaining Values have +// NumberType types, replacing them with tensors. +// The following things are done to erase NumberType info: +// - NumberType outputs are changed to DynamicType. +// - prim::Constant nodes which are numbers get changed into 0-dim tensors of +// the corresponding type +// - prim::TensorToNum, aten::Float, aten::Int and prim::NumToTensor nodes +// are erased. +// +// The pass assumes that DCE will be called sometime after. +TORCH_API void EraseNumberTypes(const std::shared_ptr& graph); +TORCH_API void EraseNumberTypesOnBlock(Block* block); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fixup_trace_scope_blocks.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fixup_trace_scope_blocks.h new file mode 100644 index 0000000000000000000000000000000000000000..472d95843a1c6dc921b072b59ea013fcbb6d57ed --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fixup_trace_scope_blocks.h @@ -0,0 +1,47 @@ +#pragma once + +#include +#include + +namespace torch { +namespace jit { + +// Directly after tracing, we have an ill-formed graph with blocks inserted. +// Example: +// +// graph(%self : ClassType, +// %input.1 : Float(3, 4)): +// %1 : ClassType = prim::GetAttr[name="relu1"](%self) +// %2 : ClassType = prim::GetAttr[name="relu2"](%self) +// %3 : ClassType = prim::GetAttr[name="rrr"](%2) +// = prim::TracedModuleForward[scope="__module.relu1"]() +// block0(): +// %input : Float(3, 4) = aten::relu(%input.1), +// -> () +// = prim::TracedModuleForward[scope="__module.relu2"](), +// block0(): +// = prim::TracedModuleForward[scope="__module.relu2.rrr"](), +// block0(): +// %6 : Float(3, 4) = aten::relu(%input), +// -> () +// -> () +// return (%6) +// +// In this pass, we: +// 1) Lift Value defs to as high of a scope as needed to ensure that +// they dominate all their uses. For example, `input` in the above +// graph needs to be lifted to the top-level block so that its use +// in the second `relu` operator is dominated. +// 2) Lambda lift the blocks. This ensures that all values used within +// each scope have their defs captured. +// 3) Convert the scope blocks into methods on their respective Modules, +// and convert TracedModuleForward nodes to CallMethod nodes into those +// methods. +// +// Then, we'll have a well-formed graph with proper method calls. +TORCH_API void FixupTraceScopeBlocks( + std::shared_ptr& graph, + Module* self); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fold_conv_bn.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fold_conv_bn.h new file mode 100644 index 0000000000000000000000000000000000000000..4032d22f2bc13f667cec5025148879cd7117cf83 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fold_conv_bn.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +/** \brief Fold Conv2d-BatchNorm2d into Conv2d in all methods of this + * module and all its submodules, forward is included by default. + * + * The weight and bias of the Conv2d are correspondingly updated. Should only be + * used on modules in eval mode. + */ +TORCH_API Module FoldConvBatchNorm(const Module& module); + +struct TORCH_API ConvBNParameters { + at::Tensor conv_w; + at::Tensor conv_b; + at::Tensor bn_rm; + at::Tensor bn_rv; + double bn_eps = 0.0; + at::Tensor bn_w; + at::Tensor bn_b; +}; + +/** + * Given the current weight and bias tensors of a Conv module and parameters + * of the BatchNorm module we're folding with, compute the updated values + * for the weight and bias. + * + * The function is basically copied from torch/nn/utils/fusion.py + */ +TORCH_API std::tuple computeUpdatedConvWeightAndBias( + const ConvBNParameters& p); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_concat_linear.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_concat_linear.h new file mode 100644 index 0000000000000000000000000000000000000000..d64cda0a88f2bbc0ebe585bf8b63e5bd94744743 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_concat_linear.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Concats multiple linear ops with the same Tensor input +// into a single linear op. +TORCH_API bool FrozenConcatLinear(std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_conv_add_relu_fusion.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_conv_add_relu_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..95991e73d9eccf7473071c5ed352af56d7c114f3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_conv_add_relu_fusion.h @@ -0,0 +1,15 @@ +#pragma once + +#include +#include + +namespace torch { +namespace jit { + +TORCH_API extern std::function&)>& +getFuseFrozenConvAddReluImpl(); + +TORCH_API void FuseFrozenConvAddRelu(std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_folding.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_folding.h new file mode 100644 index 0000000000000000000000000000000000000000..bac4bedd53a6bb45999d5d276986d0946e1a2f0b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_folding.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Fuses Linear -> BatchNormNd into a single Linear by +// folding batchnorm weights into linear weights. +// This pass only works on Frozen Graphs; otherwise it is a No-Op. +TORCH_API bool FoldFrozenLinearBatchnorm(std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_transpose.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_transpose.h new file mode 100644 index 0000000000000000000000000000000000000000..e952d1c43cef39020405de944bba8b3856398ed3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_linear_transpose.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Transposes the weight matrix for frozen linear modules. +// and converts it into a matmul +TORCH_API bool FrozenLinearTranspose(std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_ops_to_mkldnn.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_ops_to_mkldnn.h new file mode 100644 index 0000000000000000000000000000000000000000..d6ffc36906ad7e51b3fb1bc940cac69e8fb1b433 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/frozen_ops_to_mkldnn.h @@ -0,0 +1,15 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Converts operators & their parameters to mkldnn if it is profitable +// Currently encompassing Conv2d and Conv3d, and Linear +// Op must be in float32 and mkldnn must be built +// This pass only works on frozen graph +TORCH_API void ConvertFrozenOpsToMKLDNN(std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fuse_linear.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fuse_linear.h new file mode 100644 index 0000000000000000000000000000000000000000..56d37518e37866fa4ee14242215e5079c9c30f4b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/fuse_linear.h @@ -0,0 +1,24 @@ +/** \brief Fusing linear patterns as single at::linear for easier pattern + * matching in later passes + */ +#pragma once + +#include + +namespace torch { +namespace jit { + +/** \brief Match the at::linear pattern and fuse it into a single at::linear + * This pass fuse the addmm or matmul + add generated by JIT back to linear + * This pass can be deleted once the JIT can emit the aten::linear in the future + */ +TORCH_API void FuseLinear(std::shared_ptr& graph); + +/** Swap functional linear CallFunctions to aten::linear + */ +TORCH_API void SwapFunctionalLinear(std::shared_ptr& graph); +/** Swap all functional linear CallFunctions in module + */ +TORCH_API void SwapFunctionalLinear(Module& module); +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_fuser.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_fuser.h new file mode 100644 index 0000000000000000000000000000000000000000..aafb442eafb6f5e1b1e506c06627e9e9a03a5eed --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_fuser.h @@ -0,0 +1,37 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +TORCH_API bool canFuseOnCPULegacy(); +TORCH_API void overrideCanFuseOnCPULegacy(bool value); + +// NB: Be sure to run DCE before fusion, because dead instructions +// can prevent fusion opportunities from being exploited. +// On Windows will noop, NYI +TORCH_API void FuseGraph( + std::shared_ptr& graph, + bool strict_fuser_check = false); + +// \brief Custom fusion pass using a node-level callback to +// determine the inclusion of nodes in a subgraph. +// +// This helper omits aliased inputs and fusion across control flow +// boundaries. +// +// \arg graph The graph to be modified in-place +// \arg is_fusable A callback run on each fusable node in the graph. +// \arg kind The label given to the resultant fused subgraph +// \arg arg_limit The maximum number of args the resultant fused subgraph +// should have. Note: This will likely develop into a general +// post condition on the fused subgraph. +TORCH_API void CustomFuseGraph( + std::shared_ptr& graph, + const std::function& is_fusable, + Symbol kind, + size_t arg_limit = std::numeric_limits::max()); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_rewrite_helper.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_rewrite_helper.h new file mode 100644 index 0000000000000000000000000000000000000000..0920830babb8b326e994339e8c479593091d36cb --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/graph_rewrite_helper.h @@ -0,0 +1,54 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch { +namespace jit { +namespace graph_rewrite_helper { + +std::string getFuncName(Value* func_value); +Value* getValue( + const std::string& name, + const std::unordered_map& match_vmap, + const std::unordered_map& vmap); +c10::optional getIValue( + const std::string& name, + const std::unordered_map& match_vmap, + const std::unordered_map& vmap); +TORCH_API void replaceConvolutionWithAtenConv(std::shared_ptr& graph); + +bool isClampFusable( + const Match& match, + const std::unordered_map& vmap); + +// This struct contains a compiled IR patterns slated for use in the +// findPatternMatches function. The struct encapsulates the common +// information from parseIR that is used in conjunction with the +// pattern matching facility. A const instance of this struct can +// also be stored away to cache the compiled IR pattern and reduce +// runtime cost +struct PatternInfo { + std::string pattern_string; + std::unique_ptr pattern_graph; + std::unordered_map vmap; + std::vector filters; + + static PatternInfo parse_from_str( + std::string pattern_string, + const std::vector& filters = {}) { + PatternInfo rv{ + std::move(pattern_string), + std::make_unique(), + decltype(vmap){}, + filters}; + parseIR(rv.pattern_string, rv.pattern_graph.get(), rv.vmap); + return rv; + } +}; + +} // namespace graph_rewrite_helper +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/hoist_conv_packed_params.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/hoist_conv_packed_params.h new file mode 100644 index 0000000000000000000000000000000000000000..37bfa07a1267023bcd6d2227b03dac75d0f233b1 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/hoist_conv_packed_params.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +namespace torch { +namespace jit { + +void HoistConvPackedParams(script::Module& m); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_fork_wait.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_fork_wait.h new file mode 100644 index 0000000000000000000000000000000000000000..c2dbacdc4ddab7a18f495cfc9f8dc34640f65902 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inline_fork_wait.h @@ -0,0 +1,16 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Inline Fork and Wait calls. This is used, for example, in ONNX export, where +// we do not support the explicit parallelism structures and would rather +// just have a flat graph. This inlines the forked section in the fork() +// callsite and replaces uses of the result of wait() calls with the values +// produced from the (now-inlined) forked section. +TORCH_API void InlineForkWait(const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inliner.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inliner.h new file mode 100644 index 0000000000000000000000000000000000000000..b4db0ad189282d83a2e184993e1c790a41527bf3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/inliner.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Inline function and method calls. +TORCH_API void Inline(Graph& graph); + +TORCH_API GraphFunction* tryToGraphFunction(Node* n); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/insert_guards.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/insert_guards.h new file mode 100644 index 0000000000000000000000000000000000000000..28d9f168bf3d559ad434883954004797ae96e690 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/insert_guards.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace torch { +namespace jit { + +TORCH_API void InsertGuards(std::shared_ptr graph); + +TORCH_API void RemoveProfilingNodes(const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lift_closures.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lift_closures.h new file mode 100644 index 0000000000000000000000000000000000000000..c7cee8417fa457d671da2efbc6a19493762fcffb --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lift_closures.h @@ -0,0 +1,12 @@ +#pragma once + +#include +#include + +namespace torch { +namespace jit { + +TORCH_API void liftClosures(const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/liveness.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/liveness.h new file mode 100644 index 0000000000000000000000000000000000000000..7b612dee9622304b5f9279215da7c798b5958b4b --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/liveness.h @@ -0,0 +1,23 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +namespace torch { +namespace jit { + +using SparseBitVector = ::c10::SparseBitVector<256>; + +// BuildLivenessSets computes "bailout" liveness which is equivalent to +// "{LIVE_IN} or {GEN}" or "{LIVE_OUT} - {KILL}" +TORCH_API std::unordered_map> BuildLivenessSets( + std::shared_ptr graph); +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_grad_of.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_grad_of.h new file mode 100644 index 0000000000000000000000000000000000000000..a79bb56492855b6a9002fe82f9c7b9856092af51 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_grad_of.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// This pass removes 'grad_of' nodes, replacing them with conditionals of +// the form: +// if any_defined(inputs): +// outputs = +// else: +// outputs = undefineds +TORCH_API void LowerGradOf(Graph& g); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_graph.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_graph.h new file mode 100644 index 0000000000000000000000000000000000000000..6c9ea6666835a26e39ddf82830d1c43b7cd45748 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_graph.h @@ -0,0 +1,22 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +using ModulePtr = c10::intrusive_ptr; + +// Given a graph with of a method which first argument is %self, lower it to a +// graph where all attributes accesses are replaced with explicit inputs of the +// graph (rather than results of prim::GetAttr executed on %self). +// +// Returns a tuple (graph, parameters) where the last module.parameters.size() +// inputs to the graph are the trainable parameters used in this method. The +// remaining inputs are the true inputs to the function. +TORCH_API std::pair, std::vector> LowerGraph( + Graph& graph, + const ModulePtr& self); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_tuples.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_tuples.h new file mode 100644 index 0000000000000000000000000000000000000000..3ac9127b29fb084bb0c1d01d7684ac429e176453 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/lower_tuples.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// removes tuples where TupleConstruct and TupleUnpack are matched +// but leaves tuples in place across if statements, loops, and as inputs/outputs +TORCH_API void LowerSimpleTuples(const std::shared_ptr& graph); + +// removes _all_ tuples and raises an error if some cannot be removed +// this is used by ONNX to ensure there are not tuples before conversion, +// but will not work on graphs whose inputs contain tuples. +TORCH_API void LowerAllTuples(const std::shared_ptr& graph); + +TORCH_API void LowerSimpleTuples(Block* block); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mobile_optimizer_type.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mobile_optimizer_type.h new file mode 100644 index 0000000000000000000000000000000000000000..d11f288dca343308bf2167c89a3d6b2d0792a569 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/mobile_optimizer_type.h @@ -0,0 +1,13 @@ +#pragma once + +#include + +enum class MobileOptimizerType : int8_t { + CONV_BN_FUSION, + INSERT_FOLD_PREPACK_OPS, + REMOVE_DROPOUT, + FUSE_ADD_RELU, + HOIST_CONV_PACKED_PARAMS, + CONV_1D_TO_2D, + VULKAN_AUTOMATIC_GPU_TRANSFER, +}; diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onednn_graph_fuser.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onednn_graph_fuser.h new file mode 100644 index 0000000000000000000000000000000000000000..aeb79470b01ae60e38282b4d29b6942af4189ac5 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onednn_graph_fuser.h @@ -0,0 +1,64 @@ +#pragma once + +#include +#include + +#include + +namespace torch { +namespace jit { +namespace fuser { +namespace onednn { + +static std::atomic onednn_enabled{true}; + +static std::atomic& getLlgaEnabled() { + return onednn_enabled; +} + +TORCH_API void fuseGraph(std::shared_ptr& g); + +} // namespace onednn +} // namespace fuser + +struct C10_EXPORT RegisterLlgaFuseGraph + : public PassManager { + static bool setEnabled(bool enabled) { + TORCH_CHECK( + AT_MKLDNN_ENABLED(), + "Running oneDNN Graph fuser is only supported with MKLDNN builds."); + bool oldState = fuser::onednn::getLlgaEnabled(); + fuser::onednn::getLlgaEnabled() = enabled; + if (enabled) { + registerPass(fuser::onednn::fuseGraph); + } else { + clearPass(); + } + return oldState; + } + + static bool isEnabled() { + return fuser::onednn::getLlgaEnabled(); + } + + // override PassManager::registerPass to register pre-pass + static bool registerPass(GraphPass p) { + if (!isRegistered()) { + passID(registerPrePass(std::move(p)), true); + isRegistered(true); + return false; + } + return true; + } + + // override PassManager::clearPass to clear pre-pass + static void clearPass() { + if (isRegistered()) { + clearPrePass(passID()); + isRegistered(true); + } + } +}; + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx.h new file mode 100644 index 0000000000000000000000000000000000000000..11bee679164043cca58fd3f35a108fd078101a95 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/onnx.h @@ -0,0 +1,28 @@ +#pragma once + +#include +#include +#include + +namespace torch { +namespace jit { + +TORCH_API std::shared_ptr ToONNX( + std::shared_ptr& state, + ::torch::onnx::OperatorExportTypes operator_export_type); +TORCH_API std::unordered_map BlockToONNX( + Block* old_block, + Block* new_block, + ::torch::onnx::OperatorExportTypes operator_export_type, + std::unordered_map& env, + bool is_sub_block = false); +TORCH_API void NodeToONNX( + Node* old_node, + Block* new_block, + ::torch::onnx::OperatorExportTypes operator_export_type, + std::unordered_map& env); +TORCH_API void RemovePrintOps(std::shared_ptr& graph); +TORCH_API void PreprocessCaffe2Ops(std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole.h new file mode 100644 index 0000000000000000000000000000000000000000..e2d8d5f9a9f2082fe0eb94bb5aee4a7605dc7042 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// return true if graph is modified +TORCH_API bool PeepholeOptimize( + const std::shared_ptr& graph, + bool disable_shape_peepholes = false); +// return true if graph is modified +TORCH_API bool PeepholeOptimize( + Block* block, + bool disable_shape_peepholes = false); +// return true if graph is modified +TORCH_API bool FuseAddMM(const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_alias_sensitive.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_alias_sensitive.h new file mode 100644 index 0000000000000000000000000000000000000000..d61a0a4ec0d8be8e1c3e49e352b288a4767b9ed0 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_alias_sensitive.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Peephole Optimizes alias sensitive peepholes +// Currently this is invoked as part of PeepholeOptimize +// return true if graph is modified +// Optimizes on TensorType if shape_peepholes is true +TORCH_API bool PeepholeOptimizeAliasSensitive( + const std::shared_ptr& graph, + bool shape_peepholes); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_dict_idioms.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_dict_idioms.h new file mode 100644 index 0000000000000000000000000000000000000000..283c313d9ee2ae8024ba286d1a5bd0ea5cf1fdd3 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_dict_idioms.h @@ -0,0 +1,38 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Peephole Optimizes Dict Ops such as len() and __getitem__ +// 1. getitem optimizations +// Given a function like this: +// def foo(): +// d = {0 : 1} +// x = d[0] +// return x +// This pass produces (after dead code elimination): +// def foo(a, b): +// return 1 +// +// This optimization can only happen if the dict is not modified +// and the dict has constant, non overlapping keys. +// +// 2. len optimizations +// Given a function like this: +// def foo(): +// d = {0 : 1} +// return len(d) +// This pass produces (after dead code elimination): +// def foo(): +// return 1 +// +// This has the same requirements as the getitem optimizations. +// +// Currently this is invoked as part of PeepholeOptimize +// return true if graph is modified. +TORCH_API bool PeepholeOptimizeDictIdioms(const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_list_idioms.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_list_idioms.h new file mode 100644 index 0000000000000000000000000000000000000000..d20df9571db01e0e0a0a3991b410621bfcb346ba --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_list_idioms.h @@ -0,0 +1,72 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Peephole Optimizes List ops such as len(li) and li[1]. +// 1. Construct/Unpack optimizations +// Given a function like this: +// def foo(a, b): +// li = [a, b] +// x, y = li +// return x, y +// This pass produces (after dead code elimination): +// def foo(a, b): +// return a, b +// +// This is only applied to lists that are not modified. +// +// 2. getitem optimizations +// Given a function like this: +// def foo(a, b): +// li = [a, b] +// x = li[0] +// return x +// This pass produces (after dead code elimination): +// def foo(a, b): +// return a +// +// This optimization can only happen if the list is not modified. +// +// 3. len optimizations +// Given a function like this: +// def foo(): +// li = [1, 2] +// return len(li) +// This pass produces (after dead code elimination): +// def foo(): +// return 2 +// +// This has the same requirements as the getitem optimizations. +// +// 4. ListConstruct + ListConstruct +// Given a function like this: +// def foo(): +// return [1, 2] + [3, 4] +// This pass produces (after dead code elimination): +// def foo(): +// return [1, 2, 3, 4] +// +// This is only applied to lists that are not modified. +// +// 5. Slice +// Given a function like this: +// def foo(): +// return [1, 2, 3, 4, 5][0:2] +// This pass produces (after deadcode elimination): +// def foo(): +// return [1, 2] +// +// Currently this is invoked as part of PeepholeOptimize +// return true if graph is modified. +// If `refine_list_len` is true will attempt to refine the len of lists through +// len comparisons and assertions. This does not generally optimize pytorch +// programs so it is not called by default in PeepholeOptimize. +TORCH_API bool PeepholeOptimizeListIdioms( + const std::shared_ptr& graph, + bool refine_list_len = false); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_non_tensor.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_non_tensor.h new file mode 100644 index 0000000000000000000000000000000000000000..1e4daebd060cc9365c8994219803a65891c69d4e --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/peephole_non_tensor.h @@ -0,0 +1,14 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// return true if graph is modified +// Optimizing General Graph Patterns that +// are not covered in peephole.cpp and peephole_list_idioms +TORCH_API bool PeepholeOptimizeNonTensor(const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_exceptions.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_exceptions.h new file mode 100644 index 0000000000000000000000000000000000000000..e029383379f5658208a1f5806710bba7d47ce6b1 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_exceptions.h @@ -0,0 +1,23 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Considering prim::RaiseException nodes unreachable, simplify prim::If nodes +// when one of the branches contains prim::RaiseException. +// +// This pass is illegal in general case as the modified graph might not throw +// an exception that the original graph would throw. The purpose of the pass is +// to cleanup the graph in a "risky" way by removing pathways leading to +// RaiseExceptions nodes. In some sense, this pass could be considered as a +// "Release" mode, while the original graph was in a "Debug" mode. +// The pass should only be used when such transformation is guaranteed to be +// safe by some other mechanisms. For instance, when we know exact shapes of +// tensors flowing through the graph and tensors with such shapes never cause +// exceptions. +TORCH_API void EliminateExceptions(std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_mutation.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_mutation.h new file mode 100644 index 0000000000000000000000000000000000000000..eb8cf195ee4ca19ce399435e8586d4eecb8b3397 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_mutation.h @@ -0,0 +1,81 @@ +#pragma once + +#include +#include +#include +#include + +namespace torch { +namespace jit { + +struct TORCH_API MutationRemover { + MutationRemover( + std::shared_ptr graph, + c10::optional> mutation_filter = c10::nullopt) + : mutation_filter_(mutation_filter), + aliasDb_(nullptr), + graph_(std::move(graph)) {} + + // return true if graph is modified + bool removeListMutation(); + + // return true if graph is modified + bool removeTensorMutation(); + + bool isSpecialMappedOp(Node* n) { + return n->matches("aten::zero_(Tensor(a!) self) -> Tensor(a!)") || + n->matches( + "aten::fill_.Scalar(Tensor(a!) self, Scalar value) -> Tensor(a!)") || + n->matches( + "aten::normal_(Tensor(a!) self, float mean=0, float std=1, *, Generator? generator=None) -> Tensor(a!)"); + } + + bool inplaceOpVariant(Node* n); + + static bool hasSideEffectOrAlias(Value* v, AliasDb* aliasDb); + + private: + Node* createSpecialMappedOp(Node* n); + bool listMutationFollowingListConstruct(Node* n); + bool tryMakeCreationAndMutationAtomic( + Value* mutated_value, + Node* mutating_op); + bool tryMakeUnaliasedIfOutputAndMutationAtomic( + Value* mutated_value, + Node* mutating_op); + // return true if graph is modified + bool RemoveListMutation(Block* block); + // return true if graph is modified + bool RemoveTensorMutation(Block* block); + + AliasDb* getOrCreateAliasDb() { + if (!aliasDb_) { + aliasDb_ = std::make_unique(graph_); + } + return aliasDb_.get(); + } + + c10::optional> mutation_filter_; + std::unique_ptr aliasDb_ = nullptr; + std::shared_ptr graph_; +}; + +// Removes list mutation with functional equivalents +// return true if graph is modified +TORCH_API bool RemoveListMutation(const std::shared_ptr& graph); + +// Replaces in-place aten ops with their functional equivalents +// when it can be proven that this does not change graph semantics +// if `mutation_filter` is present, the pass will only attempt to +// remove mutation on nodes which return true for the filter +// return true if graph is modified +TORCH_API bool RemoveTensorMutation( + const std::shared_ptr& graph, + c10::optional> mutation_filter = c10::nullopt); + +// Replaces in-place aten activation ops with their functional equivalence +TORCH_API bool InplaceToFunctionalActivation( + const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_redundant_profiles.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_redundant_profiles.h new file mode 100644 index 0000000000000000000000000000000000000000..b574786c0bb1cf1269816edec2ef5d13980bd5e8 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/remove_redundant_profiles.h @@ -0,0 +1,11 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +TORCH_API void RemoveRedundantProfiles(std::shared_ptr& graph); +TORCH_API void RemoveRedundantProfiles(Block* block, AliasDb& db); +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/requires_grad_analysis.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/requires_grad_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..c7b80423dc5eafd88eb8f22255e472fda0d954ab --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/requires_grad_analysis.h @@ -0,0 +1,16 @@ +#pragma once + +#include + +#include + +namespace torch { +namespace jit { + +struct Graph; +struct ArgumentSpec; + +TORCH_API void PropagateRequiresGrad(std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/restore_mutation.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/restore_mutation.h new file mode 100644 index 0000000000000000000000000000000000000000..48ce9fdb9ed208441959974b015026bda98f7f06 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/restore_mutation.h @@ -0,0 +1,63 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace torch { +namespace jit { + +// A map which stores if an activation operator can perform type promotion +const std::unordered_map activation_type_promotion_mapping = { + {aten::sigmoid, true}, + {aten::tanh, true}, + {aten::celu, false}, + {aten::elu, false}, + {aten::gelu, false}, + {aten::glu, false}, + {aten::hardshrink, false}, + {aten::hardsigmoid, false}, + {aten::hardswish, false}, + {aten::hardtanh, false}, + {aten::leaky_relu, false}, + {aten::prelu, false}, + {aten::relu6, false}, + {aten::relu, false}, + {aten::rrelu, false}, + {aten::selu, false}, + {aten::silu, false}}; + +class FunctionalToInplaceRewriter { + public: + FunctionalToInplaceRewriter(std::shared_ptr graph); + + bool FunctionalToInplace(Block* block); + + private: + AliasDb* getOrCreateAliasDb() { + if (!aliasDb_) { + aliasDb_ = std::make_unique(graph_); + } + return aliasDb_.get(); + } + + bool CanBeInplace(Node* node); + + std::unique_ptr aliasDb_ = nullptr; + std::shared_ptr graph_; +}; + +// A common application scenario is to apply InplaceToFunctionalActivation +// before some JIT optimization passes, so that those passes are less +// constrained by in-place ops. After those passes are done, we can call +// FunctionalToInplaceActivation to recover in-place activation ops, +// so that we won't lose the performance benefit coming from memory reduction. + +// Replaces functional aten activation ops with their in-place equivalents +TORCH_API bool FunctionalToInplaceActivation( + const std::shared_ptr& graph); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/shape_analysis.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/shape_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..670072a0b09b45337cd8bd80eb5bd9e12ee7f0dc --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/shape_analysis.h @@ -0,0 +1,43 @@ +#pragma once + +#include +#include +#include + +namespace torch { +namespace jit { + +struct Graph; + +struct propagation_error : std::exception {}; + +class PropertyPropBase { + // Used for both Shape Propagation and Dtype/Device Propagation + public: + explicit PropertyPropBase(std::shared_ptr graph) + : graph_(std::move(graph)) {} + virtual ~PropertyPropBase() = default; + + void propagateBlock(Block* block, bool insert_expands = true); + // insert_expands is used for shape inference + + void processIf(Node* node); + void processLoop(Node* node); + + protected: + virtual void propagateNode(Node* node, bool insert_expands = true) = 0; + void setUnshapedType(Value* o); + void setUnshapedType(Node* node); + std::shared_ptr graph_; +}; + +TORCH_API void EraseShapeInformation(const std::shared_ptr& graph); +TORCH_API void PropagateInputShapes(const std::shared_ptr& graph); + +TORCH_API bool mergeTypes( + ArrayRef lhs, + ArrayRef rhs, + ArrayRef outputs); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/subgraph_rewrite.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/subgraph_rewrite.h new file mode 100644 index 0000000000000000000000000000000000000000..d932c0c1f74fa73b14e8d041a55e8a82d33bdd62 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/subgraph_rewrite.h @@ -0,0 +1,117 @@ +/** This file defines API for pattern-based subgraph rewrites. + * + * The API can be used for finding concrete patterns in the model and replacing + * the corresponding subgraphs with another subgraph. A special case of such + * rewrites is fusion, where the new subgraph consists of just a single node. + * + * There is a default set of the most common patterns that everyone could use. + * Alternatively, an arbitrary pattern can be registered. + */ +#pragma once + +#include +#include + +#include +#include +#include + +namespace torch { +namespace jit { + +// Forward declarations. +struct RewritePatternDescr; +struct Match; + +using MatchFilter = std::function< + bool(const Match&, const std::unordered_map&)>; + +/** Run pattern-based subgraph rewrites on all methods in the module. + * + * This pass will go through all methods in the module and try to replace all + * recognized patterns (see SubgraphRewriter::RegisterDefaultPatterns for the + * list of these patterns). + */ +TORCH_API Module PatternBasedRewrite(const Module& module); + +/** A class implementing API for pattern-based subgraph rewrites. + * + * To perform pattern-based subgraph rewrites on a module using this API, one + * needs to create an object of such class, register rewrite patterns and run + * the transformation pass (`runOnModule`). + * + * To use standard patterns, one could use `RegisterDefaultPatterns`. + * + * To enable rewrites of custom patterns, the custom patterns must be registered + * with `RegisterRewritePattern`. + */ +class TORCH_API SubgraphRewriter { + public: + // Run pattern-based subgraph rewrite pass on the module. + Module runOnModule(const Module& module); + + // Run pattern-based subgraph rewrite pass on the graph (used in testing). + // `filter` is a function that does extra filtering on the match. If it + // returns false for a given Match, we'll skip the Match. The filter + // function's arguments consist of a Match and a value map from parsing the + // pattern graph. Both the Match and the value map are necessary because we + // need to 1) do extra filtering on the matched result as well as 2) refer to + // the values in the matched result through the values in the pattern graph. + void runOnGraph( + std::shared_ptr& graph, + const std::vector& filters); + + void runOnGraph( + std::shared_ptr& graph, + const MatchFilter& filter = + [](const Match&, const std::unordered_map&) { + return true; + }) { + runOnGraph(graph, std::vector({filter})); + } + + // Register standard rewrite patterns. + void RegisterDefaultPatterns(); + + /** Register a custom rewrite pattern. + * + * The method takes two parameters specifying the pattern: + * \p PATTERN - IR string representing the pattern subgraph. + * \p REPLACEMENT - IR string representing the replacement subgraph. + * \p value name map - vector of pairs mapping values in the replacement graph + * to the values in the pattern graph. Used for preserving source range info + * across graph rewrite. + * + * See examples of pattern registering in `RegisterDefaultPatterns`. + */ + void RegisterRewritePattern( + const std::string& pattern, + const std::string& replacement, + const std::vector>& value_name_pair = + {}); + + private: + std::vector patterns_; + std::unordered_set nodes_to_delete_; + + void rewriteSinglePatternOnGraph( + std::shared_ptr& graph, + const RewritePatternDescr& pattern, + const std::vector& filters); + + bool overlapsWithPreviousMatches(const Match* match); +}; + +/** Rewrite pattern descriptor. + * + * This structure is used in the implementation of `SubgraphRewriter` and + * is not supposed to be used externally. + */ +struct RewritePatternDescr { + std::string pattern; + std::string replacement; + std::unordered_map value_name_map; +}; + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_analysis.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_analysis.h new file mode 100644 index 0000000000000000000000000000000000000000..824740792aaf031a0adcc181cb84a666ef539fe4 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_analysis.h @@ -0,0 +1,58 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace torch { +namespace jit { + +// CAUTION NOT TO BE USED, STILL A WIP, NOT STABLE + +TORCH_API void PropagateShapesOnGraph(std::shared_ptr& graph); + +// CAUTION NOT TO BE USED, STILL A WIP, NOT STABLE +// From [beg, end) attempt to propagate shapes and +// build up a graph that will compute all remaining symbolic +// shapes in [beg, end) that can be executed before beg + +struct ShapeComputeGraphMapping { + ShapeComputeGraphMapping( + std::shared_ptr partial_eval_shape_graph, + std::unordered_map + enclosing_graph_value_to_shape_graph_input, + std::unordered_map graph_output_to_symbolic_shape_dim) + : partial_eval_shape_graph(std::move(partial_eval_shape_graph)), + enclosing_graph_value_to_shape_graph_input_( + std::move(enclosing_graph_value_to_shape_graph_input)), + graph_output_to_symbolic_shape_dim_( + std::move(graph_output_to_symbolic_shape_dim)){}; + + std::shared_ptr partial_eval_shape_graph; + std::unordered_map + enclosing_graph_value_to_shape_graph_input_; + std::unordered_map graph_output_to_symbolic_shape_dim_; +}; + +TORCH_API c10::optional +PropagateShapesAndBuildLargeShapeComputeGraph( + std::shared_ptr& graph, + Node* beg, + Node* end); + +// don't insert complete tensor shapes in shape compute graphs and instead +// rely on our partial evaluation pipeline to propagate information. +// this is a good proxy for our ability to propagate non-complete shape +// information. +TORCH_API bool setSymbolicShapeAnalysisTestMode(bool value); +TORCH_API bool symbolicShapeAnalysisTestModeEnabled(); + +using SSAInput = std::variant; +TORCH_API c10::optional> +calculateSymbolicShapesOnOp( + const FunctionSchema* schema, + const std::vector& inputs); +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_runtime_fusion.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_runtime_fusion.h new file mode 100644 index 0000000000000000000000000000000000000000..414d699d2e4cb762d8e759081b761345f5cd55aa --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/symbolic_shape_runtime_fusion.h @@ -0,0 +1,55 @@ +#pragma once + +#include +#include +#include + +#include + +namespace torch { +namespace jit { + +// Takes in a TensorExprGraph of static shapes and generalizes the input shapes +// to symbolic dimensions. Dimensions of value 1 will be preserved, otherwise +// dimensions with the same value will be bucketed to the same symbolic shape. +// E.g. Tensor(5, 3), Tensor(3, 1) -> Tensor(SS(-1), SS(-2)), Tensor(SS(-2), 1) +// From there, runs symbolic shape inference on the graph, and creates a +// versioning if in the graph with prim::TensorExprDynamicGuard checking if +// the inputs at runtime match the Generalized Symbolic Shapes that are inputs +// to the TE Kernel. The computate to calculate all symbolic dimensions is +// inlined in to the if block with the TE Kernel. All Sym Dim Value* are +// appended to the end of the TE Kernel Graph/Node inputs, and the Node is +// augmented with a integer list attr `symbolic_shape_inputs` that gives the +// mapping from Value * -> Symbolic Shape int64_t value. For more lengthy IR +// examples and walkthrough look at ShapeAnalysisTest.DynamicShapesFusion in +// `test_shape_analysis` Returns True on Success, False on Failure, can fail if +// shape propagation fails to propagate # of dims or if complete shapes on +// inputs not set + +TORCH_API bool GenerateGuard( + Node* tensorexpr_graph_node, + bool add_composed_op = false); + +TORCH_API void runTensorExprDynamicGroup(const Code& code, Stack& stack); + +enum class StrideInput { + // Tensors natively store whether they are contiguous or not as a property + // this makes it faster to query `is_contiguous` or + // `is_contiguous(memory_format=channels_last)` + // than looping through the sizes/strides yourself + // For tensors with these properties, we only store one value: + TENSOR_CONT, + TENSOR_CONT_CHANNELS_LAST, + // now, we describe other cases, where there is one stride enum + // per dimension + S_ONE, // STRIDE_ONE: packed + S_CONT, // STRIDE_CONTIGUOUS: stride[i + 1] * sizes[i + 1] + S_TRAN_CONT, // STRIDE_TRANSPOSED_CONTIGUOUS: stride[i-1] * sizes[i-1] + S_AS_ARG, // STRIDE_AS_ARG: stride passed in as runtime value +}; + +TORCH_API std::string toString(StrideInput si); +TORCH_API StrideInput strideInputFromString(const std::string& si); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/update_differentiable_graph_requires_grad.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/update_differentiable_graph_requires_grad.h new file mode 100644 index 0000000000000000000000000000000000000000..eb51ba00c4c9f8d2ca07dd96def6f5e168160e35 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/update_differentiable_graph_requires_grad.h @@ -0,0 +1,20 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Because differentiable graphs detach the gradients of input Tensors, +// creating and inlining differentiable graphs changes the requires_grad +// property of tensors in the graph. This pass updates prim::profiles +// requires_grad to keep profiled properties up to date, it does not update +// grad properties of other nodes like graph inputs bc the only downstream +// user of the grad property is the profiling executor, which just uses +// the types of prim::profiles +TORCH_API void UpdateDifferentiableGraphRequiresGrad( + std::shared_ptr& diff_forward_graph, + c10::optional new_requires_grad); + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/vulkan_rewrite.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/vulkan_rewrite.h new file mode 100644 index 0000000000000000000000000000000000000000..395d885e8e2c3c99f5e1a6d4279c9e0e26894d07 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/vulkan_rewrite.h @@ -0,0 +1,18 @@ +#pragma once + +#include +#include +#include + +namespace torch { +namespace jit { +TORCH_API void vulkanInsertPrePackedOps(std::shared_ptr& graph); +TORCH_API void vulkanInsertPrePackedOps(script::Module& module); +TORCH_API void vulkanFusePrePackedConvWithClamp(script::Module& module); +TORCH_API void vulkanFoldPrePackingOps(script::Module& module); +TORCH_API script::Module vulkanOptimizeForMobile( + const script::Module& module, + const std::set& optimization_blocklist, + const std::vector& preserved_methods); +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/xnnpack_rewrite.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/xnnpack_rewrite.h new file mode 100644 index 0000000000000000000000000000000000000000..d1a64c52c9230ad85a3c3540e120b48532abd707 --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/passes/xnnpack_rewrite.h @@ -0,0 +1,21 @@ +#pragma once + +#include +#include +#include + +namespace torch { +namespace jit { + +TORCH_API void transformConv1dToConv2d(std::shared_ptr& graph); +TORCH_API void transformConv1dToConv2d(script::Module& module); +TORCH_API void insertPrePackedOps(std::shared_ptr& graph); +TORCH_API void insertPrePackedOps(script::Module& module); +TORCH_API void fusePrePackedLinearConvWithClamp(script::Module& module); +TORCH_API void FoldPrePackingOps(script::Module& module); +TORCH_API script::Module optimizeForMobile( + const script::Module& module, + const std::set& optimization_blocklist = {}, + const std::vector& preserved_methods = {}); +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/callstack_debug_info_serialization.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/callstack_debug_info_serialization.h new file mode 100644 index 0000000000000000000000000000000000000000..ac1bdf8d3b1d846c6cd02724fa1fd07f0208c40f --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/callstack_debug_info_serialization.h @@ -0,0 +1,91 @@ +#pragma once + +#include +#include +#include + +#include + +#include + +#include + +namespace c10 { +struct IValue; +} + +namespace torch { +namespace jit { + +class Pickler; +class InlinedCallStackSerializer { + public: + // Serialize InlinedCallStack as + // SerializedInlinedCallStack = + // [module_info, source range tag, SerializedInlinedCallStack] + // module_info = [ClassType.qualifiedName, instance_name] + // source_range_tag = unique source range id + c10::IValue serialize( + const InlinedCallStackPtr& cs_ptr, + const SourceRangeTagMap& source_range_tags); + + private: + // module_info = [ClassType.qualifiedName, instance_name] + c10::IValue serialize_module_instance_info( + const c10::optional& m); + + // This caches serialized inlined callstack ptr, since many + // InlinedCallStackPtr can refer to the same one. + ska::flat_hash_map + serialized_inlined_callstack_; + // This caches serialized module instance info. + // There might be many nodes that are part of the same + // parent, grandparent etc. module. + ska::flat_hash_map serialized_module_instance_info_; +}; + +class TORCH_API CallStackDebugInfoPickler { + public: + CallStackDebugInfoPickler() = default; + + std::vector pickle( + const std::unordered_map& callstack_ptrs, + const SourceRangeTagMap& source_range_tags); + + private: + InlinedCallStackSerializer css_; +}; + +class InlinedCallStackDeserializer { + public: + InlinedCallStackPtr deserialize( + const c10::IValue& iv, + const ska::flat_hash_map& source_range_map, + const std::shared_ptr& cu); + + private: + c10::optional deserialize_module_instance_info( + const c10::IValue& iv, + const std::shared_ptr& cu); + + ska:: + flat_hash_map, InlinedCallStackPtr> + cached_inlined_callstacks_; + ska::flat_hash_map, ModuleInstanceInfo> + cached_module_instance_info_; +}; + +class TORCH_API CallStackDebugInfoUnpickler { + public: + ska::flat_hash_map unpickle( + at::DataPtr&& data, + size_t size, + const ska::flat_hash_map& source_range_map, + const std::shared_ptr& cu); + + private: + InlinedCallStackDeserializer csds_; +}; + +} // namespace jit +} // namespace torch diff --git a/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization_impl.h b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization_impl.h new file mode 100644 index 0000000000000000000000000000000000000000..2b7cd5a14ba9282090b025f23cdf28eb9bf1c5de --- /dev/null +++ b/videollama2/lib/python3.10/site-packages/torch/include/torch/csrc/jit/serialization/source_range_serialization_impl.h @@ -0,0 +1,30 @@ +#pragma once + +#include + +namespace torch { +namespace jit { + +// Do this clownyness with virtual functions because of the split +// between ATen core and torch + +class ConcreteSourceRangeUnpickler : public SourceRangeUnpickler { + public: + ConcreteSourceRangeUnpickler(at::DataPtr&& data, size_t size); + + c10::optional findSourceRangeThatGenerated( + const SourceRange& range) override; + + private: + at::DataPtr data; + size_t size; + + void unpickle(); + + std::mutex mutex; + std::shared_ptr deserializer; + std::shared_ptr unpickled_records; +}; + +} // namespace jit +} // namespace torch diff --git a/vllm/lib/python3.10/site-packages/dns/rdtypes/ANY/__pycache__/LOC.cpython-310.pyc b/vllm/lib/python3.10/site-packages/dns/rdtypes/ANY/__pycache__/LOC.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..00626089e39ffa03500c372dc217c72beb52388e Binary files /dev/null and b/vllm/lib/python3.10/site-packages/dns/rdtypes/ANY/__pycache__/LOC.cpython-310.pyc differ diff --git a/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/AAAA.py b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/AAAA.py new file mode 100644 index 0000000000000000000000000000000000000000..0cd139e7b5c4b68a8d66e070b231eda9b0e41ca7 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/AAAA.py @@ -0,0 +1,51 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.exception +import dns.immutable +import dns.ipv6 +import dns.rdata +import dns.tokenizer + + +@dns.immutable.immutable +class AAAA(dns.rdata.Rdata): + """AAAA record.""" + + __slots__ = ["address"] + + def __init__(self, rdclass, rdtype, address): + super().__init__(rdclass, rdtype) + self.address = self._as_ipv6_address(address) + + def to_text(self, origin=None, relativize=True, **kw): + return self.address + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + address = tok.get_identifier() + return cls(rdclass, rdtype, address) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + file.write(dns.ipv6.inet_aton(self.address)) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + address = parser.get_remaining() + return cls(rdclass, rdtype, address) diff --git a/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/HTTPS.py b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/HTTPS.py new file mode 100644 index 0000000000000000000000000000000000000000..15464cbda7f387d8b73d15605bfebc49d1402c27 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/HTTPS.py @@ -0,0 +1,9 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +import dns.immutable +import dns.rdtypes.svcbbase + + +@dns.immutable.immutable +class HTTPS(dns.rdtypes.svcbbase.SVCBBase): + """HTTPS record""" diff --git a/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/IPSECKEY.py b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/IPSECKEY.py new file mode 100644 index 0000000000000000000000000000000000000000..e3a6615749f4775960ef8b87161c69c6484dd3ef --- /dev/null +++ b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/IPSECKEY.py @@ -0,0 +1,91 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2006, 2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import base64 +import struct + +import dns.exception +import dns.immutable +import dns.rdtypes.util + + +class Gateway(dns.rdtypes.util.Gateway): + name = "IPSECKEY gateway" + + +@dns.immutable.immutable +class IPSECKEY(dns.rdata.Rdata): + """IPSECKEY record""" + + # see: RFC 4025 + + __slots__ = ["precedence", "gateway_type", "algorithm", "gateway", "key"] + + def __init__( + self, rdclass, rdtype, precedence, gateway_type, algorithm, gateway, key + ): + super().__init__(rdclass, rdtype) + gateway = Gateway(gateway_type, gateway) + self.precedence = self._as_uint8(precedence) + self.gateway_type = gateway.type + self.algorithm = self._as_uint8(algorithm) + self.gateway = gateway.gateway + self.key = self._as_bytes(key) + + def to_text(self, origin=None, relativize=True, **kw): + gateway = Gateway(self.gateway_type, self.gateway).to_text(origin, relativize) + return "%d %d %d %s %s" % ( + self.precedence, + self.gateway_type, + self.algorithm, + gateway, + dns.rdata._base64ify(self.key, **kw), + ) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + precedence = tok.get_uint8() + gateway_type = tok.get_uint8() + algorithm = tok.get_uint8() + gateway = Gateway.from_text( + gateway_type, tok, origin, relativize, relativize_to + ) + b64 = tok.concatenate_remaining_identifiers().encode() + key = base64.b64decode(b64) + return cls( + rdclass, rdtype, precedence, gateway_type, algorithm, gateway.gateway, key + ) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + header = struct.pack("!BBB", self.precedence, self.gateway_type, self.algorithm) + file.write(header) + Gateway(self.gateway_type, self.gateway).to_wire( + file, compress, origin, canonicalize + ) + file.write(self.key) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + header = parser.get_struct("!BBB") + gateway_type = header[1] + gateway = Gateway.from_wire_parser(gateway_type, parser, origin) + key = parser.get_remaining() + return cls( + rdclass, rdtype, header[0], gateway_type, header[2], gateway.gateway, key + ) diff --git a/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/KX.py b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/KX.py new file mode 100644 index 0000000000000000000000000000000000000000..6073df47b3c1c7921431da0af514b511713b89ad --- /dev/null +++ b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/KX.py @@ -0,0 +1,24 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import dns.immutable +import dns.rdtypes.mxbase + + +@dns.immutable.immutable +class KX(dns.rdtypes.mxbase.UncompressedDowncasingMX): + """KX record""" diff --git a/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/NAPTR.py b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/NAPTR.py new file mode 100644 index 0000000000000000000000000000000000000000..195d1cbac5ac381403bbe834ee1ffbdce7d16e56 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/NAPTR.py @@ -0,0 +1,110 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdtypes.util + + +def _write_string(file, s): + l = len(s) + assert l < 256 + file.write(struct.pack("!B", l)) + file.write(s) + + +@dns.immutable.immutable +class NAPTR(dns.rdata.Rdata): + """NAPTR record""" + + # see: RFC 3403 + + __slots__ = ["order", "preference", "flags", "service", "regexp", "replacement"] + + def __init__( + self, rdclass, rdtype, order, preference, flags, service, regexp, replacement + ): + super().__init__(rdclass, rdtype) + self.flags = self._as_bytes(flags, True, 255) + self.service = self._as_bytes(service, True, 255) + self.regexp = self._as_bytes(regexp, True, 255) + self.order = self._as_uint16(order) + self.preference = self._as_uint16(preference) + self.replacement = self._as_name(replacement) + + def to_text(self, origin=None, relativize=True, **kw): + replacement = self.replacement.choose_relativity(origin, relativize) + return '%d %d "%s" "%s" "%s" %s' % ( + self.order, + self.preference, + dns.rdata._escapify(self.flags), + dns.rdata._escapify(self.service), + dns.rdata._escapify(self.regexp), + replacement, + ) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + order = tok.get_uint16() + preference = tok.get_uint16() + flags = tok.get_string() + service = tok.get_string() + regexp = tok.get_string() + replacement = tok.get_name(origin, relativize, relativize_to) + return cls( + rdclass, rdtype, order, preference, flags, service, regexp, replacement + ) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + two_ints = struct.pack("!HH", self.order, self.preference) + file.write(two_ints) + _write_string(file, self.flags) + _write_string(file, self.service) + _write_string(file, self.regexp) + self.replacement.to_wire(file, compress, origin, canonicalize) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + (order, preference) = parser.get_struct("!HH") + strings = [] + for _ in range(3): + s = parser.get_counted_bytes() + strings.append(s) + replacement = parser.get_name(origin) + return cls( + rdclass, + rdtype, + order, + preference, + strings[0], + strings[1], + strings[2], + replacement, + ) + + def _processing_priority(self): + return (self.order, self.preference) + + @classmethod + def _processing_order(cls, iterable): + return dns.rdtypes.util.priority_processing_order(iterable) diff --git a/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/PX.py b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/PX.py new file mode 100644 index 0000000000000000000000000000000000000000..cdca1532234d5dc0130945cc82092fdacfee39c4 --- /dev/null +++ b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/PX.py @@ -0,0 +1,73 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +import struct + +import dns.exception +import dns.immutable +import dns.name +import dns.rdata +import dns.rdtypes.util + + +@dns.immutable.immutable +class PX(dns.rdata.Rdata): + """PX record.""" + + # see: RFC 2163 + + __slots__ = ["preference", "map822", "mapx400"] + + def __init__(self, rdclass, rdtype, preference, map822, mapx400): + super().__init__(rdclass, rdtype) + self.preference = self._as_uint16(preference) + self.map822 = self._as_name(map822) + self.mapx400 = self._as_name(mapx400) + + def to_text(self, origin=None, relativize=True, **kw): + map822 = self.map822.choose_relativity(origin, relativize) + mapx400 = self.mapx400.choose_relativity(origin, relativize) + return "%d %s %s" % (self.preference, map822, mapx400) + + @classmethod + def from_text( + cls, rdclass, rdtype, tok, origin=None, relativize=True, relativize_to=None + ): + preference = tok.get_uint16() + map822 = tok.get_name(origin, relativize, relativize_to) + mapx400 = tok.get_name(origin, relativize, relativize_to) + return cls(rdclass, rdtype, preference, map822, mapx400) + + def _to_wire(self, file, compress=None, origin=None, canonicalize=False): + pref = struct.pack("!H", self.preference) + file.write(pref) + self.map822.to_wire(file, None, origin, canonicalize) + self.mapx400.to_wire(file, None, origin, canonicalize) + + @classmethod + def from_wire_parser(cls, rdclass, rdtype, parser, origin=None): + preference = parser.get_uint16() + map822 = parser.get_name(origin) + mapx400 = parser.get_name(origin) + return cls(rdclass, rdtype, preference, map822, mapx400) + + def _processing_priority(self): + return self.preference + + @classmethod + def _processing_order(cls, iterable): + return dns.rdtypes.util.priority_processing_order(iterable) diff --git a/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/__init__.py b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..dcec4dd24d49ee16a4b2cda0fdb5806b6c13695c --- /dev/null +++ b/vllm/lib/python3.10/site-packages/dns/rdtypes/IN/__init__.py @@ -0,0 +1,35 @@ +# Copyright (C) Dnspython Contributors, see LICENSE for text of ISC license + +# Copyright (C) 2003-2007, 2009-2011 Nominum, Inc. +# +# Permission to use, copy, modify, and distribute this software and its +# documentation for any purpose with or without fee is hereby granted, +# provided that the above copyright notice and this permission notice +# appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND NOMINUM DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL NOMINUM BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT +# OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. + +"""Class IN rdata type classes.""" + +__all__ = [ + "A", + "AAAA", + "APL", + "DHCID", + "HTTPS", + "IPSECKEY", + "KX", + "NAPTR", + "NSAP", + "NSAP_PTR", + "PX", + "SRV", + "SVCB", + "WKS", +]