up follow livre

This commit is contained in:
Tykayn 2025-08-30 18:14:14 +02:00 committed by tykayn
parent b4b4398bb0
commit 3a7a3849ae
12242 changed files with 2564461 additions and 6914 deletions

View file

@ -0,0 +1,174 @@
"""
=========================================================
Multidimensional image processing (:mod:`scipy.ndimage`)
=========================================================
.. currentmodule:: scipy.ndimage
This package contains various functions for multidimensional image
processing.
Filters
=======
.. autosummary::
:toctree: generated/
convolve - Multidimensional convolution
convolve1d - 1-D convolution along the given axis
correlate - Multidimensional correlation
correlate1d - 1-D correlation along the given axis
gaussian_filter
gaussian_filter1d
gaussian_gradient_magnitude
gaussian_laplace
generic_filter - Multidimensional filter using a given function
generic_filter1d - 1-D generic filter along the given axis
generic_gradient_magnitude
generic_laplace
laplace - N-D Laplace filter based on approximate second derivatives
maximum_filter
maximum_filter1d
median_filter - Calculates a multidimensional median filter
minimum_filter
minimum_filter1d
percentile_filter - Calculates a multidimensional percentile filter
prewitt
rank_filter - Calculates a multidimensional rank filter
sobel
uniform_filter - Multidimensional uniform filter
uniform_filter1d - 1-D uniform filter along the given axis
vectorized_filter
Fourier filters
===============
.. autosummary::
:toctree: generated/
fourier_ellipsoid
fourier_gaussian
fourier_shift
fourier_uniform
Interpolation
=============
.. autosummary::
:toctree: generated/
affine_transform - Apply an affine transformation
geometric_transform - Apply an arbitrary geometric transform
map_coordinates - Map input array to new coordinates by interpolation
rotate - Rotate an array
shift - Shift an array
spline_filter
spline_filter1d
zoom - Zoom an array
Measurements
============
.. autosummary::
:toctree: generated/
center_of_mass - The center of mass of the values of an array at labels
extrema - Min's and max's of an array at labels, with their positions
find_objects - Find objects in a labeled array
histogram - Histogram of the values of an array, optionally at labels
label - Label features in an array
labeled_comprehension
maximum
maximum_position
mean - Mean of the values of an array at labels
median
minimum
minimum_position
standard_deviation - Standard deviation of an N-D image array
sum_labels - Sum of the values of the array
value_indices - Find indices of each distinct value in given array
variance - Variance of the values of an N-D image array
watershed_ift
Morphology
==========
.. autosummary::
:toctree: generated/
binary_closing
binary_dilation
binary_erosion
binary_fill_holes
binary_hit_or_miss
binary_opening
binary_propagation
black_tophat
distance_transform_bf
distance_transform_cdt
distance_transform_edt
generate_binary_structure
grey_closing
grey_dilation
grey_erosion
grey_opening
iterate_structure
morphological_gradient
morphological_laplace
white_tophat
"""
# Copyright (C) 2003-2005 Peter J. Verveer
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# 3. The name of the author may not be used to endorse or promote
# products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
# bring in the public functionality from private namespaces
# mypy: ignore-errors
from ._support_alternative_backends import *
# adjust __all__ and do not leak implementation details
from . import _support_alternative_backends
__all__ = _support_alternative_backends.__all__
del _support_alternative_backends, _ndimage_api, _delegators # noqa: F821
# Deprecated namespaces, to be removed in v2.0.0
from . import filters
from . import fourier
from . import interpolation
from . import measurements
from . import morphology
from scipy._lib._testutils import PytestTester
test = PytestTester(__name__)
del PytestTester

View file

