packages

sparse

On this page

Sparse matrices on core's Array: compressed rows (Csr), compressed columns (Csc) and triplets (Coo), their products and conversions, Krylov solvers (cg, gmres, bicgstab) with preconditioners (Jacobi, ilu0, ic0) that also take matrix-free operators, and direct factorizations (cholesky, lu) after a fill-reducing order. Values are f64. Bad input throws a SparseError that says what to call instead; nothing panics except the operators, which cannot throw and panic on a shape mismatch as core's do.

Pure Nabi, so every target, wasm included, gets the same results.

Modules

  • ops linalg's operators on sparse matrices (feature ops, on by default): a @ x, a ⊡ x product with a vector, a dense matrix or a sparse matrix a \ b, a ⧵ b solve a x = b by sparse LU (a Result) a† transpose, as the other form sharing the arrays The tokens are linalg's (linalg::ops); use linalg::ops::* brings them into scope.

Structs

CooSource

pub struct Coo

A sparse matrix as (row, col, value) triplets in any order, with repeats allowed (they add up when converted). Push entries, then convert once with to_csr or to_csc.

nabi
use sparse::Coo;

let c = Coo::new([3, 3]);
for i in 0..3 { try c.push(i, i, 2.0); }
try c.push(0, 1, -1.0);
try c.push(0, 1, -1.0);
let a = c.to_csr();
assert(a.get(0, 1) == -2.0 && a.nnz() == 4);
  • pub fn new(shape: [usize; 2]) -> Coo§

    Source

    An empty shape matrix.

  • pub fn from_triplets(shape: [usize; 2], rows: List<usize>, cols: List<usize>, vals: List<f64>) throws (SparseError) -> Coo§

    Source

    The triplets (rows[p], cols[p], vals[p]), checked against shape.

    nabi
    let c = try sparse::Coo::from_triplets([2, 2], [0, 1], [1, 0], [1.0, 2.0]);
    assert(c.nnz() == 2 && c.to_dense()[1, 0] == 2.0);
    
  • pub fn push(self, i: usize, j: usize, v: f64) throws (SparseError)§

    Source

    Add v at (i, j) (on top of what is there).

  • pub fn shape(self) -> [usize; 2]§

    Source

    [rows, cols].

  • pub fn nnz(self) -> usize§

    Source

    The number of triplets (repeats counted).

  • pub fn rows(self) -> List<usize>§

    Source

    The row of each triplet.

  • pub fn cols(self) -> List<usize>§

    Source

    The column of each triplet.

  • pub fn vals(self) -> List<f64>§

    Source

    The value of each triplet.

  • pub fn to_csr(self) -> Csr§

    Source

    Compressed rows, repeats summed. O(nnz + rows + cols).

  • pub fn to_csc(self) -> Csc§

    Source

    Compressed columns, repeats summed.

  • pub fn to_dense(self) -> Matrix<f64>§

    Source

    The dense matrix, repeats summed.

CscSource

pub struct Csc

A sparse matrix in compressed sparse column form: column j's row indices are indices()[indptr()[j]..indptr()[j + 1]], rising, with their values in data(). The transpose of a Csr with the same arrays.

nabi
use sparse::Csc;

