packages

linalg

On this page

Dense linear algebra on core's Array: products, factorizations as types (Lu, Cholesky, Ldlt, Qr, Svd, Eigh, Eig, Schur), solvers and matrix functions. Every routine takes Matrix<T> / Vector<T> (Array<T, 2> / Array<T, 1>, views included) for T in f64, f32, Complex<f64>, Complex<f32> (Scalar), or the real two (Real) where the algorithm is real only. Bad input throws a LinalgError that says what to call instead; nothing panics except the operators of ops, which cannot throw and panic on a shape mismatch as core's broadcast operators do.

Pure Nabi: no BLAS or LAPACK, so every target, wasm included, gets the same results.

Modules

  • factor The factorizations, each a type with solve / det / inv where they make sense; build them with the functions at the package root (linalg::lu(a), linalg::svd(a), ...).
  • ops Operators for matrix code (feature ops, on by default): a @ b, a ⊡ b matrix product (level of *) a ⊗ b Kronecker product; outer product of two vectors (*) a \ b, a ⧵ b solve a x = b, MATLAB's left division (/) a† adjoint, the conjugate transpose (postfix, level of ?) Every operator also has a named form (linalg::matmul(a, b), ...).
  • scalar Element types: Scalar is what every routine needs (f32, f64 and their complex forms), Real adds ordering and the float functions for the iterative routines (SVD, eigen) and for norms.

Re-exports

factor::cholesky::{Cholesky, Ldlt}Source

pub use factor::cholesky::{Cholesky, Ldlt}
  • Cholesky A = L L^H of a Hermitian (real: symmetric) positive definite matrix, L lower triangular with a positive diagonal.
  • Ldlt A = L D L^H without pivoting: L unit lower triangular, D real diagonal.

factor::eig::{Eig, Schur}Source

pub use factor::eig::{Eig, Schur}
  • Eig The eigenvalues and eigenvectors of a real square matrix: A v_j = w_j v_j.
  • Schur The real Schur form A = Z T Z^T: Z orthogonal, T upper quasi-triangular with a 1 x 1 block per real eigenvalue and a 2 x 2 block per complex pair.

factor::eigh::EighSource

pub use factor::eigh::Eigh
  • Eigh A = V diag(w) V^T of a real symmetric matrix: eigenvalues w rising, orthonormal eigenvectors as the columns of V.

factor::lu::LuSource

pub use factor::lu::Lu
  • Lu P A = L U of a square matrix: L unit lower, U upper, P a row permutation.

factor::qr::QrSource

pub use factor::qr::Qr
  • Qr A P = Q R of an m x n matrix: Q unitary (orthogonal for real input), R upper triangular, P a column permutation (the identity unless built with qr_pivoted).

factor::svd::SvdSource

pub use factor::svd::Svd
  • Svd A = U diag(s) V^T of a real m x n matrix: s falls (k = min(m, n) values), U and V have orthonormal columns.

scalar::{Real, Scalar}Source

pub use scalar::{Real, Scalar}
  • Real A real element type, f32 or f64: what the SVD and the eigensolvers take, and the type of every norm.
  • Scalar An element type the routines accept: f32, f64, Complex<f32>, Complex<f64>.

Enums

LinalgErrorSource

pub enum LinalgError

What went wrong in a linear-algebra call.

nabi
use linalg::LinalgError;
use core::array::Matrix;

let a: Matrix<f64> = [[1, 2], [2, 4]];
let e = try {
    _ = try linalg::inv(a);
    LinalgError::NotFinite
} catch e: LinalgError { e };
assert(e == LinalgError::Singular { pivot: 1 });
assert(f"{e}".contains("pinv"));
  • Singular§

    Source

    A zero pivot: the matrix is singular. pivot is its 0-based row.

  • NotSquare§

    Source

    A square matrix was needed.

  • ShapeMismatch§

    Source

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

  • NotPositiveDefinite§

    Source

    Cholesky met a leading minor that is not positive; minor is its order (1-based).

  • NoConvergence§

    Source

    An iteration did not converge in iterations steps.

  • NotFinite§

    Source

    The input holds NaN or an infinity.

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

NormSource

pub enum Norm

Which norm: One (sum of |x|; for a matrix the largest column sum), Two (Euclidean; for a matrix the largest singular value), Inf (largest |x|; for a matrix the largest row sum), Fro (Frobenius: the 2-norm of all entries).

nabi
use core::array::Matrix;
use linalg::Norm;

