Algorithm Search⌘K

Algorithmresearch

Iterative rational Krylov algorithm

Also called IRKA.

Finds a reduced model that meets the H2 optimality conditions by interpolating at the mirrored poles of the current reduced model, repeated to a fixed point.

Time
O(k r n^3) worst
Space
O(n^2 + n r) extra
Where
k = the number of iterations; n = the number of states; r = the reduced order
Properties
deterministicnot exactofflineiterative
Origin
Serkan Gugercin, Athanasios C. Antoulas, Christopher Beattie, 2008

The iterative rational Krylov algorithm, IRKA, makes a small model of a large linear system that is close in the H2H_2 norm, the root of the energy of the error impulse response (see H2 norm). It needs only solves with matrices sI−AsI - A, so it applies to systems with very many states, where the Gramians of balanced truncation are too costly. The idea is interpolation. A projection onto a Krylov subspace built from the vectors (siI−A)−1b(s_i I - A)^{-1} b gives a reduced model that matches the transfer function GG and its derivative at the chosen points sis_i, as in Hermite interpolation. Meier and Luenberger (1967) showed that an H2H_2 optimal model of order rr must match GG and G′G' at the mirror images −λi-\lambda_i of its own poles. IRKA, proposed by Gugercin, Antoulas and Beattie (2008), turns this condition into a fixed-point iteration: interpolate at the current points, compute the poles of the new model, mirror them, and repeat. A fixed point satisfies the first-order conditions for a local minimum of the H2H_2 error. The iteration usually converges in tens of steps, but there is no general proof that it converges.

In plain words

A large model can be summarized by how it responds at a few chosen test frequencies. One can build a small model that copies the large model exactly at those test frequencies, both the value and its slope. The question is which test frequencies to choose. The best small model, measured by the total energy of the error, has a property that helps: its test frequencies are the mirror images of its own natural frequencies. So the method guesses test frequencies, builds the small model, reads off its natural frequencies, mirrors them to get new test frequencies, and repeats. When the test frequencies stop moving, the small model has the property that the best one must have.

The problem

Input: A∈Rn×nA \in \mathbb{R}^{n \times n} Hurwitz, b∈Rnb \in \mathbb{R}^n, c∈R1×nc \in \mathbb{R}^{1 \times n}, an order r≤nr \le n, initial shifts s1,…,srs_1, \dots, s_r in the open right half plane and closed under conjugation, a tolerance and a maximum number of iterations. The system is G(s)=c(sI−A)−1bG(s) = c(sI - A)^{-1}b, with one input and one output. Output: Ar∈Rr×rA_r \in \mathbb{R}^{r \times r}, brb_r, crc_r with Gr(s)=cr(sI−Ar)−1brG_r(s) = c_r(sI - A_r)^{-1}b_r, the final shifts, the number of iterations and a flag that says whether the shifts converged. On convergence, with λi\lambda_i the eigenvalues of ArA_r,

Gr(−λi)=G(−λi),Gr′(−λi)=G′(−λi),i=1,…,r,G_r(-\lambda_i) = G(-\lambda_i), \qquad G_r'(-\lambda_i) = G'(-\lambda_i), \qquad i = 1, \dots, r,

which are the necessary conditions for a local minimum of ∥G−Gr∥H2\|G - G_r\|_{H_2} over real models of order rr with simple poles.

The algorithm

  1. IRKA(A, b, c, r, s, tol, maxiter)
  2. 1s ← initial shifts s_1, ..., s_r, closed under conjugation, Re s_i > 0
  3. 2for it = 1 to maxiter do
  4. 3V ← basis of span{(s_i I - A)⁻¹ b}; W ← basis of span{(s_i I - Aᵀ)⁻¹ cᵀ}
  5. 4A_r ← (WᵀV)⁻¹ WᵀAV; b_r ← (WᵀV)⁻¹ Wᵀb; c_r ← cV
  6. 5s_new ← sorted −eig(A_r); δ ← max_i |s_new,i − s_i| / |s_i|; s ← s_new
  7. 6if δ < tol then
  8. 7return (A_r, b_r, c_r, s, it, converged)
  9. 8return (A_r, b_r, c_r, s, maxiter, not converged)

Line L1 takes the given shifts, or by default rr real shifts spread geometrically between 1/∥A−1∥∞1/\|A^{-1}\|_\infty and ∥A∥∞\|A\|_\infty, which bound the moduli of the eigenvalues of AA from below and above. Line L3 solves 2r2r linear systems, one with siI−As_i I - A and one with siI−ATs_i I - A^T for each shift. For a conjugate pair only one complex solve per side is needed: its real and imaginary parts span the same space as the pair, so the basis and the reduced matrices are real. The implementation orthonormalizes both bases by Gram-Schmidt, done twice; this keeps the column spaces and so the reduced model. Line L4 is the Petrov-Galerkin projection, a two-sided oblique projection. Line L5 takes the eigenvalues of the small matrix ArA_r, mirrors them, sorts them, and measures how far they moved. Lines L6 and L7 stop at a fixed point, and line L8 reports a run that did not converge.

Example

The chain of four sections. G(s)=1/((s+1)(s+2)(s+3)(s+4))G(s) = 1/((s+1)(s+2)(s+3)(s+4)), realized with AA upper bidiagonal, b=e4b = e_4 and c=e1Tc = e_1^T, has ∥G∥H2=0.0222718\|G\|_{H_2} = 0.0222718. For r=2r = 2 the default shifts are 0.585370.58537 and 44. The table lists the shifts after kk updates and the H2H_2 error of the model projected at those shifts (measurements; the error is computed from the Gramian of the error system).

kk shifts ∥G−Gr∥H2\|G - G_r\|_{H_2}
0 0.585370.58537, 44 0.0103772
1 0.25429±0.70058i0.25429 \pm 0.70058i 0.00344639
2 0.86729±0.48197i0.86729 \pm 0.48197i 0.00292236
3 0.63707±0.61264i0.63707 \pm 0.61264i 0.0028312
4 0.72113±0.57036i0.72113 \pm 0.57036i 0.0028203
6 0.70178±0.58019i0.70178 \pm 0.58019i 0.0028186
10 0.69886±0.58167i0.69886 \pm 0.58167i 0.00281857
25 0.69881±0.58170i0.69881 \pm 0.58170i 0.00281857

The run stops after 25 iterations, with the reduced poles −0.69881∓0.58170i-0.69881 \mp 0.58170i, whose mirror images are the shifts. The error falls fast in the first steps, and the shifts then spiral into the fixed point at a linear rate. The final H2H_2 error is 0.002818570.00281857, against 0.00287370.0028737 for balanced truncation of the same order, and the H∞H_\infty error is 0.00205340.0020534, against 0.00214790.0021479 (measurements). For r=1r = 1 the run takes 70 iterations and ends at the shift 0.285140.28514 with H2H_2 error 0.0127420.012742; a brute-force search over all models ϕ/(s+λ)\phi/(s + \lambda) gives the same shift. For r=3r = 3 it takes 13 iterations, ends at the shifts 0.879400.87940 and 1.65866±1.05175i1.65866 \pm 1.05175i, and has H2H_2 error 0.000223400.00022340. The model order reduction page compares both methods for each rr.

Correctness