@ -0,0 +1,303 @@
"""Delegators for alternative backends in scipy.ndimage.
The signature of `func_signature` must match the signature of ndimage.func.
The job of a `func_signature` is to know which arguments of `ndimage.func`
are arrays.
* signatures are generated by
--------------
import inspect
from scipy import ndimage
names = [x for x in dir(ndimage) if not x.startswith('_')]
objs = [getattr(ndimage, name) for name in names]
funcs = [obj for obj in objs if inspect.isroutine(obj)]
for func in funcs:
sig = inspect.signature(func)
print(f"def {func.__name__}_signature{sig}:\n\tpass\n\n")
---------------
* which arguments to delegate on: manually trawled the documentation for
array-like and array arguments
"""
import numpy as np
from scipy._lib._array_api import array_namespace
from scipy.ndimage._ni_support import _skip_if_dtype
def affine_transform_signature(
input, matrix, offset=0.0, output_shape=None, output=None, *args, **kwds
):
return array_namespace(input, matrix, _skip_if_dtype(output))
def binary_closing_signature(
input, structure=None, iterations=1, output=None, *args, **kwds
):
return array_namespace(input, structure, _skip_if_dtype(output))
binary_opening_signature = binary_closing_signature
def binary_dilation_signature(
input, structure=None, iterations=1, mask=None, output=None, *args, **kwds
):
return array_namespace(input, structure, _skip_if_dtype(output), mask)
binary_erosion_signature = binary_dilation_signature
def binary_fill_holes_signature(
input, structure=None, output=None, origin=0, *args, **kwargs
):
return array_namespace(input, structure, _skip_if_dtype(output))
def label_signature(input, structure=None, output=None, origin=0):
return array_namespace(input, structure, _skip_if_dtype(output))
def binary_hit_or_miss_signature(
input, structure1=None, structure2=None, output=None, *args, **kwds
):
return array_namespace(input, structure1, structure2, _skip_if_dtype(output))
def binary_propagation_signature(
input, structure=None, mask=None, output=None, *args, **kwds
):
return array_namespace(input, structure, mask, _skip_if_dtype(output))
def convolve_signature(input, weights, output=None, *args, **kwds):
return array_namespace(input, weights, _skip_if_dtype(output))
correlate_signature = convolve_signature
def convolve1d_signature(input, weights, axis=-1, output=None, *args, **kwds):
return array_namespace(input, weights, _skip_if_dtype(output))
correlate1d_signature = convolve1d_signature
def distance_transform_bf_signature(
input, metric='euclidean', sampling=None, return_distances=True,
return_indices=False, distances=None, indices=None
):
return array_namespace(input, distances, indices)
def distance_transform_cdt_signature(
input, metric='chessboard', return_distances=True, return_indices=False,
distances=None, indices=None
):
return array_namespace(input, distances, indices)
def distance_transform_edt_signature(
input, sampling=None, return_distances=True, return_indices=False,
distances=None, indices=None
):
return array_namespace(input, distances, indices)
def find_objects_signature(input, max_label=0):
return array_namespace(input)
def fourier_ellipsoid_signature(input, size, n=-1, axis=-1, output=None):
return array_namespace(input, _skip_if_dtype(output))
fourier_uniform_signature = fourier_ellipsoid_signature
def fourier_gaussian_signature(input, sigma, n=-1, axis=-1, output=None):
return array_namespace(input, _skip_if_dtype(output))
def fourier_shift_signature(input, shift, n=-1, axis=-1, output=None):
return array_namespace(input, _skip_if_dtype(output))
def gaussian_filter_signature(input, sigma, order=0, output=None, *args, **kwds):
return array_namespace(input, _skip_if_dtype(output))
def gaussian_filter1d_signature(
input, sigma, axis=-1, order=0, output=None, *args, **kwds
):
return array_namespace(input, _skip_if_dtype(output))
def gaussian_gradient_magnitude_signature(input, sigma, output=None, *args, **kwds):
return array_namespace(input, _skip_if_dtype(output))
gaussian_laplace_signature = gaussian_gradient_magnitude_signature
def generate_binary_structure_signature(rank, connectivity):
# XXX: no input arrays; always return numpy
return np
def generic_filter_signature(
input, function, size=None, footprint=None, output=None, *args, **kwds
):
# XXX: function LowLevelCallable w/backends
return array_namespace(input, footprint, _skip_if_dtype(output))
def generic_filter1d_signature(
input, function, filter_size, axis=-1, output=None, *args, **kwds
):
return array_namespace(input, _skip_if_dtype(output))
def generic_gradient_magnitude_signature(
input, derivative, output=None, *args, **kwds
):
# XXX: function LowLevelCallable w/backends
return array_namespace(input, _skip_if_dtype(output))
def generic_laplace_signature(input, derivative2, output=None, *args, **kwds):
# XXX: function LowLevelCallable w/backends
return array_namespace(input, _skip_if_dtype(output))
def geometric_transform_signature(
input, mapping, output_shape=None, output=None, *args, **kwds
):
return array_namespace(input, _skip_if_dtype(output))
def histogram_signature(input, min, max, bins, labels=None, index=None):
return array_namespace(input, labels)
def iterate_structure_signature(structure, iterations, origin=None):
return array_namespace(structure)
def labeled_comprehension_signature(input, labels, *args, **kwds):
return array_namespace(input, labels)
def laplace_signature(input, output=None, *args, **kwds):
return array_namespace(input, _skip_if_dtype(output))
def map_coordinates_signature(input, coordinates, output=None, *args, **kwds):
return array_namespace(input, coordinates, _skip_if_dtype(output))
def maximum_filter1d_signature(input, size, axis=-1, output=None, *args, **kwds):
return array_namespace(input, _skip_if_dtype(output))
minimum_filter1d_signature = maximum_filter1d_signature
uniform_filter1d_signature = maximum_filter1d_signature
def maximum_signature(input, labels=None, index=None):
return array_namespace(input, labels, index)
minimum_signature = maximum_signature
median_signature = maximum_signature
mean_signature = maximum_signature
variance_signature = maximum_signature
standard_deviation_signature = maximum_signature
sum_labels_signature = maximum_signature
sum_signature = maximum_signature # ndimage.sum is sum_labels
maximum_position_signature = maximum_signature
minimum_position_signature = maximum_signature
extrema_signature = maximum_signature
center_of_mass_signature = extrema_signature
def median_filter_signature(
input, size=None, footprint=None, output=None, *args, **kwds
):
return array_namespace(input, footprint, _skip_if_dtype(output))
minimum_filter_signature = median_filter_signature
maximum_filter_signature = median_filter_signature
def morphological_gradient_signature(
input, size=None, footprint=None, structure=None, output=None, *args, **kwds
):
return array_namespace(input, footprint, structure, _skip_if_dtype(output))
morphological_laplace_signature = morphological_gradient_signature
white_tophat_signature = morphological_gradient_signature
black_tophat_signature = morphological_gradient_signature
grey_closing_signature = morphological_gradient_signature
grey_dilation_signature = morphological_gradient_signature
grey_erosion_signature = morphological_gradient_signature
grey_opening_signature = morphological_gradient_signature
def percentile_filter_signature(
input, percentile, size=None, footprint=None, output=None, *args, **kwds
):
return array_namespace(input, footprint, _skip_if_dtype(output))
def prewitt_signature(input, axis=-1, output=None, *args, **kwds):
return array_namespace(input, _skip_if_dtype(output))
sobel_signature = prewitt_signature
def rank_filter_signature(
input, rank, size=None, footprint=None, output=None, *args, **kwds
):
return array_namespace(input, footprint, _skip_if_dtype(output))
def rotate_signature(
input, angle, axes=(1, 0), reshape=True, output=None , *args, **kwds
):
return array_namespace(input, _skip_if_dtype(output))
def shift_signature(input, shift, output=None, *args, **kwds):
return array_namespace(input, _skip_if_dtype(output))
def spline_filter_signature(input, order=3, output=np.float64, *args, **kwds):
return array_namespace(input, _skip_if_dtype(output))
def spline_filter1d_signature(
input, order=3, axis=-1, output=np.float64, *args, **kwds
):
return array_namespace(input, _skip_if_dtype(output))
def uniform_filter_signature(input, size=3, output=None, *args, **kwds):
return array_namespace(input, _skip_if_dtype(output))
def value_indices_signature(arr, *args, **kwds):
return array_namespace(arr)
def vectorized_filter_signature(
input, function, size=None, footprint=None, output=None, *args, **kwds
):
return array_namespace(input, footprint, _skip_if_dtype(output))
def watershed_ift_signature(input, markers, structure=None, output=None):
return array_namespace(input, markers, structure, _skip_if_dtype(output))
def zoom_signature(input, zoom, output=None, *args, **kwds):
return array_namespace(input, _skip_if_dtype(output))

File diff suppressed because it is too large Load diff

