Algorithm Search⌘K

Algorithmadvanced

Balanced truncation

Also called Moore balanced truncation.

Reduces an asymptotically stable linear system by deleting the balanced states with small Hankel singular values, with a guaranteed H-infinity error bound.

Time
O(n^3 + n^2 (m + p)) worst
Space
O(n^2) extra
Where
m = the number of inputs; n = the number of states; p = the number of outputs; r = the reduced order
Properties
deterministicnot exactofflineiterative
Origin
Bruce C. Moore, Lars Pernebo, Leonard M. Silverman, Dale F. Enns, Keith Glover, 1981

Balanced truncation makes a small model out of a large one. It applies to an asymptotically stable linear system, given by matrices AA, BB, CC, DD with nn internal states, and it returns a system with r<nr < n states whose response to every input is close to the original response. The method first measures, for each direction in the state space, how strongly the inputs drive it and how strongly the outputs show it. These two measures are matrices, the controllability Gramian and the observability Gramian. A change of coordinates, the balanced realization, makes them equal and diagonal. The diagonal entries, the Hankel singular values σ1≥⋯≥σn\sigma_1 \ge \dots \ge \sigma_n, rank the states, and the method keeps the first rr and deletes the rest. The result is guaranteed to be asymptotically stable, with ArA_r Hurwitz, when σr>σr+1\sigma_r > \sigma_{r+1}, and its worst-case gain error over all frequencies, the H-infinity norm of G−GrG - G_r, is at most twice the sum of the distinct deleted values (Enns 1984, Glover 1984). No model of order rr can do better than σr+1\sigma_{r+1}, so the method is within a factor of about 2(n−r)2(n - r) of the best possible in the worst case, and usually much closer. Moore (1981) introduced it; it is the standard method of model order reduction for dense models with up to a few thousand states.

In plain words

A large model has many internal variables, but most of them matter little for what goes from the inputs to the outputs. Some are hard to move with the inputs. Others move but barely show in the outputs. A variable is worth keeping only if it is both easy to move and easy to see. The method first turns the model so that these two qualities are measured on the same scale for each internal direction. Then it sorts the directions by that common measure and throws away the weakest ones. The thrown-away measures also give a guarantee: the small model's error, for any input, is at most twice their sum.

The problem

Input: A∈Rn×nA \in \mathbb{R}^{n \times n} Hurwitz, B∈Rn×mB \in \mathbb{R}^{n \times m}, C∈Rp×nC \in \mathbb{R}^{p \times n}, D∈Rp×mD \in \mathbb{R}^{p \times m} and an order 0≤r≤n0 \le r \le n. Output: Ar∈Rr×rA_r \in \mathbb{R}^{r \times r}, Br∈Rr×mB_r \in \mathbb{R}^{r \times m}, Cr∈Rp×rC_r \in \mathbb{R}^{p \times r}, Dr=DD_r = D, the Hankel singular values σ1≥⋯≥σn\sigma_1 \ge \dots \ge \sigma_n, and the bound

∥G−Gr∥∞≤2∑distinct σk, k>rσk,\|G - G_r\|_\infty \le 2 \sum_{\text{distinct } \sigma_k,\ k > r} \sigma_k,

where G(s)=C(sI−A)−1B+DG(s) = C(sI - A)^{-1}B + D and Gr(s)=Cr(sI−Ar)−1Br+DG_r(s) = C_r(sI - A_r)^{-1}B_r + D. The reduced model must be the truncation of a balanced realization of GG. If 0<r<n0 < r < n and σr=σr+1\sigma_r = \sigma_{r+1}, the cut would split a repeated value; the theorem then gives no guarantee, and the implementation refuses.

The algorithm

  1. BALANCED-TRUNCATION(A, B, C, D, r)
  2. 1W_c, W_o ← solve A W_c + W_c Aᵀ + B Bᵀ = 0 and Aᵀ W_o + W_o A + Cᵀ C = 0
  3. 2L_c, L_o ← factors with W_c = L_c L_cᵀ and W_o = L_o L_oᵀ
  4. 3U Σ Vᵀ ← SVD of L_oᵀ L_c ▷ σ_1 ≥ ... ≥ σ_n ≥ 0
  5. 4if 0 < r < n and σ_r = σ_(r+1) then fail ▷ a gap is needed
  6. 5T_r ← L_c V_r Σ_r^(-1/2); W_r ← L_o U_r Σ_r^(-1/2)
  7. 6A_r ← W_rᵀ A T_r; B_r ← W_rᵀ B; C_r ← C T_r; D_r ← D
  8. 7bound ← 2 · (sum of the distinct values among σ_(r+1), ..., σ_n)
  9. 8return (A_r, B_r, C_r, D_r, σ, bound)

Line L1 solves the two Lyapunov equations for the Gramians. Libraries use the Bartels-Stewart method or Hammarling's method, which work on a Schur form of AA and cost O(n3)O(n^3). The implementation solves the Kronecker form (I⊗A+A⊗I)vec⁡W=−vec⁡(BBT)(I \otimes A + A \otimes I)\operatorname{vec} W = -\operatorname{vec}(BB^T) directly, which costs O(n6)O(n^6) and is used only for the small test systems. Line L2 takes square-root factors. Libraries take Cholesky factors, usually computed directly from the Lyapunov equation; the implementation uses L=QΛ1/2L = Q \Lambda^{1/2} from a symmetric eigendecomposition, which also works when a Gramian is singular. Line L3 is the square-root step of Laub, Heath, Paige and Ward (1987): the singular values of LoTLcL_o^T L_c are the Hankel singular values. Line L4 checks the gap, with the tolerance σr−σr+1≤10−9σ1\sigma_r - \sigma_{r+1} \le 10^{-9} \sigma_1 in the code. Line L5 builds only the first rr columns of the balancing transformation T=LcVΣ−1/2T = L_c V \Sigma^{-1/2} and of T−T=LoUΣ−1/2T^{-T} = L_o U \Sigma^{-1/2}, with VrV_r and UrU_r the first rr columns of VV and UU; the full TT is never formed or inverted. Line L6 projects. Line L7 computes the bound, with values that agree within 10−9σ110^{-9}\sigma_1 counted once.