The full proof is in proofs/correctness.md. Its steps are theorems:

  1. Projection. With M(s)=WT(sI−A)VM(s) = W^T(sI - A)V, the reduced transfer function is Gr(s)=cVM(s)−1WTbG_r(s) = cV M(s)^{-1} W^T b. It depends only on the column spaces of VV and WW, so the real basis and the orthonormalization of line L3 do not change it.
  2. Hermite interpolation. For every shift with M(si)M(s_i) invertible, Gr(si)=G(si)G_r(s_i) = G(s_i) and Gr′(si)=G′(si)G_r'(s_i) = G'(s_i). This holds after every pass of line L4, not only at the end.
  3. The H2H_2 inner product by residues. For H(s)=∑kψk/(s−μk)H(s) = \sum_k \psi_k/(s - \mu_k) with poles in the open left half plane, ⟨G,H⟩H2=∑kψkG(−μk)\langle G, H \rangle_{H_2} = \sum_k \psi_k G(-\mu_k).
  4. Meier and Luenberger conditions. For GrG_r with simple poles λi\lambda_i and residues ϕi\phi_i, the partial derivatives of J=∥G−Gr∥H22J = \|G - G_r\|_{H_2}^2 are −2(G(−λi)−Gr(−λi))-2(G(-\lambda_i) - G_r(-\lambda_i)) in ϕi\phi_i and 2ϕi(G′(−λi)−Gr′(−λi))2\phi_i(G'(-\lambda_i) - G_r'(-\lambda_i)) in λi\lambda_i. So the gradient is zero if the interpolation conditions hold, and only then when every ϕi≠0\phi_i \ne 0.
  5. Fixed points. If the iteration reaches si=−λi(Ar)s_i = -\lambda_i(A_r) with simple eigenvalues in the open left half plane and WTVW^T V invertible, then steps 2 and 4 show that GrG_r is a stationary point of the H2H_2 error.

The tests check the interpolation at random shifts on 500 random projections, the equality of the real and complex bases, the conditions of step 5 on converged runs, the r=1r = 1 result against a brute-force search, the chain example, that small perturbations of the converged model do not lower the error, and that r=nr = n reproduces GG.

Proof: A fixed point of IRKA interpolates G and G' at the mirrored reduced poles, so it satisfies the first-order conditions for H2 optimalityfull

Let A∈Rn×nA \in \mathbb{R}^{n \times n} be Hurwitz, b∈Rnb \in \mathbb{R}^n, c∈R1×nc \in \mathbb{R}^{1 \times n} and G(s)=c(sI−A)−1bG(s) = c (sI - A)^{-1} b. For shifts s1,…,srs_1, \dots, s_r that are closed under conjugation and are not eigenvalues of AA, let V,W∈Cn×rV, W \in \mathbb{C}^{n \times r} have the columns xi=(siI−A)−1bx_i = (s_i I - A)^{-1} b and yi=(siI−AT)−1cTy_i = (s_i I - A^T)^{-1} c^T. Assume E=WTVE = W^T V is invertible. The projected model is

Ar=E−1WTAV,br=E−1WTb,cr=cV,Gr(s)=cr(sI−Ar)−1br.A_r = E^{-1} W^T A V, \qquad b_r = E^{-1} W^T b, \qquad c_r = c V, \qquad G_r(s) = c_r (sI - A_r)^{-1} b_r.

The H2\mathcal{H}_2 norm is ∥H∥H22=12π∫−∞∞∣H(jω)∣2 dω\|H\|_{\mathcal{H}_2}^2 = \frac{1}{2\pi} \int_{-\infty}^{\infty} |H(j\omega)|^2\, d\omega (see H2 norm). IRKA repeats the projection with the new shifts si←−λi(Ar)s_i \leftarrow -\lambda_i(A_r) until the shifts do not change.

Lemma 1: the reduced transfer function as a projection

Let M(s)=WT(sI−A)VM(s) = W^T (sI - A) V. Where M(s)M(s) is invertible, Gr(s)=cVM(s)−1WTbG_r(s) = c V M(s)^{-1} W^T b, and GrG_r depends only on the column spaces of VV and WW.

Proof. sI−Ar=E−1(sE−WTAV)=E−1M(s)sI - A_r = E^{-1}(s E - W^T A V) = E^{-1} M(s), so (sI−Ar)−1br=M(s)−1EE−1WTb=M(s)−1WTb(sI - A_r)^{-1} b_r = M(s)^{-1} E E^{-1} W^T b = M(s)^{-1} W^T b. If VV is replaced by VRV R and WW by WSW S with RR and SS invertible, MM becomes STMRS^T M R and cVR(STMR)−1STWTb=cVM−1WTbc V R (S^T M R)^{-1} S^T W^T b = c V M^{-1} W^T b. □\square

So the implementation may replace a conjugate pair of columns x,xˉx, \bar x by Re⁡x,Im⁡x\operatorname{Re} x, \operatorname{Im} x, which span the same space because Re⁡x=(x+xˉ)/2\operatorname{Re} x = (x + \bar x)/2 and Im⁡x=(x−xˉ)/(2j)\operatorname{Im} x = (x - \bar x)/(2j). Here xˉ=(sˉI−A)−1b\bar x = (\bar s I - A)^{-1} b because AA and bb are real. It may also orthonormalize the columns. Neither step changes GrG_r, and the reduced matrices become real.

Lemma 2: Hermite interpolation

If M(si)M(s_i) is invertible, then Gr(si)=G(si)G_r(s_i) = G(s_i) and Gr′(si)=G′(si)G_r'(s_i) = G'(s_i).

Proof. Fix σ=si\sigma = s_i, M=M(σ)M = M(\sigma), x=xix = x_i and y=yiy = y_i. Let P=VM−1WT(σI−A)P = V M^{-1} W^T (\sigma I - A). Then PV=VM−1M=VP V = V M^{-1} M = V, so PP is the identity on the column space of VV. As xx is a column of VV, Px=xP x = x, that is, VM−1WTb=xV M^{-1} W^T b = x. In the same way, Q=(σI−A)VM−1WTQ = (\sigma I - A) V M^{-1} W^T satisfies WTQ=WTW^T Q = W^T, so yTQ=yTy^T Q = y^T, that is, cVM−1WT=c(σI−A)−1=yTc V M^{-1} W^T = c (\sigma I - A)^{-1} = y^T. With Lemma 1:

Gr(σ)=cVM−1WTb=cx=G(σ).G_r(\sigma) = c V M^{-1} W^T b = c x = G(\sigma).

For the derivative, M′(s)=WTVM'(s) = W^T V and ddsM(s)−1=−M−1M′M−1\frac{d}{ds} M(s)^{-1} = -M^{-1} M' M^{-1}, so

Gr′(σ)=−(cVM−1WT)(VM−1WTb)=−yTx=−c(σI−A)−2b=G′(σ).□G_r'(\sigma) = -(c V M^{-1} W^T)(V M^{-1} W^T b) = -y^T x = -c (\sigma I - A)^{-2} b = G'(\sigma). \qquad \square

Note that M(si)=E(siI−Ar)M(s_i) = E (s_i I - A_r), so M(si)M(s_i) is invertible when sis_i is not an eigenvalue of ArA_r.

Lemma 3: the H2 inner product by residues

Let HH be real, strictly proper and with simple poles μ1,…,μr\mu_1, \dots, \mu_r in the open left half plane and residues ψk\psi_k, so H(s)=∑kψk/(s−μk)H(s) = \sum_k \psi_k / (s - \mu_k). Let GG be real, strictly proper and with all poles in the open left half plane. Then

