Skip to main content

lib_jsl_linalg_reference/
naive_svd.rs

1//! The singular value decomposition computed the obvious way, from the eigenproblem of `AᵀA`.
2//!
3//! If `A = U Σ Vᵀ` then `AᵀA = V Σ² Vᵀ`, so the right singular vectors are eigenvectors of `AᵀA`,
4//! the singular values are the square roots of its eigenvalues, and `u_i = A v_i / σ_i`. The trouble
5//! is that forming `AᵀA` squares every singular value: those below `√ε σ_max ≈ 10⁻⁸ σ_max` fall
6//! beneath the rounding error of the largest and are lost. Production SVDs work on `A` itself:
7//! Golub-Kahan bidiagonalisation (the default in `lib_jsl_linalg`, as in LAPACK) or one-sided
8//! Jacobi (`lib_jsl_linalg`'s `SvdJacobi`).
9//!
10//! See the book entry [The singular value decomposition](https://jwkunz.github.io/lib_jsl/book/linear_algebra/svd.html#the-decomposition).
11
12use crate::Error;
13use ndarray::{Array1, Array2};
14
15/// The thin SVD of an `m × n` matrix (`m ≥ n`): `U` is `m × n`, `σ` descends, `V` is `n × n`.
16/// Columns of `U` belonging to zero singular values are left zero.
17#[derive(Debug, Clone)]
18pub struct Svd {
19    pub u: Array2<f64>,
20    pub singular_values: Array1<f64>,
21    pub v: Array2<f64>,
22}
23
24// ANCHOR: naive_svd
25/// The SVD via the Jacobi eigenvalue method applied to `AᵀA`.
26pub fn svd_via_normal_matrix(a: &Array2<f64>) -> Result<Svd, Error> {
27    let (m, n) = a.dim();
28    let eigen = crate::jacobi_eigenvalue::jacobi_eigen(&a.t().dot(a), 1e-15)?;
29    // Jacobi orders eigenvalues ascending; singular values are conventionally descending.
30    let order: Vec<usize> = (0..n).rev().collect();
31    let singular_values: Array1<f64> = order.iter().map(|&i| eigen.values[i].max(0.0).sqrt()).collect();
32    let v = Array2::from_shape_fn((n, n), |(i, j)| eigen.vectors[[i, order[j]]]);
33    let av = a.dot(&v);
34    let u = Array2::from_shape_fn((m, n), |(i, j)| {
35        if singular_values[j] > 0.0 { av[[i, j]] / singular_values[j] } else { 0.0 }
36    });
37    Ok(Svd { u, singular_values, v })
38}
39// ANCHOR_END: naive_svd
40
41#[cfg(test)]
42mod tests {
43    use super::*;
44    use lib_jsl_linalg::SVD;
45
46    #[test]
47    fn reconstructs_a_well_conditioned_matrix() {
48        let a = crate::random_matrix(10, 6, 9);
49        let svd = svd_via_normal_matrix(&a).unwrap();
50        let rebuilt = (&svd.u * &svd.singular_values).dot(&svd.v.t());
51        assert!((rebuilt - &a).iter().all(|d| d.abs() < 1e-12));
52        let (_, reference, _) = a.svd(false, false).unwrap();
53        assert!((&svd.singular_values - &reference).iter().all(|d| d.abs() < 1e-12));
54    }
55
56    #[test]
57    fn small_singular_values_are_lost() {
58        let sigma = [1.0, 1e-3, 1e-6, 1e-10];
59        let (u, _) = crate::qr::householder(&crate::random_matrix(8, 4, 10));
60        let (v, _) = crate::qr::householder(&crate::random_matrix(4, 4, 11));
61        let a = (&u * &Array1::from(sigma.to_vec())).dot(&v.t());
62        let naive = svd_via_normal_matrix(&a).unwrap().singular_values;
63        let (_, accurate, _) = a.svd(false, false).unwrap();
64        let relative = |s: &Array1<f64>| (s[3] - sigma[3]).abs() / sigma[3];
65        assert!(relative(&naive) > 1e-2, "naive σ₄ = {:e}", naive[3]);
66        assert!(relative(&accurate) < 1e-4, "production σ₄ = {:e}", accurate[3]);
67    }
68}