Symmetric and general eigensolvers
| Problem | Compute all eigenvalues, and optionally eigenvectors, of a dense Hermitian (real symmetric) or general square matrix, real or complex |
| Devised by | Householder tridiagonalisation: Alston Householder (1958), Wallace Givens (1954, by rotations); the implicit QL algorithm: Hilary Bowdler, Roger Martin, Christian Reinsch and James Wilkinson (1968); Hessenberg reduction and the implicit double-shift QR step: John Francis (1961); balancing: Beresford Parlett and Christian Reinsch (1969) |
| Accuracy | Backward stable: the eigenvalues of with . For Hermitian matrices this bounds the eigenvalue errors by ; for non-normal matrices the errors can be much larger |
| Cost | Hermitian: flops for eigenvalues, about with vectors. General: about for eigenvalues, with vectors |
| Read first | Eigenvalue algorithms: power iteration, Jacobi and the QR algorithm |
| API | Eigh, EigValsh, Eig, EigVals |
Overview
The QR algorithm of the previous entry is the core of every dense eigensolver, but applied to a full matrix it costs per step. Production codes add three ingredients. A one-time reduction by orthogonal similarity to tridiagonal form (Hermitian) or upper Hessenberg form (general) makes each QR step or , because the QR algorithm preserves these forms. Implicit shifted steps apply the shift without ever forming , and for real matrices use complex conjugate pairs of shifts while staying in real arithmetic. Balancing rescales a general matrix to reduce its norm before iterating.
Symmetric and general problems behave very differently. Hermitian matrices have real eigenvalues and an orthonormal basis of eigenvectors, and their eigenvalues are perfectly conditioned: a perturbation of size moves them by at most . General matrices can have complex eigenvalues, may lack a full set of eigenvectors, and their eigenvalues can be extraordinarily sensitive to perturbations.
Where it is used
Dense eigensolvers are the engines behind many other chapters.
- Quantum chemistry and physics. The energy levels of a molecule or lattice are eigenvalues of its Hamiltonian matrix.
- Structural dynamics and control. Modal analysis of structures, and stability analysis of linear systems.
- Data science. PCA, spectral clustering, and the singular value decomposition use symmetric eigensolvers.
- Signal processing. Direction-finding algorithms such as MUSIC use eigendecomposition of a covariance matrix.
History
Wallace Givens (1954) reduced symmetric matrices to tridiagonal form by rotations, and Alston Householder (1958) by reflections, at half the cost. The tridiagonal QL algorithm, the QR algorithm run from the bottom up, was published with ALGOL procedures by Hilary Bowdler, Roger Martin, Christian Reinsch and James Wilkinson in 1968, in the series that became the Handbook for Automatic Computation (1971) and then the EISPACK library. John Francis’s 1961 papers already contained the Hessenberg reduction and the implicit double-shift step for real matrices. Beresford Parlett and Christian Reinsch (1969) introduced balancing. LAPACK (1992) blocked the reductions; Karen Braman, Ralph Byers and Roy Mathias (2002) introduced the small-bulge multishift QR algorithm with aggressive early deflation, which makes LAPACK much faster on large general matrices.
The idea
Hermitian matrices: tridiagonalisation and QL
The QR algorithm applied to a full matrix costs per step. Production solvers avoid that with a two-phase plan: first transform the matrix, once and in a finite number of operations, to a form with many zeros that the QR algorithm preserves; then iterate cheaply on that form.
Phase one: reduction to tridiagonal form. It would be ideal to reduce the matrix straight to diagonal form, but no finite sequence of operations can do that (it would amount to a formula for the roots of a polynomial). The next best thing is tridiagonal form, nonzero only on the main diagonal and the two diagonals beside it. Householder reflections achieve it. In the QR factorisation a reflection applied from the left zeroes a column below the diagonal. Here each reflection must be applied from both sides, , to keep the transformation a similarity, and so it is designed to zero the column below the subdiagonal; applying it from the right then leaves those zeros intact (it mixes only columns , so the first column is not touched). The result is again Hermitian, so zeros in the part of the column below the subdiagonal are mirrored by zeros in the matching part of the row to the right of the superdiagonal. After reflections is tridiagonal, at a cost of flops. For a complex Hermitian matrix, a diagonal unitary scaling then makes the off-diagonal of real and non-negative, so the rest of the work is in real arithmetic.
Phase two: iteration on the tridiagonal matrix. A shifted QR step applied to a tridiagonal matrix gives another tridiagonal matrix, and it can be carried out with plane (Givens) rotations in operations instead of . The library uses the implicit QL algorithm, a variant that works from the opposite corner of the matrix. “Implicit” means that the shift is never actually subtracted from the diagonal: the first rotation is computed from the shifted matrix, and the remaining rotations are determined by the requirement to restore tridiagonal form, which they do by chasing a single unwanted nonzero entry along the diagonal and off the end. About two steps per eigenvalue are needed, as before.
The eigenvectors of are times the product of the rotations. is accumulated in blocks (in the compact WY form, which represents a product of reflections so that it can be applied by matrix multiplications), and the product is formed with the matrix-multiply kernel.
General matrices: Hessenberg reduction and Francis’s algorithm
A nonsymmetric matrix is handled by the same two-phase plan, with three complications.
The reduced form is Hessenberg. Without symmetry, the reflections that zero a column below the subdiagonal do nothing for the corresponding row. The result is upper Hessenberg form: zero below the first subdiagonal, full above. The QR algorithm preserves this form too, and a step costs .
Real matrices can have complex eigenvalues. They come in conjugate pairs. A real shift can never converge to a complex eigenvalue, and a complex shift would force the whole computation into complex arithmetic. Francis’s double-shift step resolves the dilemma by taking two steps at once, with a conjugate pair of shifts , the eigenvalues of the trailing block. The combined effect of the two steps is governed by the matrix , which is real because the shifts are conjugates. The step is carried out implicitly: compute only the first column of that product, apply a reflection determined by it, which disturbs the Hessenberg form with a small “bulge” of unwanted nonzeros, and chase the bulge down the matrix with further reflections until it falls off the bottom. A result called the implicit Q theorem guarantees that the outcome is the same as two explicit shifted QR steps, although no complex number ever appears.
The limit is triangular, not diagonal. A nonsymmetric matrix cannot in general be diagonalised by an orthogonal similarity, but it can always be made upper triangular. In real arithmetic the iteration converges to the real Schur form, which is “quasi-triangular”: its diagonal carries blocks for real eigenvalues and blocks for complex pairs. The library then triangularises each block to obtain the complex Schur form , with upper triangular and the eigenvalues on its diagonal. (Complex input matrices use single shifts and Givens rotations throughout.) The eigenvectors of a triangular matrix follow by back substitution, and multiplying by maps them back to eigenvectors of .
Balancing
The rounding errors of the QR algorithm are proportional to . Balancing replaces by for a diagonal
chosen so that each row and the corresponding column have similar norms. With the entries of powers of 2 the
eigenvalues are unchanged, not even rounded, and the norm can fall by many orders of magnitude. It matters most for
badly scaled matrices: without it, this library’s solver returned 18 zeros and a wild complex pair for the companion
matrix of Wilkinson’s polynomial (polynomial roots); it is
now always applied, as in LAPACK’s geev.
Accuracy and conditioning
Both solvers are backward stable:
Table 7.8. Residuals and orthogonality of the production eigensolvers.
| order | symmetric: | symmetric: | general: |
|---|---|---|---|
| 50 | 2.2e-15 | 1.6e-14 | 3.2e-15 |
| 200 | 4.1e-15 | 6.8e-14 | 5.6e-15 |
| 500 | 6.3e-15 | 2.3e-13 | 7.6e-15 |
For Hermitian matrices, backward stability guarantees accurate eigenvalues, because eigenvalues of Hermitian matrices move by no more than the perturbation (Weyl’s theorem). For non-normal matrices there is no such guarantee: the sensitivity of an eigenvalue is measured by the angle between its left and right eigenvectors, and can be enormous. The Grcar matrix, a Toeplitz matrix with on the subdiagonal and on the diagonal and three superdiagonals, is the classic example:
Figure 7.5. Eigenvalues of the Grcar matrix.
Perturbations of size move its eigenvalues by up to , and even the computed eigenvalues of the unperturbed matrix are those of a matrix within rounding error of it. The eigenvalues of its symmetric part, on the other hand, do not move visibly. For non-normal matrices the pseudospectra, the sets of eigenvalues of all nearby matrices, are often more meaningful than the eigenvalues themselves.
Speed
Figure 7.6. Eigensolver speed.
The reduction to tridiagonal form makes the production symmetric solver roughly two orders of magnitude faster than the reference QR algorithm on the full matrix at . Against OpenBLAS’s LAPACK, the symmetric solver is about as fast. The general solver is as fast for small matrices and slower for large ones, where LAPACK’s blocked multishift QR pays off.
Aggressive early deflation
Since 2.21.0, active blocks of order 75 or more use aggressive early deflation (Braman, Byers and Mathias, 2002; LAPACK’s dlaqr2).
- The trailing window of order (10 to 64, by LAPACK’s defaults) is reduced to real Schur form, .
- Its coupling to the rest of the matrix becomes a single column, the spike , where is the sub-diagonal entry above the window.
- An eigenvalue at the bottom of whose spike entries are below times its size has converged and is deflated at once, often long before the sub-diagonal entries of ordinary deflation become small.
- Undeflatable eigenvalues are moved to the top of the window by block swaps, the window is returned to Hessenberg form, and is applied to the rest of the matrix and to the Schur vectors.
The undeflated eigenvalues then serve as shifts for several double-shift sweeps.
/// Aggressive early deflation (Braman, Byers and Mathias, 2002; LAPACK's `dlaqr2`) on the
/// trailing `nw × nw` window of the active block `l..hi`. The window is reduced to real Schur
/// form `T = Vᵀ W V`; the coupling to the rest is then the *spike* `s Vᵀ e₁`, `s` the sub-diagonal
/// entry above the window. Eigenvalues at the bottom of `T` whose spike entries are negligible
/// have converged and are deflated; the others are moved to the top by block swaps. The window is
/// returned to Hessenberg form and `V` applied to the rest of `H` and to `Z`. Returns the number
/// of deflated eigenvalues and the undeflated ones as shift pairs `(sum, product)`.
#[allow(clippy::too_many_arguments)]
fn aed(a: &mut Mat<f64>, zt: Option<&mut Mat<f64>>, l: usize, hi: usize, nw: usize, full: bool, pair: &mut [bool], shift_total: f64) -> Result<(usize, Vec<(f64, f64)>)> {
use crate::reorder::{block_eigs, house, reflect_cols, reflect_rows, swap_schur};
use ndarray::Array2;
let n = a.rows;
let kw = l.max(hi - nw);
let jw = hi - kw;
let spike_scale = if kw > l { a.data[kw * n + kw - 1] } else { 0.0 };
let mut win = Mat::<f64>::zeros(jw, jw);
for i in 0..jw {
for j in 0..jw {
// Entries below the sub-diagonal are the sweeps' scratch space (as in EISPACK's
// hqr), not part of the matrix.
*win.at_mut(i, j) = if i > j + 1 { 0.0 } else { a.data[(kw + i) * n + kw + j] };
}
}
let (tm, vm, _) = real_schur_unbalanced(&win)?;
let mut t = Array2::from_shape_fn((jw, jw), |(i, j)| tm.at(i, j));
let mut v = Array2::from_shape_fn((jw, jw), |(i, j)| vm.at(i, j));
// Deflation check from the bottom; undeflatable blocks move to position `ilst`.
let eps = f64::EPSILON;
let small = f64::MIN_POSITIVE * (n as f64 / eps);
let mut ns = jw;
let mut ilst = 0;
while ilst < ns {
let two = ns >= 2 && t[(ns - 1, ns - 2)] != 0.0;
let size = if two { 2 } else { 1 };
let top = ns - size;
let deflatable = if two {
let size_scale = t[(ns - 1, ns - 1)].abs() + t[(ns - 1, ns - 2)].abs().sqrt() * t[(ns - 2, ns - 1)].abs().sqrt();
let size_scale = if size_scale == 0.0 { spike_scale.abs() } else { size_scale };
(spike_scale * v[(0, ns - 1)]).abs().max((spike_scale * v[(0, ns - 2)]).abs()) <= small.max(eps * size_scale)
} else {
let size_scale = if t[(ns - 1, ns - 1)] == 0.0 { spike_scale.abs() } else { t[(ns - 1, ns - 1)].abs() };
(spike_scale * v[(0, ns - 1)]).abs() <= small.max(eps * size_scale)
};
if deflatable {
ns -= size;
continue;
}
// Move the block at `top` up to `ilst` by adjacent swaps.
let mut k = top;
let mut moved = true;
while k > ilst {
let above = if k >= 2 && t[(k - 1, k - 2)] != 0.0 { 2 } else { 1 };
if !swap_schur(&mut t, &mut v, k - above, above, size) {
moved = false;
break;
}
k -= above;
}
if !moved {
break;
}
ilst += size;
}
let nd = jw - ns;
// The undeflated eigenvalues, as shift pairs.
let mut shifts = Vec::new();
let mut reals = Vec::new();
let mut k = 0;
while k < ns {
let two = k + 1 < ns && t[(k + 1, k)] != 0.0;
let ev = block_eigs(&t, k, if two { 2 } else { 1 });
if two && ev[0].im != 0.0 {
shifts.push((2.0 * ev[0].re, ev[0].norm_sqr()));
} else {
reals.extend(ev.iter().map(|z| z.re));
}
k += if two { 2 } else { 1 };
}
for p in reals.chunks(2) {
if p.len() == 2 {
shifts.push((p[0] + p[1], p[0] * p[1]));
}
}
if nd == 0 && spike_scale != 0.0 {
return Ok((0, shifts));
}
// The spike, with the deflated part zero; return the undeflated part to Hessenberg form.
let mut spike: Vec<f64> = (0..jw).map(|i| if i < ns { spike_scale * v[(0, i)] } else { 0.0 }).collect();
if ns > 1 && spike_scale != 0.0 {
let (u, beta) = house(&spike[..ns]);
reflect_rows(&mut t, &u, beta, 0);
reflect_cols(&mut t, &u, beta, 0);
reflect_cols(&mut v, &u, beta, 0);
let s0: f64 = u.iter().zip(&spike).map(|(a, b)| a * b).sum();
spike[0] -= beta * s0;
for item in spike.iter_mut().take(ns).skip(1) {
*item = 0.0;
}
for c in 0..ns.saturating_sub(2) {
let x: Vec<f64> = (c + 1..ns).map(|i| t[(i, c)]).collect();
let (u, beta) = house(&x);
reflect_rows(&mut t, &u, beta, c + 1);
reflect_cols(&mut t, &u, beta, c + 1);
reflect_cols(&mut v, &u, beta, c + 1);
for i in c + 2..ns {
t[(i, c)] = 0.0;
}
}
}
// Write the window back and apply V to the rest of H and to Z.
for i in 0..jw {
for j in 0..jw {
a.data[(kw + i) * n + kw + j] = if j + 1 < i { 0.0 } else { t[(i, j)] };
}
}
if kw > l {
for i in 0..jw {
a.data[(kw + i) * n + kw - 1] = if i == 0 { spike[0] } else { 0.0 };
}
}
let r0 = if full { 0 } else { l };
// The window's orthogonal factor V, applied to the rest of H (rows above, columns to the
// right) and to Zᵀ by matrix products.
let vv: Vec<f64> = (0..jw * jw).map(|x| v[(x / jw, x % jw)]).collect();
let jwi = jw as isize;
if kw > r0 {
let nr = kw - r0;
let mut tmp = vec![0.0f64; nr * jw];
// SAFETY: `tmp` and `vv` are separate buffers from `a`; strides follow the shapes.
unsafe { f64::gemm_sub(nr, jw, jw, a.data.as_ptr().add(r0 * n + kw), n as isize, 1, vv.as_ptr(), jwi, 1, tmp.as_mut_ptr(), jwi, 1) };
for (r, row) in tmp.chunks_exact(jw).enumerate() {
for (dst, &x) in a.data[(r0 + r) * n + kw..(r0 + r) * n + hi].iter_mut().zip(row) {
*dst = -x;
}
}
}
let c1 = if full { n } else { hi };
if c1 > hi {
let nc = c1 - hi;
let mut tmp = vec![0.0f64; jw * nc];
// SAFETY: as above (Vᵀ is read as V with its strides swapped).
unsafe { f64::gemm_sub(jw, jw, nc, vv.as_ptr(), 1, jwi, a.data.as_ptr().add(kw * n + hi), n as isize, 1, tmp.as_mut_ptr(), nc as isize, 1) };
for (i, row) in tmp.chunks_exact(nc).enumerate() {
for (dst, &x) in a.data[(kw + i) * n + hi..(kw + i) * n + c1].iter_mut().zip(row) {
*dst = -x;
}
}
}
if let Some(zt) = zt {
let m = zt.cols;
let mut tmp = vec![0.0f64; jw * m];
// SAFETY: as above.
unsafe { f64::gemm_sub(jw, jw, m, vv.as_ptr(), 1, jwi, zt.data.as_ptr().add(kw * m), m as isize, 1, tmp.as_mut_ptr(), m as isize, 1) };
for (dst, &x) in zt.data[kw * m..hi * m].iter_mut().zip(&tmp) {
*dst = -x;
}
}
// The deflated eigenvalues are final: mark complex pairs and undo the accumulated shift.
let mut k = kw + ns;
while k < hi {
if k + 1 < hi && a.data[(k + 1) * n + k] != 0.0 {
pair[k] = true;
a.data[k * n + k] += shift_total;
a.data[(k + 1) * n + k + 1] += shift_total;
k += 2;
} else {
a.data[k * n + k] += shift_total;
k += 1;
}
}
Ok((nd, shifts))
}
One subtlety: the double-shift sweeps leave stale bulge entries below the sub-diagonal, which EISPACK’s algorithm never reads again, so the window must be read as a Hessenberg matrix.
On this book’s build machine, against OpenBLAS (single-threaded), the change took the general eigenproblem with eigenvectors at from 3.3 to 2.3 times LAPACK’s time, and at from 2.3 to about 1.5 times; timings there vary by up to 20 % between runs.
Multi-bulge sweeps and blocked reduction (2.32)
Release 2.32 closed most of the rest of the gap with three changes, each checked against the version it replaced.
- Pipelined bulges. The shifts that aggressive early deflation returns are used by one sweep each. Sweep may run its reflector at row once the previous sweep has finished row : the rows and columns they touch are then disjoint, so the result equals that of the sweeps in sequence (a test compares them to rounding). The bulges follow each other along the diagonal.
- Deferred updates. The bulges advance in chunks. Within a chunk the reflectors are applied only inside a window of rows and columns, and their product is accumulated there. The rest of the matrix and the Schur vectors are then updated by three matrix products with , where one reflector at a time streams through the whole matrix. This is the idea of LAPACK’s
dlaqr5. - Blocked Hessenberg reduction and real eigenvectors. The reduction works on panels of 32 columns (
dlahr2): half of its work becomes matrix multiplication. The window’s orthogonal factor in early deflation is applied by matrix products too. For a real matrix the eigenvectors are found from the real Schur form by back-substitution through its and blocks, and is a real product, where the complex Schur form needed four times the arithmetic.
/// Several implicit double-shift sweeps at once (the idea of LAPACK's `laqr5`). Sweep `s` is the
/// one [`sweep`] would do with shifts `shifts[s] = (x, y, w)`, after the sweeps before it; its
/// reflector at row `k` may run as soon as the previous sweep has passed row `k + 4`, so the
/// bulges follow each other four rows apart, `SPACING`, along the diagonal. They advance in
/// chunks. Within a chunk every reflector is applied only inside a window of rows and columns
/// (the entries the next reflectors read), and the product `Q` of the chunk's reflectors is
/// accumulated on the window; the rest of the matrix and `Zᵀ` are then updated with three matrix
/// products by `Q`, where applying the reflectors one by one would stream through the whole
/// matrix three times for each of them.
///
/// Unlike [`sweep`], every bulge starts at the top of the active block `l..=nn`.
#[allow(clippy::too_many_arguments)]
fn multi_sweep(a: &mut Mat<f64>, mut zt: Option<&mut Mat<f64>>, l: usize, nn: usize, shifts: &[(f64, f64, f64)], full: bool) {
let n = a.rows;
let ce = if full { n } else { nn + 1 };
let rs = if full { 0 } else { l };
macro_rules! at {
($i:expr, $j:expr) => {
a.data[($i) * n + ($j)]
};
}
// The fill below the sub-diagonal that earlier sweeps leave behind.
for i in l..nn - 1 {
at!(i + 2, i) = 0.0;
if i != l {
at!(i + 2, i - 1) = 0.0;
}
}
let m = shifts.len();
let ramp = SPACING * (m - 1);
let mut tau0 = l;
while tau0 < nn + ramp {
let kmin = l.max(tau0.saturating_sub(ramp));
let kmax = (nn - 1).min(tau0 + CHUNK - 1);
if kmin > kmax {
tau0 += CHUNK;
continue;
}
let w0 = l.max(kmin.saturating_sub(1));
let w1 = (nn + 1).min(kmax + 4);
let w = w1 - w0;
let mut q_acc = Mat::<f64>::identity(w);
for tau in tau0..tau0 + CHUNK {
for (si, &(sx, sy, sw)) in shifts.iter().enumerate() {
let Some(k) = tau.checked_sub(SPACING * si) else { continue };
if k < l || k >= nn {
continue;
}
let last = k + 1 == nn;
let (mut p, mut q, mut r, x);
if k == l {
let z = at!(l, l);
let (rr, ss) = (sx - z, sy - z);
p = (rr * ss - sw) / at!(l + 1, l) + at!(l, l + 1);
q = at!(l + 1, l + 1) - z - rr - ss;
r = at!(l + 2, l + 1);
x = p.abs() + q.abs() + r.abs();
p /= x;
q /= x;
r /= x;
} else {
p = at!(k, k - 1);
q = at!(k + 1, k - 1);
r = if last { 0.0 } else { at!(k + 2, k - 1) };
at!(k + 1, k - 1) = 0.0;
if !last {
at!(k + 2, k - 1) = 0.0;
}
x = p.abs() + q.abs() + r.abs();
if x != 0.0 {
p /= x;
q /= x;
r /= x;
}
}
let sgn = (p * p + q * q + r * r).sqrt().copysign(p);
if sgn == 0.0 {
continue;
}
if k != l {
at!(k, k - 1) = -sgn * x;
}
p += sgn;
let (hx, hy, hz) = (p / sgn, q / sgn, r / sgn);
q /= p;
r /= p;
for j in k..w1 {
let mut t = at!(k, j) + q * at!(k + 1, j);
if !last {
t += r * at!(k + 2, j);
at!(k + 2, j) -= t * hz;
}
at!(k + 1, j) -= t * hy;
at!(k, j) -= t * hx;
}
for i in w0..=nn.min(k + 3) {
let mut t = hx * at!(i, k) + hy * at!(i, k + 1);
if !last {
t += hz * at!(i, k + 2);
at!(i, k + 2) -= t * r;
}
at!(i, k + 1) -= t * q;
at!(i, k) -= t;
}
// Q ← Q P.
let kk = k - w0;
for row in q_acc.data.chunks_exact_mut(w) {
let mut t = hx * row[kk] + hy * row[kk + 1];
if !last {
t += hz * row[kk + 2];
row[kk + 2] -= t * r;
}
row[kk + 1] -= t * q;
row[kk] -= t;
}
}
}
// The rest of the matrix and Zᵀ: rows w0..w1 ← Qᵀ ·, and columns w0..w1 ← · Q.
let wi = w as isize;
let rest = ce.saturating_sub(w1);
if rest > 0 {
let mut tmp = vec![0.0f64; w * rest];
// SAFETY: `tmp` and `q_acc` are separate buffers from `a`; strides follow the shapes
// (Qᵀ is read as Q with its strides swapped).
unsafe { f64::gemm_sub(w, w, rest, q_acc.data.as_ptr(), 1, wi, a.data.as_ptr().add(w0 * n + w1), n as isize, 1, tmp.as_mut_ptr(), rest as isize, 1) };
for (r, row) in tmp.chunks_exact(rest).enumerate() {
for (dst, &v) in a.data[(w0 + r) * n + w1..(w0 + r) * n + ce].iter_mut().zip(row) {
*dst = -v;
}
}
}
let top = w0 - rs;
if top > 0 {
let mut tmp = vec![0.0f64; top * w];
// SAFETY: as above.
unsafe { f64::gemm_sub(top, w, w, a.data.as_ptr().add(rs * n + w0), n as isize, 1, q_acc.data.as_ptr(), wi, 1, tmp.as_mut_ptr(), wi, 1) };
for (r, row) in tmp.chunks_exact(w).enumerate() {
for (dst, &v) in a.data[(rs + r) * n + w0..(rs + r) * n + w1].iter_mut().zip(row) {
*dst = -v;
}
}
}
if let Some(zt) = zt.as_deref_mut() {
let mut tmp = vec![0.0f64; w * n];
// SAFETY: as above.
unsafe { f64::gemm_sub(w, w, n, q_acc.data.as_ptr(), 1, wi, zt.data.as_ptr().add(w0 * n), n as isize, 1, tmp.as_mut_ptr(), n as isize, 1) };
for (dst, &v) in zt.data[w0 * n..w1 * n].iter_mut().zip(&tmp) {
*dst = -v;
}
}
tau0 += CHUNK;
}
}
/// Eigenvalues and unit-norm eigenvectors of a real matrix, without leaving real arithmetic until
/// the end (LAPACK's `geev`): the eigenvectors of the quasi-triangular Schur factor `T` by back
/// substitution through its 1 × 1 and 2 × 2 diagonal blocks (a real vector for a real eigenvalue,
/// a complex one for the first of a conjugate pair), and the products `Z X` as real matrix
/// multiplications on the real and imaginary parts. A conjugate pair's eigenvalues come with the
/// positive imaginary part first.
fn eig_real(a: &Mat<f64>) -> Result<(Vec<C>, Mat<C>)> {
require_square(a.rows, a.cols)?;
let n = a.rows;
let mut h = a.clone();
let d = balance(&mut h);
let mut zt = hessenberg(&mut h, true).expect("Z requested");
let pair = real_schur(&mut h, Some(&mut zt))?;
let t = &h;
let norm = t.data.iter().fold(0.0f64, |m, v| m.max(v.abs())).max(f64::MIN_POSITIVE);
let small = f64::EPSILON * norm;
let guard = |z: C| if z.norm() < small { C::new(small, 0.0) } else { z };
// The eigenvalues.
let mut values = vec![C::new(0.0, 0.0); n];
let mut k = 0;
while k < n {
if pair[k] {
let (p, q, r, s) = (t.at(k, k), t.at(k, k + 1), t.at(k + 1, k), t.at(k + 1, k + 1));
let half = (p - s) * 0.5;
let im = (-(half * half + q * r)).max(0.0).sqrt();
values[k] = C::new((p + s) * 0.5, im);
values[k + 1] = C::new((p + s) * 0.5, -im);
k += 2;
} else {
values[k] = C::new(t.at(k, k), 0.0);
k += 1;
}
}
// Eigenvectors of T, as rows of Xᵗ: row k is the real vector for a real eigenvalue, and the
// real part (row k) and imaginary part (row k + 1) of the vector of a pair's first eigenvalue.
let mut xt = Mat::<f64>::zeros(n, n);
let mut k = 0;
while k < n {
if !pair[k] {
let lambda = t.at(k, k);
let x = &mut xt.data[k * n..(k + 1) * n];
x[k] = 1.0;
let mut j = k as isize - 1;
while j >= 0 {
let ju = j as usize;
let (j0, size) = if ju > 0 && pair[ju - 1] { (ju - 1, 2) } else { (ju, 1) };
let row_sum = |i: usize, x: &[f64]| (j0 + size..=k).map(|m| t.at(i, m) * x[m]).sum::<f64>();
if size == 1 {
let mut den = t.at(j0, j0) - lambda;
if den.abs() < small {
den = small;
}
x[j0] = -row_sum(j0, x) / den;
} else {
let (r0, r1) = (-row_sum(j0, x), -row_sum(j0 + 1, x));
let (a00, a01, a10, a11) = (t.at(j0, j0) - lambda, t.at(j0, j0 + 1), t.at(j0 + 1, j0), t.at(j0 + 1, j0 + 1) - lambda);
let mut det = a00 * a11 - a01 * a10;
if det.abs() < small * small {
det = small * small;
}
x[j0] = (r0 * a11 - a01 * r1) / det;
x[j0 + 1] = (a00 * r1 - a10 * r0) / det;
}
j = j0 as isize - 1;
}
k += 1;
} else {
let lambda = values[k];
let (p, q) = (t.at(k, k), t.at(k, k + 1));
let mut x = vec![C::new(0.0, 0.0); n];
x[k] = C::new(q, 0.0);
x[k + 1] = C::new(lambda.re - p, lambda.im);
let top = k + 1;
let mut j = k as isize - 1;
while j >= 0 {
let ju = j as usize;
let (j0, size) = if ju > 0 && pair[ju - 1] { (ju - 1, 2) } else { (ju, 1) };
let row_sum = |i: usize, x: &[C]| (j0 + size..=top).fold(C::new(0.0, 0.0), |s, m| s + x[m] * t.at(i, m));
if size == 1 {
x[j0] = -row_sum(j0, &x) / guard(C::new(t.at(j0, j0), 0.0) - lambda);
} else {
let (r0, r1) = (-row_sum(j0, &x), -row_sum(j0 + 1, &x));
let (a00, a01, a10, a11) = (C::new(t.at(j0, j0), 0.0) - lambda, C::new(t.at(j0, j0 + 1), 0.0), C::new(t.at(j0 + 1, j0), 0.0), C::new(t.at(j0 + 1, j0 + 1), 0.0) - lambda);
let det = guard(a00 * a11 - a01 * a10);
x[j0] = (r0 * a11 - a01 * r1) / det;
x[j0 + 1] = (a00 * r1 - a10 * r0) / det;
}
j = j0 as isize - 1;
}
for (m, z) in x.iter().enumerate() {
xt.data[k * n + m] = z.re;
xt.data[(k + 1) * n + m] = z.im;
}
k += 2;
}
}
// W = −Z X, a real matrix product (Zᵀ and Xᵗ are read through transposed strides).
let mut w = Mat::<f64>::zeros(n, n);
if n > 0 {
let n_ = n as isize;
// SAFETY: three distinct n × n buffers; (rs, cs) = (1, n) reads Zᵀ as Z and Xᵗ as X.
unsafe { f64::gemm_sub(n, n, n, zt.data.as_ptr(), 1, n_, xt.data.as_ptr(), 1, n_, w.data.as_mut_ptr(), n_, 1) };
}
// Undo the balancing, normalise, and assemble the complex eigenvectors.
let mut vectors = Mat::<C>::zeros(n, n);
let mut k = 0;
while k < n {
if pair[k] {
let mut sq = 0.0;
for i in 0..n {
let (re, im) = (-w.data[i * n + k] * d[i], -w.data[i * n + k + 1] * d[i]);
sq += re * re + im * im;
}
let s = if sq > 0.0 { 1.0 / sq.sqrt() } else { 1.0 };
for i in 0..n {
let v = C::new(-w.data[i * n + k] * d[i] * s, -w.data[i * n + k + 1] * d[i] * s);
vectors.data[i * n + k] = v;
vectors.data[i * n + k + 1] = v.conj();
}
k += 2;
} else {
let sq: f64 = (0..n).map(|i| (w.data[i * n + k] * d[i]).powi(2)).sum();
let s = if sq > 0.0 { 1.0 / sq.sqrt() } else { 1.0 };
for i in 0..n {
vectors.data[i * n + k] = C::new(-w.data[i * n + k] * d[i] * s, 0.0);
}
k += 1;
}
}
Ok((values, vectors))
}
With eigenvectors the library now takes about 1.1 to 1.3 times LAPACK’s time at and about 1.8 to 1.9 times at (from 2.1 and 3.3). What remains is mostly the matrix-vector half of the Hessenberg reduction, and the early-deflation window’s own Schur decomposition, which is done unblocked.
Algorithm
eigh, for a Hermitian matrix.
- Tridiagonalise. Apply Householder reflections from both sides, giving .
- Make real. For a complex matrix, scale by a diagonal unitary matrix so that the off-diagonal entries become real and non-negative.
- Diagonalise by the implicit QL algorithm with shifts. If eigenvectors are wanted, accumulate the rotations into a matrix . Whenever an off-diagonal entry becomes negligible the problem splits there.
- Sort the eigenvalues into ascending order, permuting the columns of to match.
- Form the eigenvectors as the product .
eig, for a general matrix.
- Balance by a diagonal similarity with powers of 2.
- Reduce to Hessenberg form by Householder reflections, accumulating them into .
- Iterate to Schur form. Apply Francis double-shift steps (real matrices) or single-shift steps (complex matrices). After each step, set negligible subdiagonal entries to zero; when the trailing or block separates, deflate it and continue on the rest.
- Triangularise each remaining block, which holds a complex conjugate pair, to obtain the complex Schur form . The diagonal of holds the eigenvalues.
- Eigenvectors of . For each eigenvalue , solve the triangular system by back substitution, with and zeros below.
- Map back: multiply by , undo the balancing, and normalise each vector.
Both solvers cost : about flops for the tridiagonal reduction and for the Hessenberg reduction, plus the iteration and the accumulation of vectors.
Implementation
The implicit QL algorithm for the tridiagonal matrix (after Numerical Recipes’ tqli, with the norm-relative deflation test of
EISPACK’s tql2, without which the iteration failed on rank-deficient matrices such as the centred kernel matrices of
kernel PCA):
/// Implicit QL with shifts on the symmetric tridiagonal matrix with diagonal `d` and
/// sub-diagonal `e` (`e[i]` couples `i` and `i+1`; `e[n−1]` is unused), accumulating the
/// rotations into the *rows* of `zt` (the transpose of the eigenvector matrix; Numerical Recipes
/// `tqli`).
fn tql(d: &mut [f64], e: &mut [f64], mut zt: Option<&mut Mat<f64>>) -> Result<()> {
let n = d.len();
// A sub-diagonal entry is negligible when it is below rounding relative to its neighbours or
// to the norm of the part already processed (EISPACK tql2's `tst1`). The purely local test
// never deflates a block of eigenvalues that are zero up to rounding, as in a rank-deficient
// matrix, where the diagonal and sub-diagonal entries are all rounding noise.
let mut norm: f64 = 0.0;
for l in 0..n {
norm = norm.max(d[l].abs() + e[l].abs());
let mut iterations = 0;
loop {
let mut m = l;
while m + 1 < n {
let dd = d[m].abs() + d[m + 1].abs();
if e[m].abs() <= f64::EPSILON * dd.max(norm) {
break;
}
m += 1;
}
if m == l {
break;
}
iterations += 1;
if iterations > 60 {
return Err(LinalgError::NoConvergence("the symmetric QL iteration"));
}
let mut g = (d[l + 1] - d[l]) / (2.0 * e[l]);
let mut r = g.hypot(1.0);
g = d[m] - d[l] + e[l] / (g + r.copysign(g));
let (mut s, mut c, mut p) = (1.0, 1.0, 0.0);
let mut i = m;
let mut underflow = false;
while i > l {
i -= 1;
let f = s * e[i];
let b = c * e[i];
r = f.hypot(g);
e[i + 1] = r;
if r == 0.0 {
d[i + 1] -= p;
e[m] = 0.0;
underflow = true;
break;
}
s = f / r;
c = g / r;
g = d[i + 1] - p;
r = (d[i] - g) * s + 2.0 * c * b;
p = s * r;
d[i + 1] = g + p;
g = c * r - b;
if let Some(zt) = zt.as_deref_mut() {
let (row_i, row_next) = zt.data[i * n..(i + 2) * n].split_at_mut(n);
for (zi, f) in row_i.iter_mut().zip(row_next.iter_mut()) {
let (a, b) = (*zi, *f);
*f = s * a + c * b;
*zi = c * a - s * b;
}
}
}
if underflow {
continue;
}
d[l] -= p;
e[l] = g;
e[m] = 0.0;
}
}
Ok(())
}
Balancing:
/// Balances `a` in place by a diagonal similarity `D⁻¹ A D` (Parlett and Reinsch, 1969, as in
/// LAPACK's `gebal`), so that each row and the matching column have similar norms; returns `D`.
/// The scale factors are powers of two, so the eigenvalues are unchanged exactly, while the
/// rounding errors of the QR iteration, proportional to `‖A‖`, can shrink by many orders of
/// magnitude (companion matrices of polynomials with widely ranging coefficients are the classic
/// case). An eigenvector `v` of the balanced matrix is `D v` for the original.
fn balance<T: Scalar>(a: &mut Mat<T>) -> Vec<f64> {
let n = a.rows;
let mut d = vec![1.0f64; n];
let mut converged = false;
while !converged {
converged = true;
for i in 0..n {
let (mut c, mut r) = (0.0f64, 0.0f64);
for j in (0..n).filter(|&j| j != i) {
c += a.at(j, i).abs();
r += a.at(i, j).abs();
}
if c == 0.0 || r == 0.0 {
continue;
}
let (s, mut f) = (c + r, 1.0f64);
let (mut c2, mut r2) = (c, r);
while c2 < r2 / 2.0 {
(c2, r2, f) = (c2 * 2.0, r2 / 2.0, f * 2.0);
}
while c2 >= r2 * 2.0 {
(c2, r2, f) = (c2 / 2.0, r2 * 2.0, f / 2.0);
}
// Rescale only if it reduces the row-plus-column norm noticeably.
if c2 + r2 < 0.95 * s {
converged = false;
d[i] *= f;
for j in 0..n {
*a.at_mut(i, j) = a.at(i, j).scale(1.0 / f);
*a.at_mut(j, i) = a.at(j, i).scale(f);
}
}
}
}
d
}
eigh(uplo)reads one triangle and returns ascending eigenvalues and orthonormal eigenvectors;eigvalshskips the vectors.eigreturns complex eigenvalues (in Schur order) and unit-norm complex eigenvectors for real or complex input;eigvalsskips the vectors.
In practice
//! Production eigensolvers: Hermitian and general, real and complex.
//!
//! Run with `cargo run -p lib_jsl_linalg_reference --example linalg_eigen`.
use lib_jsl_linalg::{Eig, EigVals, Eigh, UPLO};
use ndarray::{Array2, array};
use num_complex::Complex;
fn main() {
// Normal modes of three masses joined by springs: K v = ω² M v with M = I.
let k = array![[2.0, -1.0, 0.0], [-1.0, 2.0, -1.0], [0.0, -1.0, 2.0]];
let (omega2, modes) = k.eigh(UPLO::Lower).unwrap();
println!("ω² = {omega2:.6}");
println!("mode shapes (columns):\n{modes:.4}");
// A rotation by 90° has complex eigenvalues ±i.
println!("eigenvalues of a rotation: {:.6}", array![[0.0, -1.0], [1.0, 0.0]].eigvals().unwrap());
// A general real matrix: eigenvalues and eigenvectors, checked by A v = λ v.
let a = array![[4.0, 1.0, -2.0], [0.5, 3.0, 1.0], [2.0, -1.0, 1.0]];
let (w, v) = a.eig().unwrap();
let ac = a.mapv(|x| Complex::new(x, 0.0));
let residual = (ac.dot(&v) - &v * &w).iter().map(|z| z.norm()).fold(0.0, f64::max);
println!("eigenvalues {w:.6}; max |A v − λ v| = {residual:.1e}");
// Hermitian complex matrices have real eigenvalues.
let h: Array2<Complex<f64>> = array![[Complex::new(2.0, 0.0), Complex::new(0.0, 1.0)], [Complex::new(0.0, -1.0), Complex::new(2.0, 0.0)]];
println!("Hermitian eigenvalues: {:.6}", h.eigh(UPLO::Lower).unwrap().0);
}
Strengths
- Complete, backward-stable dense eigensolvers for real and complex, Hermitian and general matrices.
- The Hermitian solver matches LAPACK’s speed.
Weaknesses
- The general solver has aggressive early deflation but not LAPACK’s blocked multishift sweeps, and falls behind LAPACK for large matrices.
- No generalised eigenproblem (; for symmetric positive definite , reduce with the Cholesky factor of ), and no iterative methods for a few eigenvalues of large sparse matrices.
- Eigenvalues of non-normal matrices may be inaccurate, as for any method.
Exercises
- Show that the QR algorithm preserves upper Hessenberg form and symmetric tridiagonal form.
- Count the flops of Householder tridiagonalisation.
- Compute the eigenvalues of the companion matrix of with and without balancing, and explain the difference.
- Compute the condition numbers (with unit left and right eigenvectors) of the eigenvalues of the Grcar matrix.
- Solve the generalised problem for a mass-spring system with non-uniform masses by transforming with .
Hints and answers
- If is upper Hessenberg, is upper triangular and is upper Hessenberg, so is upper Hessenberg. In the symmetric case the result is symmetric and Hessenberg, hence tridiagonal.
- Reducing a symmetric matrix to tridiagonal form with Householder reflections costs about flops (without forming ); count the cost of the reflection at step (about ) and sum.
- The companion matrix of has entries spanning many orders of magnitude, so its eigenvalues are very sensitive to rounding. Balancing scales rows and columns to reduce the norm and typically improves the accuracy of the eigenvalues noticeably; compare the errors with and without it.
- The Grcar matrix is highly non-normal and its eigenvalues are very ill-conditioned: expect condition numbers that grow rapidly with the dimension, even though the matrix is only a banded Toeplitz matrix.
- With , becomes , a symmetric standard eigenproblem; transform the eigenvectors back by .
Further reading
- J. H. Wilkinson, The Algebraic Eigenvalue Problem, Oxford University Press, 1965.
- J. H. Wilkinson and C. Reinsch, Handbook for Automatic Computation, Volume II: Linear Algebra, Springer, 1971.
- D. S. Watkins, The Matrix Eigenvalue Problem: GR and Krylov Subspace Methods, SIAM, 2007.
- K. Braman, R. Byers and R. Mathias, “The multishift QR algorithm. Part II: aggressive early deflation”, SIAM Journal on Matrix Analysis and Applications 23 (2002) 948–973.
- L. N. Trefethen and M. Embree, Spectra and Pseudospectra, Princeton University Press, 2005.