⟨G,H⟩=12π∫−∞∞G(jω)H(jω)‾ dω=∑k=1rψk G(−μk).\langle G, H \rangle = \frac{1}{2\pi} \int_{-\infty}^{\infty} G(j\omega) \overline{H(j\omega)}\, d\omega = \sum_{k=1}^{r} \psi_k\, G(-\mu_k).

Proof. HH is real, so H(jω)‾=H(−jω)\overline{H(j\omega)} = H(-j\omega), and the integral is 12πj∫jRG(s)H(−s) ds\frac{1}{2\pi j} \int_{j\mathbb{R}} G(s) H(-s)\, ds. The integrand is O(∣s∣−2)O(|s|^{-2}), so the contour can be closed by a large half circle in the right half plane, which runs clockwise. In the right half plane GG has no poles, and H(−s)=−∑kψk/(s+μk)H(-s) = -\sum_k \psi_k / (s + \mu_k) has simple poles at s=−μks = -\mu_k with residues −ψkG(−μk)-\psi_k G(-\mu_k) for the product. A clockwise contour gives minus the sum of the residues. □\square

Theorem 1: the first-order conditions of Meier and Luenberger

Let Gr(s)=∑i=1rϕi/(s−λi)G_r(s) = \sum_{i=1}^r \phi_i / (s - \lambda_i) be real, with simple poles λi\lambda_i in the open left half plane. The gradient of J=∥G−Gr∥H22J = \|G - G_r\|_{\mathcal{H}_2}^2 with respect to the poles and residues is zero if

G(−λi)=Gr(−λi)andG′(−λi)=Gr′(−λi),i=1,…,r,G(-\lambda_i) = G_r(-\lambda_i) \quad \text{and} \quad G'(-\lambda_i) = G_r'(-\lambda_i), \qquad i = 1, \dots, r,

and when every ϕi≠0\phi_i \ne 0 these conditions are also necessary.

Proof. By Lemma 3 with H=GrH = G_r, and again with G=H=GrG = H = G_r,

J=∥G∥2−2∑iϕi G(−λi)+∑i∑kϕiϕk−λi−λk.J = \|G\|^2 - 2 \sum_i \phi_i\, G(-\lambda_i) + \sum_i \sum_k \frac{\phi_i \phi_k}{-\lambda_i - \lambda_k}.

This formula defines a holomorphic function J(ϕ,λ)J(\phi, \lambda) of the 2r2r complex parameters near the given point. Since Gr(−λi)=∑kϕk/(−λi−λk)G_r(-\lambda_i) = \sum_k \phi_k / (-\lambda_i - \lambda_k) and Gr′(−λi)=−∑kϕk/(λi+λk)2G_r'(-\lambda_i) = -\sum_k \phi_k / (\lambda_i + \lambda_k)^2, direct differentiation gives

∂J∂ϕi=−2(G(−λi)−Gr(−λi)),∂J∂λi=2ϕi(G′(−λi)−Gr′(−λi)).\frac{\partial J}{\partial \phi_i} = -2\big(G(-\lambda_i) - G_r(-\lambda_i)\big), \qquad \frac{\partial J}{\partial \lambda_i} = 2 \phi_i \big(G'(-\lambda_i) - G_r'(-\lambda_i)\big).

On the set of real models, the parameters are closed under conjugation: a real pole has a real residue, and a pair (λi,λk=λˉi)(\lambda_i, \lambda_k = \bar\lambda_i) has residues ϕk=ϕˉi\phi_k = \bar\phi_i. The real coordinates are the real parameters and the real and imaginary parts of one member of each pair. For a pair, ∂/∂(Re⁡λi)=∂/∂λi+∂/∂λk\partial / \partial (\operatorname{Re} \lambda_i) = \partial / \partial \lambda_i + \partial / \partial \lambda_k and ∂/∂(Im⁡λi)=j(∂/∂λi−∂/∂λk)\partial / \partial (\operatorname{Im} \lambda_i) = j(\partial / \partial \lambda_i - \partial / \partial \lambda_k), and the same holds for the residues. Because GG and GrG_r are real, the formulas above give ∂J/∂λk=∂J/∂λi‾\partial J / \partial \lambda_k = \overline{\partial J / \partial \lambda_i} on this set. So both real derivatives are zero if and only if ∂J/∂λi=0\partial J / \partial \lambda_i = 0. The interpolation conditions make every complex partial zero, which proves sufficiency. If the gradient is zero and every ϕi≠0\phi_i \ne 0, the two formulas give the conditions. □\square

Theorem 2: a fixed point of IRKA is a stationary point of the H2 error

Assume IRKA reaches shifts with si=−λi(Ar)s_i = -\lambda_i(A_r) for every ii, where the eigenvalues λi\lambda_i of ArA_r are simple and lie in the open left half plane, and EE is invertible. Then GrG_r satisfies the conditions of Theorem 1, so it is a stationary point of ∥G−Gr∥H2\|G - G_r\|_{\mathcal{H}_2} over real models of order rr with simple poles.

Proof. Each si=−λis_i = -\lambda_i lies in the open right half plane, so it is not an eigenvalue of the Hurwitz matrices AA and ArA_r. So M(si)=E(siI−Ar)M(s_i) = E (s_i I - A_r) is invertible, and Lemma 2 gives Gr(−λi)=G(−λi)G_r(-\lambda_i) = G(-\lambda_i) and Gr′(−λi)=G′(−λi)G_r'(-\lambda_i) = G'(-\lambda_i). The poles of GrG_r are among the λi\lambda_i, and Theorem 1 applies. □\square

What is not proved

A stationary point need not be a minimum, and the iteration need not converge. Flagg, Beattie and Gugercin (2012) proved that for state-space-symmetric systems (A=ATA = A^T and b=cTb = c^T) the fixed point is locally attractive. For general systems, convergence is an open problem. The implementation therefore returns a flag converged, and the tests check the conclusions of Theorem 2 only on runs that converged.

The implementation stops when the largest relative change of the sorted shifts is below tol, so at the returned model the conditions of Theorem 2 hold up to an error of the size of tol times the sensitivity of the reduced poles.

Complexity

Each pass costs:

  • Line L3: 2r2r linear solves of size nn, which is O(rn3)O(r n^3) with dense Gaussian elimination, as in the implementation, and much less with sparse factorizations, depending on the sparsity pattern. Conjugate pairs halve the count. The Gram-Schmidt step costs O(nr2)O(n r^2).
  • Line L4: O(n2r)O(n^2 r) for WTAVW^T A V with dense AA, or O(nnz(A) r)O(\text{nnz}(A)\, r) with sparse AA, and O(r3)O(r^3) for the small solve.
  • Line L5: O(r3)O(r^3) for the eigenvalues of ArA_r.

So kk passes cost O(krn3)O(k r n^3) with dense matrices, and the extra space is O(n2+nr)O(n^2 + nr) for one factorization and the two bases. The count kk is not bounded in advance, and the code stops at maxiter. Compared with balanced truncation, which needs O(n3)O(n^3) work for two Lyapunov equations and dense storage, IRKA needs only solves, so the sparse cost is what matters for large models.

Rounding. In the floating-point model, each solve of line L3 by Gaussian elimination with partial pivoting is backward stable in the infinity norm in practice (a rule of thumb; the growth factor is usually small). The basis vectors for nearby shifts are nearly parallel, which is why the bases are orthonormalized: the projection uses the subspaces, not the vectors. The eigenvalues of ArA_r in line L5 are sensitive when ArA_r is far from normal, and this limits how small tol can usefully be.

