Skip to main content

lib_jsl_linalg/sparse/
eigen.rs

1//! A few eigenvalues of a large symmetric operator by the Lanczos process (SciPy's `eigsh`), and a
2//! few singular values by Golub-Kahan bidiagonalisation (SciPy's `svds`), both with full
3//! reorthogonalisation and restarts that enlarge the subspace until the wanted values converge.
4
5use super::direct::{Ordering, SparseLu};
6use super::formats::CsrMatrix;
7use super::iterative::LinearOperator;
8use crate::error::{LinalgError, Result};
9use crate::{Eigh, SVD, UPLO};
10use ndarray::Array2;
11
12/// Which eigenvalues [`eigsh`] returns (SciPy's `which`).
13#[derive(Clone, Copy, Debug, PartialEq, Eq)]
14pub enum Which {
15    /// Largest in magnitude (`'LM'`, SciPy's default).
16    LargestMagnitude,
17    /// Largest algebraic (`'LA'`).
18    LargestAlgebraic,
19    /// Smallest algebraic (`'SA'`).
20    SmallestAlgebraic,
21}
22
23/// Eigenvalues (ascending) and eigenvectors (columns).
24pub type EigenPairs = (Vec<f64>, Array2<f64>);
25
26fn dot(a: &[f64], b: &[f64]) -> f64 {
27    a.iter().zip(b).map(|(x, y)| x * y).sum()
28}
29
30fn norm(a: &[f64]) -> f64 {
31    dot(a, a).sqrt()
32}
33
34/// A deterministic start vector with all components non-zero, orthogonal to `locked`.
35pub(super) fn start_vector(n: usize, locked: &[Vec<f64>]) -> Vec<f64> {
36    let mut v: Vec<f64> = (0..n).map(|i| 1.0 + 0.5 * ((i as f64 * 1.618_033_988_75).fract() - 0.5)).collect();
37    reorthogonalise(&mut v, locked, &[]);
38    let s = norm(&v);
39    v.iter_mut().for_each(|t| *t /= s);
40    v
41}
42
43/// Orthogonalises `w` against the vectors in `locked` and `basis` together, twice (classical
44/// Gram-Schmidt, repeated). Both sets must be in every pass: projecting against one set after the
45/// other puts back components along the first, multiplied by the (large) Lanczos coefficients,
46/// and the error grows geometrically from step to step.
47fn reorthogonalise(w: &mut [f64], locked: &[Vec<f64>], basis: &[Vec<f64>]) {
48    for _ in 0..2 {
49        for q in locked.iter().chain(basis) {
50            let c = dot(w, q);
51            w.iter_mut().zip(q).for_each(|(wi, qi)| *wi -= c * qi);
52        }
53    }
54}
55
56/// How strongly `which` prefers the eigenvalue `theta` (larger is preferred).
57fn preference(which: Which, theta: f64) -> f64 {
58    match which {
59        Which::LargestMagnitude => theta.abs(),
60        Which::LargestAlgebraic => theta,
61        Which::SmallestAlgebraic => -theta,
62    }
63}
64
65/// Repeats `run` in the orthogonal complement of the vectors found so far, keeping the `k` most
66/// preferred, until a run finds nothing that beats them. A single Krylov subspace holds only one
67/// vector of each eigenspace, so a repeated eigenvalue appears once per run: deflation (locking)
68/// finds the other copies.
69fn with_deflation<T: Clone>(k: usize, limit: usize, key: impl Fn(&T) -> f64, locked: impl Fn(&[T]) -> usize, mut run: impl FnMut(&[T]) -> Result<Vec<T>>) -> Result<Vec<T>> {
70    let mut found = run(&[])?;
71    while locked(&found) < limit {
72        let worst = found.iter().map(&key).fold(f64::INFINITY, f64::min);
73        let more: Vec<T> = run(&found)?.into_iter().filter(|p| found.len() < k || key(p) > worst * (1.0 + 1e-12 * worst.signum()) + 1e-300).collect();
74        if more.is_empty() {
75            break;
76        }
77        found.extend(more);
78        found.sort_by(|x, y| key(y).total_cmp(&key(x)));
79        found.truncate(k);
80    }
81    Ok(found)
82}
83
84// ANCHOR: eigsh
85/// `k` eigenvalues and eigenvectors of a symmetric operator (SciPy's `eigsh`). The Lanczos
86/// process builds an orthonormal basis `Q` of the Krylov subspace in which `A` is tridiagonal,
87/// `QᵀAQ = T`; the eigenvalues of `T` (Ritz values) approximate the extreme eigenvalues of `A`,
88/// with residual norms `|β_m s_{m,i}|` known without forming the vectors. Full
89/// reorthogonalisation keeps `Q` orthonormal in floating point; if the wanted Ritz values have not
90/// converged to `tol` relative accuracy, the subspace is doubled.
91pub fn eigsh(a: &dyn LinearOperator, k: usize, which: Which, tol: f64) -> Result<EigenPairs> {
92    let (n, n2) = a.shape();
93    if n != n2 || k == 0 || k > n {
94        return Err(LinalgError::Shape(format!("need a square operator and 1 ≤ k ≤ n, got {n} × {n2}, k = {k}")));
95    }
96    let tol = if tol > 0.0 { tol } else { f64::EPSILON.sqrt() * 1e-2 };
97    let mut pairs = with_deflation(k, n, |p: &(f64, Vec<f64>)| preference(which, p.0), |f| f.len(), |found| {
98        let locked: Vec<Vec<f64>> = found.iter().map(|p| p.1.clone()).collect();
99        lanczos(a, k, which, tol, &locked)
100    })?;
101    pairs.sort_by(|x, y| x.0.total_cmp(&y.0));
102    let values = pairs.iter().map(|p| p.0).collect();
103    let vectors = Array2::from_shape_fn((n, pairs.len()), |(r, c)| pairs[c].1[r]);
104    Ok((values, vectors))
105}
106
107/// One Lanczos run in the orthogonal complement of `locked`: the `k` wanted Ritz pairs, the
108/// subspace doubled until their residuals `|β_m s_{m,i}|` are below `tol` times the largest Ritz
109/// value.
110fn lanczos(a: &dyn LinearOperator, k: usize, which: Which, tol: f64, locked: &[Vec<f64>]) -> Result<Vec<(f64, Vec<f64>)>> {
111    let n = a.shape().0;
112    let room = n - locked.len();
113    if room == 0 {
114        return Ok(Vec::new());
115    }
116    let mut m = (2 * k + 1).max(20).min(room);
117    loop {
118        let mut q = vec![start_vector(n, locked)];
119        let (mut alpha, mut beta) = (Vec::with_capacity(m), Vec::with_capacity(m));
120        let mut last_beta = 0.0;
121        for j in 0..m {
122            let mut w = a.matvec(&q[j]);
123            let aj = dot(&w, &q[j]);
124            alpha.push(aj);
125            reorthogonalise(&mut w, locked, &q);
126            let b = norm(&w);
127            let breakdown = b <= f64::EPSILON * aj.abs().max(1.0);
128            last_beta = if breakdown { 0.0 } else { b };
129            if j + 1 == m || breakdown {
130                break;
131            }
132            beta.push(b);
133            q.push(w.iter().map(|t| t / b).collect());
134        }
135        let size = alpha.len();
136        let t = Array2::from_shape_fn((size, size), |(i, j)| if i == j { alpha[i] } else if i + 1 == j || j + 1 == i { beta[i.min(j)] } else { 0.0 });
137        let (theta, s) = t.eigh(UPLO::Lower)?;
138        let mut idx: Vec<usize> = (0..size).collect();
139        idx.sort_by(|&x, &y| preference(which, theta[y]).total_cmp(&preference(which, theta[x])));
140        let wanted: Vec<usize> = idx.into_iter().take(k).collect();
141        let scale = theta.iter().fold(0.0f64, |acc, v| acc.max(v.abs())).max(f64::MIN_POSITIVE);
142        let converged = wanted.iter().all(|&i| (last_beta * s[(size - 1, i)]).abs() <= tol * scale);
143        if converged || size == room || size < m {
144            return Ok(wanted
145                .iter()
146                .map(|&i| {
147                    let mut v = vec![0.0; n];
148                    for (j, qj) in q.iter().enumerate() {
149                        let c = s[(j, i)];
150                        v.iter_mut().zip(qj).for_each(|(vi, qi)| *vi += c * qi);
151                    }
152                    (theta[i], v)
153                })
154                .collect());
155        }
156        m = (2 * m).min(room);
157    }
158}
159// ANCHOR_END: eigsh
160
161/// `(A − σI)⁻¹` through a sparse LU factorisation, for shift-invert Lanczos.
162pub(super) struct ShiftInvert {
163    pub(super) lu: SparseLu,
164    pub(super) n: usize,
165}
166
167impl LinearOperator for ShiftInvert {
168    fn shape(&self) -> (usize, usize) {
169        (self.n, self.n)
170    }
171    fn matvec(&self, x: &[f64]) -> Vec<f64> {
172        self.lu.solve(x).expect("length checked")
173    }
174    fn rmatvec(&self, x: &[f64]) -> Vec<f64> {
175        self.matvec(x)
176    }
177}
178
179// ANCHOR: shift_invert
180/// The `k` eigenvalues of a symmetric sparse matrix nearest `σ`, with eigenvectors (SciPy's
181/// `eigsh(A, k, sigma=σ)`, shift-invert mode). The eigenvalues `λ` of `A` near `σ` are the
182/// largest in magnitude of `(A − σI)⁻¹`, `θ = 1/(λ − σ)`, which Lanczos finds quickly; each
183/// product with the inverse is one solve with a sparse LU factorisation of `A − σI`.
184pub fn eigsh_shift_invert(a: &CsrMatrix, k: usize, sigma: f64, tol: f64) -> Result<EigenPairs> {
185    let n = a.nrows;
186    if a.ncols != n {
187        return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
188    }
189    let shifted = a.add(1.0, &CsrMatrix::identity(n), -sigma)?;
190    let op = ShiftInvert { lu: SparseLu::factor(&shifted, Ordering::MinimumDegree)?, n };
191    let (theta, vectors) = eigsh(&op, k, Which::LargestMagnitude, tol)?;
192    let mut pairs: Vec<(f64, usize)> = theta.iter().enumerate().map(|(i, &t)| (sigma + 1.0 / t, i)).collect();
193    pairs.sort_by(|x, y| x.0.total_cmp(&y.0));
194    let values = pairs.iter().map(|p| p.0).collect();
195    let vecs = Array2::from_shape_fn((n, pairs.len()), |(r, c)| vectors[(r, pairs[c].1)]);
196    Ok((values, vecs))
197}
198// ANCHOR_END: shift_invert
199
200/// A singular triplet: value, left vector, right vector.
201type Triplet = (f64, Vec<f64>, Vec<f64>);
202
203/// The `k` largest singular values with their left and right singular vectors (columns),
204/// descending (SciPy's `svds`, which returns them ascending). Golub-Kahan bidiagonalisation
205/// `A V = U B` with full reorthogonalisation, the SVD of the small bidiagonal `B`, a doubled
206/// subspace until the residuals are below `tol`, and deflation for repeated singular values.
207pub fn svds(a: &dyn LinearOperator, k: usize, tol: f64) -> Result<(Vec<f64>, Array2<f64>, Array2<f64>)> {
208    let (rows, cols) = a.shape();
209    let p = rows.min(cols);
210    if k == 0 || k > p {
211        return Err(LinalgError::Shape(format!("need 1 ≤ k ≤ min(m, n) = {p}")));
212    }
213    let tol = if tol > 0.0 { tol } else { f64::EPSILON.sqrt() * 1e-2 };
214    let found = with_deflation(k, p, |t: &Triplet| t.0, |f| f.len(), |found| {
215        let lu: Vec<Vec<f64>> = found.iter().map(|t| t.1.clone()).collect();
216        let lv: Vec<Vec<f64>> = found.iter().map(|t| t.2.clone()).collect();
217        bidiagonalise(a, k, tol, &lu, &lv)
218    })?;
219    let left = Array2::from_shape_fn((rows, found.len()), |(r, c)| found[c].1[r]);
220    let right = Array2::from_shape_fn((cols, found.len()), |(r, c)| found[c].2[r]);
221    Ok((found.iter().map(|t| t.0).collect(), left, right))
222}
223
224/// One Golub-Kahan run with `u` kept orthogonal to `lu` and `v` to `lv`.
225fn bidiagonalise(a: &dyn LinearOperator, k: usize, tol: f64, lu: &[Vec<f64>], lv: &[Vec<f64>]) -> Result<Vec<Triplet>> {
226    let (rows, cols) = a.shape();
227    let room = rows.min(cols) - lv.len();
228    if room == 0 {
229        return Ok(Vec::new());
230    }
231    let mut m = (2 * k + 1).max(20).min(room);
232    loop {
233        let mut v = vec![start_vector(cols, lv)];
234        let mut u: Vec<Vec<f64>> = Vec::new();
235        let (mut alpha, mut beta) = (Vec::new(), Vec::new());
236        let mut last_beta = 0.0;
237        for j in 0..m {
238            let mut uj = a.matvec(&v[j]);
239            if j > 0 {
240                let b = beta[j - 1];
241                uj.iter_mut().zip(&u[j - 1]).for_each(|(x, y)| *x -= b * y);
242            }
243            reorthogonalise(&mut uj, lu, &u);
244            let aj = norm(&uj);
245            if aj == 0.0 {
246                break;
247            }
248            alpha.push(aj);
249            u.push(uj.iter().map(|t| t / aj).collect());
250            let mut vj = a.rmatvec(&u[j]);
251            vj.iter_mut().zip(&v[j]).for_each(|(x, y)| *x -= aj * y);
252            reorthogonalise(&mut vj, lv, &v);
253            let bj = norm(&vj);
254            last_beta = bj;
255            if j + 1 == m || bj == 0.0 {
256                break;
257            }
258            beta.push(bj);
259            v.push(vj.iter().map(|t| t / bj).collect());
260        }
261        let size = alpha.len();
262        if size == 0 {
263            return Ok(Vec::new());
264        }
265        let b = Array2::from_shape_fn((size, size), |(i, j)| if i == j { alpha[i] } else if j == i + 1 { beta[i] } else { 0.0 });
266        let (ub, sv, vbt) = b.svd(true, true)?;
267        let (ub, vbt) = (ub.expect("requested"), vbt.expect("requested"));
268        let smax = sv.iter().copied().fold(0.0, f64::max).max(f64::MIN_POSITIVE);
269        let kk = k.min(size);
270        // Residual of the i-th triplet: β_m |last component of the right singular vector of B|.
271        let converged = (0..kk).all(|i| (last_beta * vbt[(i, size - 1)]).abs() <= tol * smax);
272        if converged || size == room || size < m {
273            return Ok((0..kk)
274                .map(|c| {
275                    let left = (0..rows).map(|r| (0..size).map(|j| u[j][r] * ub[(j, c)]).sum()).collect();
276                    let right = (0..cols).map(|r| (0..size).map(|j| v[j][r] * vbt[(c, j)]).sum()).collect();
277                    (sv[c], left, right)
278                })
279                .collect());
280        }
281        m = (2 * m).min(room);
282    }
283}