C++#

#include <numerical/numerical.hpp> brings in everything below, in namespace numerical. The free functions (solve, inverse, determinant, einsum, expm, fft and the rest) are listed, with every overload, in the Doxygen reference.

Containers#

template<typename T>
class matrix#

A dense, row-major matrix of T with value semantics.

Template Parameters:

T – The scalar element type.

Public Functions

matrix() = default#

An empty matrix (0×0).

inline matrix(std::initializer_list<std::initializer_list<T>> rows)#

From a braced list of rows; every row must have the same length.

Parameters:

rows – [in] The rows, each a braced list of elements.

Throws:

dimension_error – If the rows have unequal lengths.

inline explicit matrix(std::size_t rows, std::size_t cols, buffer<T> elements)#

From dimensions and a flat row-major buffer.

Parameters:
  • rows, cols – [in] The dimensions.

  • elements – [in] The rows*cols elements, row-major (moved in).

Throws:

dimension_error – If elements.size() is not rows*cols.

inline explicit matrix(std::size_t rows, std::size_t cols, const std::vector<T> &elements)#

From dimensions and a flat row-major std::vector, copied into the storage (a buffer moves in instead).

Parameters:
  • rows, cols – [in] The dimensions.

  • elements – [in] The rows*cols elements, row-major.

Throws:

dimension_error – If elements.size() is not rows*cols.

inline explicit matrix(std::size_t rows, std::size_t cols, std::initializer_list<T> elements)#

From dimensions and a braced list of the elements, row-major.

Parameters:
  • rows, cols – [in] The dimensions.

  • elements – [in] The rows*cols elements, row-major.

Throws:

dimension_error – If the list’s length is not rows*cols.

inline std::size_t rows() const noexcept#

The number of rows.

inline std::size_t cols() const noexcept#

The number of columns.

inline const T &operator()(std::size_t row, std::size_t col) const#

The element at (row, col).

Pre:

In bounds.

inline bool operator==(const matrix &other) const#

Exact equality (same shape and equal elements).

inline buffer<T>::const_iterator begin() const noexcept#

Const iterator to the first element (row-major).

inline buffer<T>::const_iterator end() const noexcept#

Const iterator past the last element.

inline buffer<T> elements() &&#

The elements, row-major, handed over by a matrix about to expire, which is left 0 × 0: a large result moves on without a copy (each copy of a fresh buffer faults its pages in one by one).

template<typename T>
class vector#

A dense vector of T with value semantics.

Template Parameters:

T – The scalar element type.

Public Functions

vector() = default#

An empty vector (size 0).

inline vector(std::initializer_list<T> elements)#

From a braced list of elements.

Parameters:

elements – [in] The elements.

inline explicit vector(buffer<T> elements)#

From an existing buffer.

Parameters:

elements – [in] The elements (moved in).

inline explicit vector(const std::vector<T> &elements)#

From a std::vector, copied into the storage (a buffer moves in instead).

Parameters:

elements – [in] The elements.

inline std::size_t size() const noexcept#

The number of elements.

inline const T &operator[](std::size_t index) const#

The element at index.

Pre:

index < size.

inline buffer<T>::const_iterator begin() const noexcept#

Const iterator to the first element.

inline buffer<T>::const_iterator end() const noexcept#

Const iterator past the last element.

inline bool operator==(const vector &other) const#

Exact element-wise equality (same size, equal elements).

template<typename T>
class tensor#

A dense N-dimensional tensor of T with value semantics, read row-major. Its elements are immutable once built, so tensors share them: a copy, a tensor of another shape over the same elements (reshaped), one with its axes permuted (transposed) and a slice of them (sliced), views reading them along other strides, hold the one buffer, freed with the last of them. A view’s elements in row-major order (data) are copied out on first need, once, and shared with the view’s copies.

Template Parameters:

T – The scalar element type.

Public Functions

inline tensor(std::vector<std::size_t> shape, buffer<T> elements)#

From a shape and a flat row-major buffer.

Parameters:
  • shape – [in] The size of each axis (empty ⇒ a rank-0 scalar).

  • elements – [in] The prod(shape) elements, row-major (moved in).

Throws:

dimension_error – If elements.size() is not prod(shape).

inline tensor(std::vector<std::size_t> shape, const std::vector<T> &elements)#

From a shape and a flat row-major std::vector, copied into the storage (a buffer moves in instead).

Parameters:
  • shape – [in] The size of each axis.

  • elements – [in] The prod(shape) elements, row-major.

Throws:

dimension_error – If elements.size() is not prod(shape).

inline tensor(std::vector<std::size_t> shape, std::initializer_list<T> elements)#

From a shape and a braced list of the elements, row-major.

inline explicit tensor(const vector<T> &v)#

A rank-1 tensor from a vector.

Parameters:

v – [in] The vector.

inline explicit tensor(matrix<T> &&m)#

A rank-2 tensor taking over an expiring matrix’s elements, without a copy.

Parameters:

m – [in] The matrix. The members are initialised in their order, the extents before the elements move: a call’s arguments, and MSVC’s braced lists, have none.

inline explicit tensor(const matrix<T> &m)#

A rank-2 tensor from a matrix.

Parameters:

m – [in] The matrix.

