Skip to main content

lib_jsl_linalg/
subspaces.rs

1//! Pseudoinverses, rank, orthonormal bases of the range and null space, matrix norms and condition
2//! numbers, all from the singular value decomposition (SciPy's `pinv`, `null_space`, `orth`;
3//! NumPy's `matrix_rank`, `norm` and `cond`).
4//!
5//! See the book entry [Matrix functions, subspaces and norms](https://jwkunz.github.io/lib_jsl/book/linear_algebra/subspaces-norms.html).
6
7use crate::error::{LinalgError, Result};
8use crate::scalar::Scalar;
9use crate::SVD;
10use ndarray::{Array1, Array2, ArrayBase, Data, Ix2, s};
11
12fn svd_full<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>) -> Result<(Array2<T>, Array1<f64>, Array2<T>)> {
13    let (u, sv, vt) = a.svd(true, true)?;
14    Ok((u.expect("requested"), sv, vt.expect("requested")))
15}
16
17fn rank_of(sv: &Array1<f64>, rtol: f64) -> usize {
18    let smax = sv.iter().copied().fold(0.0, f64::max);
19    sv.iter().filter(|&&s| s > rtol * smax).count()
20}
21
22// ANCHOR: pinv
23/// The Moore-Penrose pseudoinverse `A⁺ = V Σ⁺ Uᴴ` (SciPy's `pinv`): singular values at most
24/// `rtol · σ_max` are treated as zero, with `rtol = max(m, n) ε` by default.
25pub fn pinv<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, rtol: Option<f64>) -> Result<Array2<T>> {
26    let (m, n) = a.dim();
27    let (u, sv, vt) = svd_full(a)?;
28    let rtol = rtol.unwrap_or(m.max(n) as f64 * f64::EPSILON);
29    let r = rank_of(&sv, rtol);
30    let mut out = Array2::<T>::from_elem((n, m), T::zero());
31    for k in 0..r {
32        let inv = 1.0 / sv[k];
33        for i in 0..n {
34            let vik = vt[(k, i)].conj().scale(inv);
35            for j in 0..m {
36                out[(i, j)] += vik * u[(j, k)].conj();
37            }
38        }
39    }
40    Ok(out)
41}
42// ANCHOR_END: pinv
43
44/// The numerical rank: the number of singular values above `tol` (NumPy's default
45/// `σ_max · max(m, n) · ε` when `None`).
46pub fn matrix_rank<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, tol: Option<f64>) -> Result<usize> {
47    let (_, sv, _) = a.svd(false, false)?;
48    let (m, n) = a.dim();
49    let smax = sv.iter().copied().fold(0.0, f64::max);
50    let tol = tol.unwrap_or(smax * m.max(n) as f64 * f64::EPSILON);
51    Ok(sv.iter().filter(|&&s| s > tol).count())
52}
53
54/// An orthonormal basis of the null space of `A`, as columns (SciPy's `null_space`): the right
55/// singular vectors of the singular values at most `rcond · σ_max` (default `max(m, n) ε`).
56pub fn null_space<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, rcond: Option<f64>) -> Result<Array2<T>> {
57    let (m, n) = a.dim();
58    let (_, sv, vt) = svd_full(a)?;
59    let r = rank_of(&sv, rcond.unwrap_or(m.max(n) as f64 * f64::EPSILON));
60    Ok(vt.slice(s![r.., ..]).t().mapv(|v| v.conj()))
61}
62
63/// An orthonormal basis of the range (column space) of `A`, as columns (SciPy's `orth`).
64pub fn orth<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, rcond: Option<f64>) -> Result<Array2<T>> {
65    let (m, n) = a.dim();
66    let (u, sv, _) = svd_full(a)?;
67    let r = rank_of(&sv, rcond.unwrap_or(m.max(n) as f64 * f64::EPSILON));
68    Ok(u.slice(s![.., ..r]).to_owned())
69}
70
71/// Which matrix norm [`norm`] computes (NumPy's `ord`).
72#[derive(Clone, Copy, Debug, PartialEq, Eq)]
73pub enum Norm {
74    /// `√Σ|aᵢⱼ|²`.
75    Frobenius,
76    /// The sum of the singular values.
77    Nuclear,
78    /// The largest column sum of absolute values.
79    One,
80    /// The smallest column sum.
81    MinusOne,
82    /// The largest singular value.
83    Two,
84    /// The smallest singular value.
85    MinusTwo,
86    /// The largest row sum.
87    Infinity,
88    /// The smallest row sum.
89    MinusInfinity,
90}
91
92// ANCHOR: norm
93/// A matrix norm (or, for the `Minus` variants, the corresponding minimum), as NumPy's `norm`.
94pub fn norm<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, ord: Norm) -> Result<f64> {
95    let (m, n) = a.dim();
96    if m == 0 || n == 0 {
97        return Err(LinalgError::Shape("empty matrix".into()));
98    }
99    let col_sums = || (0..n).map(|j| (0..m).map(|i| a[(i, j)].abs()).sum::<f64>());
100    let row_sums = || (0..m).map(|i| (0..n).map(|j| a[(i, j)].abs()).sum::<f64>());
101    Ok(match ord {
102        Norm::Frobenius => a.iter().map(|v| v.abs_sqr()).sum::<f64>().sqrt(),
103        Norm::One => col_sums().fold(0.0, f64::max),
104        Norm::MinusOne => col_sums().fold(f64::INFINITY, f64::min),
105        Norm::Infinity => row_sums().fold(0.0, f64::max),
106        Norm::MinusInfinity => row_sums().fold(f64::INFINITY, f64::min),
107        Norm::Two | Norm::MinusTwo | Norm::Nuclear => {
108            let (_, sv, _) = a.svd(false, false)?;
109            match ord {
110                Norm::Two => sv.iter().copied().fold(0.0, f64::max),
111                Norm::MinusTwo => sv.iter().copied().fold(f64::INFINITY, f64::min),
112                _ => sv.sum(),
113            }
114        }
115    })
116}
117// ANCHOR_END: norm
118
119/// The condition number `‖A‖ ‖A⁻¹‖` in the given norm (NumPy's `cond`); for the 2-norm,
120/// `σ_max / σ_min`, which is also defined for rectangular matrices. Infinite for singular
121/// matrices.
122pub fn cond<T: Scalar, S: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, ord: Norm) -> Result<f64> {
123    match ord {
124        Norm::Two | Norm::MinusTwo => {
125            let (_, sv, _) = a.svd(false, false)?;
126            let (big, small) = (sv.iter().copied().fold(0.0, f64::max), sv.iter().copied().fold(f64::INFINITY, f64::min));
127            Ok(if ord == Norm::Two { big / small } else { small / big })
128        }
129        _ => {
130            let inv = match crate::Inverse::inv(a) {
131                Ok(i) => i,
132                Err(LinalgError::Singular(_)) => return Ok(f64::INFINITY),
133                Err(e) => return Err(e),
134            };
135            Ok(norm(a, ord)? * norm(&inv, ord)?)
136        }
137    }
138}
139
140#[cfg(test)]
141mod tests {
142    use super::*;
143    use ndarray::array;
144
145    #[test]
146    fn pinv_and_null_space_of_a_rank_two_matrix() {
147        let a = array![[1.0, 2.0, 3.0], [2.0, 4.0, 6.0], [1.0, 0.0, 1.0], [0.0, 1.0, 1.0]];
148        assert_eq!(matrix_rank(&a, None).unwrap(), 2);
149        let p = pinv(&a, None).unwrap();
150        // Penrose conditions: A A⁺ A = A and A⁺ A A⁺ = A⁺.
151        let apa = a.dot(&p).dot(&a);
152        assert!(apa.iter().zip(a.iter()).all(|(x, y)| (x - y).abs() < 1e-12));
153        let ns = null_space(&a, None).unwrap();
154        assert_eq!(ns.ncols(), 1);
155        assert!(a.dot(&ns).iter().all(|v| v.abs() < 1e-12));
156        assert_eq!(orth(&a, None).unwrap().ncols(), 2);
157        let id = array![[2.0, 0.0], [0.0, 0.5]];
158        assert!((cond(&id, Norm::Two).unwrap() - 4.0).abs() < 1e-14);
159        assert!((cond(&id, Norm::One).unwrap() - 4.0).abs() < 1e-14);
160        assert!((norm(&id, Norm::Nuclear).unwrap() - 2.5).abs() < 1e-14);
161    }
162}