Skip to main content

caroli_dense/
schur.rs

1//! In-house complex Schur decomposition, and the reordering of a Schur form.
2//!
3//! - Hessenberg reduction: faer.
4//! - QR iterations: implicit single-shift, with Wilkinson shifts and deflation (LAPACK zlahqr).
5//! - Reordering: adjacent swaps by Givens rotations (LAPACK ztrexc). [`partition`] makes them in
6//!   windows and applies their accumulated rotations to the rest of the matrix as products
7//!   (Kressner's block algorithm, ACM TOMS 32, 2006): most of the work becomes matrix products.
8
9use crate::{Op, matmul};
10use faer::{Accum, Mat, c64};
11
12const ZERO: c64 = c64::new(0.0, 0.0);
13const ONE: c64 = c64::new(1.0, 0.0);
14
15/// Window of the blocked reordering, and the largest number of eigenvalues moved through it at
16/// once.
17const WINDOW: usize = 64;
18const BATCH: usize = 32;
19
20/// Givens rotation `(c, s)` with `[c s; −s̄ c] [f; g] = [r; 0]` (LAPACK zlartg). `f` and `g` are
21/// first scaled by a power of two (exactly): a subnormal norm would carry too few digits, and the
22/// rotation would not be unitary.
23fn givens(f: c64, g: c64) -> (f64, c64) {
24    if g == ZERO {
25        return (1.0, ZERO);
26    }
27    let m = f.re.abs().max(f.im.abs()).max(g.re.abs()).max(g.im.abs());
28    let scale = if m < 2f64.powi(-500) {
29        2f64.powi(600)
30    } else if m > 2f64.powi(500) {
31        2f64.powi(-600)
32    } else {
33        1.0
34    };
35    let (f, g) = (f * scale, g * scale);
36    if f == ZERO {
37        return (0.0, g.conj() / g.norm());
38    }
39    let d = f.norm().hypot(g.norm());
40    (f.norm() / d, f / f.norm() * g.conj() / d)
41}
42
43/// `H ← G H G†` and `Z ← Z G†` for the rotation `G = [c s; −s̄ c]` on indices `k, k+1`, rows
44/// restricted to `cols` and columns to `rows`.
45fn rotate(
46    h: &mut Mat<c64>,
47    z: &mut Mat<c64>,
48    k: usize,
49    c: f64,
50    s: c64,
51    cols: std::ops::Range<usize>,
52    rows: std::ops::Range<usize>,
53) {
54    for j in cols {
55        let (x, y) = (h[(k, j)], h[(k + 1, j)]);
56        h[(k, j)] = x * c + s * y;
57        h[(k + 1, j)] = y * c - s.conj() * x;
58    }
59    for i in rows {
60        let (x, y) = (h[(i, k)], h[(i, k + 1)]);
61        h[(i, k)] = x * c + s.conj() * y;
62        h[(i, k + 1)] = y * c - s * x;
63    }
64    for i in 0..z.nrows() {
65        let (x, y) = (z[(i, k)], z[(i, k + 1)]);
66        z[(i, k)] = x * c + s.conj() * y;
67        z[(i, k + 1)] = y * c - s * x;
68    }
69}
70
71/// Complex Schur decomposition `a = q t q†` (`t` upper triangular). Returns `(q, t)`.
72#[cfg_attr(all(target_os = "macos", feature = "accelerate"), allow(dead_code))]
73pub(crate) fn schur(a: faer::MatRef<'_, c64>) -> Result<(Mat<c64>, Mat<c64>), crate::DenseError> {
74    use crate::DenseError;
75    use faer::dyn_stack::{MemBuffer, MemStack, StackReq};
76    use faer::linalg::evd::hessenberg;
77    use faer::linalg::householder;
78    use faer::{Conj, Par, Spec};
79    let n = a.nrows();
80    let mut h = a.to_owned();
81    let mut q = Mat::<c64>::identity(n, n);
82    if n <= 1 {
83        return Ok((q, h));
84    }
85    if !(h.norm_max().is_finite()) {
86        return Err(DenseError::Schur);
87    }
88    // Hessenberg form h = q h' q†.
89    let par = Par::Seq;
90    let bs = faer::linalg::qr::no_pivoting::factor::recommended_block_size::<c64>(n - 1, n - 1);
91    let req = StackReq::any_of(&[
92        hessenberg::hessenberg_in_place_scratch::<c64>(n, bs, par, Spec::default()),
93        householder::apply_block_householder_sequence_on_the_right_in_place_scratch::<c64>(n - 1, bs, n - 1),
94    ]);
95    let mut mem = MemBuffer::new(req);
96    let stack = MemStack::new(&mut mem);
97    let mut hh = Mat::<c64>::zeros(bs, n - 1);
98    hessenberg::hessenberg_in_place(h.as_mut(), hh.as_mut(), par, stack, Spec::default());
99    householder::apply_block_householder_sequence_on_the_right_in_place_with_conj(
100        h.as_ref().submatrix(1, 0, n - 1, n - 1),
101        hh.as_ref(),
102        Conj::No,
103        q.as_mut().submatrix_mut(1, 1, n - 1, n - 1),
104        par,
105        stack,
106    );
107    for j in 0..n {
108        for i in j + 2..n {
109            h[(i, j)] = ZERO;
110        }
111    }
112
113    // Implicit single-shift QR on the active block [lo, hi]. A subdiagonal entry is negligible
114    // next to its two diagonal neighbours. When an eigenvalue takes more than ten iterations, it
115    // is also negligible next to the norm of the matrix (a normwise backward error of one ulp):
116    // this deflates clusters of tiny eigenvalues, such as the zero eigenvalues of a low-rank
117    // matrix, whose diagonal entries shrink with the subdiagonal ones.
118    let ulp = f64::EPSILON;
119    let frobenius = h.norm_l2();
120    let mut hi = n - 1;
121    let max_iter = 30 * n.max(10);
122    let mut total = 0;
123    loop {
124        // Deflate negligible subdiagonal entries at the bottom.
125        let mut its = 0;
126        loop {
127            let mut lo = hi;
128            while lo > 0 {
129                let sub = h[(lo, lo - 1)].norm();
130                let mut scale = h[(lo - 1, lo - 1)].norm() + h[(lo, lo)].norm();
131                if scale == 0.0 {
132                    scale = h.norm_max();
133                }
134                if sub <= ulp * scale || (its >= 10 && sub <= ulp * frobenius) {
135                    h[(lo, lo - 1)] = ZERO;
136                    break;
137                }
138                lo -= 1;
139            }
140            if lo == hi {
141                break; // h[hi][hi] has converged
142            }
143            total += 1;
144            if total > max_iter {
145                return Err(DenseError::Schur);
146            }
147            // Shift: eigenvalue of the trailing 2×2 block closest to its last entry, or an
148            // exceptional shift every 10 iterations.
149            let shift = if its > 0 && its % 10 == 0 {
150                h[(hi, hi)] + c64::new(0.75 * h[(hi, hi - 1)].norm(), 0.0)
151            } else {
152                let (aa, bb, cc, dd) = (h[(hi - 1, hi - 1)], h[(hi - 1, hi)], h[(hi, hi - 1)], h[(hi, hi)]);
153                let half = (aa - dd) * 0.5;
154                let disc = (half * half + bb * cc).sqrt();
155                let (l1, l2) = ((aa + dd) * 0.5 + disc, (aa + dd) * 0.5 - disc);
156                if (l1 - dd).norm() < (l2 - dd).norm() { l1 } else { l2 }
157            };
158            // Bulge chase from lo to hi.
159            let (mut x, mut y) = (h[(lo, lo)] - shift, h[(lo + 1, lo)]);
160            for k in lo..hi {
161                if k > lo {
162                    x = h[(k, k - 1)];
163                    y = h[(k + 1, k - 1)];
164                }
165                let (c, s) = givens(x, y);
166                let first = if k > lo { k - 1 } else { lo };
167                rotate(&mut h, &mut q, k, c, s, first..n, 0..(k + 3).min(hi + 1));
168                if k > lo {
169                    h[(k + 1, k - 1)] = ZERO;
170                }
171            }
172            its += 1;
173        }
174        if hi == 0 {
175            break;
176        }
177        hi -= 1;
178    }
179    for j in 0..n {
180        for i in j + 1..n {
181            h[(i, j)] = ZERO;
182        }
183    }
184    Ok((q, h))
185}
186
187/// Swaps the adjacent eigenvalues `k`, `k + 1` of the Schur form `(t, q)` (LAPACK ztrexc).
188fn swap_adjacent(t: &mut Mat<c64>, q: &mut Mat<c64>, k: usize) {
189    let n = t.nrows();
190    let (t11, t22) = (t[(k, k)], t[(k + 1, k + 1)]);
191    let (c, s) = givens(t[(k, k + 1)], t22 - t11);
192    rotate(t, q, k, c, s, k + 2..n, 0..k);
193    t[(k, k)] = t22;
194    t[(k + 1, k + 1)] = t11;
195}
196
197/// Stable reordering of the Schur form `(t, q)` by increasing `keys`, by adjacent swaps on the
198/// whole matrix. Cheap when few eigenvalues move; [`partition`] is the fast way to move many.
199pub fn reorder(t: &mut Mat<c64>, q: &mut Mat<c64>, keys: &mut [usize]) {
200    for i in 1..keys.len() {
201        let mut j = i;
202        while j > 0 && keys[j - 1] > keys[j] {
203            swap_adjacent(t, q, j - 1);
204            keys.swap(j - 1, j);
205            j -= 1;
206        }
207    }
208}
209
210/// Moves the selected eigenvalues of the Schur form `(t, q)` to the leading positions, keeping
211/// the order among the selected and among the others (as LAPACK ztrsen). Returns their number.
212///
213/// Batches of up to `BATCH` eigenvalues move up together through windows of `WINDOW` positions;
214/// the rotations of a window are applied to the rest of `t` and to `q` as matrix products.
215pub fn partition(t: &mut Mat<c64>, q: &mut Mat<c64>, select: &[bool]) -> usize {
216    assert_eq!(select.len(), t.nrows(), "partition: one flag per eigenvalue");
217    let positions: Vec<usize> = (0..select.len()).filter(|&k| select[k]).collect();
218    let (mut placed, mut next) = (0, 0);
219    while next < positions.len() {
220        let first = positions[next];
221        if first == placed {
222            placed += 1;
223            next += 1;
224            continue;
225        }
226        // The batch: the next selected eigenvalues, spread over half a window at most. Those
227        // before it are in place, so everything between `placed` and the batch is unselected.
228        let mut k = 1;
229        while next + k < positions.len() && k < BATCH && positions[next + k] < first + WINDOW / 2 {
230            k += 1;
231        }
232        let batch = &positions[next..next + k];
233        let mut end = batch[k - 1] + 1;
234        let mut gathered = false;
235        loop {
236            let start = placed.max(end.saturating_sub(WINDOW));
237            let local: Vec<bool> = (start..end)
238                .map(|p| if gathered { p >= end - k } else { batch.binary_search(&p).is_ok() })
239                .collect();
240            window_partition(t, q, start, &local);
241            gathered = true;
242            if start == placed {
243                break;
244            }
245            end = start + k;
246        }
247        placed += k;
248        next += k;
249    }
250    positions.len()
251}
252
253/// Stable partition of the window `start..start + select.len()` of `t` (selected first). The
254/// swaps act on a copy of the diagonal block, their product `u` on the rest.
255fn window_partition(t: &mut Mat<c64>, q: &mut Mat<c64>, start: usize, select: &[bool]) {
256    let (n, w) = (t.nrows(), select.len());
257    let end = start + w;
258    let mut tw = t.as_ref().submatrix(start, start, w, w).to_owned();
259    let mut u = Mat::<c64>::identity(w, w);
260    let (mut target, mut swaps) = (0, 0);
261    for (j, &selected) in select.iter().enumerate() {
262        if selected {
263            for p in (target..j).rev() {
264                swap_adjacent(&mut tw, &mut u, p);
265                swaps += 1;
266            }
267            target += 1;
268        }
269    }
270    if swaps == 0 {
271        return;
272    }
273    t.as_mut().submatrix_mut(start, start, w, w).copy_from(&tw);
274    if end < n {
275        let right = t.as_ref().submatrix(start, end, w, n - end).to_owned();
276        let dst = t.as_mut().submatrix_mut(start, end, w, n - end);
277        matmul(dst, Accum::Replace, u.as_ref(), Op::Adjoint, right.as_ref(), Op::Plain, ONE);
278    }
279    if start > 0 {
280        let above = t.as_ref().submatrix(0, start, start, w).to_owned();
281        let dst = t.as_mut().submatrix_mut(0, start, start, w);
282        matmul(dst, Accum::Replace, above.as_ref(), Op::Plain, u.as_ref(), Op::Plain, ONE);
283    }
284    let m = q.nrows();
285    let cols = q.as_ref().submatrix(0, start, m, w).to_owned();
286    matmul(
287        q.as_mut().submatrix_mut(0, start, m, w),
288        Accum::Replace,
289        cols.as_ref(),
290        Op::Plain,
291        u.as_ref(),
292        Op::Plain,
293        ONE,
294    );
295}
296
297#[cfg(test)]
298mod tests {
299    use super::*;
300
301    fn test_matrix(n: usize) -> Mat<c64> {
302        Mat::from_fn(n, n, |i, j| {
303            c64::new(((i * 7 + j * 13) % 17) as f64 / 17.0 - 0.5, ((i * 3 + j * 5) % 11) as f64 / 11.0 - 0.5)
304        })
305    }
306
307    fn unitarity(q: &Mat<c64>) -> f64 {
308        let n = q.ncols();
309        (q.adjoint() * q - Mat::<c64>::identity(n, n)).norm_max()
310    }
311
312    fn check_schur(a: &Mat<c64>, q: &Mat<c64>, t: &Mat<c64>, tol: f64) {
313        let n = a.nrows();
314        let err = (q * t * q.adjoint() - a).norm_max();
315        assert!(err < tol && unitarity(q) < tol, "n {n}: {err:e}, {:e}", unitarity(q));
316        for j in 0..n {
317            for i in j + 1..n {
318                assert_eq!(t[(i, j)], ZERO);
319            }
320        }
321    }
322
323    /// Both Schur decompositions (in-house and the build's backend): `a = q t q†`, eigenvalues as
324    /// faer's.
325    #[test]
326    fn schur_decompositions() {
327        for n in [1usize, 2, 5, 40, 97, 200] {
328            let a = test_matrix(n);
329            for (name, (q, t)) in
330                [("in-house", schur(a.as_ref()).unwrap()), ("backend", crate::schur(a.as_ref()).unwrap())]
331            {
332                check_schur(&a, &q, &t, 1e-11);
333                let mut ours: Vec<c64> = (0..n).map(|k| t[(k, k)]).collect();
334                let mut theirs: Vec<c64> = a.eigenvalues().unwrap();
335                let key = |z: &c64| (z.re * 1e6).round() as i64 * 1_000_000_000 + (z.im * 1e6).round() as i64;
336                ours.sort_by_key(key);
337                theirs.sort_by_key(key);
338                assert!(
339                    ours.iter().zip(&theirs).all(|(x, y)| (x - y).norm() < 1e-9),
340                    "{name} n {n}: eigenvalues differ"
341                );
342            }
343        }
344    }
345
346    /// The blocked partition moves the selected eigenvalues to the front, stably, and the leading
347    /// Schur vectors span their invariant subspace; the result matches the unblocked swaps.
348    #[test]
349    fn partition_and_reorder() {
350        for n in [1usize, 2, 5, 40, 97, 300] {
351            let a = test_matrix(n);
352            let (q0, t0) = crate::schur(a.as_ref()).unwrap();
353            let eig: Vec<c64> = (0..n).map(|k| t0[(k, k)]).collect();
354            let mut mods: Vec<f64> = eig.iter().map(|z| z.norm()).collect();
355            mods.sort_by(|a, b| a.partial_cmp(b).unwrap());
356            for cut in [mods[n / 2], mods[n / 5], mods[(4 * n) / 5]] {
357                let select: Vec<bool> = eig.iter().map(|z| z.norm() < cut).collect();
358                let (mut q, mut t) = (q0.clone(), t0.clone());
359                let m = partition(&mut t, &mut q, &select);
360                check_schur(&a, &q, &t, 1e-10);
361                let expected: Vec<c64> = eig
362                    .iter()
363                    .zip(&select)
364                    .filter(|(_, s)| **s)
365                    .chain(eig.iter().zip(&select).filter(|(_, s)| !**s))
366                    .map(|(z, _)| *z)
367                    .collect();
368                assert!((0..n).all(|k| (t[(k, k)] - expected[k]).norm() < 1e-9 * (1.0 + expected[k].norm())));
369                let q1 = q.as_ref().submatrix(0, 0, n, m).to_owned();
370                let t11 = t.as_ref().submatrix(0, 0, m, m).to_owned();
371                assert!((&a * &q1 - &q1 * &t11).norm_max() < 1e-10, "n {n}: invariant subspace");
372                // Unblocked swaps give the same subspace.
373                let (mut qu, mut tu) = (q0.clone(), t0.clone());
374                let mut keys: Vec<usize> = select.iter().map(|&s| (!s) as usize).collect();
375                reorder(&mut tu, &mut qu, &mut keys);
376                let qu1 = qu.as_ref().submatrix(0, 0, n, m).to_owned();
377                let overlap = qu1.adjoint() * &q1; // unitary when the subspaces agree
378                assert!(unitarity(&overlap) < 1e-9, "n {n}: subspaces differ");
379            }
380        }
381    }
382
383    #[test]
384    #[ignore]
385    fn timing() {
386        for n in [256usize, 512, 1024] {
387            let a = test_matrix(n);
388            let t0 = std::time::Instant::now();
389            let (q0, t0m) = crate::schur(a.as_ref()).unwrap();
390            let ts = t0.elapsed();
391            let mut mods: Vec<f64> = (0..n).map(|k| t0m[(k, k)].norm()).collect();
392            mods.sort_by(|a, b| a.partial_cmp(b).unwrap());
393            let select: Vec<bool> = (0..n).map(|k| t0m[(k, k)].norm() < mods[n / 2]).collect();
394            let (mut q, mut t) = (q0.clone(), t0m.clone());
395            let start = std::time::Instant::now();
396            partition(&mut t, &mut q, &select);
397            let tp = start.elapsed();
398            let (mut q, mut t) = (q0.clone(), t0m.clone());
399            let mut keys: Vec<usize> = select.iter().map(|&s| (!s) as usize).collect();
400            let start = std::time::Instant::now();
401            reorder(&mut t, &mut q, &mut keys);
402            let tr = start.elapsed();
403            println!(
404                "n {n}: schur ({}) {ts:.1?} | half to the front: blocked {tp:.1?}, unblocked {tr:.1?}",
405                crate::BACKEND
406            );
407        }
408    }
409}