inline tensor reshaped(std::vector<std::size_t> shape) const#

This tensor’s elements in shape, without a copy: the new tensor shares the buffer, as NumPy’s reshape of a contiguous array is a view. A view’s are read where they lie where NumPy’s reshape of it is a view too (reshaped_strides; axes of extent 1 put in or taken out, an axis split, axes whose elements lie one stride from the next joined); else they are its row-major copy (data), made if not yet made.

Throws:

dimension_error – If shape holds another number of elements.

inline tensor transposed(const std::vector<std::size_t> &axes) const#

This tensor with its axes in the order axes (axis k of the result is axis axes[k] of this one), without a copy, as NumPy’s transpose: a view over the same elements, whose row-major copy (data) is made on first need. A permutation that leaves them row-major (one that moves only axes of extent 1, or undoes an earlier one) gives a tensor that shares them as they lie.

Throws:

dimension_error – If axes is not a permutation of the axes.

template<typename Keep = std::vector<bool>>
inline tensor sliced(const std::vector<std::size_t> &starts, const std::vector<std::ptrdiff_t> &steps, const std::vector<std::size_t> &counts, const Keep &keep) const#

The elements starts[a] + i·steps[a] for i < counts[a] along each axis a, without a copy, as NumPy’s basic slicing: a view over the same elements, whose row-major copy (data) is made on first need. An axis whose keep is false (an integer index, its count 1) is dropped from the result’s shape. A step may be negative (::-1); a count of 0 gives an empty tensor.

Throws:
  • dimension_error – If the arguments do not hold one entry per axis, or a dropped axis’s count is not 1.

  • index_error – If a range of a nonzero count leaves its axis.

inline tensor diagonal_view(std::size_t row, std::size_t column, std::size_t length) const#

The length elements from (row, column) down the diagonal of each matrix (the last two axes), without a copy: a view over the same elements, the batch’s axes then the diagonal’s, whose row-major copy (data) is made on first need; a few elements copied at once, as sliced.

Pre:

The rank is at least 2, and length elements from (row, column) lie in each matrix (any start for a length of 0).

inline std::optional<std::pair<tensor, std::vector<std::size_t>>> laid_out() const#

Where this view reaches each of its elements once from the first (a transpose’s, transposed): its axes in the order the elements lie (the widest stride first), with the tensor over those elements row-major in that order, no element copied; nothing for a tensor laid out row-major or any other view. Along each axis the elements are the same, in the same order: what is computed line by line along an axis of this view is computed along the matching axis of the laid out tensor.

inline tensor transposed() const#

transposed with the axes reversed: a matrix’s transpose, NumPy’s .T.

inline std::size_t rank() const noexcept#

The number of axes (0 for a scalar).

inline std::size_t size() const noexcept#

The total number of elements.

inline const std::vector<std::size_t> &shape() const noexcept#

The size of each axis.

inline const T *origin() const noexcept#

The first element where the elements are held (index 0 along every axis): a view (transposed, sliced) reads the others along strides from it. Past the end of nothing for an empty tensor.

inline const std::vector<std::ptrdiff_t> &strides() const noexcept#

Each axis’s step, in elements, from the first element (origin), row-major unless a view, negative along an axis a view reverses.

inline bool contiguous() const noexcept#

Whether the elements lie row-major where they are held: data then copies nothing.

inline tensor materialized() const#

This tensor holding its own elements row-major and nothing more: itself where they lie so, else its row-major copy (data) without the view’s base, which no longer stays alive through it (a copy of a slice of a large array frees that array, as ndarray.copy’s does).

Throws:

std::bad_alloc – If a view finds no memory for its copy.

inline const buffer<T> &data() const#

The elements, row-major. A view’s (transposed) are copied out by the first call, one thread copying while any other waits, and kept for the later calls and for the view’s copies.

Throws:

std::bad_alloc – If a view finds no memory for its copy (a later call tries again).

inline const T &operator()(const std::vector<std::size_t> &index) const#

The element at a multi-index, read where it lies.

Pre:

Its length is rank, in bounds.

inline bool operator==(const tensor &other) const#

Exact equality (same shape and equal elements).

Decompositions#

template<field T>
class lu_decomposition#

An LU factorisation with partial pivoting of a square matrix: each column’s pivot the first entry of the largest detail::pivot_magnitude below the diagonal, |Re| + |Im| of a complex one, as LAPACK’s.

Factorises once on construction; solve, determinant and inverse then reuse the factors. Built for the common case of one matrix and several right-hand sides.

Template Parameters:

T – The scalar element type (a field: double, std::complex<double>, …).

Public Functions

inline explicit lu_decomposition(const matrix<T> &a)#

Factorises a (in place, into combined L\U with a row permutation).

Parameters:

a – [in] The square matrix to factorise.

Throws:

dimension_error – If a is not square.

inline explicit lu_decomposition(matrix<T> &&a)#

Factorises a in its own storage, an expiring matrix’s elements taken over: no copy of them.

Parameters:

a – [in] The square matrix to factorise.

Throws:

dimension_error – If a is not square.

inline vector<T> solve(const vector<T> &b) const#

Solves A x = b using the stored factors.

Parameters:

b – [in] The right-hand side.

