or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

array-operations.mdcuda-integration.mdcustom-kernels.mdfft.mdindex.mdio-operations.mdjit-compilation.mdlinear-algebra.mdmathematical-functions.mdperformance-profiling.mdpolynomial-operations.mdrandom.mdscipy-extensions.md

scipy-extensions.mddocs/

0

# SciPy Extensions

1

2

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.

3

4

## Capabilities

5

6

### Array Module Detection

7

8

Utility functions for determining appropriate array modules in generic code.

9

10

```python { .api }

11

def get_array_module(*args):

12

"""

13

Get the appropriate array module (cupyx.scipy or scipy) based on input arrays.

14

15

Parameters:

16

args: array_like - Input arrays to inspect

17

18

Returns:

19

module - cupyx.scipy if any input is a CuPy array, otherwise scipy

20

"""

21

```

22

23

### Fast Fourier Transform (cupyx.scipy.fft)

24

25

SciPy-compatible FFT operations with additional functionality beyond cupy.fft.

26

27

```python { .api }

28

# Real FFT functions with SciPy compatibility

29

def rfft(x, n=None, axis=-1, norm=None, overwrite_x=False):

30

"""

31

Compute the 1D discrete Fourier Transform for real input.

32

33

Parameters:

34

x: array_like - Input array

35

n: int, optional - Number of points along transformation axis

36

axis: int, optional - Axis over which to compute the FFT

37

norm: {None, 'ortho'}, optional - Normalization mode

38

overwrite_x: bool, optional - If True, the contents of x can be destroyed

39

"""

40

41

def irfft(x, n=None, axis=-1, norm=None, overwrite_x=False):

42

"""

43

Compute the inverse of the 1D discrete Fourier Transform for real input.

44

45

Parameters:

46

x: array_like - Input array

47

n: int, optional - Length of the transformed axis of the output

48

axis: int, optional - Axis over which to compute the FFT

49

norm: {None, 'ortho'}, optional - Normalization mode

50

overwrite_x: bool, optional - If True, the contents of x can be destroyed

51

"""

52

53

# Discrete Cosine Transform

54

def dct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):

55

"""

56

Return the Discrete Cosine Transform of arbitrary type sequence x.

57

58

Parameters:

59

x: array_like - Input array

60

type: {1, 2, 3, 4}, optional - Type of the DCT (default is 2)

61

n: int, optional - Length of the transform

62

axis: int, optional - Axis along which the dct is computed

63

norm: {None, 'ortho'}, optional - Normalization mode

64

overwrite_x: bool, optional - If True, the contents of x can be destroyed

65

"""

66

67

def idct(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):

68

"""

69

Return the Inverse Discrete Cosine Transform of an arbitrary type sequence.

70

71

Parameters:

72

x: array_like - Input array

73

type: {1, 2, 3, 4}, optional - Type of the DCT (default is 2)

74

n: int, optional - Length of the transform

75

axis: int, optional - Axis along which the idct is computed

76

norm: {None, 'ortho'}, optional - Normalization mode

77

overwrite_x: bool, optional - If True, the contents of x can be destroyed

78

"""

79

80

# Discrete Sine Transform

81

def dst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):

82

"""

83

Return the Discrete Sine Transform of arbitrary type sequence x.

84

85

Parameters:

86

x: array_like - Input array

87

type: {1, 2, 3, 4}, optional - Type of the DST (default is 2)

88

n: int, optional - Length of the transform

89

axis: int, optional - Axis along which the dst is computed

90

norm: {None, 'ortho'}, optional - Normalization mode

91

overwrite_x: bool, optional - If True, the contents of x can be destroyed

92

"""

93

94

def idst(x, type=2, n=None, axis=-1, norm=None, overwrite_x=False):

95

"""

96

Return the Inverse Discrete Sine Transform of an arbitrary type sequence.

97

98

Parameters:

99

x: array_like - Input array

100

type: {1, 2, 3, 4}, optional - Type of the DST (default is 2)

101

n: int, optional - Length of the transform

102

axis: int, optional - Axis along which the idst is computed

103

norm: {None, 'ortho'}, optional - Normalization mode

104

overwrite_x: bool, optional - If True, the contents of x can be destroyed

105

"""

106

```

107

108

### Linear Algebra (cupyx.scipy.linalg)

109

110

Extended linear algebra operations beyond cupy.linalg with SciPy compatibility.

111

112

