NumPy & SciPy compatible GPU-accelerated array library for CUDA computing
—
GPU implementations of SciPy functionality including sparse matrices, signal processing, special functions, statistics, and N-dimensional image processing. CuPy provides comprehensive SciPy compatibility through the cupyx.scipy namespace, enabling GPU acceleration of scientific computing workflows.
GPU-accelerated sparse matrix formats and operations for memory-efficient computation on large, sparse datasets.
class csr_matrix:
"""Compressed Sparse Row matrix format.
Args:
arg1: Data, indices, indptr tuple or dense array
shape: Matrix shape
dtype: Data type
copy: Whether to copy data
Attributes:
data: Non-zero values array
indices: Column indices array
indptr: Row pointer array
"""
class csc_matrix:
"""Compressed Sparse Column matrix format.
Args:
arg1: Data, indices, indptr tuple or dense array
shape: Matrix shape
dtype: Data type
copy: Whether to copy data
Attributes:
data: Non-zero values array
indices: Row indices array
indptr: Column pointer array
"""
class coo_matrix:
"""Coordinate format sparse matrix.
Args:
arg1: Data, (row, col) tuple or dense array
shape: Matrix shape
dtype: Data type
copy: Whether to copy data
Attributes:
data: Non-zero values array
row: Row coordinate array
col: Column coordinate array
"""
class dia_matrix:
"""Sparse matrix with diagonal storage format.
Args:
arg1: Data, offsets tuple or dense array
shape: Matrix shape
dtype: Data type
copy: Whether to copy data
Attributes:
data: Diagonal values array
offsets: Diagonal offsets array
"""
def eye(m, n=None, k=0, dtype=float, format=None):
"""Create sparse identity matrix.
Args:
m: Number of rows
n: Number of columns, defaults to m
k: Diagonal offset
dtype: Data type
format: Sparse format ('csr', 'csc', 'coo')
Returns:
Sparse matrix: Identity matrix in specified format
"""
def identity(n, dtype=float, format=None):
"""Create n x n identity matrix."""
def diags(diagonals, offsets=0, shape=None, format=None, dtype=None):
"""Create sparse matrix from diagonals.
Args:
diagonals: Diagonal values
offsets: Diagonal offsets
shape: Matrix shape
format: Sparse format
dtype: Data type
Returns:
Sparse matrix: Matrix with specified diagonals
"""
def spdiags(data, diags, m, n, format=None):
"""Create sparse matrix from diagonals (MATLAB-style)."""
def rand(m, n, density=0.01, format='coo', dtype=None, random_state=None):
"""Generate random sparse matrix."""
def random(m, n, density=0.01, format='coo', dtype=None, random_state=None):
"""Generate random sparse matrix with uniform distribution."""def bmat(blocks, format=None, dtype=None):
"""Build sparse matrix from blocks.
Args:
blocks: 2D array of matrices
format: Output format
dtype: Data type
Returns:
Sparse matrix: Block matrix
"""
def hstack(blocks, format=None, dtype=None):
"""Stack sparse matrices horizontally."""
def vstack(blocks, format=None, dtype=None):
"""Stack sparse matrices vertically."""
def kron(A, B, format=None):
"""Kronecker product of sparse matrices."""
def kronsum(A, B, format=None):
"""Kronecker sum of sparse matrices."""
def issparse(x):
"""Check if input is sparse matrix."""
def isspmatrix(x):
"""Check if input is sparse matrix object."""
def isspmatrix_csr(x):
"""Check if input is CSR matrix."""
def isspmatrix_csc(x):
"""Check if input is CSC matrix."""
def isspmatrix_coo(x):
"""Check if input is COO matrix."""GPU-accelerated signal processing functions for filtering, correlation, and spectral analysis.
def convolve(in1, in2, mode='full'):
"""Convolution of two N-dimensional arrays.
Args:
in1: First input array
in2: Second input array
mode: Output size ('full', 'valid', 'same')
Returns:
cupy.ndarray: Convolution result
"""
def correlate(in1, in2, mode='full'):
"""Cross-correlation of two N-dimensional arrays.
Args:
in1: First input array
in2: Second input array
mode: Output size ('full', 'valid', 'same')
Returns:
cupy.ndarray: Correlation result
"""
def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0):
"""2D convolution with boundary conditions."""
def correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0):
"""2D correlation with boundary conditions."""
def fftconvolve(in1, in2, mode='full', axes=None):
"""FFT-based N-dimensional convolution."""
def hilbert(x, N=None, axis=-1):
"""Compute Hilbert transform.
Args:
x: Input signal
N: Length of transform
axis: Axis along which to compute
Returns:
cupy.ndarray: Analytic signal
"""
def detrend(data, axis=-1, type='linear', bp=0, overwrite_data=False):
"""Remove linear trend from data."""
def periodogram(x, fs=1.0, window='boxcar', nfft=None, detrend='constant',
return_onesided=True, scaling='density', axis=-1):
"""Estimate power spectral density using periodogram."""
def welch(x, fs=1.0, window='hann', nperseg=None, noverlap=None, nfft=None,
detrend='constant', return_onesided=True, scaling='density', axis=-1):
"""Estimate power spectral density using Welch's method."""def sosfilt(sos, x, axis=-1, zi=None):
"""Filter data using second-order sections.
Args:
sos: Second-order sections representation
x: Input data
axis: Axis to filter along
zi: Initial conditions
Returns:
cupy.ndarray: Filtered output
"""
def filtfilt(b, a, x, axis=-1, padtype='odd', padlen=None, method='pad', irlen=None):
"""Zero-phase digital filtering."""
def lfilter(b, a, x, axis=-1, zi=None):
"""Filter data with IIR or FIR filter."""
def medfilt(volume, kernel_size=None):
"""N-dimensional median filter."""
def order_filter(input, domain, rank):
"""N-dimensional order filter."""
def wiener(im, noise=None, balance=0.1):
"""Wiener filter for noise reduction."""Mathematical special functions commonly used in scientific computing.
def gamma(z):
"""Gamma function.
Args:
z: Input values
Returns:
cupy.ndarray: Gamma function values
"""
def gammaln(z):
"""Natural logarithm of gamma function."""
def digamma(z):
"""Digamma (psi) function."""
def polygamma(n, z):
"""Polygamma function."""
def beta(a, b):
"""Beta function."""
def betaln(a, b):
"""Natural logarithm of beta function."""
def factorial(n, exact=False):
"""Factorial function."""
def factorial2(n, exact=False):
"""Double factorial function."""
def factorialk(n, k, exact=False):
"""K-factorial function."""
def comb(N, k, exact=False, repetition=False):
"""Combinations (binomial coefficients)."""
def perm(N, k, exact=False):
"""Permutations."""
def erf(z):
"""Error function."""
def erfc(z):
"""Complementary error function."""
def erfcx(z):
"""Scaled complementary error function."""
def erfi(z):
"""Imaginary error function."""
def dawsn(z):
"""Dawson's integral."""
def fresnel(z):
"""Fresnel integrals."""
def ellipk(m):
"""Complete elliptic integral of the first kind."""
def ellipe(m):
"""Complete elliptic integral of the second kind."""def j0(z):
"""Bessel function of the first kind of order 0."""
def j1(z):
"""Bessel function of the first kind of order 1."""
def jn(n, z):
"""Bessel function of the first kind of order n."""
def jv(v, z):
"""Bessel function of the first kind of real order."""
def y0(z):
"""Bessel function of the second kind of order 0."""
def y1(z):
"""Bessel function of the second kind of order 1."""
def yn(n, z):
"""Bessel function of the second kind of order n."""
def yv(v, z):
"""Bessel function of the second kind of real order."""
def i0(z):
"""Modified Bessel function of the first kind of order 0."""
def i1(z):
"""Modified Bessel function of the first kind of order 1."""
def iv(v, z):
"""Modified Bessel function of the first kind of real order."""
def k0(z):
"""Modified Bessel function of the second kind of order 0."""
def k1(z):
"""Modified Bessel function of the second kind of order 1."""
def kn(n, z):
"""Modified Bessel function of the second kind of order n."""
def kv(v, z):
"""Modified Bessel function of the second kind of real order."""Advanced image processing operations for scientific and computer vision applications.
def binary_erosion(input, structure=None, iterations=1, mask=None, output=None,
border_value=0, origin=0, brute_force=False):
"""Multi-dimensional binary erosion."""
def binary_dilation(input, structure=None, iterations=1, mask=None, output=None,
border_value=0, origin=0, brute_force=False):
"""Multi-dimensional binary dilation."""
def binary_opening(input, structure=None, iterations=1, output=None, origin=0):
"""Multi-dimensional binary opening."""
def binary_closing(input, structure=None, iterations=1, output=None, origin=0):
"""Multi-dimensional binary closing."""
def grey_erosion(input, size=None, footprint=None, structure=None, output=None,
mode='reflect', cval=0.0, origin=0):
"""Multi-dimensional greyscale erosion."""
def grey_dilation(input, size=None, footprint=None, structure=None, output=None,
mode='reflect', cval=0.0, origin=0):
"""Multi-dimensional greyscale dilation."""
def gaussian_filter(input, sigma, order=0, output=None, mode='reflect',
cval=0.0, truncate=4.0):
"""Multi-dimensional Gaussian filter.
Args:
input: Input array
sigma: Standard deviation for Gaussian kernel
order: Derivative order (0 for smoothing)
output: Output array
mode: Boundary mode
cval: Constant value for 'constant' mode
truncate: Truncate filter at this many sigmas
Returns:
cupy.ndarray: Filtered array
"""
def uniform_filter(input, size=3, output=None, mode='reflect', cval=0.0, origin=0):
"""Multi-dimensional uniform filter."""
def maximum_filter(input, size=None, footprint=None, output=None, mode='reflect',
cval=0.0, origin=0):
"""Multi-dimensional maximum filter."""
def minimum_filter(input, size=None, footprint=None, output=None, mode='reflect',
cval=0.0, origin=0):
"""Multi-dimensional minimum filter."""
def median_filter(input, size=None, footprint=None, output=None, mode='reflect',
cval=0.0, origin=0):
"""Multi-dimensional median filter."""
def rank_filter(input, rank, size=None, footprint=None, output=None,
mode='reflect', cval=0.0, origin=0):
"""Multi-dimensional rank filter."""
def percentile_filter(input, percentile, size=None, footprint=None, output=None,
mode='reflect', cval=0.0, origin=0):
"""Multi-dimensional percentile filter."""
def sobel(input, axis=-1, output=None, mode='reflect', cval=0.0):
"""Sobel edge detection filter."""
def laplace(input, output=None, mode='reflect', cval=0.0):
"""N-dimensional Laplace filter."""
def gaussian_laplace(input, sigma, output=None, mode='reflect', cval=0.0,
truncate=4.0):
"""Multi-dimensional Laplace filter using Gaussian second derivatives."""
def generic_gradient_magnitude(input, derivative, output=None, mode='reflect',
cval=0.0, extra_arguments=(), extra_keywords={}):
"""Gradient magnitude using a provided gradient function."""
def zoom(input, zoom, output=None, order=1, mode='constant', cval=0.0,
prefilter=True, grid_mode=False):
"""Zoom an array by spline interpolation."""
def rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=1,
mode='constant', cval=0.0, prefilter=True):
"""Rotate array by given angle."""
def affine_transform(input, matrix, offset=0.0, output_shape=None, output=None,
order=1, mode='constant', cval=0.0, prefilter=True):
"""Apply affine transformation."""
def shift(input, shift, output=None, order=1, mode='constant', cval=0.0,
prefilter=True):
"""Shift array by given offset."""
def map_coordinates(input, coordinates, output=None, order=1, mode='constant',
cval=0.0, prefilter=True):
"""Map input array to new coordinates by interpolation."""def label(input, structure=None, output=None):
"""Label connected components in binary array.
Args:
input: Binary input array
structure: Structuring element
output: Output array
Returns:
tuple: Labeled array and number of features
"""
def find_objects(input, max_label=0):
"""Find objects in labeled array."""
def center_of_mass(input, labels=None, index=None):
"""Calculate center of mass of objects."""
def measurements_sum(input, labels=None, index=None):
"""Calculate sum of values for labeled objects."""
def measurements_mean(input, labels=None, index=None):
"""Calculate mean of values for labeled objects."""
def measurements_variance(input, labels=None, index=None):
"""Calculate variance of values for labeled objects."""
def measurements_standard_deviation(input, labels=None, index=None):
"""Calculate standard deviation of values for labeled objects."""
def measurements_minimum(input, labels=None, index=None):
"""Calculate minimum of values for labeled objects."""
def measurements_maximum(input, labels=None, index=None):
"""Calculate maximum of values for labeled objects."""
def measurements_extrema(input, labels=None, index=None):
"""Calculate extrema of values for labeled objects."""
def distance_transform_edt(input, sampling=None, return_distances=True,
return_indices=False, distances=None, indices=None):
"""Exact Euclidean distance transform."""
def distance_transform_cdt(input, metric='chessboard', return_distances=True,
return_indices=False, distances=None, indices=None):
"""Chamfer distance transform."""
def distance_transform_bf(input, metric='euclidean', sampling=None,
return_distances=True, return_indices=False,
distances=None, indices=None):
"""Distance transform by brute force."""import cupy as cp
from cupyx.scipy import sparse
# Create sparse matrices
data = cp.array([1, 2, 3, 4, 5])
row = cp.array([0, 0, 1, 2, 2])
col = cp.array([0, 2, 1, 0, 2])
coo = sparse.coo_matrix((data, (row, col)), shape=(3, 3))
# Convert between formats
csr = coo.tocsr()
csc = coo.tocsc()
# Sparse matrix operations
A = sparse.random(1000, 1000, density=0.01)
B = sparse.random(1000, 1000, density=0.01)
C = A @ B # Matrix multiplication
# Create identity and diagonal matrices
I = sparse.eye(1000, format='csr')
D = sparse.diags([1, -2, 1], [-1, 0, 1], shape=(1000, 1000))import cupy as cp
from cupyx.scipy import signal
# Generate test signal
t = cp.linspace(0, 1, 1000)
sig = cp.sin(2 * cp.pi * 5 * t) + 0.5 * cp.sin(2 * cp.pi * 10 * t)
noise = 0.2 * cp.random.randn(len(t))
noisy_sig = sig + noise
# Apply filters
filtered = signal.medfilt(noisy_sig, kernel_size=5)
smoothed = signal.gaussian_filter1d(filtered, sigma=2)
# Convolution and correlation
kernel = cp.array([1, 0, -1])
convolved = signal.convolve(noisy_sig, kernel, mode='same')
correlated = signal.correlate(sig, noisy_sig, mode='full')
# Spectral analysis
f, Pxx = signal.welch(noisy_sig, fs=1000, nperseg=256)import cupy as cp
from cupyx.scipy import ndimage
# Load and process image
image = cp.random.rand(256, 256)
# Smoothing filters
gaussian = ndimage.gaussian_filter(image, sigma=2)
uniform = ndimage.uniform_filter(image, size=5)
median = ndimage.median_filter(image, size=3)
# Edge detection
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 > 0.5
opened = ndimage.binary_opening(binary, iterations=2)
closed = ndimage.binary_closing(opened, iterations=2)
# Geometric transformations
rotated = ndimage.rotate(image, 45, reshape=False)
zoomed = ndimage.zoom(image, 1.5)
shifted = ndimage.shift(image, [10, -5])
# Object labeling and analysis
labels, num_features = ndimage.label(binary)
centers = ndimage.center_of_mass(image, labels, range(1, num_features + 1))import cupy as cp
from cupyx.scipy import special
# Gamma and related functions
x = cp.linspace(0.1, 5, 100)
gamma_vals = special.gamma(x)
loggamma_vals = special.gammaln(x)
digamma_vals = special.digamma(x)
# Error functions
z = cp.linspace(-3, 3, 100)
erf_vals = special.erf(z)
erfc_vals = special.erfc(z)
# Bessel functions
v = cp.linspace(0, 10, 100)
j0_vals = special.j0(v)
y0_vals = special.y0(v)
i0_vals = special.i0(v)
k0_vals = special.k0(v)
# Combinatorics
n = cp.arange(10)
factorial_vals = special.factorial(n)
combinations = special.comb(10, n)import cupy as cp
from cupyx.scipy import sparse, linalg
# Create large sparse system
n = 10000
A = sparse.random(n, n, density=0.001, format='csr')
A = A + A.T # Make symmetric
b = cp.random.randn(n)
# Sparse linear algebra
x = linalg.spsolve(A, b)
# Eigenvalue problems for sparse matrices
eigenvals = linalg.eigsh(A, k=10, which='SM')
# Sparse matrix factorizations
lu = linalg.splu(A)
chol = linalg.cholesky(A)Install with Tessl CLI
npx tessl i tessl/pypi-cupy-cuda114