Throws:
Returns:

The solution x.

inline T determinant() const#

The determinant (the pivot sign times the product of U’s diagonal; 0 if singular).

inline std::pair<T, double> log_determinant() const#

The determinant as its unit-modulus sign and the natural logarithm of its magnitude, as numpy.linalg.slogdet gives them: a sum of logarithms does not underflow or overflow where the product does (det(1e-2·I) of order 200 is 0.0; its logarithm is −921.0).

Returns:

The sign (+1 or −1 for a real matrix, a unit complex number for a complex one) and the logarithm; a singular matrix gives a sign of 0 and a logarithm of −∞.

inline matrix<T> inverse() const#

The inverse, U⁻¹ L⁻¹ P, by blocks of rows through the matrix product kernel: L⁻¹ from the identity, whose row i stays zero past column i in the forward pass, so that pass reads only the triangle it fills (a third of the products of a full one, as LAPACK’s dgetri spares them); then U⁻¹ on it, and P as a permutation of the columns. The terms left out are products with zeros.

Throws:

singular_matrix_error – If the matrix is singular.

Returns:

The inverse matrix.

inline matrix<T> inverse(buffer<T> storage) const#

inverse in storage, its elements discarded: no fresh n × n mapped and faulted in where it holds that much already. pivoted_inverse, then P applied in place, by bands of rows on the threads.

Parameters:

storage – [in] The storage of the result, taken over.

Throws:

singular_matrix_error – If the matrix is singular.

Returns:

The inverse matrix, in storage.

inline matrix<T> pivoted_inverse(buffer<T> storage) const#

(P A)⁻¹ = U⁻¹ L⁻¹, the inverse of the rows in their pivoted order, in storage (its elements discarded): column pivots()[i] of A⁻¹ is its column i, which inverse moves there (a caller that copies the result anyway can move them as it copies). The identity written by bands of rows on the threads.

Parameters:

storage – [in] The storage of the result, taken over.

Throws:

singular_matrix_error – If the matrix is singular.

Returns:

(P A)⁻¹, in storage.

inline matrix<T> solve(const matrix<T> &b) const#

Solves A X = B for every column of b at once.

By blocks of rows, the products of a block’s solution into the rows still to solve go through the matrix product kernel. The forward substitution is the vector solve’s, term for term; the backward one gives each row the farther blocks’ terms first, so a column agrees with the vector solve to rounding.

Parameters:

b – [in] The right-hand sides (n × k).

Throws:
Returns:

X (n × k).

inline matrix<T> solve(matrix<T> &&b) const#

solve on an expiring b, in its own storage: its rows permuted in place (cycle by cycle of the pivots, one row held aside), then solved there. No copy of B.

Parameters:

b – [in] The right-hand sides (n × k), taken over.

Throws:
Returns:

X (n × k), in b’s storage.

inline matrix<T> factors() const &#

L and U in one matrix, as LAPACK’s dgetrf leaves them: U on and above the diagonal, L below it (its unit diagonal not stored), of the rows in their pivoted order.

inline matrix<T> factors() &&#

factors, moved out of an expiring decomposition: no copy.

inline const std::vector<std::size_t> &pivots() const noexcept#

The row permutation: row i of P A = L U is row pivots()[i] of A.

inline bool singular() const noexcept#

Whether a pivot was zero: U is singular, and solve and inverse throw.

double reciprocal_condition(double one_norm) const#

The reciprocal condition number 1 / (‖A‖₁ ‖A⁻¹‖₁) of the factorised matrix, as LAPACK’s gecon: ‖A⁻¹‖₁ estimated from the factors (Hager’s method, a few solves of n² each), so within a small factor of the exact; the caller gives ‖A‖₁, the largest column sum of moduli of A, which the factors no longer hold. Under the machine epsilon, a solve’s answer may have no correct digit.

Parameters:

one_norm – [in] ‖A‖₁.

Returns:

The estimate: 1 for an empty matrix; 0 for a singular one, a zero one_norm, or an estimate that overflows.

template<field T>
class cholesky_decomposition#

A Cholesky factorisation A = L Lᴴ of a Hermitian positive-definite matrix.

L is lower-triangular with a real, positive diagonal. Only the lower triangle of a is read, so a is assumed Hermitian (symmetric, for a real scalar); the factorisation is about twice as cheap as an LU for this special case and cannot be singular. A matrix that is not positive-definite throws not_positive_definite_error.

Template Parameters:

T – The scalar element type (a field: double, std::complex<double>, …).

Public Functions

inline explicit cholesky_decomposition(const matrix<T> &a)#

Factorises a.

Parameters:

a – [in] The Hermitian positive-definite matrix, its lower triangle alone read.

Throws:
inline explicit cholesky_decomposition(matrix<T> &&a)#

Factorises a in its own storage, an expiring matrix’s elements taken over: no copy of them.

Parameters:

a – [in] The Hermitian positive-definite matrix, its lower triangle alone read.

Throws:
inline matrix<T> lower() const &#

The lower-triangular factor L (with L Lᴴ == A).

inline matrix<T> lower() &&#

The lower-triangular factor L, moved out of an expiring decomposition.

inline vector<T> solve(const vector<T> &b) const#