Properties

  • Interpolation at every pass (a theorem): the model of each pass matches GG and G′G' at its shifts.
  • Stationary at a fixed point (a theorem): a converged model with simple poles satisfies the Meier and Luenberger conditions. It is a local, not a global, optimum in general.
  • Convergence is not guaranteed. Flagg, Beattie and Gugercin (2012) proved local convergence for state-space-symmetric systems, A=ATA = A^T and b=cTb = c^T (a theorem). For general systems the iteration usually converges in tens of passes (a rule of thumb), but it can cycle or diverge.
  • Asymptotic stability is not guaranteed for the intermediate models; a pass can return an ArA_r with an eigenvalue in the right half plane. Converged models of asymptotically stable systems are usually asymptotically stable in practice (a rule of thumb).
  • No a priori error bound. Unlike balanced truncation, the error is known only after the model is computed.
  • Linear rate. On the chain example the shifts approach the fixed point at a linear rate, with a spiral in the complex plane (a measurement).
  • Deterministic. For fixed initial shifts the result is fixed, but different initial shifts can lead to different local optima.

Variants and improvements

  • Several inputs and outputs. The MIMO version uses tangential interpolation: each shift comes with a right direction and a left direction, which are updated from the eigenvectors of ArA_r and the residues of GrG_r.
  • One-sided projection. For a state-space-symmetric system, W=VW = V gives the same conditions with half the solves.
  • Data-driven IRKA. The steps need only values of GG and G′G' at the shifts, so the reduced model can be built from measurements of the transfer function, without AA, by a Loewner matrix construction.
  • Rational Krylov at fixed points. Without the iteration, one projection at chosen shifts is moment matching. With one shift at infinity it gives the Padé approximation computed by the Lanczos algorithm or the Arnoldi iteration.
  • Safer shifts. Reflect a shift that falls into the left half plane back to the right half plane, or start from the mirrored poles of a balanced truncation model. Both are rules of thumb.
  • Faster convergence. Treat the fixed-point equation as a nonlinear system and apply the Newton-Raphson method or a trust-region method to the H2H_2 error.
  • Descriptor and discrete-time systems. Use sE−AsE - A in the solves, or the unit disk version of the conditions, where the mirror of a pole λ\lambda is 1/λ1/\lambda.

When to use it

Use IRKA when the model is large and sparse, when solves with sI−AsI - A are affordable but dense Gramians are not, and when the H2H_2 error matters, for example the energy of the impulse response error. Also use it for a medium-sized model when balanced truncation is not accurate enough and a local optimum in the H2H_2 norm is wanted. Start from shifts spread over the spectrum, or from the mirrored poles of a balanced truncation model. Check the converged flag, and check the error after the run, since no bound is known in advance. Use balanced truncation instead when a guaranteed H∞H_\infty error bound or guaranteed asymptotic stability is needed.

Pitfalls

  • Line L1 with a set of shifts that is not closed under conjugation. Then the reduced model is complex. The implementation raises an error. Give conjugate pairs together.
  • Line L1 with poor shifts. Shifts far from the spectrum of AA give slow convergence: for the chain with r=1r = 1 the default shift needs 70 passes. Spread the shifts over the scale of the eigenvalues of AA.
  • Line L3 with nearly equal shifts. The columns (siI−A)−1b(s_i I - A)^{-1} b are then nearly parallel, and a basis without orthonormalization is ill conditioned. The implementation orthonormalizes, and it raises an error if a column is lost.
  • Line L4 with WTVW^T V singular. Then the Petrov-Galerkin model does not exist. This happens rarely, for special shifts; change the shifts.
  • Line L5 with an eigenvalue of ArA_r in the right half plane. Its mirror image is a shift in the left half plane, perhaps near an eigenvalue of AA, and the next solve is ill conditioned. The implementation does not check this. Reflect such shifts into the right half plane.
  • Line L6 with shifts that are not matched. The change must compare each new shift with the corresponding old one. The implementation sorts both lists the same way before the comparison. Without the sort, a reordering looks like a large change.
  • Line L8 ignored. A run that hits maxiter returns the last model, which need not satisfy any optimality condition. Check the flag.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