Example

A chain of four first-order sections. A=[−11000−21000−31000−4]A = \begin{bmatrix} -1 & 1 & 0 & 0 \\ 0 & -2 & 1 & 0 \\ 0 & 0 & -3 & 1 \\ 0 & 0 & 0 & -4 \end{bmatrix}, B=e4B = e_4, C=e1TC = e_1^T, D=0D = 0, so G(s)=1/((s+1)(s+2)(s+3)(s+4))G(s) = 1/((s+1)(s+2)(s+3)(s+4)). Line L3 gives σ=(0.0279876,0.00821788,0.00112693,0.0000632855)\sigma = (0.0279876, 0.00821788, 0.00112693, 0.0000632855). The norm of GG is ∥G∥∞=G(0)=1/24=0.041667\|G\|_\infty = G(0) = 1/24 = 0.041667. The table lists, for each rr, the error measured on a frequency grid, the lower bound σr+1\sigma_{r+1}, the bound of line L7, the poles of GrG_r and its gain at s=0s = 0.

rr σr+1\sigma_{r+1} ∥G−Gr∥∞\|G - G_r\|_\infty (grid) bound (L7) poles of GrG_r Gr(0)G_r(0)
0 0.027988 0.041667 0.074791 none 0
1 0.0082179 0.014601 0.018816 −0.21816-0.21816 0.055975
2 0.0011269 0.0021479 0.0023804 −0.65319±0.60793i-0.65319 \pm 0.60793i 0.039539
3 0.0000632855 0.00012657 0.00012657 −0.87126-0.87126, −1.64055±1.07396i-1.64055 \pm 1.07396i 0.041793

Every error lies between σr+1\sigma_{r+1} and the bound, as the theorems require. For r=3r = 3 the error on the grid equals 2σ42\sigma_4 within 10−1210^{-12}, so the bound is attained (a measurement; the tests check it). The reduced poles are not a subset of the original poles −1,−2,−3,−4-1, -2, -3, -4: balanced truncation does not keep modes, it keeps directions. With r=2r = 2 the model has two states and a relative error of 0.0021479/0.041667=5.20.0021479 / 0.041667 = 5.2 percent. The gain at s=0s = 0 is not kept: for r=1r = 1 it is 0.0560.056 instead of 0.0420.042.

Two modes. For G(s)=1/(s+1)+1/(s+3)G(s) = 1/(s+1) + 1/(s+3), the balanced realization page gives the balanced form; truncation to r=1r = 1 gives G1(s)=1.83205/(s+1.44530)G_1(s) = 1.83205/(s + 1.44530) with error 0.065741=2σ20.065741 = 2\sigma_2, again the bound, attained at ω=0\omega = 0.

Correctness

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

  1. The values are right. The singular values of LoTLcL_o^T L_c are the square roots of the eigenvalues of LcTLoLoTLcL_c^T L_o L_o^T L_c, which has the same nonzero eigenvalues as LcLcTLoLoT=WcWoL_c L_c^T L_o L_o^T = W_c W_o.
  2. The projection is oblique and exact. From LoTLcVr=UrΣrL_o^T L_c V_r = U_r \Sigma_r and LcTLoUr=VrΣrL_c^T L_o U_r = V_r \Sigma_r follows WrTTr=Σr−1/2UrTLoTLcVrΣr−1/2=IrW_r^T T_r = \Sigma_r^{-1/2} U_r^T L_o^T L_c V_r \Sigma_r^{-1/2} = I_r.
  3. The reduced model is balanced. WcWr=TrΣrW_c W_r = T_r \Sigma_r and WoTr=WrΣrW_o T_r = W_r \Sigma_r. Multiplying the full Lyapunov equations by WrTW_r^T and WrW_r, or by TrTT_r^T and TrT_r, gives ArΣr+ΣrArT+BrBrT=0A_r \Sigma_r + \Sigma_r A_r^T + B_r B_r^T = 0 and ArTΣr+ΣrAr+CrTCr=0A_r^T \Sigma_r + \Sigma_r A_r + C_r^T C_r = 0.
  4. It is the truncation of a balanced realization. When the system is minimal, T=LcVΣ−1/2T = L_c V \Sigma^{-1/2} balances it, TrT_r is its first rr columns and WrTW_r^T the first rr rows of T−1T^{-1}, so (Ar,Br,Cr)(A_r, B_r, C_r) is the leading block of the balanced realization.
  5. Stability and the bound. If σr>σr+1\sigma_r > \sigma_{r+1}, ArA_r is Hurwitz (Pernebo and Silverman 1982) and the bound of line L7 holds (Enns 1984, Glover 1984). The proof is on the error bound page.

The tests check the Gramians by their Lyapunov residuals, the values against the square roots of the roots of det⁡(sI−WcWo)\det(sI - W_c W_o) on 500 random systems, the invariance under a change of coordinates, the balanced Gramians and the stability of ArA_r, the error between σr+1\sigma_{r+1} and the bound on a grid, and the cases where the bound is attained.

Proof: The square root method returns a balanced reduced model with gramians diag(sigma_1, ..., sigma_r), and its error obeys the twice-the-tail boundfull

Let A∈Rn×nA \in \mathbb{R}^{n \times n} be Hurwitz, B∈Rn×mB \in \mathbb{R}^{n \times m}, C∈Rp×nC \in \mathbb{R}^{p \times n} and D∈Rp×mD \in \mathbb{R}^{p \times m}, with G(s)=C(sI−A)−1B+DG(s) = C (sI - A)^{-1} B + D. The gramians are the unique solutions of

AWc+WcAT+BBT=0,ATWo+WoA+CTC=0.A W_c + W_c A^T + B B^T = 0, \qquad A^T W_o + W_o A + C^T C = 0.

They are symmetric positive semidefinite, because Wc=∫0∞eAtBBTeATt dtW_c = \int_0^\infty e^{At} B B^T e^{A^T t}\, dt and Wo=∫0∞eATtCTCeAt dtW_o = \int_0^\infty e^{A^T t} C^T C e^{At}\, dt (see Lyapunov equation). The algorithm takes any square factors Lc,Lo∈Rn×nL_c, L_o \in \mathbb{R}^{n \times n} with Wc=LcLcTW_c = L_c L_c^T and Wo=LoLoTW_o = L_o L_o^T, and a singular value decomposition

