RiptideRiptide
Download Riptide SDKInstall Riptorch
Menu
Raya docs · Numerical computing

Sparse linear algebra

COO, CSR, CSC and BSR matrices, SIMD sparse products, Krylov solvers (CG, PCG, GMRES, BiCGSTAB, MINRES) with Jacobi, ILU(0) and IC(0) preconditioners, reorderings and sparse Cholesky.

import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
21 classes81 functions and methods66 of 135 documented70 runnable examplesWhat scipy.sparse does

Overview

Sparse linear algebra. The GPU SpMV lives in riptide_numerics_gpu.

What's in it

FileContents
formats.rayCooMatrix (build here; duplicates summed on compression), CsrMatrix (SpMV, A^{T}x, SpMM with Float64x2 lanes over the right-hand sides, Gustavson sparse × sparse, add, transpose, triangle, symmetric permutation, diags, dense round trip), CscMatrix, BsrMatrix (dense r \times c blocks; 2 \times 2 and 3 \times 3 unrolled)
operator.rayLinearOperator (what the solvers take: any format, DenseOperator, matrix-free FunctionOperator), level-1 Vec kernels
krylov.rayKrylov.cg (PCG with a preconditioner), gmres (restarted, right-preconditioned, MGS + reorthogonalisation, Givens), bicgstab (right-preconditioned), minres (Paige–Saunders, SPD preconditioner); SciPy's stopping rule \Vert r\Vert \le \max(rtol‖b‖, atol); SolveResult.residual is the true residual recomputed at the end
preconditioners.rayJacobiPreconditioner, Ilu0Preconditioner (Saad Alg. 10.4), IncompleteCholeskyPreconditioner (IC(0) with Manteuffel's diagonal shift on breakdown)
ordering.rayOrdering.reverseCuthillMcKee (George–Liu pseudo-peripheral start), Ordering.approximateMinimumDegree (quotient graph, element absorption, the AMD degree bound with w(e) counters and aggressive absorption; no supervariables or mass elimination yet), bandwidth
direct.raySparseCholesky and SparseLdlt (up-looking, elimination tree + row reach in topological order; FillOrdering.natural / reverseCuthillMcKee / approximateMinimumDegree); log-determinant, inertia
io.ray, gallery.rayMatrix Market read/write; 2-D Poisson and 1-D convection–diffusion test matrices

The CSR arrays (indptr, indices, data) are SciPy's csr_matrix layout, so they map 1:1 onto part A's NDArray (three 1-D arrays) and onto the GPU SpMV buffers (data narrowed to f32 with dataAsFloat32).

Correctness

Fixtures from SciPy 1.18.1 / NumPy 2.5.4: COO→CSR (duplicates, sorting) exact; SpMV, A^{T}x, SpMM, sparse × sparse, transpose within 1e-14 (sparsity pattern identical); CG, GMRES, BiCGSTAB (plain and ILU(0)), MINRES and sparse Cholesky/LDLᵀ (all three orderings) agree with spsolve to 1e-9–1e-12; log det to 1e-9; RCM bandwidth within SciPy's + 4; IC(0) needs no shift on Poisson; MINRES solves a symmetric indefinite Poisson - 2.5I; LDLᵀ reports inertia (64, 12, 0) on a quasi-definite KKT matrix that Cholesky rejects.

Limits and next

  • AMD without supervariable detection is O(slow) on big meshes: 88 ms to order a 16k-row Poisson (busy Mac). Add supervariables and mass elimination (the paper's sections 4–5).
  • LDLᵀ has no pivoting (Bunch–Kaufman would need a supernodal or multifrontal code); no supernodal Cholesky yet.
  • No multithreading (isolates) yet; GPU SpMV in riptide_numerics_gpu.
  • When part A's NDArray lands: constructors from NDArray and toNdArray.

Classes

enum FillOrdering

Which fill-reducing ordering a sparse factorisation applies first.

Values

naturalvalue
natural
reverseCuthillMcKee
approximateMinimumDegree
final class SparseCholesky extends _SparseFactor

Sparse Cholesky A = P \cdot L \cdot L^{T} \cdot P^{T} (see _SparseFactor).

Constructors

SparseCholeskyconstructor
SparseCholesky(CsrMatrix a, {FillOrdering ordering = FillOrdering.approximateMinimumDegree})
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  final a = Gallery.poisson2d(4, 4); // 16 × 16, symmetric positive definite
  final c = SparseCholesky(a);
  final natural = SparseCholesky(a, ordering: FillOrdering.natural);
  print('fill in L: ${c.nnzL} with minimum degree, ${natural.nnzL} in natural order');
}
Output
fill in L: 58 with minimum degree, 67 in natural order

Properties

nnzLgetter
int get nnzL

Methods

solvemethod
Float64List solve(Float64List b)

Solves A \cdot x = b.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(4, 4); // 16 × 16, symmetric positive definite
  final b = Float64List(16)..fillRange(0, 16, 1);
  final x = SparseCholesky(a).solve(b);
  print('x = ${x.sublist(0, 4).map((v) => v.toStringAsFixed(4)).toList()} …');
  final y = Float64List(16);
  a.apply(x, y);
  print('A x = b: ${y.every((v) => (v - 1).abs() < 1e-12)}');
}
Output
x = [0.8333, 1.1667, 1.1667, 0.8333] …
A x = b: true
double logDeterminant()

Log det A = 2 \sum \log L_{jj}.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  print('log det = ${SparseCholesky(a).logDeterminant()}, det = ${math.exp(SparseCholesky(a).logDeterminant()).toStringAsFixed(6)} (n + 1 = 6)');
}
Output
log det = 1.7917594692280552, det = 6.000000 (n + 1 = 6)
final class SparseLdlt extends _SparseFactor