Solves A x = b via L y = b then Lᴴ x = y.

Parameters:

b – [in] The right-hand side.

Throws:

dimension_error – If b’s size differs from the matrix.

Returns:

The solution x.

inline matrix<T> solve(const matrix<T> &b) const#

Solves A X = B for every column of b at once: L Y = B, then Lᴴ X = Y, row by row, each row of the solution its column’s terms in solve’s order (so each column solve’s bits), a row of terms at a time over the columns; the threads share the columns by slices of 8 and more.

Parameters:

b – [in] The right-hand sides (n × k).

Throws:

dimension_error – If b’s row count differs from the matrix.

Returns:

X (n × k).

inline T determinant() const#

The determinant — the product of the squared diagonal of L (real, positive), its partial products kept among the doubles (detail::scaled_product).

inline double reciprocal_condition(double one_norm) const#

The reciprocal condition number 1 / (‖A‖₁ ‖A⁻¹‖₁) of the factorised matrix, as LAPACK’s pocon: ‖A⁻¹‖₁ estimated from L (Hager’s method, a few solves of n² each), so within a small factor of the exact; the caller gives ‖A‖₁. Under the machine epsilon, a solve’s answer may have no correct digit.

Parameters:

one_norm – [in] ‖A‖₁, the largest column sum of moduli of A.

Returns:

The estimate: 1 for an empty matrix; 0 for a zero one_norm or an estimate that overflows.

template<double_field T>
class ldl_decomposition#

The symmetric indefinite factorisation of a symmetric or Hermitian matrix, as scipy.linalg.ldl: A = L D Lᴴ (Hermitian) or A = L D Lᵀ (symmetric), Bunch and Kaufman’s diagonal pivoting (LAPACK’s sytrf, hetrf: by panels of 64 columns from order 384, their trailing update one matrix product; the unblocked sytf2, hetf2 below it and for the last columns) on the lower triangle, or on the upper one (lower = false, L then upper triangular); D block diagonal with blocks of order 1 and 2; L with a unit diagonal once its rows are permuted (permutation), as SciPy returns them.

Template Parameters:

T – double or std::complex<double>.

Public Functions

inline explicit ldl_decomposition(const matrix<T> &a, bool lower = true, bool hermitian = true)#

Factorises a, of which only the triangle lower names is read.

Parameters:
  • a – [in] The square matrix.

  • lower – [in] The lower triangle (and a lower L), or the upper.

  • hermitian – [in] For a complex matrix, A = Aᴴ (the diagonal’s imaginary parts ignored) or A = Aᵀ; a real one’s either.

Throws:
inline const matrix<T> &factor() const noexcept#

L, permuted (SciPy’s lu): L[permutation()] is triangular with a unit diagonal.

inline const matrix<T> &d() const noexcept#

D, block diagonal (blocks of order 1 and 2).

inline const std::vector<std::size_t> &permutation() const noexcept#

The rows’ order that makes factor triangular (SciPy’s perm).

template<field T>
class qr_decomposition#

A QR factorisation A = Q R of an m × n matrix, as NumPy’s qr, reduced by default.

With k = min(m, n), Q is m × k with orthonormal columns (Qᴴ Q = I) and R is k × n upper trapezoidal (triangular when m ≥ n) with a real, non-negative diagonal; complete (qr_mode::complete), Q is m × m and R m × n, its rows past k zero. Computed by Householder reflections, so Q stays orthonormal to rounding however ill-conditioned A is, and a rank-deficient A factorises too (with zeros on R’s diagonal). solve returns the least-squares solution of A x ≈ b for a full-column-rank A (m ≥ n); for a rank-deficient or wide one, numerical::lstsq gives the minimum-norm solution.

Template Parameters:

T – The scalar element type (a field: double, std::complex<double>, …).

Public Functions

inline explicit qr_decomposition(const matrix<T> &a, qr_mode mode = qr_mode::reduced)#

Factorises a.

Parameters:
  • a – [in] The matrix, any shape.

  • mode – [in] qr_mode::reduced (Q m × k) or qr_mode::complete (Q m × m).

Throws:

non_finite_error – If an entry is infinite or NaN.

inline explicit qr_decomposition(matrix<T> &&a, qr_mode mode = qr_mode::reduced)#

Factorises a in its own storage, an expiring matrix’s elements taken over: no copy of them.

Parameters:
  • a – [in] The matrix, any shape.

  • mode – [in] qr_mode::reduced (Q m × k) or qr_mode::complete (Q m × m).

Throws:

non_finite_error – If an entry is infinite or NaN.

inline matrix<T> q() const &#

The factor Q (orthonormal columns): m × k, k = min(m, n), or m × m complete.

inline matrix<T> q() &&#

Q, moved out of an expiring decomposition (r stays).

inline matrix<T> r() const &#

The upper-trapezoidal factor R: k × n, k = min(m, n), or m × n complete.

inline matrix<T> r() &&#

R, moved out of an expiring decomposition (q stays).

inline vector<T> solve(const vector<T> &b) const#

The least-squares solution of A x ≈ b (x = R⁻¹ Qᴴ b) for a full-rank A.

Parameters:

b – [in] The right-hand side (size m).