M=LoTLc=UΣVT,Σ=diag⁡(σ1,…,σn),σ1≥⋯≥σn≥0,M = L_o^T L_c = U \Sigma V^T, \qquad \Sigma = \operatorname{diag}(\sigma_1, \dots, \sigma_n), \quad \sigma_1 \ge \dots \ge \sigma_n \ge 0,

with UU and VV orthogonal. For 1≤r≤n1 \le r \le n with σr>0\sigma_r > 0, let UrU_r and VrV_r be the first rr columns of UU and VV, Σr=diag⁡(σ1,…,σr)\Sigma_r = \operatorname{diag}(\sigma_1, \dots, \sigma_r), and

Tr=LcVrΣr−1/2,Wr=LoUrΣr−1/2,Ar=WrTATr,Br=WrTB,Cr=CTr,Dr=D.T_r = L_c V_r \Sigma_r^{-1/2}, \quad W_r = L_o U_r \Sigma_r^{-1/2}, \quad A_r = W_r^T A T_r, \quad B_r = W_r^T B, \quad C_r = C T_r, \quad D_r = D.

Lemma 1: the sigma_i are the Hankel singular values

σi2\sigma_i^2 are the eigenvalues of WcWoW_c W_o, so the σi\sigma_i do not depend on the choice of factors.

Proof. WcWo=Lc(LcTLoLoT)W_c W_o = L_c (L_c^T L_o L_o^T). For square matrices XX and YY, XYXY and YXYX have the same characteristic polynomial. With X=LcX = L_c and Y=LcTLoLoTY = L_c^T L_o L_o^T, YX=LcTLoLoTLc=MTM=VΣ2VTYX = L_c^T L_o L_o^T L_c = M^T M = V \Sigma^2 V^T, whose eigenvalues are σ12,…,σn2\sigma_1^2, \dots, \sigma_n^2. □\square

Lemma 2: the two singular vector identities

MVr=UrΣrM V_r = U_r \Sigma_r and MTUr=VrΣrM^T U_r = V_r \Sigma_r.

Proof. MV=UΣVTV=UΣM V = U \Sigma V^T V = U \Sigma and MTU=VΣUTU=VΣM^T U = V \Sigma U^T U = V \Sigma. Take the first rr columns. □\square

Lemma 3: the projection is oblique and exact on its range

WrTTr=IrW_r^T T_r = I_r, so Π=TrWrT\Pi = T_r W_r^T is a projection and (Ar,Br,Cr)(A_r, B_r, C_r) is the Petrov-Galerkin projection of (A,B,C)(A, B, C) onto im⁡Tr\operatorname{im} T_r along ker⁡WrT\ker W_r^T.

Proof. WrTTr=Σr−1/2UrTLoTLcVrΣr−1/2=Σr−1/2UrTMVrΣr−1/2=Σr−1/2UrTUrΣrΣr−1/2=IrW_r^T T_r = \Sigma_r^{-1/2} U_r^T L_o^T L_c V_r \Sigma_r^{-1/2} = \Sigma_r^{-1/2} U_r^T M V_r \Sigma_r^{-1/2} = \Sigma_r^{-1/2} U_r^T U_r \Sigma_r \Sigma_r^{-1/2} = I_r, by Lemma 2. □\square

Lemma 4: the gramians act on the projection bases by Sigma_r

WcWr=TrΣrW_c W_r = T_r \Sigma_r and WoTr=WrΣrW_o T_r = W_r \Sigma_r.

Proof. WcWr=LcLcTLoUrΣr−1/2=LcMTUrΣr−1/2=LcVrΣrΣr−1/2=TrΣrW_c W_r = L_c L_c^T L_o U_r \Sigma_r^{-1/2} = L_c M^T U_r \Sigma_r^{-1/2} = L_c V_r \Sigma_r \Sigma_r^{-1/2} = T_r \Sigma_r. In the same way, WoTr=LoLoTLcVrΣr−1/2=LoMVrΣr−1/2=LoUrΣr1/2=WrΣrW_o T_r = L_o L_o^T L_c V_r \Sigma_r^{-1/2} = L_o M V_r \Sigma_r^{-1/2} = L_o U_r \Sigma_r^{1/2} = W_r \Sigma_r. Both use Lemma 2. □\square

Theorem 1: the reduced model is balanced

ArΣr+ΣrArT+BrBrT=0A_r \Sigma_r + \Sigma_r A_r^T + B_r B_r^T = 0 and ArTΣr+ΣrAr+CrTCr=0A_r^T \Sigma_r + \Sigma_r A_r + C_r^T C_r = 0.

Proof. Multiply the controllability equation on the left by WrTW_r^T and on the right by WrW_r:

WrTA(WcWr)+(WrTWc)ATWr+WrTBBTWr=0.W_r^T A (W_c W_r) + (W_r^T W_c) A^T W_r + W_r^T B B^T W_r = 0.

By Lemma 4, WcWr=TrΣrW_c W_r = T_r \Sigma_r, and its transpose is WrTWc=ΣrTrTW_r^T W_c = \Sigma_r T_r^T. So the left side is ArΣr+ΣrArT+BrBrTA_r \Sigma_r + \Sigma_r A_r^T + B_r B_r^T. Multiply the observability equation on the left by TrTT_r^T and on the right by TrT_r, and use WoTr=WrΣrW_o T_r = W_r \Sigma_r and TrTWo=ΣrWrTT_r^T W_o = \Sigma_r W_r^T:

TrTATWrΣr+ΣrWrTATr+TrTCTCTr=ArTΣr+ΣrAr+CrTCr=0.□T_r^T A^T W_r \Sigma_r + \Sigma_r W_r^T A T_r + T_r^T C^T C T_r = A_r^T \Sigma_r + \Sigma_r A_r + C_r^T C_r = 0. \qquad \square