let a = try Csc::from_triplets([2, 3], [0, 1], [2, 0], [1.0, 2.0]);
assert(a.get(0, 2) == 1.0 && a.indptr() == [0, 1, 1, 2]);
assert((try a.matvec([1, 1, 1])).to_list() == [1.0, 2.0]);
  • pub fn new(shape: [usize; 2], indptr: List<usize>, indices: List<usize>, data: List<f64>) throws (SparseError) -> Csc§

    Source

    The matrix of shape from its compressed arrays (see Csc). Unsorted columns and repeated rows are sorted and summed.

  • pub fn from_triplets(shape: [usize; 2], rows: List<usize>, cols: List<usize>, vals: List<f64>) throws (SparseError) -> Csc§

    Source

    The matrix with vals[p] at (rows[p], cols[p]); repeated positions are summed.

  • pub fn from_dense(m: Matrix<f64>, drop: f64 = 0.0) -> Csc§

    Source

    The entries of m with |x| > drop.

  • pub fn shape(self) -> [usize; 2]§

    Source

    [rows, cols].

  • pub fn nnz(self) -> usize§

    Source

    The number of stored entries.

  • pub fn indptr(self) -> List<usize>§

    Source

    The column pointers: cols + 1 offsets into indices and data.

  • pub fn indices(self) -> List<usize>§

    Source

    The row index of each stored entry, column by column.

  • pub fn data(self) -> List<f64>§

    Source

    The value of each stored entry, column by column.

  • pub fn get(self, i: usize, j: usize) -> f64§

    Source

    The element at (i, j): 0 where nothing is stored. Panics outside the shape.

  • pub fn matvec<X: AsVector<f64>>(self, x: X) throws (SparseError) -> Vector<f64>§

    Source

    A x. O(nnz).

  • pub fn rmatvec<X: AsVector<f64>>(self, x: X) throws (SparseError) -> Vector<f64>§

    Source

    A^T x. O(nnz).

  • pub fn matmul(self, b: Csc) throws (SparseError) -> Csc§

    Source

    A B for a sparse B, as (B^T A^T)^T on the row kernels.

    nabi
    let a = sparse::eye(2).to_csc().scale(2.0);
    assert((try a.matmul(a)).get(0, 0) == 4.0);
    
  • pub fn add(self, b: Csc) throws (SparseError) -> Csc§

    Source

    A + B.

  • pub fn sub(self, b: Csc) throws (SparseError) -> Csc§

    Source

    A - B.

  • pub fn scale(self, s: f64) -> Csc§

    Source

    s A.

  • pub fn t(self) -> Csr§

    Source

    The transpose as a Csr sharing these arrays: O(1).

  • pub fn transpose(self) -> Csc§

    Source

    The transpose as a new Csc. O(nnz).

  • pub fn to_csr(self) -> Csr§

    Source

    The same matrix in compressed sparse row form. O(nnz).

  • pub fn to_coo(self) -> Coo§

    Source

    The entries as triplets.

  • pub fn to_dense(self) -> Matrix<f64>§

    Source

    The dense matrix.

  • pub fn diagonal(self) -> Vector<f64>§

    Source

    The main diagonal.

  • pub fn cols(self, r: Range<usize>) throws (SparseError) -> Csc§

    Source

    Columns r, as a new matrix.

    nabi
    let a = sparse::eye(4).to_csc();
    assert((try a.cols(1..2)).shape() == [4, 1]);
    
  • pub fn rows(self, r: Range<usize>) throws (SparseError) -> Csc§

    Source

    Rows r, as a new matrix.

Trait implementations 2
  • impl PartialEq for Csc
  • impl Debug for Csc

CsrSource

pub struct Csr

A sparse matrix in compressed sparse row form: row i's column indices are indices()[indptr()[i]..indptr()[i + 1]], rising, with their values in data(). Build one with from_triplets, from_dense, eye, diags or Coo::to_csr; A x costs O(nnz).

nabi
use sparse::Csr;

