Skip to main content

lib_jsl_linalg/sparse/
arnoldi.rs

1//! A few eigenvalues of a large nonsymmetric operator (SciPy's `eigs`), by the Arnoldi process
2//! with Krylov-Schur restarts: the wanted part of the Ritz subspace is kept, in a real orthonormal
3//! basis, and the rest discarded, until the wanted Ritz pairs converge.
4
5use super::direct::{Ordering, SparseLu};
6use super::eigen::{ShiftInvert, start_vector};
7use super::formats::CsrMatrix;
8use super::iterative::LinearOperator;
9use crate::error::{LinalgError, Result};
10use crate::{SVD, schur_complex};
11use ndarray::{Array2, s};
12use num_complex::Complex;
13
14type C = Complex<f64>;
15
16/// Which eigenvalues [`eigs`] returns (SciPy's `which`).
17#[derive(Clone, Copy, Debug, PartialEq, Eq)]
18#[non_exhaustive]
19pub enum EigsWhich {
20    /// Largest magnitude `|λ|` (`'LM'`, SciPy's default).
21    LargestMagnitude,
22    /// Smallest magnitude (`'SM'`); [`eigs_shift_invert`] with `σ = 0` is usually far faster.
23    SmallestMagnitude,
24    /// Largest real part (`'LR'`).
25    LargestReal,
26    /// Smallest real part (`'SR'`).
27    SmallestReal,
28    /// Largest imaginary part in magnitude, `|Im λ|` (`'LI'`; for a real matrix the eigenvalues
29    /// come in conjugate pairs, and ARPACK compares `|Im λ|`).
30    LargestImaginary,
31    /// Smallest `|Im λ|` (`'SI'`).
32    SmallestImaginary,
33}
34
35/// Options for [`eigs`] (SciPy's keyword arguments).
36#[derive(Clone, Debug, Default)]
37pub struct EigsOptions {
38    /// The largest dimension of the Krylov subspace (`ncv`); default `max(2k + 1, 30)`, at most `n`
39    /// (SciPy's is `max(2k + 1, 20)`; the larger space costs fewer products in the book's tests).
40    pub ncv: Option<usize>,
41    /// Relative accuracy of the Ritz residuals; 0 (the default) means machine precision, taken
42    /// as 8ε, the level at which the residual estimates of converged pairs settle.
43    pub tol: f64,
44    /// The most restarts (`maxiter`); default `10 n`.
45    pub max_restarts: Option<usize>,
46    /// The start vector; default a fixed vector with all components non-zero.
47    pub v0: Option<Vec<f64>>,
48}
49
50/// The result of [`eigs`].
51#[derive(Clone, Debug)]
52#[non_exhaustive]
53pub struct EigsResult {
54    /// The eigenvalues, most wanted first; a real eigenvalue has a zero imaginary part.
55    pub values: Vec<C>,
56    /// Unit eigenvectors (columns), each scaled so that its largest component is real and
57    /// positive, which makes the vectors of a conjugate pair conjugates and real eigenvalues'
58    /// vectors real.
59    pub vectors: Array2<C>,
60    /// Whether all `k` pairs met the tolerance.
61    pub converged: bool,
62    /// How many of the `k` pairs met it.
63    pub nconv: usize,
64    /// Restarts made.
65    pub restarts: usize,
66    /// Products with the operator.
67    pub matvecs: usize,
68}
69
70/// How strongly `which` prefers `z` (larger is preferred).
71fn preference(which: EigsWhich, z: C) -> f64 {
72    match which {
73        EigsWhich::LargestMagnitude => z.norm(),
74        EigsWhich::SmallestMagnitude => -z.norm(),
75        EigsWhich::LargestReal => z.re,
76        EigsWhich::SmallestReal => -z.re,
77        EigsWhich::LargestImaginary => z.im.abs(),
78        EigsWhich::SmallestImaginary => -z.im.abs(),
79    }
80}
81
82fn dot(a: &[f64], b: &[f64]) -> f64 {
83    a.iter().zip(b).map(|(x, y)| x * y).sum()
84}
85
86/// `[c s; −s̄ c] [f; g] = [r; 0]` with real `c` (LAPACK's `zlartg`).
87fn rotation(f: C, g: C) -> (f64, C) {
88    if g == C::new(0.0, 0.0) {
89        return (1.0, C::new(0.0, 0.0));
90    }
91    if f == C::new(0.0, 0.0) {
92        return (0.0, g.conj() / g.norm());
93    }
94    let r = f.norm().hypot(g.norm());
95    (f.norm() / r, f / f.norm() * g.conj() / r)
96}
97
98// ANCHOR: swap
99/// Swaps the adjacent diagonal entries `k`, `k + 1` of the upper triangular `T` in
100/// `H = Z T Zᴴ` by a plane rotation (LAPACK's `ztrexc`): the rotation that maps the eigenvector
101/// `(t₁₂, t₂₂ − t₁₁)` of the 2 × 2 block onto the first axis makes the second eigenvalue lead.
102fn swap(t: &mut Array2<C>, z: &mut Array2<C>, k: usize) {
103    let m = t.nrows();
104    let (t11, t22) = (t[(k, k)], t[(k + 1, k + 1)]);
105    let (c, s) = rotation(t[(k, k + 1)], t22 - t11);
106    for j in k + 2..m {
107        let (x, y) = (t[(k, j)], t[(k + 1, j)]);
108        t[(k, j)] = x * c + s * y;
109        t[(k + 1, j)] = y * c - s.conj() * x;
110    }
111    for i in 0..k {
112        let (x, y) = (t[(i, k)], t[(i, k + 1)]);
113        t[(i, k)] = x * c + s.conj() * y;
114        t[(i, k + 1)] = y * c - s * x;
115    }
116    t[(k, k)] = t22;
117    t[(k + 1, k + 1)] = t11;
118    for i in 0..m {
119        let (x, y) = (z[(i, k)], z[(i, k + 1)]);
120        z[(i, k)] = x * c + s.conj() * y;
121        z[(i, k + 1)] = y * c - s * x;
122    }
123}
124// ANCHOR_END: swap
125
126/// Reorders the Schur form so that the eigenvalues come in order of preference, a conjugate pair
127/// (whose two values a real matrix always has) kept together. Returns the group of each position:
128/// equal numbers mark the two halves of a pair.
129fn reorder(t: &mut Array2<C>, z: &mut Array2<C>, which: EigsWhich) -> Vec<usize> {
130    let m = t.nrows();
131    let vals: Vec<C> = (0..m).map(|i| t[(i, i)]).collect();
132    let scale = vals.iter().fold(0.0f64, |acc, v| acc.max(v.norm())).max(f64::MIN_POSITIVE);
133    let small = 1e3 * f64::EPSILON * scale;
134    // Pair each value having positive imaginary part with the nearest conjugate.
135    let mut group = vec![usize::MAX; m];
136    let mut groups: Vec<Vec<usize>> = Vec::new();
137    for i in 0..m {
138        if group[i] != usize::MAX {
139            continue;
140        }
141        group[i] = groups.len();
142        let mut members = vec![i];
143        if vals[i].im.abs() > small {
144            let partner = (0..m)
145                .filter(|&j| group[j] == usize::MAX && vals[j].im * vals[i].im < 0.0)
146                .min_by(|&x, &y| (vals[x] - vals[i].conj()).norm().total_cmp(&(vals[y] - vals[i].conj()).norm()));
147            if let Some(j) = partner {
148                group[j] = groups.len();
149                members.push(j);
150                members.sort_by(|&x, &y| vals[y].im.total_cmp(&vals[x].im));
151            }
152        }
153        groups.push(members);
154    }
155    let key = |g: &Vec<usize>| g.iter().map(|&i| preference(which, vals[i])).fold(f64::NEG_INFINITY, f64::max);
156    let mut order: Vec<usize> = (0..groups.len()).collect();
157    order.sort_by(|&x, &y| key(&groups[y]).total_cmp(&key(&groups[x])));
158    // Move the values into place one by one, tracking each position's original index.
159    let mut label: Vec<usize> = (0..m).collect();
160    let mut target = 0;
161    for g in &order {
162        for &orig in &groups[*g] {
163            let mut j = label.iter().position(|&l| l == orig).expect("present");
164            while j > target {
165                swap(t, z, j - 1);
166                label.swap(j - 1, j);
167                j -= 1;
168            }
169            target += 1;
170        }
171    }
172    label.iter().map(|&l| group[l]).collect()
173}
174
175/// The eigenvector of the upper triangular `T` for its `i`-th diagonal value, by back
176/// substitution in the leading `(i + 1) × (i + 1)` block.
177fn triangular_eigenvector(t: &Array2<C>, i: usize) -> Vec<C> {
178    let lambda = t[(i, i)];
179    let floor = f64::EPSILON * t.iter().fold(0.0f64, |acc, v| acc.max(v.norm())).max(f64::MIN_POSITIVE);
180    let mut s = vec![C::new(0.0, 0.0); t.nrows()];
181    s[i] = C::new(1.0, 0.0);
182    for r in (0..i).rev() {
183        let sum: C = (r + 1..=i).map(|c| t[(r, c)] * s[c]).sum();
184        let mut d = t[(r, r)] - lambda;
185        if d.norm() < floor {
186            d = C::new(floor, 0.0);
187        }
188        s[r] = -sum / d;
189    }
190    s
191}
192
193// ANCHOR: eigs
194/// `k` eigenvalues and eigenvectors of a square operator (SciPy's `eigs`), by the Krylov-Schur
195/// method. The Arnoldi process builds an orthonormal basis `V` of a Krylov subspace with
196/// `A V = V H + f eₘᵀ`; the eigenvalues of the small `H` (Ritz values) approximate those of `A`,
197/// with residuals `‖f‖ |eₘᵀ y|` known without forming the vectors. When the subspace reaches
198/// `ncv` vectors, the Schur form of `H` is reordered to put the wanted Ritz values first, and
199/// the factorisation is cut back to their invariant subspace: a real orthonormal basis of it, so
200/// that the work stays in real arithmetic. The Arnoldi process then extends it again.
201pub fn eigs(a: &dyn LinearOperator, k: usize, which: EigsWhich, options: &EigsOptions) -> Result<EigsResult> {
202    let (n, n2) = a.shape();
203    if n != n2 || k == 0 || k > n {
204        return Err(LinalgError::Shape(format!("need a square operator and 1 ≤ k ≤ n, got {n} × {n2}, k = {k}")));
205    }
206    let m = options.ncv.unwrap_or((2 * k + 1).max(30)).clamp((k + 1).min(n), n);
207    // Residual estimates of converged pairs settle at a few ε|θ|, which may lie just above ε|θ|.
208    let tol = options.tol.max(8.0 * f64::EPSILON);
209    let max_restarts = options.max_restarts.unwrap_or(10 * n);
210    let mut v0 = match &options.v0 {
211        Some(v) if v.len() == n && v.iter().any(|x| *x != 0.0) => v.clone(),
212        Some(_) => return Err(LinalgError::Shape(format!("v0 must be a non-zero vector of length {n}"))),
213        None => start_vector(n, &[]),
214    };
215    let nv = dot(&v0, &v0).sqrt();
216    v0.iter_mut().for_each(|x| *x /= nv);
217    let mut basis: Vec<Vec<f64>> = vec![v0];
218    // H̄ is (m + 1) × m: A V[:, :j] = V[:, :j+1] H̄[:j+1, :j] for the columns built so far.
219    let mut hbar = Array2::<f64>::zeros((m + 1, m));
220    let (mut kept, mut restarts, mut matvecs) = (0, 0, 0);
221    loop {
222        // Extend the Arnoldi factorisation from `kept` to `m` columns.
223        for j in kept..m {
224            let mut w = a.matvec(&basis[j]);
225            matvecs += 1;
226            let wnorm = dot(&w, &w).sqrt();
227            // Classical Gram-Schmidt, twice (the second pass restores orthogonality).
228            for _ in 0..2 {
229                let c: Vec<f64> = basis.iter().map(|v| dot(&w, v)).collect();
230                for (v, ci) in basis.iter().zip(&c) {
231                    w.iter_mut().zip(v).for_each(|(wi, vi)| *wi -= ci * vi);
232                }
233                for (i, ci) in c.iter().enumerate() {
234                    hbar[(i, j)] += ci;
235                }
236            }
237            let beta = dot(&w, &w).sqrt();
238            if beta > 1e3 * f64::EPSILON * wnorm.max(f64::MIN_POSITIVE) {
239                hbar[(j + 1, j)] = beta;
240                basis.push(w.iter().map(|x| x / beta).collect());
241            } else {
242                // An invariant subspace: continue with a new direction, or a zero vector if
243                // the basis already spans the whole space.
244                hbar[(j + 1, j)] = 0.0;
245                basis.push(if basis.len() < n { start_vector(n, &basis) } else { vec![0.0; n] });
246            }
247        }
248        let beta_m = hbar[(m, m - 1)];
249        let h = hbar.slice(s![..m, ..]).to_owned();
250        let (mut t, mut z) = schur_complex(&h)?;
251        let group = reorder(&mut t, &mut z, which);
252        let hnorm = h.iter().map(|v| v * v).sum::<f64>().sqrt().max(f64::MIN_POSITIVE);
253        let eps23 = f64::EPSILON.powf(2.0 / 3.0) * hnorm;
254        let wanted = k.min(m);
255        let ritz: Vec<Vec<C>> = (0..wanted).map(|i| {
256            let s = triangular_eigenvector(&t, i);
257            (0..m).map(|r| (0..=i).map(|c| z[(r, c)] * s[c]).sum()).collect()
258        }).collect();
259        let nconv = (0..wanted)
260            .filter(|&i| {
261                let y = &ritz[i];
262                let ynorm = y.iter().map(|v| v.norm_sqr()).sum::<f64>().sqrt();
263                beta_m * y[m - 1].norm() / ynorm <= tol * t[(i, i)].norm().max(eps23)
264            })
265            .count();
266        if nconv >= wanted || restarts >= max_restarts || m == n {
267            return Ok(finish(&basis, &t, &group, &ritz, n, m, nconv, wanted, restarts, matvecs));
268        }
269        restarts += 1;
270        // Keep the wanted values and half of the rest, without splitting a conjugate pair.
271        let mut p = (k + (m - k) / 2).min(m - 1);
272        if p < m && p > 0 && group[p] == group[p - 1] {
273            if p + 1 < m { p += 1 } else { p -= 1 }
274        }
275        // A real orthonormal basis of the invariant subspace spanned by the leading p Schur
276        // vectors: it is closed under conjugation, so [Re Z_p, Im Z_p] has rank p.
277        let w = Array2::from_shape_fn((m, 2 * p), |(r, c)| if c < p { z[(r, c)].re } else { z[(r, c - p)].im });
278        let (u, _, _) = w.svd(true, false)?;
279        let u = u.expect("requested").slice(s![.., ..p]).to_owned();
280        let small = u.t().dot(&h).dot(&u);
281        let mut new_basis: Vec<Vec<f64>> = (0..p).map(|c| {
282            let mut v = vec![0.0; n];
283            for (j, bj) in basis.iter().take(m).enumerate() {
284                let coef = u[(j, c)];
285                v.iter_mut().zip(bj).for_each(|(vi, b)| *vi += coef * b);
286            }
287            v
288        }).collect();
289        new_basis.push(basis[m].clone());
290        basis = new_basis;
291        hbar.fill(0.0);
292        hbar.slice_mut(s![..p, ..p]).assign(&small);
293        for c in 0..p {
294            hbar[(p, c)] = beta_m * u[(m - 1, c)];
295        }
296        kept = p;
297    }
298}
299// ANCHOR_END: eigs
300
301/// The Ritz pairs as eigenvalues and unit eigenvectors of `A`.
302#[allow(clippy::too_many_arguments)]
303fn finish(basis: &[Vec<f64>], t: &Array2<C>, group: &[usize], ritz: &[Vec<C>], n: usize, m: usize, nconv: usize, wanted: usize, restarts: usize, matvecs: usize) -> EigsResult {
304    let mut values = Vec::with_capacity(wanted);
305    let mut vectors = Array2::<C>::zeros((n, wanted));
306    for i in 0..wanted {
307        let paired = group.iter().filter(|&&g| g == group[i]).count() == 2;
308        let lambda = t[(i, i)];
309        values.push(if paired { lambda } else { C::new(lambda.re, 0.0) });
310        let mut x = vec![C::new(0.0, 0.0); n];
311        for (j, bj) in basis.iter().take(m).enumerate() {
312            let y = ritz[i][j];
313            x.iter_mut().zip(bj).for_each(|(xi, b)| *xi += y * b);
314        }
315        let big = x.iter().copied().max_by(|p, q| p.norm().total_cmp(&q.norm())).unwrap_or(C::new(1.0, 0.0));
316        let norm = x.iter().map(|v| v.norm_sqr()).sum::<f64>().sqrt();
317        let phase = if big.norm() > 0.0 { big.conj() / big.norm() } else { C::new(1.0, 0.0) };
318        for (r, xi) in x.iter().enumerate() {
319            let v = xi * phase / norm;
320            vectors[(r, i)] = if paired { v } else { C::new(v.re, 0.0) };
321        }
322    }
323    EigsResult { values, vectors, converged: nconv >= wanted, nconv, restarts, matvecs }
324}
325
326// ANCHOR: eigs_shift_invert
327/// The `k` eigenvalues of a sparse matrix nearest the real shift `σ`, with eigenvectors
328/// (SciPy's `eigs(A, k, sigma=σ)`). The eigenvalues `λ` near `σ` are the largest in magnitude of
329/// `(A − σI)⁻¹`, `θ = 1/(λ − σ)`, which Arnoldi finds quickly; each product with the inverse is
330/// one solve with a sparse LU factorisation of `A − σI`. The values are returned nearest first.
331pub fn eigs_shift_invert(a: &CsrMatrix, k: usize, sigma: f64, options: &EigsOptions) -> Result<EigsResult> {
332    let n = a.nrows;
333    if a.ncols != n {
334        return Err(LinalgError::NotSquare { rows: a.nrows, cols: a.ncols });
335    }
336    let shifted = a.add(1.0, &CsrMatrix::identity(n), -sigma)?;
337    let op = ShiftInvert { lu: SparseLu::factor(&shifted, Ordering::MinimumDegree)?, n };
338    let mut r = eigs(&op, k, EigsWhich::LargestMagnitude, options)?;
339    for v in r.values.iter_mut() {
340        let lambda = C::new(sigma, 0.0) + C::new(1.0, 0.0) / *v;
341        *v = if v.im == 0.0 { C::new(lambda.re, 0.0) } else { lambda };
342    }
343    Ok(r)
344}
345// ANCHOR_END: eigs_shift_invert
346
347#[cfg(test)]
348mod tests {
349    use super::*;
350    use crate::Eig;
351    use crate::sparse::CooMatrix;
352
353    /// A pseudo-random sparse matrix with complex eigenvalues: four off-diagonal entries per row.
354    fn scattered(n: usize) -> CsrMatrix {
355        let mut coo = CooMatrix::new(n, n);
356        for i in 0..n {
357            coo.push(i, i, (i as f64 * 0.37).sin());
358            for t in 1..=4 {
359                let j = (i * 37 + 11 * t + 7 * t * t) % n;
360                coo.push(i, j, (i as f64 + 3.0 * t as f64 + 1.0).sin());
361            }
362        }
363        coo.to_csr().unwrap()
364    }
365
366    /// The 5-point convection-diffusion operator on an `m × m` grid; complex eigenvalues when `γ > 1`.
367    fn convection(m: usize, gamma: f64) -> CsrMatrix {
368        let mut coo = CooMatrix::new(m * m, m * m);
369        for i in 0..m {
370            for j in 0..m {
371                let r = i * m + j;
372                coo.push(r, r, 4.0);
373                if i > 0 { coo.push(r, r - m, -1.0 - gamma); }
374                if i + 1 < m { coo.push(r, r + m, -1.0 + gamma); }
375                if j > 0 { coo.push(r, r - 1, -1.0 - gamma); }
376                if j + 1 < m { coo.push(r, r + 1, -1.0 + gamma); }
377            }
378        }
379        coo.to_csr().unwrap()
380    }
381
382    fn check(a: &CsrMatrix, k: usize, which: EigsWhich) {
383        let r = eigs(a, k, which, &EigsOptions::default()).unwrap();
384        assert!(r.converged, "{which:?}: {} of {k} after {} restarts", r.nconv, r.restarts);
385        let (all, _) = a.to_dense().eig().unwrap();
386        let mut all: Vec<C> = all.to_vec();
387        all.sort_by(|x, y| preference(which, *y).total_cmp(&preference(which, *x)));
388        let scale = all.iter().fold(0.0f64, |acc, v| acc.max(v.norm()));
389        // Each value found is an eigenvalue, and the k-th most wanted is matched in preference.
390        for (i, v) in r.values.iter().enumerate() {
391            let nearest = all.iter().map(|w| (w - v).norm()).fold(f64::INFINITY, f64::min);
392            assert!(nearest < 1e-10 * scale, "{which:?} value {v} is {nearest:e} from the spectrum");
393            assert!((preference(which, *v) - preference(which, all[i])).abs() < 1e-10 * scale, "{which:?}: {:?} vs {:?}", r.values, &all[..k]);
394            let x: Vec<C> = r.vectors.column(i).to_vec();
395            let re: Vec<f64> = x.iter().map(|z| z.re).collect();
396            let im: Vec<f64> = x.iter().map(|z| z.im).collect();
397            let (are, aim) = (a.matvec(&re), a.matvec(&im));
398            let res = (0..x.len()).map(|j| (C::new(are[j], aim[j]) - v * x[j]).norm_sqr()).sum::<f64>().sqrt();
399            assert!(res < 1e-9 * scale, "{which:?} residual {res:e}");
400        }
401    }
402
403    #[test]
404    fn every_which_on_a_scattered_matrix() {
405        let a = scattered(300);
406        for which in [EigsWhich::LargestMagnitude, EigsWhich::LargestReal, EigsWhich::SmallestReal, EigsWhich::LargestImaginary] {
407            check(&a, 6, which);
408        }
409    }
410
411    /// A diagonal ramp plus a skew-symmetric tridiagonal part: nearly normal, with complex
412    /// eigenvalues spread along the real axis.
413    fn ramp(n: usize) -> CsrMatrix {
414        let mut coo = CooMatrix::new(n, n);
415        for i in 0..n {
416            coo.push(i, i, 2.0 * i as f64 / n as f64);
417            if i + 1 < n {
418                coo.push(i, i + 1, 1.0);
419                coo.push(i + 1, i, -1.0);
420            }
421        }
422        coo.to_csr().unwrap()
423    }
424
425    #[test]
426    fn convection_diffusion_and_a_complex_spectrum() {
427        check(&convection(15, 0.5), 5, EigsWhich::LargestMagnitude);
428        check(&convection(15, 0.5), 4, EigsWhich::SmallestReal);
429        let a = ramp(400);
430        for which in [EigsWhich::LargestReal, EigsWhich::LargestImaginary, EigsWhich::SmallestReal] {
431            check(&a, 6, which);
432        }
433    }
434
435    #[test]
436    fn shift_invert_and_small_problems() {
437        let a = scattered(300);
438        let sigma = 0.3;
439        let r = eigs_shift_invert(&a, 5, sigma, &EigsOptions::default()).unwrap();
440        assert!(r.converged);
441        let (all, _) = a.to_dense().eig().unwrap();
442        let mut d: Vec<f64> = all.iter().map(|w| (w - sigma).norm()).collect();
443        d.sort_by(f64::total_cmp);
444        for (v, want) in r.values.iter().zip(&d) {
445            assert!(((v - sigma).norm() - want).abs() < 1e-9, "{:?}", r.values);
446        }
447        // k = n, and an operator smaller than the default subspace.
448        let small = scattered(7);
449        check(&small, 7, EigsWhich::LargestMagnitude);
450        check(&small, 3, EigsWhich::SmallestMagnitude);
451        assert!(eigs(&small, 0, EigsWhich::LargestMagnitude, &EigsOptions::default()).is_err());
452    }
453}