If ArA_r is Hurwitz, the gramians of the reduced model are the unique solutions of these equations, so both are Σr\Sigma_r. The reduced model is then balanced, and its Hankel singular values are σ1,…,σr\sigma_1, \dots, \sigma_r.

Theorem 2: the reduced model is the truncation of a balanced realization

Assume σn>0\sigma_n > 0 (the realization is minimal). Let T=LcVΣ−1/2T = L_c V \Sigma^{-1/2}. Then T−1=Σ−1/2UTLoTT^{-1} = \Sigma^{-1/2} U^T L_o^T, the realization (T−1AT,T−1B,CT)(T^{-1} A T, T^{-1} B, C T) is balanced with both gramians equal to Σ\Sigma, and (Ar,Br,Cr)(A_r, B_r, C_r) is its leading r×rr \times r, r×mr \times m and p×rp \times r block.

Proof. Lemma 3 with r=nr = n gives (Σ−1/2UTLoT)T=I(\Sigma^{-1/2} U^T L_o^T) T = I, so this is the inverse. The new gramians are T−1WcT−TT^{-1} W_c T^{-T} and TTWoTT^T W_o T. Lemma 4 with r=nr = n gives WcWn=TΣW_c W_n = T \Sigma, where WnT=T−1W_n^T = T^{-1}. So T−1WcT−T=T−1(WcWn)=T−1TΣ=ΣT^{-1} W_c T^{-T} = T^{-1} (W_c W_n) = T^{-1} T \Sigma = \Sigma, and TTWoT=TTWnΣ=ΣT^T W_o T = T^T W_n \Sigma = \Sigma. The first rr columns of TT are TrT_r and the first rr rows of T−1T^{-1} are WrTW_r^T, so the leading blocks are WrTATrW_r^T A T_r, WrTBW_r^T B and CTrC T_r. □\square

Theorem 3: stability and the error bound

Assume σn>0\sigma_n > 0 and σr>σr+1\sigma_r > \sigma_{r+1}. Then ArA_r is Hurwitz, and

σr+1≤∥G−Gr∥H∞≤2∑kτk,\sigma_{r+1} \le \|G - G_r\|_{\mathcal{H}_\infty} \le 2 \sum_{k} \tau_k,

where τ1>τ2>…\tau_1 > \tau_2 > \dots are the distinct values among σr+1,…,σn\sigma_{r+1}, \dots, \sigma_n.

Proof. By Theorem 2, GrG_r is the truncation of a balanced realization of GG. The balanced truncation error bound theorem gives both claims for such a truncation; its proof is on that page. The lower bound holds for every model of order rr, not only for this one. □\square

The checks in the implementation

The implementation raises ValueError when 0<r<n0 < r < n and σr−σr+1≤rtol⋅σ1\sigma_r - \sigma_{r+1} \le \text{rtol} \cdot \sigma_1, because then the hypothesis of Theorem 3 fails or cannot be decided in floating point. It also raises when σr=0\sigma_r = 0, because Σr−1/2\Sigma_r^{-1/2} does not exist. The function error_bound counts two computed values as one distinct value when they differ by at most rtol⋅σ1\text{rtol} \cdot \sigma_1. In exact arithmetic this is the bound of Theorem 3. In floating point, values that are equal in exact arithmetic come out with a small difference, and without the grouping the bound would count them twice and be up to twice too large.

For a realization that is not minimal (σn=0\sigma_n = 0), Theorem 1 still holds, because its proof does not use σn>0\sigma_n > 0. The tests check this case on a system with one uncontrollable state.

Complexity

With dense matrices, and counting floating-point operations:

  • Line L1 costs O(n3+n2(m+p))O(n^3 + n^2 (m + p)) by the Bartels-Stewart method; the Kronecker solve of the implementation costs O(n6)O(n^6) time and O(n4)O(n^4) space.
  • Lines L2 and L3 cost O(n3)O(n^3), for the factorizations and the SVD.
  • Lines L5 and L6 cost O(n2r+nr(m+p))O(n^2 r + n r (m + p)).
  • Line L7 costs O(n)O(n) after the sort.

So the time is O(n3+n2(m+p))O(n^3 + n^2(m + p)) and the extra space is O(n2)O(n^2). The dense cost limits the method to about n≤104n \le 10^4 on one computer. For large sparse AA, low-rank factors LcL_c and LoL_o with few columns come from iterative Lyapunov solvers, and lines L3 to L6 then cost O(nk2)O(n k^2) for factors with kk columns.