let a: Matrix<f64> = [[3, 0], [0, 4]];
assert(try linalg::matrix_norm(a, Norm::Two) == 4.0);
assert(try linalg::matrix_norm(a, Norm::Fro) == 5.0);

TriangleSource

pub enum Triangle

Which triangle of a matrix holds the data.

nabi
use core::array::{Matrix, Vector};
use linalg::Triangle;

let u: Matrix<f64> = [[1, 1], [0, 2]];
let b: Vector<f64> = [3, 4];
assert(try linalg::solve_triangular(u, b, Triangle::Upper) == Vector::<f64>::from([1.0, 2.0]));

Traits

AsVectorSource

pub trait AsVector<T>

Something that reads as a Vector<T>: a Vector<T> itself, a List<T> or a [T; K]; for T = f64 also vectors, lists and fixed arrays of f32, i64, i32 and usize, and an i64 range; for T = Complex<f64> real f64 data. A Vector<T> and a List<T> are shared, not copied (a function taking AsVector never writes to its input); every other form is a converted copy.

Take it as a bound to accept all of them with one signature. Give the result its type (let v: Vector<f64> = ..): a list of f32 reads as a Vector<f32> too, and the annotation picks the one meant.

nabi
use linalg::AsVector;
use core::array::Vector;

fn total<X: AsVector<f64>>(x: X) -> f64 {
    let v: Vector<f64> = x.as_vector();
    v.sum()
}

let v: Vector<f64> = [1, 2, 3];
assert(total(v) == 6.0);
assert(total([1, 2, 3]) == 6.0);
assert(total([0.5, 1.5]) == 2.0);
assert(total([1.5f32, 2.5f32]) == 4.0);
assert(total(1..4) == 6.0);
  • fn as_vector(self) -> Vector<T>§

    Source

    self as a vector (see the trait for when it is a copy).

RhsSource

pub trait Rhs<T>

A right-hand side b of A x = b: a vector or a list, or a matrix whose columns are separate right-hand sides. The answer has b's kind.

nabi
use core::array::{Array, Matrix, Vector};

let a: Matrix<f64> = [[2, 0], [0, 4]];
let v: Vector<f64> = [2, 4];
let m: Matrix<f64> = [[2, 4], [4, 8]];
assert(try linalg::solve(a, v) == Vector::<f64>::from([1.0, 1.0]));
assert((try linalg::solve(a, m)).shape() == [2, 2]);
let xs: List<f64> = [2, 4];
assert(try linalg::solve(a, xs) == [1.0, 1.0]);
  • fn matrix(self) -> Matrix<T>§

    Source

    self as a matrix of columns.

  • fn like(self, x: Matrix<T>) -> Self§

    Source

    A solution matrix x in self's kind.

Functions

adjointSource

pub fn adjoint<T: Scalar>(a: Matrix<T>) -> Matrix<T>

The conjugate transpose a^H: a view (a.t()) for a real matrix, a conjugated copy for a complex one.

nabi
use core::array::Matrix;
use core::num::Complex;

let z: Matrix<Complex<f64>> = [[1.0 + 2.0i, 3.0i]];
let h = linalg::adjoint(z);
assert(h.shape() == [2, 1] && h[0, 0] == Complex::new(1.0, -2.0));

diagSource

pub fn diag<T: Scalar>(v: Vector<T>) -> Matrix<T>

The square matrix with v on its diagonal.

nabi
use core::array::Vector;

let v: Vector<f64> = [1, 2];
assert(linalg::diag(v)[1, 1] == 2.0);

diagonalSource

pub fn diagonal<T: Scalar>(a: Matrix<T>) -> Vector<T>

The diagonal a[i, i] of any matrix, as a copy.

nabi
use core::array::{Matrix, Vector};

let a: Matrix<f64> = [[1, 2, 3], [4, 5, 6]];
assert(linalg::diagonal(a) == Vector::<f64>::from([1.0, 5.0]));

eyeSource

pub fn eye<T: Scalar>(n: usize) -> Matrix<T>

The n x n identity.

nabi
use core::array::Matrix;

let i: Matrix<f64> = linalg::eye(2);
assert(i == Matrix::<f64>::from_list([1.0, 0.0, 0.0, 1.0], [2, 2]));

traceSource

pub fn trace<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> T

The sum of the diagonal of a square matrix.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 2], [3, 4]];
assert(try linalg::trace(a) == 5.0);

expmSource

pub fn expm<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> Matrix<T>

e^A of a square matrix.

nabi
use core::array::Matrix;