ctlmat.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and polynomial routines for the control pages.

Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
  right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
  [1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
  every entry is an int or a Fraction, so the result is exact. With float or
  complex entries they compute in floating point.
- transpose does not conjugate complex entries.

Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
  infinity norm at most 1/2 and the series stops when a term is below
  2^-60 times the sum. For matrices that are not far from normal the relative
  error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
  well conditioned polynomial come out with a relative error near 1e-12 (the
  tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
  grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
  fourfold root. For real coefficients the output is closed under
  conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
  1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
  be positive.

This file holds no algorithm of a control page.
"""

import cmath
import math
from fractions import Fraction

__all__ = [
    "zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
    "dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
    "trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
    "polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]


def _is_exact(v):
    return isinstance(v, (int, Fraction))


def _all_exact(*mats):
    for m in mats:
        for row in m:
            if isinstance(row, list):
                for v in row:
                    if not _is_exact(v):
                        return False
            elif not _is_exact(row):
                return False
    return True


def _to_fraction(a):
    return [[Fraction(v) for v in row] for row in a]


def _shape(a):
    return len(a), (len(a[0]) if a else 0)


def zeros(n, m=None):
    """Return the n by m zero matrix (n by n if m is None), with int entries."""
    if m is None:
        m = n
    return [[0] * m for _ in range(n)]


def eye(n):
    """Return the n by n identity matrix, with int entries."""
    return [[1 if i == j else 0 for j in range(n)] for i in range(n)]


def add(a, b):
    """Return a + b."""
    if _shape(a) != _shape(b):
        raise ValueError("add: shapes differ")
    return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def sub(a, b):
    """Return a - b."""
    if _shape(a) != _shape(b):
        raise ValueError("sub: shapes differ")
    return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]


def scale(c, a):
    """Return the scalar c times the matrix a."""
    return [[c * x for x in row] for row in a]


def mul(a, b):
    """Return the matrix product a b."""
    n, k = _shape(a)
    k2, m = _shape(b)
    if k != k2:
        raise ValueError("mul: inner dimensions differ")
    bt = list(zip(*b)) if b else []
    out = []
    for row in a:
        out_row = []
        for col in bt:
            s = 0
            for x, y in zip(row, col):
                s += x * y
            out_row.append(s)
        out.append(out_row)
    return out


def transpose(a):
    """Return the transpose of a (no complex conjugation)."""
    return [list(col) for col in zip(*a)]


def matvec(a, x):
    """Return the vector a x, for a flat list x."""
    if a and len(a[0]) != len(x):
        raise ValueError("matvec: dimensions differ")
    out = []
    for row in a:
        s = 0
        for v, w in zip(row, x):
            s += v * w
        out.append(s)
    return out


def dot(x, y):
    """Return sum of x_i y_i (no complex conjugation)."""
    if len(x) != len(y):
        raise ValueError("dot: lengths differ")
    s = 0
    for v, w in zip(x, y):
        s += v * w
    return s


def _sym_eigvals(s):
    """Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
    n = len(s)
    a = [list(map(float, row)) for row in s]
    for _ in range(100):
        off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
        diag = sum(a[i][i] ** 2 for i in range(n))
        if off <= 1e-30 * max(diag, 1e-300):
            break
        for p in range(n - 1):
            for q in range(p + 1, n):
                if a[p][q] == 0.0:
                    continue
                theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
                t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
                c = 1.0 / math.sqrt(t * t + 1.0)
                sn = t * c
                for k in range(n):
                    akp, akq = a[k][p], a[k][q]
                    a[k][p] = c * akp - sn * akq
                    a[k][q] = sn * akp + c * akq
                for k in range(n):
                    apk, aqk = a[p][k], a[q][k]
                    a[p][k] = c * apk - sn * aqk
                    a[q][k] = sn * apk + c * aqk
    return [a[i][i] for i in range(n)]


def norm2(x):
    """Return the 2-norm.

    For a flat vector this is the Euclidean norm. For a matrix it is the
    induced 2-norm (the largest singular value), computed from the
    eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
    the same singular values. The result is a float.
    """
    if not x:
        return 0.0
    if not isinstance(x[0], list):
        return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
    if any(isinstance(v, complex) for row in x for v in row):
        re = [[complex(v).real for v in row] for row in x]
        im = [[complex(v).imag for v in row] for row in x]
        m = block([[re, scale(-1, im)], [im, re]])
    else:
        m = [[float(v) for v in row] for row in x]
    g = mul(transpose(m), m)
    lam = max(_sym_eigvals(g))
    return math.sqrt(max(lam, 0.0))


def block(rows):
    """Build a matrix from a list of rows of blocks.

    A block is a matrix, or the int 0 for a zero block whose size is taken
    from the other blocks in its block row and block column.
    """
    heights = []
    for r in rows:
        h = None
        for b in r:
            if isinstance(b, list):
                h = len(b)
                break
        if h is None:
            raise ValueError("block: a block row has no matrix block")
        heights.append(h)
    ncols = len(rows[0])
    widths = []
    for j in range(ncols):
        w = None
        for r in rows:
            if isinstance(r[j], list):
                w = len(r[j][0]) if r[j] else 0
                break
        if w is None:
            raise ValueError("block: a block column has no matrix block")
        widths.append(w)
    out = []
    for r, h in zip(rows, heights):
        if len(r) != ncols:
            raise ValueError("block: block rows have different lengths")
        for i in range(h):
            line = []
            for b, w in zip(r, widths):
                if isinstance(b, list):
                    if len(b) != h or (b and len(b[0]) != w):
                        raise ValueError("block: block sizes do not match")
                    line.extend(b[i])
                elif b == 0:
                    line.extend([0] * w)
                else:
                    raise ValueError("block: a scalar block must be 0")
            out.append(line)
    return out


def kron(a, b):
    """Return the Kronecker product of a and b."""
    n, m = _shape(a)
    p, q = _shape(b)
    return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]


def vec(a):
    """Stack the columns of a into one flat list."""
    n, m = _shape(a)
    return [a[i][j] for j in range(m) for i in range(n)]


def unvec(v, n, m=None):
    """Inverse of vec: return the n by m matrix whose stacked columns are v."""
    if m is None:
        m = len(v) // n
    if n * m != len(v):
        raise ValueError("unvec: length does not match the shape")
    return [[v[j * n + i] for j in range(m)] for i in range(n)]


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a flat vector or a matrix; the result has the same form. With int
    and Fraction entries the result is exact (Fraction). Raises ValueError
    if a is singular (an exactly zero pivot).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("solve: matrix is not square")
    is_vec = not (b and isinstance(b[0], list))
    rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
    if len(rhs) != n:
        raise ValueError("solve: right side has the wrong length")
    if _all_exact(a, rhs):
        aa = _to_fraction(a)
        rhs = _to_fraction(rhs)
    else:
        aa = [list(row) for row in a]
    k = len(rhs[0]) if rhs else 0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            raise ValueError("solve: matrix is singular")
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            rhs[c], rhs[p] = rhs[p], rhs[c]
        piv = aa[c][c]
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            row_r, row_c = aa[r], aa[c]
            for j in range(c, n):
                row_r[j] -= f * row_c[j]
            rr, rc = rhs[r], rhs[c]
            for j in range(k):
                rr[j] -= f * rc[j]
    x = [[0] * k for _ in range(n)]
    for c in range(n - 1, -1, -1):
        for j in range(k):
            s = rhs[c][j]
            for t in range(c + 1, n):
                s -= aa[c][t] * x[t][j]
            x[c][j] = s / aa[c][c]
    return [row[0] for row in x] if is_vec else x


def inv(a):
    """Return the inverse of a (exact with int and Fraction entries)."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of a by elimination with partial pivoting.

    With int and Fraction entries the result is an exact Fraction.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("det: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    d = Fraction(1) if _all_exact(a) else 1.0
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(aa[r][c]))
        if aa[p][c] == 0:
            return d * 0
        if p != c:
            aa[c], aa[p] = aa[p], aa[c]
            d = -d
        piv = aa[c][c]
        d *= piv
        for r in range(c + 1, n):
            f = aa[r][c] / piv
            if f == 0:
                continue
            for j in range(c, n):
                aa[r][j] -= f * aa[c][j]
    return d


def trace(a):
    """Return the sum of the diagonal entries of a."""
    s = 0
    for i in range(len(a)):
        s += a[i][i]
    return s


def charpoly(a):
    """Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.

    Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
    a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("charpoly: matrix is not square")
    aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
    coeffs = [1]
    mk = zeros(n)
    for k in range(1, n + 1):
        mk = mul(aa, mk)
        c = coeffs[-1]
        for i in range(n):
            mk[i][i] += c
        am = mul(aa, mk)
        coeffs.append(-trace(am) / k)
    return coeffs


def polyval(p, x):
    """Evaluate the polynomial p at x by Horner's rule."""
    s = 0
    for c in p:
        s = s * x + c
    return s


def _strip(p):
    i = 0
    while i < len(p) - 1 and p[i] == 0:
        i += 1
    return list(p[i:]) if p else [0]


def polyadd(p, q):
    """Return p + q, with exactly zero leading coefficients removed."""
    n = max(len(p), len(q))
    pp = [0] * (n - len(p)) + list(p)
    qq = [0] * (n - len(q)) + list(q)
    return _strip([x + y for x, y in zip(pp, qq)])


def polymul(p, q):
    """Return the product p q."""
    if not p or not q:
        return [0]
    out = [0] * (len(p) + len(q) - 1)
    for i, x in enumerate(p):
        for j, y in enumerate(q):
            out[i + j] += x * y
    return _strip(out)


def polyder(p):
    """Return the derivative of p."""
    n = len(p) - 1
    if n <= 0:
        return [0]
    return _strip([c * (n - i) for i, c in enumerate(p[:-1])])


def polyroots(p, tol=1e-15, maxiter=1000):
    """Return the complex roots of p, sorted by real part, then imaginary part.

    Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
    when every relative correction is below tol, then a Newton polish of
    each root. For real coefficients the roots are made exactly real or
    exact conjugate pairs. See the module notes for the accuracy.
    """
    c = [complex(v) for v in p]
    while c and c[0] == 0:
        c.pop(0)
    if not c:
        raise ValueError("polyroots: zero polynomial")
    real_coeffs = all(v.imag == 0 for v in c)
    origin = 0
    while len(c) > 1 and c[-1] == 0:
        c.pop()
        origin += 1
    n = len(c) - 1
    a = [v / c[0] for v in c]
    if n == 0:
        z = []
    elif n == 1:
        z = [-a[1]]
    else:
        r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
        if r == 0:
            r = 1.0
        z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
        for _ in range(maxiter):
            worst = 0.0
            for i in range(n):
                den = 1.0 + 0j
                for j in range(n):
                    if j != i:
                        den *= z[i] - z[j]
                if den == 0:
                    z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
                    worst = 1.0
                    continue
                d = polyval(a, z[i]) / den
                z[i] -= d
                worst = max(worst, abs(d) / (1.0 + abs(z[i])))
            if worst < tol:
                break
        dp = polyder(a)
        for i in range(n):
            zi = z[i]
            fz = abs(polyval(a, zi))
            for _ in range(5):
                der = polyval(dp, zi)
                if der == 0 or fz == 0:
                    break
                step = polyval(a, zi) / der
                if abs(step) > 1e-6 * (1.0 + abs(zi)):
                    break
                znew = zi - step
                fnew = abs(polyval(a, znew))
                if fnew >= fz:
                    break
                zi, fz = znew, fnew
            z[i] = zi
    z = z + [0j] * origin
    if real_coeffs:
        thr = 1e-9
        upper = [v for v in z if v.imag > thr * (1 + abs(v))]
        lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
        reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
        # A cluster of close roots can leave more roots above the real axis
        # than below it (or the other way). The extra roots nearest to the
        # axis are then taken as real, so the output is closed under
        # conjugation.
        if len(upper) < len(lower):
            upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
        upper.sort(key=lambda v: v.imag)
        extra = len(upper) - len(lower)
        reals += [complex(v.real, 0.0) for v in upper[:extra]]
        upper = upper[extra:]
        out = list(reals)
        rest = list(lower)
        for u in upper:
            w = min(rest, key=lambda v: abs(v - u.conjugate()))
            rest.remove(w)
            re = (u.real + w.real) / 2
            im = (u.imag - w.imag) / 2
            out.append(complex(re, im))
            out.append(complex(re, -im))
        z = out
    return sorted(z, key=lambda v: (v.real, v.imag))


def _norm_inf(a):
    return max((sum(abs(v) for v in row) for row in a), default=0.0)


def expm(a):
    """Return e^A in floating point by scaling and squaring with a Taylor series.

    A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
    series of the scaled matrix is summed until a term is below 2^-60 of the
    sum, and the result is squared s times. Entries of the result are float
    (complex if A has complex entries).
    """
    n, m = _shape(a)
    if n != m:
        raise ValueError("expm: matrix is not square")
    cplx = any(isinstance(v, complex) for row in a for v in row)
    conv = complex if cplx else float
    x = [[conv(v) for v in row] for row in a]
    nrm = _norm_inf(x)
    s = 0
    while nrm > 0.5:
        nrm /= 2.0
        s += 1
    x = scale(conv(2.0 ** -s), x)
    e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
    term = [row[:] for row in e]
    for k in range(1, 60):
        term = scale(1.0 / k, mul(term, x))
        e = add(e, term)
        tn = _norm_inf(term)
        if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
            break
    for _ in range(s):
        e = mul(e, e)
    return e


def mat_power(a, k):
    """Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
    n, m = _shape(a)
    if n != m:
        raise ValueError("mat_power: matrix is not square")
    if k < 0:
        a = inv(a)
        k = -k
    result = eye(n)
    base = [list(row) for row in a]
    while k:
        if k & 1:
            result = mul(result, base)
        k >>= 1
        if k:
            base = mul(base, base)
    return result


def is_symmetric(a, tol=0):
    """Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
    n, m = _shape(a)
    if n != m:
        return False
    return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))