View file

@ -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

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,16 @@
"""This is the 'bare' ndimage API.
This --- private! --- module only collects implementations of public ndimage API
for _support_alternative_backends.
The latter --- also private! --- module adds delegation to CuPy etc and
re-exports decorated names to __init__.py
"""
from ._filters import * # noqa: F403
from ._fourier import * # noqa: F403
from ._interpolation import * # noqa: F403
from ._measurements import * # noqa: F403
from ._morphology import * # noqa: F403
# '@' due to pytest bug, scipy/scipy#22236
__all__ = [s for s in dir() if not s.startswith(('_', '@'))]

View file

@ -0,0 +1,214 @@
"""Docstring components common to several ndimage functions."""
from typing import Final
from scipy._lib import doccer
__all__ = ['docfiller']
_input_doc = (
"""input : array_like
The input array.""")
_axis_doc = (
"""axis : int, optional
The axis of `input` along which to calculate. Default is -1.""")
_output_doc = (
"""output : array or dtype, optional
The array in which to place the output, or the dtype of the
returned array. By default an array of the same dtype as input
will be created.""")
_nan_doc = (
"""The behavior of this function with NaN elements is undefined. To control
behavior in the presence of NaNs, consider using `vectorized_filter`.""")
_size_foot_doc = (
"""size : scalar or tuple, optional
See footprint, below. Ignored if footprint is given.
footprint : array, optional
Either `size` or `footprint` must be defined. `size` gives
the shape that is taken from the input array, at every element
position, to define the input to the filter function.
`footprint` is a boolean array that specifies (implicitly) a
shape, but also which of the elements within this shape will get
passed to the filter function. Thus ``size=(n,m)`` is equivalent
to ``footprint=np.ones((n,m))``. We adjust `size` to the number
of dimensions of the input array, so that, if the input array is
shape (10,10,10), and `size` is 2, then the actual size used is
(2,2,2). When `footprint` is given, `size` is ignored.""")
_mode_reflect_doc = (
"""mode : {'reflect', 'constant', 'nearest', 'mirror', 'wrap'}, optional
The `mode` parameter determines how the input array is extended
beyond its boundaries. Default is 'reflect'. Behavior for each valid
value is as follows:
'reflect' (`d c b a | a b c d | d c b a`)
The input is extended by reflecting about the edge of the last
pixel. This mode is also sometimes referred to as half-sample
symmetric.
'constant' (`k k k k | a b c d | k k k k`)
The input is extended by filling all values beyond the edge with
the same constant value, defined by the `cval` parameter.
'nearest' (`a a a a | a b c d | d d d d`)
The input is extended by replicating the last pixel.
'mirror' (`d c b | a b c d | c b a`)
The input is extended by reflecting about the center of the last
pixel. This mode is also sometimes referred to as whole-sample
symmetric.
'wrap' (`a b c d | a b c d | a b c d`)
The input is extended by wrapping around to the opposite edge.
For consistency with the interpolation functions, the following mode
names can also be used:
'grid-mirror'
This is a synonym for 'reflect'.
'grid-constant'
This is a synonym for 'constant'.
'grid-wrap'
This is a synonym for 'wrap'.""")
_mode_interp_constant_doc = (
"""mode : {'reflect', 'grid-mirror', 'constant', 'grid-constant', 'nearest', \
'mirror', 'grid-wrap', 'wrap'}, optional
The `mode` parameter determines how the input array is extended
beyond its boundaries. Default is 'constant'. Behavior for each valid
value is as follows (see additional plots and details on
:ref:`boundary modes <ndimage-interpolation-modes>`):
'reflect' (`d c b a | a b c d | d c b a`)
The input is extended by reflecting about the edge of the last
pixel. This mode is also sometimes referred to as half-sample
symmetric.
'grid-mirror'
This is a synonym for 'reflect'.
'constant' (`k k k k | a b c d | k k k k`)
The input is extended by filling all values beyond the edge with
the same constant value, defined by the `cval` parameter. No
interpolation is performed beyond the edges of the input.
'grid-constant' (`k k k k | a b c d | k k k k`)
The input is extended by filling all values beyond the edge with
the same constant value, defined by the `cval` parameter. Interpolation
occurs for samples outside the input's extent as well.
'nearest' (`a a a a | a b c d | d d d d`)
The input is extended by replicating the last pixel.
'mirror' (`d c b | a b c d | c b a`)
The input is extended by reflecting about the center of the last
pixel. This mode is also sometimes referred to as whole-sample
symmetric.
'grid-wrap' (`a b c d | a b c d | a b c d`)
The input is extended by wrapping around to the opposite edge.
'wrap' (`d b c d | a b c d | b c a b`)
The input is extended by wrapping around to the opposite edge, but in a
way such that the last point and initial point exactly overlap. In this
case it is not well defined which sample will be chosen at the point of
overlap.""")
_mode_interp_mirror_doc = (
_mode_interp_constant_doc.replace("Default is 'constant'",
"Default is 'mirror'")
)
assert _mode_interp_mirror_doc != _mode_interp_constant_doc, \
'Default not replaced'
_mode_multiple_doc = (
"""mode : str or sequence, optional
The `mode` parameter determines how the input array is extended
when the filter overlaps a border. By passing a sequence of modes
with length equal to the number of dimensions of the input array,
different modes can be specified along each axis. Default value is
'reflect'. The valid values and their behavior is as follows:
'reflect' (`d c b a | a b c d | d c b a`)
The input is extended by reflecting about the edge of the last
pixel. This mode is also sometimes referred to as half-sample
symmetric.
'constant' (`k k k k | a b c d | k k k k`)
The input is extended by filling all values beyond the edge with
the same constant value, defined by the `cval` parameter.
'nearest' (`a a a a | a b c d | d d d d`)
The input is extended by replicating the last pixel.
'mirror' (`d c b | a b c d | c b a`)
The input is extended by reflecting about the center of the last
pixel. This mode is also sometimes referred to as whole-sample
symmetric.
'wrap' (`a b c d | a b c d | a b c d`)
The input is extended by wrapping around to the opposite edge.
For consistency with the interpolation functions, the following mode
names can also be used:
'grid-constant'
This is a synonym for 'constant'.
'grid-mirror'
This is a synonym for 'reflect'.
'grid-wrap'
This is a synonym for 'wrap'.""")
_cval_doc = (
"""cval : scalar, optional
Value to fill past edges of input if `mode` is 'constant'. Default
is 0.0.""")
_origin_doc = (
"""origin : int, optional
Controls the placement of the filter on the input array's pixels.
A value of 0 (the default) centers the filter over the pixel, with
positive values shifting the filter to the left, and negative ones
to the right.""")
_origin_multiple_doc = (
"""origin : int or sequence, optional
Controls the placement of the filter on the input array's pixels.
A value of 0 (the default) centers the filter over the pixel, with
positive values shifting the filter to the left, and negative ones
to the right. By passing a sequence of origins with length equal to
the number of dimensions of the input array, different shifts can
be specified along each axis.""")
_extra_arguments_doc = (
"""extra_arguments : sequence, optional
Sequence of extra positional arguments to pass to passed function.""")
_extra_keywords_doc = (
"""extra_keywords : dict, optional
dict of extra keyword arguments to pass to passed function.""")
_prefilter_doc = (
"""prefilter : bool, optional
Determines if the input array is prefiltered with `spline_filter`
before interpolation. The default is True, which will create a
temporary `float64` array of filtered values if ``order > 1``. If
setting this to False, the output will be slightly blurred if
``order > 1``, unless the input is prefiltered, i.e. it is the result
of calling `spline_filter` on the original input.""")
docdict = {
'input': _input_doc,
'axis': _axis_doc,
'output': _output_doc,
'size_foot': _size_foot_doc,
'mode_interp_constant': _mode_interp_constant_doc,
'mode_interp_mirror': _mode_interp_mirror_doc,
'mode_reflect': _mode_reflect_doc,
'mode_multiple': _mode_multiple_doc,
'cval': _cval_doc,
'origin': _origin_doc,
'origin_multiple': _origin_multiple_doc,
'extra_arguments': _extra_arguments_doc,
'extra_keywords': _extra_keywords_doc,
'prefilter': _prefilter_doc,
'nan': _nan_doc,
}
docfiller: Final = doccer.filldoc(docdict)