Sparse LDLᵀ A = P \cdot L \cdot D \cdot L^{T} \cdot P^{T} with unit lower L (see _SparseFactor).

Constructors

SparseLdltconstructor
SparseLdlt(CsrMatrix a, {FillOrdering ordering = FillOrdering.approximateMinimumDegree})
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  // Symmetric but indefinite: 2 positive, 1 negative eigenvalue.
  final a = CsrMatrix.fromDense(Float64List.fromList([1, 2, 0, 2, 1, 0, 0, 0, 3]), 3, 3);
  final f = SparseLdlt(a);
  print('D = ${f.d}, nnz(L) = ${f.nnzL}');
}
Output
D = [3.0, 1.0, -3.0], nnz(L) = 4

Properties

dfield
final Float64List d

The diagonal D.

nnzLgetter
int get nnzL

Methods

solvemethod
Float64List solve(Float64List b)

Solves A \cdot x = b.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Symmetric but indefinite: 2 positive, 1 negative eigenvalue.
  final a = CsrMatrix.fromDense(Float64List.fromList([1, 2, 0, 2, 1, 0, 0, 0, 3]), 3, 3);
  final x = SparseLdlt(a).solve(Float64List.fromList([3, 3, 3]));
  print('x = $x');
}
Output
x = [1.0, 1.0, 1.0]
inertiamethod
(int, int, int) inertia()

(positive, negative, zero) eigenvalue counts of A by Sylvester's law of inertia.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Symmetric but indefinite: 2 positive, 1 negative eigenvalue.
  final a = CsrMatrix.fromDense(Float64List.fromList([1, 2, 0, 2, 1, 0, 0, 0, 3]), 3, 3);
  final (pos, neg, zero) = SparseLdlt(a).inertia();
  print('positive $pos, negative $neg, zero $zero');
}
Output
positive 2, negative 1, zero 0
final class CooMatrix

A sparse matrix in coordinate (triplet) form: the format to build in. Entries may repeat; toCsr and toCsc sum duplicates (SciPy's coo_matrix.tocsr semantics). Indices are 0-based.

Constructors

CooMatrixconstructor
CooMatrix(this.rows, this.cols, {int capacity = 16})
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  final c = CooMatrix(4, 4);
  for (var i = 0; i < 4; i++) {
    c.add(i, i, 4);
    c.add(i, (i + 1) % 4, -1);
  }
  c.add(0, 0, 1); // duplicates are summed
  final a = c.toCsr();
  print('nnz in COO ${c.nnz}, in CSR ${a.nnz}');
}
Output
nnz in COO 9, in CSR 8
factory CooMatrix.fromTriplets(int rows, int cols, List<int> row, List<int> col, List<double> val)

From parallel arrays of row indices, column indices and values.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  final c = CooMatrix.fromTriplets(3, 3, [0, 1, 2, 0], [0, 1, 2, 2], [1, 2, 3, 9]);
  print('rows ${c.rowIndices}, cols ${c.colIndices}, values ${c.values}');
}
Output
rows [0, 1, 2, 0], cols [0, 1, 2, 2], values [1.0, 2.0, 3.0, 9.0]

Properties

rowsfield
final int rows
colsfield
final int cols
nnzgetter
int get nnz

Stored entries, counting duplicates.

Int32List get rowIndices
Int32List get colIndices
valuesgetter
Float64List get values

Methods

addmethod
void add(int i, int j, double v)

Appends a(i, j) + = v.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final c = CooMatrix(3, 3);
  c.add(1, 1, 2);
  c.add(1, 1, 3);
  print('stored triplets ${c.nnz}; after conversion A[1, 1] = ${c.toCsr()[(i: 1, j: 1)]}');
}
Output
stored triplets 2; after conversion A[1, 1] = 5.0
toCsrmethod
CsrMatrix toCsr()

Compressed rows: counting sort by row, then each row's columns sorted and duplicates summed.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  final c = CooMatrix.fromTriplets(3, 4, [2, 0, 1, 0], [3, 1, 0, 0], [5, 6, 7, 8]);
  final a = c.toCsr();
  print('indptr ${a.indptr}, indices ${a.indices}, data ${a.data}');
}
Output
indptr [0, 2, 3, 4], indices [0, 1, 0, 3], data [8.0, 6.0, 7.0, 5.0]
toCscmethod
CscMatrix toCsc()

Compressed columns (the transpose's rows).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final c = CooMatrix.fromTriplets(3, 3, [0, 2, 1], [0, 0, 2], [1, 2, 3]);
  final s = c.toCsc();
  print('column pointers ${s.indptr}, row indices ${s.indices}, data ${s.data}');
}
Output
column pointers [0, 2, 2, 3], row indices [0, 2, 1], data [1.0, 2.0, 3.0]
final class CsrMatrix implements LinearOperator

Compressed sparse row: row i's entries are indices[indptr[i].. indptr[i+1]) (sorted, no duplicates when built by this package) with values in data. The format SpMV, the solvers and the preconditioners use; the same three arrays as SciPy's csr_matrix and as the GPU SpMV buffers (with data narrowed to f32).

Constructors

CsrMatrixconstructor
CsrMatrix(this.rows, this.cols, this.indptr, this.indices, this.data)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  // [[1, 0, 2], [0, 0, 3], [4, 5, 0]] by hand.
  final a = CsrMatrix(3, 3, Int32List.fromList([0, 2, 3, 5]), Int32List.fromList([0, 2, 2, 0, 1]), Float64List.fromList([1, 2, 3, 4, 5]));
  print('nnz ${a.nnz}, A[2, 1] = ${a[(i: 2, j: 1)]}');
}
Output
nnz 5, A[2, 1] = 5.0
factory CsrMatrix.fromDense(Float64List a, int rows, int cols, {double dropTolerance = 0})