def is_pos_def(a, margin=0):
    """Return True if a is symmetric and a - margin I is positive definite.

    With int and Fraction entries (and an exact margin) the test is exact:
    every leading principal minor of a - margin I must be positive
    (Sylvester's criterion), computed in Fraction. With float entries the
    matrix must be symmetric within 1e-12 times its largest entry, and the
    Cholesky factorization of a - margin I must have positive pivots.
    Complex entries are not accepted.
    """
    n, m = _shape(a)
    if n != m:
        return False
    if any(isinstance(v, complex) for row in a for v in row):
        raise ValueError("is_pos_def: complex entries are not accepted")
    if _all_exact(a) and _is_exact(margin):
        b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
        if not is_symmetric(b):
            return False
        return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
    b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
    big = max((abs(float(v)) for row in a for v in row), default=0.0)
    if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
        return False
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
        if not d > 0.0:
            return False
        low[j][j] = math.sqrt(d)
        for i in range(j + 1, n):
            low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
    return True


def _self_test():
    a = [[0, 1], [-2, -3]]
    assert charpoly(a) == [1, 3, 2]
    assert det(a) == 2
    assert mul(inv(a), a) == eye(2)
    assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
    r = polyroots([1, 3, 2])
    assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
    t = 0.7
    e = expm([[0.0, t], [-t, 0.0]])
    want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
    assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
    assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
    assert not is_pos_def([[1, 2], [2, 1]])
    assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
    return True


if __name__ == "__main__":
    _self_test()
iterative_rational_krylov.py 178 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterative-rational-krylov/. The authors are listed in prov/P106V2.jsonl.

"""The iterative rational Krylov algorithm (IRKA) for SISO systems.

For G(s) = c (s I - A)^(-1) b with A Hurwitz, IRKA looks for a reduced model
G_r of order r that satisfies the first-order conditions for a local minimum
of the H2 error ||G - G_r||_H2: G_r must interpolate G and G' at the mirror
images -lambda_i of its own poles lambda_i.

One step takes shifts s_1, ..., s_r (closed under conjugation), builds

    V = [(s_1 I - A)^(-1) b, ..., (s_r I - A)^(-1) b]
    W = [(s_1 I - A^T)^(-1) c^T, ..., (s_r I - A^T)^(-1) c^T]

and the Petrov-Galerkin model A_r = (W^T V)^(-1) W^T A V,
b_r = (W^T V)^(-1) W^T b, c_r = c V. Then the new shifts are -eig(A_r).
The step stops when the shifts stop moving.

For a conjugate pair of shifts the two complex columns are replaced by the
real and imaginary parts of one of them. That leaves the column space the
same, so the reduced transfer function is the same, and all reduced
matrices are real. The bases are orthonormalized for conditioning; that also
leaves the spaces the same.
"""

import math

from ctlmat import charpoly, eye, kron, mul, polyroots, solve, transpose, unvec, vec

__all__ = [
    "project", "irka", "default_shifts", "transfer", "transfer_derivative",
    "h2_norm", "h2_error", "poles",
]


def _gram_schmidt(cols):
    """Orthonormalize real column vectors (twice, for stability)."""
    out = []
    for v in cols:
        w = list(v)
        for _ in range(2):
            for q in out:
                h = sum(x * y for x, y in zip(q, w))
                w = [x - h * y for x, y in zip(w, q)]
        nrm = math.sqrt(sum(x * x for x in w))
        if nrm == 0.0:
            raise ValueError("the projection basis is rank deficient")
        out.append([x / nrm for x in w])
    return out


def _real_basis(mat, vec_b, shifts):
    """Return real columns spanning {(s I - mat)^(-1) vec_b : s in shifts}."""
    n = len(mat)
    cols = []
    for s in shifts:
        if s.imag < 0:
            continue
        m = [[(s if i == j else 0) - mat[i][j] for j in range(n)] for i in range(n)]
        if s.imag == 0:
            x = solve([[float(v.real) for v in row] for row in m], [float(v) for v in vec_b])
            cols.append(x)
        else:
            x = solve(m, [complex(v) for v in vec_b])
            cols.append([v.real for v in x])
            cols.append([v.imag for v in x])
    return _gram_schmidt(cols)