// e^[[0, t], [-t, 0]] is the rotation by t.
let a: Matrix<f64> = [[0, 1], [-1, 0]];
let e = try linalg::expm(a);
assert((e[0, 0] - 1.0.cos()).abs() < 1e-15 && (e[0, 1] - 1.0.sin()).abs() < 1e-15);

matrix_normSource

pub fn matrix_norm<T: Scalar>(a: Matrix<T>, ord: Norm) throws (LinalgError) -> T::Real

The ord norm of a matrix. Two takes an SVD (O(mn^2)) and can throw NoConvergence; the others are O(mn) and never throw for finite input.

nabi
use core::array::Matrix;
use linalg::Norm;

let a: Matrix<f64> = [[1, -2], [3, 4]];
assert(try linalg::matrix_norm(a, Norm::One) == 6.0);
assert(try linalg::matrix_norm(a, Norm::Inf) == 7.0);
assert((try linalg::matrix_norm(a, Norm::Fro) - 30.0.sqrt()).abs() < 1e-12);

normSource

pub fn norm<T: Scalar>(v: Vector<T>) -> T::Real

The Euclidean norm of v.

nabi
use core::array::Vector;

let v: Vector<f64> = [3, 4];
assert(linalg::norm(v) == 5.0);
let big: Vector<f64> = [3e200, 4e200];   // the squares would overflow
assert((linalg::norm(big) / 5e200 - 1.0).abs() < 1e-15);
let n = v .* 2.0 |> linalg::norm;           // `|>` binds loosest
assert(n == 10.0);

vector_normSource

pub fn vector_norm<T: Scalar>(v: Vector<T>, ord: Norm) -> T::Real

The ord norm of a vector (Fro is Two).

nabi
use core::array::Vector;
use linalg::Norm;

let v: Vector<f64> = [1, -3, 2];
assert(linalg::vector_norm(v, Norm::One) == 6.0);
assert(linalg::vector_norm(v, Norm::Inf) == 3.0);

dotSource

pub fn dot<T: Scalar>(x: Vector<T>, y: Vector<T>) throws (LinalgError) -> T

sum x[i] y[i] (no conjugation; see vdot). Four partial sums.

nabi
use core::array::Vector;

let x: Vector<f64> = [1, 2, 3];
assert(try linalg::dot(x, x) == 14.0);

kronSource

pub fn kron<T: Scalar>(a: Matrix<T>, b: Matrix<T>) -> Matrix<T>

The Kronecker product: the (p r) x (q s) block matrix whose block (i, j) is a[i, j] b.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 2]];
let b: Matrix<f64> = [[1], [10]];
assert(linalg::kron(a, b) == Matrix::<f64>::from_list([1.0, 2.0, 10.0, 20.0], [2, 2]));

matmulSource

pub fn matmul<T: Scalar>(a: Matrix<T>, b: Matrix<T>) throws (LinalgError) -> Matrix<T>

a b for an m x k and a k x n matrix. Cache-blocked; rows of the result are split across workers once mnk reaches 128^3. O(mnk).

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 2], [3, 4]];
let b: Matrix<f64> = [[0, 1], [1, 0]];
assert(try linalg::matmul(a, b) == Matrix::<f64>::from_list([2.0, 1.0, 4.0, 3.0], [2, 2]));

matrix_powerSource

pub fn matrix_power<T: Scalar>(a: Matrix<T>, k: i64) throws (LinalgError) -> Matrix<T>

a to the power k by repeated squaring (O(n^3 log k)); k < 0 inverts first, k = 0 is the identity.

nabi
use core::array::Matrix;

let f: Matrix<f64> = [[1, 1], [1, 0]];
assert((try linalg::matrix_power(f, 10))[0, 1] == 55.0);

matvecSource

pub fn matvec<T: Scalar>(a: Matrix<T>, x: Vector<T>) throws (LinalgError) -> Vector<T>

a x for an m x n matrix and a vector of n. O(mn).

nabi
use core::array::{Matrix, Vector};

let a: Matrix<f64> = [[1, 2], [3, 4]];
let x: Vector<f64> = [1, 1];
assert(try linalg::matvec(a, x) == Vector::<f64>::from([3.0, 7.0]));

outerSource

pub fn outer<T: Scalar>(x: Vector<T>, y: Vector<T>) -> Matrix<T>

The outer product: element (i, j) is x[i] y[j].

nabi
use core::array::{Matrix, Vector};

let x: Vector<f64> = [1, 2];
let y: Vector<f64> = [3, 4, 5];
assert(linalg::outer(x, y)[1, 2] == 10.0);

vdotSource