From a dense row-major rows x cols array, keeping entries with |a| > dropTolerance.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  final a = CsrMatrix.fromDense(Float64List.fromList([1, 1e-12, 0, 0, 2, 0, 3, 0, 4]), 3, 3, dropTolerance: 1e-9);
  print('kept ${a.nnz} of 9 entries');
}
Output
kept 4 of 9 entries
factory CsrMatrix.identity(int n, [double scale = 1])
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final i = CsrMatrix.identity(4, 2.5);
  print('nnz ${i.nnz}, diagonal ${i.diagonal()}');
}
Output
nnz 4, diagonal [2.5, 2.5, 2.5, 2.5]
factory CsrMatrix.diags(int n, List<List<double>> diagonals, List<int> offsets)

A diagonal-offset (banded) matrix: diagonals[k] sits on offset offsets[k] (0 main, +1 super, -1 sub), like scipy.sparse.diags. Diagonal k holds n − |offset| values.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  print('nnz ${a.nnz}');
}
Output
nnz 13

Properties

rowsfield
final int rows
colsfield
final int cols
indptrfield
final Int32List indptr
indicesfield
final Int32List indices
datafield
final Float64List data
nnzgetter
int get nnz

Methods

spmvmethod
void spmv(Float64List x, Float64List y, {double alpha = 1, double beta = 0})

y = \alpha \cdot A \cdot x + \beta \cdot y (beta 0 overwrites y, so it may hold garbage).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  final x = Float64List.fromList([1, 2, 3, 4, 5]), y = Float64List.fromList([1, 1, 1, 1, 1]);
  a.spmv(x, y, alpha: 2, beta: -1); // y = 2 A x − y
  print('y = $y');
}
Output
y = [-1.0, -1.0, -1.0, -1.0, 11.0]
applymethod
void apply(Float64List x, Float64List y)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  final x = Float64List.fromList([1, 4, 9, 16, 25]), y = Float64List(5);
  a.apply(x, y);
  print('A x on squares: $y (−2 inside: the second difference)');
}
Output
A x on squares: [-2.0, -2.0, -2.0, -2.0, 34.0] (−2 inside: the second difference)
void spmvTransposed(Float64List x, Float64List y, {double alpha = 1, double beta = 0})

y = \alpha \cdot A^{T} \cdot x + \beta \cdot y (scatter by column).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = CsrMatrix.fromDense(Float64List.fromList([1, 2, 0, 0, 0, 3]), 2, 3);
  final y = Float64List(3);
  a.spmvTransposed(Float64List.fromList([1, 1]), y);
  print('Aᵀ(1, 1) = $y');
}
Output
Aᵀ(1, 1) = [1.0, 2.0, 3.0]
spmmmethod
void spmm(Float64List x, int k, Float64List y)

Sparse × dense: Y (rows × k, row-major) = A \cdot X (cols × k, row-major). With k even the inner loop runs on Float64x2 lanes over the right-hand sides (one gather of a row of X serves \frac{k}{2} SIMD FMAs), the shape that makes SpMM worth more than k SpMVs.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  // A times a 5 × 2 block (row-major): columns (1,…,1) and (1,…,5).
  final x = Float64List.fromList([1, 1, 1, 2, 1, 3, 1, 4, 1, 5]), y = Float64List(10);
  a.spmm(x, 2, y);
  print('A X = $y');
}
Output
A X = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 6.0]
matmulmethod
CsrMatrix matmul(CsrMatrix b)

Sparse × sparse (Gustavson's row-by-row algorithm with a dense accumulator): C = A \cdot B, columns sorted.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  final a2 = a.matmul(a);
  print('A² has ${a2.nnz} nonzeros (bandwidth 2)');
}
Output
A² has 19 nonzeros (bandwidth 2)
addmethod
CsrMatrix add(CsrMatrix b, {double alpha = 1, double beta = 1})

\alpha \cdot A + \beta \cdot B (same shape), sorted merge per row.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  final s = a.add(CsrMatrix.identity(5), alpha: 0.5, beta: 3);
  print('diagonal of A/2 + 3I: ${s.diagonal()}');
}
Output
diagonal of A/2 + 3I: [4.0, 4.0, 4.0, 4.0, 4.0]
transposemethod
CsrMatrix transpose()

A^{T} as CSR (a counting sort by column, which leaves each transposed row sorted).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  final a = CsrMatrix.fromDense(Float64List.fromList([1, 2, 3, 0, 0, 4]), 2, 3);
  final t = a.transpose();
  print('${a.rows}×${a.cols} -> ${t.rows}×${t.cols}');
}
Output
2×3 -> 3×2
toCscmethod
CscMatrix toCsc()

The same matrix in CSC (shares no storage).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  final c = a.toCsc();
  print('CSC indptr ${c.indptr}');
}
Output
CSC indptr [0, 2, 5, 8, 11, 13]
diagonalmethod
Float64List diagonal()

The main diagonal (zeros where not stored).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(4, 4); // 16 × 16, symmetric positive definite
  print('diagonal ${a.diagonal().sublist(0, 6)} …');
}
Output
diagonal [4.0, 4.0, 4.0, 4.0, 4.0, 4.0] …
toDensemethod
Float64List toDense()