let a = try Csr::from_triplets([2, 3], [0, 1, 1, 0], [0, 2, 2, 1], [1.0, 2.0, 3.0, 4.0]);
assert(a.nnz() == 3 && a.get(1, 2) == 5.0 && a.get(1, 0) == 0.0);
let y = try a.matvec([1, 1, 1]);
assert(y.to_list() == [5.0, 5.0]);
  • pub fn new(shape: [usize; 2], indptr: List<usize>, indices: List<usize>, data: List<f64>) throws (SparseError) -> Csr§

    Source

    The matrix of shape from its compressed arrays (see Csr). Unsorted rows and repeated columns are sorted and summed; arrays that do not describe a matrix throw BadStructure.

    nabi
    use sparse::Csr;
    
    let a = try Csr::new([2, 2], [0, 1, 2], [1, 0], [5.0, 6.0]);
    assert(a.get(0, 1) == 5.0 && a.get(1, 0) == 6.0);
    
  • pub fn from_triplets(shape: [usize; 2], rows: List<usize>, cols: List<usize>, vals: List<f64>) throws (SparseError) -> Csr§

    Source

    The matrix with vals[p] at (rows[p], cols[p]); repeated positions are summed (the finite-element assembly rule).

    nabi
    use sparse::Csr;
    
    let a = try Csr::from_triplets([2, 2], [0, 0, 1], [0, 0, 1], [1.0, 2.0, 4.0]);
    assert(a.get(0, 0) == 3.0 && a.nnz() == 2);
    
  • pub fn from_dense(m: Matrix<f64>, drop: f64 = 0.0) -> Csr§

    Source

    The entries of m with |x| > drop (default: every nonzero).

    nabi
    use sparse::Csr;
    use core::array::Matrix;
    
    let m: Matrix<f64> = [[1, 0], [0, 1e-20]];
    assert(Csr::from_dense(m).nnz() == 2);
    assert(Csr::from_dense(m, drop: 1e-12).nnz() == 1);
    
  • pub fn shape(self) -> [usize; 2]§

    Source

    [rows, cols].

  • pub fn nnz(self) -> usize§

    Source

    The number of stored entries.

  • pub fn indptr(self) -> List<usize>§

    Source

    The row pointers: rows + 1 offsets into indices and data.

  • pub fn indices(self) -> List<usize>§

    Source

    The column index of each stored entry, row by row.

  • pub fn data(self) -> List<f64>§

    Source

    The value of each stored entry, row by row.

  • pub fn get(self, i: usize, j: usize) -> f64§

    Source

    The element at (i, j): 0 where nothing is stored. O(log of the row's length). Panics outside the shape, as indexing does.

    nabi
    let a = sparse::eye(3);
    assert(a.get(2, 2) == 1.0 && a.get(0, 2) == 0.0);
    
  • pub fn matvec<X: AsVector<f64>>(self, x: X) throws (SparseError) -> Vector<f64>§

    Source

    A x. O(nnz).

    nabi
    let a = try sparse::diags([[2.0, 2.0], [1.0]], [0, 1], [2, 2]);
    assert((try a.matvec([1, 1])).to_list() == [3.0, 2.0]);
    
  • pub fn rmatvec<X: AsVector<f64>>(self, x: X) throws (SparseError) -> Vector<f64>§

    Source

    A^T x. O(nnz).

    nabi
    let a = try sparse::diags([[2.0, 2.0], [1.0]], [0, 1], [2, 2]);
    assert((try a.rmatvec([1, 1])).to_list() == [2.0, 3.0]);
    
  • pub fn matmul_dense(self, b: Matrix<f64>) throws (SparseError) -> Matrix<f64>§

    Source

    A B for a dense B: one sparse row times B per row of the answer. O(nnz * B's columns).

    nabi
    use core::array::Matrix;
    
    let b: Matrix<f64> = [[1, 2], [3, 4]];
    assert(try sparse::eye(2).matmul_dense(b) == b);
    
  • pub fn matmul(self, b: Csr) throws (SparseError) -> Csr§

    Source

    A B for a sparse B (Gustavson's algorithm).

    nabi
    let a = try sparse::diags([[1.0, 2.0]], [0], [2, 2]);
    let b = try a.matmul(a);
    assert(b.get(1, 1) == 4.0 && b.nnz() == 2);
    
  • pub fn add(self, b: Csr) throws (SparseError) -> Csr§

    Source

    A + B.

    nabi
    let a = sparse::eye(2);
    assert((try a.add(a)).get(1, 1) == 2.0);
    
  • pub fn sub(self, b: Csr) throws (SparseError) -> Csr§

    Source

    A - B.

  • pub fn scale(self, s: f64) -> Csr§

    Source

    s A.

    nabi
    assert(sparse::eye(2).scale(3.0).get(0, 0) == 3.0);
    
  • pub fn t(self) -> Csc§

    Source

    The transpose as a Csc sharing these arrays: O(1).

    nabi
    let a = try sparse::Csr::from_triplets([2, 3], [0], [2], [7.0]);
    assert(a.t().shape() == [3, 2] && a.t().get(2, 0) == 7.0);
    
  • pub fn transpose(self) -> Csr§

    Source

    The transpose as a new Csr. O(nnz).

  • pub fn to_csc(self) -> Csc§

    Source

    The same matrix in compressed sparse column form. O(nnz).

    nabi
    let a = sparse::eye(3);
    assert(a.to_csc().get(1, 1) == 1.0);
    
  • pub fn to_coo(self) -> Coo§

    Source

    The entries as triplets.

  • pub fn to_dense(self) -> Matrix<f64>§

    Source

    The dense matrix.

    nabi
    let d = sparse::eye(2).to_dense();
    assert(d[1, 1] == 1.0 && d[0, 1] == 0.0);
    
  • pub fn diagonal(self) -> Vector<f64>§

    Source

    The main diagonal.

  • pub fn rows(self, r: Range<usize>) throws (SparseError) -> Csr§

    Source

    Rows r, as a new matrix.

    nabi
    let a = sparse::eye(4);
    let b = try a.rows(1..3);
    assert(b.shape() == [2, 4] && b.get(0, 1) == 1.0);
    
  • pub fn cols(self, r: Range<usize>) throws (SparseError) -> Csr§

    Source

    Columns r, as a new matrix.

    nabi
    let a = sparse::eye(4);
    let b = try a.cols(2..4);
    assert(b.shape() == [4, 2] && b.get(3, 1) == 1.0);
    
Trait implementations 2
  • impl PartialEq for Csr
  • impl Debug for Csr

CholeskySource

pub struct Cholesky

P A P^T = L L^T for a sparse symmetric positive definite A. See cholesky.

  • pub fn solve<X: AsVector<f64>>(self, b: X) throws (SparseError) -> Vector<f64>§

    Source

    x with A x = b: two triangular solves, O(|L|).

  • pub fn l(self) -> Csc§

    Source

    The factor L (lower triangular, of P A P^T).

  • pub fn perm(self) -> List<usize>§

    Source

    The permutation: row and column i of P A P^T are perm()[i] of A.

  • pub fn nnz(self) -> usize§

    Source

    The number of stored entries of L (the fill shows here).

  • pub fn logdet(self) -> f64§

    Source

    ln det A, 2 sum ln L_ii: no overflow for large matrices.

    nabi
    let a = try sparse::diags([[2.0, 8.0]], [0], [2, 2]);
    assert(((try sparse::cholesky(a)).logdet() - 16.0.ln()).abs() < 1e-14);
    
Trait implementations 1

LuSource

pub struct Lu

P A Q = L U for a sparse square nonsingular A. See lu.

  • pub fn solve<X: AsVector<f64>>(self, b: X) throws (SparseError) -> Vector<f64>§

    Source

    x with A x = b: two triangular solves, O(|L| + |U|).

  • pub fn l(self) -> Csc§

    Source

    L: unit lower triangular, of P A Q.

  • pub fn u(self) -> Csc§

    Source

    U: upper triangular, of P A Q.

  • pub fn p(self) -> List<usize>§

    Source

    The row order: row k of P A is row p()[k] of A.

  • pub fn q(self) -> List<usize>§

    Source

    The column order: column k of A Q is column q()[k] of A.

  • pub fn nnz(self) -> usize§

    Source

    The number of stored entries of L and U together.

  • pub fn det(self) -> f64§

    Source

    det A: the product of U's diagonal and the signs of both permutations.

Trait implementations 1

SolutionSource

pub struct Solution

What an iterative solver found: x, the steps it took (gmres: inner steps over all restarts) and the final residual norm ||b - A x||, computed afresh.

nabi
let a = try sparse::diags([[2.0], [-1.0], [-1.0]], [0, 1, -1], [10, 10]);
let s = try sparse::cg(a, List::filled(10, 1.0));
assert(s.iterations <= 10 && s.residual <= 1e-8 * 10.0.sqrt());
println(s.x);
  • pub x: Vector<f64>§

    Source

    The solution.

  • pub iterations: usize§

    Source

    The number of steps taken.

  • pub residual: f64§

    Source

    ||b - A x||.

FnOperatorSource

pub struct FnOperator

A matrix-free n x n operator: f(x) is A x. See operator.

Trait implementations 1

Ic0Source

pub struct Ic0

A ~ L L^T on the pattern of the lower triangle of a symmetric A. See ic0.

Trait implementations 1

IdentitySource

pub struct Identity

No preconditioning: M = I. The solvers' default.

Trait implementations 1

Ilu0Source

pub struct Ilu0

A ~ L U on the pattern of A (L unit lower, both stored in one CSR). See ilu0.

Trait implementations 1

JacobiSource

pub struct Jacobi

M = diag(A): divides by the diagonal. Cheap; helps when rows are scaled very differently.

  • pub fn new<S: Sparse>(a: S) throws (SparseError) -> Jacobi§

    Source

    The Jacobi preconditioner of a square a; a zero on the diagonal throws Singular.

Trait implementations 1

Enums

SparseErrorSource

pub enum SparseError

What went wrong in a sparse call.

nabi
use sparse::SparseError;

let a = try sparse::diags([[1.0, 0.0]], [0], [2, 2]);
let e = try {
    _ = try sparse::lu(a);
    SparseError::NotFinite
} catch e: SparseError { e };
assert(e == SparseError::Singular { column: 1 });
assert(f"{e}".contains("lstsq"));
  • ShapeMismatch§

    Source

    The operands' shapes do not fit; what names both.

  • OutOfBounds§

    Source

    A row or column index is outside the shape.

  • BadStructure§

    Source

    Compressed arrays that do not describe a matrix: what says which rule they break.

  • NotSquare§

    Source

    A square matrix was needed.

  • NotSymmetric§

    Source

    A symmetric matrix was needed; (row, col) differs from its mirror.

  • Singular§

    Source

    No usable pivot in column (0-based, in elimination order): the matrix is singular, or numerically so.

  • NotPositiveDefinite§

    Source

    A pivot that is not positive in column (0-based, in elimination order): the matrix is not positive definite.

  • NoConvergence§

    Source

    An iterative solver stopped after iterations steps with the residual norm residual above the tolerance.

  • Breakdown§

    Source

    An iterative solver divided by zero after iterations steps; what names the quantity.

  • NotFinite§

    Source

    The input holds NaN or an infinity.

Trait implementations 2
  • impl Display for SparseError
  • impl Error for SparseError

OrderSource

pub enum Order

How a direct factorization orders the unknowns before eliminating.

nabi
use sparse::Order;

let a = try sparse::diags([[4.0], [-1.0], [-1.0]], [0, 1, -1], [5, 5]);
let f = try sparse::cholesky(a, order: Order::Natural);
assert(f.perm() == [0, 1, 2, 3, 4]);
  • Natural§

    Source

    As given.

  • Reverse Cuthill-McKee: a small bandwidth, quick to compute.

  • MinDegree§

    Source

    Minimum degree: the least fill of the three on most problems (the default).

Traits

SparseSource

pub trait Sparse

A sparse matrix in any form: Csr, Csc or Coo. A function that takes Sparse converts once to the form it works in (free when it is already that form).

nabi
use sparse::Sparse;

let a = sparse::eye(2);
assert(a.as_csc().get(1, 1) == 1.0 && a.to_coo().as_csr() == a);

OperatorSource

pub trait Operator

A linear map x -> A x of dims() ([rows, cols]): Csr, Csc, a dense Matrix<f64>, or a function wrapped by operator.

nabi
use sparse::Operator;
use core::array::Vector;

let a = sparse::eye(2).scale(2.0);
let x: Vector<f64> = [1, 3];
assert(a.dims() == [2, 2] && a.apply(x).to_list() == [2.0, 6.0]);
  • fn dims(self) -> [usize; 2]§

    Source

    [rows, cols].

  • fn apply(self, x: Vector<f64>) -> Vector<f64>§

    Source

    A x, for x of length cols.

PreconditionerSource

pub trait Preconditioner

r -> M^-1 r for some M close to A and cheap to solve with: Identity (none), Jacobi, Ilu0, Ic0, or an exact Cholesky / Lu of a nearby matrix.

nabi
use sparse::Preconditioner;
use core::array::Vector;

let a = try sparse::diags([[4.0, 2.0]], [0], [2, 2]);
let m = try sparse::Jacobi::new(a);
let r: Vector<f64> = [4, 4];
assert(m.precondition(r).to_list() == [1.0, 2.0]);
  • fn precondition(self, r: Vector<f64>) -> Vector<f64>§

    Source

    M^-1 r.

Functions

diagsSource

pub fn diags(diagonals: List<List<f64>>, offsets: List<i64>, shape: [usize; 2]) throws (SparseError) -> Csr

The shape matrix with diagonals[d] on diagonal offsets[d] (0 the main one, k > 0 above it, k < 0 below), as SciPy's diags. Each diagonal has its full length (min(m, n - k) for k >= 0, min(m + k, n) below) or one value, repeated.

nabi
// The 1-d Laplacian: 2 on the diagonal, -1 next to it.
let a = try sparse::diags([[2.0], [-1.0], [-1.0]], [0, 1, -1], [4, 4]);
assert(a.nnz() == 10 && a.get(3, 2) == -1.0 && a.get(0, 0) == 2.0);

eyeSource

pub fn eye(n: usize) -> Csr

The n x n identity.

nabi
let i = sparse::eye(3);
assert(i.nnz() == 3 && i.get(1, 1) == 1.0);

kronSource

pub fn kron(a: Csr, b: Csr) -> Csr

The Kronecker product A ⊗ B: block (i, j) is a[i, j] B. The 2-d Laplacian is kron(I, T) + kron(T, I) for the 1-d one T.

nabi
let t = try sparse::diags([[2.0], [-1.0], [-1.0]], [0, 1, -1], [3, 3]);
let i = sparse::eye(3);
let l = try sparse::kron(i, t).add(sparse::kron(t, i));
assert(l.shape() == [9, 9] && l.get(4, 4) == 4.0 && l.get(4, 1) == -1.0);

choleskySource

pub fn cholesky<S: Sparse>(a: S, order: Order = Order::MinDegree) throws (SparseError) -> Cholesky

The sparse Cholesky factorization of a symmetric positive definite a after the fill-reducing order (default minimum degree). A matrix that is not symmetric throws NotSymmetric, one that is not positive definite NotPositiveDefinite. Cost O(flops of L), about n^1.5 on a 2-d grid with minimum degree.

nabi
use core::array::Vector;

let t = try sparse::diags([[4.0], [-1.0], [-1.0]], [0, 1, -1], [10, 10]);
let a = try sparse::kron(sparse::eye(10), t).add(sparse::kron(t, sparse::eye(10)));
let f = try sparse::cholesky(a);
let x = try f.solve(List::filled(100, 1.0));
assert((try a.matvec(x)).all_close(Vector::<f64>::ones([100])));

luSource

pub fn lu<S: Sparse>(a: S, order: Order = Order::MinDegree, pivot_tol: f64 = 0.1) throws (SparseError) -> Lu

The sparse LU factorization of a square a: the columns in order (default minimum degree on A + A^T), rows by threshold partial pivoting. A diagonal entry is kept as the pivot while it is at least pivot_tol times the column's largest candidate (1.0: plain partial pivoting, smaller: sparser factors at some cost in stability). No nonzero pivot throws Singular.

nabi
use core::array::Vector;

let a = try sparse::Csr::from_triplets([3, 3], [0, 0, 1, 2, 2], [1, 2, 0, 0, 2], [2.0, 1.0, 3.0, 1.0, 4.0]);
let f = try sparse::lu(a);
let x = try f.solve([3, 3, 5]);
assert(x.all_close(Vector::<f64>::from([1.0, 1.0, 1.0])));
assert((f.det() - (-24.0)).abs() < 1e-12);

bicgstabSource

pub fn bicgstab<A: Operator, X: AsVector<f64>>(a: A, b: X, pre: any Preconditioner = Identity {}, x0: Vector<f64> | none = none, rtol: f64 = 1e-8, atol: f64 = 0.0, max_iter: usize | none = none) throws (SparseError) -> Solution

Solve A x = b for any square nonsingular A by BiCGSTAB: short recurrences, so memory O(n) whatever the step count; each step costs two A x and two pre. Convergence is not monotone and it can break down (a zero inner product): that throws Breakdown, after which gmres is the safe choice.

nabi
let a = try sparse::diags([[3.0], [-1.5], [-0.5]], [0, 1, -1], [50, 50]);
let s = try sparse::bicgstab(a, List::filled(50, 1.0), pre: try sparse::ilu0(a));
assert(s.residual <= 1e-8 * 50.0.sqrt());

cgSource

pub fn cg<A: Operator, X: AsVector<f64>>(a: A, b: X, pre: any Preconditioner = Identity {}, x0: Vector<f64> | none = none, rtol: f64 = 1e-8, atol: f64 = 0.0, max_iter: usize | none = none) throws (SparseError) -> Solution

Solve A x = b for a symmetric positive definite A by conjugate gradients, with an SPD preconditioner pre (Jacobi, ic0, ...). Each step costs one A x, one pre and O(n); in exact arithmetic it ends within n steps, in practice after about sqrt(cond(A)) unpreconditioned ones. A direction with p^T A p <= 0 shows A is not positive definite and throws NotPositiveDefinite.

nabi
use core::array::Vector;

let a = try sparse::diags([[4.0], [1.0], [1.0]], [0, 1, -1], [3, 3]);
let s = try sparse::cg(a, [1, 2, 3]);
let b: Vector<f64> = [1, 2, 3];
assert((try a.matvec(s.x)).all_close(b, abs: 1e-8));

gmresSource

pub fn gmres<A: Operator, X: AsVector<f64>>(a: A, b: X, pre: any Preconditioner = Identity {}, x0: Vector<f64> | none = none, rtol: f64 = 1e-8, atol: f64 = 0.0, restart: usize = 30, max_iter: usize | none = none) throws (SparseError) -> Solution

Solve A x = b for any square nonsingular A by GMRES(restart): minimizes ||b - A x|| over a Krylov space of up to restart vectors, then starts again from the best x. Never breaks down; memory restart * n, step k costs O(k n) plus one A x and one pre. Right preconditioning, so the residual tested is the true one.

nabi
// Convection-diffusion: not symmetric, so not for cg.
let a = try sparse::diags([[3.0], [-1.5], [-0.5]], [0, 1, -1], [50, 50]);
let s = try sparse::gmres(a, List::filled(50, 1.0), restart: 10);
assert(s.residual <= 1e-8 * 50.0.sqrt());

operatorSource

pub fn operator(n: usize, f: fn(Vector<f64>) -> Vector<f64>) -> FnOperator

The n x n operator x -> f(x), for the iterative solvers when A is cheaper to apply than to store.

nabi
use core::array::Vector;

// The 1-d Laplacian as a stencil.
let n = 50;
let lap = sparse::operator(n, |x: Vector<f64>| -> Vector<f64> {
    Vector::<f64>::from_fn([n], |i: [usize; 1]| -> f64 {
        let k = i[0];
        2.0 * x[k] - (if k > 0 { x[k - 1] } else { 0.0 }) - (if k + 1 < n { x[k + 1] } else { 0.0 })
    })
});
let s = try sparse::cg(lap, Vector::<f64>::ones([n]));
assert(s.residual < 1e-6);

min_degreeSource

pub fn min_degree<S: Sparse>(a: S) throws (SparseError) -> List<usize>

The minimum degree order of a square a: eliminate a vertex of the fewest neighbours in the elimination graph, then join its neighbours (Tinney and Walker 1967, on the explicit graph, without AMD's approximate degrees or supervariables: exact, slower on big 3-d problems).

nabi
let t = try sparse::diags([[4.0], [-1.0], [-1.0]], [0, 1, -1], [4, 4]);
let a = try sparse::kron(sparse::eye(4), t).add(sparse::kron(t, sparse::eye(4)));
let p = try sparse::min_degree(a);
assert(p.len() == 16 && p[0] == 0);   // a corner has the fewest neighbours

rcmSource

pub fn rcm<S: Sparse>(a: S) throws (SparseError) -> List<usize>

The reverse Cuthill-McKee order of a square a: breadth-first from a pseudo-peripheral vertex (George and Liu 1979) of each component, neighbours by rising degree, then reversed. O(nnz log).

nabi
let a = try sparse::diags([[2.0], [-1.0], [-1.0]], [0, 3, -3], [6, 6]);
let p = try sparse::rcm(a);
assert(p.len() == 6);

ic0Source

pub fn ic0<S: Sparse>(a: S) throws (SparseError) -> Ic0

The IC(0) preconditioner of a symmetric positive definite a (only the lower triangle is read), for cg. A pivot that is not positive throws NotPositiveDefinite; IC(0) can fail on an SPD matrix that is not diagonally dominant, so then use Jacobi or ilu0.

nabi
let t = try sparse::diags([[2.0], [-1.0], [-1.0]], [0, 1, -1], [200, 200]);
let plain = try sparse::cg(t, List::filled(200, 1.0));
let pre = try sparse::cg(t, List::filled(200, 1.0), pre: try sparse::ic0(t));
assert(pre.iterations < plain.iterations);

ilu0Source

pub fn ilu0<S: Sparse>(a: S) throws (SparseError) -> Ilu0

The ILU(0) preconditioner of a square a: Gaussian elimination that drops every fill-in outside a's pattern (IKJ order). A zero or missing diagonal pivot throws Singular. O(sum of row lengths squared).

nabi
let t = try sparse::diags([[4.0], [-1.0], [-1.0]], [0, 1, -1], [100, 100]);
let s = try sparse::gmres(t, List::filled(100, 1.0), pre: try sparse::ilu0(t));
assert(s.iterations <= 2);    // ILU(0) of a tridiagonal matrix is exact