def poles(a):
    """Return the eigenvalues of a small real matrix (roots of its characteristic polynomial)."""
    return polyroots(charpoly([[float(v) for v in row] for row in a]))


def project(a, b, c, shifts):
    """Return (A_r, b_r, c_r) of the rational Krylov projection at the shifts.

    a is n by n, b is a flat list of length n (the input column), c is a
    flat list (the output row). shifts is a list of complex numbers, closed
    under conjugation. The result interpolates G and G' at every shift.
    """
    af = [[float(v) for v in row] for row in a]
    v_cols = _real_basis(af, b, shifts)  # @line L3
    w_cols = _real_basis(transpose(af), c, shifts)
    r = len(v_cols)
    if r != len(w_cols) or r != len(shifts):
        raise ValueError("shifts must be closed under conjugation")
    v = transpose(v_cols)
    w = transpose(w_cols)
    wt = w_cols
    e = mul(wt, v)
    ar = solve(e, mul(mul(wt, af), v))  # @line L4
    br = solve(e, [sum(wt[i][k] * b[k] for k in range(len(b))) for i in range(r)])
    cr = [sum(c[k] * v[k][j] for k in range(len(c))) for j in range(r)]
    return ar, br, cr


def default_shifts(a, r):
    """Return r real shifts spread geometrically over the spectrum scale of A.

    The ends are 1 / ||A^(-1)||_inf and ||A||_inf, which bound the smallest
    and largest eigenvalue magnitudes from below and above.
    """
    af = [[float(v) for v in row] for row in a]
    inv_a = solve(af, eye(len(af)))
    lo = 1.0 / max(sum(abs(x) for x in row) for row in inv_a)
    hi = max(sum(abs(x) for x in row) for row in af)
    if r == 1:
        return [complex(math.sqrt(lo * hi))]
    return [complex(lo * (hi / lo) ** (k / (r - 1))) for k in range(r)]


def _shift_key(s):
    return (round(s.real, 12), s.imag)


def irka(a, b, c, r, shifts=None, tol=1e-10, maxiter=200):
    """Run IRKA. Returns (A_r, b_r, c_r, shifts, iterations, converged).

    shifts are the final shifts, equal to -eig(A_r) at convergence. The
    iteration stops when the largest relative change of the sorted shifts
    is below tol, or after maxiter steps.
    """
    s = list(shifts) if shifts is not None else default_shifts(a, r)  # @line L1
    s = sorted((complex(x) for x in s), key=_shift_key)
    for it in range(1, maxiter + 1):  # @line L2
        ar, br, cr = project(a, b, c, s)
        new = sorted((-z for z in poles(ar)), key=_shift_key)  # @line L5
        change = max(abs(x - y) / abs(y) for x, y in zip(new, s))
        s = new
        if change < tol:  # @line L6
            return ar, br, cr, s, it, True  # @line L7
    return ar, br, cr, s, maxiter, False  # @line L8


def transfer(a, b, c, s):
    """Return c (s I - A)^(-1) b."""
    n = len(a)
    m = [[(s if i == j else 0) - a[i][j] for j in range(n)] for i in range(n)]
    x = solve([[complex(v) for v in row] for row in m], [complex(v) for v in b])
    return sum(ci * xi for ci, xi in zip(c, x))


def transfer_derivative(a, b, c, s):
    """Return G'(s) = -c (s I - A)^(-2) b."""
    n = len(a)
    m = [[complex((s if i == j else 0) - a[i][j]) for j in range(n)] for i in range(n)]
    x = solve(m, [complex(v) for v in b])
    y = solve(m, x)
    return -sum(ci * yi for ci, yi in zip(c, y))


def _lyap(a, q):
    n = len(a)
    big = [[x + y for x, y in zip(r1, r2)] for r1, r2 in zip(kron(eye(n), a), kron(a, eye(n)))]
    return unvec(solve(big, [-v for v in vec(q)]), n, n)


def h2_norm(a, b, c):
    """Return ||c (s I - A)^(-1) b||_H2 = sqrt(c P c^T), A P + P A^T + b b^T = 0."""
    af = [[float(v) for v in row] for row in a]
    p = _lyap(af, [[float(x) * float(y) for y in b] for x in b])
    val = sum(float(c[i]) * p[i][j] * float(c[j]) for i in range(len(c)) for j in range(len(c)))
    return math.sqrt(max(val, 0.0))


def h2_error(a, b, c, ar, br, cr):
    """Return ||G - G_r||_H2 from the Lyapunov equation of the error system.

    Both A and A_r must be Hurwitz.
    """
    n, r = len(a), len(ar)
    ae = [[float(a[i][j]) for j in range(n)] + [0.0] * r for i in range(n)]
    ae += [[0.0] * n + [float(ar[i][j]) for j in range(r)] for i in range(r)]
    be = [float(v) for v in b] + [float(v) for v in br]
    ce = [float(v) for v in c] + [-float(v) for v in cr]
    return h2_norm(ae, be, ce)
test_iterative_rational_krylov.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/iterative-rational-krylov/. The authors are listed in prov/P106V2.jsonl.

import math
import random

from ctlmat import mul, solve, transpose
from iterative_rational_krylov import (
    default_shifts, h2_error, h2_norm, irka, poles, project, transfer,
    transfer_derivative,
)

CHAIN_A = [[-1, 1, 0, 0], [0, -2, 1, 0], [0, 0, -3, 1], [0, 0, 0, -4]]
CHAIN_B = [0, 0, 0, 1]
CHAIN_C = [1, 0, 0, 0]


def random_stable(rng, n):
    r = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
    rho = max(sum(abs(v) for v in row) for row in r)
    a = [[r[i][j] - (rho + 0.3 if i == j else 0.0) for j in range(n)] for i in range(n)]
    b = [rng.uniform(-1, 1) for _ in range(n)]
    c = [rng.uniform(-1, 1) for _ in range(n)]
    return a, b, c


def assert_hermite(a, b, c, ar, br, cr, shifts, tol):
    for s in shifts:
        g, gr = transfer(a, b, c, s), transfer(ar, br, cr, s)
        dg, dgr = transfer_derivative(a, b, c, s), transfer_derivative(ar, br, cr, s)
        assert abs(g - gr) <= tol * (abs(g) + 1e-300)
        assert abs(dg - dgr) <= tol * (abs(dg) + 1e-300)


def test_h2_norm_of_first_order():
    # ||1/(s + a)||_H2^2 = 1/(2a)
    assert abs(h2_norm([[-1.0]], [1.0], [1.0]) - math.sqrt(0.5)) < 1e-14
    assert abs(h2_norm([[-3.0]], [2.0], [1.0]) - math.sqrt(4.0 / 6.0)) < 1e-14


def test_one_projection_interpolates_at_any_shifts():
    rng = random.Random(20)
    for _ in range(10):
        a, b, c = random_stable(rng, 6)
        shifts = [complex(rng.uniform(0.2, 3.0))]
        im = rng.uniform(0.2, 2.0)
        re = rng.uniform(0.2, 3.0)
        shifts += [complex(re, im), complex(re, -im)]
        ar, br, cr = project(a, b, c, shifts)
        assert len(ar) == 3
        assert_hermite(a, b, c, ar, br, cr, shifts, 1e-9)