Dense row-major copy (tests and small matrices).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  print(a.toDense());
}
Output
[2.0, -1.0, 0.0, 0.0, 0.0, -1.0, 2.0, -1.0, 0.0, 0.0, 0.0, -1.0, 2.0, -1.0, 0.0, 0.0, 0.0, -1.0, 2.0, -1.0, 0.0, 0.0, 0.0, -1.0, 2.0]
trianglemethod
CsrMatrix triangle({bool lower = true})

The lower (or upper) triangle including the diagonal.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  final l = a.triangle(), u = a.triangle(lower: false);
  print('lower nnz ${l.nnz}, upper nnz ${u.nnz}');
}
Output
lower nnz 9, upper nnz 9
CsrMatrix permuteSymmetric(Int32List perm)

P \cdot A \cdot P^{T} for a symmetric permutation: row/column perm[k] of A becomes row/column k.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  final a = Gallery.poisson2d(4, 4); // 16 × 16, symmetric positive definite
  final p = Ordering.reverseCuthillMcKee(a);
  final b = a.permuteSymmetric(p);
  print('bandwidth ${Ordering.bandwidth(a)} -> ${Ordering.bandwidth(b)}');
}
Output
bandwidth 4 -> 4
bool isSymmetric({double tolerance = 0})

Whether A equals A^{T} to within tolerance (absolute).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  print('second difference: ${a.isSymmetric()}');
  print('convection-diffusion: ${Gallery.convectionDiffusion1d(5, 0.5).isSymmetric()}');
}
Output
second difference: true
convection-diffusion: false
Float32List dataAsFloat32()

A copy with values narrowed to f32 (the GPU SpMV buffers).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  final f = a.dataAsFloat32();
  print('${f.runtimeType == Float32List ? 'Float32List' : 'float32'} of ${f.length}: $f');
}
Output from the Raya VM
float32 of 13: [2.0, -1.0, -1.0, 2.0, -1.0, -1.0, 2.0, -1.0, -1.0, 2.0, -1.0, -1.0, 2.0]

Operators

operator []operator
double operator [](({int i, int j}) at)

a(i, j), by binary search in row i (0 when not stored).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  print('A[0, 0] = ${a[(i: 0, j: 0)]}, A[0, 1] = ${a[(i: 0, j: 1)]}, A[0, 4] = ${a[(i: 0, j: 4)]}');
}
Output
A[0, 0] = 2.0, A[0, 1] = -1.0, A[0, 4] = 0.0
final class CscMatrix implements LinearOperator

Compressed sparse column: column j's entries are indices[indptr[j].. indptr[j+1]) (row indices, sorted). The natural format for column operations and for Cholesky's left-looking forms; SpMV scatters.

Constructors

CscMatrixconstructor
CscMatrix(this.rows, this.cols, this.indptr, this.indices, this.data)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  // [[1, 0, 2], [0, 3, 0]] stored by columns.
  final c = CscMatrix(2, 3, Int32List.fromList([0, 1, 2, 3]), Int32List.fromList([0, 1, 0]), Float64List.fromList([1, 3, 2]));
  print('nnz ${c.nnz}');
}
Output
nnz 3

Properties

rowsfield
final int rows
colsfield
final int cols
indptrfield
final Int32List indptr
indicesfield
final Int32List indices
datafield
final Float64List data
nnzgetter
int get nnz

Methods

spmvmethod
void spmv(Float64List x, Float64List y, {double alpha = 1, double beta = 0})

y = \alpha \cdot A \cdot x + \beta \cdot y.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // [[1, 0, 2], [0, 3, 0]] stored by columns.
  final c = CscMatrix(2, 3, Int32List.fromList([0, 1, 2, 3]), Int32List.fromList([0, 1, 0]), Float64List.fromList([1, 3, 2]));
  final y = Float64List(2);
  c.spmv(Float64List.fromList([1, 1, 1]), y, alpha: 2);
  print('2 A·1 = $y');
}
Output
2 A·1 = [6.0, 6.0]
applymethod
void apply(Float64List x, Float64List y)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // [[1, 0, 2], [0, 3, 0]] stored by columns.
  final c = CscMatrix(2, 3, Int32List.fromList([0, 1, 2, 3]), Int32List.fromList([0, 1, 0]), Float64List.fromList([1, 3, 2]));
  final y = Float64List(2);
  c.apply(Float64List.fromList([1, 2, 3]), y);
  print('A x = $y');
}
Output
A x = [7.0, 6.0]
toCsrmethod
CsrMatrix toCsr()

The same matrix in CSR.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // [[1, 0, 2], [0, 3, 0]] stored by columns.
  final c = CscMatrix(2, 3, Int32List.fromList([0, 1, 2, 3]), Int32List.fromList([0, 1, 0]), Float64List.fromList([1, 3, 2]));
  final r = c.toCsr();
  print('CSR indptr ${r.indptr}, indices ${r.indices}, data ${r.data}');
}
Output
CSR indptr [0, 2, 3], indices [0, 2, 1], data [1.0, 2.0, 3.0]
final class BsrMatrix implements LinearOperator

Block compressed sparse row with dense blockRows × blockCols blocks (row-major inside each block), like SciPy's bsr_matrix. For matrices from vector PDEs (3 dof per node: 3 \times 3 blocks) it stores one column index per block and runs the block multiply on Float64x2 lanes.

Constructors

BsrMatrixconstructor
BsrMatrix(this.rows, this.cols, this.blockRows, this.blockCols, this.indptr, this.indices, this.data)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // One 2 × 2 block on the diagonal of a 4 × 4 matrix, one off it.
  final b = BsrMatrix(4, 4, 2, 2, Int32List.fromList([0, 2, 3]), Int32List.fromList([0, 1, 1]), Float64List.fromList([1, 2, 3, 4, 5, 0, 0, 5, 6, 7, 8, 9]));
  final y = Float64List(4);
  b.apply(Float64List.fromList([1, 1, 1, 1]), y);
  print('blocks ${b.blocks}, A·1 = $y');
}
Output
blocks 3, A·1 = [8.0, 12.0, 13.0, 17.0]
factory BsrMatrix.fromCsr(CsrMatrix a, int blockRows, int blockCols)

