Skip to main content

lib_jsl_linalg_reference/
qr_algorithm.rs

1//! The QR algorithm (Francis and Kublanovskaya, 1961) for the eigenvalues of a symmetric matrix.
2//!
3//! Factor `A_k = Q_k R_k`, then multiply in the other order: `A_{k+1} = R_k Q_k = Q_kᵀ A_k Q_k`.
4//! Every iterate is similar to `A`, and the product `Q_1 Q_2 ⋯ Q_k` is exactly what subspace
5//! (orthogonal) iteration on `Aᵏ` would produce, so `A_k` converges to a diagonal matrix of
6//! eigenvalues, ordered by magnitude, with entry `(i, j)` decaying like `|λ_i / λ_j|ᵏ`. Equal
7//! magnitudes (`±λ`) never separate.
8//!
9//! The **shifted** algorithm factors `A_k − μ I` instead and adds `μ I` back. A shift close to an
10//! eigenvalue makes the last row converge in a few steps; that eigenvalue is then **deflated** and
11//! the iteration continues on the leading block. Wilkinson's shift, the eigenvalue of the trailing
12//! 2 × 2 block nearer its corner entry, always converges for symmetric matrices. Production codes
13//! add one more ingredient, a preliminary reduction to tridiagonal (or Hessenberg) form, so that
14//! each step costs `O(n)` (or `O(n²)`) rather than `O(n³)`.
15//!
16//! See the book entry [Eigenvalue algorithms](https://jwkunz.github.io/lib_jsl/book/linear_algebra/eigen-iterations.html#the-qr-algorithm).
17
18use crate::Error;
19use crate::qr::householder;
20use ndarray::{Array1, Array2, s};
21
22/// Eigenvalues in ascending order and the number of QR steps taken.
23#[derive(Debug, Clone)]
24pub struct QrEigenvalues {
25    pub values: Array1<f64>,
26    pub iterations: usize,
27}
28
29fn sorted_diagonal(a: &Array2<f64>) -> Array1<f64> {
30    let mut d = a.diag().to_vec();
31    d.sort_by(f64::total_cmp);
32    Array1::from(d)
33}
34
35fn frobenius(a: &Array2<f64>) -> f64 {
36    a.iter().map(|x| x * x).sum::<f64>().sqrt()
37}
38
39/// Unshifted QR iteration until the off-diagonal norm is below `tolerance × ‖A‖_F`.
40pub fn unshifted_qr(a: &Array2<f64>, tolerance: f64, max_iterations: usize) -> Result<QrEigenvalues, Error> {
41    let scale = frobenius(a);
42    let mut a = a.clone();
43    for iterations in 0..=max_iterations {
44        if crate::off_diagonal_norm(&a) <= tolerance * scale {
45            return Ok(QrEigenvalues { values: sorted_diagonal(&a), iterations });
46        }
47        let (q, r) = householder(&a);
48        a = r.dot(&q);
49    }
50    Err("unshifted QR did not converge")
51}
52
53// ANCHOR: shifted_qr
54/// QR iteration with Wilkinson shifts and deflation.
55pub fn shifted_qr(a: &Array2<f64>, tolerance: f64, max_iterations: usize) -> Result<QrEigenvalues, Error> {
56    let scale = frobenius(a);
57    let mut a = a.clone();
58    let mut m = a.nrows();
59    let mut iterations = 0;
60    while m > 1 {
61        let last_row = a.slice(s![m - 1, ..m - 1]);
62        if last_row.dot(&last_row).sqrt() <= tolerance * scale {
63            m -= 1; // a[m−1, m−1] is an eigenvalue; continue on the leading block.
64            continue;
65        }
66        if iterations == max_iterations {
67            return Err("shifted QR did not converge");
68        }
69        let mu = wilkinson_shift(a[[m - 2, m - 2]], a[[m - 1, m - 2]], a[[m - 1, m - 1]]);
70        let shift = crate::identity(m) * mu;
71        let (q, r) = householder(&(&a.slice(s![..m, ..m]) - &shift));
72        a.slice_mut(s![..m, ..m]).assign(&(r.dot(&q) + shift));
73        iterations += 1;
74    }
75    Ok(QrEigenvalues { values: sorted_diagonal(&a), iterations })
76}
77// ANCHOR_END: shifted_qr
78
79/// The eigenvalue of `[[a, b], [b, c]]` closer to `c`.
80pub fn wilkinson_shift(a: f64, b: f64, c: f64) -> f64 {
81    let d = (a - c) / 2.0;
82    let sign = if d >= 0.0 { 1.0 } else { -1.0 };
83    c - sign * b * b / (d.abs() + (d * d + b * b).sqrt())
84}
85
86#[cfg(test)]
87mod tests {
88    use super::*;
89    use lib_jsl_linalg::{EigValsh, UPLO};
90    use ndarray::array;
91
92    #[test]
93    fn shifts_and_deflation_cut_the_work() {
94        let a = crate::random_symmetric(12, 8);
95        let reference = a.eigvalsh(UPLO::Lower).unwrap();
96        let plain = unshifted_qr(&a, 1e-13, 100_000).unwrap();
97        let shifted = shifted_qr(&a, 1e-15, 1_000).unwrap();
98        assert!((&plain.values - &reference).iter().all(|d| d.abs() < 1e-10));
99        assert!((&shifted.values - &reference).iter().all(|d| d.abs() < 1e-12));
100        assert!(shifted.iterations < 4 * 12, "{} shifted steps", shifted.iterations);
101        assert!(plain.iterations > 10 * shifted.iterations, "{} vs {}", plain.iterations, shifted.iterations);
102    }
103
104    #[test]
105    fn equal_magnitudes_defeat_the_unshifted_algorithm() {
106        // Eigenvalues ±1: R Q reproduces A exactly, forever.
107        let a = array![[0.0, 1.0], [1.0, 0.0]];
108        assert!(unshifted_qr(&a, 1e-12, 1_000).is_err());
109        let shifted = shifted_qr(&a, 1e-15, 10).unwrap();
110        assert!((&shifted.values - &array![-1.0, 1.0]).iter().all(|d| d.abs() < 1e-14), "{shifted:?}");
111    }
112}