def test_hermite_interpolation_on_500_random_projections():
    # oracle: G and G' evaluated directly from (A, b, c) by complex solves
    rng = random.Random(25)
    for _ in range(500):
        n = rng.randint(2, 4)
        a, b, c = random_stable(rng, n)
        r = rng.randint(1, n - 1)
        shifts = []
        while len(shifts) < r:
            if r - len(shifts) >= 2 and rng.random() < 0.5:
                re, im = rng.uniform(0.2, 3.0), rng.uniform(0.2, 2.0)
                shifts += [complex(re, im), complex(re, -im)]
            else:
                shifts.append(complex(rng.uniform(0.2, 3.0)))
        ar, br, cr = project(a, b, c, shifts)
        assert_hermite(a, b, c, ar, br, cr, shifts, 1e-7)


def test_real_and_complex_bases_give_the_same_model():
    rng = random.Random(21)
    a, b, c = random_stable(rng, 5)
    shifts = [complex(0.7, 0.9), complex(0.7, -0.9), complex(2.0, 0.0)]
    ar, br, cr = project(a, b, c, shifts)
    n = len(a)

    def col(mat, vecb, s):
        m = [[complex((s if i == j else 0) - mat[i][j]) for j in range(n)] for i in range(n)]
        return solve(m, [complex(x) for x in vecb])

    v = transpose([col(a, b, s) for s in shifts])
    w = transpose([col(transpose(a), c, s) for s in shifts])
    wt = transpose(w)
    e = mul(wt, v)
    ac = solve(e, mul(mul(wt, [[complex(x) for x in row] for row in a]), v))
    bc = solve(e, [sum(wt[i][k] * b[k] for k in range(n)) for i in range(3)])
    cc = [sum(c[k] * v[k][j] for k in range(n)) for j in range(3)]
    for s in [0.1j, 1.0 + 1.0j, 4.0, -0.5 + 3j]:
        g1, g2 = transfer(ar, br, cr, s), transfer(ac, bc, cc, s)
        assert abs(g1 - g2) < 1e-10 * abs(g1)


def test_converged_model_meets_h2_conditions():
    rng = random.Random(22)
    done = 0
    for _ in range(6):
        a, b, c = random_stable(rng, 6)
        for r in (1, 2, 3):
            ar, br, cr, s, it, ok = irka(a, b, c, r)
            if not ok:
                continue
            done += 1
            # the shifts are the mirror images of the reduced poles
            lam = sorted((-z for z in poles(ar)), key=lambda z: (round(z.real, 8), z.imag))
            ss = sorted(s, key=lambda z: (round(z.real, 8), z.imag))
            for x, y in zip(lam, ss):
                assert abs(x - y) < 1e-8 * abs(y)
            assert all(z.real < 0 for z in poles(ar))
            assert_hermite(a, b, c, ar, br, cr, s, 1e-7)
    assert done >= 15


def test_r1_against_brute_force():
    # For G_r = phi/(s + lam), the error is ||G||^2 - 2 phi G(lam) + phi^2/(2 lam).
    # The best phi is 2 lam G(lam), so the best lam maximizes 2 lam G(lam)^2.
    a, b, c = CHAIN_A, CHAIN_B, CHAIN_C

    def score(lam):
        return 2 * lam * transfer(a, b, c, lam).real ** 2

    grid = [10 ** (k / 2000.0) for k in range(-4000, 2001)]
    best = max(grid, key=score)
    lo, hi = best / 1.01, best * 1.01
    for _ in range(100):
        m1, m2 = lo + (hi - lo) / 3, hi - (hi - lo) / 3
        if score(m1) < score(m2):
            lo = m1
        else:
            hi = m2
    lam = (lo + hi) / 2
    ar, br, cr, s, it, ok = irka(a, b, c, 1)
    assert ok
    assert abs(s[0].real - lam) < 1e-6 * lam
    g2 = h2_norm(a, b, c) ** 2
    assert abs(h2_error(a, b, c, ar, br, cr) - math.sqrt(g2 - score(lam))) < 1e-10


def test_chain_example_of_the_page():
    a, b, c = CHAIN_A, CHAIN_B, CHAIN_C
    assert abs(h2_norm(a, b, c) - 0.0222718) < 1e-7
    ar, br, cr, s, it, ok = irka(a, b, c, 2)
    assert ok
    assert abs(s[0] - complex(0.698811, -0.581699)) < 1e-6
    assert abs(h2_error(a, b, c, ar, br, cr) - 0.00281857) < 1e-8
    want = {1: 0.0127419, 3: 0.000223404}
    for r, e in want.items():
        red = irka(a, b, c, r)
        assert red[5]
        assert abs(h2_error(a, b, c, *red[:3]) - e) < 1e-6 * e * 10


def test_perturbations_do_not_lower_the_error():
    rng = random.Random(23)
    a, b, c = CHAIN_A, CHAIN_B, CHAIN_C
    ar, br, cr, s, it, ok = irka(a, b, c, 2)
    assert ok
    e0 = h2_error(a, b, c, ar, br, cr)
    for _ in range(40):
        d = 1e-3
        ap = [[x + d * rng.uniform(-1, 1) * abs(x) for x in row] for row in ar]
        bp = [x + d * rng.uniform(-1, 1) * abs(x) for x in br]
        cp = [x + d * rng.uniform(-1, 1) * abs(x) for x in cr]
        assert h2_error(a, b, c, ap, bp, cp) >= e0 - 1e-13


def test_full_order_reproduces_g():
    rng = random.Random(24)
    a, b, c = random_stable(rng, 4)
    ar, br, cr, s, it, ok = irka(a, b, c, 4)
    assert ok
    for z in [0.5j, 2.0, 1.0 + 3.0j]:
        g = transfer(a, b, c, z)
        assert abs(g - transfer(ar, br, cr, z)) < 1e-9 * abs(g)
    assert h2_error(a, b, c, ar, br, cr) < 1e-7 * h2_norm(a, b, c)


def test_default_shifts_are_positive_and_spread():
    s = default_shifts(CHAIN_A, 3)
    assert all(z.imag == 0 and z.real > 0 for z in s)
    assert s[0].real < s[1].real < s[2].real

History

Meier and Luenberger (1967) derived the first-order conditions for the H2H_2 optimal approximation of a system with one input and one output: the reduced model must interpolate GG and G′G' at the mirror images of its poles. Many methods for H2H_2 optimal reduction followed, most based on Lyapunov or Sylvester equations. Gugercin, Antoulas and Beattie (2008) reformulated the conditions as interpolation by a rational Krylov projection and proposed the fixed-point iteration, which needs only linear solves and so applies to large systems. Flagg, Beattie and Gugercin (2012) proved local convergence for state-space-symmetric systems.

References

  1. S. Gugercin, A. C. Antoulas and C. Beattie, H2 model reduction for large-scale linear dynamical systems, SIAM Journal on Matrix Analysis and Applications 30(2), 609-638, 2008, the interpolation conditions for H2 optimality and the iterative rational Krylov algorithm
  2. L. Meier and D. G. Luenberger, Approximation of linear constant systems, IEEE Transactions on Automatic Control 12(5), 585-588, 1967, the first-order necessary conditions for an H2 optimal approximation, as interpolation of G and G' at the mirrored reduced poles
  3. G. Flagg, C. Beattie and S. Gugercin, Convergence of the iterative rational Krylov algorithm, Systems and Control Letters 61(6), 688-691, 2012, the local convergence of the iteration for state-space-symmetric systems

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example