Groups a CSR matrix into blocks (any block touched by a stored entry is stored densely).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(4, 4); // 16 × 16, symmetric positive definite
  final b = BsrMatrix.fromCsr(a, 4, 4);
  print('16 × 16 as ${b.blocks} blocks of 4 × 4');
}
Output
16 × 16 as 10 blocks of 4 × 4

Properties

rowsfield
final int rows
colsfield
final int cols
final int blockRows
final int blockCols
indptrfield
final Int32List indptr
indicesfield
final Int32List indices
datafield
final Float64List data
blocksgetter
int get blocks

Methods

spmvmethod
void spmv(Float64List x, Float64List y)

y = A \cdot x. One pass over the blocks with all blockRows accumulators live; 2 \times 2 and 3 \times 3 blocks (2-D and 3-D vector fields) are unrolled. Scalar: on other runtimes, building Float64x2 values from a gather costs more than it saves.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(4, 4); // 16 × 16, symmetric positive definite
  final b = BsrMatrix.fromCsr(a, 2, 2);
  final x = Float64List.fromList([for (var i = 0; i < 16; i++) i.toDouble()]), y1 = Float64List(16), y2 = Float64List(16);
  b.spmv(x, y1);
  a.apply(x, y2);
  print('BSR equals CSR: ${[for (var i = 0; i < 16; i++) y1[i] == y2[i]].every((v) => v)}');
}
Output
BSR equals CSR: true
applymethod
void apply(Float64List x, Float64List y)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  final b = BsrMatrix.fromCsr(CsrMatrix.diags(6, [[-1, -1, -1, -1, -1], [2, 2, 2, 2, 2, 2], [-1, -1, -1, -1, -1]], [-1, 0, 1]), 2, 2);
  final y = Float64List(6);
  b.apply(Float64List.fromList([1, 1, 1, 1, 1, 1]), y);
  print('A·1 = $y');
}
Output
A·1 = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0]
abstract final class MatrixMarket

Matrix Market exchange format (NIST, https://math.nist.gov/MatrixMarket/formats.html), coordinate real with general or symmetric symmetry (and pattern, read as ones): the format SuiteSparse Matrix Collection test matrices and scipy.io.mmwrite use.

Static

parsestaticmethod
static CsrMatrix parse(String text)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

List<List<double>> rowsOf(CsrMatrix a) {
  final d = a.toDense();
  return [for (var i = 0; i < a.rows; i++) [for (var j = 0; j < a.cols; j++) d[i * a.cols + j]]];
}

void main() {
  const text = '''%%MatrixMarket matrix coordinate real general
3 3 4
1 1 2.0
2 2 3.0
3 1 -1.0
3 3 4.0
''';
  final a = MatrixMarket.parse(text);
  print('${a.rows} × ${a.cols}, nnz ${a.nnz}');
}
Output
3 × 3, nnz 4
formatstaticmethod
static String format(CsrMatrix a)

Writes coordinate real general with 17 significant digits (round-trips every double).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  print(MatrixMarket.format(a));
}
Output
%%MatrixMarket matrix coordinate real general
5 5 13
1 1 2.0000000000000000
1 2 -1.0000000000000000
2 1 -1.0000000000000000
2 2 2.0000000000000000
2 3 -1.0000000000000000
3 2 -1.0000000000000000
3 3 2.0000000000000000
3 4 -1.0000000000000000
4 3 -1.0000000000000000
4 4 2.0000000000000000
4 5 -1.0000000000000000
5 4 -1.0000000000000000
5 5 2.0000000000000000
final class SolveResult

What an iterative solve returns. residual is the true relative residual \Vert b - A \cdot x\Vert / \Vert b\Vert recomputed at the end (not the solver's running estimate).

Constructors

SolveResultconstructor
SolveResult(this.x, this.iterations, this.residual, this.converged)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final r = SolveResult(Float64List.fromList([1, 2]), 3, 1e-12, true);
  print(r);
}
Output
SolveResult(iterations: 3, residual: 1e-12, converged: true)

Properties

xfield
final Float64List x
final int iterations
final double residual
final bool converged

Methods

toStringmethod
String toString()
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(4, 4); // 16 × 16, symmetric positive definite
  print(Krylov.cg(a, Float64List(16)..fillRange(0, 16, 1)));
}
Output
SolveResult(iterations: 3, residual: 5.661048867003676e-16, converged: true)
class

Krylov

abstract final class Krylov

Krylov subspace solvers for A \cdot x = b (Saad 2003; Barrett et al. "Templates for the Solution of Linear Systems", SIAM 1994; MINRES from Paige and Saunders 1975 as structured in SciPy's minres, BSD-3). Each stops when \Vert r\Vert \le \max(\mathrm{rtol} \cdot \Vert b\Vert, atol), SciPy's criterion. x0 is the initial guess (zero when omitted); it is not modified.

Static

cgstaticmethod
static SolveResult cg(LinearOperator a, Float64List b, {Float64List? x0, Preconditioner? m, double rtol = 1e-10, double atol = 0, int? maxIterations})

Conjugate gradients, preconditioned when m is given (PCG). A and M must be symmetric positive definite.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(20, 20);
  final b = Float64List(a.rows)..fillRange(0, a.rows, 1);
  final r = Krylov.cg(a, b);
  final p = Krylov.cg(a, b, m: IncompleteCholeskyPreconditioner(a));
  print('CG ${r.iterations} iterations, with IC(0) ${p.iterations}');
}
Output
CG 40 iterations, with IC(0) 23
gmresstaticmethod
static SolveResult gmres(LinearOperator a, Float64List b, {Float64List? x0, Preconditioner? m, int restart = 30, double rtol = 1e-10, double atol = 0, int? maxIterations})