Throws:
  • dimension_error – If b’s size differs from the row count, or A is wide (m < n: its system is underdetermined, and numerical::lstsq gives its minimum-norm solution).

  • singular_matrix_error – If A is rank-deficient: a diagonal entry of R is under detail::rank_tolerance (numerical::lstsq solves such a system).

Returns:

The solution x (size n).

inline matrix<T> solve(const matrix<T> &b) const#

The least-squares solutions of A X ≈ B (X = R⁻¹ Qᴴ B) for a full-rank A, every column of b at once: Qᴴ B through the matrix product kernel, then the back substitution by rows of R over all the columns (each column solve’s to rounding: the product sums its terms in another order).

Parameters:

b – [in] The right-hand sides (m × k).

Throws:
Returns:

X (n × k).

template<double_field T>
class pivoted_qr_decomposition#

A QR factorisation with column pivoting A P = Q R of an m × n matrix, as scipy.linalg.qr(a, pivoting=True) (LAPACK’s geqp3): at each step the column of largest remaining norm moved first, so R’s diagonal does not grow in modulus down the diagonal and reveals A’s numerical rank; the norms downdated as LAPACK’s laqp2 downdates them, recomputed where the downdate has lost too much (√ε). Householder reflectors as larfg forms them; R’s diagonal then made real and non-negative, as qr_decomposition’s (Q’s columns taking the phases), where LAPACK’s may be negative.

Public Functions

inline explicit pivoted_qr_decomposition(const matrix<T> &a, qr_mode mode = qr_mode::reduced)#

Factorises a: Q m × k and R k × n (k = min(m, n)), or Q m × m and R m × n (mode complete).

Throws:

non_finite_error – If an entry is infinite or NaN.

inline const matrix<T> &q() const noexcept#

Q, orthonormal columns: m × k, or m × m complete.

inline const matrix<T> &r() const noexcept#

R, upper trapezoidal, its diagonal real, non-negative and not increasing: k × n, or m × n.

inline const std::vector<std::size_t> &permutation() const noexcept#

The column permutation: column j of A P is column permutation()[j] of A, as SciPy’s P.

template<field T>
class svd_decomposition#

The singular value decomposition A = U Σ Vᴴ of an m × n matrix.

With k = min(m, n): the k singular values, descending; U (m × k) and V (n × k) with orthonormal columns, also where A is rank-deficient. Computed after a Householder QR of A (of Aᴴ when m < n): by default R is reduced to bidiagonal form and the bidiagonal decomposed by divide and conquer (svd_method::divide_and_conquer), the method of LAPACK’s dgesdd, most of its work in matrix products, or by implicit-shift QR (svd_method::bidiagonal_qr, dgesvd’s); either way each singular value to an absolute accuracy of the largest times the machine epsilon. One-sided Jacobi on R (svd_method::jacobi) gives every singular value to high relative accuracy — the small ones of a graded matrix too — at several times the cost. vh is Vᴴ, the third factor NumPy’s svd returns. Full (full true, NumPy’s full_matrices=True), U is m × m and V n × n: the columns past k are an orthonormal basis of the complement, the rest of the complete Householder Q of the larger side.

Template Parameters:

T – The scalar element type (double or std::complex<double>).

Public Functions

inline explicit svd_decomposition(const matrix<T> &a, svd_method method = svd_method::divide_and_conquer, bool full = false)#

Decomposes a.

Parameters:
  • a – [in] The matrix.

  • method – [in] The algorithm for R.

  • full – [in] Whether U and V are square (m × m, n × n), as NumPy’s full_matrices=True.

Throws:
inline explicit svd_decomposition(matrix<T> &&a, svd_method method = svd_method::divide_and_conquer, bool full = false)#

Decomposes a in its own storage, an expiring matrix’s elements taken over: its scaled copy is made in place, one matrix less at the peak.

Parameters:
  • a – [in] The matrix.

  • method – [in] The algorithm for R.

  • full – [in] Whether U and V are square (m × m, n × n), as NumPy’s full_matrices=True.

Throws:
inline const vector<double> &singular_values() const noexcept#

The singular values, descending.

inline const matrix<T> &u() const & noexcept#

The left singular vectors U (columns): m × k, or m × m full.

inline matrix<T> u() &&#

U, moved out of an expiring decomposition (v and the singular values stay).

inline const matrix<T> &v() const & noexcept#

The right singular vectors V (columns): n × k, or n × n full.

inline matrix<T> vh() const#

Vᴴ (k × n, or n × n full), so that A = U Σ Vᴴ reads u() * diag(singular_values()) * vh() (full, Σ padded with zeros to m × n).

class symmetric_eigen#

The eigenvalues and eigenvectors of a real symmetric matrix.

By default the matrix is reduced to tridiagonal form by Householder reflections and the tridiagonal is diagonalised by divide and conquer (eigen_method::divide_and_conquer), the method of LAPACK’s dsyevd, most of its work in matrix products; implicit QL (eigen_method::tridiagonal_ql, dsyev’s) and cyclic Jacobi rotations (eigen_method::jacobi) are the alternatives. Whichever, the eigenvalues are real and the eigenvectors orthonormal. The eigenvalues are returned in ascending order, with vectors j-th column the eigenvector of values [j] (A = V Λ Vᵀ). Real symmetric only (the complex Hermitian case is hermitian_eigen). Only the lower triangle is read, as numpy.linalg.eigh reads it by default: the upper one is taken to mirror it.