```python { .api }

113

def solve_banded(l_and_u, ab, b, overwrite_ab=False, overwrite_b=False, debug=None, check_finite=True):

114

"""

115

Solve the equation a x = b for x, assuming a is banded matrix.

116

117

Parameters:

118

l_and_u: (integer, integer) - Number of non-zero lower and upper diagonals

119

ab: (l_and_u[0] + l_and_u[1] + 1, M) array_like - Banded matrix

120

b: (M,) or (M, K) array_like - Right-hand side

121

overwrite_ab: bool, optional - Discard data in ab (may enhance performance)

122

overwrite_b: bool, optional - Discard data in b (may enhance performance)

123

debug: None - Reserved for future use

124

check_finite: bool, optional - Check that input matrices contain only finite numbers

125

"""

126

127

def solve_triangular(a, b, trans=0, lower=False, unit_diagonal=False, overwrite_b=False, debug=None, check_finite=True):

128

"""

129

Solve the equation a x = b for x, assuming a is a triangular matrix.

130

131

Parameters:

132

a: (M, M) array_like - Triangular matrix

133

b: (M,) or (M, N) array_like - Right-hand side matrix or vector

134

trans: {0, 1, 2, 'N', 'T', 'C'}, optional - Type of system to solve

135

lower: bool, optional - Use only data contained in the lower triangle of a

136

unit_diagonal: bool, optional - If True, diagonal elements of a are assumed to be 1

137

overwrite_b: bool, optional - Allow overwriting data in b

138

debug: None - Reserved for future use

139

check_finite: bool, optional - Check that input matrices contain only finite numbers

140

"""

141

142

def lu_factor(a, overwrite_a=False, check_finite=True):

143

"""

144

Compute pivoted LU decomposition of a matrix.

145

146

Parameters:

147

a: (M, N) array_like - Matrix to decompose

148

overwrite_a: bool, optional - Allow data in a to be overwritten

149

check_finite: bool, optional - Check that input matrix contains only finite numbers

150

"""

151

152

def lu_solve(lu_and_piv, b, trans=0, overwrite_b=False, check_finite=True):

153

"""

154

Solve an equation system, a x = b, given the LU factorization of a.

155

156

Parameters:

157

lu_and_piv: tuple - LU factorization of matrix a, as given by lu_factor

158

b: array - Right-hand side

159

trans: {0, 1, 2}, optional - Type of system to solve

160

overwrite_b: bool, optional - Allow data in b to be overwritten

161

check_finite: bool, optional - Check that input arrays contain only finite numbers

162

"""

163

164

def cho_factor(a, lower=False, overwrite_a=False, check_finite=True):

165

"""

166

Compute the Cholesky decomposition of a matrix.

167

168

Parameters:

169

a: (M, M) array_like - Matrix to be decomposed

170

lower: bool, optional - Whether to compute the upper or lower triangular Cholesky factorization

171

overwrite_a: bool, optional - Allow data in a to be overwritten

172

check_finite: bool, optional - Check that input matrix contains only finite numbers

173

"""

174

175

def cho_solve(c_and_lower, b, overwrite_b=False, check_finite=True):

176

"""

177

Solve the linear equations A x = b, given the Cholesky factorization of A.

178

179

Parameters:

180

c_and_lower: tuple - Cholesky factorization of a, as given by cho_factor

181

b: array - Right-hand side

182

overwrite_b: bool, optional - Allow data in b to be overwritten

183

check_finite: bool, optional - Check that input arrays contain only finite numbers

184

"""

185

186

def block_diag(*arrs):

187

"""

188

Create a block diagonal matrix from provided arrays.

189

190

Parameters:

191

arrs: sequence of array_like - Input arrays

192

"""

193

194

def tril(m, k=0):

195

"""

196

Make a copy of a matrix with elements above the k-th diagonal zeroed.

197

198

Parameters:

199

m: array_like - Matrix whose lower triangle is desired

200

k: int, optional - Diagonal above which to zero elements

201

"""

202

203

def triu(m, k=0):

204

"""

205

Make a copy of a matrix with elements below the k-th diagonal zeroed.

206

207

Parameters:

208

m: array_like - Matrix whose upper triangle is desired

209

k: int, optional - Diagonal below which to zero elements

210

"""

211

```

212

213

### Sparse Matrices (cupyx.scipy.sparse)

214

215

Comprehensive sparse matrix operations and formats for memory-efficient computation.

216

217