View file

@ -0,0 +1,139 @@
# Copyright (C) 2003-2005 Peter J. Verveer
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
#
# 1. Redistributions of source code must retain the above copyright
# notice, this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above
# copyright notice, this list of conditions and the following
# disclaimer in the documentation and/or other materials provided
# with the distribution.
#
# 3. The name of the author may not be used to endorse or promote
# products derived from this software without specific prior
# written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
# OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
# GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
from collections.abc import Iterable
import operator
import warnings
import numpy as np
def _extend_mode_to_code(mode, is_filter=False):
"""Convert an extension mode to the corresponding integer code.
"""
if mode == 'nearest':
return 0
elif mode == 'wrap':
return 1
elif mode in ['reflect', 'grid-mirror']:
return 2
elif mode == 'mirror':
return 3
elif mode == 'constant':
return 4
elif mode == 'grid-wrap' and is_filter:
return 1
elif mode == 'grid-wrap':
return 5
elif mode == 'grid-constant' and is_filter:
return 4
elif mode == 'grid-constant':
return 6
else:
raise RuntimeError('boundary mode not supported')
def _normalize_sequence(input, rank):
"""If input is a scalar, create a sequence of length equal to the
rank by duplicating the input. If input is a sequence,
check if its length is equal to the length of array.
"""
is_str = isinstance(input, str)
if not is_str and np.iterable(input):
normalized = list(input)
if len(normalized) != rank:
err = "sequence argument must have length equal to input rank"
raise RuntimeError(err)
else:
normalized = [input] * rank
return normalized
def _get_output(output, input, shape=None, complex_output=False):
if shape is None:
shape = input.shape
if output is None:
if not complex_output:
output = np.zeros(shape, dtype=input.dtype.name)
else:
complex_type = np.promote_types(input.dtype, np.complex64)
output = np.zeros(shape, dtype=complex_type)
elif isinstance(output, type | np.dtype):
# Classes (like `np.float32`) and dtypes are interpreted as dtype
if complex_output and np.dtype(output).kind != 'c':
warnings.warn("promoting specified output dtype to complex", stacklevel=3)
output = np.promote_types(output, np.complex64)
output = np.zeros(shape, dtype=output)
elif isinstance(output, str):
output = np.dtype(output)
if complex_output and output.kind != 'c':
raise RuntimeError("output must have complex dtype")
elif not issubclass(output.type, np.number):
raise RuntimeError("output must have numeric dtype")
output = np.zeros(shape, dtype=output)
else:
# output was supplied as an array
output = np.asarray(output)
if output.shape != shape:
raise RuntimeError("output shape not correct")
elif complex_output and output.dtype.kind != 'c':
raise RuntimeError("output must have complex dtype")
return output
def _check_axes(axes, ndim):
if axes is None:
return tuple(range(ndim))
elif np.isscalar(axes):
axes = (operator.index(axes),)
elif isinstance(axes, Iterable):
for ax in axes:
axes = tuple(operator.index(ax) for ax in axes)
if ax < -ndim or ax > ndim - 1:
raise ValueError(f"specified axis: {ax} is out of range")
axes = tuple(ax % ndim if ax < 0 else ax for ax in axes)
else:
message = "axes must be an integer, iterable of integers, or None"
raise ValueError(message)
if len(tuple(set(axes))) != len(axes):
raise ValueError("axes must be unique")
return axes
def _skip_if_dtype(arg):
"""'array or dtype' polymorphism.
Return None for np.int8, dtype('float32') or 'f' etc
arg for np.empty(3) etc
"""
if isinstance(arg, str):
return None
if type(arg) is type:
return None if issubclass(arg, np.generic) else arg
else:
return None if isinstance(arg, np.dtype) else arg

View file

