NumPy & SciPy-compatible GPU-accelerated computing library for CUDA 11.2 environments
—
Extended functionality through cupyx.scipy providing SciPy-compatible operations for sparse matrices, signal processing, image processing, special functions, and scientific computing on GPU.
GPU-accelerated sparse matrix computations with SciPy-compatible interface.
import cupyx.scipy.sparse
class cupyx.scipy.sparse.csr_matrix:
"""
Compressed Sparse Row matrix.
Parameters:
- arg1: array, tuple, or sparse matrix
- shape: tuple, matrix dimensions
- dtype: data type
- copy: bool, copy input data
"""
def __init__(self, arg1, shape=None, dtype=None, copy=False): ...
def toarray(self): ...
def tocoo(self): ...
def tocsc(self): ...
def todense(self): ...
def transpose(self, axes=None, copy=False): ...
def multiply(self, other): ...
def dot(self, other): ...
def sum(self, axis=None): ...
def mean(self, axis=None): ...
def max(self, axis=None): ...
def min(self, axis=None): ...
class cupyx.scipy.sparse.csc_matrix:
"""
Compressed Sparse Column matrix.
Parameters:
- arg1: array, tuple, or sparse matrix
- shape: tuple, matrix dimensions
- dtype: data type
- copy: bool, copy input data
"""
def __init__(self, arg1, shape=None, dtype=None, copy=False): ...
class cupyx.scipy.sparse.coo_matrix:
"""
COOrdinate format sparse matrix.
Parameters:
- arg1: array, tuple, or sparse matrix
- shape: tuple, matrix dimensions
- dtype: data type
- copy: bool, copy input data
"""
def __init__(self, arg1, shape=None, dtype=None, copy=False): ...
def cupyx.scipy.sparse.eye(m, n=None, k=0, dtype=float, format=None):
"""
Sparse identity matrix.
Parameters:
- m: int, number of rows
- n: int, number of columns
- k: int, diagonal offset
- dtype: data type
- format: str, sparse format
Returns:
sparse matrix, identity matrix
"""
def cupyx.scipy.sparse.diags(diagonals, offsets=0, shape=None, format=None, dtype=None):
"""
Construct sparse matrix from diagonals.
Parameters:
- diagonals: array or sequence of arrays
- offsets: int or sequence of ints, diagonal offsets
- shape: tuple, matrix shape
- format: str, sparse format
- dtype: data type
Returns:
sparse matrix, diagonal matrix
"""
def cupyx.scipy.sparse.kron(A, B, format=None):
"""
Kronecker product of sparse matrices.
Parameters:
- A: sparse matrix
- B: sparse matrix
- format: str, output format
Returns:
sparse matrix, Kronecker product
"""
def cupyx.scipy.sparse.hstack(blocks, format=None, dtype=None):
"""
Stack sparse matrices horizontally.
Parameters:
- blocks: sequence of sparse matrices
- format: str, output format
- dtype: data type
Returns:
sparse matrix, horizontally stacked result
"""
def cupyx.scipy.sparse.vstack(blocks, format=None, dtype=None):
"""
Stack sparse matrices vertically.
Parameters:
- blocks: sequence of sparse matrices
- format: str, output format
- dtype: data type
Returns:
sparse matrix, vertically stacked result
"""Specialized linear algebra operations for sparse matrices.
import cupyx.scipy.sparse.linalg
def cupyx.scipy.sparse.linalg.spsolve(A, b, permc_spec=None, use_umfpack=True):
"""
Solve sparse linear system Ax = b.
Parameters:
- A: sparse matrix, coefficient matrix
- b: array, right-hand side
- permc_spec: str, permutation method
- use_umfpack: bool, use UMFPACK solver
Returns:
cupy.ndarray, solution vector
"""
def cupyx.scipy.sparse.linalg.norm(x, ord=None, axis=None):
"""
Norm of sparse matrix or vector.
Parameters:
- x: sparse matrix or array
- ord: norm order
- axis: int, axis for norm computation
Returns:
float or cupy.ndarray, norm value
"""
def cupyx.scipy.sparse.linalg.eigsh(A, k=6, M=None, sigma=None, which='LM', v0=None, ncv=None, maxiter=None, tol=0, return_eigenvectors=True):
"""
Find eigenvalues and eigenvectors of symmetric sparse matrix.
Parameters:
- A: sparse matrix, symmetric matrix
- k: int, number of eigenvalues
- M: sparse matrix, mass matrix
- sigma: float, shift value
- which: str, which eigenvalues to find
- v0: array, starting vector
- ncv: int, number of Lanczos vectors
- maxiter: int, maximum iterations
- tol: float, tolerance
- return_eigenvectors: bool, return eigenvectors
Returns:
tuple, (eigenvalues, eigenvectors) or eigenvalues only
"""
def cupyx.scipy.sparse.linalg.svds(A, k=6, ncv=None, tol=0, which='LM', v0=None, maxiter=None, return_singular_vectors=True):
"""
Compute SVD of sparse matrix.
Parameters:
- A: sparse matrix
- k: int, number of singular values
- ncv: int, number of Lanczos vectors
- tol: float, tolerance
- which: str, which singular values
- v0: array, starting vector
- maxiter: int, maximum iterations
- return_singular_vectors: bool, return U and V
Returns:
tuple, (U, s, Vt) or s only
"""GPU-accelerated signal processing operations.
import cupyx.scipy.signal
def cupyx.scipy.signal.convolve(in1, in2, mode='full', method='auto'):
"""
Convolve two N-dimensional arrays.
Parameters:
- in1: array, first input
- in2: array, second input
- mode: str, convolution mode ('full', 'valid', 'same')
- method: str, computation method ('auto', 'direct', 'fft')
Returns:
cupy.ndarray, convolved array
"""
def cupyx.scipy.signal.correlate(in1, in2, mode='full', method='auto'):
"""
Cross-correlate two N-dimensional arrays.
Parameters:
- in1: array, first input
- in2: array, second input
- mode: str, correlation mode
- method: str, computation method
Returns:
cupy.ndarray, cross-correlation result
"""
def cupyx.scipy.signal.fftconvolve(in1, in2, mode='full', axes=None):
"""
Convolve using FFT.
Parameters:
- in1: array, first input
- in2: array, second input
- mode: str, convolution mode
- axes: sequence of ints, axes for convolution
Returns:
cupy.ndarray, convolved array
"""
def cupyx.scipy.signal.wiener(im, noise=None, mysize=None):
"""
Wiener filter for noise reduction.
Parameters:
- im: array, input image
- noise: float, noise variance
- mysize: tuple, filter size
Returns:
cupy.ndarray, filtered image
"""
def cupyx.scipy.signal.medfilt(volume, kernel_size=None):
"""
Median filter.
Parameters:
- volume: array, input array
- kernel_size: int or tuple, filter size
Returns:
cupy.ndarray, filtered array
"""
def cupyx.scipy.signal.find_peaks(x, height=None, threshold=None, distance=None, prominence=None, width=None, wlen=None, rel_height=0.5, plateau_size=None):
"""
Find peaks in 1-D array.
Parameters:
- x: array, input signal
- height: float or tuple, peak height constraints
- threshold: float or tuple, peak threshold
- distance: float, minimum peak distance
- prominence: float or tuple, peak prominence
- width: float or tuple, peak width
- wlen: int, window length for prominence
- rel_height: float, relative height for width
- plateau_size: float or tuple, plateau size
Returns:
tuple, (peaks, properties)
"""N-dimensional image processing operations.
import cupyx.scipy.ndimage
def cupyx.scipy.ndimage.gaussian_filter(input, sigma, order=0, output=None, mode='reflect', cval=0.0, truncate=4.0):
"""
Multi-dimensional Gaussian filter.
Parameters:
- input: array, input array
- sigma: float or sequence, standard deviation
- order: int or sequence, derivative order
- output: array, output array
- mode: str, boundary mode
- cval: scalar, constant value for boundaries
- truncate: float, filter truncation
Returns:
cupy.ndarray, filtered array
"""
def cupyx.scipy.ndimage.median_filter(input, size=None, footprint=None, output=None, mode='reflect', cval=0.0, origin=0):
"""
Multi-dimensional median filter.
Parameters:
- input: array, input array
- size: int or sequence, filter size
- footprint: array, filter footprint
- output: array, output array
- mode: str, boundary mode
- cval: scalar, constant value
- origin: int or sequence, filter origin
Returns:
cupy.ndarray, filtered array
"""
def cupyx.scipy.ndimage.binary_erosion(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False):
"""
Multi-dimensional binary erosion.
Parameters:
- input: array, binary input
- structure: array, structuring element
- iterations: int, number of iterations
- mask: array, operation mask
- output: array, output array
- border_value: int, border value
- origin: int or sequence, origin
- brute_force: bool, force brute force algorithm
Returns:
cupy.ndarray, eroded binary image
"""
def cupyx.scipy.ndimage.binary_dilation(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False):
"""
Multi-dimensional binary dilation.
Parameters:
- input: array, binary input
- structure: array, structuring element
- iterations: int, number of iterations
- mask: array, operation mask
- output: array, output array
- border_value: int, border value
- origin: int or sequence, origin
- brute_force: bool, force brute force algorithm
Returns:
cupy.ndarray, dilated binary image
"""
def cupyx.scipy.ndimage.label(input, structure=None, output=None):
"""
Label connected components in binary image.
Parameters:
- input: array, binary input
- structure: array, connectivity structure
- output: array, output array
Returns:
tuple, (labeled_array, num_labels)
"""
def cupyx.scipy.ndimage.distance_transform_edt(input, sampling=None, return_distances=True, return_indices=False, distances=None, indices=None):
"""
Euclidean distance transform.
Parameters:
- input: array, binary input
- sampling: sequence, pixel spacing
- return_distances: bool, return distance array
- return_indices: bool, return index array
- distances: array, output distance array
- indices: array, output index array
Returns:
cupy.ndarray or tuple, distances and/or indices
"""Mathematical special functions for scientific computing.
import cupyx.scipy.special
def cupyx.scipy.special.gamma(z, out=None):
"""
Gamma function.
Parameters:
- z: array-like, input values
- out: array, output array
Returns:
cupy.ndarray, gamma function values
"""
def cupyx.scipy.special.gammaln(z, out=None):
"""
Natural logarithm of gamma function.
Parameters:
- z: array-like, input values
- out: array, output array
Returns:
cupy.ndarray, log-gamma values
"""
def cupyx.scipy.special.erf(z, out=None):
"""
Error function.
Parameters:
- z: array-like, input values
- out: array, output array
Returns:
cupy.ndarray, error function values
"""
def cupyx.scipy.special.erfc(z, out=None):
"""
Complementary error function.
Parameters:
- z: array-like, input values
- out: array, output array
Returns:
cupy.ndarray, complementary error function values
"""
def cupyx.scipy.special.j0(z, out=None):
"""
Bessel function of the first kind of order 0.
Parameters:
- z: array-like, input values
- out: array, output array
Returns:
cupy.ndarray, Bessel function values
"""
def cupyx.scipy.special.j1(z, out=None):
"""
Bessel function of the first kind of order 1.
Parameters:
- z: array-like, input values
- out: array, output array
Returns:
cupy.ndarray, Bessel function values
"""
def cupyx.scipy.special.y0(z, out=None):
"""
Bessel function of the second kind of order 0.
Parameters:
- z: array-like, input values
- out: array, output array
Returns:
cupy.ndarray, Bessel function values
"""
def cupyx.scipy.special.y1(z, out=None):
"""
Bessel function of the second kind of order 1.
Parameters:
- z: array-like, input values
- out: array, output array
Returns:
cupy.ndarray, Bessel function values
"""Utility for choosing appropriate SciPy module based on array types.
def cupyx.scipy.get_array_module(*args):
"""
Returns appropriate SciPy module for arguments.
Parameters:
- args: array arguments to check
Returns:
module, cupyx.scipy or scipy based on input types
"""import cupy as cp
import cupyx.scipy.sparse as sparse
# Create sparse matrix from dense array
dense_matrix = cp.random.random((1000, 1000))
dense_matrix[dense_matrix < 0.9] = 0 # Make sparse
# Convert to sparse formats
csr_matrix = sparse.csr_matrix(dense_matrix)
csc_matrix = sparse.csc_matrix(dense_matrix)
coo_matrix = sparse.coo_matrix(dense_matrix)
print(f"Density: {csr_matrix.nnz / (1000 * 1000):.4f}")
# Sparse matrix operations
transposed = csr_matrix.transpose()
result = csr_matrix.dot(csc_matrix.transpose())
# Create sparse matrices directly
eye_sparse = sparse.eye(1000, format='csr')
diag_sparse = sparse.diags([1, 2, 1], [-1, 0, 1], shape=(1000, 1000))
# Sparse linear algebra
b = cp.random.random(1000)
x = sparse.linalg.spsolve(csr_matrix, b)
# Eigenvalue computation for sparse matrix
eigenvals, eigenvecs = sparse.linalg.eigsh(csr_matrix, k=10)import cupy as cp
import cupyx.scipy.signal as signal
# Create test signals
t = cp.linspace(0, 1, 1000)
sig1 = cp.sin(2 * cp.pi * 10 * t)
sig2 = cp.exp(-t) * cp.cos(2 * cp.pi * 20 * t)
# Convolution
convolved = signal.convolve(sig1, sig2, mode='same')
# Cross-correlation
correlation = signal.correlate(sig1, sig2, mode='full')
# Find peaks in signal
noisy_signal = sig1 + 0.1 * cp.random.randn(len(t))
peaks, properties = signal.find_peaks(noisy_signal, height=0.5, distance=50)
print(f"Found {len(peaks)} peaks")
# Filtering
from cupyx.scipy import ndimage
filtered_signal = ndimage.gaussian_filter(noisy_signal, sigma=2.0)
# FFT-based convolution for large signals
large_signal = cp.random.randn(100000)
kernel = cp.array([1, 2, 1]) / 4
fft_conv = signal.fftconvolve(large_signal, kernel, mode='same')import cupy as cp
import cupyx.scipy.ndimage as ndimage
# Create test image
x, y = cp.ogrid[-10:10:100j, -10:10:100j]
image = cp.exp(-(x**2 + y**2) / 10)
# Add noise
noisy_image = image + 0.1 * cp.random.randn(*image.shape)
# Gaussian filter
smoothed = ndimage.gaussian_filter(noisy_image, sigma=1.5)
# Median filter
median_filtered = ndimage.median_filter(noisy_image, size=3)
# Edge detection using gradient
gradient_x = ndimage.gaussian_filter(image, sigma=1, order=[0, 1])
gradient_y = ndimage.gaussian_filter(image, sigma=1, order=[1, 0])
gradient_magnitude = cp.sqrt(gradient_x**2 + gradient_y**2)
# Binary operations
binary_image = image > 0.5
eroded = ndimage.binary_erosion(binary_image, iterations=2)
dilated = ndimage.binary_dilation(binary_image, iterations=2)
# Connected component labeling
labeled, num_labels = ndimage.label(binary_image)
print(f"Found {num_labels} connected components")
# Distance transform
distance = ndimage.distance_transform_edt(binary_image)import cupy as cp
import cupyx.scipy.special as special
# Test values
x = cp.linspace(-3, 3, 1000)
z = cp.linspace(0.1, 5, 1000)
# Gamma function and log-gamma
gamma_vals = special.gamma(z)
loggamma_vals = special.gammaln(z)
# Error functions
erf_vals = special.erf(x)
erfc_vals = special.erfc(x)
# Bessel functions
j0_vals = special.j0(z)
j1_vals = special.j1(z)
y0_vals = special.y0(z[z > 0]) # Avoid zero
y1_vals = special.y1(z[z > 0])
# Statistical applications
from cupyx.scipy import stats
# Probability density functions (if available)
# normal_pdf = stats.norm.pdf(x, loc=0, scale=1)import cupy as cp
import cupyx.scipy
import numpy as np
import scipy
# Create mixed CPU/GPU workflow
cpu_data = np.random.random((1000, 1000))
gpu_data = cp.asarray(cpu_data)
# Use get_array_module for generic code
def process_data(data):
# Automatically choose appropriate module
xp = cupyx.scipy.get_array_module(data)
if hasattr(xp, 'ndimage'):
filtered = xp.ndimage.gaussian_filter(data, sigma=1.0)
else:
# Fallback for modules without ndimage
filtered = data
return filtered
# Works with both CPU and GPU data
cpu_result = process_data(cpu_data)
gpu_result = process_data(gpu_data)
# Convert results as needed
gpu_result_cpu = cp.asnumpy(gpu_result)Install with Tessl CLI
npx tessl i tessl/pypi-cupy-cuda112