```python { .api }

218

class spmatrix:

219

"""

220

Base sparse matrix class.

221

222

This is the base class for all sparse matrix formats in CuPy.

223

"""

224

def __init__(self): ...

225

226

def toarray(self): ...

227

def tocsr(self, copy=False): ...

228

def tocsc(self, copy=False): ...

229

def tocoo(self, copy=False): ...

230

def todia(self, copy=False): ...

231

def todense(self): ...

232

233

def multiply(self, other): ...

234

def maximum(self, other): ...

235

def minimum(self, other): ...

236

237

@property

238

def shape(self): ...

239

@property

240

def dtype(self): ...

241

@property

242

def nnz(self): ...

243

244

class csr_matrix(spmatrix):

245

"""

246

Compressed Sparse Row matrix.

247

248

Efficient for arithmetic operations and matrix-vector products.

249

"""

250

def __init__(self, arg1, shape=None, dtype=None, copy=False): ...

251

252

def eliminate_zeros(self): ...

253

def sum_duplicates(self): ...

254

def sort_indices(self): ...

255

def has_sorted_indices(self): ...

256

257

class csc_matrix(spmatrix):

258

"""

259

Compressed Sparse Column matrix.

260

261

Efficient for column slicing and operations requiring column access.

262

"""

263

def __init__(self, arg1, shape=None, dtype=None, copy=False): ...

264

265

def eliminate_zeros(self): ...

266

def sum_duplicates(self): ...

267

def sort_indices(self): ...

268

def has_sorted_indices(self): ...

269

270

class coo_matrix(spmatrix):

271

"""

272

A sparse matrix in COOrdinate format (aka triplet format).

273

274

Efficient for constructing sparse matrices incrementally.

275

"""

276

def __init__(self, arg1, shape=None, dtype=None, copy=False): ...

277

278

def eliminate_zeros(self): ...

279

def sum_duplicates(self): ...

280

281

class dia_matrix(spmatrix):

282

"""

283

Sparse matrix with DIAgonal storage.

284

285

Efficient for matrices with few diagonals.

286

"""

287

def __init__(self, arg1, shape=None, dtype=None, copy=False): ...

288

289

# Sparse matrix construction functions

290

def eye(m, n=None, k=0, dtype=float, format=None):

291

"""

292

Sparse identity matrix.

293

294

Parameters:

295

m: int - Number of rows

296

n: int, optional - Number of columns (default equals m)

297

k: int, optional - Diagonal offset

298

dtype: dtype, optional - Data type of the matrix

299

format: str, optional - Sparse format of the result

300

"""

301

302

def identity(n, dtype='d', format=None):

303

"""

304

Identity matrix in sparse format.

305

306

Parameters:

307

n: int - Size of the identity matrix

308

dtype: dtype, optional - Data type of the matrix

309

format: str, optional - Sparse format of the result

310

"""

311

312

def spdiags(data, diags, m, n, format=None):

313

"""

314

Return a sparse matrix from diagonals.

315

316

Parameters:

317

data: array_like - Matrix diagonals stored row-wise

318

diags: sequence - Diagonal offsets

319

m, n: int - Shape of the result

320

format: str, optional - Sparse format of the result

321

"""

322

323

def diags(diagonals, offsets=0, shape=None, format=None, dtype=None):

324

"""

325

Construct a sparse matrix from diagonals.

326

327

Parameters:

328

diagonals: sequence of array_like - Diagonal values

329

offsets: sequence of int or int - Diagonal offsets

330

shape: tuple, optional - Shape of the result

331

format: str, optional - Sparse format of the result

332

dtype: dtype, optional - Data type of the result

333

"""

334

335

def rand(m, n, density=0.01, format='coo', dtype=None, random_state=None):

336

"""

337

Generate a sparse matrix of the given shape and density with uniformly distributed values.

338

339

Parameters:

340

m, n: int - Shape of the matrix

341

density: real, optional - Density of the generated matrix

342

format: str, optional - Sparse format of the result

343

dtype: dtype, optional - Type of the returned matrix values

344

random_state: int or RandomState, optional - Random number generator seed

345

"""

346

347

def random(m, n, density=0.01, format='coo', dtype=None, random_state=None, data_rvs=None):

348

"""

349

Generate a sparse matrix of the given shape and density with random values.

350

351

Parameters:

352

m, n: int - Shape of the matrix

353

density: real, optional - Density of the generated matrix

354

format: str, optional - Sparse format of the result

355

dtype: dtype, optional - Type of the returned matrix values

356

random_state: int or RandomState, optional - Random number generator seed

357

data_rvs: callable, optional - Samples the data values (default uniform on [0,1))

358

"""

359

360

# Sparse matrix operations

361

def kron(A, B, format=None):

362

"""

363

Kronecker product of two sparse matrices.

364

365

Parameters:

366

A, B: sparse or dense matrices - Input matrices

367

format: str, optional - Format of the result

368

"""

369

370

def kronsum(A, B, format=None):

371

"""

372

Kronecker sum of two sparse matrices.

373

374

Parameters:

375

A, B: sparse matrices - Input matrices

376

format: str, optional - Format of the result

377

"""

378

379

def hstack(blocks, format=None, dtype=None):

380

"""

381

Stack sparse matrices horizontally (column wise).

382

383

Parameters:

384

blocks: sequence - Sparse matrices with compatible first dimensions

385

format: str, optional - Format of the result

386

dtype: dtype, optional - Type of the result

387

"""

388

389

def vstack(blocks, format=None, dtype=None):

390

"""

391

Stack sparse matrices vertically (row wise).

392

393

Parameters:

394

blocks: sequence - Sparse matrices with compatible second dimensions

395

format: str, optional - Format of the result

396

dtype: dtype, optional - Type of the result

397

"""

398

399

def bmat(blocks, format=None, dtype=None):

400

"""

401

Build a sparse matrix from sparse sub-blocks.

402

403

Parameters:

404

blocks: array_like - Grid of sparse matrices

405

format: str, optional - Format of the result

406

dtype: dtype, optional - Type of the result

407

"""

408

409

# Sparse matrix utilities

410

def issparse(x):

411

"""

412

Check whether x is a sparse matrix.

413

414

Parameters:

415

x: any - Object to check

416

"""

417

418

def isspmatrix(x):

419

"""

420

Check whether x is a sparse matrix (alias for issparse).

421

422

Parameters:

423

x: any - Object to check

424

"""

425

426

def isspmatrix_csr(x):

427

"""

428

Check whether x is a CSR matrix.

429

430

Parameters:

431

x: any - Object to check

432

"""

433

434

def isspmatrix_csc(x):

435

"""

436

Check whether x is a CSC matrix.

437

438

Parameters:

439

x: any - Object to check

440

"""

441

442

def isspmatrix_coo(x):

443

"""

444

Check whether x is a COO matrix.

445

446

Parameters:

447

x: any - Object to check

448

"""

449

450

def find(A):

451

"""

452

Return the indices and values of the nonzero elements of a matrix.

453

454

Parameters:

455

A: sparse matrix - Input matrix

456

"""

457

458

def tril(A, k=0, format=None):

459

"""

460

Return the lower triangular portion of a matrix in sparse format.

461

462

Parameters:

463

A: sparse matrix - Input matrix

464

k: int, optional - Diagonal offset

465

format: str, optional - Sparse format of the result

466

"""

467

468

def triu(A, k=0, format=None):

469

"""

470

Return the upper triangular portion of a matrix in sparse format.

471

472

Parameters:

473

A: sparse matrix - Input matrix

474

k: int, optional - Diagonal offset

475

format: str, optional - Sparse format of the result

476

"""

477

```

