0
# SciPy Extensions
1
2
Extended functionality through cupyx.scipy providing SciPy-compatible operations for sparse matrices, signal processing, image processing, special functions, and scientific computing on GPU.
3
4
## Capabilities
5
6
### Sparse Matrix Operations
7
8
GPU-accelerated sparse matrix computations with SciPy-compatible interface.
9
10
```python { .api }
11
import cupyx.scipy.sparse
12
13
class cupyx.scipy.sparse.csr_matrix:
14
"""
15
Compressed Sparse Row matrix.
16
17
Parameters:
18
- arg1: array, tuple, or sparse matrix
19
- shape: tuple, matrix dimensions
20
- dtype: data type
21
- copy: bool, copy input data
22
"""
23
def __init__(self, arg1, shape=None, dtype=None, copy=False): ...
24
def toarray(self): ...
25
def tocoo(self): ...
26
def tocsc(self): ...
27
def todense(self): ...
28
def transpose(self, axes=None, copy=False): ...
29
def multiply(self, other): ...
30
def dot(self, other): ...
31
def sum(self, axis=None): ...
32
def mean(self, axis=None): ...
33
def max(self, axis=None): ...
34
def min(self, axis=None): ...
35
36
class cupyx.scipy.sparse.csc_matrix:
37
"""
38
Compressed Sparse Column matrix.
39
40
Parameters:
41
- arg1: array, tuple, or sparse matrix
42
- shape: tuple, matrix dimensions
43
- dtype: data type
44
- copy: bool, copy input data
45
"""
46
def __init__(self, arg1, shape=None, dtype=None, copy=False): ...
47
48
class cupyx.scipy.sparse.coo_matrix:
49
"""
50
COOrdinate format sparse matrix.
51
52
Parameters:
53
- arg1: array, tuple, or sparse matrix
54
- shape: tuple, matrix dimensions
55
- dtype: data type
56
- copy: bool, copy input data
57
"""
58
def __init__(self, arg1, shape=None, dtype=None, copy=False): ...
59
60
def cupyx.scipy.sparse.eye(m, n=None, k=0, dtype=float, format=None):
61
"""
62
Sparse identity matrix.
63
64
Parameters:
65
- m: int, number of rows
66
- n: int, number of columns
67
- k: int, diagonal offset
68
- dtype: data type
69
- format: str, sparse format
70
71
Returns:
72
sparse matrix, identity matrix
73
"""
74
75
def cupyx.scipy.sparse.diags(diagonals, offsets=0, shape=None, format=None, dtype=None):
76
"""
77
Construct sparse matrix from diagonals.
78
79
Parameters:
80
- diagonals: array or sequence of arrays
81
- offsets: int or sequence of ints, diagonal offsets
82
- shape: tuple, matrix shape
83
- format: str, sparse format
84
- dtype: data type
85
86
Returns:
87
sparse matrix, diagonal matrix
88
"""
89
90
def cupyx.scipy.sparse.kron(A, B, format=None):
91
"""
92
Kronecker product of sparse matrices.
93
94
Parameters:
95
- A: sparse matrix
96
- B: sparse matrix
97
- format: str, output format
98
99
Returns:
100
sparse matrix, Kronecker product
101
"""
102
103
def cupyx.scipy.sparse.hstack(blocks, format=None, dtype=None):
104
"""
105
Stack sparse matrices horizontally.
106
107
Parameters:
108
- blocks: sequence of sparse matrices
109
- format: str, output format
110
- dtype: data type
111
112
Returns:
113
sparse matrix, horizontally stacked result
114
"""
115
116
def cupyx.scipy.sparse.vstack(blocks, format=None, dtype=None):
117
"""
118
Stack sparse matrices vertically.
119
120
Parameters:
121
- blocks: sequence of sparse matrices
122
- format: str, output format
123
- dtype: data type
124
125
Returns:
126
sparse matrix, vertically stacked result
127
"""
128
```
129
130
### Sparse Linear Algebra
131
132
Specialized linear algebra operations for sparse matrices.
133
134
```python { .api }
135
import cupyx.scipy.sparse.linalg
136
137
def cupyx.scipy.sparse.linalg.spsolve(A, b, permc_spec=None, use_umfpack=True):
138
"""
139
Solve sparse linear system Ax = b.
140
141
Parameters:
142
- A: sparse matrix, coefficient matrix
143
- b: array, right-hand side
144
- permc_spec: str, permutation method
145
- use_umfpack: bool, use UMFPACK solver
146
147
Returns:
148
cupy.ndarray, solution vector
149
"""
150
151
def cupyx.scipy.sparse.linalg.norm(x, ord=None, axis=None):
152
"""
153
Norm of sparse matrix or vector.
154
155
Parameters:
156
- x: sparse matrix or array
157
- ord: norm order
158
- axis: int, axis for norm computation
159
160
Returns:
161
float or cupy.ndarray, norm value
162
"""
163
164
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):
165
"""
166
Find eigenvalues and eigenvectors of symmetric sparse matrix.
167
168
Parameters:
169
- A: sparse matrix, symmetric matrix
170
- k: int, number of eigenvalues
171
- M: sparse matrix, mass matrix
172
- sigma: float, shift value
173
- which: str, which eigenvalues to find
174
- v0: array, starting vector
175
- ncv: int, number of Lanczos vectors
176
- maxiter: int, maximum iterations
177
- tol: float, tolerance
178
- return_eigenvectors: bool, return eigenvectors
179
180
Returns:
181
tuple, (eigenvalues, eigenvectors) or eigenvalues only
182
"""
183
184
def cupyx.scipy.sparse.linalg.svds(A, k=6, ncv=None, tol=0, which='LM', v0=None, maxiter=None, return_singular_vectors=True):
185
"""
186
Compute SVD of sparse matrix.
187
188
Parameters:
189
- A: sparse matrix
190
- k: int, number of singular values
191
- ncv: int, number of Lanczos vectors
192
- tol: float, tolerance
193
- which: str, which singular values
194
- v0: array, starting vector
195
- maxiter: int, maximum iterations
196
- return_singular_vectors: bool, return U and V
197
198
Returns:
199
tuple, (U, s, Vt) or s only
200
"""
201
```
202
203
### Signal Processing
204
205
GPU-accelerated signal processing operations.
206
207
```python { .api }
208
import cupyx.scipy.signal
209
210
def cupyx.scipy.signal.convolve(in1, in2, mode='full', method='auto'):
211
"""
212
Convolve two N-dimensional arrays.
213
214
Parameters:
215
- in1: array, first input
216
- in2: array, second input
217
- mode: str, convolution mode ('full', 'valid', 'same')
218
- method: str, computation method ('auto', 'direct', 'fft')
219
220
Returns:
221
cupy.ndarray, convolved array
222
"""
223
224
def cupyx.scipy.signal.correlate(in1, in2, mode='full', method='auto'):
225
"""
226
Cross-correlate two N-dimensional arrays.
227
228
Parameters:
229
- in1: array, first input
230
- in2: array, second input
231
- mode: str, correlation mode
232
- method: str, computation method
233
234
Returns:
235
cupy.ndarray, cross-correlation result
236
"""
237
238
def cupyx.scipy.signal.fftconvolve(in1, in2, mode='full', axes=None):
239
"""
240
Convolve using FFT.
241
242
Parameters:
243
- in1: array, first input
244
- in2: array, second input
245
- mode: str, convolution mode
246
- axes: sequence of ints, axes for convolution
247
248
Returns:
249
cupy.ndarray, convolved array
250
"""
251
252
def cupyx.scipy.signal.wiener(im, noise=None, mysize=None):
253
"""
254
Wiener filter for noise reduction.
255
256
Parameters:
257
- im: array, input image
258
- noise: float, noise variance
259
- mysize: tuple, filter size
260
261
Returns:
262
cupy.ndarray, filtered image
263
"""
264
265
def cupyx.scipy.signal.medfilt(volume, kernel_size=None):
266
"""
267
Median filter.
268
269
Parameters:
270
- volume: array, input array
271
- kernel_size: int or tuple, filter size
272
273
Returns:
274
cupy.ndarray, filtered array
275
"""
276
277
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):
278
"""
279
Find peaks in 1-D array.
280
281
Parameters:
282
- x: array, input signal
283
- height: float or tuple, peak height constraints
284
- threshold: float or tuple, peak threshold
285
- distance: float, minimum peak distance
286
- prominence: float or tuple, peak prominence
287
- width: float or tuple, peak width
288
- wlen: int, window length for prominence
289
- rel_height: float, relative height for width
290
- plateau_size: float or tuple, plateau size
291
292
Returns:
293
tuple, (peaks, properties)
294
"""
295
```
296
297
### Image Processing
298
299
N-dimensional image processing operations.
300
301
```python { .api }
302
import cupyx.scipy.ndimage
303
304
def cupyx.scipy.ndimage.gaussian_filter(input, sigma, order=0, output=None, mode='reflect', cval=0.0, truncate=4.0):
305
"""
306
Multi-dimensional Gaussian filter.
307
308
Parameters:
309
- input: array, input array
310
- sigma: float or sequence, standard deviation
311
- order: int or sequence, derivative order
312
- output: array, output array
313
- mode: str, boundary mode
314
- cval: scalar, constant value for boundaries
315
- truncate: float, filter truncation
316
317
Returns:
318
cupy.ndarray, filtered array
319
"""
320
321
def cupyx.scipy.ndimage.median_filter(input, size=None, footprint=None, output=None, mode='reflect', cval=0.0, origin=0):
322
"""
323
Multi-dimensional median filter.
324
325
Parameters:
326
- input: array, input array
327
- size: int or sequence, filter size
328
- footprint: array, filter footprint
329
- output: array, output array
330
- mode: str, boundary mode
331
- cval: scalar, constant value
332
- origin: int or sequence, filter origin
333
334
Returns:
335
cupy.ndarray, filtered array
336
"""
337
338
def cupyx.scipy.ndimage.binary_erosion(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False):
339
"""
340
Multi-dimensional binary erosion.
341
342
Parameters:
343
- input: array, binary input
344
- structure: array, structuring element
345
- iterations: int, number of iterations
346
- mask: array, operation mask
347
- output: array, output array
348
- border_value: int, border value
349
- origin: int or sequence, origin
350
- brute_force: bool, force brute force algorithm
351
352
Returns:
353
cupy.ndarray, eroded binary image
354
"""
355
356
def cupyx.scipy.ndimage.binary_dilation(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False):
357
"""
358
Multi-dimensional binary dilation.
359
360
Parameters:
361
- input: array, binary input
362
- structure: array, structuring element
363
- iterations: int, number of iterations
364
- mask: array, operation mask
365
- output: array, output array
366
- border_value: int, border value
367
- origin: int or sequence, origin
368
- brute_force: bool, force brute force algorithm
369
370
Returns:
371
cupy.ndarray, dilated binary image
372
"""
373
374
def cupyx.scipy.ndimage.label(input, structure=None, output=None):
375
"""
376
Label connected components in binary image.
377
378
Parameters:
379
- input: array, binary input
380
- structure: array, connectivity structure
381
- output: array, output array
382
383
Returns:
384
tuple, (labeled_array, num_labels)
385
"""
386
387
def cupyx.scipy.ndimage.distance_transform_edt(input, sampling=None, return_distances=True, return_indices=False, distances=None, indices=None):
388
"""
389
Euclidean distance transform.
390
391
Parameters:
392
- input: array, binary input
393
- sampling: sequence, pixel spacing
394
- return_distances: bool, return distance array
395
- return_indices: bool, return index array
396
- distances: array, output distance array
397
- indices: array, output index array
398
399
Returns:
400
cupy.ndarray or tuple, distances and/or indices
401
"""
402
```
403
404
### Special Functions
405
406
Mathematical special functions for scientific computing.
407
408
```python { .api }
409
import cupyx.scipy.special
410
411
def cupyx.scipy.special.gamma(z, out=None):
412
"""
413
Gamma function.
414
415
Parameters:
416
- z: array-like, input values
417
- out: array, output array
418
419
Returns:
420
cupy.ndarray, gamma function values
421
"""
422
423
def cupyx.scipy.special.gammaln(z, out=None):
424
"""
425
Natural logarithm of gamma function.
426
427
Parameters:
428
- z: array-like, input values
429
- out: array, output array
430
431
Returns:
432
cupy.ndarray, log-gamma values
433
"""
434
435
def cupyx.scipy.special.erf(z, out=None):
436
"""
437
Error function.
438
439
Parameters:
440
- z: array-like, input values
441
- out: array, output array
442
443
Returns:
444
cupy.ndarray, error function values
445
"""
446
447
def cupyx.scipy.special.erfc(z, out=None):
448
"""
449
Complementary error function.
450
451
Parameters:
452
- z: array-like, input values
453
- out: array, output array
454
455
Returns:
456
cupy.ndarray, complementary error function values
457
"""
458
459
def cupyx.scipy.special.j0(z, out=None):
460
"""
461
Bessel function of the first kind of order 0.
462
463
Parameters:
464
- z: array-like, input values
465
- out: array, output array
466
467
Returns:
468
cupy.ndarray, Bessel function values
469
"""
470
471
def cupyx.scipy.special.j1(z, out=None):
472
"""
473
Bessel function of the first kind of order 1.
474
475
Parameters:
476
- z: array-like, input values
477
- out: array, output array
478
479
Returns:
480
cupy.ndarray, Bessel function values
481
"""
482
483
def cupyx.scipy.special.y0(z, out=None):
484
"""
485
Bessel function of the second kind of order 0.
486
487
Parameters:
488
- z: array-like, input values
489
- out: array, output array
490
491
Returns:
492
cupy.ndarray, Bessel function values
493
"""
494
495
def cupyx.scipy.special.y1(z, out=None):
496
"""
497
Bessel function of the second kind of order 1.
498
499
Parameters:
500
- z: array-like, input values
501
- out: array, output array
502
503
Returns:
504
cupy.ndarray, Bessel function values
505
"""
506
```
507
508
### Array Module Selection
509
510
Utility for choosing appropriate SciPy module based on array types.
511
512
```python { .api }
513
def cupyx.scipy.get_array_module(*args):
514
"""
515
Returns appropriate SciPy module for arguments.
516
517
Parameters:
518
- args: array arguments to check
519
520
Returns:
521
module, cupyx.scipy or scipy based on input types
522
"""
523
```
524
525
## Usage Examples
526
527
### Sparse Matrix Operations
528
529
```python
530
import cupy as cp
531
import cupyx.scipy.sparse as sparse
532
533
# Create sparse matrix from dense array
534
dense_matrix = cp.random.random((1000, 1000))
535
dense_matrix[dense_matrix < 0.9] = 0 # Make sparse
536
537
# Convert to sparse formats
538
csr_matrix = sparse.csr_matrix(dense_matrix)
539
csc_matrix = sparse.csc_matrix(dense_matrix)
540
coo_matrix = sparse.coo_matrix(dense_matrix)
541
542
print(f"Density: {csr_matrix.nnz / (1000 * 1000):.4f}")
543
544
# Sparse matrix operations
545
transposed = csr_matrix.transpose()
546
result = csr_matrix.dot(csc_matrix.transpose())
547
548
# Create sparse matrices directly
549
eye_sparse = sparse.eye(1000, format='csr')
550
diag_sparse = sparse.diags([1, 2, 1], [-1, 0, 1], shape=(1000, 1000))
551
552
# Sparse linear algebra
553
b = cp.random.random(1000)
554
x = sparse.linalg.spsolve(csr_matrix, b)
555
556
# Eigenvalue computation for sparse matrix
557
eigenvals, eigenvecs = sparse.linalg.eigsh(csr_matrix, k=10)
558
```
559
560
### Signal Processing
561
562
```python
563
import cupy as cp
564
import cupyx.scipy.signal as signal
565
566
# Create test signals
567
t = cp.linspace(0, 1, 1000)
568
sig1 = cp.sin(2 * cp.pi * 10 * t)
569
sig2 = cp.exp(-t) * cp.cos(2 * cp.pi * 20 * t)
570
571
# Convolution
572
convolved = signal.convolve(sig1, sig2, mode='same')
573
574
# Cross-correlation
575
correlation = signal.correlate(sig1, sig2, mode='full')
576
577
# Find peaks in signal
578
noisy_signal = sig1 + 0.1 * cp.random.randn(len(t))
579
peaks, properties = signal.find_peaks(noisy_signal, height=0.5, distance=50)
580
581
print(f"Found {len(peaks)} peaks")
582
583
# Filtering
584
from cupyx.scipy import ndimage
585
filtered_signal = ndimage.gaussian_filter(noisy_signal, sigma=2.0)
586
587
# FFT-based convolution for large signals
588
large_signal = cp.random.randn(100000)
589
kernel = cp.array([1, 2, 1]) / 4
590
fft_conv = signal.fftconvolve(large_signal, kernel, mode='same')
591
```
592
593
### Image Processing
594
595
```python
596
import cupy as cp
597
import cupyx.scipy.ndimage as ndimage
598
599
# Create test image
600
x, y = cp.ogrid[-10:10:100j, -10:10:100j]
601
image = cp.exp(-(x**2 + y**2) / 10)
602
603
# Add noise
604
noisy_image = image + 0.1 * cp.random.randn(*image.shape)
605
606
# Gaussian filter
607
smoothed = ndimage.gaussian_filter(noisy_image, sigma=1.5)
608
609
# Median filter
610
median_filtered = ndimage.median_filter(noisy_image, size=3)
611
612
# Edge detection using gradient
613
gradient_x = ndimage.gaussian_filter(image, sigma=1, order=[0, 1])
614
gradient_y = ndimage.gaussian_filter(image, sigma=1, order=[1, 0])
615
gradient_magnitude = cp.sqrt(gradient_x**2 + gradient_y**2)
616
617
# Binary operations
618
binary_image = image > 0.5
619
eroded = ndimage.binary_erosion(binary_image, iterations=2)
620
dilated = ndimage.binary_dilation(binary_image, iterations=2)
621
622
# Connected component labeling
623
labeled, num_labels = ndimage.label(binary_image)
624
print(f"Found {num_labels} connected components")
625
626
# Distance transform
627
distance = ndimage.distance_transform_edt(binary_image)
628
```
629
630
### Special Functions
631
632
```python
633
import cupy as cp
634
import cupyx.scipy.special as special
635
636
# Test values
637
x = cp.linspace(-3, 3, 1000)
638
z = cp.linspace(0.1, 5, 1000)
639
640
# Gamma function and log-gamma
641
gamma_vals = special.gamma(z)
642
loggamma_vals = special.gammaln(z)
643
644
# Error functions
645
erf_vals = special.erf(x)
646
erfc_vals = special.erfc(x)
647
648
# Bessel functions
649
j0_vals = special.j0(z)
650
j1_vals = special.j1(z)
651
y0_vals = special.y0(z[z > 0]) # Avoid zero
652
y1_vals = special.y1(z[z > 0])
653
654
# Statistical applications
655
from cupyx.scipy import stats
656
657
# Probability density functions (if available)
658
# normal_pdf = stats.norm.pdf(x, loc=0, scale=1)
659
```
660
661
### Integration with CuPy and SciPy
662
663
```python
664
import cupy as cp
665
import cupyx.scipy
666
import numpy as np
667
import scipy
668
669
# Create mixed CPU/GPU workflow
670
cpu_data = np.random.random((1000, 1000))
671
gpu_data = cp.asarray(cpu_data)
672
673
# Use get_array_module for generic code
674
def process_data(data):
675
# Automatically choose appropriate module
676
xp = cupyx.scipy.get_array_module(data)
677
678
if hasattr(xp, 'ndimage'):
679
filtered = xp.ndimage.gaussian_filter(data, sigma=1.0)
680
else:
681
# Fallback for modules without ndimage
682
filtered = data
683
684
return filtered
685
686
# Works with both CPU and GPU data
687
cpu_result = process_data(cpu_data)
688
gpu_result = process_data(gpu_data)
689
690
# Convert results as needed
691
gpu_result_cpu = cp.asnumpy(gpu_result)
692
```