Public Functions

inline explicit symmetric_eigen(const matrix<double> &input, eigen_method method = eigen_method::divide_and_conquer)#

Diagonalises input.

Parameters:
  • input – [in] A real symmetric matrix (its lower triangle is read).

  • method – [in] The algorithm.

Throws:
inline explicit symmetric_eigen(matrix<double> &&input, eigen_method method = eigen_method::divide_and_conquer)#

Diagonalises input in its own storage, an expiring matrix’s elements taken over: its scaled copy is made in place, one matrix less at the peak.

Parameters:
  • input – [in] A real symmetric matrix (its lower triangle is read).

  • method – [in] The algorithm.

Throws:
inline symmetric_eigen(const matrix<double> &a, const matrix<double> &b, eigen_method method = eigen_method::divide_and_conquer)#

Diagonalises the pencil A − λ B, A x = λ B x, as scipy.linalg.eigh(a, b): B = L Lᴴ and the symmetric L⁻¹ A L⁻ᴴ diagonalised, its eigenvectors y the pencil’s L⁻ᴴ y, B-orthonormal (Xᵀ B X = I). Each matrix’s lower triangle alone is read.

Parameters:
  • a – [in] A real symmetric matrix.

  • b – [in] A real symmetric positive-definite matrix of its order.

  • method – [in] The algorithm for the standard form.

Throws:
inline const vector<double> &values() const noexcept#

The eigenvalues, ascending.

inline const matrix<double> &vectors() const & noexcept#

The eigenvectors as columns, ordered to match values.

inline matrix<double> vectors() &&#

The eigenvectors, moved out of an expiring decomposition.

class hermitian_eigen#

The eigenvalues and eigenvectors of a complex Hermitian matrix.

The matrix is reduced to a real symmetric tridiagonal by Householder reflections and unit phases (the method of LAPACK’s zheevd), which the divide and conquer of symmetric_eigen diagonalises (implicit QL, zheev’s, on request). The eigenvalues are real and returned in ascending order, with vectors j-th column the eigenvector of values [j] (A = V Λ Vᴴ, V unitary). Only the lower triangle is read and the imaginary part of the diagonal is ignored, as numpy.linalg.eigh reads a matrix by default.

Public Functions

inline explicit hermitian_eigen(const matrix<std::complex<double>> &input, eigen_method method = eigen_method::divide_and_conquer)#

Diagonalises input.

Parameters:
  • input – [in] A complex Hermitian matrix (its lower triangle is read).

  • method – [in] The algorithm for the tridiagonal: eigen_method::divide_and_conquer or eigen_method::tridiagonal_ql.

Throws:
  • argument_error – If method is eigen_method::jacobi, which has no complex form here.

  • dimension_error – If input is not square.

  • non_finite_error – If an entry is infinite or NaN.

  • convergence_error – If an iteration (implicit QL or the secular equation) did not converge within its bound (not observed).

inline hermitian_eigen(const matrix<std::complex<double>> &a, const matrix<std::complex<double>> &b, eigen_method method = eigen_method::divide_and_conquer)#

Diagonalises the pencil A − λ B, A x = λ B x, as scipy.linalg.eigh(a, b): B = L Lᴴ and the Hermitian L⁻¹ A L⁻ᴴ diagonalised, its eigenvectors y the pencil’s L⁻ᴴ y, B-orthonormal (Xᴴ B X = I). Each matrix’s lower triangle alone is read, of the diagonal its real part.

Parameters:
  • a – [in] A complex Hermitian matrix.

  • b – [in] A complex Hermitian positive-definite matrix of its order.

  • method – [in] The algorithm for the tridiagonal, as for one matrix.

Throws:
inline const vector<double> &values() const noexcept#

The eigenvalues, ascending.

inline const matrix<std::complex<double>> &vectors() const & noexcept#

The eigenvectors as columns, ordered to match values.

inline matrix<std::complex<double>> vectors() &&#

The eigenvectors, moved out of an expiring decomposition.

template<double_field T>
class eigen_decomposition#

The eigenvalues, and optionally the right eigenvectors, of a general square matrix, as numpy.linalg.eig.

T is double or std::complex<double>; the eigenvalues and vectors are complex either way (real says whether a real matrix’s are all real). Column j of vectors is the eigenvector of values [j], A V = V Λ, each of unit norm with its component of largest modulus real.

Public Functions

inline explicit eigen_decomposition(const matrix<T> &input, bool vectors = true, bool left = false)#

Decomposes input.

Parameters:
  • input – [in] A square matrix.

  • vectors – [in] Whether to compute the eigenvectors (the eigenvalues alone cost a third as much).

  • left – [in] Whether to compute the left eigenvectors too (left_vectors), from the same Schur form.

Throws:
inline explicit eigen_decomposition(matrix<T> &&input, bool vectors = true, bool left = false)#

Decomposes input in its own storage, an expiring matrix’s elements taken over: its scaled copy is made in place, one matrix less at the peak.

