Real QZ, reordering and Hankel transforms
| Problem | Reduce a real pencil (A, B) to real generalised Schur form; reorder Schur and generalised Schur forms so that chosen eigenvalues come first, giving orthonormal bases of the corresponding invariant and deflating subspaces; transform Hermitian-symmetric signals; and compute Hankel transforms of log-spaced data |
| Devised by | Cleve Moler and G. W. Stewart (1973), the QZ algorithm; Zhaojun Bai and James Demmel (1993), and Bo Kågström (1993), swapping diagonal blocks; Andrew Hamilton (2000), FFTLog, after James Talman (1978) |
| Accuracy | Backward errors of ; eigenvalues, selected counts and subspaces agree with SciPy (LAPACK) to ; the transforms agree with scipy.fft to |
| Cost | QZ: , about 30 flops with both transformations; a block swap , reordering per eigenvalue moved; FFTLog: two real FFTs, |
| Read first | Generalised eigenproblems and structured matrices, Further factorisations |
| API | qz_real, ordqz, ordqz_complex, schur_sorted, schur_sorted_complex, EigenSort; hfft, ihfft, fht, ifht, fhtoffset |
Overview
The complex QZ algorithm already gives the generalised eigenvalues of a pencil . For a real pencil the real QZ form keeps the arithmetic real: with 2 × 2 blocks for complex conjugate pairs, just as the real Schur form does for a single matrix.
Many applications need the eigenvalues in a particular order. The leading columns of then span the subspace belonging to the first eigenvalues:
- Riccati equations and LQR control need the stable eigenvalues ( or ) first.
- Rational expectations models in economics need a stable/unstable split.
- Spectral projectors need the eigenvalues in a chosen region of the plane.
schur(a, sort=...) and ordqz provide this: they reorder the forms so that the selected eigenvalues come first. SciPy’s predefined selections are the left or right half-plane and the inside or outside of the unit circle; a predicate gives any other.
The entry also adds two Fourier-type transforms from scipy.fft:
hfftandihfft, the FFT of a signal with Hermitian symmetry given by half of its samples.- The fast Hankel transform (FFTLog), which computes for logarithmically spaced samples. It is the workhorse for correlation functions and power spectra in cosmology.
Where it is used
The generalised Schur form is the stable way to handle matrix pencils.
- Descriptor and singular systems. Systems with singular arise in circuit simulation and constrained mechanics.
- Control. Reordering Schur forms places the stable and unstable eigenvalues apart, which is how Riccati equations and optimal controllers are solved robustly.
- Hankel transforms. Used in system identification from impulse responses.
History
Cleve Moler and G. W. Stewart (1973) introduced the QZ algorithm: the Francis double-shift step applied to without forming it. Robert Ward (1975) and Linda Kaufman (1974) refined its deflations. Zhaojun Bai and James Demmel (1993) showed how to swap adjacent blocks of a real Schur form stably, through a small Sylvester equation. Bo Kågström (1993) did the same for pencils, and their methods are LAPACK’s trexc, trsen, tgexc and tgsen.
James Talman (1978) computed Hankel transforms by FFTs in the logarithm of the radius. Andrew Hamilton (2000) turned this into FFTLog, with the low-ringing offset condition SciPy’s fhtoffset uses.
The idea
The real QZ algorithm
- A QR factorisation makes triangular.
- Givens rotations from the bottom up make upper Hessenberg. Each rotation spoils ’s triangle by one entry, which a column rotation restores.
- The double-shift step: the first column of has three non-zero entries, computable from and alone, with the eigenvalues of the trailing 2 × 2 block of .
- A 3 × 3 Householder reflector introduces this bulge. Alternating left reflectors (restoring ’s Hessenberg form) and right reflectors (restoring ’s triangle) chase it down the pencil.
- When a subdiagonal entry of becomes negligible the problem splits. A negligible diagonal entry of is an infinite eigenvalue: rotations chase it to the bottom of the active window, where it deflates.
- Finally, 2 × 2 blocks with real eigenvalues are split by a rotation built from an eigenvector.
Swapping diagonal blocks
Suppose a quasi-triangular has blocks of size 1 or 2. If solves the Sylvester equation , then so the columns of span the invariant subspace of ’s eigenvalues. An orthogonal whose leading columns span the same space, from a QR factorisation, gives with ’s eigenvalues in the leading block. The equation is a linear system of at most 4 unknowns.
For pencils, the right and left deflating subspaces come from the pair of equations Then and give and .
Reordering moves each selected block up, one adjacent swap at a time, to just below the blocks already moved.
Subspaces, not matrices, are unique
The Schur vectors depend on the algorithm’s choices: signs, rotations within a block, and the order among selected eigenvalues. The subspace spanned by the first columns does not, as long as the selected and unselected eigenvalues are distinct. It is compared through its orthogonal projector .
FFTLog
With and , the Hankel transform is a convolution in . Its kernel’s Fourier coefficients are the Mellin transform of , a ratio of gamma functions:
So . The offset is chosen (fhtoffset) so that is real at the Nyquist frequency, which reduces ringing. The bias multiplies the input by a power of for functions that decay slowly at one end.
Implementation
/// The real generalised Schur form of the pencil `(A, B)` (SciPy's `qz(a, b, output='real')`):
/// orthogonal `Q`, `Z` with `Qᵀ A Z = AA` quasi upper triangular and `Qᵀ B Z = BB` upper
/// triangular. `B` is made triangular by a QR factorisation and `A` Hessenberg by Givens
/// rotations that keep `B` triangular; then Moler and Stewart's implicit double-shift QZ sweeps
/// — the Francis step applied to `A B⁻¹` without forming it — chase bulges down the pencil until
/// `A` is quasi-triangular. A zero on the diagonal of `B` (an infinite eigenvalue) is chased to
/// the bottom of the active window and deflated. 2 × 2 blocks with real eigenvalues are split.
pub fn qz_real<S: Data<Elem = f64>, S2: Data<Elem = f64>>(a: &ArrayBase<S, Ix2>, b: &ArrayBase<S2, Ix2>) -> Result<RealQzFactors> {
let n = a.nrows();
if a.ncols() != n || b.dim() != (n, n) {
return Err(LinalgError::Shape(format!("A ({:?}) and B ({:?}) must be square and of one size", a.dim(), b.dim())));
}
if a.iter().chain(b.iter()).any(|v| !v.is_finite()) {
return Err(LinalgError::NonFinite);
}
let mut p = Pencil { a: a.to_owned(), b: b.to_owned(), q: Array2::eye(n), z: Array2::eye(n) };
if n == 0 {
return Ok(RealQzFactors { aa: p.a, bb: p.b, q: p.q, z: p.z });
}
// B = QR.
for j in 0..n.saturating_sub(1) {
let col: Vec<f64> = (j..n).map(|i| p.b[(i, j)]).collect();
let (u, beta) = house(&col);
p.house_rows(&u, beta, j);
for i in j + 1..n {
p.b[(i, j)] = 0.0;
}
}
// A to Hessenberg form, keeping B triangular.
for j in 0..n.saturating_sub(2) {
for i in (j + 2..n).rev() {
let (c, s) = givens(p.a[(i - 1, j)], p.a[(i, j)]);
p.rows(i - 1, i, c, s);
p.a[(i, j)] = 0.0;
let (c, s) = givens(p.b[(i, i)], p.b[(i, i - 1)]);
p.cols(i, i - 1, c, s);
p.b[(i, i - 1)] = 0.0;
}
}
let anorm = p.a.iter().map(|v| v * v).sum::<f64>().sqrt().max(f64::MIN_POSITIVE);
let bnorm = p.b.iter().map(|v| v * v).sum::<f64>().sqrt().max(f64::MIN_POSITIVE);
let eps = f64::EPSILON;
let mut hi = n as isize - 1;
let mut iterations = 0;
let mut since_deflation = 0;
while hi >= 0 {
let h = hi as usize;
// Find the start of the active window.
let mut l = 0;
for k in (1..=h).rev() {
if p.a[(k, k - 1)].abs() <= eps * (p.a[(k - 1, k - 1)].abs() + p.a[(k, k)].abs()).max(eps * anorm) {
p.a[(k, k - 1)] = 0.0;
l = k;
break;
}
}
// A negligible diagonal entry of B: an infinite eigenvalue.
if let Some(j) = (l..=h).find(|&j| p.b[(j, j)].abs() <= eps * bnorm) {
p.b[(j, j)] = 0.0;
p.chase_zero(j, l, h);
hi -= 1;
since_deflation = 0;
continue;
}
match h - l + 1 {
1 => {
hi -= 1;
since_deflation = 0;
}
2 => {
p.standardize(l);
hi -= 2;
since_deflation = 0;
}
_ => {
iterations += 1;
since_deflation += 1;
if iterations > 30 * n.max(10) {
return Err(LinalgError::NoConvergence("qz_real: the QZ iteration did not converge"));
}
p.double_shift(l, h, since_deflation % 10 == 0);
}
}
}
// A non-negative diagonal for B.
for j in 0..n {
if p.b[(j, j)] < 0.0 {
for c in 0..n {
p.a[(j, c)] = -p.a[(j, c)];
p.b[(j, c)] = -p.b[(j, c)];
}
for r in 0..n {
p.q[(r, j)] = -p.q[(r, j)];
}
}
}
Ok(RealQzFactors { aa: p.a, bb: p.b, q: p.q, z: p.z })
}
/// The real generalised Schur form with the eigenvalues selected by `sort` leading (SciPy's
/// `ordqz(a, b, sort=..., output='real')`): [`qz_real`], then adjacent block swaps (LAPACK's
/// `dtgsen`/`dtgexc`) built from the generalised Sylvester equation
/// `A₁₁R − L A₂₂ = −A₁₂`, `B₁₁R − L B₂₂ = −B₁₂`, whose solution spans the deflating subspaces of
/// the lower block.
pub fn ordqz<S: Data<Elem = f64>, S2: Data<Elem = f64>>(a: &ArrayBase<S, Ix2>, b: &ArrayBase<S2, Ix2>, sort: &EigenSort) -> Result<OrdQz> {
let f = qz_real(a, b)?;
let mut p = Pencil { a: f.aa, b: f.bb, q: f.q, z: f.z };
let mut ks = 0;
loop {
let bl = blocks(&p.a);
let (alpha, beta) = pencil_eigs(&p.a, &p.b);
let mut idx = 0;
let mut next = None;
for &(k, s) in &bl {
if k >= ks && (0..s).any(|t| sort.pencil(alpha[idx + t], C::new(beta[idx + t], 0.0))) {
next = Some((k, s));
break;
}
idx += s;
}
let Some((mut k, s)) = next else { break };
while k > ks {
let above = blocks(&p.a).into_iter().rfind(|&(kk, _)| kk < k).expect("a block above");
if !swap_pencil(&mut p, above.0, above.1, s) {
return Err(LinalgError::NoConvergence("ordqz: the blocks are too close to swap"));
}
k = above.0;
}
ks += s;
}
for j in 0..p.a.nrows() {
if p.b[(j, j)] < 0.0 && (j + 1 >= p.a.nrows() || p.a[(j + 1, j)] == 0.0) && (j == 0 || p.a[(j, j - 1)] == 0.0) {
for c in 0..p.a.ncols() {
p.a[(j, c)] = -p.a[(j, c)];
p.b[(j, c)] = -p.b[(j, c)];
}
for r in 0..p.q.nrows() {
p.q[(r, j)] = -p.q[(r, j)];
}
}
}
let (alpha, beta) = pencil_eigs(&p.a, &p.b);
Ok(OrdQz { aa: p.a, bb: p.b, alpha, beta, q: p.q, z: p.z, sdim: ks })
}
/// The fast Hankel transform (SciPy's `fht`) of `a`, sampled at `r_j = r_c exp((j − j_c) dln)`,
/// `j_c = (n − 1)/2`: approximately `A(k_j) = ∫₀^∞ a(r) J_μ(k_j r) k_j dr` at
/// `k_j = exp(offset)/r_c · exp((j − j_c) dln)`. With `bias = q` the input is multiplied by
/// `(r/r_c)^{−q}` and the output by `(k/k_c)^{−q}`, which can reduce ringing. FFTLog computes it
/// exactly for the periodic, log-spaced interpolant of `a`: an rFFT, multiplication by
/// `u_m = 2^{q} Γ((μ+1+q+iy_m)/2)/Γ((μ+1−q−iy_m)/2) · e^{i y_m (ln 2 − offset)}`, an inverse rFFT
/// and a reversal.
pub fn fht(a: &[f64], dln: f64, mu: f64, offset: f64, bias: f64) -> Result<Vec<f64>, ErrorsJSL> {
let n = a.len();
if n == 0 || dln.is_nan() || dln <= 0.0 {
return Err(ErrorsJSL::InvalidInputRange("fht: need a non-empty input and dln > 0"));
}
let jc = (n as f64 - 1.0) / 2.0;
let biased: Vec<f64> = if bias != 0.0 { a.iter().enumerate().map(|(j, &v)| v * (-bias * (j as f64 - jc) * dln).exp()).collect() } else { a.to_vec() };
let u = fhtcoeff(n, dln, mu, offset, bias, false);
let mut out = fhtq(&biased, &u, false)?;
if bias != 0.0 {
for (j, v) in out.iter_mut().enumerate() {
*v *= (-bias * ((j as f64 - jc) * dln + offset)).exp();
}
}
Ok(out)
}
- The complex variants (
schur_sorted_complex,ordqz_complex) swap 1 × 1 blocks with single rotations. EigenSortfollows SciPy’s two conventions:- for
schur,'rhp'means ; - for
ordqz,'rhp'means , and the infinite eigenvalues count as outside the unit circle.
- for
- The gamma ratios use a complex log-gamma from Stirling’s series after upward recurrence, accurate to rounding.
In practice
The references are from SciPy 1.17.1, written by book/generator/data/make_qz213_refs.py:
Table 7.29. The real QZ algorithm, `ordqz` and sorted Schur forms against SciPy: backward error, eigenvalues (matched, relative), the number selected for each sort, and the largest difference between the projectors onto the leading subspaces.
| Pencil | ‖Q AA Zᵀ − A‖, ‖Q BB Zᵀ − B‖ | Eigenvalues vs SciPy | sdim (real and complex) | ordqz subspaces | schur(sort) subspaces |
|---|---|---|---|---|---|
| 6 × 6 | 7e-15 | 1e-16 | same | 2e-15 | 3e-15 |
| 12 × 12 | 1e-14 | 1e-14 | same | 6e-15 | 3e-15 |
| 30 × 30 | 1e-14 | 7e-15 | same | 4e-15 | 4e-15 |
| 8 × 8, B with two zero rows (rhp, iuc) | 4e-15 | 7e-16 | same | 2e-15 | — |
The leading invariant and deflating subspaces agree with LAPACK’s to for every sort. One case differs. When is singular, LAPACK leaves the infinite eigenvalues with of rounding size () rather than zero, so the sign of that rounding error decides whether they count as left-half-plane or outside the unit circle. The library deflates them with exactly, and only the unaffected sorts are compared for that pencil.
Table 7.30. `hfft`, `ihfft` and the fast Hankel transform against `scipy.fft`.
| Transform | Largest difference from SciPy (relative to the largest value) |
|---|---|
hfft, 9 inputs; n = 16, 13, 6 | 3e-15 |
ihfft, 11 inputs | 8e-17 |
fht, ifht, fhtoffset: μ = 0, r e^{−r²/2}, n = 128 | 1e-15 / 1e-15 / 0 |
fht, ifht, fhtoffset: μ = 1, r² e^{−r}, n = 128 | 8e-16 / 9e-16 / 7e-16 |
fht, ifht, fhtoffset: μ = ½, bias 0.4, log-normal, n = 128 | 2e-14 / 2e-14 / 4e-16 |
fht, ifht, fhtoffset: μ = −½, bias −0.3, 1/(1 + r²), n = 128 | 1e-14 / 1e-14 / 3e-16 |
Figure 7.20. The generalised eigenvalues of a random 30 × 30 pencil after `ordqz` with `'iuc'`. The 13 inside the unit circle occupy the leading block, so the first 13 columns of span their right deflating subspace (eigenvalues beyond the axes are not shown).
Figure 7.21. FFTLog with 128 samples at spacing 0.05 in . The transform matches the exact over most of the range. Near the ends it deviates, because FFTLog treats the samples as periodic in .
Strengths
- Real arithmetic throughout for real pencils, with infinite eigenvalues deflated exactly.
- Reordering by any predicate, with SciPy’s four named selections.
- FFTLog in for any order , with SciPy’s offset and bias options.
Weaknesses
- The QZ sweeps are the unblocked single-bulge algorithm, slower than LAPACK’s multishift variants for large .
- No condition estimates for the reordered subspaces (LAPACK’s
trsen/tgsenwithijob > 0). - FFTLog’s periodic wrap-around causes ringing at the ends unless the input decays there.
Exercises
- Show that when .
- Why is the Sylvester equation uniquely solvable exactly when and have no eigenvalue in common?
- Why does the projector not depend on which orthonormal basis of the subspace is used?
- Show that
hfft(ihfft(x), n)returnsxfor realxof lengthn.
Hints and answers
- The first block row is , the Sylvester equation; the second is .
- The operator has eigenvalues .
- Another basis is with orthogonal, and .
ihfft(x)is , andhfftapplies , which undoes it.
Further reading
- C. B. Moler and G. W. Stewart, “An algorithm for generalized matrix eigenvalue problems”, SIAM Journal on Numerical Analysis 10 (1973) 241–256.
- Z. Bai and J. W. Demmel, “On swapping diagonal blocks in real Schur form”, Linear Algebra and its Applications 186 (1993) 73–95.
- B. Kågström, “A direct method for reordering eigenvalues in the generalized real Schur form of a regular matrix pair (A, B)”, in Linear Algebra for Large Scale and Real-Time Applications, Kluwer (1993) 195–218.
- A. J. S. Hamilton, “Uncorrelated modes of the non-linear power spectrum”, Monthly Notices of the Royal Astronomical Society 312 (2000) 257–284.
- J. D. Talman, “Numerical Fourier and Bessel transforms in logarithmic variables”, Journal of Computational Physics 29 (1978) 35–48.
- G. H. Golub and C. F. Van Loan, Matrix Computations, 4th ed., Johns Hopkins (2013), §7.7.