478

479

### Signal Processing (cupyx.scipy.signal)

480

481

Signal processing operations including filtering, convolution, and spectral analysis.

482

483

```python { .api }

484

def convolve(in1, in2, mode='full', method='auto'):

485

"""

486

Convolve two N-dimensional arrays.

487

488

Parameters:

489

in1: array_like - First input array

490

in2: array_like - Second input array

491

mode: str, optional - Size of output ('full', 'valid', 'same')

492

method: str, optional - Method to use for convolution ('auto', 'direct', 'fft')

493

"""

494

495

def correlate(in1, in2, mode='full', method='auto'):

496

"""

497

Cross-correlate two N-dimensional arrays.

498

499

Parameters:

500

in1: array_like - First input array

501

in2: array_like - Second input array

502

mode: str, optional - Size of output ('full', 'valid', 'same')

503

method: str, optional - Method to use for correlation ('auto', 'direct', 'fft')

504

"""

505

506

def fftconvolve(in1, in2, mode='full', axes=None):

507

"""

508

Convolve two N-dimensional arrays using FFT.

509

510

Parameters:

511

in1: array_like - First input array

512

in2: array_like - Second input array

513

mode: str, optional - Size of output ('full', 'valid', 'same')

514

axes: int or array_like of ints or None, optional - Axes over which to compute convolution

515

"""

516

517

def convolve2d(in1, in2, mode='full', boundary='fill', fillvalue=0):

518

"""

519

Convolve two 2-dimensional arrays.

520

521

Parameters:

522

in1: array_like - First input array

523

in2: array_like - Second input array

524

mode: str, optional - Size of output ('full', 'valid', 'same')

525

boundary: str, optional - Flag indicating how to handle boundaries

526

fillvalue: scalar, optional - Value to fill pad input arrays with

527

"""

528

529

def correlate2d(in1, in2, mode='full', boundary='fill', fillvalue=0):

530

"""

531

Cross-correlate two 2-dimensional arrays.

532

533

Parameters:

534

in1: array_like - First input array

535

in2: array_like - Second input array

536

mode: str, optional - Size of output ('full', 'valid', 'same')

537

boundary: str, optional - Flag indicating how to handle boundaries

538

fillvalue: scalar, optional - Value to fill pad input arrays with

539

"""

540

541

def sepfir2d(input, hrow, hcol):

542

"""

543

Convolve with a 2-D separable FIR filter.

544

545

Parameters:

546

input: array_like - Input array to filter

547

hrow: array_like - 1-D filter for rows

548

hcol: array_like - 1-D filter for columns

549

"""

550

551

def lfilter(b, a, x, axis=-1, zi=None):

552

"""

553

Filter data along one-dimension with an IIR or FIR filter.

554

555

Parameters:

556

b: array_like - Numerator coefficient vector

557

a: array_like - Denominator coefficient vector

558

x: array_like - Input data array

559

axis: int, optional - Axis of x to which the filter is applied

560

zi: array_like, optional - Initial conditions for the filter delays

561

"""

562

563

def filtfilt(b, a, x, axis=-1, padtype='odd', padlen=None, method='pad', irlen=None):

564

"""

565

Apply a digital filter forward and backward to a signal.

566

567

Parameters:

568

b: array_like - Numerator coefficient vector

569

a: array_like - Denominator coefficient vector

570

x: array_like - Input data array

571

axis: int, optional - Axis of x to which the filter is applied

572

padtype: str or None, optional - Type of padding to use

573

padlen: int or None, optional - Number of elements by which to extend x

574

method: str, optional - Determines the method for handling the edges

575

irlen: int or None, optional - Length of impulse response of filter

576

"""

577

578

def hilbert(x, N=None, axis=-1):

579

"""

580

Compute the analytic signal, using the Hilbert transform.

581

582

Parameters:

583

x: array_like - Signal data

584

N: int, optional - Length of the Hilbert transform

585

axis: int, optional - Axis along which to do the transformation

586

"""

587

588

def hilbert2(x, N=None):

589

"""

590

Compute the '2-D' analytic signal of x.

591

592

Parameters:

593

x: array_like - 2-D signal data

594

N: int or array_like of two ints, optional - Length of the Hilbert transform

595

"""

596

597

# Window functions

598

def get_window(window, Nx, fftbins=True):

599

"""

600

Return a window function.

601

602

Parameters:

603

window: string, float, or tuple - Type of window to create

604

Nx: int - Length of the window

605

fftbins: bool, optional - Generate symmetric window for use in filter design

606

"""

607

608

def hann(M, sym=True):

609

"""

610

Return a Hann window.

611

612

Parameters:

613

M: int - Number of points in the output window

614

sym: bool, optional - Generate symmetric window

615

"""

616

617

def hamming(M, sym=True):

618

"""

619

Return a Hamming window.

620

621

Parameters:

622

M: int - Number of points in the output window

623

sym: bool, optional - Generate symmetric window

624

"""

625

626

def blackman(M, sym=True):

627

"""

628

Return a Blackman window.

629

630

Parameters:

631

M: int - Number of points in the output window

632

sym: bool, optional - Generate symmetric window

633

"""

634

```

635

636

### Image Processing (cupyx.scipy.ndimage)

637

638

N-dimensional image processing operations including filtering, morphology, and geometric transformations.

639

640

