This commit is contained in:
2024-11-29 18:15:30 +00:00
parent 40aade2d8e
commit bc9415586e
5298 changed files with 1938676 additions and 80 deletions

View File

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

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,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 <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
}
docfiller = doccer.filldoc(docdict)

View File

@ -0,0 +1,119 @@
# 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):
"""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':
return 5
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 isinstance(input, Iterable):
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)
elif 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

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

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 0 1 0 0 0
1 0 1 0 1 0 1
1 1 0 0 0 1 1
1 1 1 0 1 1 1
1 0 1 1 1 0 1
0 0 0 1 0 0 0
1 0 0 1 0 0 1
1 1 1 1 1 1 1
1 0 0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 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 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)

View File

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

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,137 @@
import numpy as np
from numpy import fft
from numpy.testing import (assert_almost_equal, assert_array_almost_equal,
assert_equal)
import pytest
from scipy import ndimage
class TestNdimageFourier:
@pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
@pytest.mark.parametrize('dtype, dec', [(np.float32, 6), (np.float64, 14)])
def test_fourier_gaussian_real01(self, shape, dtype, dec):
a = np.zeros(shape, dtype)
a[0, 0] = 1.0
a = fft.rfft(a, shape[0], 0)
a = fft.fft(a, shape[1], 1)
a = ndimage.fourier_gaussian(a, [5.0, 2.5], shape[0], 0)
a = fft.ifft(a, shape[1], 1)
a = fft.irfft(a, shape[0], 0)
assert_almost_equal(ndimage.sum(a), 1, decimal=dec)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
@pytest.mark.parametrize('dtype, dec', [(np.complex64, 6), (np.complex128, 14)])
def test_fourier_gaussian_complex01(self, shape, dtype, dec):
a = np.zeros(shape, dtype)
a[0, 0] = 1.0
a = fft.fft(a, shape[0], 0)
a = fft.fft(a, shape[1], 1)
a = ndimage.fourier_gaussian(a, [5.0, 2.5], -1, 0)
a = fft.ifft(a, shape[1], 1)
a = fft.ifft(a, shape[0], 0)
assert_almost_equal(ndimage.sum(a.real), 1.0, decimal=dec)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
@pytest.mark.parametrize('dtype, dec', [(np.float32, 6), (np.float64, 14)])
def test_fourier_uniform_real01(self, shape, dtype, dec):
a = np.zeros(shape, dtype)
a[0, 0] = 1.0
a = fft.rfft(a, shape[0], 0)
a = fft.fft(a, shape[1], 1)
a = ndimage.fourier_uniform(a, [5.0, 2.5], shape[0], 0)
a = fft.ifft(a, shape[1], 1)
a = fft.irfft(a, shape[0], 0)
assert_almost_equal(ndimage.sum(a), 1.0, decimal=dec)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
@pytest.mark.parametrize('dtype, dec', [(np.complex64, 6), (np.complex128, 14)])
def test_fourier_uniform_complex01(self, shape, dtype, dec):
a = np.zeros(shape, dtype)
a[0, 0] = 1.0
a = fft.fft(a, shape[0], 0)
a = fft.fft(a, shape[1], 1)
a = ndimage.fourier_uniform(a, [5.0, 2.5], -1, 0)
a = fft.ifft(a, shape[1], 1)
a = fft.ifft(a, shape[0], 0)
assert_almost_equal(ndimage.sum(a.real), 1.0, decimal=dec)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
@pytest.mark.parametrize('dtype, dec', [(np.float32, 4), (np.float64, 11)])
def test_fourier_shift_real01(self, shape, dtype, dec):
expected = np.arange(shape[0] * shape[1], dtype=dtype)
expected.shape = shape
a = fft.rfft(expected, shape[0], 0)
a = fft.fft(a, shape[1], 1)
a = ndimage.fourier_shift(a, [1, 1], shape[0], 0)
a = fft.ifft(a, shape[1], 1)
a = fft.irfft(a, shape[0], 0)
assert_array_almost_equal(a[1:, 1:], expected[:-1, :-1], decimal=dec)
assert_array_almost_equal(a.imag, np.zeros(shape), decimal=dec)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
@pytest.mark.parametrize('dtype, dec', [(np.complex64, 4), (np.complex128, 11)])
def test_fourier_shift_complex01(self, shape, dtype, dec):
expected = np.arange(shape[0] * shape[1], dtype=dtype)
expected.shape = shape
a = fft.fft(expected, shape[0], 0)
a = fft.fft(a, shape[1], 1)
a = ndimage.fourier_shift(a, [1, 1], -1, 0)
a = fft.ifft(a, shape[1], 1)
a = fft.ifft(a, shape[0], 0)
assert_array_almost_equal(a.real[1:, 1:], expected[:-1, :-1], decimal=dec)
assert_array_almost_equal(a.imag, np.zeros(shape), decimal=dec)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15), (1, 10)])
@pytest.mark.parametrize('dtype, dec', [(np.float32, 5), (np.float64, 14)])
def test_fourier_ellipsoid_real01(self, shape, dtype, dec):
a = np.zeros(shape, dtype)
a[0, 0] = 1.0
a = fft.rfft(a, shape[0], 0)
a = fft.fft(a, shape[1], 1)
a = ndimage.fourier_ellipsoid(a, [5.0, 2.5],
shape[0], 0)
a = fft.ifft(a, shape[1], 1)
a = fft.irfft(a, shape[0], 0)
assert_almost_equal(ndimage.sum(a), 1.0, decimal=dec)
@pytest.mark.parametrize('shape', [(32, 16), (31, 15)])
@pytest.mark.parametrize('dtype, dec', [(np.complex64, 5), (np.complex128, 14)])
def test_fourier_ellipsoid_complex01(self, shape, dtype, dec):
a = np.zeros(shape, dtype)
a[0, 0] = 1.0
a = fft.fft(a, shape[0], 0)
a = fft.fft(a, shape[1], 1)
a = ndimage.fourier_ellipsoid(a, [5.0, 2.5], -1, 0)
a = fft.ifft(a, shape[1], 1)
a = fft.ifft(a, shape[0], 0)
assert_almost_equal(ndimage.sum(a.real), 1.0, decimal=dec)
def test_fourier_ellipsoid_unimplemented_ndim(self):
# arrays with ndim > 3 raise NotImplementedError
x = np.ones((4, 6, 8, 10), dtype=np.complex128)
with pytest.raises(NotImplementedError):
ndimage.fourier_ellipsoid(x, 3)
def test_fourier_ellipsoid_1d_complex(self):
# expected result of 1d ellipsoid is the same as for fourier_uniform
for shape in [(32, ), (31, )]:
for type_, dec in zip([np.complex64, np.complex128], [5, 14]):
x = np.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', [np.float32, np.float64,
np.complex64, np.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):
a = np.ones(shape, dtype)
b = test_func(a, 3)
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,77 @@
import pytest
import numpy as np
from .._ni_support import _get_output
@pytest.mark.parametrize(
'dtype',
[
# String specifiers
'f4', 'float32', 'complex64', 'complex128',
# Type and dtype specifiers
np.float32, float, np.dtype('f4'),
# Derive from input
None,
],
)
def test_get_output_basic(dtype):
shape = (2, 3)
input_ = np.zeros(shape, '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)
result = _get_output(output, input_)
assert result is output
def test_get_output_complex():
shape = (2, 3)
input_ = np.zeros(shape)
# None, promote input type to complex
result = _get_output(None, input_, complex_output=True)
assert result.shape == shape
assert result.dtype == np.dtype('complex128')
# Explicit type, promote type to complex
with pytest.warns(UserWarning, match='promoting specified output dtype to complex'):
result = _get_output(float, input_, complex_output=True)
assert result.shape == shape
assert result.dtype == np.dtype('complex128')
# String specifier, simply verify complex output
result = _get_output('complex64', input_, complex_output=True)
assert result.shape == shape
assert result.dtype == np.dtype('complex64')
def test_get_output_error_cases():
input_ = np.zeros((2, 3), 'float32')
# Two separate paths can raise the same error
with pytest.raises(RuntimeError, match='output must have complex dtype'):
_get_output('float32', input_, complex_output=True)
with pytest.raises(RuntimeError, match='output must have complex dtype'):
_get_output(np.zeros((2, 3)), input_, complex_output=True)
with pytest.raises(RuntimeError, match='output must have numeric dtype'):
_get_output('void', input_)
with pytest.raises(RuntimeError, match='shape not correct'):
_get_output(np.zeros((3, 2)), input_)

View File

@ -0,0 +1,65 @@
"""Tests for spline filtering."""
import numpy as np
import pytest
from numpy.testing import assert_almost_equal
from scipy import ndimage
def get_spline_knot_values(order):
"""Knot values to the right of a B-spline's center."""
knot_values = {0: [1],
1: [1],
2: [6, 1],
3: [4, 1],
4: [230, 76, 1],
5: [66, 26, 1]}
return knot_values[order]
def make_spline_knot_matrix(n, order, mode='mirror'):
"""Matrix to invert to find the spline coefficients."""
knot_values = get_spline_knot_values(order)
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 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):
n = 100
eye = np.eye(n, dtype=float)
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(n, order, mode=mode)
assert_almost_equal(eye, np.dot(spline_filter_axis_0, matrix))
assert_almost_equal(eye, np.dot(spline_filter_axis_1, matrix.T))