Skip to main content

lib_jsl_linalg_reference/
jacobi_eigenvalue.rs

1//! The Jacobi eigenvalue method for symmetric matrices (Jacobi, 1846).
2//!
3//! A plane rotation `J` in the `(p, q)` plane can be chosen so that `Jᵀ A J` has a zero in position
4//! `(p, q)`. Later rotations fill that zero in again, but the sum of squares of the off-diagonal
5//! entries falls by `2 a_pq²` every time, so sweeping over all pairs repeatedly drives `A` to a
6//! diagonal matrix of eigenvalues; the product of the rotations holds the eigenvectors. The cyclic
7//! method converges quadratically once the off-diagonal part is small. It is slower than
8//! tridiagonalisation followed by QL (what `lib_jsl_linalg` does) but simple, highly accurate, and
9//! the basis of the one-sided Jacobi SVD.
10//!
11//! See the book entry [Eigenvalue algorithms](https://jwkunz.github.io/lib_jsl/book/linear_algebra/eigen-iterations.html#the-jacobi-method).
12
13use crate::Error;
14use ndarray::{Array1, Array2};
15
16/// Eigenvalues in ascending order, eigenvectors as columns, and the number of sweeps.
17#[derive(Debug, Clone)]
18pub struct JacobiEigen {
19    pub values: Array1<f64>,
20    pub vectors: Array2<f64>,
21    pub sweeps: usize,
22}
23
24// ANCHOR: jacobi
25/// Cyclic Jacobi: sweeps over all pairs `p < q` until the off-diagonal norm is below
26/// `tolerance × ‖A‖_F`.
27pub fn jacobi_eigen(a: &Array2<f64>, tolerance: f64) -> Result<JacobiEigen, Error> {
28    let n = a.nrows();
29    let mut a = a.clone();
30    let mut v = crate::identity(n);
31    let scale = a.iter().map(|x| x * x).sum::<f64>().sqrt();
32    let mut sweeps = 0;
33    while crate::off_diagonal_norm(&a) > tolerance * scale {
34        if sweeps == 100 {
35            return Err("the Jacobi method did not converge");
36        }
37        for p in 0..n {
38            for q in p + 1..n {
39                if a[[p, q]] == 0.0 {
40                    continue;
41                }
42                // tan θ is the smaller root of t² + 2 t cot 2θ − 1 = 0, keeping |θ| ≤ π/4.
43                let cot = (a[[q, q]] - a[[p, p]]) / (2.0 * a[[p, q]]);
44                let t = cot.signum() / (cot.abs() + (cot * cot + 1.0).sqrt());
45                let c = 1.0 / (t * t + 1.0).sqrt();
46                let s = t * c;
47                rotate_columns(&mut a, p, q, c, s);
48                rotate_rows(&mut a, p, q, c, s);
49                rotate_columns(&mut v, p, q, c, s);
50            }
51        }
52        sweeps += 1;
53    }
54    let mut order: Vec<usize> = (0..n).collect();
55    order.sort_by(|&i, &j| a[[i, i]].total_cmp(&a[[j, j]]));
56    Ok(JacobiEigen {
57        values: order.iter().map(|&i| a[[i, i]]).collect(),
58        vectors: Array2::from_shape_fn((n, n), |(i, j)| v[[i, order[j]]]),
59        sweeps,
60    })
61}
62// ANCHOR_END: jacobi
63
64/// `X ← X J` for the rotation with `J_pp = J_qq = c`, `J_pq = s`, `J_qp = −s`.
65fn rotate_columns(x: &mut Array2<f64>, p: usize, q: usize, c: f64, s: f64) {
66    for k in 0..x.nrows() {
67        let (xp, xq) = (x[[k, p]], x[[k, q]]);
68        x[[k, p]] = c * xp - s * xq;
69        x[[k, q]] = s * xp + c * xq;
70    }
71}
72
73/// `X ← Jᵀ X`.
74fn rotate_rows(x: &mut Array2<f64>, p: usize, q: usize, c: f64, s: f64) {
75    for k in 0..x.ncols() {
76        let (xp, xq) = (x[[p, k]], x[[q, k]]);
77        x[[p, k]] = c * xp - s * xq;
78        x[[q, k]] = s * xp + c * xq;
79    }
80}
81
82#[cfg(test)]
83mod tests {
84    use super::*;
85    use lib_jsl_linalg::{EigValsh, UPLO};
86
87    #[test]
88    fn matches_the_production_eigensolver() {
89        let a = crate::random_symmetric(20, 7);
90        let e = jacobi_eigen(&a, 1e-15).unwrap();
91        let reference = a.eigvalsh(UPLO::Lower).unwrap();
92        assert!((&e.values - &reference).iter().all(|d| d.abs() < 1e-12));
93        let residual = a.dot(&e.vectors) - &e.vectors * &e.values;
94        assert!(residual.iter().all(|r| r.abs() < 1e-12));
95        assert!(e.sweeps < 12, "quadratic convergence: {} sweeps", e.sweeps);
96    }
97}