Skip to main content

lib_jsl_linalg/
mod.rs

1//! Dense linear algebra in pure Rust for real (`f64`) and complex (`Complex<f64>`) matrices.
2//!
3//! | Operation | Trait | Algorithm |
4//! |---|---|---|
5//! | Solve `A x = b`, inverse, determinant | [`Solve`], [`Inverse`], [`Factorize`], [`Determinant`] | LU with partial pivoting |
6//! | Hermitian positive-definite factorisation | [`Cholesky`] | Cholesky `A = L Lᴴ` |
7//! | Triangular systems | [`SolveTriangular`] | Forward and back substitution |
8//! | Hermitian / symmetric eigenproblem | [`Eigh`], [`EigValsh`] | Householder tridiagonalisation and implicit QL |
9//! | General eigenproblem | [`Eig`], [`EigVals`] | Hessenberg reduction and shifted QR (complex Schur form) |
10//! | Singular value decomposition | [`SVD`], [`SvdJacobi`] | Golub-Kahan bidiagonalisation; one-sided Jacobi for high relative accuracy |
11//! | Least squares, minimum-norm for rank-deficient systems | [`LeastSquaresSvd`] | Householder QR with column pivoting; SVD when rank-deficient |
12//! | Complex Schur form | [`schur_complex`] | Hessenberg reduction and shifted QR |
13//! | QR (optionally pivoted), RQ, Hessenberg, real Schur, `LDLᵀ`, polar | [`qr`], [`rq`], [`hessenberg`], [`schur_real`], [`ldl`], [`polar`] | Householder reflectors as LAPACK's; Bunch-Kaufman pivoting |
14//! | Generalised eigenproblems `A x = λ B x` | [`eigh_generalized`], [`eig_generalized`], [`qz`] | Cholesky reduction; the QZ algorithm |
15//! | Structured matrices and their solvers | [`toeplitz`], [`circulant`], [`solve_toeplitz`], [`solve_circulant`], [`solve_banded`], [`solveh_banded`], … | Levinson recursion; FFT; band LU and Cholesky |
16//! | General matrix functions, principal angles | [`funm`], [`subspace_angles`] | Schur-Parlett; SVDs of orthonormal bases |
17//! | Matrix exponential | [`expm`] | Scaling and squaring with Padé approximants |
18//! | Square root, logarithm, fractional powers | [`sqrtm`], [`logm`], [`fractional_matrix_power`] | Schur method; inverse scaling and squaring |
19//! | Pseudoinverse, rank, null space, range, norms, condition | [`pinv`], [`matrix_rank`], [`null_space`], [`orth`], [`norm`], [`cond`] | From the SVD |
20//! | Sparse matrices: storage, sparse LU, Krylov solvers, a few eigenvalues and singular values | [`sparse`] | CSR/CSC; Gilbert-Peierls LU with reverse Cuthill-McKee; CG, MINRES, GMRES, LGMRES, BiCGSTAB, LSQR; Lanczos `eigsh`, `svds`; Krylov-Schur `eigs` |
21//! | Sylvester and Lyapunov equations | [`solve_sylvester`], [`solve_continuous_lyapunov`], [`solve_discrete_lyapunov`] | Bartels-Stewart on the complex Schur form |
22//! | Algebraic Riccati equations | [`solve_continuous_are`], [`solve_discrete_are`] | Matrix sign function; structure-preserving doubling; Newton refinement |
23//!
24//! The traits follow the names and signatures of the `ndarray-linalg` crate, so code written
25//! against it ports by changing the import. They are implemented for every ndarray
26//! `ArrayBase<S, Ix2>` (owned arrays and views). Everything is written for clarity and moderate
27//! sizes (up to a few hundred rows); for large problems an optimised LAPACK will be faster. The
28//! benchmarks in `crates/linalg_bench` compare the two.
29//!
30//! See the book chapter [Dense linear algebra](https://jwkunz.github.io/lib_jsl/book/linear_algebra/index.html).
31
32// Matrix algorithms read most clearly with explicit row and column indices.
33#![allow(clippy::needless_range_loop)]
34
35mod cholesky;
36mod dense;
37mod eig;
38mod eigh;
39mod equations;
40mod error;
41mod factorizations;
42mod generalized;
43mod structured;
44mod logsqrt;
45mod lu;
46mod matfun;
47mod qr;
48mod reflectors;
49mod scalar;
50pub mod sparse;
51mod reorder;
52mod subspaces;
53mod svd;
54
55pub use structured::{ConvolutionMode, DftScale, PascalKind, block_diag, circulant, companion, convolution_matrix, dft, fiedler, hadamard, hankel, hilbert, invhilbert, invpascal, leslie, pascal, solve_banded, solve_circulant, solve_toeplitz, solveh_banded, toeplitz};
56pub use reorder::{EigenSort, OrdQz, OrdQzComplex, RealQzFactors, ordqz, ordqz_complex, qz_real, schur_sorted, schur_sorted_complex};
57pub use generalized::{GeneralizedEigen, QzFactors, eig_generalized, eigh_generalized, qz};
58pub use factorizations::{LdlFactors, QrFactors, QrMode, funm, hessenberg, ldl, polar, qr, rq, schur_real, subspace_angles};
59pub use error::{Diag, LinalgError, Result, UPLO};
60pub use equations::{solve_continuous_are, solve_continuous_lyapunov, solve_discrete_are, solve_discrete_lyapunov, solve_sylvester};
61pub use lu::LuFactorization;
62pub use logsqrt::{fractional_matrix_power, logm, sqrtm};
63pub use matfun::expm;
64pub use subspaces::{Norm, cond, matrix_rank, norm, null_space, orth, pinv};
65pub use scalar::Scalar;
66
67use dense::{Mat, require_square, to_array1, vector};
68use ndarray::{Array1, Array2, ArrayBase, Data, Ix1, Ix2};
69use num_complex::Complex;
70
71/// The complex Schur form `A = Z T Zᴴ`: `T` upper triangular with the eigenvalues of `A` on its
72/// diagonal, `Z` unitary (SciPy's `linalg.schur(a, output='complex')`). Returns `(T, Z)`.
73pub fn schur_complex<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>) -> Result<ComplexSchur> {
74    let (t, z) = eig::schur_unbalanced(&Mat::from_array(a)?)?;
75    Ok((t.into_array(), z.into_array()))
76}
77
78/// Solves `A x = b` for square `A` by LU with partial pivoting.
79pub trait Solve<T> {
80    fn solve<S: Data<Elem = T>>(&self, b: &ArrayBase<S, Ix1>) -> Result<Array1<T>>;
81    /// As [`Solve::solve`], consuming the right-hand side.
82    fn solve_into(&self, b: Array1<T>) -> Result<Array1<T>> {
83        self.solve(&b)
84    }
85    /// Solves `Aᵀ x = b` (transpose, without conjugation).
86    fn solve_t<S: Data<Elem = T>>(&self, b: &ArrayBase<S, Ix1>) -> Result<Array1<T>>;
87    /// As [`Solve::solve_t`], consuming the right-hand side.
88    fn solve_t_into(&self, b: Array1<T>) -> Result<Array1<T>> {
89        self.solve_t(&b)
90    }
91    /// Solves `Aᴴ x = b` (conjugate transpose).
92    fn solve_h<S: Data<Elem = T>>(&self, b: &ArrayBase<S, Ix1>) -> Result<Array1<T>>;
93    /// As [`Solve::solve_h`], consuming the right-hand side.
94    fn solve_h_into(&self, b: Array1<T>) -> Result<Array1<T>> {
95        self.solve_h(&b)
96    }
97}
98
99/// The inverse of a square matrix.
100pub trait Inverse<T> {
101    fn inv(&self) -> Result<Array2<T>>;
102}
103
104/// The determinant of a square matrix.
105pub trait Determinant<T> {
106    fn det(&self) -> Result<T>;
107}
108
109/// An LU factorisation to solve many systems with the same matrix.
110pub trait Factorize<T> {
111    fn factorize(&self) -> Result<LuFactorization<T>>;
112}
113
114/// The Cholesky factor of a Hermitian positive-definite matrix whose `uplo` triangle is read:
115/// lower `L` with `A = L Lᴴ` for [`UPLO::Lower`], upper `U = Lᴴ` for [`UPLO::Upper`].
116pub trait Cholesky<T> {
117    fn cholesky(&self, uplo: UPLO) -> Result<Array2<T>>;
118}
119
120/// Solves `T X = B` for a triangular `T` (only the `uplo` triangle is read) and a right-hand side
121/// that is a vector or a matrix.
122pub trait SolveTriangular<T, Rhs> {
123    type Output;
124    fn solve_triangular(&self, uplo: UPLO, diag: Diag, b: &Rhs) -> Result<Self::Output>;
125}
126
127/// Eigenvalues (ascending) and orthonormal eigenvectors (columns) of a Hermitian matrix whose
128/// `uplo` triangle is read.
129pub trait Eigh<T> {
130    fn eigh(&self, uplo: UPLO) -> Result<(Array1<f64>, Array2<T>)>;
131}
132
133/// Eigenvalues (ascending) of a Hermitian matrix.
134pub trait EigValsh {
135    fn eigvalsh(&self, uplo: UPLO) -> Result<Array1<f64>>;
136}
137
138/// A complex Schur form `(T, Z)` with `A = Z T Zᴴ`.
139pub type ComplexSchur = (Array2<Complex<f64>>, Array2<Complex<f64>>);
140
141/// Complex eigenvalues and eigenvectors (as columns).
142pub type ComplexEigen = (Array1<Complex<f64>>, Array2<Complex<f64>>);
143
144/// Eigenvalues and unit eigenvectors (columns) of a general square matrix, both complex.
145pub trait Eig {
146    fn eig(&self) -> Result<ComplexEigen>;
147}
148
149/// Eigenvalues of a general square matrix.
150pub trait EigVals {
151    fn eigvals(&self) -> Result<Array1<Complex<f64>>>;
152}
153
154/// The singular value decomposition `A = U Σ Vᴴ`: `(U, σ, Vᴴ)` with the full square unitary
155/// factors when requested and the `min(m, n)` singular values in descending order.
156#[allow(clippy::upper_case_acronyms)]
157pub trait SVD<T> {
158    #[allow(clippy::type_complexity)]
159    fn svd(&self, calc_u: bool, calc_vt: bool) -> Result<(Option<Array2<T>>, Array1<f64>, Option<Array2<T>>)>;
160}
161
162/// The SVD by the one-sided Jacobi method, with the same output as [`SVD::svd`]. It is slower than
163/// the default (Golub-Kahan) method but determines small singular values to high *relative*
164/// accuracy, which matters for graded or badly scaled matrices.
165pub trait SvdJacobi<T> {
166    #[allow(clippy::type_complexity)]
167    fn svd_jacobi(&self, calc_u: bool, calc_vt: bool) -> Result<(Option<Array2<T>>, Array1<f64>, Option<Array2<T>>)>;
168}
169
170/// The result of [`LeastSquaresSvd::least_squares`].
171#[derive(Debug, Clone)]
172#[non_exhaustive]
173pub struct LeastSquaresResult<T> {
174    /// The minimum-norm minimiser of `‖A x − b‖₂`.
175    pub solution: Array1<T>,
176    pub singular_values: Array1<f64>,
177    /// The numerical rank (singular values above `max(m, n) · ε · σ_max`).
178    pub rank: usize,
179    /// `‖A x − b‖²` when the system is overdetermined and of full rank.
180    pub residual_sum_of_squares: Option<f64>,
181}
182
183/// The minimum-norm least-squares solution of `A x ≈ b`, robust to rank deficiency.
184///
185/// Overdetermined systems are first factorised by Householder QR with column pivoting; when that
186/// shows full column rank, the solution follows by back-substitution and the singular values from
187/// the eigenvalues of `RᴴR`. Rank-deficient and underdetermined systems use the SVD, which gives
188/// the minimum-norm solution.
189pub trait LeastSquaresSvd<T> {
190    fn least_squares<S: Data<Elem = T>>(&self, b: &ArrayBase<S, Ix1>) -> Result<LeastSquaresResult<T>>;
191}
192
193impl<T: Scalar, S: Data<Elem = T>> Solve<T> for ArrayBase<S, Ix2> {
194    fn solve<S2: Data<Elem = T>>(&self, b: &ArrayBase<S2, Ix1>) -> Result<Array1<T>> {
195        let lu = self.factorize()?;
196        lu.solve(b)
197    }
198    fn solve_t<S2: Data<Elem = T>>(&self, b: &ArrayBase<S2, Ix1>) -> Result<Array1<T>> {
199        self.t().solve(b)
200    }
201    fn solve_h<S2: Data<Elem = T>>(&self, b: &ArrayBase<S2, Ix1>) -> Result<Array1<T>> {
202        self.t().mapv(|v| v.conj()).solve(b)
203    }
204}
205
206impl<T: Scalar> LuFactorization<T> {
207    /// Solves `A x = b` with the stored factorisation.
208    pub fn solve<S: Data<Elem = T>>(&self, b: &ArrayBase<S, Ix1>) -> Result<Array1<T>> {
209        if b.len() != self.dimension() {
210            return Err(LinalgError::Shape(format!("matrix of order {} and vector of length {}", self.dimension(), b.len())));
211        }
212        Ok(to_array1(self.solve_vec(&vector(b)?)))
213    }
214
215    /// The inverse of the factorised matrix.
216    pub fn inv(&self) -> Array2<T> {
217        self.inverse().into_array()
218    }
219}
220
221impl<T: Scalar, S: Data<Elem = T>> Factorize<T> for ArrayBase<S, Ix2> {
222    fn factorize(&self) -> Result<LuFactorization<T>> {
223        LuFactorization::new(Mat::from_array(self)?)
224    }
225}
226
227impl<T: Scalar, S: Data<Elem = T>> Inverse<T> for ArrayBase<S, Ix2> {
228    fn inv(&self) -> Result<Array2<T>> {
229        Ok(self.factorize()?.inv())
230    }
231}
232
233impl<T: Scalar, S: Data<Elem = T>> Determinant<T> for ArrayBase<S, Ix2> {
234    fn det(&self) -> Result<T> {
235        require_square(self.nrows(), self.ncols())?;
236        match self.factorize() {
237            Ok(lu) => Ok(lu.determinant()),
238            Err(LinalgError::Singular(_)) => Ok(T::zero()),
239            Err(e) => Err(e),
240        }
241    }
242}
243
244impl<T: Scalar, S: Data<Elem = T>> Cholesky<T> for ArrayBase<S, Ix2> {
245    fn cholesky(&self, uplo: UPLO) -> Result<Array2<T>> {
246        let l = cholesky::cholesky_lower(&Mat::from_array(self)?, uplo)?;
247        Ok(match uplo {
248            UPLO::Lower => l.into_array(),
249            UPLO::Upper => l.adjoint().into_array(),
250        })
251    }
252}
253
254impl<T: Scalar, S: Data<Elem = T>, S2: Data<Elem = T>> SolveTriangular<T, ArrayBase<S2, Ix2>> for ArrayBase<S, Ix2> {
255    type Output = Array2<T>;
256    fn solve_triangular(&self, uplo: UPLO, diag: Diag, b: &ArrayBase<S2, Ix2>) -> Result<Array2<T>> {
257        Ok(cholesky::solve_triangular(&Mat::from_array(self)?, uplo, diag, &Mat::from_array(b)?)?.into_array())
258    }
259}
260
261impl<T: Scalar, S: Data<Elem = T>, S2: Data<Elem = T>> SolveTriangular<T, ArrayBase<S2, Ix1>> for ArrayBase<S, Ix2> {
262    type Output = Array1<T>;
263    fn solve_triangular(&self, uplo: UPLO, diag: Diag, b: &ArrayBase<S2, Ix1>) -> Result<Array1<T>> {
264        let rhs = Mat { rows: b.len(), cols: 1, data: vector(b)? };
265        Ok(to_array1(cholesky::solve_triangular(&Mat::from_array(self)?, uplo, diag, &rhs)?.data))
266    }
267}
268
269impl<T: Scalar, S: Data<Elem = T>> Eigh<T> for ArrayBase<S, Ix2> {
270    fn eigh(&self, uplo: UPLO) -> Result<(Array1<f64>, Array2<T>)> {
271        let (values, vectors) = eigh::eigh(&Mat::from_array(self)?, uplo)?;
272        Ok((Array1::from_vec(values), vectors.into_array()))
273    }
274}
275
276impl<T: Scalar, S: Data<Elem = T>> EigValsh for ArrayBase<S, Ix2> {
277    fn eigvalsh(&self, uplo: UPLO) -> Result<Array1<f64>> {
278        Ok(Array1::from_vec(eigh::eigvalsh(&Mat::from_array(self)?, uplo)?))
279    }
280}
281
282impl<T: Scalar, S: Data<Elem = T>> Eig for ArrayBase<S, Ix2> {
283    fn eig(&self) -> Result<ComplexEigen> {
284        let (values, vectors) = eig::eig(&Mat::from_array(self)?)?;
285        Ok((Array1::from_vec(values), vectors.into_array()))
286    }
287}
288
289impl<T: Scalar, S: Data<Elem = T>> EigVals for ArrayBase<S, Ix2> {
290    fn eigvals(&self) -> Result<Array1<Complex<f64>>> {
291        Ok(Array1::from_vec(eig::eigvals(&Mat::from_array(self)?)?))
292    }
293}
294
295impl<T: Scalar, S: Data<Elem = T>> SVD<T> for ArrayBase<S, Ix2> {
296    fn svd(&self, calc_u: bool, calc_vt: bool) -> Result<(Option<Array2<T>>, Array1<f64>, Option<Array2<T>>)> {
297        let a = Mat::from_array(self)?;
298        if !calc_u && !calc_vt {
299            return Ok((None, Array1::from_vec(svd::singular_values(&a)?), None));
300        }
301        Ok(full_factors(svd::thin_svd(&a)?, calc_u, calc_vt))
302    }
303}
304
305impl<T: Scalar, S: Data<Elem = T>> SvdJacobi<T> for ArrayBase<S, Ix2> {
306    fn svd_jacobi(&self, calc_u: bool, calc_vt: bool) -> Result<(Option<Array2<T>>, Array1<f64>, Option<Array2<T>>)> {
307        Ok(full_factors(svd::thin_svd_jacobi(&Mat::from_array(self)?)?, calc_u, calc_vt))
308    }
309}
310
311/// Completes a thin SVD to square `U` and `Vᴴ` as requested.
312#[allow(clippy::type_complexity)]
313fn full_factors<T: Scalar>(thin: svd::ThinSvd<T>, calc_u: bool, calc_vt: bool) -> (Option<Array2<T>>, Array1<f64>, Option<Array2<T>>) {
314    let u = calc_u.then(|| svd::complete_square(&thin.u).into_array());
315    let vt = calc_vt.then(|| svd::complete_square(&thin.v).adjoint().into_array());
316    (u, Array1::from_vec(thin.sigma), vt)
317}
318
319impl<T: Scalar, S: Data<Elem = T>> LeastSquaresSvd<T> for ArrayBase<S, Ix2> {
320    fn least_squares<S2: Data<Elem = T>>(&self, b: &ArrayBase<S2, Ix1>) -> Result<LeastSquaresResult<T>> {
321        let (m, n) = self.dim();
322        if b.len() != m {
323            return Err(LinalgError::Shape(format!("matrix {m} × {n} and right-hand side of length {}", b.len())));
324        }
325        let a = Mat::from_array(self)?;
326        let rhs = vector(b)?;
327        // ANCHOR: least_squares
328        if m >= n && n > 0 {
329            let qr = qr::householder_pivoted(&a);
330            let mut qtb = rhs.clone();
331            qr.apply_adjoint(&mut qtb);
332            let r00 = qr.r.at(0, 0).abs();
333            let tolerance = r00 * f64::EPSILON * m.max(n) as f64;
334            if r00 > 0.0 && (0..n).all(|i| qr.r.at(i, i).abs() > tolerance * 1e3) {
335                // Full column rank: back-substitute R z = (Qᴴ b)[..n], then undo the pivoting.
336                let mut z = qtb[..n].to_vec();
337                for i in (0..n).rev() {
338                    let s = (i + 1..n).fold(T::zero(), |s, k| s + qr.r.at(i, k) * z[k]);
339                    z[i] = (z[i] - s) / qr.r.at(i, i);
340                }
341                let mut x = vec![T::zero(); n];
342                for (j, &p) in qr.permutation.iter().enumerate() {
343                    x[p] = z[j];
344                }
345                // The singular values of A are those of R. (Taking them as the square roots of
346                // eig(RᴴR) squared the condition number: σ = 1e-10 next to σ = 1 came out 3.5e-9.)
347                let singular_values = Array1::from_vec(svd::singular_values(&qr.upper())?);
348                let residual = (m > n).then(|| qtb[n..].iter().map(|v| v.abs_sqr()).sum::<f64>());
349                return Ok(LeastSquaresResult { solution: to_array1(x), singular_values, rank: n, residual_sum_of_squares: residual });
350            }
351        }
352        let thin = svd::thin_svd(&a)?;
353        let threshold = thin.sigma.first().copied().unwrap_or(0.0) * f64::EPSILON * m.max(n) as f64;
354        let rank = thin.sigma.iter().filter(|&&s| s > threshold).count();
355        // x = V Σ⁺ Uᴴ b over the numerically non-zero singular values.
356        let mut x = vec![T::zero(); n];
357        for j in 0..rank {
358            let coefficient = (0..m).fold(T::zero(), |s, i| s + thin.u.at(i, j).conj() * rhs[i]).scale(1.0 / thin.sigma[j]);
359            for (i, xi) in x.iter_mut().enumerate() {
360                *xi += thin.v.at(i, j) * coefficient;
361            }
362        }
363        let residual_sum_of_squares = (m > n && rank == n).then(|| {
364            (0..m).map(|i| (rhs[i] - (0..n).fold(T::zero(), |s, j| s + a.at(i, j) * x[j])).abs_sqr()).sum::<f64>()
365        });
366        Ok(LeastSquaresResult { solution: to_array1(x), singular_values: Array1::from_vec(thin.sigma), rank, residual_sum_of_squares })
367        // ANCHOR_END: least_squares
368    }
369}
370
371#[cfg(test)]
372mod tests;