Restarted GMRES(restart) with right preconditioning (so the minimised residual is the true one): Arnoldi with modified Gram–Schmidt plus one reorthogonalisation pass, Givens rotations for the least-squares problem.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.convectionDiffusion1d(100, 0.8);
  final b = Float64List(100)..fillRange(0, 100, 1);
  for (final restart in [5, 20, 100]) {
    final r = Krylov.gmres(a, b, restart: restart);
    print('restart $restart: ${r.iterations} iterations, converged ${r.converged}');
  }
}
Output
restart 5: 1000 iterations, converged false
restart 20: 1000 iterations, converged false
restart 100: 100 iterations, converged true
bicgstabstaticmethod
static SolveResult bicgstab(LinearOperator a, Float64List b, {Float64List? x0, Preconditioner? m, double rtol = 1e-10, double atol = 0, int? maxIterations})

BiCGSTAB (van der Vorst 1992) with right preconditioning, for nonsymmetric systems: short recurrences (fixed memory, unlike GMRES) and smoother convergence than BiCG.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.convectionDiffusion1d(100, 0.8);
  final b = Float64List(100)..fillRange(0, 100, 1);
  final r = Krylov.bicgstab(a, b);
  print('BiCGSTAB: ${r.iterations} iterations, residual ${r.residual.toStringAsExponential(2)}');
  final y = Float64List(100);
  a.apply(r.x, y);
  print('solution on the grid, first values ${r.x.sublist(0, 3).map((v) => v.toStringAsFixed(3)).toList()}');
}
Output
BiCGSTAB: 112 iterations, residual 3.51e-11
solution on the grid, first values [0.004, 0.008, 0.013]
minresstaticmethod
static SolveResult minres(LinearOperator a, Float64List b, {Float64List? x0, Preconditioner? m, double rtol = 1e-10, double atol = 0, int? maxIterations})

MINRES (Paige and Saunders 1975) for symmetric, possibly indefinite A; the optional preconditioner must be symmetric positive definite. Minimises \Vert b - A \cdot x\Vert (in the M^{-1} norm when preconditioned) over the Krylov space.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Symmetric but indefinite: 2 positive, 1 negative eigenvalue.
  final a = CsrMatrix.fromDense(Float64List.fromList([1, 2, 0, 2, 1, 0, 0, 0, 3]), 3, 3);
  final r = Krylov.minres(a, Float64List.fromList([3, 3, 3]));
  print('MINRES on a symmetric indefinite system: x = ${r.x.map((v) => v.toStringAsFixed(6)).toList()} (${r.iterations} iterations)');
}
Output
MINRES on a symmetric indefinite system: x = [1.000000, 1.000000, 1.000000] (1 iterations)
abstract interface class LinearOperator

Anything that computes y = A \cdot x: every sparse format, a dense matrix, or a matrix-free stencil. The Krylov solvers only need this.

Properties

rowsgetter
int get rows
colsgetter
int get cols

Methods

applymethod
void apply(Float64List x, Float64List y)

y = A \cdot x (y fully overwritten).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // Any matrix-free operator works with the Krylov solvers.
  final LinearOperator op = FunctionOperator(3, 3, (x, y) {
    y[0] = 2 * x[0] + x[1];
    y[1] = x[0] + 2 * x[1] + x[2];
    y[2] = x[1] + 2 * x[2];
  });
  final y = Float64List(3);
  op.apply(Float64List.fromList([1, 0, 0]), y);
  print('${op.rows}×${op.cols}, first column $y');
}
Output
3×3, first column [2.0, 1.0, 0.0]
final class FunctionOperator implements LinearOperator

A matrix-free operator from a closure.

Constructors

FunctionOperatorconstructor
FunctionOperator(this.rows, this.cols, this._apply)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 1-D Laplacian without storing it.
  const n = 50;
  final op = FunctionOperator(n, n, (x, y) {
    for (var i = 0; i < n; i++) {
      y[i] = 2 * x[i] - (i > 0 ? x[i - 1] : 0) - (i < n - 1 ? x[i + 1] : 0);
    }
  });
  final r = Krylov.cg(op, Float64List(n)..fillRange(0, n, 1));
  print('matrix-free CG: ${r.iterations} iterations');
}
Output
matrix-free CG: 25 iterations

Properties

rowsfield
final int rows
colsfield
final int cols

Methods

applymethod
void apply(Float64List x, Float64List y)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final op = FunctionOperator(2, 2, (x, y) {
    y[0] = -x[1];
    y[1] = x[0];
  });
  final y = Float64List(2);
  op.apply(Float64List.fromList([1, 0]), y);
  print('a quarter turn: $y');
}
Output
a quarter turn: [-0.0, 1.0]
final class DenseOperator implements LinearOperator

A dense row-major operator (small systems, tests).

Constructors

DenseOperatorconstructor
DenseOperator(this.a, this.rows, this.cols)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final op = DenseOperator(Float64List.fromList([4, 1, 1, 3]), 2, 2);
  final r = Krylov.cg(op, Float64List.fromList([1, 2]));
  print('x = ${r.x.map((v) => v.toStringAsFixed(6)).toList()} (1/11, 7/11)');
}
Output
x = [0.090909, 0.636364] (1/11, 7/11)

Properties