Rounding. In the floating-point model with unit roundoff uu, the SVD in line L3 is backward stable in the 2-norm: the computed values are the exact singular values of LoTLc+EL_o^T L_c + E with ∥E∥2=O(u∥Lo∥2∥Lc∥2)\|E\|_2 = O(u \|L_o\|_2 \|L_c\|_2), so each computed σi\sigma_i has absolute error O(u σ1)O(u\, \sigma_1) relative to the computed factors (a theorem, see backward error analysis). The Lyapunov solvers give small residuals but are not backward stable in the Frobenius norm in general (Higham's analysis of the Sylvester equation). So values below about u σ1u\, \sigma_1 carry no information, and a cut there is not meaningful (a rule of thumb). Line L3 avoids forming WcWoW_c W_o, whose eigenvalues σi2\sigma_i^2 would lose the small values below u σ1\sqrt{u}\, \sigma_1 instead.

Properties

  • Asymptotic stability is kept, with ArA_r Hurwitz, when σr>σr+1\sigma_r > \sigma_{r+1} (a theorem). Without the gap the truncated model can have poles on the imaginary axis.
  • The error bound holds in the H∞H_\infty norm, with each distinct value counted once (a theorem). The error is also at least σr+1\sigma_{r+1}, as for every model of order rr (a theorem).
  • The reduced model is balanced and minimal, with Hankel singular values σ1,…,σr\sigma_1, \dots, \sigma_r (a theorem). So reducing further from GrG_r gives the same result as reducing from GG.
  • It does not depend on the realization. A change of coordinates of (A,B,C)(A, B, C) changes the Gramians by congruences and leaves GrG_r the same, up to the sign freedom of the balanced realization (a theorem).
  • High frequencies are matched. Gr(∞)=D=G(∞)G_r(\infty) = D = G(\infty), and the error tends to zero as ω→∞\omega \to \infty. The gain at s=0s = 0 is not matched in general.
  • Not optimal. The result is not the best model of order rr in the H∞H_\infty, H2H_2 or Hankel norm. On the chain example, the iterative rational Krylov algorithm gives slightly smaller H2H_2 errors for r=1,2,3r = 1, 2, 3 (a measurement).

Variants and improvements

  • Balanced singular perturbation approximation. Partition the balanced system and set x˙2=0\dot x_2 = 0 instead of x2=0x_2 = 0 (see singular perturbation method). The result matches G(0)G(0), keeps asymptotic stability and has the same error bound. Use it when the steady-state gain matters.
  • Balancing-free square-root method. Replace TrT_r and WrW_r by orthonormal bases of the same column spaces, which gives a better conditioned projection with the same GrG_r.
  • Frequency-weighted balanced truncation (Enns 1984). Use the Gramians of the system with input and output weights. It is used for controller reduction. The general bound does not hold for it, and asymptotic stability can be lost unless the method is modified.
  • Low-rank balanced truncation. For large sparse systems, compute low-rank Cholesky factors of the Gramians with alternating direction implicit or rational Krylov iterations, and apply lines L3 to L6 to them.
  • Unstable systems. Split off the unstable part, which is kept, or use LQG balanced truncation, which uses Riccati equations and has a bound in a gap metric (see nu-gap metric).
  • Discrete time. Replace the Lyapunov equations by Stein equations. The same bound holds for ∥G−Gr∥∞\|G - G_r\|_\infty on the unit circle.
  • Hankel-norm approximation (Glover 1984). Not a truncation, but built from the same Gramians. It reaches the best possible Hankel norm error σr+1\sigma_{r+1} (a theorem).

When to use it

Use balanced truncation when the model is linear, asymptotically stable and of moderate size, up to a few thousand states, and when a guaranteed error bound in the worst-case gain is wanted, for example to reduce a plant model before a robust control design, or to reduce a controller of high order. Look at the Hankel singular values first: a fast decay means a small accurate model exists, and the gap condition tells you where to cut. Use it with low-rank Gramians for large sparse models. Use the iterative rational Krylov algorithm instead when the model is very large and only solves with sI−AsI - A are affordable, or when the H2H_2 error matters more than the H∞H_\infty error. Use the singular perturbation variant when the gain at s=0s = 0 must be exact.

Pitfalls

  • Line L4 skipped. If σr=σr+1\sigma_r = \sigma_{r+1} and the cut splits the pair, the bound and the stability proof fail. For G=diag⁡(1/(s+1),1/(s+3),1/(s+3))G = \operatorname{diag}(1/(s+1), 1/(s+3), 1/(s+3)) the values are 1/2,1/6,1/61/2, 1/6, 1/6, and the implementation refuses r=2r = 2. Choose rr at a gap.
  • Line L1 on an unstable AA. The Lyapunov equation can still have a solution, but it is not a Gramian and need not be positive semidefinite; for 1/(s−1)1/(s - 1) it is −1/2-1/2. The implementation does not check that AA is Hurwitz; the caller must. Split off the unstable part first.
  • Line L3 on the product. Computing σi=λi(WcWo)\sigma_i = \sqrt{\lambda_i(W_c W_o)} with an eigenvalue routine works in exact arithmetic but squares the range of the values, and the small σi\sigma_i, the ones that decide the cut, lose their accuracy. Use the SVD of LoTLcL_o^T L_c.
  • Line L5 with the full inverse. Forming TT and then T−1ATT^{-1} A T requires inverting a matrix with condition number up to κ2(Lc)σ1/σn\kappa_2(L_c)\sqrt{\sigma_1/\sigma_n}. The formulas of line L5 avoid the inverse.
  • Line L6 changes the gain at s=0s = 0. Dr=DD_r = D matches GG at infinite frequency, not at zero frequency. A reduced plant used for steady-state design can have the wrong static gain, as for r=1r = 1 in the example. Use the singular perturbation variant.
  • Line L7 with a loose tolerance. Values that are close but not equal are distinct, and each must be counted. Counting a cluster as one value gives a bound that is too small. The code merges only values within 10−9σ110^{-9}\sigma_1.

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.

balanced_truncation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/balanced-truncation/. The authors are listed in prov/F4R34P.jsonl.

"""Balanced truncation of a continuous-time LTI system (square root method).

For x' = A x + B u, y = C x + D u with A Hurwitz, the gramians solve

    A W_c + W_c A^T + B B^T = 0,    A^T W_o + W_o A + C^T C = 0.

With W_c = L_c L_c^T, W_o = L_o L_o^T and the SVD L_o^T L_c = U S V^T, the
Hankel singular values are the diagonal of S. The reduced model of order r is

    T_r = L_c V_r S_r^(-1/2),   W_r = L_o U_r S_r^(-1/2),
    A_r = W_r^T A T_r,  B_r = W_r^T B,  C_r = C T_r,  D_r = D.

W_r^T T_r = I, and the reduced model is balanced with gramians S_r. If
sigma_r > sigma_(r+1), A_r is Hurwitz and the H-infinity norm of the error is
at most 2 times the sum of the distinct values among sigma_(r+1), ..., sigma_n.

Everything is in float. The gramians are found by the Kronecker method
(O(n^6) work), which is fine for the small n of the tests and the page.
"""

import math

from ctlmat import eye, kron, mul, norm2, solve, sub, transpose, unvec, vec

__all__ = [
    "lyap", "gramians", "sym_eig", "sqrt_factor", "svd", "hankel_singular_values",
    "balanced_truncation", "error_bound", "freq_response", "hinf_on_grid",
]


def lyap(a, q):
    """Return X with A X + X A^T + Q = 0 (A Hurwitz), in float."""
    n = len(a)
    af = [[float(v) for v in row] for row in a]
    big = [[x + y for x, y in zip(r1, r2)] for r1, r2 in zip(kron(eye(n), af), kron(af, eye(n)))]
    x = unvec(solve(big, [-float(v) for v in vec(q)]), n, n)
    return [[(x[i][j] + x[j][i]) / 2.0 for j in range(n)] for i in range(n)]


def gramians(a, b, c):
    """Return (W_c, W_o), the controllability and observability gramians."""
    wc = lyap(a, mul(b, transpose(b)))
    wo = lyap(transpose(a), mul(transpose(c), c))
    return wc, wo


def sym_eig(s, sweeps=100):
    """Return (values, vectors) of a real symmetric matrix by cyclic Jacobi.

    vectors is a matrix whose columns are orthonormal eigenvectors, so
    s = vectors diag(values) vectors^T up to rounding.
    """
    n = len(s)
    a = [[float(v) for v in row] for row in s]
    q = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        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 r in range(p + 1, n):
                if a[p][r] == 0.0:
                    continue
                theta = (a[r][r] - a[p][p]) / (2.0 * a[p][r])
                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, akr = a[k][p], a[k][r]
                    a[k][p] = c * akp - sn * akr
                    a[k][r] = sn * akp + c * akr
                for k in range(n):
                    apk, ark = a[p][k], a[r][k]
                    a[p][k] = c * apk - sn * ark
                    a[r][k] = sn * apk + c * ark
                for k in range(n):
                    qkp, qkr = q[k][p], q[k][r]
                    q[k][p] = c * qkp - sn * qkr
                    q[k][r] = sn * qkp + c * qkr
    return [a[i][i] for i in range(n)], q


def sqrt_factor(w):
    """Return L with W = L L^T for a symmetric positive semidefinite W.

    L = Q diag(sqrt(max(lambda, 0))) from the eigendecomposition, so a
    gramian that is singular to rounding error still gets a factor.
    """
    vals, q = sym_eig(w)
    n = len(w)
    return [[q[i][j] * math.sqrt(max(vals[j], 0.0)) for j in range(n)] for i in range(n)]


def svd(m, sweeps=100):
    """Return (U, s, V) with M = U diag(s) V^T for a square M (one-sided Jacobi).

    s is sorted in decreasing order. A column of U that belongs to a zero
    singular value is set to zero.
    """
    n = len(m)
    g = [[float(m[i][j]) for j in range(n)] for i in range(n)]
    v = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
    for _ in range(sweeps):
        rotated = False
        for p in range(n - 1):
            for r in range(p + 1, n):
                alpha = sum(g[k][p] ** 2 for k in range(n))
                beta = sum(g[k][r] ** 2 for k in range(n))
                gamma = sum(g[k][p] * g[k][r] for k in range(n))
                if abs(gamma) <= 1e-15 * math.sqrt(alpha * beta) or gamma == 0.0:
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = math.copysign(1.0, zeta) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                c = 1.0 / math.sqrt(1.0 + t * t)
                sn = c * t
                for k in range(n):
                    gp, gr = g[k][p], g[k][r]
                    g[k][p] = c * gp - sn * gr
                    g[k][r] = sn * gp + c * gr
                    vp, vr = v[k][p], v[k][r]
                    v[k][p] = c * vp - sn * vr
                    v[k][r] = sn * vp + c * vr
        if not rotated:
            break
    s = [math.sqrt(sum(g[k][j] ** 2 for k in range(n))) for j in range(n)]
    order = sorted(range(n), key=lambda j: -s[j])
    s = [s[j] for j in order]
    vv = [[v[i][j] for j in order] for i in range(n)]
    u = [[(g[i][j] / s[jj]) if s[jj] > 0.0 else 0.0 for jj, j in enumerate(order)] for i in range(n)]
    return u, s, vv


def hankel_singular_values(a, b, c):
    """Return the Hankel singular values sigma_1 >= ... >= sigma_n."""
    wc, wo = gramians(a, b, c)
    _, s, _ = svd(mul(transpose(sqrt_factor(wo)), sqrt_factor(wc)))
    return s


def error_bound(sigma, r, rtol=1e-9):
    """Return 2 times the sum of the distinct values among sigma[r:].

    Two values count as equal when they differ by at most rtol * sigma[0].
    """
    tail = sigma[r:]
    tol = rtol * (sigma[0] if sigma else 0.0)
    distinct = []
    for x in tail:
        if not any(abs(x - y) <= tol for y in distinct):
            distinct.append(x)
    return 2.0 * sum(distinct)


def balanced_truncation(a, b, c, d, r, rtol=1e-9):
    """Return (A_r, B_r, C_r, D_r, sigma, bound) for the reduced order r.

    sigma is the list of all Hankel singular values and bound is the
    H-infinity error bound. Raises ValueError if 0 < r < n and
    sigma_r - sigma_(r+1) <= rtol * sigma_1, because the cut then splits a
    repeated value and the theorem gives no guarantee.
    """
    n = len(a)
    wc, wo = gramians(a, b, c)  # @line L1
    lc, lo = sqrt_factor(wc), sqrt_factor(wo)  # @line L2
    u, sigma, v = svd(mul(transpose(lo), lc))  # @line L3
    if not 0 <= r <= n:
        raise ValueError("r must be between 0 and n")
    if 0 < r < n and sigma[r - 1] - sigma[r] <= rtol * sigma[0]:  # @line L4
        raise ValueError("sigma_r equals sigma_(r+1): choose another r")
    if r > 0 and sigma[r - 1] <= 0.0:
        raise ValueError("the system has fewer than r controllable and observable modes")
    isq = [1.0 / math.sqrt(sigma[j]) for j in range(r)]
    tr = [[sum(lc[i][k] * v[k][j] for k in range(n)) * isq[j] for j in range(r)] for i in range(n)]  # @line L5
    wr = [[sum(lo[i][k] * u[k][j] for k in range(n)) * isq[j] for j in range(r)] for i in range(n)]
    wrt = transpose(wr) if r > 0 else []
    ar = mul(mul(wrt, a), tr) if r > 0 else []  # @line L6
    br = mul(wrt, b) if r > 0 else []
    cr = mul(c, tr) if r > 0 else [[] for _ in c]
    dr = [list(row) for row in d]
    bound = error_bound(sigma, r, rtol)  # @line L7
    return ar, br, cr, dr, sigma, bound  # @line L8


def freq_response(a, b, c, d, s):
    """Return G(s) = C (s I - A)^(-1) B + D as a complex matrix."""
    n = len(a)
    p = len(d)
    m = len(d[0])
    if n == 0:
        return [[complex(d[i][j]) for j in range(m)] for i in range(p)]
    si_a = sub([[complex(s) if i == j else 0j for j in range(n)] for i in range(n)], [[complex(v) for v in row] for row in a])
    x = solve(si_a, [[complex(v) for v in row] for row in b])
    g = mul([[complex(v) for v in row] for row in c], x)
    return [[g[i][j] + d[i][j] for j in range(m)] for i in range(p)]


def hinf_on_grid(sys1, sys2, omegas):
    """Return the largest 2-norm of G1(j w) - G2(j w) over the grid (a lower estimate)."""
    best = 0.0
    for w in omegas:
        g1 = freq_response(*sys1, 1j * w)
        g2 = freq_response(*sys2, 1j * w)
        e = [[x - y for x, y in zip(r1, r2)] for r1, r2 in zip(g1, g2)]
        best = max(best, norm2(e))
    return best
ctlmat.py 630 lines
# 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()
test_balanced_truncation.py 186 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/balanced-truncation/. The authors are listed in prov/F4R34P.jsonl.

import math
import random

import pytest

from balanced_truncation import (
    balanced_truncation, error_bound, freq_response, gramians,
    hankel_singular_values, hinf_on_grid, lyap, svd, sym_eig,
)
from ctlmat import charpoly, inv, mul, polyroots, transpose

GRID = [0.0] + [10 ** (k / 60.0) for k in range(-180, 181)]


def random_stable(rng, n, m, p):
    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(m)] for _ in range(n)]
    c = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
    d = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(p)]
    return a, b, c, d