```python { .api }

641

def gaussian_filter(input, sigma, order=0, output=None, mode='reflect', cval=0.0, truncate=4.0):

642

"""

643

Multidimensional Gaussian filter.

644

645

Parameters:

646

input: array_like - Input array

647

sigma: scalar or sequence of scalars - Standard deviation for Gaussian kernel

648

order: int or sequence of ints, optional - Order of the filter along each axis

649

output: array or dtype, optional - Array in which to place the output

650

mode: str or sequence, optional - Points outside boundaries are filled according to the given mode

651

cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'

652

truncate: float, optional - Truncate the filter at this many standard deviations

653

"""

654

655

def uniform_filter(input, size=3, output=None, mode='reflect', cval=0.0, origin=0):

656

"""

657

Multidimensional uniform filter.

658

659

Parameters:

660

input: array_like - Input array

661

size: int or sequence of ints - Shape that is taken from the input array

662

output: array or dtype, optional - Array in which to place the output

663

mode: str, optional - Points outside boundaries are filled according to the given mode

664

cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'

665

origin: int or sequence, optional - Controls the placement of the filter on the input array

666

"""

667

668

def median_filter(input, size=None, footprint=None, output=None, mode='reflect', cval=0.0, origin=0):

669

"""

670

Calculate a multidimensional median filter.

671

672

Parameters:

673

input: array_like - Input array

674

size: scalar or tuple, optional - See footprint, below. Ignored if footprint is given

675

footprint: array, optional - Either size or footprint must be defined

676

output: array or dtype, optional - Array in which to place the output

677

mode: str, optional - Points outside boundaries are filled according to the given mode

678

cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'

679

origin: int or sequence, optional - Controls the placement of the filter on the input array

680

"""

681

682

def maximum_filter(input, size=None, footprint=None, output=None, mode='reflect', cval=0.0, origin=0):

683

"""

684

Calculate a multidimensional maximum filter.

685

686

Parameters:

687

input: array_like - Input array

688

size: scalar or tuple, optional - See footprint, below. Ignored if footprint is given

689

footprint: array, optional - Either size or footprint must be defined

690

output: array or dtype, optional - Array in which to place the output

691

mode: str, optional - Points outside boundaries are filled according to the given mode

692

cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'

693

origin: int or sequence, optional - Controls the placement of the filter on the input array

694

"""

695

696

def minimum_filter(input, size=None, footprint=None, output=None, mode='reflect', cval=0.0, origin=0):

697

"""

698

Calculate a multidimensional minimum filter.

699

700

Parameters:

701

input: array_like - Input array

702

size: scalar or tuple, optional - See footprint, below. Ignored if footprint is given

703

footprint: array, optional - Either size or footprint must be defined

704

output: array or dtype, optional - Array in which to place the output

705

mode: str, optional - Points outside boundaries are filled according to the given mode

706

cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'

707

origin: int or sequence, optional - Controls the placement of the filter on the input array

708

"""

709

710

def rotate(input, angle, axes=(1, 0), reshape=True, output=None, order=1, mode='constant', cval=0.0, prefilter=True):

711

"""

712

Rotate an array.

713

714

Parameters:

715

input: array_like - Input array

716

angle: float - Rotation angle in degrees

717

axes: tuple of 2 ints, optional - Plane of rotation specified by axes

718

reshape: bool, optional - Reshape the output array so that the input array is contained completely

719

output: array or dtype, optional - Array in which to place the output

720

order: int, optional - Spline interpolation order (0-5)

721

mode: str, optional - Points outside boundaries are filled according to the given mode

722

cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'

723

prefilter: bool, optional - Apply spline filter before interpolation

724

"""

725

726

def zoom(input, zoom, output=None, order=1, mode='constant', cval=0.0, prefilter=True):

727

"""

728

Zoom an array.

729

730

Parameters:

731

input: array_like - Input array

732

zoom: float or sequence - Zoom factor along the axes

733

output: array or dtype, optional - Array in which to place the output

734

order: int, optional - Spline interpolation order (0-5)

735

mode: str, optional - Points outside boundaries are filled according to the given mode

736

cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'

737

prefilter: bool, optional - Apply spline filter before interpolation

738

"""

739

740

def shift(input, shift, output=None, order=1, mode='constant', cval=0.0, prefilter=True):

741

"""

742

Shift an array.

743

744

Parameters:

745

input: array_like - Input array

746

shift: float or sequence - Shift along the axes

747

output: array or dtype, optional - Array in which to place the output

748

order: int, optional - Spline interpolation order (0-5)

749

mode: str, optional - Points outside boundaries are filled according to the given mode

750

cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'

751

prefilter: bool, optional - Apply spline filter before interpolation

752

"""

753

754

def affine_transform(input, matrix, offset=0.0, output_shape=None, output=None, order=1, mode='constant', cval=0.0, prefilter=True):

755

"""

756

Apply an affine transformation.

757

758

Parameters:

759

input: array_like - Input array

760

matrix: ndarray - Transformation matrix

761

offset: float or sequence, optional - Offset vector

762

output_shape: tuple of ints, optional - Shape of the output array

763

output: array or dtype, optional - Array in which to place the output

764

order: int, optional - Spline interpolation order (0-5)

765

mode: str, optional - Points outside boundaries are filled according to the given mode

766

cval: scalar, optional - Value used for points outside the boundaries when mode is 'constant'

767

prefilter: bool, optional - Apply spline filter before interpolation

768

"""

769

770

# Morphological operations

771

def binary_erosion(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False):

772

"""

773

Multidimensional binary erosion with the given structuring element.

774

775

Parameters:

776

input: array_like - Binary array_like to be eroded

777

structure: array_like, optional - Structuring element used for the erosion

778

iterations: int, optional - Number of times to repeat the erosion

779

mask: array_like, optional - Mask array that defines (>0) pixels that are considered

780

output: ndarray, optional - Array of the same shape as input for the output

781

border_value: int (cast to 0 or 1), optional - Value at the border in the output array

782

origin: int or tuple of ints, optional - Placement of the filter

783

brute_force: boolean, optional - Memory condition: if False, only the pixels whose value was changed are tracked

784

"""

785

786

def binary_dilation(input, structure=None, iterations=1, mask=None, output=None, border_value=0, origin=0, brute_force=False):

787

"""

788

Multidimensional binary dilation with the given structuring element.

789

790

Parameters:

791

input: array_like - Binary array_like to be dilated

792

structure: array_like, optional - Structuring element used for the dilation

793

iterations: int, optional - Number of times to repeat the dilation

794

mask: array_like, optional - Mask array that defines (>0) pixels that are considered

795

output: ndarray, optional - Array of the same shape as input for the output

796

border_value: int (cast to 0 or 1), optional - Value at the border in the output array

797

origin: int or tuple of ints, optional - Placement of the filter

798

brute_force: boolean, optional - Memory condition: if False, only the pixels whose value was changed are tracked

799

"""

800

801

def binary_opening(input, structure=None, iterations=1, output=None, origin=0):

802

"""

803

Multidimensional binary opening with the given structuring element.

804

805

Parameters:

806

input: array_like - Binary array_like to be opened

807

structure: array_like, optional - Structuring element used for the opening

808

iterations: int, optional - Number of times to repeat the operation

809

output: ndarray, optional - Array of the same shape as input for the output

810

origin: int or tuple of ints, optional - Placement of the filter

811

"""

812

813

def binary_closing(input, structure=None, iterations=1, output=None, origin=0):

814

"""

815

Multidimensional binary closing with the given structuring element.

816

817

Parameters:

818

input: array_like - Binary array_like to be closed

819

structure: array_like, optional - Structuring element used for the closing

820

iterations: int, optional - Number of times to repeat the operation

821

output: ndarray, optional - Array of the same shape as input for the output

822

origin: int or tuple of ints, optional - Placement of the filter

823

"""

824

825

# Label and connectivity

826

def label(input, structure=None, output=None):

827

"""

828

Label features in an array.

829

830

Parameters:

831

input: array of ints - Input array

832

structure: array of ints, optional - Structuring element that defines feature connections

833

output: (None, data-type, array of data-type), optional - Array of the same shape as input

834

"""

835

836

def find_objects(input, max_label=0):

837

"""

838

Find objects in a labeled array.

839

840

Parameters:

841

input: ndarray of ints - Array containing integer objects

842

max_label: int, optional - Maximum label to search for

843

"""

844

845

def center_of_mass(input, labels=None, index=None):

846

"""

847

Calculate the center of mass of the values of an array at labels.

848

849

Parameters:

850

input: ndarray - Data from which to calculate center-of-mass

851

labels: ndarray, optional - Labels for objects in input

852

index: int or sequence of ints, optional - Labels for which to calculate centers

853

"""

854

```