pub fn vdot<T: Scalar>(x: Vector<T>, y: Vector<T>) throws (LinalgError) -> T

sum conj(x[i]) y[i], the inner product of complex vectors (dot for real ones).

nabi
use core::array::Vector;
use core::num::Complex;

let x: Vector<Complex<f64>> = [1.0 + 1.0i];
assert(try linalg::vdot(x, x) == Complex::new(2.0, 0.0));

vecmatSource

pub fn vecmat<T: Scalar>(x: Vector<T>, a: Matrix<T>) throws (LinalgError) -> Vector<T>

x a (x as a row) for a vector of m and an m x n matrix. O(mn).

nabi
use core::array::{Matrix, Vector};

let a: Matrix<f64> = [[1, 2], [3, 4]];
let x: Vector<f64> = [1, 1];
assert(try linalg::vecmat(x, a) == Vector::<f64>::from([4.0, 6.0]));

condSource

pub fn cond<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> T::Real

The 2-norm condition number s_max / s_min (infinite for a rank-deficient matrix). log10 of it is about the digits a solve loses.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 0], [0, 1e-3]];
assert((try linalg::cond(a) - 1e3).abs() < 1e-9);

detSource

pub fn det<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> T

det(a) by LU (0 for a singular matrix).

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 2], [3, 4]];
assert((try linalg::det(a) + 2.0).abs() < 1e-12);

invSource

pub fn inv<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> Matrix<T>

a^-1 by LU. Throws Singular for a zero pivot; prefer solve to multiplying by the inverse.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[2, 0], [0, 4]];
assert((try linalg::inv(a))[1, 1] == 0.25);

lstsqSource

pub fn lstsq<T: Scalar, B: Rhs<T>>(a: Matrix<T>, b: B) throws (LinalgError) -> B

The least-squares solution of a x = b (m x n a, any shape and rank): minimizes ||a x - b||, and among minimizers ||x||. A pivoted QR finds the numerical rank (diagonal of R above max(m, n) * eps * |R[0, 0]|); a full-rank problem is solved from R, a deficient one through a complete orthogonal decomposition (LAPACK's xGELSY). O(mn^2).

nabi
use core::array::{Matrix, Vector};

// Fit y = c0 + c1 t through (0, 1), (1, 3), (2, 5).
let a: Matrix<f64> = [[1, 0], [1, 1], [1, 2]];
let y: Vector<f64> = [1, 3, 5];
let c = try linalg::lstsq(a, y);
assert((c[0] - 1.0).abs() < 1e-12 && (c[1] - 2.0).abs() < 1e-12);

null_spaceSource

pub fn null_space<T: Real>(a: Matrix<T>) throws (LinalgError) -> Matrix<T>

An orthonormal basis of the null space {x : a x = 0}, as the columns of an n x (n - rank) matrix (from the trailing rows of V^T).

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 1]];
let z = try linalg::null_space(a);
assert(z.shape() == [2, 1] && (z[0, 0] + z[1, 0]).abs() < 1e-12);

pinvSource

pub fn pinv<T: Real>(a: Matrix<T>) throws (LinalgError) -> Matrix<T>

The Moore-Penrose pseudo-inverse V S^+ U^T (n x m), singular values at or below max(m, n) * eps * s_max taken as zero.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 0], [0, 0]];
assert(try linalg::pinv(a) == a);

rankSource

pub fn rank<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> usize

The number of singular values above max(m, n) * eps * s_max.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 2], [2, 4], [3, 6]];
assert(try linalg::rank(a) == 1);

slogdetSource

pub fn slogdet<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> (T, T::Real)

(sign, ln |det(a)|): det(a) = sign * exp(logabs) without overflow. sign has modulus 1 (+-1 for a real matrix), or is 0 with logabs = -inf for a singular one.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1e200, 0], [0, -1e200]];
let (s, l) = try linalg::slogdet(a);
assert(s == -1.0 && (l - 400.0 * 10.0.ln()).abs() < 1e-9);

solveSource

pub fn solve<T: Scalar, B: Rhs<T>>(a: Matrix<T>, b: B) throws (LinalgError) -> B

x with a x = b for a square a, by LU with partial pivoting; b is a vector or a matrix of columns. Throws Singular for a zero pivot. O(2n^3/3 + 2n^2 k).

nabi
use core::array::{Matrix, Vector};

let a: Matrix<f64> = [[3, 1], [1, 2]];
let b: Vector<f64> = [9, 8];
let x = try linalg::solve(a, b);
assert(x == Vector::<f64>::from([2.0, 3.0]));
let r = a @ x .- b |> linalg::norm;           // the residual
assert(r == 0.0);

