Skip to main content

lib_jsl_linalg_reference/
qr.rs

1//! The QR factorisation `A = Q R`: orthonormal columns times an upper triangular matrix.
2//!
3//! **Gram-Schmidt** builds `Q` one column at a time by subtracting from each column of `A` its
4//! projections onto the columns already found. The *classical* form projects the original column;
5//! the *modified* form projects the partially orthogonalised one, which is algebraically identical
6//! but loses orthogonality much more slowly in floating point (roughly `ε κ(A)` instead of
7//! `ε κ(A)²`, where `κ` is the condition number).
8//!
9//! **Householder** QR instead multiplies `A` by reflections `H = I − 2 v vᵀ`, each zeroing the
10//! entries below one diagonal position. Products of reflections are exactly orthogonal, so `Q` is
11//! orthonormal to working precision whatever the conditioning of `A`. This is what production
12//! libraries use.
13//!
14//! All three return the thin factorisation of an `m × n` matrix with `m ≥ n`: `Q` is `m × n` and
15//! `R` is `n × n`.
16//!
17//! See the book entry [QR factorisation](https://jwkunz.github.io/lib_jsl/book/linear_algebra/qr.html).
18
19use ndarray::{Array1, Array2, s};
20
21/// Classical Gram-Schmidt: `r_ij = q_i · a_j` with the *original* column `a_j`.
22pub fn classical_gram_schmidt(a: &Array2<f64>) -> (Array2<f64>, Array2<f64>) {
23    let (m, n) = a.dim();
24    let mut q = Array2::zeros((m, n));
25    let mut r = Array2::zeros((n, n));
26    for j in 0..n {
27        let mut v = a.column(j).to_owned();
28        for i in 0..j {
29            r[[i, j]] = q.column(i).dot(&a.column(j));
30            v.scaled_add(-r[[i, j]], &q.column(i));
31        }
32        r[[j, j]] = v.dot(&v).sqrt();
33        q.column_mut(j).assign(&(v / r[[j, j]]));
34    }
35    (q, r)
36}
37
38// ANCHOR: mgs
39/// Modified Gram-Schmidt: `r_ij = q_i · v` with the column `v` as orthogonalised so far.
40pub fn modified_gram_schmidt(a: &Array2<f64>) -> (Array2<f64>, Array2<f64>) {
41    let (m, n) = a.dim();
42    let mut q = Array2::zeros((m, n));
43    let mut r = Array2::zeros((n, n));
44    for j in 0..n {
45        let mut v = a.column(j).to_owned();
46        for i in 0..j {
47            r[[i, j]] = q.column(i).dot(&v);
48            v.scaled_add(-r[[i, j]], &q.column(i));
49        }
50        r[[j, j]] = v.dot(&v).sqrt();
51        q.column_mut(j).assign(&(v / r[[j, j]]));
52    }
53    (q, r)
54}
55// ANCHOR_END: mgs
56
57// ANCHOR: householder
58/// Householder QR. Reflection `k` maps column `k` (from row `k` down) onto a multiple of `e_1`;
59/// `Q` is then accumulated by applying the reflections to the first `n` columns of the identity.
60pub fn householder(a: &Array2<f64>) -> (Array2<f64>, Array2<f64>) {
61    let (m, n) = a.dim();
62    let mut r = a.clone();
63    let mut reflectors: Vec<Array1<f64>> = Vec::with_capacity(n);
64    for k in 0..n {
65        let mut v = r.slice(s![k.., k]).to_owned();
66        let norm = v.dot(&v).sqrt();
67        // Reflect onto −sign(x₀)‖x‖ e₁ so that v₀ = x₀ + sign(x₀)‖x‖ involves no cancellation.
68        v[0] += if v[0] >= 0.0 { norm } else { -norm };
69        let v_norm = v.dot(&v).sqrt();
70        if v_norm > 0.0 {
71            v /= v_norm;
72        }
73        apply_reflector(&mut r, &v, k);
74        reflectors.push(v);
75    }
76    let mut q = Array2::from_shape_fn((m, n), |(i, j)| if i == j { 1.0 } else { 0.0 });
77    for (k, v) in reflectors.iter().enumerate().rev() {
78        apply_reflector(&mut q, v, k);
79    }
80    let r = Array2::from_shape_fn((n, n), |(i, j)| if j >= i { r[[i, j]] } else { 0.0 });
81    (q, r)
82}
83// ANCHOR_END: householder
84
85/// Overwrites rows `k..` of `x` with `(I − 2 v vᵀ)` applied to them.
86fn apply_reflector(x: &mut Array2<f64>, v: &Array1<f64>, k: usize) {
87    for j in 0..x.ncols() {
88        let d: f64 = v.iter().enumerate().map(|(i, vi)| vi * x[[k + i, j]]).sum();
89        for (i, vi) in v.iter().enumerate() {
90            x[[k + i, j]] -= 2.0 * d * vi;
91        }
92    }
93}
94
95/// `‖QᵀQ − I‖_F`, the loss of orthogonality.
96pub fn orthogonality_error(q: &Array2<f64>) -> f64 {
97    let e = q.t().dot(q) - crate::identity(q.ncols());
98    e.iter().map(|v| v * v).sum::<f64>().sqrt()
99}
100
101#[cfg(test)]
102mod tests {
103    use super::*;
104
105    fn hilbert(n: usize) -> Array2<f64> {
106        Array2::from_shape_fn((n, n), |(i, j)| 1.0 / (i + j + 1) as f64)
107    }
108
109    #[test]
110    fn all_three_factorise_a_well_conditioned_matrix() {
111        let a = crate::random_matrix(9, 6, 4);
112        for (q, r) in [classical_gram_schmidt(&a), modified_gram_schmidt(&a), householder(&a)] {
113            assert!((q.dot(&r) - &a).iter().all(|v| v.abs() < 1e-12));
114            assert!(orthogonality_error(&q) < 1e-12);
115        }
116    }
117
118    #[test]
119    fn orthogonality_degrades_in_the_textbook_order() {
120        // The 10 × 10 Hilbert matrix has condition number ≈ 1.6e13.
121        let a = hilbert(10);
122        let cgs = orthogonality_error(&classical_gram_schmidt(&a).0);
123        let mgs = orthogonality_error(&modified_gram_schmidt(&a).0);
124        let (q, r) = householder(&a);
125        let house = orthogonality_error(&q);
126        assert!(cgs > 1.0, "classical: {cgs:e}");
127        assert!(mgs > 1e-6 && mgs < 1e-1, "modified: {mgs:e}");
128        assert!(house < 1e-14, "Householder: {house:e}");
129        assert!((q.dot(&r) - &a).iter().all(|v| v.abs() < 1e-14));
130    }
131}