afield
final Float64List a
rowsfield
final int rows
colsfield
final int cols

Methods

applymethod
void apply(Float64List x, Float64List y)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final op = DenseOperator(Float64List.fromList([1, 2, 3, 4, 5, 6]), 2, 3);
  final y = Float64List(2);
  op.apply(Float64List.fromList([1, 1, 1]), y);
  print('row sums: $y');
}
Output
row sums: [6.0, 15.0]
class

Vec

abstract final class Vec

Level-1 kernels on Float64List used by the solvers. Two accumulators per loop, so the adds pipeline (and Raya's vectoriser pairs them).

Static

dotstaticmethod
static double dot(Float64List a, Float64List b)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Float64List.fromList([1, 2, 2]), b = Float64List.fromList([3, 0, 4]);
  print(Vec.dot(a, b));
}
Output
11.0
normstaticmethod
static double norm(Float64List a)

The 2-norm, scaled to avoid overflow and underflow (LAPACK dnrm2's idea, one pass).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Float64List.fromList([1, 2, 2]), b = Float64List.fromList([3, 0, 4]);
  print('|a| = ${Vec.norm(a)}, |b| = ${Vec.norm(b)}');
}
Output
|a| = 3.0, |b| = 5.0
axpystaticmethod
static void axpy(double alpha, Float64List x, Float64List y)

y + = \alpha \cdot x.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Float64List.fromList([1, 2, 2]), b = Float64List.fromList([3, 0, 4]);
  Vec.axpy(2, a, b);
  print('b ← 2a + b = $b');
}
Output
b ← 2a + b = [5.0, 4.0, 8.0]
xpbystaticmethod
static void xpby(Float64List x, double beta, Float64List y)

y = x + \beta \cdot y.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Float64List.fromList([1, 2, 2]), b = Float64List.fromList([3, 0, 4]);
  Vec.xpby(a, 0.5, b);
  print('b ← a + 0.5 b = $b');
}
Output
b ← a + 0.5 b = [2.5, 2.0, 4.0]
abstract final class Ordering

Fill-reducing and bandwidth-reducing orderings of a symmetric sparsity pattern. Each returns a permutation perm where perm[k] is the original index placed at position k (use with CsrMatrix.permuteSymmetric). Only the pattern of A + A^{T} is used; the diagonal is ignored.

Static

naturalstaticmethod
static Int32List natural(int n)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  print(Ordering.natural(6));
}
Output
[0, 1, 2, 3, 4, 5]
static Int32List reverseCuthillMcKee(CsrMatrix a)

Reverse Cuthill–McKee (George and Liu 1981): breadth-first from a pseudo-peripheral vertex, visiting neighbours by increasing degree, then reversed. Small bandwidth/profile: good for banded solvers and cache locality in SpMV.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(6, 6);
  final p = Ordering.reverseCuthillMcKee(a);
  print('bandwidth ${Ordering.bandwidth(a)} -> ${Ordering.bandwidth(a.permuteSymmetric(p))}');
  print('first of the order: ${p.sublist(0, 8)}');
}
Output
bandwidth 6 -> 6
first of the order: [35, 34, 29, 33, 28, 23, 32, 27]
static Int32List approximateMinimumDegree(CsrMatrix a)

Approximate minimum degree on the quotient graph (Amestoy, Davis and Duff, "An Approximate Minimum Degree Ordering Algorithm", SIMAX 1996): eliminated vertices become elements, elements adjacent to the pivot are absorbed, and each neighbour's degree is the AMD bound d_{i} = \min(n_{\mathrm{live}} - 1, d_{i\mathrm{old}} + |L_{p} \setminus i|, |A_{i} \setminus i| + |L_{p} \setminus i| + \sum_{e \in E_{i} \setminus p} |L_{e} \setminus L_{p}|), with |L_{e} \setminus L_{p}| from the w(e) counters and aggressive absorption of elements with |L_{e} \setminus L_{p}| = 0. Written from the paper (SuiteSparse AMD is BSD-3; no code taken). Not implemented: supervariable detection and mass elimination, so it is slower than SuiteSparse on large meshes; orderings are comparable in fill.

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(8, 8);
  final natural = SparseCholesky(a, ordering: FillOrdering.natural).nnzL;
  final amd = SparseCholesky(a.permuteSymmetric(Ordering.approximateMinimumDegree(a)), ordering: FillOrdering.natural).nnzL;
  print('nnz(L): natural $natural, AMD order $amd');
}
Output
nnz(L): natural 519, AMD order 354
bandwidthstaticmethod
static int bandwidth(CsrMatrix a)

Bandwidth max |i - j| over stored entries (to compare orderings).

Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // The 5 × 5 second-difference matrix [−1, 2, −1].
  final a = CsrMatrix.diags(5, [[-1, -1, -1, -1], [2, 2, 2, 2, 2], [-1, -1, -1, -1]], [-1, 0, 1]);
  print('tridiagonal: ${Ordering.bandwidth(a)}');
  print('poisson2d(10, 10): ${Ordering.bandwidth(Gallery.poisson2d(10, 10))}');
}
Output
tridiagonal: 1
poisson2d(10, 10): 10
abstract interface class Preconditioner

z = M^{-1} \cdot r for a preconditioner M \approx A. Krylov solvers converge in far fewer iterations on M^{-1}A than on A.

Methods

solvemethod
void solve(Float64List r, Float64List z)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  // A custom preconditioner: scale by 1/4 (the diagonal of the 2-D Laplacian).
  final a = Gallery.poisson2d(10, 10);
  final b = Float64List(100)..fillRange(0, 100, 1);
  final r = Krylov.cg(a, b, m: Quarter());
  print('CG with a custom preconditioner: ${r.iterations} iterations');
}