@ -0,0 +1,84 @@
import functools
from scipy._lib._array_api import (
is_cupy, is_jax, scipy_namespace_for, SCIPY_ARRAY_API
)
import numpy as np
from ._ndimage_api import * # noqa: F403
from . import _ndimage_api
from . import _delegators
__all__ = _ndimage_api.__all__
MODULE_NAME = 'ndimage'
def _maybe_convert_arg(arg, xp):
"""Convert arrays/scalars hiding in the sequence `arg`."""
if isinstance(arg, np.ndarray | np.generic):
return xp.asarray(arg)
elif isinstance(arg, list | tuple):
return type(arg)(_maybe_convert_arg(x, xp) for x in arg)
else:
return arg
# Some cupyx.scipy.ndimage functions don't exist or are incompatible with
# their SciPy counterparts
CUPY_BLOCKLIST = ['vectorized_filter']
def delegate_xp(delegator, module_name):
def inner(func):
@functools.wraps(func)
def wrapper(*args, **kwds):
xp = delegator(*args, **kwds)
# try delegating to a cupyx/jax namesake
if is_cupy(xp) and func.__name__ not in CUPY_BLOCKLIST:
# https://github.com/cupy/cupy/issues/8336
import importlib
cupyx_module = importlib.import_module(f"cupyx.scipy.{module_name}")
cupyx_func = getattr(cupyx_module, func.__name__)
return cupyx_func(*args, **kwds)
elif is_jax(xp) and func.__name__ == "map_coordinates":
spx = scipy_namespace_for(xp)
jax_module = getattr(spx, module_name)
jax_func = getattr(jax_module, func.__name__)
return jax_func(*args, **kwds)
else:
# the original function (does all np.asarray internally)
# XXX: output arrays
result = func(*args, **kwds)
if isinstance(result, np.ndarray | np.generic):
# XXX: np.int32->np.array_0D
return xp.asarray(result)
elif isinstance(result, int):
return result
elif isinstance(result, dict):
# value_indices: result is {np.int64(1): (array(0), array(1))} etc
return {
k.item(): tuple(xp.asarray(vv) for vv in v)
for k,v in result.items()
}
elif result is None:
# inplace operations
return result
else:
# lists/tuples
return _maybe_convert_arg(result, xp)
return wrapper
return inner
# ### decorate ###
for func_name in _ndimage_api.__all__:
bare_func = getattr(_ndimage_api, func_name)
delegator = getattr(_delegators, func_name + "_signature")
f = (delegate_xp(delegator, MODULE_NAME)(bare_func)
if SCIPY_ARRAY_API
else bare_func)
# add the decorated function to the namespace, to be imported in __init__.py
vars()[func_name] = f

View file

@ -0,0 +1,27 @@
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.ndimage` namespace for importing the functions
# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822
'correlate1d', 'convolve1d', 'gaussian_filter1d',
'gaussian_filter', 'prewitt', 'sobel', 'generic_laplace',
'laplace', 'gaussian_laplace', 'generic_gradient_magnitude',
'gaussian_gradient_magnitude', 'correlate', 'convolve',
'uniform_filter1d', 'uniform_filter', 'minimum_filter1d',
'maximum_filter1d', 'minimum_filter', 'maximum_filter',
'rank_filter', 'median_filter', 'percentile_filter',
'generic_filter1d', 'generic_filter'
]
def __dir__():
return __all__
def __getattr__(name):
return _sub_module_deprecation(sub_package='ndimage', module='filters',
private_modules=['_filters'], all=__all__,
attribute=name)

View file

@ -0,0 +1,21 @@
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.ndimage` namespace for importing the functions
# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822
'fourier_gaussian', 'fourier_uniform',
'fourier_ellipsoid', 'fourier_shift'
]
def __dir__():
return __all__
def __getattr__(name):
return _sub_module_deprecation(sub_package='ndimage', module='fourier',
private_modules=['_fourier'], all=__all__,
attribute=name)

View file

@ -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)

View file