def poles(a):
    return polyroots(charpoly(a))


def maxdiff(x, y):
    return max(abs(u - v) for r1, r2 in zip(x, y) for u, v in zip(r1, r2))


CHAIN = (
    [[-1, 1, 0, 0], [0, -2, 1, 0], [0, 0, -3, 1], [0, 0, 0, -4]],
    [[0], [0], [0], [1]],
    [[1, 0, 0, 0]],
    [[0]],
)


def test_first_order_system():
    assert abs(hankel_singular_values([[-1]], [[1]], [[1]])[0] - 0.5) < 1e-14
    # 1/(s + a) with b = c = 1 has sigma = 1/(2a)
    assert abs(hankel_singular_values([[-4.0]], [[1.0]], [[1.0]])[0] - 0.125) < 1e-14


def test_lyap_residual_and_jacobi():
    rng = random.Random(10)
    a, b, c, _ = random_stable(rng, 5, 2, 2)
    wc, wo = gramians(a, b, c)
    bb = mul(b, transpose(b))
    res = [[sum(a[i][k] * wc[k][j] + wc[i][k] * a[j][k] for k in range(5)) + bb[i][j] for j in range(5)] for i in range(5)]
    assert maxdiff(res, [[0.0] * 5 for _ in range(5)]) < 1e-12
    vals, q = sym_eig(wc)
    rebuilt = [[sum(q[i][k] * vals[k] * q[j][k] for k in range(5)) for j in range(5)] for i in range(5)]
    assert maxdiff(rebuilt, wc) < 1e-13
    m = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(4)]
    u, s, v = svd(m)
    rebuilt = [[sum(u[i][k] * s[k] * v[j][k] for k in range(4)) for j in range(4)] for i in range(4)]
    assert maxdiff(rebuilt, m) < 1e-13
    assert all(x >= y for x, y in zip(s, s[1:]))