solve_triangularSource

pub fn solve_triangular<T: Scalar, B: Rhs<T>>(t: Matrix<T>, b: B, part: Triangle) throws (LinalgError) -> B

x with t x = b for a square triangular t, by substitution; only the given triangle of t is read. Throws Singular for a zero on the diagonal. O(n^2 k).

nabi
use core::array::{Matrix, Vector};
use linalg::Triangle;

let l: Matrix<f64> = [[2, 0], [1, 1]];
let b: Vector<f64> = [2, 3];
assert(try linalg::solve_triangular(l, b, Triangle::Lower) == Vector::<f64>::from([1.0, 2.0]));

svdvalsSource

pub fn svdvals<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> Vector<T::Real>

The singular values of a, largest first; complex matrices go through the real form [[Re, -Im], [Im, Re]], whose singular values are those of a, each twice.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[0, 2], [1, 0]];
let s = try linalg::svdvals(a);
assert(s[0] == 2.0 && s[1] == 1.0);

luSource

pub fn lu<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> Lu<T>

P A = L U with partial pivoting (square a). See Lu.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 2], [3, 4]];
let f = try linalg::lu(a);
assert((f.det() + 2.0).abs() < 1e-12);

choleskySource

pub fn cholesky<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> Cholesky<T>

A = L L^H of a Hermitian positive definite matrix. See Cholesky.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[4, 2], [2, 5]];
assert((try linalg::cholesky(a)).l()[1, 1] == 2.0);

ldltSource

pub fn ldlt<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> Ldlt<T>

A = L D L^H without pivoting. See Ldlt.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[2, 1], [1, -1]];
assert((try linalg::ldlt(a)).d()[1] == -1.5);

qrSource

pub fn qr<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> Qr<T>

Householder A = Q R of any m x n matrix. See Qr.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 1], [1, 2], [1, 3]];
let f = try linalg::qr(a);
assert(f.q().shape() == [3, 2] && f.r().shape() == [2, 2]);

qr_pivotedSource

pub fn qr_pivoted<T: Scalar>(a: Matrix<T>) throws (LinalgError) -> Qr<T>

A P = Q R with column pivoting: |R[i, i]| falls, which shows the numerical rank. See Qr.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 10], [1, 20]];
assert((try linalg::qr_pivoted(a)).perm() == [1, 0]);

svdSource

pub fn svd<T: Real>(a: Matrix<T>) throws (LinalgError) -> Svd<T>

The thin SVD of a real matrix (U is m x k, V^T k x n, k = min(m, n)). See Svd.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 0, 0], [0, 2, 0]];
let f = try linalg::svd(a);
assert(f.u().shape() == [2, 2] && f.vt().shape() == [2, 3]);

svd_fullSource

pub fn svd_full<T: Real>(a: Matrix<T>) throws (LinalgError) -> Svd<T>

The full SVD (U is m x m, V^T n x n). See Svd.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[1, 0, 0], [0, 2, 0]];
assert((try linalg::svd_full(a)).vt().shape() == [3, 3]);

eighSource

pub fn eigh<T: Real>(a: Matrix<T>) throws (LinalgError) -> Eigh<T>

Eigenvalues and eigenvectors of a real symmetric matrix. See Eigh.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[2, 0], [0, 1]];
assert((try linalg::eigh(a)).values()[0] == 1.0);

eigvalshSource

pub fn eigvalsh<T: Real>(a: Matrix<T>) throws (LinalgError) -> Vector<T>

The eigenvalues of a real symmetric matrix, rising, without the vectors (about a third of the work of eigh).

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[0, 1], [1, 0]];
let w = try linalg::eigvalsh(a);
assert((w[0] + 1.0).abs() < 1e-15 && (w[1] - 1.0).abs() < 1e-15);

eigSource

pub fn eig<T: Real>(a: Matrix<T>) throws (LinalgError) -> Eig<T>

Eigenvalues and eigenvectors of a general real matrix (complex in general). See Eig.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[2, 1], [0, 3]];
assert((try linalg::eig(a)).values().len() == 2);

schurSource

pub fn schur<T: Real>(a: Matrix<T>) throws (LinalgError) -> Schur<T>

The real Schur form A = Z T Z^T. See Schur.

nabi
use core::array::Matrix;

let a: Matrix<f64> = [[0, -1], [1, 0]];
assert((try linalg::schur(a)).t()[1, 0] != 0.0);   // one 2 x 2 block