855

856

### Special Functions (cupyx.scipy.special)

857

858

Mathematical special functions for advanced scientific computation.

859

860

```python { .api }

861

def gamma(z, out=None):

862

"""

863

Gamma function.

864

865

Parameters:

866

z: array_like - Input values

867

out: ndarray, optional - Optional output array for the function results

868

"""

869

870

def gammaln(z, out=None):

871

"""

872

Logarithm of the absolute value of the Gamma function.

873

874

Parameters:

875

z: array_like - Input values

876

out: ndarray, optional - Optional output array for the function results

877

"""

878

879

def digamma(z, out=None):

880

"""

881

The digamma function (psi function).

882

883

Parameters:

884

z: array_like - Input values

885

out: ndarray, optional - Optional output array for the function results

886

"""

887

888

def erf(z, out=None):

889

"""

890

Error function.

891

892

Parameters:

893

z: array_like - Input values

894

out: ndarray, optional - Optional output array for the function results

895

"""

896

897

def erfc(z, out=None):

898

"""

899

Complementary error function.

900

901

Parameters:

902

z: array_like - Input values

903

out: ndarray, optional - Optional output array for the function results

904

"""

905

906

def erfcx(z, out=None):

907

"""

908

Scaled complementary error function.

909

910

Parameters:

911

z: array_like - Input values

912

out: ndarray, optional - Optional output array for the function results

913

"""

914

915

def erfinv(z, out=None):

916

"""

917

Inverse error function.

918

919

Parameters:

920

z: array_like - Input values

921

out: ndarray, optional - Optional output array for the function results

922

"""

923

924

def j0(z, out=None):

925

"""

926

Bessel function of the first kind of order 0.

927

928

Parameters:

929

z: array_like - Input values

930

out: ndarray, optional - Optional output array for the function results

931

"""

932

933

def j1(z, out=None):

934

"""

935

Bessel function of the first kind of order 1.

936

937

Parameters:

938

z: array_like - Input values

939

out: ndarray, optional - Optional output array for the function results

940

"""

941

942

def y0(z, out=None):

943

"""

944

Bessel function of the second kind of order 0.

945

946

Parameters:

947

z: array_like - Input values

948

out: ndarray, optional - Optional output array for the function results

949

"""

950

951

def y1(z, out=None):

952

"""

953

Bessel function of the second kind of order 1.

954

955

Parameters:

956

z: array_like - Input values

957

out: ndarray, optional - Optional output array for the function results

958

"""

959

960

def i0(z, out=None):

961

"""

962

Modified Bessel function of the first kind of order 0.

963

964

Parameters:

965

z: array_like - Input values

966

out: ndarray, optional - Optional output array for the function results

967

"""

968

969

def i1(z, out=None):

970

"""

971

Modified Bessel function of the first kind of order 1.

972

973

Parameters:

974

z: array_like - Input values

975

out: ndarray, optional - Optional output array for the function results

976

"""

977

978

def k0(z, out=None):

979

"""

980

Modified Bessel function of the second kind of order 0.

981

982

Parameters:

983

z: array_like - Input values

984

out: ndarray, optional - Optional output array for the function results

985

"""

986

987

def k1(z, out=None):

988

"""

989

Modified Bessel function of the second kind of order 1.

990

991

Parameters:

992

z: array_like - Input values

993

out: ndarray, optional - Optional output array for the function results

994

"""

995

```