@ -0,0 +1,24 @@
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.ndimage` namespace for importing the functions
# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822
'label', 'find_objects', 'labeled_comprehension',
'sum', 'mean', 'variance', 'standard_deviation',
'minimum', 'maximum', 'median', 'minimum_position',
'maximum_position', 'extrema', 'center_of_mass',
'histogram', 'watershed_ift', 'sum_labels'
]
def __dir__():
return __all__
def __getattr__(name):
return _sub_module_deprecation(sub_package='ndimage', module='measurements',
private_modules=['_measurements'], all=__all__,
attribute=name)

View file

@ -0,0 +1,27 @@
# This file is not meant for public use and will be removed in SciPy v2.0.0.
# Use the `scipy.ndimage` namespace for importing the functions
# included below.
from scipy._lib.deprecation import _sub_module_deprecation
__all__ = [ # noqa: F822
'iterate_structure', 'generate_binary_structure',
'binary_erosion', 'binary_dilation', 'binary_opening',
'binary_closing', 'binary_hit_or_miss', 'binary_propagation',
'binary_fill_holes', 'grey_erosion', 'grey_dilation',
'grey_opening', 'grey_closing', 'morphological_gradient',
'morphological_laplace', 'white_tophat', 'black_tophat',
'distance_transform_bf', 'distance_transform_cdt',
'distance_transform_edt'
]
def __dir__():
return __all__
def __getattr__(name):
return _sub_module_deprecation(sub_package='ndimage', module='morphology',
private_modules=['_morphology'], all=__all__,
attribute=name)

View file

@ -0,0 +1,12 @@
import numpy as np
# list of numarray data types
integer_types: list[str] = [
"int8", "uint8", "int16", "uint16",
"int32", "uint32", "int64", "uint64"]
float_types: list[str] = ["float32", "float64"]
complex_types: list[str] = ["complex64", "complex128"]
types: list[str] = integer_types + float_types

View file

@ -0,0 +1,21 @@
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 1 1 1 1
1 1 1 0 1 1 1
1 1 0 0 0 1 1
1 0 1 0 1 0 1
0 0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 4 0 5
0 0 0 4 0 0 0
6 0 0 7 0 0 8
9 10 7 11 12 8 13
10 0 0 12 0 0 14
0 0 0 15 0 0 0
16 0 15 17 18 0 19
1 0 2 2 2 0 3
0 0 0 2 0 0 0
2 0 0 2 0 0 2
2 2 2 2 2 2 2
2 0 0 2 0 0 2
0 0 0 2 0 0 0
4 0 2 2 2 0 5

View file

@ -0,0 +1,42 @@
0 0 1
1 1 1
1 0 0
1 0 0
1 1 1
0 0 1
0 0 0
1 1 1
0 0 0
0 1 1
0 1 0
1 1 0
0 0 0
0 0 0
0 0 0
0 1 1
1 1 1
1 1 0
0 1 0
1 1 1
0 1 0
1 0 0
0 1 0
0 0 1
0 1 0
0 1 0
0 1 0
1 1 1
1 1 1
1 1 1
1 1 0
0 1 0
0 1 1
1 0 1
0 1 0
1 0 1
0 0 1
0 1 0
1 0 0
1 1 0
1 1 1
0 1 1

Binary file not shown.

After

Width:  |  Height:  |  Size: 2.1 KiB

View file

@ -0,0 +1,102 @@
import numpy as np
from scipy._lib._array_api import xp_assert_close
from scipy import ndimage
from scipy.ndimage import _ctest
from scipy.ndimage import _cytest
from scipy._lib._ccallback import LowLevelCallable
FILTER1D_FUNCTIONS = [
lambda filter_size: _ctest.filter1d(filter_size),
lambda filter_size: _cytest.filter1d(filter_size, with_signature=False),
lambda filter_size: LowLevelCallable(
_cytest.filter1d(filter_size, with_signature=True)
),
lambda filter_size: LowLevelCallable.from_cython(
_cytest, "_filter1d",
_cytest.filter1d_capsule(filter_size),
),
]
FILTER2D_FUNCTIONS = [
lambda weights: _ctest.filter2d(weights),
lambda weights: _cytest.filter2d(weights, with_signature=False),
lambda weights: LowLevelCallable(_cytest.filter2d(weights, with_signature=True)),
lambda weights: LowLevelCallable.from_cython(_cytest,
"_filter2d",
_cytest.filter2d_capsule(weights),),
]
TRANSFORM_FUNCTIONS = [
lambda shift: _ctest.transform(shift),
lambda shift: _cytest.transform(shift, with_signature=False),
lambda shift: LowLevelCallable(_cytest.transform(shift, with_signature=True)),
lambda shift: LowLevelCallable.from_cython(_cytest,
"_transform",
_cytest.transform_capsule(shift),),
]
def test_generic_filter():
def filter2d(footprint_elements, weights):
return (weights*footprint_elements).sum()
def check(j):
func = FILTER2D_FUNCTIONS[j]
im = np.ones((20, 20))
im[:10,:10] = 0
footprint = np.array([[0, 1, 0], [1, 1, 1], [0, 1, 0]])
footprint_size = np.count_nonzero(footprint)
weights = np.ones(footprint_size)/footprint_size
res = ndimage.generic_filter(im, func(weights),
footprint=footprint)
std = ndimage.generic_filter(im, filter2d, footprint=footprint,
extra_arguments=(weights,))
xp_assert_close(res, std, err_msg=f"#{j} failed")
for j, func in enumerate(FILTER2D_FUNCTIONS):
check(j)
def test_generic_filter1d():
def filter1d(input_line, output_line, filter_size):
for i in range(output_line.size):
output_line[i] = 0
for j in range(filter_size):
output_line[i] += input_line[i+j]
output_line /= filter_size
def check(j):
func = FILTER1D_FUNCTIONS[j]
im = np.tile(np.hstack((np.zeros(10), np.ones(10))), (10, 1))
filter_size = 3
res = ndimage.generic_filter1d(im, func(filter_size),
filter_size)
std = ndimage.generic_filter1d(im, filter1d, filter_size,
extra_arguments=(filter_size,))
xp_assert_close(res, std, err_msg=f"#{j} failed")
for j, func in enumerate(FILTER1D_FUNCTIONS):
check(j)
def test_geometric_transform():
def transform(output_coordinates, shift):
return output_coordinates[0] - shift, output_coordinates[1] - shift
def check(j):
func = TRANSFORM_FUNCTIONS[j]
im = np.arange(12).reshape(4, 3).astype(np.float64)
shift = 0.5
res = ndimage.geometric_transform(im, func(shift))
std = ndimage.geometric_transform(im, transform, extra_arguments=(shift,))
xp_assert_close(res, std, err_msg=f"#{j} failed")
for j, func in enumerate(TRANSFORM_FUNCTIONS):
check(j)

View file

@ -0,0 +1,67 @@
""" Testing data types for ndimage calls
"""
import numpy as np
from scipy._lib._array_api import assert_array_almost_equal
import pytest
from scipy import ndimage
def test_map_coordinates_dts():
# check that ndimage accepts different data types for interpolation
data = np.array([[4, 1, 3, 2],
[7, 6, 8, 5],
[3, 5, 3, 6]])
shifted_data = np.array([[0, 0, 0, 0],
[0, 4, 1, 3],
[0, 7, 6, 8]])
idx = np.indices(data.shape)
dts = (np.uint8, np.uint16, np.uint32, np.uint64,
np.int8, np.int16, np.int32, np.int64,
np.intp, np.uintp, np.float32, np.float64)
for order in range(0, 6):
for data_dt in dts:
these_data = data.astype(data_dt)
for coord_dt in dts:
# affine mapping
mat = np.eye(2, dtype=coord_dt)
off = np.zeros((2,), dtype=coord_dt)
out = ndimage.affine_transform(these_data, mat, off)
assert_array_almost_equal(these_data, out)
# map coordinates
coords_m1 = idx.astype(coord_dt) - 1
coords_p10 = idx.astype(coord_dt) + 10
out = ndimage.map_coordinates(these_data, coords_m1, order=order)
assert_array_almost_equal(out, shifted_data)
# check constant fill works
out = ndimage.map_coordinates(these_data, coords_p10, order=order)
assert_array_almost_equal(out, np.zeros((3,4)))
# check shift and zoom
out = ndimage.shift(these_data, 1)
assert_array_almost_equal(out, shifted_data)
out = ndimage.zoom(these_data, 1)
assert_array_almost_equal(these_data, out)
@pytest.mark.xfail(True, reason="Broken on many platforms")
def test_uint64_max():
# Test interpolation respects uint64 max. Reported to fail at least on
# win32 (due to the 32 bit visual C compiler using signed int64 when
# converting between uint64 to double) and Debian on s390x.
# Interpolation is always done in double precision floating point, so
# we use the largest uint64 value for which int(float(big)) still fits
# in a uint64.
# This test was last enabled on macOS only, and there it started failing
# on arm64 as well (see gh-19117).
big = 2**64 - 1025
arr = np.array([big, big, big], dtype=np.uint64)
# Tests geometric transform (map_coordinates, affine_transform)
inds = np.indices(arr.shape) - 0.1
x = ndimage.map_coordinates(arr, inds)
assert x[1] == int(float(big))
assert x[2] == int(float(big))
# Tests zoom / shift
x = ndimage.shift(arr, 0.1)
assert x[1] == int(float(big))
assert x[2] == int(float(big))

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,187 @@
import math
import numpy as np
from scipy._lib._array_api import (
xp_assert_equal,
assert_array_almost_equal,
assert_almost_equal,
is_cupy,
)
import pytest
from scipy import ndimage
skip_xp_backends = pytest.mark.skip_xp_backends
pytestmark = [skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'])]
@skip_xp_backends('jax.numpy', reason="jax-ml/jax#23827")
class TestNdimageFourier:
@pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
@pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
def test_fourier_gaussian_real01(self, shape, dtype, dec, xp):
fft = getattr(xp, 'fft')
a = np.zeros(shape, dtype=dtype)
a[0, 0] = 1.0
a = xp.asarray(a)
a = fft.rfft(a, n=shape[0], axis=0)
a = fft.fft(a, n=shape[1], axis=1)
a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0)
a = fft.ifft(a, n=shape[1], axis=1)
a = fft.irfft(a, n=shape[0], axis=0)
assert_almost_equal(ndimage.sum(a), xp.asarray(1), decimal=dec,
check_0d=False)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
@pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
def test_fourier_gaussian_complex01(self, shape, dtype, dec, xp):
fft = getattr(xp, 'fft')
a = np.zeros(shape, dtype=dtype)
a[0, 0] = 1.0
a = xp.asarray(a)
a = fft.fft(a, n=shape[0], axis=0)
a = fft.fft(a, n=shape[1], axis=1)
a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0)
a = fft.ifft(a, n=shape[1], axis=1)
a = fft.ifft(a, n=shape[0], axis=0)
assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
check_0d=False)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
@pytest.mark.parametrize('dtype, dec', [("float32", 6), ("float64", 14)])
def test_fourier_uniform_real01(self, shape, dtype, dec, xp):
fft = getattr(xp, 'fft')
a = np.zeros(shape, dtype=dtype)
a[0, 0] = 1.0
a = xp.asarray(a)
a = fft.rfft(a, n=shape[0], axis=0)
a = fft.fft(a, n=shape[1], axis=1)
a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0)
a = fft.ifft(a, n=shape[1], axis=1)
a = fft.irfft(a, n=shape[0], axis=0)
assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
check_0d=False)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
@pytest.mark.parametrize('dtype, dec', [("complex64", 6), ("complex128", 14)])
def test_fourier_uniform_complex01(self, shape, dtype, dec, xp):
fft = getattr(xp, 'fft')
a = np.zeros(shape, dtype=dtype)
a[0, 0] = 1.0
a = xp.asarray(a)
a = fft.fft(a, n=shape[0], axis=0)
a = fft.fft(a, n=shape[1], axis=1)
a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0)
a = fft.ifft(a, n=shape[1], axis=1)
a = fft.ifft(a, n=shape[0], axis=0)
assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
check_0d=False)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
@pytest.mark.parametrize('dtype, dec', [("float32", 4), ("float64", 11)])
def test_fourier_shift_real01(self, shape, dtype, dec, xp):
fft = getattr(xp, 'fft')
expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
expected = xp.asarray(expected)
a = fft.rfft(expected, n=shape[0], axis=0)
a = fft.fft(a, n=shape[1], axis=1)
a = ndimage.fourier_shift(a, [1, 1], shape[0], 0)
a = fft.ifft(a, n=shape[1], axis=1)
a = fft.irfft(a, n=shape[0], axis=0)
assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1], decimal=dec)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
@pytest.mark.parametrize('dtype, dec', [("complex64", 4), ("complex128", 11)])
def test_fourier_shift_complex01(self, shape, dtype, dec, xp):
fft = getattr(xp, 'fft')
expected = np.arange(shape[0] * shape[1], dtype=dtype).reshape(shape)
expected = xp.asarray(expected)
a = fft.fft(expected, n=shape[0], axis=0)
a = fft.fft(a, n=shape[1], axis=1)
a = ndimage.fourier_shift(a, [1, 1], -1, 0)
a = fft.ifft(a, n=shape[1], axis=1)
a = fft.ifft(a, n=shape[0], axis=0)
assert_array_almost_equal(xp.real(a)[1:, 1:], expected[:-1, :-1], decimal=dec)
assert_array_almost_equal(xp.imag(a), xp.zeros(shape), decimal=dec)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
@pytest.mark.parametrize('dtype, dec', [("float32", 5), ("float64", 14)])
def test_fourier_ellipsoid_real01(self, shape, dtype, dec, xp):
fft = getattr(xp, 'fft')
a = np.zeros(shape, dtype=dtype)
a[0, 0] = 1.0
a = xp.asarray(a)
a = fft.rfft(a, n=shape[0], axis=0)
a = fft.fft(a, n=shape[1], axis=1)
a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], shape[0], 0)
a = fft.ifft(a, n=shape[1], axis=1)
a = fft.irfft(a, n=shape[0], axis=0)
assert_almost_equal(ndimage.sum(a), xp.asarray(1.0), decimal=dec,
check_0d=False)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
@pytest.mark.parametrize('dtype, dec', [("complex64", 5), ("complex128", 14)])
def test_fourier_ellipsoid_complex01(self, shape, dtype, dec, xp):
fft = getattr(xp, 'fft')
a = np.zeros(shape, dtype=dtype)
a[0, 0] = 1.0
a = xp.asarray(a)
a = fft.fft(a, n=shape[0], axis=0)
a = fft.fft(a, n=shape[1], axis=1)
a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0)
a = fft.ifft(a, n=shape[1], axis=1)
a = fft.ifft(a, n=shape[0], axis=0)
assert_almost_equal(ndimage.sum(xp.real(a)), xp.asarray(1.0), decimal=dec,
check_0d=False)
def test_fourier_ellipsoid_unimplemented_ndim(self, xp):
# arrays with ndim > 3 raise NotImplementedError
x = xp.ones((4, 6, 8, 10), dtype=xp.complex128)
with pytest.raises(NotImplementedError):
ndimage.fourier_ellipsoid(x, 3)
def test_fourier_ellipsoid_1d_complex(self, xp):
# expected result of 1d ellipsoid is the same as for fourier_uniform
for shape in [(32, ), (31, )]:
for type_, dec in zip([xp.complex64, xp.complex128], [5, 14]):
x = xp.ones(shape, dtype=type_)
a = ndimage.fourier_ellipsoid(x, 5, -1, 0)
b = ndimage.fourier_uniform(x, 5, -1, 0)
assert_array_almost_equal(a, b, decimal=dec)
@pytest.mark.parametrize('shape', [(0, ), (0, 10), (10, 0)])
@pytest.mark.parametrize('dtype', ["float32", "float64",
"complex64", "complex128"])
@pytest.mark.parametrize('test_func',
[ndimage.fourier_ellipsoid,
ndimage.fourier_gaussian,
ndimage.fourier_uniform])
def test_fourier_zero_length_dims(self, shape, dtype, test_func, xp):
if (
is_cupy(xp)
and test_func.__name__ == "fourier_ellipsoid"
and math.prod(shape) == 0
):
pytest.xfail("CuPy's fourier_ellipsoid does not accept size==0 arrays")
dtype = getattr(xp, dtype)
a = xp.ones(shape, dtype=dtype)
b = test_func(a, 3)
xp_assert_equal(a, b)

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,78 @@
import pytest
import numpy as np
from .._ni_support import _get_output
@pytest.mark.parametrize(
'dtype',
[
# String specifiers
'f4', 'float32', 'complex64', 'complex128',
# Type and dtype specifiers
np.float32, float, np.dtype('f4'),
# Derive from input
None,
],
)
def test_get_output_basic(dtype):
shape = (2, 3)
input_ = np.zeros(shape, dtype='float32')
# For None, derive dtype from input
expected_dtype = 'float32' if dtype is None else dtype
# Output is dtype-specifier, retrieve shape from input
result = _get_output(dtype, input_)
assert result.shape == shape
assert result.dtype == np.dtype(expected_dtype)
# Output is dtype specifier, with explicit shape, overriding input
result = _get_output(dtype, input_, shape=(3, 2))
assert result.shape == (3, 2)
assert result.dtype == np.dtype(expected_dtype)
# Output is pre-allocated array, return directly
output = np.zeros(shape, dtype=dtype)
result = _get_output(output, input_)
assert result is output
@pytest.mark.thread_unsafe
def test_get_output_complex():
shape = (2, 3)
input_ = np.zeros(shape)
# None, promote input type to complex
result = _get_output(None, input_, complex_output=True)
assert result.shape == shape
assert result.dtype == np.dtype('complex128')
# Explicit type, promote type to complex
with pytest.warns(UserWarning, match='promoting specified output dtype to complex'):
result = _get_output(float, input_, complex_output=True)
assert result.shape == shape
assert result.dtype == np.dtype('complex128')
# String specifier, simply verify complex output
result = _get_output('complex64', input_, complex_output=True)
assert result.shape == shape
assert result.dtype == np.dtype('complex64')
def test_get_output_error_cases():
input_ = np.zeros((2, 3), 'float32')
# Two separate paths can raise the same error
with pytest.raises(RuntimeError, match='output must have complex dtype'):
_get_output('float32', input_, complex_output=True)
with pytest.raises(RuntimeError, match='output must have complex dtype'):
_get_output(np.zeros((2, 3)), input_, complex_output=True)
with pytest.raises(RuntimeError, match='output must have numeric dtype'):
_get_output('void', input_)
with pytest.raises(RuntimeError, match='shape not correct'):
_get_output(np.zeros((3, 2)), input_)

View file

@ -0,0 +1,70 @@
"""Tests for spline filtering."""
import pytest
import numpy as np
from scipy._lib._array_api import assert_almost_equal
from scipy import ndimage
skip_xp_backends = pytest.mark.skip_xp_backends
pytestmark = [skip_xp_backends(cpu_only=True, exceptions=['cupy', 'jax.numpy'])]
def get_spline_knot_values(order):
"""Knot values to the right of a B-spline's center."""
knot_values = {0: [1],
1: [1],
2: [6, 1],
3: [4, 1],
4: [230, 76, 1],
5: [66, 26, 1]}
return knot_values[order]
def make_spline_knot_matrix(xp, n, order, mode='mirror'):
"""Matrix to invert to find the spline coefficients."""
knot_values = get_spline_knot_values(order)
# NB: do computations with numpy, convert to xp as the last step only
matrix = np.zeros((n, n))
for diag, knot_value in enumerate(knot_values):
indices = np.arange(diag, n)
if diag == 0:
matrix[indices, indices] = knot_value
else:
matrix[indices, indices - diag] = knot_value
matrix[indices - diag, indices] = knot_value
knot_values_sum = knot_values[0] + 2 * sum(knot_values[1:])
if mode == 'mirror':
start, step = 1, 1
elif mode == 'reflect':
start, step = 0, 1
elif mode == 'grid-wrap':
start, step = -1, -1
else:
raise ValueError(f'unsupported mode {mode}')
for row in range(len(knot_values) - 1):
for idx, knot_value in enumerate(knot_values[row + 1:]):
matrix[row, start + step*idx] += knot_value
matrix[-row - 1, -start - 1 - step*idx] += knot_value
return xp.asarray(matrix / knot_values_sum)
@pytest.mark.parametrize('order', [0, 1, 2, 3, 4, 5])
@pytest.mark.parametrize('mode', ['mirror', 'grid-wrap', 'reflect'])
def test_spline_filter_vs_matrix_solution(order, mode, xp):
n = 100
eye = xp.eye(n, dtype=xp.float64)
spline_filter_axis_0 = ndimage.spline_filter1d(eye, axis=0, order=order,
mode=mode)
spline_filter_axis_1 = ndimage.spline_filter1d(eye, axis=1, order=order,
mode=mode)
matrix = make_spline_knot_matrix(xp, n, order, mode=mode)
assert_almost_equal(eye, spline_filter_axis_0 @ matrix)
assert_almost_equal(eye, spline_filter_axis_1 @ matrix.T)