def test_hsv_against_eigenvalues_of_gramian_product():
    a, b, c, _ = CHAIN
    wc, wo = gramians(a, b, c)
    lam = sorted((z.real for z in poles(mul(wc, wo))), reverse=True)
    sig = hankel_singular_values(a, b, c)
    for s, l in zip(sig, lam):
        assert abs(s - math.sqrt(l)) < 1e-9 * sig[0]


def test_hsv_against_eigenvalues_on_500_random_systems():
    # oracle: sqrt of the roots of det(s I - W_c W_o), with the gramians
    # from the Kronecker solve and the roots from ctlmat.polyroots
    rng = random.Random(15)
    for _ in range(500):
        n = rng.randint(1, 3)
        a, b, c, _ = random_stable(rng, n, rng.randint(1, 2), rng.randint(1, 2))
        wc, wo = gramians(a, b, c)
        lam = sorted((max(z.real, 0.0) for z in poles(mul(wc, wo))), reverse=True)
        sig = hankel_singular_values(a, b, c)
        for s, l in zip(sig, lam):
            assert abs(s - math.sqrt(l)) < 1e-6 * sig[0]


def test_hsv_invariant_under_similarity():
    rng = random.Random(11)
    for _ in range(5):
        a, b, c, _ = random_stable(rng, 4, 1, 2)
        t = [[rng.uniform(-1, 1) + (2.0 if i == j else 0.0) for j in range(4)] for i in range(4)]
        ti = inv(t)
        s1 = hankel_singular_values(a, b, c)
        s2 = hankel_singular_values(mul(mul(ti, a), t), mul(ti, b), mul(c, t))
        for x, y in zip(s1, s2):
            assert abs(x - y) < 1e-9 * s1[0]


def test_reduced_model_is_balanced_and_stable():
    rng = random.Random(12)
    for trial in range(6):
        a, b, c, d = random_stable(rng, 5, 2, 2)
        for r in range(1, 5):
            ar, br, cr, dr, sig, bound = balanced_truncation(a, b, c, d, r)
            wc, wo = gramians(ar, br, cr)
            want = [[sig[i] if i == j else 0.0 for j in range(r)] for i in range(r)]
            assert maxdiff(wc, want) < 1e-9 * sig[0]
            assert maxdiff(wo, want) < 1e-9 * sig[0]
            assert all(z.real < 0 for z in poles(ar))