Parameters:
  • input – [in] A square matrix.

  • vectors – [in] Whether to compute the eigenvectors (the eigenvalues alone cost a third as much).

  • left – [in] Whether to compute the left eigenvectors too (left_vectors), from the same Schur form.

Throws:
inline const vector<std::complex<double>> &values() const noexcept#

The eigenvalues, in the order of the Schur form.

inline const matrix<std::complex<double>> &left_vectors() const noexcept#

The left eigenvectors as columns, ordered to match values (empty where they were not computed): column j is u with uᴴ A = λ_j uᴴ, of unit norm with its component of largest modulus real, as dgeev’s VL; from the same Schur form as the right ones, so that each matches its eigenvalue.

inline const matrix<std::complex<double>> &vectors() const & noexcept#

The eigenvectors as columns, ordered to match values (empty where they were not computed).

inline matrix<std::complex<double>> vectors() &&#

The eigenvectors, moved out of an expiring decomposition.

inline bool real() const noexcept#

Whether every eigenvalue is real (a real matrix’s whose Schur form has no 2 × 2 block): its vectors are then real too.

template<double_field T>
class schur_decomposition#

The Schur decomposition A = Z T Zᴴ of a square matrix, as scipy.linalg.schur (LAPACK’s dgees/zgees): Z orthogonal (unitary), T upper quasi-triangular for a real A (a complex pair a 2 × 2 block in standard form, its diagonal equal, its off-diagonal of opposite signs), upper triangular for a complex one; T’s diagonal (and blocks) holds the eigenvalues. Eigenvalues isolated first by permutations (detail::isolate, dgees’s dgebal(‘P)), which keepZorthogonal and leave a triangular or block-triangular part no iteration; no diagonal scaling, which would not. \tparam Tdoubleorstd::complex<double>`.

Public Functions

inline explicit schur_decomposition(const matrix<T> &input)#

Decomposes input.

Throws:
inline explicit schur_decomposition(matrix<T> &&input)#

Decomposes input in its own storage, an expiring matrix’s elements taken over.

template<typename Select>
inline schur_decomposition(const matrix<T> &input, Select select)#

Decomposes input, then moves the eigenvalues for which select holds to the leading block of T (sort), as scipy.linalg.schur(a, sort=...) (LAPACK’s dgees/zgees with a selection).

Throws:
inline std::vector<std::complex<double>> values() const#

The eigenvalues, in T’s order: its diagonal, a real 2 × 2 block a conjugate pair, the positive first.

inline std::size_t reorder(const std::vector<bool> &chosen)#

Moves the eigenvalues whose entries of chosen (one per eigenvalue, in values’s order) are set to the leading block of T, in their order, Z turning with them, as LAPACK’s trsen (MATLAB’s ordschur): a real conjugate pair moves where either of its two is chosen. A = Z T Zᴴ still holds.

Throws:
Returns:

The eigenvalues moved.

inline std::size_t sort(const detail::eigenvalue_selection &select)#

The eigenvalues for which select holds moved to the leading block (reorder), as dgees/zgees sort them:

Throws:

convergence_error – If two blocks were too close to exchange, or (real) the rounding of the exchanges left a selected eigenvalue past one not selected, as dgees’s info n + 1 and n + 2.

Returns:

their count, sdim, a real pair counted twice where either of its two is selected.

inline std::size_t leading() const noexcept#

The eigenvalues the selecting constructor moved to the leading block (its sdim); 0 otherwise.

inline const matrix<T> &t() const & noexcept#

T, upper quasi-triangular (real) or triangular (complex).

inline matrix<T> t() &&#

T, moved out of an expiring decomposition.

inline const matrix<T> &z() const & noexcept#

Z, the Schur vectors as columns.

inline matrix<T> z() &&#

Z, moved out of an expiring decomposition.

class generalized_schur#

The generalized Schur decomposition of a complex pencil A − λ B, A = Q S Zᴴ and B = Q T Zᴴ, as scipy.linalg.qz(a, b, output="complex") (LAPACK’s zgges): Q and Z unitary, S and T upper triangular, T’s diagonal real and non-negative; the generalized eigenvalues α_k / β_k on the diagonals (β_k = 0 an infinite one). Reordered as scipy.linalg.ordqz by sort or reorder. Each operand is first brought into the range [√safmin / ε, ε / √safmin] of its largest magnitude where it lies outside, as zgges scales it, and the form and the eigenvalues taken back.

Public Types

using selection = std::function<bool(const std::complex<double>&, const std::complex<double>&)>#

The selection scipy.linalg.ordqz takes: true for (α, β) to lead.

Public Functions

inline generalized_schur(const matrix<std::complex<double>> &a, const matrix<std::complex<double>> &b)#

Decomposes the pencil of a and b.

Throws:
inline generalized_schur(const matrix<std::complex<double>> &a, const matrix<std::complex<double>> &b, std::size_t steps)#

Decomposes the pencil within steps QZ iterations (zhgeqz’s bound 30 n by default).

inline matrix<std::complex<double>> s() const#

S, upper triangular.

inline matrix<std::complex<double>> t() const#

T, upper triangular, its diagonal real and non-negative.

inline matrix<std::complex<double>> q() const#

Q, unitary: A = Q S Zᴴ.

inline matrix<std::complex<double>> z() const#

Z, unitary.

inline const std::vector<std::pair<std::complex<double>, std::complex<double>>> &values() const noexcept#

The eigenvalues as (α, β), in the diagonals’ order: α = S(k, k), β = T(k, k).

inline std::size_t reorder(const std::vector<bool> &chosen)#

Moves the eigenvalues whose entries of chosen are set to the leading diagonal places, in their order, as LAPACK’s ztgsen (by ztgexc’s exchanges), Q and Z turning with them, T’s diagonal made real and non-negative again.

Throws:
  • dimension_error – If chosen does not hold one entry per eigenvalue.

  • convergence_error – If an exchange is refused (ztgex2’s tests: two eigenvalues too close to separate); the decomposition is then unchanged.

Returns:

The eigenvalues moved.

inline std::size_t sort(const selection &select)#

The eigenvalues select holds moved first (reorder), as scipy.linalg.ordqz(…, sort=…) sorts them.

Returns:

Their count.

class real_generalized_schur#

The generalized real Schur decomposition of a real pencil A − λ B, A = Q S Zᵀ and B = Q T Zᵀ, as scipy.linalg.qz(a, b) (LAPACK’s dgges): Q and Z orthogonal, T upper triangular with a non-negative diagonal, S quasi-triangular, a 2 × 2 diagonal block for each conjugate pair of eigenvalues, T diagonal and positive there; the eigenvalues (αr + i αi) / β (β = 0 an infinite one).

Public Types

using selection = std::function<bool(const std::complex<double>&, const std::complex<double>&)>#

The selection scipy.linalg.ordqz takes: true for (α, β) to lead, α = αr + i αi.

Public Functions

inline real_generalized_schur(const matrix<double> &a, const matrix<double> &b)#

Decomposes the pencil of a and b.

Throws:
inline real_generalized_schur(const matrix<double> &a, const matrix<double> &b, std::size_t steps)#

Decomposes the pencil within steps QZ iterations (dhgeqz’s bound 30 n by default).

inline matrix<double> s() const#

S, quasi-triangular.

inline matrix<double> t() const#

T, upper triangular, its diagonal non-negative.

inline matrix<double> q() const#

Q, orthogonal: A = Q S Zᵀ.

inline matrix<double> z() const#

Z, orthogonal.

inline const std::vector<detail::real_pencil_value> &values() const noexcept#

The eigenvalues as (αr, αi, β), in the diagonal’s order.

inline std::size_t reorder(const std::vector<bool> &chosen)#

Moves the eigenvalues whose entries of chosen are set to the leading diagonal places, in their order, as LAPACK’s dtgsen (by dtgexc’s exchanges of blocks), a conjugate pair moved together where either of its two is chosen; Q and Z turning with them, the eigenvalues recomputed as dtgsen gives them.

Throws:
  • dimension_error – If chosen does not hold one entry per eigenvalue.

  • convergence_error – If an exchange is refused (dtgex2’s tests: two eigenvalues too close to separate); the decomposition is then unchanged.

Returns:

The eigenvalues moved.

inline std::size_t sort(const selection &select)#

The eigenvalues select holds moved first (reorder), as scipy.linalg.ordqz(…, sort=…) sorts them.

Returns:

Their count.

Exceptions#

class dimension_error : public numerical::detail::tagged<std::runtime_error>#

Thrown when an operation’s operands have incompatible shapes.

Public Functions

inline explicit dimension_error(const std::string &message)#

Builds the error.

Parameters:

message – [in] Human-readable cause.

class singular_matrix_error : public numerical::detail::tagged<std::runtime_error>#

Thrown when a matrix has no unique solution (it is singular).

Public Functions

inline explicit singular_matrix_error(const std::string &message)#

Builds the error.

Parameters:

message – [in] Human-readable cause.

class not_positive_definite_error : public numerical::detail::tagged<std::runtime_error>#

Thrown when a Cholesky factorisation finds the matrix not positive-definite.

Public Functions

inline explicit not_positive_definite_error(const std::string &message, std::size_t order = 0)#

Builds the error.

Parameters:
  • message – [in] Human-readable cause.

  • order – [in] As order gives it.

inline std::size_t order() const noexcept#

The order of the first leading minor found not positive definite (LAPACK’s info), 0 where unknown.

class non_finite_error : public numerical::detail::tagged<std::domain_error>#

Thrown when a decomposition’s input holds an infinite or NaN entry: no factorisation of it means anything, and the iterative ones (eigh, SVD) would stop at once and return plausible values.

Public Functions

inline explicit non_finite_error(const std::string &message)#

Builds the error.

Parameters:

message – [in] Human-readable cause.

class convergence_error : public numerical::detail::tagged<std::runtime_error>#

Thrown when an iterative algorithm has not converged within its bound of sweeps.

Public Functions

inline explicit convergence_error(const std::string &message)#

Builds the error.

Parameters:

message – [in] Human-readable cause.

class einsum_error : public numerical::detail::tagged<std::runtime_error>#

Thrown when an einsum specification is malformed or inconsistent.

Public Functions

inline explicit einsum_error(const std::string &message)#

Builds the error.

Parameters:

message – [in] Human-readable cause.