CuPy: NumPy & SciPy for GPU - CUDA 11.x optimized distribution providing GPU-accelerated computing with Python
—
CuPy provides comprehensive SciPy-compatible extensions through the cupyx.scipy module, offering GPU-accelerated implementations of scientific computing functions including sparse matrices, signal processing, image processing, linear algebra, optimization, and statistical operations.
Utility functions for determining appropriate array modules in generic code.
def get_array_module(*args):
"""
Get the appropriate array module (cupyx.scipy or scipy) based on input arrays.
Parameters:
args: array_like - Input arrays to inspect
Returns:
module - cupyx.scipy if any input is a CuPy array, otherwise scipy
"""SciPy-compatible FFT operations with additional functionality beyond cupy.fft.
# Real FFT functions with SciPy compatibility
def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False):
"""
Compute the 1D discrete Fourier Transform for real input.
Parameters:
x: array_like - Input array
n: int, optional - Number of points along transformation axis
axis: int, optional - Axis over which to compute the FFT
norm: {None, 'ortho'}, optional - Normalization mode
overwrite_x: bool, optional - If True, the contents of x can be destroyed
"""
def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False):
"""
Compute the inverse of the 1D discrete Fourier Transform for real input.
Parameters:
x: array_like - Input array
n: int, optional - Length of the transformed axis of the output
axis: int, optional - Axis over which to compute the FFT
norm: {None, 'ortho'}, optional - Normalization mode
overwrite_x: bool, optional - If True, the contents of x can be destroyed
"""
# Discrete Cosine Transform
def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
"""
Return the Discrete Cosine Transform of arbitrary type sequence x.
Parameters:
x: array_like - Input array
type: {1, 2, 3, 4}, optional - Type of the DCT (default is 2)
n: int, optional - Length of the transform
axis: int, optional - Axis along which the dct is computed
norm: {None, 'ortho'}, optional - Normalization mode
overwrite_x: bool, optional - If True, the contents of x can be destroyed
"""
def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
"""
Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.
Parameters:
x: array_like - Input array
type: {1, 2, 3, 4}, optional - Type of the DCT (default is 2)
n: int, optional - Length of the transform
axis: int, optional - Axis along which the idct is computed
norm: {None, 'ortho'}, optional - Normalization mode
overwrite_x: bool, optional - If True, the contents of x can be destroyed
"""
# Discrete Sine Transform
def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
"""
Return the Discrete Sine Transform of arbitrary type sequence x.
Parameters:
x: array_like - Input array
type: {1, 2, 3, 4}, optional - Type of the DST (default is 2)
n: int, optional - Length of the transform
axis: int, optional - Axis along which the dst is computed
norm: {None, 'ortho'}, optional - Normalization mode
overwrite_x: bool, optional - If True, the contents of x can be destroyed
"""
def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):
"""
Return the Inverse Discrete Sine Transform of an arbitrary type sequence.
Parameters:
x: array_like - Input array
type: {1, 2, 3, 4}, optional - Type of the DST (default is 2)
n: int, optional - Length of the transform
axis: int, optional - Axis along which the idst is computed
norm: {None, 'ortho'}, optional - Normalization mode
overwrite_x: bool, optional - If True, the contents of x can be destroyed
"""Extended linear algebra operations beyond cupy.linalg with SciPy compatibility.
def solve_banded(l_and_u, ab, b, overwrite_ab=False, overwrite_b=False, debug=None, check_finite=True):
"""
Solve the equation a x = b for x, assuming a is banded matrix.
Parameters:
l_and_u: (integer, integer) - Number of non-zero lower and upper diagonals
ab: (l_and_u[0] + l_and_u[1] + 1, M) array_like - Banded matrix
b: (M,) or (M, K) array_like - Right-hand side
overwrite_ab: bool, optional - Discard data in ab (may enhance performance)
overwrite_b: bool, optional - Discard data in b (may enhance performance)
debug: None - Reserved for future use
check_finite: bool, optional - Check that input matrices contain only finite numbers
"""
def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False, overwrite_b=False, debug=None, check_finite=True):
"""
Solve the equation a x = b for x, assuming a is a triangular matrix.
Parameters:
a: (M, M) array_like - Triangular matrix
b: (M,) or (M, N) array_like - Right-hand side matrix or vector
trans: {0, 1, 2, 'N', 'T', 'C'}, optional - Type of system to solve
lower: bool, optional - Use only data contained in the lower triangle of a
unit_diagonal: bool, optional - If True, diagonal elements of a are assumed to be 1
overwrite_b: bool, optional - Allow overwriting data in b
debug: None - Reserved for future use
check_finite: bool, optional - Check that input matrices contain only finite numbers
"""
def lu_factor(a, overwrite_a=False, check_finite=True):
"""
Compute pivoted LU decomposition of a matrix.
Parameters:
a: (M, N) array_like - Matrix to decompose
overwrite_a: bool, optional - Allow data in a to be overwritten
check_finite: bool, optional - Check that input matrix contains only finite numbers
"""
def lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True):
"""
Solve an equation system, a x = b, given the LU factorization of a.
Parameters:
lu_and_piv: tuple - LU factorization of matrix a, as given by lu_factor
b: array - Right-hand side
trans: {0, 1, 2}, optional - Type of system to solve
overwrite_b: bool, optional - Allow data in b to be overwritten
check_finite: bool, optional - Check that input arrays contain only finite numbers
"""
def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):
"""
Compute the Cholesky decomposition of a matrix.
Parameters:
a: (M, M) array_like - Matrix to be decomposed
lower: bool, optional - Whether to compute the upper or lower triangular Cholesky factorization
overwrite_a: bool, optional - Allow data in a to be overwritten
check_finite: bool, optional - Check that input matrix contains only finite numbers
"""
def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):
"""
Solve the linear equations A x = b, given the Cholesky factorization of A.
Parameters:
c_and_lower: tuple - Cholesky factorization of a, as given by cho_factor
b: array - Right-hand side
overwrite_b: bool, optional - Allow data in b to be overwritten
check_finite: bool, optional - Check that input arrays contain only finite numbers
"""
def block_diag(*arrs):
"""
Create a block diagonal matrix from provided arrays.
Parameters:
arrs: sequence of array_like - Input arrays
"""
def tril(m, k=0):
"""
Make a copy of a matrix with elements above the k-th diagonal zeroed.
Parameters:
m: array_like - Matrix whose lower triangle is desired
k: int, optional - Diagonal above which to zero elements
"""
def triu(m, k=0):
"""
Make a copy of a matrix with elements below the k-th diagonal zeroed.
Parameters:
m: array_like - Matrix whose upper triangle is desired
k: int, optional - Diagonal below which to zero elements
"""Comprehensive sparse matrix operations and formats for memory-efficient computation.
class spmatrix:
"""
Base sparse matrix class.
This is the base class for all sparse matrix formats in CuPy.
"""
def __init__(self): ...
def toarray(self): ...
def tocsr(self, copy=False): ...
def tocsc(self, copy=False): ...
def tocoo(self, copy=False): ...
def todia(self, copy=False): ...
def todense(self): ...
def multiply(self, other): ...
def maximum(self, other): ...
def minimum(self, other): ...
@property
def shape(self): ...
@property
def dtype(self): ...
@property
def nnz(self): ...
class csr_matrix(spmatrix):
"""
Compressed Sparse Row matrix.
Efficient for arithmetic operations and matrix-vector products.
"""
def __init__(self, arg1, shape=None, dtype=None, copy=False): ...
def eliminate_zeros(self): ...
def sum_duplicates(self): ...
def sort_indices(self): ...
def has_sorted_indices(self): ...
class csc_matrix(spmatrix):
"""
Compressed Sparse Column matrix.
Efficient for column slicing and operations requiring column access.
"""
def __init__(self, arg1, shape=None, dtype=None, copy=False): ...
def eliminate_zeros(self): ...
def sum_duplicates(self): ...
def sort_indices(self): ...
def has_sorted_indices(self): ...
class coo_matrix(spmatrix):
"""
A sparse matrix in COOrdinate format (aka triplet format).
Efficient for constructing sparse matrices incrementally.
"""
def __init__(self, arg1, shape=None, dtype=None, copy=False): ...
def eliminate_zeros(self): ...
def sum_duplicates(self): ...
class dia_matrix(spmatrix):
"""
Sparse matrix with DIAgonal storage.
Efficient for matrices with few diagonals.
"""
def __init__(self, arg1, shape=None, dtype=None, copy=False): ...
# Sparse matrix construction functions
def eye(m, n=None, k=0, dtype=float, format=None):
"""
Sparse identity matrix.
Parameters:
m: int - Number of rows
n: int, optional - Number of columns (default equals m)
k: int, optional - Diagonal offset
dtype: dtype, optional - Data type of the matrix
format: str, optional - Sparse format of the result
"""
def identity(n, dtype='d', format=None):
"""
Identity matrix in sparse format.
Parameters:
n: int - Size of the identity matrix
dtype: dtype, optional - Data type of the matrix
format: str, optional - Sparse format of the result
"""
def spdiags(data, diags, m, n, format=None):
"""
Return a sparse matrix from diagonals.
Parameters:
data: array_like - Matrix diagonals stored row-wise
diags: sequence - Diagonal offsets
m, n: int - Shape of the result
format: str, optional - Sparse format of the result
"""
def diags(diagonals, offsets=0, shape=None, format=None, dtype=None):
"""
Construct a sparse matrix from diagonals.
Parameters:
diagonals: sequence of array_like - Diagonal values
offsets: sequence of int or int - Diagonal offsets
shape: tuple, optional - Shape of the result
format: str, optional - Sparse format of the result
dtype: dtype, optional - Data type of the result
"""
def rand(m, n, density=0.01, format='coo', dtype=None, random_state=None):
"""
Generate a sparse matrix of the given shape and density with uniformly distributed values.
Parameters:
m, n: int - Shape of the matrix
density: real, optional - Density of the generated matrix
format: str, optional - Sparse format of the result
dtype: dtype, optional - Type of the returned matrix values
random_state: int or RandomState, optional - Random number generator seed
"""
def random(m, n, density=0.01, format='coo', dtype=None, random_state=None, data_rvs=None):
"""
Generate a sparse matrix of the given shape and density with random values.
Parameters:
m, n: int - Shape of the matrix
density: real, optional - Density of the generated matrix
format: str, optional - Sparse format of the result
dtype: dtype, optional - Type of the returned matrix values
random_state: int or RandomState, optional - Random number generator seed
data_rvs: callable, optional - Samples the data values (default uniform on [0,1))
"""
# Sparse matrix operations
def kron(A, B, format=None):
"""
Kronecker product of two sparse matrices.
Parameters:
A, B: sparse or dense matrices - Input matrices
format: str, optional - Format of the result
"""
def kronsum(A, B, format=None):
"""
Kronecker sum of two sparse matrices.
Parameters:
A, B: sparse matrices - Input matrices
format: str, optional - Format of the result
"""
def hstack(blocks, format=None, dtype=None):
"""
Stack sparse matrices horizontally (column wise).
Parameters:
blocks: sequence - Sparse matrices with compatible first dimensions
format: str, optional - Format of the result
dtype: dtype, optional - Type of the result
"""
def vstack(blocks, format=None, dtype=None):
"""
Stack sparse matrices vertically (row wise).
Parameters:
blocks: sequence - Sparse matrices with compatible second dimensions
format: str, optional - Format of the result
dtype: dtype, optional - Type of the result
"""
def bmat(blocks, format=None, dtype=None):
"""
Build a sparse matrix from sparse sub-blocks.
Parameters:
blocks: array_like - Grid of sparse matrices
format: str, optional - Format of the result
dtype: dtype, optional - Type of the result
"""
# Sparse matrix utilities
def issparse(x):
"""
Check whether x is a sparse matrix.
Parameters:
x: any - Object to check
"""
def isspmatrix(x):
"""
Check whether x is a sparse matrix (alias for issparse).
Parameters:
x: any - Object to check
"""
def isspmatrix_csr(x):
"""
Check whether x is a CSR matrix.
Parameters:
x: any - Object to check
"""
def isspmatrix_csc(x):
"""
Check whether x is a CSC matrix.
Parameters:
x: any - Object to check
"""
def isspmatrix_coo(x):
"""
Check whether x is a COO matrix.
Parameters:
x: any - Object to check
"""
def find(A):
"""
Return the indices and values of the nonzero elements of a matrix.
Parameters:
A: sparse matrix - Input matrix
"""
def tril(A, k=0, format=None):
"""
Return the lower triangular portion of a matrix in sparse format.
Parameters:
A: sparse matrix - Input matrix
k: int, optional - Diagonal offset
format: str, optional - Sparse format of the result
"""
def triu(A, k=0, format=None):
"""
Return the upper triangular portion of a matrix in sparse format.
Parameters:
A: sparse matrix - Input matrix
k: int, optional - Diagonal offset
format: str, optional - Sparse format of the result
"""Signal processing operations including filtering, convolution, and spectral analysis.
def convolve(in1, in2, mode='full', method='auto'):
"""
Convolve two N-dimensional arrays.
Parameters:
in1: array_like - First input array
in2: array_like - Second input array
mode: str, optional - Size of output ('full', 'valid', 'same')
method: str, optional - Method to use for convolution ('auto', 'direct', 'fft')
"""
def correlate(in1, in2, mode='full', method='auto'):
"""
Cross-correlate two N-dimensional arrays.
Parameters:
in1: array_like - First input array
in2: array_like - Second input array
mode: str, optional - Size of output ('full', 'valid', 'same')
method: str, optional - Method to use for correlation ('auto', 'direct', 'fft')
"""
def fftconvolve(in1, in2, mode='full', axes=None):
"""
Convolve two N-dimensional arrays using FFT.
Parameters:
in1: array_like - First input array
in2: array_like - Second input array
mode: str, optional - Size of output ('full', 'valid', 'same')
axes: int or array_like of ints or None, optional - Axes over which to compute convolution
"""
def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0):
"""
Convolve two 2-dimensional arrays.
Parameters:
in1: array_like - First input array
in2: array_like - Second input array
mode: str, optional - Size of output ('full', 'valid', 'same')
boundary: str, optional - Flag indicating how to handle boundaries
fillvalue: scalar, optional - Value to fill pad input arrays with
"""
def correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0):
"""
Cross-correlate two 2-dimensional arrays.
Parameters:
in1: array_like - First input array
in2: array_like - Second input array
mode: str, optional - Size of output ('full', 'valid', 'same')
boundary: str, optional - Flag indicating how to handle boundaries
fillvalue: scalar, optional - Value to fill pad input arrays with
"""
def sepfir2d(input, hrow, hcol):
"""
Convolve with a 2-D separable FIR filter.
Parameters:
input: array_like - Input array to filter
hrow: array_like - 1-D filter for rows
hcol: array_like - 1-D filter for columns
"""
def lfilter(b, a, x, axis=-1, zi=None):
"""
Filter data along one-dimension with an IIR or FIR filter.
Parameters:
b: array_like - Numerator coefficient vector
a: array_like - Denominator coefficient vector
x: array_like - Input data array
axis: int, optional - Axis of x to which the filter is applied
zi: array_like, optional - Initial conditions for the filter delays
"""
def filtfilt(b, a, x, axis=-1, padtype='odd', padlen=None, method='pad', irlen=None):
"""
Apply a digital filter forward and backward to a signal.
Parameters:
b: array_like - Numerator coefficient vector
a: array_like - Denominator coefficient vector
x: array_like - Input data array
axis: int, optional - Axis of x to which the filter is applied
padtype: str or None, optional - Type of padding to use
padlen: int or None, optional - Number of elements by which to extend x
method: str, optional - Determines the method for handling the edges
irlen: int or None, optional - Length of impulse response of filter
"""
def hilbert(x, N=None, axis=-1):
"""
Compute the analytic signal, using the Hilbert transform.
Parameters:
x: array_like - Signal data
N: int, optional - Length of the Hilbert transform
axis: int, optional - Axis along which to do the transformation
"""
def hilbert2(x, N=None):
"""
Compute the '2-D' analytic signal of x.
Parameters:
x: array_like - 2-D signal data
N: int or array_like of two ints, optional - Length of the Hilbert transform
"""
# Window functions
def get_window(window, Nx, fftbins=True):
"""
Return a window function.
Parameters:
window: string, float, or tuple - Type of window to create
Nx: int - Length of the window
fftbins: bool, optional - Generate symmetric window for use in filter design
"""
def hann(M, sym=True):
"""
Return a Hann window.
Parameters:
M: int - Number of points in the output window
sym: bool, optional - Generate symmetric window
"""
def hamming(M, sym=True):
"""
Return a Hamming window.
Parameters:
M: int - Number of points in the output window
sym: bool, optional - Generate symmetric window
"""
def blackman(M, sym=True):
"""
Return a Blackman window.
Parameters:
M: int - Number of points in the output window
sym: bool, optional - Generate symmetric window
"""N-dimensional image processing operations including filtering, morphology, and geometric transformations.
def gaussian_filter(input, sigma, order=0, output=None, mode='reflect', cval=0.0, truncate=4.0):
"""
Multidimensional Gaussian filter.
Parameters:
input: array_like - Input array
sigma: scalar or sequence of scalars - Standard deviation for Gaussian kernel
order: int or sequence of ints, optional - Order of the filter along each axis
output: array or dtype, optional - Array in which to place the output
mode: str or sequence, optional - Points outside boundaries are filled according to the given mode
cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'
truncate: float, optional - Truncate the filter at this many standard deviations
"""
def uniform_filter(input, size=3, output=None, mode='reflect', cval=0.0, origin=0):
"""
Multidimensional uniform filter.
Parameters:
input: array_like - Input array
size: int or sequence of ints - Shape that is taken from the input array
output: array or dtype, optional - Array in which to place the output
mode: str, optional - Points outside boundaries are filled according to the given mode
cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'
origin: int or sequence, optional - Controls the placement of the filter on the input array
"""
def median_filter(input, size=None, footprint=None, output=None, mode='reflect', cval=0.0, origin=0):
"""
Calculate a multidimensional median filter.
Parameters:
input: array_like - Input array
size: scalar or tuple, optional - See footprint, below. Ignored if footprint is given
footprint: array, optional - Either size or footprint must be defined
output: array or dtype, optional - Array in which to place the output
mode: str, optional - Points outside boundaries are filled according to the given mode
cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'
origin: int or sequence, optional - Controls the placement of the filter on the input array
"""
def maximum_filter(input, size=None, footprint=None, output=None, mode='reflect', cval=0.0, origin=0):
"""
Calculate a multidimensional maximum filter.
Parameters:
input: array_like - Input array
size: scalar or tuple, optional - See footprint, below. Ignored if footprint is given
footprint: array, optional - Either size or footprint must be defined
output: array or dtype, optional - Array in which to place the output
mode: str, optional - Points outside boundaries are filled according to the given mode
cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'
origin: int or sequence, optional - Controls the placement of the filter on the input array
"""
def minimum_filter(input, size=None, footprint=None, output=None, mode='reflect', cval=0.0, origin=0):
"""
Calculate a multidimensional minimum filter.
Parameters:
input: array_like - Input array
size: scalar or tuple, optional - See footprint, below. Ignored if footprint is given
footprint: array, optional - Either size or footprint must be defined
output: array or dtype, optional - Array in which to place the output
mode: str, optional - Points outside boundaries are filled according to the given mode
cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'
origin: int or sequence, optional - Controls the placement of the filter on the input array
"""
def rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=1, mode='constant', cval=0.0, prefilter=True):
"""
Rotate an array.
Parameters:
input: array_like - Input array
angle: float - Rotation angle in degrees
axes: tuple of 2 ints, optional - Plane of rotation specified by axes
reshape: bool, optional - Reshape the output array so that the input array is contained completely
output: array or dtype, optional - Array in which to place the output
order: int, optional - Spline interpolation order (0-5)
mode: str, optional - Points outside boundaries are filled according to the given mode
cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'
prefilter: bool, optional - Apply spline filter before interpolation
"""
def zoom(input, zoom, output=None, order=1, mode='constant', cval=0.0, prefilter=True):
"""
Zoom an array.
Parameters:
input: array_like - Input array
zoom: float or sequence - Zoom factor along the axes
output: array or dtype, optional - Array in which to place the output
order: int, optional - Spline interpolation order (0-5)
mode: str, optional - Points outside boundaries are filled according to the given mode
cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'
prefilter: bool, optional - Apply spline filter before interpolation
"""
def shift(input, shift, output=None, order=1, mode='constant', cval=0.0, prefilter=True):
"""
Shift an array.
Parameters:
input: array_like - Input array
shift: float or sequence - Shift along the axes
output: array or dtype, optional - Array in which to place the output
order: int, optional - Spline interpolation order (0-5)
mode: str, optional - Points outside boundaries are filled according to the given mode
cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'
prefilter: bool, optional - Apply spline filter before interpolation
"""
def affine_transform(input, matrix, offset=0.0, output_shape=None, output=None, order=1, mode='constant', cval=0.0, prefilter=True):
"""
Apply an affine transformation.
Parameters:
input: array_like - Input array
matrix: ndarray - Transformation matrix
offset: float or sequence, optional - Offset vector
output_shape: tuple of ints, optional - Shape of the output array
output: array or dtype, optional - Array in which to place the output
order: int, optional - Spline interpolation order (0-5)
mode: str, optional - Points outside boundaries are filled according to the given mode
cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'
prefilter: bool, optional - Apply spline filter before interpolation
"""
# Morphological operations
def binary_erosion(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False):
"""
Multidimensional binary erosion with the given structuring element.
Parameters:
input: array_like - Binary array_like to be eroded
structure: array_like, optional - Structuring element used for the erosion
iterations: int, optional - Number of times to repeat the erosion
mask: array_like, optional - Mask array that defines (>0) pixels that are considered
output: ndarray, optional - Array of the same shape as input for the output
border_value: int (cast to 0 or 1), optional - Value at the border in the output array
origin: int or tuple of ints, optional - Placement of the filter
brute_force: boolean, optional - Memory condition: if False, only the pixels whose value was changed are tracked
"""
def binary_dilation(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False):
"""
Multidimensional binary dilation with the given structuring element.
Parameters:
input: array_like - Binary array_like to be dilated
structure: array_like, optional - Structuring element used for the dilation
iterations: int, optional - Number of times to repeat the dilation
mask: array_like, optional - Mask array that defines (>0) pixels that are considered
output: ndarray, optional - Array of the same shape as input for the output
border_value: int (cast to 0 or 1), optional - Value at the border in the output array
origin: int or tuple of ints, optional - Placement of the filter
brute_force: boolean, optional - Memory condition: if False, only the pixels whose value was changed are tracked
"""
def binary_opening(input, structure=None, iterations=1, output=None, origin=0):
"""
Multidimensional binary opening with the given structuring element.
Parameters:
input: array_like - Binary array_like to be opened
structure: array_like, optional - Structuring element used for the opening
iterations: int, optional - Number of times to repeat the operation
output: ndarray, optional - Array of the same shape as input for the output
origin: int or tuple of ints, optional - Placement of the filter
"""
def binary_closing(input, structure=None, iterations=1, output=None, origin=0):
"""
Multidimensional binary closing with the given structuring element.
Parameters:
input: array_like - Binary array_like to be closed
structure: array_like, optional - Structuring element used for the closing
iterations: int, optional - Number of times to repeat the operation
output: ndarray, optional - Array of the same shape as input for the output
origin: int or tuple of ints, optional - Placement of the filter
"""
# Label and connectivity
def label(input, structure=None, output=None):
"""
Label features in an array.
Parameters:
input: array of ints - Input array
structure: array of ints, optional - Structuring element that defines feature connections
output: (None, data-type, array of data-type), optional - Array of the same shape as input
"""
def find_objects(input, max_label=0):
"""
Find objects in a labeled array.
Parameters:
input: ndarray of ints - Array containing integer objects
max_label: int, optional - Maximum label to search for
"""
def center_of_mass(input, labels=None, index=None):
"""
Calculate the center of mass of the values of an array at labels.
Parameters:
input: ndarray - Data from which to calculate center-of-mass
labels: ndarray, optional - Labels for objects in input
index: int or sequence of ints, optional - Labels for which to calculate centers
"""Mathematical special functions for advanced scientific computation.
def gamma(z, out=None):
"""
Gamma function.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def gammaln(z, out=None):
"""
Logarithm of the absolute value of the Gamma function.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def digamma(z, out=None):
"""
The digamma function (psi function).
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def erf(z, out=None):
"""
Error function.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def erfc(z, out=None):
"""
Complementary error function.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def erfcx(z, out=None):
"""
Scaled complementary error function.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def erfinv(z, out=None):
"""
Inverse error function.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def j0(z, out=None):
"""
Bessel function of the first kind of order 0.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def j1(z, out=None):
"""
Bessel function of the first kind of order 1.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def y0(z, out=None):
"""
Bessel function of the second kind of order 0.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def y1(z, out=None):
"""
Bessel function of the second kind of order 1.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def i0(z, out=None):
"""
Modified Bessel function of the first kind of order 0.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def i1(z, out=None):
"""
Modified Bessel function of the first kind of order 1.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def k0(z, out=None):
"""
Modified Bessel function of the second kind of order 0.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""
def k1(z, out=None):
"""
Modified Bessel function of the second kind of order 1.
Parameters:
z: array_like - Input values
out: ndarray, optional - Optional output array for the function results
"""Statistical distributions and hypothesis testing functions.
def norm():
"""
A normal continuous random variable.
This object has methods for probability density function (pdf),
cumulative distribution function (cdf), survival function (sf),
percent point function (ppf), and random variates (rvs).
"""
def chi2():
"""
A chi-squared continuous random variable.
This object has methods for probability density function (pdf),
cumulative distribution function (cdf), survival function (sf),
percent point function (ppf), and random variates (rvs).
"""
def t():
"""
A Student's t continuous random variable.
This object has methods for probability density function (pdf),
cumulative distribution function (cdf), survival function (sf),
percent point function (ppf), and random variates (rvs).
"""
def f():
"""
An F continuous random variable.
This object has methods for probability density function (pdf),
cumulative distribution function (cdf), survival function (sf),
percent point function (ppf), and random variates (rvs).
"""import cupy as cp
import cupyx.scipy as scipy
import cupyx.scipy.sparse as sparse
import cupyx.scipy.ndimage as ndimage
import cupyx.scipy.signal as signal
import cupyx.scipy.linalg as linalg
# Sparse matrix operations
# Create sparse matrices
data = cp.array([1, 2, 3, 4])
row = cp.array([0, 1, 2, 3])
col = cp.array([0, 1, 2, 3])
coo = sparse.coo_matrix((data, (row, col)), shape=(4, 4))
# Convert between formats
csr = coo.tocsr()
csc = coo.tocsc()
# Sparse matrix arithmetic
A = sparse.random(1000, 1000, density=0.01)
B = sparse.random(1000, 1000, density=0.01)
C = A @ B # Matrix multiplication
# Sparse linear algebra
x = sparse.linalg.spsolve(A, cp.random.rand(1000))
# Image processing with ndimage
# Load or generate image data
image = cp.random.rand(512, 512)
# Apply Gaussian filter
smoothed = ndimage.gaussian_filter(image, sigma=2.0)
# Edge detection with gradients
sobel_x = ndimage.sobel(image, axis=0)
sobel_y = ndimage.sobel(image, axis=1)
edges = cp.sqrt(sobel_x**2 + sobel_y**2)
# Morphological operations
binary_image = image > 0.5
opened = ndimage.binary_opening(binary_image)
closed = ndimage.binary_closing(binary_image)
# Geometric transformations
rotated = ndimage.rotate(image, 45, reshape=False)
zoomed = ndimage.zoom(image, 2.0)
# Label connected components
labeled, num_features = ndimage.label(binary_image)
centers = ndimage.center_of_mass(image, labeled,
range(1, num_features + 1))
# Signal processing
# Generate test signal
fs = 1000
t = cp.linspace(0, 1, fs, endpoint=False)
signal_data = cp.sin(2 * cp.pi * 50 * t) + 0.5 * cp.sin(2 * cp.pi * 120 * t)
# Convolution and correlation
kernel = signal.hann(51)
convolved = signal.convolve(signal_data, kernel, mode='same')
correlated = signal.correlate(signal_data, kernel, mode='same')
# FFT-based convolution (faster for large signals)
fft_convolved = signal.fftconvolve(signal_data, kernel, mode='same')
# Digital filtering
b, a = signal.butter(4, 0.2) # 4th order Butterworth filter
filtered = signal.filtfilt(b, a, signal_data)
# Hilbert transform for analytic signal
analytic = signal.hilbert(signal_data)
amplitude = cp.abs(analytic)
phase = cp.angle(analytic)
# 2D signal processing
image_2d = cp.random.rand(256, 256)
kernel_2d = cp.ones((5, 5)) / 25 # Simple averaging kernel
filtered_2d = signal.convolve2d(image_2d, kernel_2d, mode='same')
# Linear algebra extensions
# Solve banded systems
ab = cp.random.rand(5, 100) # Banded matrix storage
b_vec = cp.random.rand(100)
x = linalg.solve_banded((2, 2), ab, b_vec)
# Triangular systems
L = cp.tril(cp.random.rand(100, 100)) # Lower triangular
x_tri = linalg.solve_triangular(L, b_vec, lower=True)
# Cholesky factorization
A_pos = cp.random.rand(100, 100)
A_pos = A_pos @ A_pos.T + cp.eye(100) # Make positive definite
cho_fac, lower = linalg.cho_factor(A_pos)
x_cho = linalg.cho_solve((cho_fac, lower), b_vec)
# Block diagonal matrices
blocks = [cp.random.rand(10, 10) for _ in range(5)]
block_diag = linalg.block_diag(*blocks)
# FFT extensions with SciPy compatibility
# Discrete Cosine Transform
dct_result = scipy.fft.dct(signal_data)
reconstructed = scipy.fft.idct(dct_result)
# Discrete Sine Transform
dst_result = scipy.fft.dst(signal_data)
dst_reconstructed = scipy.fft.idst(dst_result)
# Special functions
x = cp.linspace(0.1, 5, 100)
gamma_values = scipy.special.gamma(x)
log_gamma = scipy.special.gammaln(x)
erf_values = scipy.special.erf(x)
bessel_j0 = scipy.special.j0(x)
# Advanced sparse matrix operations
# Construct large sparse system
n = 10000
# Create a sparse Laplacian matrix
diagonals = [-cp.ones(n-1), 2*cp.ones(n), -cp.ones(n-1)]
offsets = [-1, 0, 1]
laplacian = sparse.diags(diagonals, offsets, format='csr')
# Solve sparse linear system
rhs = cp.random.rand(n)
solution = sparse.linalg.spsolve(laplacian, rhs)
# Eigenvalue problems for sparse matrices
eigenvals, eigenvecs = sparse.linalg.eigsh(laplacian, k=10, which='SM')
# Sparse matrix I/O and manipulation
# Find nonzero elements
rows, cols, values = sparse.find(laplacian)
# Extract triangular parts
upper_tri = sparse.triu(laplacian)
lower_tri = sparse.tril(laplacian)
# Kronecker products for tensor operations
small_matrix = sparse.diags([1, -2, 1], [-1, 0, 1], shape=(10, 10))
tensor_op = sparse.kron(small_matrix, sparse.eye(100))
# Performance comparison example
def compare_dense_vs_sparse(n=1000, density=0.01):
"""Compare dense vs sparse matrix operations."""
# Create sparse matrix
A_sparse = sparse.random(n, n, density=density, format='csr')
# Convert to dense
A_dense = A_sparse.toarray()
# Vector for multiplication
x = cp.random.rand(n)
import time
# Time sparse multiplication
start = time.time()
y_sparse = A_sparse @ x
sparse_time = time.time() - start
# Time dense multiplication
start = time.time()
y_dense = A_dense @ x
dense_time = time.time() - start
print(f"Sparse: {sparse_time:.4f}s, Dense: {dense_time:.4f}s")
print(f"Speedup: {dense_time/sparse_time:.2f}x")
return sparse_time, dense_time
# Advanced image processing pipeline
def image_processing_pipeline(image):
"""Complete image processing pipeline."""
# Preprocessing
smoothed = ndimage.gaussian_filter(image, sigma=1.0)
# Edge detection
edges = ndimage.sobel(smoothed)
# Thresholding
binary = edges > cp.percentile(edges, 90)
# Morphological cleanup
cleaned = ndimage.binary_opening(binary, iterations=2)
cleaned = ndimage.binary_closing(cleaned, iterations=2)
# Label connected components
labeled, num_objects = ndimage.label(cleaned)
# Find object properties
centers = ndimage.center_of_mass(image, labeled,
range(1, num_objects + 1))
return {
'processed': cleaned,
'labeled': labeled,
'num_objects': num_objects,
'centers': centers
}
# Example usage
sample_image = cp.random.rand(512, 512)
results = image_processing_pipeline(sample_image)SciPy extensions in CuPy provide comprehensive scientific computing capabilities optimized for GPU acceleration, enabling efficient sparse linear algebra, advanced signal and image processing, statistical analysis, and specialized mathematical functions with familiar SciPy interfaces while leveraging the parallel processing power of modern GPUs.
Install with Tessl CLI
npx tessl i tessl/pypi-cupy-cuda11x