def test_error_between_lower_and_upper_bound():
    rng = random.Random(13)
    systems = [CHAIN] + [random_stable(rng, 4, 1, 1) for _ in range(3)] + [random_stable(rng, 4, 2, 2)]
    for sys in systems:
        n = len(sys[0])
        for r in range(0, n):
            red = balanced_truncation(*sys, r)
            sig, bound = red[4], red[5]
            err = hinf_on_grid(sys, red[:4], GRID)
            assert err <= bound * (1 + 1e-9)
            # sigma_(r+1) is a lower bound for every model of order r; the grid
            # gives a lower estimate of the norm, so allow a small margin.
            assert err >= 0.98 * sig[r]


def test_chain_example_of_the_page():
    sig = hankel_singular_values(*CHAIN[:3])
    want = [0.0279876, 0.00821788, 0.00112693, 0.0000632855]
    for s, w in zip(sig, want):
        assert abs(s - w) < 5e-6 * w
    ar, br, cr, dr, _, bound = balanced_truncation(*CHAIN, 2)
    assert abs(bound - 0.00238044) < 1e-8
    err = hinf_on_grid(CHAIN, (ar, br, cr, dr), GRID)
    assert abs(err - 0.00214790) < 1e-7
    # dropping only the last state: the error equals 2 sigma_4 on this system
    red3 = balanced_truncation(*CHAIN, 3)
    assert abs(hinf_on_grid(CHAIN, red3[:4], GRID) - 2 * sig[3]) < 1e-12


def test_full_order_reproduces_g():
    rng = random.Random(14)
    a, b, c, d = random_stable(rng, 4, 2, 3)
    ar, br, cr, dr, _, bound = balanced_truncation(a, b, c, d, 4)
    assert bound == 0.0
    for s in [0.3j, 1.0 + 2.0j, -0.2 + 5j, 10.0]:
        assert maxdiff(freq_response(a, b, c, d, s), freq_response(ar, br, cr, dr, s)) < 1e-10


def test_repeated_values_counted_once_and_tight():
    # diag(1/(s+1), 1/(s+3), 1/(s+3)) has sigma = 1/2, 1/6, 1/6
    a = [[-1, 0, 0], [0, -3, 0], [0, 0, -3]]
    b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]]
    c = b
    d = [[0] * 3 for _ in range(3)]
    ar, br, cr, dr, sig, bound = balanced_truncation(a, b, c, d, 1)
    assert abs(sig[0] - 0.5) < 1e-14 and abs(sig[1] - 1 / 6) < 1e-14 and abs(sig[2] - 1 / 6) < 1e-14
    assert abs(bound - 1 / 3) < 1e-12
    assert abs(hinf_on_grid((a, b, c, d), (ar, br, cr, dr), GRID) - 1 / 3) < 1e-12
    assert abs(error_bound(sig, 1, rtol=0.0) - 1 / 3) < 1e-12
    with pytest.raises(ValueError):
        balanced_truncation(a, b, c, d, 2)


def test_bound_is_attained_for_first_order():
    # G = 1/(s+1), r = 0: G_r = 0 and the error is 1 = 2 sigma_1
    ar, br, cr, dr, sig, bound = balanced_truncation([[-1]], [[1]], [[1]], [[0]], 0)
    assert abs(bound - 1.0) < 1e-14
    assert abs(hinf_on_grid(([[-1]], [[1]], [[1]], [[0]]), (ar, br, cr, dr), [0.0]) - 1.0) < 1e-14


def test_non_minimal_system():
    # the second state is not controllable: sigma_2 = 0, order 1 is exact
    a = [[-1.0, 0.0], [0.0, -2.0]]
    b = [[1.0], [0.0]]
    c = [[1.0, 1.0]]
    d = [[0.0]]
    sig = hankel_singular_values(a, b, c)
    assert abs(sig[0] - 0.5) < 1e-12 and abs(sig[1]) < 1e-7
    ar, br, cr, dr, _, bound = balanced_truncation(a, b, c, d, 1)
    assert hinf_on_grid((a, b, c, d), (ar, br, cr, dr), GRID) < 1e-9
    with pytest.raises(ValueError):
        balanced_truncation(a, b, c, d, 2)

History

Moore (1981) introduced internally balanced realizations, by analogy with principal component analysis, and proposed to delete the weakly controllable and weakly observable states. Pernebo and Silverman (1982) proved that the truncated model is asymptotically stable and minimal. Enns (1984) proved the bound of twice the sum of the deleted values and proposed the frequency-weighted version, and Glover (1984), in his paper on optimal Hankel-norm approximation, proved the bound with each distinct value counted once. Laub, Heath, Paige and Ward (1987) gave the square-root computation from Cholesky factors and an SVD, which is the form used in numerical libraries.

References

  1. B. C. Moore, Principal component analysis in linear systems, controllability, observability, and model reduction, IEEE Transactions on Automatic Control 26(1), 17-32, 1981, the internally balanced realization and the reduced model obtained by deleting the weak states
  2. L. Pernebo and L. M. Silverman, Model reduction via balanced state space representations, IEEE Transactions on Automatic Control 27(2), 382-387, 1982, the stability and minimality of the truncated balanced model
  3. Dale F. Enns, Model reduction with balanced realizations, an error bound and a frequency weighted generalization, 23rd IEEE Conference on Decision and Control, 127-132, 1984, the bound of twice the sum of the deleted Hankel singular values and the frequency-weighted version
  4. Keith Glover, All optimal Hankel-norm approximations of linear multivariable systems and their L-infinity error bounds, International Journal of Control 39(6), 1115-1193, 1984, the L-infinity error bound for balanced truncation, with each distinct Hankel singular value counted once
  5. A. J. Laub, M. T. Heath, C. C. Paige and R. C. Ward, Computation of system balancing transformations and other applications of simultaneous diagonalization algorithms, IEEE Transactions on Automatic Control 32(2), 115-122, 1987, the balancing transformation from Cholesky factors of the Gramians and an SVD of their product
  6. Athanasios C. Antoulas, Approximation of Large-Scale Dynamical Systems, SIAM, 2005, Chapter 7, Balancing and balanced approximations
  7. Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, Chapter 7, Model Reduction by Balanced Truncation

Where this leads

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