Skip to main content

lib_jsl_linalg/
generalized.rs

1//! Generalised eigenvalue problems `A x = λ B x`: the symmetric-definite case by Cholesky
2//! reduction (SciPy's `eigh(a, b)`), and the general case by the QZ algorithm (Moler and Stewart,
3//! 1973), which gives the generalised Schur form `A = Q S Zᴴ`, `B = Q T Zᴴ` (SciPy's
4//! `qz(output='complex')` and `eig(a, b)`).
5//!
6//! See the book entry [Generalised eigenproblems and structured matrices](https://jwkunz.github.io/lib_jsl/book/linear_algebra/generalized-structured.html).
7
8use crate::error::{LinalgError, Result};
9use crate::scalar::Scalar;
10use crate::{Cholesky, Diag, Eigh, QrMode, SolveTriangular, UPLO, qr};
11use ndarray::{Array1, Array2, ArrayBase, Data, Ix2};
12use num_complex::Complex;
13
14type C = Complex<f64>;
15
16fn cz() -> C {
17    C::new(0.0, 0.0)
18}
19
20// ANCHOR: eigh_generalized
21/// The eigenvalues (ascending) and eigenvectors of the symmetric-definite problem `A x = λ B x`,
22/// `A` Hermitian and `B` Hermitian positive definite (SciPy's `eigh(a, b)`, LAPACK's `sygv`
23/// type 1). With `B = L Lᴴ`, the problem becomes the standard `C y = λ y` for
24/// `C = L⁻¹ A L⁻ᴴ`, and `x = L⁻ᴴ y`; the eigenvectors are `B`-orthonormal, `Xᴴ B X = I`.
25pub fn eigh_generalized<T: Scalar, S: Data<Elem = T>, S2: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, b: &ArrayBase<S2, Ix2>, uplo: UPLO) -> Result<(Array1<f64>, Array2<T>)> {
26    let n = a.nrows();
27    if a.ncols() != n || b.dim() != (n, n) {
28        return Err(LinalgError::Shape(format!("A ({:?}) and B ({:?}) must be square and of one size", a.dim(), b.dim())));
29    }
30    // Both triangles of A from the `uplo` one.
31    let full = Array2::from_shape_fn((n, n), |(i, j)| {
32        let read_lower = matches!(uplo, UPLO::Lower);
33        if (i >= j) == read_lower || i == j { a[(i, j)] } else { a[(j, i)].conj() }
34    });
35    let l = b.cholesky(uplo).map(|f| if matches!(uplo, UPLO::Lower) { f } else { f.t().mapv(|v| v.conj()) })?;
36    // C = L⁻¹ A L⁻ᴴ: W = L⁻¹ A, then C = (L⁻¹ Wᴴ)ᴴ.
37    let w = l.solve_triangular(UPLO::Lower, Diag::NonUnit, &full)?;
38    let wh = w.t().mapv(|v| v.conj());
39    let c = l.solve_triangular(UPLO::Lower, Diag::NonUnit, &wh)?.t().mapv(|v| v.conj());
40    let c = Array2::from_shape_fn((n, n), |(i, j)| (c[(i, j)] + c[(j, i)].conj()).scale(0.5));
41    let (values, y) = c.eigh(UPLO::Lower)?;
42    let lh = l.t().mapv(|v| v.conj());
43    let x = lh.solve_triangular(UPLO::Upper, Diag::NonUnit, &y)?;
44    Ok((values, x))
45}
46// ANCHOR_END: eigh_generalized
47
48/// `(c, s)` with `[c s; −s̄ c] [f; g] = [r; 0]`, `c` real (LAPACK's `lartg`).
49fn rotation(f: C, g: C) -> (f64, C) {
50    if g == cz() {
51        return (1.0, cz());
52    }
53    if f == cz() {
54        return (0.0, g.conj() / g.norm());
55    }
56    let r = f.norm().hypot(g.norm());
57    (f.norm() / r, f / f.norm() * g.conj() / r)
58}
59
60/// Rows `p`, `q` of `m` (columns `cols`) ← `[c s; −s̄ c]` applied to them.
61fn rotate_rows(m: &mut Array2<C>, p: usize, q: usize, c: f64, s: C, cols: std::ops::Range<usize>) {
62    for j in cols {
63        let (x, y) = (m[(p, j)], m[(q, j)]);
64        m[(p, j)] = x * c + s * y;
65        m[(q, j)] = y * c - s.conj() * x;
66    }
67}
68
69/// Columns `q`, `p` of `m` (rows `rows`) ← `(c q + s p, −s̄ q + c p)`: a right multiplication by a
70/// unitary matrix, chosen so that it zeros an entry of column `p`.
71fn rotate_cols(m: &mut Array2<C>, q: usize, p: usize, c: f64, s: C, rows: std::ops::Range<usize>) {
72    for i in rows {
73        let (x, y) = (m[(i, q)], m[(i, p)]);
74        m[(i, q)] = x * c + s * y;
75        m[(i, p)] = y * c - s.conj() * x;
76    }
77}
78
79/// The generalised complex Schur form `A = Q S Zᴴ`, `B = Q T Zᴴ`.
80#[derive(Clone, Debug)]
81#[non_exhaustive]
82pub struct QzFactors {
83    /// Upper triangular.
84    pub s: Array2<C>,
85    /// Upper triangular, with a real non-negative diagonal.
86    pub t: Array2<C>,
87    pub q: Array2<C>,
88    pub z: Array2<C>,
89}
90
91/// A row rotation on rows `p`, `q` of `S` and `T` (columns from `from`), with `Q ← Q Gᴴ`.
92fn left_rot(f: &mut QzFactors, p: usize, q: usize, c: f64, s: C, from: usize) {
93    let n = f.s.ncols();
94    rotate_rows(&mut f.s, p, q, c, s, from..n);
95    rotate_rows(&mut f.t, p, q, c, s, from..n);
96    // Q ← Q Gᴴ: columns (p, q) ← (c Q_p + s̄ Q_q, −s Q_p + c Q_q).
97    for i in 0..n {
98        let (x, y) = (f.q[(i, p)], f.q[(i, q)]);
99        f.q[(i, p)] = x * c + s.conj() * y;
100        f.q[(i, q)] = y * c - s * x;
101    }
102}
103
104/// A column rotation on columns `q`, `p` of `S` (rows `..s_rows`) and `T` (rows `..t_rows`), with
105/// the same rotation applied to `Z`.
106fn right_rot(f: &mut QzFactors, q: usize, p: usize, c: f64, s: C, s_rows: usize, t_rows: usize) {
107    let n = f.s.ncols();
108    rotate_cols(&mut f.s, q, p, c, s, 0..s_rows);
109    rotate_cols(&mut f.t, q, p, c, s, 0..t_rows);
110    rotate_cols(&mut f.z, q, p, c, s, 0..n);
111}
112
113// ANCHOR: qz
114/// The generalised complex Schur form of the pencil `(A, B)` (SciPy's `qz(a, b, output='complex')`):
115/// unitary `Q`, `Z` with `Qᴴ A Z = S`, `Qᴴ B Z = T` upper triangular. The generalised eigenvalues
116/// are `S_ii / T_ii` (infinite where `T_ii = 0`). `B` is first made triangular by a QR
117/// factorisation and `A` Hessenberg by Givens rotations that keep `B` triangular; then QZ sweeps
118/// with Wilkinson-type shifts chase a bulge down the pencil until the subdiagonal of `S`
119/// vanishes. A zero on the diagonal of `T` (an infinite eigenvalue) is chased to the bottom and
120/// deflated.
121pub fn qz<T: Scalar, S: Data<Elem = T>, S2: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, b: &ArrayBase<S2, Ix2>) -> Result<QzFactors> {
122    let n = a.nrows();
123    if a.ncols() != n || b.dim() != (n, n) {
124        return Err(LinalgError::Shape(format!("A ({:?}) and B ({:?}) must be square and of one size", a.dim(), b.dim())));
125    }
126    let ac = a.mapv(|v| v.to_complex());
127    let bc = b.mapv(|v| v.to_complex());
128    if ac.iter().chain(bc.iter()).any(|v| !v.re.is_finite() || !v.im.is_finite()) {
129        return Err(LinalgError::NonFinite);
130    }
131    // B = Q₀ R₀; S = Q₀ᴴ A.
132    let f0 = qr(&bc, QrMode::Full, false)?;
133    let q0h = f0.q.t().mapv(|v| v.conj());
134    let mut f = QzFactors { s: q0h.dot(&ac), t: f0.r, q: f0.q, z: Array2::from_shape_fn((n, n), |(i, j)| if i == j { C::new(1.0, 0.0) } else { cz() }) };
135    // Hessenberg-triangular reduction.
136    for j in 0..n.saturating_sub(2) {
137        for i in (j + 2..n).rev() {
138            let (c, s) = rotation(f.s[(i - 1, j)], f.s[(i, j)]);
139            left_rot(&mut f, i - 1, i, c, s, 0);
140            f.s[(i, j)] = cz();
141            // T[i, i−1] filled in; zero it with columns (i, i − 1).
142            let (c, s) = rotation(f.t[(i, i)], f.t[(i, i - 1)]);
143            right_rot(&mut f, i, i - 1, c, s, n, i + 1);
144            f.t[(i, i - 1)] = cz();
145        }
146    }
147    let norm = |m: &Array2<C>| m.iter().map(|v| v.norm_sqr()).sum::<f64>().sqrt();
148    let (snorm, tnorm) = (norm(&f.s).max(f64::MIN_POSITIVE), norm(&f.t).max(f64::MIN_POSITIVE));
149    let eps = f64::EPSILON;
150    let mut hi = n;
151    let mut its = 0;
152    let mut total = 0;
153    while hi > 0 {
154        let ihi = hi - 1;
155        // The start of the active block: the last negligible subdiagonal entry.
156        let mut l = ihi;
157        while l > 0 {
158            let sub = f.s[(l, l - 1)].norm();
159            if sub <= eps * (f.s[(l, l)].norm() + f.s[(l - 1, l - 1)].norm()).max(eps * snorm) {
160                f.s[(l, l - 1)] = cz();
161                break;
162            }
163            l -= 1;
164        }
165        if l == ihi {
166            hi -= 1;
167            its = 0;
168            continue;
169        }
170        total += 1;
171        if total > 30 * n.max(1) * 10 {
172            return Err(LinalgError::Shape("qz: the QZ iteration did not converge".into()));
173        }
174        // An infinite eigenvalue: chase the zero on T's diagonal to the bottom and deflate.
175        if let Some(j) = (l..=ihi).find(|&j| f.t[(j, j)].norm() <= eps * tnorm) {
176            f.t[(j, j)] = cz();
177            for k in j..ihi {
178                let (c, s) = rotation(f.t[(k, k + 1)], f.t[(k + 1, k + 1)]);
179                left_rot(&mut f, k, k + 1, c, s, k.saturating_sub(1));
180                f.t[(k + 1, k + 1)] = cz();
181                if k > l {
182                    let (c, s) = rotation(f.s[(k + 1, k)], f.s[(k + 1, k - 1)]);
183                    right_rot(&mut f, k, k - 1, c, s, (k + 2).min(n), k + 1);
184                    f.s[(k + 1, k - 1)] = cz();
185                }
186            }
187            let (c, s) = rotation(f.s[(ihi, ihi)], f.s[(ihi, ihi - 1)]);
188            right_rot(&mut f, ihi, ihi - 1, c, s, ihi + 1, ihi + 1);
189            f.s[(ihi, ihi - 1)] = cz();
190            continue;
191        }
192        its += 1;
193        // Shift: the eigenvalue of the trailing 2 × 2 pencil nearer S_mm / T_mm.
194        let m = ihi;
195        let shift = if its % 10 == 0 {
196            // An exceptional shift breaks cycles.
197            f.s[(m, m - 1)] / f.t[(m - 1, m - 1)] + f.s[(m, m)] / f.t[(m, m)]
198        } else {
199            let (a11, a12, a21, a22) = (f.s[(m - 1, m - 1)], f.s[(m - 1, m)], f.s[(m, m - 1)], f.s[(m, m)]);
200            let (b11, b12, b22) = (f.t[(m - 1, m - 1)], f.t[(m - 1, m)], f.t[(m, m)]);
201            // det(A₂ − λ B₂) = 0: (a11 − λb11)(a22 − λb22) − (a12 − λb12) a21 = 0.
202            let qa = b11 * b22;
203            let qb = -(a11 * b22 + a22 * b11 - b12 * a21);
204            let qc = a11 * a22 - a12 * a21;
205            let disc = (qb * qb - qa * qc * 4.0).sqrt();
206            let (r1, r2) = ((-qb + disc) / (qa * 2.0), (-qb - disc) / (qa * 2.0));
207            let target = a22 / b22;
208            if (r1 - target).norm() <= (r2 - target).norm() { r1 } else { r2 }
209        };
210        // The QZ sweep from l to ihi.
211        let (c, s) = rotation(f.s[(l, l)] - shift * f.t[(l, l)], f.s[(l + 1, l)]);
212        left_rot(&mut f, l, l + 1, c, s, l);
213        for k in l..ihi {
214            let (c, s) = rotation(f.t[(k + 1, k + 1)], f.t[(k + 1, k)]);
215            right_rot(&mut f, k + 1, k, c, s, (k + 3).min(ihi + 1), k + 2);
216            f.t[(k + 1, k)] = cz();
217            if k + 1 < ihi {
218                let (c, s) = rotation(f.s[(k + 1, k)], f.s[(k + 2, k)]);
219                left_rot(&mut f, k + 1, k + 2, c, s, k);
220                f.s[(k + 2, k)] = cz();
221            }
222        }
223    }
224    // Make T's diagonal real and non-negative, as LAPACK does.
225    for i in 0..n {
226        let b = f.t[(i, i)];
227        if b.norm() > 0.0 && (b.im != 0.0 || b.re < 0.0) {
228            let phase = b.conj() / b.norm();
229            for j in i..n {
230                f.t[(i, j)] *= phase;
231                f.s[(i, j)] *= phase;
232            }
233            for r in 0..n {
234                f.q[(r, i)] *= phase.conj();
235            }
236            f.t[(i, i)] = C::new(f.t[(i, i)].norm(), 0.0);
237        }
238    }
239    for i in 0..n {
240        for j in 0..i {
241            f.s[(i, j)] = cz();
242            f.t[(i, j)] = cz();
243        }
244    }
245    Ok(f)
246}
247// ANCHOR_END: qz
248
249/// The solution of the generalised eigenproblem `A x = λ B x`.
250#[derive(Clone, Debug)]
251#[non_exhaustive]
252pub struct GeneralizedEigen {
253    /// `λ = α / β`: infinite (`∞ + 0i`) where `β = 0`, NaN where both vanish.
254    pub values: Array1<C>,
255    pub alpha: Array1<C>,
256    /// Real and non-negative.
257    pub beta: Array1<f64>,
258    /// Right eigenvectors as unit columns (as SciPy normalises them).
259    pub vectors: Array2<C>,
260}
261
262// ANCHOR: eig_generalized
263/// The generalised eigenvalues and right eigenvectors of `(A, B)` (SciPy's `eig(a, b)`), from
264/// the QZ form: for each `k`, `(β_k S − α_k T) y = 0` is solved by back substitution with
265/// `y_k = 1`, and `x = Z y` is normalised to unit length.
266pub fn eig_generalized<T: Scalar, S: Data<Elem = T>, S2: Data<Elem = T>>(a: &ArrayBase<S, Ix2>, b: &ArrayBase<S2, Ix2>) -> Result<GeneralizedEigen> {
267    let f = qz(a, b)?;
268    let n = f.s.nrows();
269    let alpha = Array1::from_shape_fn(n, |i| f.s[(i, i)]);
270    let beta = Array1::from_shape_fn(n, |i| f.t[(i, i)].re);
271    let values = Array1::from_shape_fn(n, |i| {
272        if beta[i] != 0.0 {
273            alpha[i] / beta[i]
274        } else if alpha[i] != cz() {
275            C::new(f64::INFINITY, 0.0)
276        } else {
277            C::new(f64::NAN, if alpha.iter().all(|v| v.im == 0.0) { 0.0 } else { f64::NAN })
278        }
279    });
280    let scale = f.s.iter().chain(f.t.iter()).fold(0.0f64, |m, v| m.max(v.norm())).max(f64::MIN_POSITIVE);
281    let mut vectors = Array2::from_elem((n, n), cz());
282    for k in 0..n {
283        let (ak, bk) = (alpha[k], C::new(beta[k], 0.0));
284        let mut y = vec![cz(); n];
285        y[k] = C::new(1.0, 0.0);
286        for i in (0..k).rev() {
287            let sum: C = (i + 1..=k).map(|j| (bk * f.s[(i, j)] - ak * f.t[(i, j)]) * y[j]).sum();
288            let mut d = bk * f.s[(i, i)] - ak * f.t[(i, i)];
289            if d.norm() < f64::EPSILON * scale {
290                d = C::new(f64::EPSILON * scale, 0.0);
291            }
292            y[i] = -sum / d;
293        }
294        let x: Vec<C> = (0..n).map(|r| (0..=k).map(|j| f.z[(r, j)] * y[j]).sum()).collect();
295        let nx = x.iter().map(|v| v.norm_sqr()).sum::<f64>().sqrt();
296        for (r, v) in x.iter().enumerate() {
297            vectors[(r, k)] = v / nx;
298        }
299    }
300    Ok(GeneralizedEigen { values, alpha, beta, vectors })
301}
302// ANCHOR_END: eig_generalized
303
304#[cfg(test)]
305mod tests {
306    use super::*;
307
308    fn pencil(n: usize, seed: f64) -> (Array2<f64>, Array2<f64>) {
309        let a = Array2::from_shape_fn((n, n), |(i, j)| (seed + 1.3 * i as f64 + 0.7 * (j * j) as f64 + 0.37 * (i * j) as f64).sin());
310        let b = Array2::from_shape_fn((n, n), |(i, j)| (seed + 0.5 * i as f64 - 0.9 * j as f64 + 0.21 * (i * j) as f64).cos() + if i == j { 3.0 } else { 0.0 });
311        (a, b)
312    }
313
314    fn residual(a: &Array2<C>, b: &Array2<C>, e: &GeneralizedEigen) -> f64 {
315        let n = a.nrows();
316        let mut worst = 0.0f64;
317        for k in 0..n {
318            let x = e.vectors.column(k);
319            let (al, be) = (e.alpha[k], C::new(e.beta[k], 0.0));
320            for i in 0..n {
321                let r: C = (0..n).map(|j| (be * a[(i, j)] - al * b[(i, j)]) * x[j]).sum();
322                worst = worst.max(r.norm());
323            }
324        }
325        worst
326    }
327
328    #[test]
329    fn qz_form_and_eigenpairs() {
330        for (n, seed) in [(1, 0.0), (2, 1.0), (6, 2.0), (15, 3.0)] {
331            let (a, b) = pencil(n, seed);
332            let f = qz(&a, &b).unwrap();
333            let (ac, bc) = (a.mapv(|v| C::new(v, 0.0)), b.mapv(|v| C::new(v, 0.0)));
334            let zh = f.z.t().mapv(|v| v.conj());
335            let ra = f.q.dot(&f.s).dot(&zh) - &ac;
336            let rb = f.q.dot(&f.t).dot(&zh) - &bc;
337            assert!(ra.iter().chain(rb.iter()).all(|v| v.norm() < 1e-12), "n = {n}");
338            assert!((0..n).all(|i| (0..i).all(|j| f.s[(i, j)] == cz() && f.t[(i, j)] == cz())));
339            assert!((0..n).all(|i| f.t[(i, i)].im == 0.0 && f.t[(i, i)].re >= 0.0));
340            let e = eig_generalized(&a, &b).unwrap();
341            assert!(residual(&ac, &bc, &e) < 1e-11, "n = {n}");
342        }
343        // Complex data.
344        let (a, b) = pencil(7, 4.0);
345        let ac = Array2::from_shape_fn((7, 7), |(i, j)| C::new(a[(i, j)], b[(j, i)] - 3.0 * (i == j) as u8 as f64));
346        let bc = Array2::from_shape_fn((7, 7), |(i, j)| C::new(b[(i, j)], 0.3 * a[(j, i)]));
347        let e = eig_generalized(&ac, &bc).unwrap();
348        assert!(residual(&ac, &bc, &e) < 1e-11);
349    }
350
351    #[test]
352    fn singular_b_gives_infinite_eigenvalues() {
353        // B = diag(1, 1, 0): one infinite eigenvalue; the finite ones are those of A's leading block.
354        let a = Array2::from_shape_vec((3, 3), vec![2.0, 1.0, 0.5, 0.0, 3.0, 1.0, 1.0, 0.0, 4.0]).unwrap();
355        let b = Array2::from_shape_vec((3, 3), vec![1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0]).unwrap();
356        let e = eig_generalized(&a, &b).unwrap();
357        assert_eq!(e.values.iter().filter(|v| v.re.is_infinite()).count(), 1, "{:?}", e.values);
358        // det(A − λB) = 4λ² − ... : the finite eigenvalues solve det of the Schur complement.
359        let finite: Vec<C> = e.values.iter().copied().filter(|v| v.re.is_finite()).collect();
360        for l in finite {
361            let m = Array2::from_shape_fn((3, 3), |(i, j)| C::new(a[(i, j)] - if i == j && i < 2 { l.re } else { 0.0 }, if i == j && i < 2 { -l.im } else { 0.0 }));
362            let det = m[(0, 0)] * (m[(1, 1)] * m[(2, 2)] - m[(1, 2)] * m[(2, 1)]) - m[(0, 1)] * (m[(1, 0)] * m[(2, 2)] - m[(1, 2)] * m[(2, 0)]) + m[(0, 2)] * (m[(1, 0)] * m[(2, 1)] - m[(1, 1)] * m[(2, 0)]);
363            assert!(det.norm() < 1e-10, "{l}: {det}");
364        }
365    }
366
367    #[test]
368    fn symmetric_definite_pencils() {
369        let n = 6;
370        let (a, b) = pencil(n, 5.0);
371        let sa = Array2::from_shape_fn((n, n), |(i, j)| a[(i, j)] + a[(j, i)]);
372        let sb = b.t().dot(&b);
373        for uplo in [UPLO::Lower, UPLO::Upper] {
374            let (w, x) = eigh_generalized(&sa, &sb, uplo).unwrap();
375            assert!(w.windows(2).into_iter().all(|p| p[0] <= p[1]));
376            let xbx = x.t().dot(&sb).dot(&x);
377            let ax = sa.dot(&x);
378            let bx = sb.dot(&x);
379            for k in 0..n {
380                assert!((0..n).all(|i| (ax[(i, k)] - w[k] * bx[(i, k)]).abs() < 1e-10));
381                assert!((0..n).all(|i| (xbx[(i, k)] - if i == k { 1.0 } else { 0.0 }).abs() < 1e-10));
382            }
383        }
384        assert!(eigh_generalized(&sa, &(-&sb), UPLO::Lower).is_err(), "B must be positive definite");
385    }
386}