Skip to main content

lib_jsl_linalg_reference/
power_iteration.rs

1//! Power iteration and its two refinements, for one eigenpair of a symmetric matrix.
2//!
3//! Multiplying a vector repeatedly by `A` amplifies its component along the eigenvector of the
4//! largest-magnitude eigenvalue, at the rate `|λ₂ / λ₁|` per step. **Inverse iteration** applies
5//! the same idea to `(A − σI)⁻¹`, whose dominant eigenvalue `1 / (λ − σ)` belongs to the eigenvalue
6//! nearest the shift `σ`; the closer the shift, the faster the convergence. **Rayleigh quotient
7//! iteration** updates the shift to the current estimate `σ = vᵀAv` at every step, which converges
8//! cubically for symmetric matrices, at the price of a new factorisation per step.
9//!
10//! See the book entry [Eigenvalue algorithms](https://jwkunz.github.io/lib_jsl/book/linear_algebra/eigen-iterations.html#power-iteration-inverse-iteration-and-the-rayleigh-quotient).
11
12use crate::Error;
13use ndarray::{Array1, Array2};
14
15/// An eigenvalue estimate, its unit eigenvector and the iterations taken.
16#[derive(Debug, Clone)]
17pub struct EigenEstimate {
18    pub value: f64,
19    pub vector: Array1<f64>,
20    pub iterations: usize,
21}
22
23/// Iterates `v ← f(v) / ‖f(v)‖` until the eigen-residual `‖A v − (vᵀAv) v‖` is below `tolerance`.
24fn iterate(
25    a: &Array2<f64>,
26    start: &Array1<f64>,
27    tolerance: f64,
28    max_iterations: usize,
29    mut step: impl FnMut(&Array1<f64>, f64) -> Result<Option<Array1<f64>>, Error>,
30) -> Result<EigenEstimate, Error> {
31    let mut v = start / start.dot(start).sqrt();
32    let mut value = v.dot(&a.dot(&v));
33    for iterations in 1..=max_iterations {
34        let Some(w) = step(&v, value)? else {
35            // The shifted matrix is exactly singular: the shift is an eigenvalue.
36            return Ok(EigenEstimate { value, vector: v, iterations });
37        };
38        v = &w / w.dot(&w).sqrt();
39        let av = a.dot(&v);
40        value = v.dot(&av);
41        let residual = &av - &(&v * value);
42        if residual.dot(&residual).sqrt() < tolerance {
43            return Ok(EigenEstimate { value, vector: v, iterations });
44        }
45    }
46    Err("the iteration did not converge")
47}
48
49/// Power iteration: `v ← A v`. Converges to the eigenvalue of largest magnitude.
50pub fn power_iteration(a: &Array2<f64>, start: &Array1<f64>, tolerance: f64, max_iterations: usize) -> Result<EigenEstimate, Error> {
51    iterate(a, start, tolerance, max_iterations, |v, _| Ok(Some(a.dot(v))))
52}
53
54/// Inverse iteration with a fixed shift: `v ← (A − σI)⁻¹ v`, factorising once.
55pub fn inverse_iteration(
56    a: &Array2<f64>,
57    shift: f64,
58    start: &Array1<f64>,
59    tolerance: f64,
60    max_iterations: usize,
61) -> Result<EigenEstimate, Error> {
62    let factors = crate::lu::lu(&(a - &(crate::identity(a.nrows()) * shift)))?;
63    iterate(a, start, tolerance, max_iterations, |v, _| factors.solve(v).map(Some))
64}
65
66// ANCHOR: rqi
67/// Rayleigh quotient iteration: `v ← (A − σ_k I)⁻¹ v` with `σ_k = vᵀAv`, refactorising each step.
68pub fn rayleigh_quotient_iteration(
69    a: &Array2<f64>,
70    start: &Array1<f64>,
71    tolerance: f64,
72    max_iterations: usize,
73) -> Result<EigenEstimate, Error> {
74    let n = a.nrows();
75    iterate(a, start, tolerance, max_iterations, |v, shift| {
76        match crate::lu::lu(&(a - &(crate::identity(n) * shift))) {
77            Ok(factors) => factors.solve(v).map(Some),
78            Err(_) => Ok(None),
79        }
80    })
81}
82// ANCHOR_END: rqi
83
84#[cfg(test)]
85mod tests {
86    use super::*;
87
88    /// `Q diag(1, 2, …, n) Qᵀ` with a random orthogonal `Q`.
89    fn known_spectrum(n: usize) -> Array2<f64> {
90        let (q, _) = crate::qr::householder(&crate::random_matrix(n, n, 5));
91        let d = Array2::from_shape_fn((n, n), |(i, j)| if i == j { (i + 1) as f64 } else { 0.0 });
92        q.dot(&d).dot(&q.t())
93    }
94
95    #[test]
96    fn shifts_buy_speed() {
97        let a = known_spectrum(10);
98        let start = Array1::from_iter(crate::random_matrix(10, 1, 6).iter().copied());
99        let power = power_iteration(&a, &start, 1e-10, 10_000).unwrap();
100        let inverse = inverse_iteration(&a, 3.2, &start, 1e-10, 10_000).unwrap();
101        let rayleigh = rayleigh_quotient_iteration(&a, &inverse_iteration(&a, 3.2, &start, 1e-1, 100).unwrap().vector, 1e-10, 100).unwrap();
102        assert!((power.value - 10.0).abs() < 1e-9);
103        assert!((inverse.value - 3.0).abs() < 1e-9);
104        assert!((rayleigh.value - 3.0).abs() < 1e-9);
105        // Linear rate 0.9 versus 0.25 versus cubic.
106        assert!(power.iterations > 100, "{}", power.iterations);
107        assert!(inverse.iterations < 30, "{}", inverse.iterations);
108        assert!(rayleigh.iterations <= 3, "{}", rayleigh.iterations);
109    }
110}