final class Quarter implements Preconditioner {
  @override
  void solve(Float64List r, Float64List z) {
    for (var i = 0; i < r.length; i++) {
      z[i] = r[i] / 4;
    }
  }
}
Output
CG with a custom preconditioner: 15 iterations
final class IdentityPreconditioner implements Preconditioner

M = I.

Constructors

const IdentityPreconditioner()
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(25, 25);
  final b = Float64List(a.rows)..fillRange(0, a.rows, 1);
  final m = const IdentityPreconditioner();
  final r = Krylov.cg(a, b, m: m);
  print('CG with IdentityPreconditioner: ${r.iterations} iterations (plain ${Krylov.cg(a, b).iterations})');
}
Output
CG with IdentityPreconditioner: 52 iterations (plain 52)

Methods

solvemethod
void solve(Float64List r, Float64List z)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(3, 3);
  final m = const IdentityPreconditioner();
  final z = Float64List(9);
  m.solve(Float64List(9)..fillRange(0, 9, 1), z);
  print('z = M⁻¹·1 = ${z.map((v) => v.toStringAsFixed(4)).toList()}');
}
Output
z = M⁻¹·1 = [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000]
final class JacobiPreconditioner implements Preconditioner

M = \operatorname{diag}(A). Cheap, embarrassingly parallel (the GPU-friendly one), and enough for diagonally dominant systems.

Constructors

JacobiPreconditioner(CsrMatrix a)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(25, 25);
  final b = Float64List(a.rows)..fillRange(0, a.rows, 1);
  final m = JacobiPreconditioner(a);
  final r = Krylov.cg(a, b, m: m);
  print('CG with JacobiPreconditioner: ${r.iterations} iterations (plain ${Krylov.cg(a, b).iterations})');
}
Output
CG with JacobiPreconditioner: 52 iterations (plain 52)

Methods

solvemethod
void solve(Float64List r, Float64List z)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(3, 3);
  final m = JacobiPreconditioner(a);
  final z = Float64List(9);
  m.solve(Float64List(9)..fillRange(0, 9, 1), z);
  print('z = M⁻¹·1 = ${z.map((v) => v.toStringAsFixed(4)).toList()}');
}
Output
z = M⁻¹·1 = [0.2500, 0.2500, 0.2500, 0.2500, 0.2500, 0.2500, 0.2500, 0.2500, 0.2500]
final class Ilu0Preconditioner implements Preconditioner

Incomplete LU with zero fill (ILU(0); Saad, "Iterative Methods for Sparse Linear Systems", 2nd ed. Algorithm 10.4): L and U keep exactly A's sparsity pattern (unit lower L below the diagonal, U on and above it, stored in one CSR copy). For general nonsymmetric systems with GMRES or BiCGSTAB.

Constructors

Ilu0Preconditioner(CsrMatrix a)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(25, 25);
  final b = Float64List(a.rows)..fillRange(0, a.rows, 1);
  final m = Ilu0Preconditioner(a);
  final r = Krylov.cg(a, b, m: m);
  print('CG with Ilu0Preconditioner: ${r.iterations} iterations (plain ${Krylov.cg(a, b).iterations})');
}
Output
CG with Ilu0Preconditioner: 28 iterations (plain 52)

Methods

solvemethod
void solve(Float64List r, Float64List z)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(3, 3);
  final m = Ilu0Preconditioner(a);
  final z = Float64List(9);
  m.solve(Float64List(9)..fillRange(0, 9, 1), z);
  print('z = M⁻¹·1 = ${z.map((v) => v.toStringAsFixed(4)).toList()}');
}
Output
z = M⁻¹·1 = [0.6083, 0.7166, 0.5471, 0.7166, 0.8900, 0.7093, 0.5471, 0.7093, 0.6046]
final class IncompleteCholeskyPreconditioner implements Preconditioner

Incomplete Cholesky with zero fill (IC(0)): L has the pattern of tril(A) and A \approx L \cdot L^{T}. For symmetric positive definite systems with PCG. If a pivot goes non-positive (IC(0) can break down even for SPD A) it restarts on A + \alpha I with \alpha doubling from 1 \times 10^{-3} \cdot \max|a_{ii}| (Manteuffel's shift); shift reports the \alpha used (0 when none).

Constructors

IncompleteCholeskyPreconditioner(CsrMatrix a)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(25, 25);
  final b = Float64List(a.rows)..fillRange(0, a.rows, 1);
  final m = IncompleteCholeskyPreconditioner(a);
  final r = Krylov.cg(a, b, m: m);
  print('CG with IncompleteCholeskyPreconditioner: ${r.iterations} iterations (plain ${Krylov.cg(a, b).iterations})');
}
Output
CG with IncompleteCholeskyPreconditioner: 28 iterations (plain 52)

Properties

shiftfield
late final double shift

The diagonal shift \alpha the factorisation needed (0 for none).

Methods

solvemethod
void solve(Float64List r, Float64List z)
Example
import 'package:riptide_numerics_sparse/riptide_numerics_sparse.ray';
import 'raya:convert';
import 'raya:math' as math;
import 'raya:typed_data';

void main() {
  final a = Gallery.poisson2d(3, 3);
  final m = IncompleteCholeskyPreconditioner(a);
  final z = Float64List(9);
  m.solve(Float64List(9)..fillRange(0, 9, 1), z);
  print('z = M⁻¹·1 = ${z.map((v) => v.toStringAsFixed(4)).toList()}');
}
Output
z = M⁻¹·1 = [0.6083, 0.7166, 0.5471, 0.7166, 0.8900, 0.7093, 0.5471, 0.7093, 0.6046]