Overview
Sparse linear algebra. The GPU SpMV lives in riptide_numerics_gpu.
What's in it
| File | Contents |
|---|---|
formats.ray | CooMatrix (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.ray | LinearOperator (what the solvers take: any format, DenseOperator, matrix-free FunctionOperator), level-1 Vec kernels |
krylov.ray | Krylov.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.ray | JacobiPreconditioner, Ilu0Preconditioner (Saad Alg. 10.4), IncompleteCholeskyPreconditioner (IC(0) with Manteuffel's diagonal shift on breakdown) |
ordering.ray | Ordering.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.ray | SparseCholesky and SparseLdlt (up-looking, elimination tree + row reach in topological order; FillOrdering.natural / reverseCuthillMcKee / approximateMinimumDegree); log-determinant, inertia |
io.ray, gallery.ray | Matrix 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
FillOrdering
enum FillOrdering
Which fill-reducing ordering a sparse factorisation applies first.
Values
naturalreverseCuthillMcKeeapproximateMinimumDegreeSparseCholesky
final class SparseCholesky extends _SparseFactor
Sparse Cholesky A = P \cdot L \cdot L^{T} \cdot P^{T} (see _SparseFactor).
Constructors
SparseCholesky(CsrMatrix a, {FillOrdering ordering = FillOrdering.approximateMinimumDegree})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');
}fill in L: 58 with minimum degree, 67 in natural order
Properties
int get nnzLMethods
Float64List solve(Float64List b)Solves A \cdot x = b.
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)}');
}x = [0.8333, 1.1667, 1.1667, 0.8333] … A x = b: true
double logDeterminant()Log det A = 2 \sum \log L_{jj}.
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)');
}log det = 1.7917594692280552, det = 6.000000 (n + 1 = 6)
SparseLdlt
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
SparseLdlt(CsrMatrix a, {FillOrdering ordering = FillOrdering.approximateMinimumDegree})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}');
}D = [3.0, 1.0, -3.0], nnz(L) = 4
Properties
int get nnzLMethods
Float64List solve(Float64List b)Solves A \cdot x = b.
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');
}x = [1.0, 1.0, 1.0]
(int, int, int) inertia()(positive, negative, zero) eigenvalue counts of A by Sylvester's law of inertia.
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');
}positive 2, negative 1, zero 0
CooMatrix
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
CooMatrix(this.rows, this.cols, {int capacity = 16})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}');
}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.
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}');
}rows [0, 1, 2, 0], cols [0, 1, 2, 2], values [1.0, 2.0, 3.0, 9.0]
Properties
final int rowsfinal int colsInt32List get rowIndicesInt32List get colIndicesFloat64List get valuesMethods
void add(int i, int j, double v)Appends a(i, j) + = v.
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)]}');
}stored triplets 2; after conversion A[1, 1] = 5.0
CsrMatrix toCsr()Compressed rows: counting sort by row, then each row's columns sorted and duplicates summed.
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}');
}indptr [0, 2, 3, 4], indices [0, 1, 0, 3], data [8.0, 6.0, 7.0, 5.0]
CscMatrix toCsc()Compressed columns (the transpose's rows).
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}');
}column pointers [0, 2, 2, 3], row indices [0, 2, 1], data [1.0, 2.0, 3.0]
CsrMatrix
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
CsrMatrix(this.rows, this.cols, this.indptr, this.indices, this.data)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)]}');
}nnz 5, A[2, 1] = 5.0
factory CsrMatrix.fromDense(Float64List a, int rows, int cols, {double dropTolerance = 0})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');
}kept 4 of 9 entries
factory CsrMatrix.identity(int n, [double scale = 1])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()}');
}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.
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}');
}nnz 13
Properties
final int rowsfinal int colsfinal Int32List indptrfinal Int32List indicesfinal Float64List dataint get nnzMethods
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).
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');
}y = [-1.0, -1.0, -1.0, -1.0, 11.0]
void apply(Float64List x, Float64List y)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)');
}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).
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');
}Aᵀ(1, 1) = [1.0, 2.0, 3.0]
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.
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');
}A X = [1.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 1.0, 6.0]
CsrMatrix matmul(CsrMatrix b)Sparse × sparse (Gustavson's row-by-row algorithm with a dense accumulator): C = A \cdot B, columns sorted.
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)');
}A² has 19 nonzeros (bandwidth 2)
CsrMatrix add(CsrMatrix b, {double alpha = 1, double beta = 1})\alpha \cdot A + \beta \cdot B (same shape), sorted merge per row.
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()}');
}diagonal of A/2 + 3I: [4.0, 4.0, 4.0, 4.0, 4.0]
CsrMatrix transpose()A^{T} as CSR (a counting sort by column, which leaves each transposed row sorted).
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}');
}2×3 -> 3×2
CscMatrix toCsc()The same matrix in CSC (shares no storage).
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}');
}CSC indptr [0, 2, 5, 8, 11, 13]
Float64List diagonal()The main diagonal (zeros where not stored).
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)} …');
}diagonal [4.0, 4.0, 4.0, 4.0, 4.0, 4.0] …
Float64List toDense()Dense row-major copy (tests and small matrices).
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());
}[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]
CsrMatrix triangle({bool lower = true})The lower (or upper) triangle including the diagonal.
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}');
}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.
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)}');
}bandwidth 4 -> 4
bool isSymmetric({double tolerance = 0})Whether A equals A^{T} to within tolerance (absolute).
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()}');
}second difference: true convection-diffusion: false
Float32List dataAsFloat32()A copy with values narrowed to f32 (the GPU SpMV buffers).
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');
}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
double operator [](({int i, int j}) at)a(i, j), by binary search in row i (0 when not stored).
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)]}');
}A[0, 0] = 2.0, A[0, 1] = -1.0, A[0, 4] = 0.0
CscMatrix
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
CscMatrix(this.rows, this.cols, this.indptr, this.indices, this.data)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}');
}nnz 3
Properties
final int rowsfinal int colsfinal Int32List indptrfinal Int32List indicesfinal Float64List dataint get nnzMethods
void spmv(Float64List x, Float64List y, {double alpha = 1, double beta = 0})y = \alpha \cdot A \cdot x + \beta \cdot y.
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');
}2 A·1 = [6.0, 6.0]
void apply(Float64List x, Float64List y)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');
}A x = [7.0, 6.0]
CsrMatrix toCsr()The same matrix in CSR.
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}');
}CSR indptr [0, 2, 3], indices [0, 2, 1], data [1.0, 2.0, 3.0]
BsrMatrix
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
BsrMatrix(this.rows, this.cols, this.blockRows, this.blockCols, this.indptr, this.indices, this.data)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');
}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).
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');
}16 × 16 as 10 blocks of 4 × 4
Properties
final int rowsfinal int colsfinal int blockRowsfinal int blockColsfinal Int32List indptrfinal Int32List indicesfinal Float64List dataint get blocksMethods
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.
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)}');
}BSR equals CSR: true
void apply(Float64List x, Float64List y)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');
}A·1 = [1.0, 0.0, 0.0, 0.0, 0.0, 1.0]
Gallery
abstract final class Gallery
Standard test matrices.
Static
static CsrMatrix poisson2d(int nx, int ny)The 5-point Laplacian on an nx × ny grid with Dirichlet boundaries (SPD, condition number ~ (\frac{n}{\pi})^{2}): the matrix of scipy.sparse examples and of every pressure projection in a grid fluid.
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]]];
}
List<List<String>> edgesOf(CsrMatrix a) => [
for (var i = 0; i < a.rows; i++)
for (var p = a.indptr[i]; p < a.indptr[i + 1]; p++)
if (a.indices[p] > i) ['$i', '${a.indices[p]}'],
];
void main() {
final a = Gallery.poisson2d(3, 3);
print('${a.rows} unknowns, ${a.nnz} nonzeros');
}9 unknowns, 33 nonzeros
static CsrMatrix convectionDiffusion1d(int n, double c)1-D convection–diffusion -u'' + c \cdot u' (central differences, Péclet number c \cdot \frac{h}{2}): nonsymmetric for c \ne 0, the standard GMRES / BiCGSTAB test.
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.convectionDiffusion1d(6, 0.5);
print('symmetric: ${a.isSymmetric()}');
}symmetric: false
MatrixMarket
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
static CsrMatrix parse(String text)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}');
}3 × 3, nnz 4
static String format(CsrMatrix a)Writes coordinate real general with 17 significant digits (round-trips every double).
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));
}%%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
SolveResult
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
SolveResult(this.x, this.iterations, this.residual, this.converged)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);
}SolveResult(iterations: 3, residual: 1e-12, converged: true)
Properties
final Float64List xfinal int iterationsfinal double residualfinal bool convergedMethods
String toString()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)));
}SolveResult(iterations: 3, residual: 5.661048867003676e-16, converged: true)
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
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.
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}');
}CG 40 iterations, with IC(0) 23
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.
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}');
}
}restart 5: 1000 iterations, converged false restart 20: 1000 iterations, converged false restart 100: 100 iterations, converged true
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.
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()}');
}BiCGSTAB: 112 iterations, residual 3.51e-11 solution on the grid, first values [0.004, 0.008, 0.013]
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.
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)');
}MINRES on a symmetric indefinite system: x = [1.000000, 1.000000, 1.000000] (1 iterations)
LinearOperator
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
int get rowsint get colsMethods
void apply(Float64List x, Float64List y)y = A \cdot x (y fully overwritten).
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');
}3×3, first column [2.0, 1.0, 0.0]
FunctionOperator
final class FunctionOperator implements LinearOperator
A matrix-free operator from a closure.
Constructors
FunctionOperator(this.rows, this.cols, this._apply)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');
}matrix-free CG: 25 iterations
Properties
final int rowsfinal int colsMethods
void apply(Float64List x, Float64List y)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');
}a quarter turn: [-0.0, 1.0]
DenseOperator
final class DenseOperator implements LinearOperator
A dense row-major operator (small systems, tests).
Constructors
DenseOperator(this.a, this.rows, this.cols)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)');
}x = [0.090909, 0.636364] (1/11, 7/11)
Properties
final Float64List afinal int rowsfinal int colsMethods
void apply(Float64List x, Float64List y)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');
}row sums: [6.0, 15.0]
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
static double dot(Float64List a, Float64List b)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));
}11.0
static double norm(Float64List a)The 2-norm, scaled to avoid overflow and underflow (LAPACK dnrm2's idea, one pass).
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)}');
}|a| = 3.0, |b| = 5.0
static void axpy(double alpha, Float64List x, Float64List y)y + = \alpha \cdot x.
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');
}b ← 2a + b = [5.0, 4.0, 8.0]
static void xpby(Float64List x, double beta, Float64List y)y = x + \beta \cdot y.
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');
}b ← a + 0.5 b = [2.5, 2.0, 4.0]
Ordering
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
static Int32List natural(int n)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));
}[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.
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)}');
}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.
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');
}nnz(L): natural 519, AMD order 354
static int bandwidth(CsrMatrix a)Bandwidth max |i - j| over stored entries (to compare orderings).
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))}');
}tridiagonal: 1 poisson2d(10, 10): 10
Preconditioner
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
void solve(Float64List r, Float64List z)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;
}
}
}CG with a custom preconditioner: 15 iterations
final class IdentityPreconditioner implements Preconditioner
M = I.
Constructors
const IdentityPreconditioner()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})');
}CG with IdentityPreconditioner: 52 iterations (plain 52)
Methods
void solve(Float64List r, Float64List z)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()}');
}z = M⁻¹·1 = [1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000, 1.0000]
JacobiPreconditioner
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)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})');
}CG with JacobiPreconditioner: 52 iterations (plain 52)
Methods
void solve(Float64List r, Float64List z)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()}');
}z = M⁻¹·1 = [0.2500, 0.2500, 0.2500, 0.2500, 0.2500, 0.2500, 0.2500, 0.2500, 0.2500]
Ilu0Preconditioner
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)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})');
}CG with Ilu0Preconditioner: 28 iterations (plain 52)
Methods
void solve(Float64List r, Float64List z)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()}');
}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)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})');
}CG with IncompleteCholeskyPreconditioner: 28 iterations (plain 52)
Properties
Methods
void solve(Float64List r, Float64List z)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()}');
}z = M⁻¹·1 = [0.6083, 0.7166, 0.5471, 0.7166, 0.8900, 0.7093, 0.5471, 0.7093, 0.6046]