996

997

### Statistical Functions (cupyx.scipy.stats)

998

999

Statistical distributions and hypothesis testing functions.

1000

1001

```python { .api }

1002

def norm():

1003

"""

1004

A normal continuous random variable.

1005

1006

This object has methods for probability density function (pdf),

1007

cumulative distribution function (cdf), survival function (sf),

1008

percent point function (ppf), and random variates (rvs).

1009

"""

1010

1011

def chi2():

1012

"""

1013

A chi-squared continuous random variable.

1014

1015

This object has methods for probability density function (pdf),

1016

cumulative distribution function (cdf), survival function (sf),

1017

percent point function (ppf), and random variates (rvs).

1018

"""

1019

1020

def t():

1021

"""

1022

A Student's t continuous random variable.

1023

1024

This object has methods for probability density function (pdf),

1025

cumulative distribution function (cdf), survival function (sf),

1026

percent point function (ppf), and random variates (rvs).

1027

"""

1028

1029

def f():

1030

"""

1031

An F continuous random variable.

1032

1033

This object has methods for probability density function (pdf),

1034

cumulative distribution function (cdf), survival function (sf),

1035

percent point function (ppf), and random variates (rvs).

1036

"""

1037

```

1038

1039

## Usage Examples

1040

1041

```python

1042

import cupy as cp

1043

import cupyx.scipy as scipy

1044

import cupyx.scipy.sparse as sparse

1045

import cupyx.scipy.ndimage as ndimage

1046

import cupyx.scipy.signal as signal

1047

import cupyx.scipy.linalg as linalg

1048

1049

# Sparse matrix operations

1050

# Create sparse matrices

1051

data = cp.array([1, 2, 3, 4])

1052

row = cp.array([0, 1, 2, 3])

1053

col = cp.array([0, 1, 2, 3])

1054

coo = sparse.coo_matrix((data, (row, col)), shape=(4, 4))

1055

1056

# Convert between formats

1057

csr = coo.tocsr()

1058

csc = coo.tocsc()

1059

1060

# Sparse matrix arithmetic

1061

A = sparse.random(1000, 1000, density=0.01)

1062

B = sparse.random(1000, 1000, density=0.01)

1063

C = A @ B # Matrix multiplication

1064

1065

# Sparse linear algebra

1066

x = sparse.linalg.spsolve(A, cp.random.rand(1000))

1067

1068

# Image processing with ndimage

1069

# Load or generate image data

1070

image = cp.random.rand(512, 512)

1071

1072

# Apply Gaussian filter

1073

smoothed = ndimage.gaussian_filter(image, sigma=2.0)

1074

1075

# Edge detection with gradients

1076

sobel_x = ndimage.sobel(image, axis=0)

1077

sobel_y = ndimage.sobel(image, axis=1)

1078

edges = cp.sqrt(sobel_x**2 + sobel_y**2)

1079

1080

# Morphological operations

1081

binary_image = image > 0.5

1082

opened = ndimage.binary_opening(binary_image)

1083

closed = ndimage.binary_closing(binary_image)

1084

1085

# Geometric transformations

1086

rotated = ndimage.rotate(image, 45, reshape=False)

1087

zoomed = ndimage.zoom(image, 2.0)

1088

1089

# Label connected components

1090

labeled, num_features = ndimage.label(binary_image)

1091

centers = ndimage.center_of_mass(image, labeled,

1092

range(1, num_features + 1))

1093

1094

# Signal processing

1095

# Generate test signal

1096

fs = 1000

1097

t = cp.linspace(0, 1, fs, endpoint=False)

1098

signal_data = cp.sin(2 * cp.pi * 50 * t) + 0.5 * cp.sin(2 * cp.pi * 120 * t)

1099

1100

# Convolution and correlation

1101

kernel = signal.hann(51)

1102

convolved = signal.convolve(signal_data, kernel, mode='same')

1103

correlated = signal.correlate(signal_data, kernel, mode='same')

1104

1105

# FFT-based convolution (faster for large signals)

1106

fft_convolved = signal.fftconvolve(signal_data, kernel, mode='same')

1107

1108

# Digital filtering

1109

b, a = signal.butter(4, 0.2) # 4th order Butterworth filter

1110

filtered = signal.filtfilt(b, a, signal_data)

1111

1112

# Hilbert transform for analytic signal

1113

analytic = signal.hilbert(signal_data)

1114

amplitude = cp.abs(analytic)

1115

phase = cp.angle(analytic)

1116

1117

# 2D signal processing

1118

image_2d = cp.random.rand(256, 256)

1119

kernel_2d = cp.ones((5, 5)) / 25 # Simple averaging kernel

1120

filtered_2d = signal.convolve2d(image_2d, kernel_2d, mode='same')

1121

1122

# Linear algebra extensions

1123

# Solve banded systems

1124

ab = cp.random.rand(5, 100) # Banded matrix storage

1125

b_vec = cp.random.rand(100)

1126

x = linalg.solve_banded((2, 2), ab, b_vec)

1127

1128

# Triangular systems

1129

L = cp.tril(cp.random.rand(100, 100)) # Lower triangular

1130

x_tri = linalg.solve_triangular(L, b_vec, lower=True)

1131

1132

# Cholesky factorization

1133

A_pos = cp.random.rand(100, 100)

1134

A_pos = A_pos @ A_pos.T + cp.eye(100) # Make positive definite

1135

cho_fac, lower = linalg.cho_factor(A_pos)

1136

x_cho = linalg.cho_solve((cho_fac, lower), b_vec)

1137

1138

# Block diagonal matrices

1139

blocks = [cp.random.rand(10, 10) for _ in range(5)]

1140

block_diag = linalg.block_diag(*blocks)

1141

1142

# FFT extensions with SciPy compatibility

1143

# Discrete Cosine Transform

1144

dct_result = scipy.fft.dct(signal_data)

1145

reconstructed = scipy.fft.idct(dct_result)

1146

1147

# Discrete Sine Transform

1148

dst_result = scipy.fft.dst(signal_data)

1149

dst_reconstructed = scipy.fft.idst(dst_result)

1150

1151

# Special functions

1152

x = cp.linspace(0.1, 5, 100)

1153

gamma_values = scipy.special.gamma(x)

1154

log_gamma = scipy.special.gammaln(x)

1155

erf_values = scipy.special.erf(x)

1156

bessel_j0 = scipy.special.j0(x)

1157

1158

# Advanced sparse matrix operations

1159

# Construct large sparse system

1160

n = 10000

1161

# Create a sparse Laplacian matrix

1162

diagonals = [-cp.ones(n-1), 2*cp.ones(n), -cp.ones(n-1)]

1163

offsets = [-1, 0, 1]

1164

laplacian = sparse.diags(diagonals, offsets, format='csr')

1165

1166

# Solve sparse linear system

1167

rhs = cp.random.rand(n)

1168

solution = sparse.linalg.spsolve(laplacian, rhs)

1169

1170

# Eigenvalue problems for sparse matrices

1171

eigenvals, eigenvecs = sparse.linalg.eigsh(laplacian, k=10, which='SM')

1172

1173

# Sparse matrix I/O and manipulation

1174

# Find nonzero elements

1175

rows, cols, values = sparse.find(laplacian)

1176

1177

# Extract triangular parts

1178

upper_tri = sparse.triu(laplacian)

1179

lower_tri = sparse.tril(laplacian)

1180

1181

# Kronecker products for tensor operations

1182

small_matrix = sparse.diags([1, -2, 1], [-1, 0, 1], shape=(10, 10))

1183

tensor_op = sparse.kron(small_matrix, sparse.eye(100))

1184

1185

# Performance comparison example

1186

def compare_dense_vs_sparse(n=1000, density=0.01):

1187

"""Compare dense vs sparse matrix operations."""

1188

1189

# Create sparse matrix

1190

A_sparse = sparse.random(n, n, density=density, format='csr')

1191

1192

# Convert to dense

1193

A_dense = A_sparse.toarray()

1194

1195

# Vector for multiplication

1196

x = cp.random.rand(n)

1197

1198

import time

1199

1200

# Time sparse multiplication

1201

start = time.time()

1202

y_sparse = A_sparse @ x

1203

sparse_time = time.time() - start

1204

1205

# Time dense multiplication

1206

start = time.time()

1207

y_dense = A_dense @ x

1208

dense_time = time.time() - start

1209

1210

print(f"Sparse: {sparse_time:.4f}s, Dense: {dense_time:.4f}s")

1211

print(f"Speedup: {dense_time/sparse_time:.2f}x")

1212

1213

return sparse_time, dense_time

1214

1215

# Advanced image processing pipeline

1216

def image_processing_pipeline(image):

1217

"""Complete image processing pipeline."""

1218

1219

# Preprocessing

1220

smoothed = ndimage.gaussian_filter(image, sigma=1.0)

1221

1222

# Edge detection

1223

edges = ndimage.sobel(smoothed)

1224

1225

# Thresholding

1226

binary = edges > cp.percentile(edges, 90)

1227

1228

# Morphological cleanup

1229

cleaned = ndimage.binary_opening(binary, iterations=2)

1230

cleaned = ndimage.binary_closing(cleaned, iterations=2)

1231

1232

# Label connected components

1233

labeled, num_objects = ndimage.label(cleaned)

1234

1235

# Find object properties

1236

centers = ndimage.center_of_mass(image, labeled,

1237

range(1, num_objects + 1))

1238

1239

return {

1240

'processed': cleaned,

1241

'labeled': labeled,

1242

'num_objects': num_objects,

1243

'centers': centers

1244

}

1245

1246

# Example usage

1247

sample_image = cp.random.rand(512, 512)

1248

results = image_processing_pipeline(sample_image)

1249

```

1250

1251

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.