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
Twith 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*colselements, row-major (moved in).
- Throws:
dimension_error – If
elements.size()is notrows*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*colselements, row-major.
- Throws:
dimension_error – If
elements.size()is notrows*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*colselements, 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.
-
template<typename T>
class vector# A dense vector of
Twith 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.
-
template<typename T>
class tensor# A dense N-dimensional tensor of
Twith 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 notprod(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 notprod(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
shapeholds another number of elements.
-
inline tensor transposed(const std::vector<std::size_t> &axes) const#
This tensor with its axes in the order
axes(axiskof the result is axisaxes[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
axesis 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]fori < counts[a]along each axisa, 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 whosekeepis 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
lengthelements 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
lengthelements 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).
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
ais not square.
-
inline explicit lu_decomposition(matrix<T> &&a)#
Factorises
ain 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
ais not square.
-
inline vector<T> solve(const vector<T> &b) const#
Solves
A x = busing the stored factors.- Parameters:
b – [in] The right-hand side.
- Throws:
dimension_error – If
b’s size differs from the matrix.singular_matrix_error – If the matrix is singular.
- 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.slogdetgives 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 (
+1or−1for 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 rowistays zero past columniin the forward pass, so that pass reads only the triangle it fills (a third of the products of a full one, as LAPACK’sdgetrispares them); thenU⁻¹on it, andPas 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 freshn × nmapped and faulted in where it holds that much already. pivoted_inverse, thenPapplied 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, instorage(its elements discarded): columnpivots()[i]ofA⁻¹is its columni, 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)⁻¹, instorage.
-
inline matrix<T> solve(const matrix<T> &b) const#
Solves
A X = Bfor every column ofbat 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:
dimension_error – If
b’s row count differs from the matrix.singular_matrix_error – If the matrix is singular.
- 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 ofB.- Parameters:
b – [in] The right-hand sides (
n × k), taken over.- Throws:
dimension_error – If
b’s row count differs from the matrix.singular_matrix_error – If the matrix is singular.
- Returns:
X(n × k), inb’s storage.
-
inline matrix<T> factors() const &#
LandUin one matrix, as LAPACK’sdgetrfleaves them:Uon and above the diagonal,Lbelow it (its unit diagonal not stored), of the rows in their pivoted order.
-
inline const std::vector<std::size_t> &pivots() const noexcept#
The row permutation: row
iofP A = L Uis rowpivots()[i]ofA.
-
inline bool singular() const noexcept#
Whether a pivot was zero:
Uis 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’sgecon:‖A⁻¹‖₁estimated from the factors (Hager’s method, a few solves ofn²each), so within a small factor of the exact; the caller gives‖A‖₁, the largest column sum of moduli ofA, 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.Lis lower-triangular with a real, positive diagonal. Only the lower triangle ofais read, soais 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:
dimension_error – If
ais not square.non_finite_error – If an entry of its lower triangle is infinite or NaN.
not_positive_definite_error – If
ais not positive-definite.
-
inline explicit cholesky_decomposition(matrix<T> &&a)#
Factorises
ain 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:
dimension_error – If
ais not square.non_finite_error – If an entry of its lower triangle is infinite or NaN.
not_positive_definite_error – If
ais not positive-definite.
-
inline vector<T> solve(const vector<T> &b) const#
Solves
A x = bviaL y = bthenLᴴ 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 = Bfor every column ofbat once:L Y = B, thenLᴴ 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’spocon:‖A⁻¹‖₁estimated fromL(Hager’s method, a few solves ofn²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 ofA.- Returns:
The estimate: 1 for an empty matrix; 0 for a zero
one_normor 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) orA = L D Lᵀ(symmetric), Bunch and Kaufman’s diagonal pivoting (LAPACK’ssytrf,hetrf: by panels of 64 columns from order 384, their trailing update one matrix product; the unblockedsytf2,hetf2below it and for the last columns) on the lower triangle, or on the upper one (lower = false,Lthen upper triangular);Dblock diagonal with blocks of order 1 and 2;Lwith a unit diagonal once its rows are permuted (permutation), as SciPy returns them.- Template Parameters:
T –
doubleorstd::complex<double>.
Public Functions
-
inline explicit ldl_decomposition(const matrix<T> &a, bool lower = true, bool hermitian = true)#
Factorises
a, of which only the trianglelowernames 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) orA = Aᵀ; a real one’s either.
- Throws:
dimension_error – If
ais not square.non_finite_error – If an entry is infinite or NaN.
-
inline const matrix<T> &factor() const noexcept#
L, permuted (SciPy’slu):L[permutation()]is triangular with a unit diagonal.
-
template<field T>
class qr_decomposition# A QR factorisation
A = Q Rof anm × nmatrix, as NumPy’sqr, reduced by default.With
k = min(m, n),Qism × kwith orthonormal columns (Qᴴ Q = I) andRisk × nupper trapezoidal (triangular whenm ≥ n) with a real, non-negative diagonal; complete (qr_mode::complete),Qism × mandRm × n, its rows pastkzero. Computed by Householder reflections, soQstays orthonormal to rounding however ill-conditionedAis, and a rank-deficientAfactorises too (with zeros onR’s diagonal). solve returns the least-squares solution ofA x ≈ bfor a full-column-rankA(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 (
Qm × k) or qr_mode::complete (Qm × 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
ain 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 (
Qm × k) or qr_mode::complete (Qm × 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), orm × mcomplete.
-
inline matrix<T> r() const &#
The upper-trapezoidal factor
R:k × n,k = min(m, n), orm × ncomplete.
-
inline vector<T> solve(const vector<T> &b) const#
The least-squares solution of
A x ≈ b(x = R⁻¹ Qᴴ b) for a full-rankA.- Parameters:
b – [in] The right-hand side (size
m).- Throws:
dimension_error – If
b’s size differs from the row count, orAis wide (m < n: its system is underdetermined, and numerical::lstsq gives its minimum-norm solution).singular_matrix_error – If
Ais rank-deficient: a diagonal entry ofRis under detail::rank_tolerance (numerical::lstsq solves such a system).
- Returns:
The solution
x(sizen).
-
inline matrix<T> solve(const matrix<T> &b) const#
The least-squares solutions of
A X ≈ B(X = R⁻¹ Qᴴ B) for a full-rankA, every column ofbat once:Qᴴ Bthrough the matrix product kernel, then the back substitution by rows ofRover 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:
dimension_error – If
b’s row count differs from the matrix’s, orAis wide (as solve).singular_matrix_error – If
Ais rank-deficient (as solve).
- Returns:
X(n × k).
-
template<double_field T>
class pivoted_qr_decomposition# A QR factorisation with column pivoting
A P = Q Rof anm × nmatrix, asscipy.linalg.qr(a, pivoting=True)(LAPACK’sgeqp3): at each step the column of largest remaining norm moved first, soR’s diagonal does not grow in modulus down the diagonal and revealsA’s numerical rank; the norms downdated as LAPACK’slaqp2downdates them, recomputed where the downdate has lost too much (√ε). Householder reflectors aslarfgforms 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:Qm × kandRk × n(k = min(m, n)), orQm × mandRm × n(modecomplete).- Throws:
non_finite_error – If an entry is infinite or NaN.
-
inline const matrix<T> &r() const noexcept#
R, upper trapezoidal, its diagonal real, non-negative and not increasing:k × n, orm × n.
-
inline const std::vector<std::size_t> &permutation() const noexcept#
The column permutation: column
jofA Pis columnpermutation()[j]ofA, as SciPy’sP.
-
inline explicit pivoted_qr_decomposition(const matrix<T> &a, qr_mode mode = qr_mode::reduced)#
-
template<field T>
class svd_decomposition# The singular value decomposition
A = U Σ Vᴴof anm × nmatrix.With
k = min(m, n): theksingular values, descending;U(m × k) andV(n × k) with orthonormal columns, also whereAis rank-deficient. Computed after a Householder QR ofA(ofAᴴwhenm < n): by defaultRis reduced to bidiagonal form and the bidiagonal decomposed by divide and conquer (svd_method::divide_and_conquer), the method of LAPACK’sdgesdd, 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 onR(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 isVᴴ, the third factor NumPy’ssvdreturns. Full (fulltrue, NumPy’sfull_matrices=True),Uism × mandVn × n: the columns pastkare an orthonormal basis of the complement, the rest of the complete HouseholderQof the larger side.- Template Parameters:
T – The scalar element type (
doubleorstd::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
UandVare square (m × m,n × n), as NumPy’sfull_matrices=True.
- Throws:
non_finite_error – If an entry is infinite or NaN.
convergence_error – If the iteration does not converge within its bound (not observed).
-
inline explicit svd_decomposition(matrix<T> &&a, svd_method method = svd_method::divide_and_conquer, bool full = false)#
Decomposes
ain 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
UandVare square (m × m,n × n), as NumPy’sfull_matrices=True.
- Throws:
non_finite_error – If an entry is infinite or NaN.
convergence_error – If the iteration does not converge within its bound (not observed).
-
inline const matrix<T> &u() const & noexcept#
The left singular vectors
U(columns):m × k, orm × mfull.
-
inline matrix<T> u() &&#
U, moved out of an expiring decomposition (v and the singular values stay).
-
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 vectorsj-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, asnumpy.linalg.eighreads 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:
dimension_error – If
inputis not square.convergence_error – If the method did not converge within its bound.
-
inline explicit symmetric_eigen(matrix<double> &&input, eigen_method method = eigen_method::divide_and_conquer)#
Diagonalises
inputin 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:
dimension_error – If
inputis not square.convergence_error – If the method did not converge within its bound.
-
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, asscipy.linalg.eigh(a, b):B = L Lᴴand the symmetricL⁻¹ A L⁻ᴴdiagonalised, its eigenvectorsythe pencil’sL⁻ᴴ 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:
dimension_error – If
aorbis not square, or their orders differ.non_finite_error – If an entry read is infinite or NaN.
not_positive_definite_error – If
bis not positive definite.convergence_error – If the method did not converge within its bound.
-
inline explicit symmetric_eigen(const matrix<double> &input, eigen_method method = eigen_method::divide_and_conquer)#
-
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 vectorsj-th column the eigenvector of values[j](A = V Λ Vᴴ,Vunitary). Only the lower triangle is read and the imaginary part of the diagonal is ignored, asnumpy.linalg.eighreads 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
methodis eigen_method::jacobi, which has no complex form here.dimension_error – If
inputis 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, asscipy.linalg.eigh(a, b):B = L Lᴴand the HermitianL⁻¹ A L⁻ᴴdiagonalised, its eigenvectorsythe pencil’sL⁻ᴴ 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:
argument_error – If
methodis eigen_method::jacobi.dimension_error – If
aorbis not square, or their orders differ.non_finite_error – If an entry read is infinite or NaN.
not_positive_definite_error – If
bis not positive definite.convergence_error – If an iteration did not converge within its bound (not observed).
-
inline explicit hermitian_eigen(const matrix<std::complex<double>> &input, eigen_method method = eigen_method::divide_and_conquer)#
-
template<double_field T>
class eigen_decomposition# The eigenvalues, and optionally the right eigenvectors, of a general square matrix, as
numpy.linalg.eig.Tisdoubleorstd::complex<double>; the eigenvalues and vectors are complex either way (real says whether a real matrix’s are all real). Columnjof 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:
dimension_error – If
inputis not square.non_finite_error – If an entry is infinite or NaN.
convergence_error – If the QR iterations did not converge.
-
inline explicit eigen_decomposition(matrix<T> &&input, bool vectors = true, bool left = false)#
Decomposes
inputin 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:
dimension_error – If
inputis not square.non_finite_error – If an entry is infinite or NaN.
convergence_error – If the QR iterations did not converge.
-
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
jisuwithuᴴ A = λ_j uᴴ, of unit norm with its component of largest modulus real, asdgeev’sVL; 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.
-
inline explicit eigen_decomposition(const matrix<T> &input, bool vectors = true, bool left = false)#
-
template<double_field T>
class schur_decomposition# The Schur decomposition
A = Z T Zᴴof a square matrix, asscipy.linalg.schur(LAPACK’sdgees/zgees):Zorthogonal (unitary),Tupper quasi-triangular for a realA(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:
dimension_error – If
inputis not square.non_finite_error – If an entry is infinite or NaN.
convergence_error – If the QR iterations did not converge.
-
inline explicit schur_decomposition(matrix<T> &&input)#
Decomposes
inputin 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 whichselectholds to the leading block ofT(sort), asscipy.linalg.schur(a, sort=...)(LAPACK’sdgees/zgeeswith a selection).- Throws:
dimension_error – If
inputis not square.non_finite_error – If an entry is infinite or NaN.
convergence_error – If the QR iterations did not converge, or as sort.
-
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 ofT, in their order,Zturning with them, as LAPACK’strsen(MATLAB’sordschur): a real conjugate pair moves where either of its two is chosen.A = Z T Zᴴstill holds.- Throws:
dimension_error – If
chosendoes not hold one entry per eigenvalue.convergence_error – If two blocks were too close to exchange.
- Returns:
The eigenvalues moved.
-
inline std::size_t sort(const detail::eigenvalue_selection &select)#
The eigenvalues for which
selectholds moved to the leading block (reorder), asdgees/zgeessort 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’sinfon + 1andn + 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 explicit schur_decomposition(const matrix<T> &input)#
-
class generalized_schur#
The generalized Schur decomposition of a complex pencil
A − λ B,A = Q S ZᴴandB = Q T Zᴴ, asscipy.linalg.qz(a, b, output="complex")(LAPACK’szgges):QandZunitary,SandTupper triangular,T’s diagonal real and non-negative; the generalized eigenvaluesα_k / β_kon the diagonals (β_k = 0an infinite one). Reordered asscipy.linalg.ordqzby sort or reorder. Each operand is first brought into the range[√safmin / ε, ε / √safmin]of its largest magnitude where it lies outside, aszggesscales 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.ordqztakes: 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
aandb.- Throws:
dimension_error – If
aorbis not square or their orders differ.non_finite_error – If an entry is infinite or NaN.
convergence_error – If the QZ iterations did not converge.
-
inline generalized_schur(const matrix<std::complex<double>> &a, const matrix<std::complex<double>> &b, std::size_t steps)#
Decomposes the pencil within
stepsQZ iterations (zhgeqz’s bound30 nby default).
-
inline matrix<std::complex<double>> t() const#
T, upper triangular, its diagonal real and non-negative.
-
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
chosenare set to the leading diagonal places, in their order, as LAPACK’sztgsen(byztgexc’s exchanges),QandZturning with them,T’s diagonal made real and non-negative again.- Throws:
dimension_error – If
chosendoes 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.
-
using selection = std::function<bool(const std::complex<double>&, const std::complex<double>&)>#
-
class real_generalized_schur#
The generalized real Schur decomposition of a real pencil
A − λ B,A = Q S ZᵀandB = Q T Zᵀ, asscipy.linalg.qz(a, b)(LAPACK’sdgges):QandZorthogonal,Tupper triangular with a non-negative diagonal,Squasi-triangular, a 2 × 2 diagonal block for each conjugate pair of eigenvalues,Tdiagonal and positive there; the eigenvalues(αr + i αi) / β(β = 0an infinite one).Public Types
-
using selection = std::function<bool(const std::complex<double>&, const std::complex<double>&)>#
The selection
scipy.linalg.ordqztakes: 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
aandb.- Throws:
dimension_error – If
aorbis not square or their orders differ.non_finite_error – If an entry is infinite or NaN.
convergence_error – If the QZ iterations did not converge.
-
inline real_generalized_schur(const matrix<double> &a, const matrix<double> &b, std::size_t steps)#
Decomposes the pencil within
stepsQZ iterations (dhgeqz’s bound30 nby default).
-
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
chosenare set to the leading diagonal places, in their order, as LAPACK’sdtgsen(bydtgexc’s exchanges of blocks), a conjugate pair moved together where either of its two is chosen;QandZturning with them, the eigenvalues recomputed asdtgsengives them.- Throws:
dimension_error – If
chosendoes 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.
-
using selection = std::function<bool(const std::complex<double>&, const std::complex<double>&)>#
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.
-
inline explicit dimension_error(const std::string &message)#
-
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.
-
inline explicit singular_matrix_error(const std::string &message)#
-
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.
-
inline explicit not_positive_definite_error(const std::string &message, std::size_t order = 0)#
-
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.
-
inline explicit non_finite_error(const std::string &message)#
-
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.
-
inline explicit convergence_error(const std::string &message)#