Algorithm Search⌘K

Algorithmadvanced

H-infinity norm computation by bisection

Also called Boyd-Balakrishnan-Bruinsma-Steinbuch algorithm, Hamiltonian bisection for the H-infinity norm.

Decides whether the H-infinity norm of a system with A Hurwitz is at least gamma from the imaginary eigenvalues of a Hamiltonian matrix, then bisects on gamma or raises gamma by the level set method.

Time
O((n + m + p)^3 log(n / e)) worst
Space
O((n + m + p)^2) extra
Where
e = the relative accuracy (epsilon on the page); m = the number of inputs; n = the state dimension; p = the number of outputs
Properties
deterministicnot exactofflineiterative
Origin
Stephen Boyd, Venkataramanan Balakrishnan, Pierre Kabamba, N. A. Bruinsma, Maarten Steinbuch, 1989

H-infinity norm computation finds the H-infinity norm of a linear system with a Hurwitz state matrix, the peak over all frequencies of the largest singular value of its transfer matrix, to a chosen relative accuracy. It does not search over frequency. Instead it answers the question "is the norm at least gamma?" exactly, by checking whether a 2n×2n2n \times 2n Hamiltonian matrix built from the state-space data has an eigenvalue on the imaginary axis. Boyd, Balakrishnan and Kabamba (1989) used this test inside a bisection on gamma, and Bruinsma and Steinbuch (1990) used the frequencies of the imaginary eigenvalues to raise gamma at each step, which converges quadratically.

In plain words

A system whose free motion dies out amplifies some input signals more than others, and the amount depends on how fast the input oscillates. The H-infinity norm is the largest amplification over all inputs and all speeds. You could test many speeds one by one, but you can miss a narrow peak between two test points. This method asks a different question: is there any speed at which the amplification reaches a given level? A small matrix built from the system answers this question with certainty, and it also tells you at which speeds the amplification crosses that level. Bisection then halves the range of possible levels until it is small enough. The faster variant uses the crossing speeds: the peak lies between two crossings, so it tests the middle of each such gap and moves the level up to the best value found.

The problem

Input. Real matrices A∈Rn×nA \in \mathbb{R}^{n \times n}, 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} of the system x′=Ax+Bux' = A x + B u, y=Cx+Duy = C x + D u, with AA Hurwitz, and a relative accuracy ε>0\varepsilon > 0. The realization need not be minimal.

Output. Numbers lo≤hilo \le hi with

lo≤∥G∥∞≤hi,hi−lo≤2ε lo,lo \le \|G\|_\infty \le hi, \qquad hi - lo \le 2\varepsilon\, lo,

where G(s)=C(sI−A)−1B+DG(s) = C(sI - A)^{-1}B + D is the transfer function and ∥G∥∞=sup⁡ω∈Rσmax⁡(G(jω))\|G\|_\infty = \sup_{\omega \in \mathbb{R}} \sigma_{\max}(G(j\omega)), with σmax⁡\sigma_{\max} the largest singular value. The level set method also returns a frequency ω\omega (possibly ∞\infty) with σmax⁡(G(jω))=lo\sigma_{\max}(G(j\omega)) = lo.

The test. For γ>0\gamma > 0 that is not a singular value of DD, let Mγ=[D−γIp−γImDT]M_\gamma = \begin{bmatrix} D & -\gamma I_p \\ -\gamma I_m & D^T \end{bmatrix} and

Hγ=[A00−AT]+[B00−CT]Mγ−1[−C00−BT],Hγ=[Aγ−1BBT−γ−1CTC−AT] if D=0.H_\gamma = \begin{bmatrix} A & 0 \\ 0 & -A^T \end{bmatrix} + \begin{bmatrix} B & 0 \\ 0 & -C^T \end{bmatrix} M_\gamma^{-1} \begin{bmatrix} -C & 0 \\ 0 & -B^T \end{bmatrix}, \qquad H_\gamma = \begin{bmatrix} A & \gamma^{-1} B B^T \\ -\gamma^{-1} C^T C & -A^T \end{bmatrix} \text{ if } D = 0.

If AA has no imaginary eigenvalue, then γ\gamma is a singular value of G(jω0)G(j\omega_0) exactly when jω0j\omega_0 is an eigenvalue of HγH_\gamma. With AA Hurwitz and γ>σmax⁡(D)\gamma > \sigma_{\max}(D) it follows that ∥G∥∞≥γ\|G\|_\infty \ge \gamma if and only if HγH_\gamma has an imaginary eigenvalue. The characteristic polynomial of HγH_\gamma is even, det⁡(sI−Hγ)=r(s2)\det(sI - H_\gamma) = r(s^2) with deg⁡r=n\deg r = n, so the imaginary eigenvalues ±jω\pm j\omega are the real roots t=−ω2≤0t = -\omega^2 \le 0 of rr.

The algorithm

  1. IMAGINARY-FREQUENCIES(A, B, C, D, γ)
  2. 1M ← [[D, -γ I_p], [-γ I_m, D^T]]; H ← [[A, 0], [0, -A^T]] + [[B, 0], [0, -C^T]] M^(-1) [[-C, 0], [0, -B^T]]
  3. 2r ← the polynomial of degree n with det(sI - H) = r(s²)
  4. 3return the sorted list of ω = √(-t) for the real roots t ≤ 0 of r
  5. HINF-BISECTION(A, B, C, D, ε)
  6. 4check that A is Hurwitz; d ← σ_max(D)
  7. 5σ_1 ≥ ... ≥ σ_n ← the Hankel singular values, the square roots of the eigenvalues of W_c W_o
  8. 6lo ← max(d, σ_1); hi ← d + 2 (σ_1 + ... + σ_n)
  9. 7while hi - lo > 2ε lo
  10. 8γ ← (lo + hi) / 2
  11. 9if IMAGINARY-FREQUENCIES(A, B, C, D, γ) is not empty then lo ← γ else hi ← γ
  12. 10return (lo, hi)
  13. HINF-LEVEL-SET(A, B, C, D, ε)
  14. 11check that A is Hurwitz; lb ← the largest of σ_max(D), σ_max(G(0)) and σ_max(G(j|λ|)) for the eigenvalues λ of A
  15. 12loop
  16. 13γ ← (1 + 2ε) lb; F ← IMAGINARY-FREQUENCIES(A, B, C, D, γ)
  17. 14if F is empty then return (lb, γ)
  18. 15ω_1 < ... < ω_k ← F together with -F; best ← max(lb, max over i < k of σ_max(G(j (ω_i + ω_(i+1)) / 2)))
  19. 16if best ≤ γ then return (best, γ) else lb ← best

Lines L1 to L3 are the test. Line L1 needs MγM_\gamma invertible, which holds for every γ>σmax⁡(D)\gamma > \sigma_{\max}(D); both callers only use such levels. Line L2 drops the odd coefficients of the characteristic polynomial, which are zero in exact arithmetic. Line L3 turns each real root t≤0t \le 0 of rr into a frequency ω≥0\omega \ge 0 at which some singular value of G(jω)G(j\omega) equals γ\gamma. These crossings belong to any singular value, not only the largest one.

Lines L5 and L6 give the start interval. Here WcW_c and WoW_o are the controllability gramian and the observability gramian, from AWc+WcAT+BBT=0A W_c + W_c A^T + B B^T = 0 and ATWo+WoA+CTC=0A^T W_o + W_o A + C^T C = 0. The norm is at least σmax⁡(D)\sigma_{\max}(D) (its limit at infinity) and at least the largest Hankel singular value, and at most σmax⁡(D)+2∑σi\sigma_{\max}(D) + 2 \sum \sigma_i by the balanced truncation error bound with nothing kept. Lines L7 to L9 keep the norm in [lo,hi][lo, hi] and halve the interval at each pass.

Line L11 starts the level set method from values of σmax⁡\sigma_{\max} at three kinds of points: infinity, zero, and the moduli of the poles, where lightly damped peaks sit. Bruinsma and Steinbuch use a similar rule with one pole frequency. Each pass of lines L12 to L16 tests the level just above the current lower bound. If the test fails, the norm is below γ\gamma and the interval [lb,γ][lb, \gamma] is the answer. If it passes, the frequencies where some singular value equals γ\gamma cut the axis into pieces. On every piece where σmax⁡>γ\sigma_{\max} > \gamma both ends are crossings, so the midpoint of two consecutive crossings falls inside, and line L15 finds a value above γ\gamma. Line L15 uses negative frequencies too, so that a peak at ω=0\omega = 0, between −ω1-\omega_1 and ω1\omega_1, is found.

The implementation forms HγH_\gamma, computes its characteristic polynomial with the Faddeev-LeVerrier algorithm, and finds the roots of rr with the Durand-Kerner method of the shared helper module. A root tt counts as real when ∣Im⁡t∣≤10−6(1+∣t∣)|\operatorname{Im} t| \le 10^{-6}(1 + |t|) and as nonpositive when Re⁡t≤10−10(1+∣t∣)\operatorname{Re} t \le 10^{-10}(1 + |t|). This is fine for the small nn of the tests (2n≤62n \le 6); a production code computes the eigenvalues of HγH_\gamma with a structure preserving variant of the QR algorithm.

Example

A lightly damped mode. Take G(s)=1/(s2+0.2s+1)G(s) = 1/(s^2 + 0.2 s + 1), with damping ratio ζ=0.1\zeta = 0.1 and natural frequency 1 rad/s, as A=[01−1−0.2]A = \begin{bmatrix} 0 & 1 \\ -1 & -0.2 \end{bmatrix}, B=[01]B = \begin{bmatrix} 0 \\ 1 \end{bmatrix}, C=[10]C = \begin{bmatrix} 1 & 0 \end{bmatrix} and D=0D = 0. The exact norm is 1/(2ζ1−ζ2)=5.0251891/(2\zeta\sqrt{1 - \zeta^2}) = 5.025189, reached at ω=1−2ζ2=0.98995\omega = \sqrt{1 - 2\zeta^2} = 0.98995 rad/s. Here

Hγ=[0100−1−0.201/γ−1/γ00100−10.2],r(t)=t2+1.96 t+1−1γ2.H_\gamma = \begin{bmatrix} 0 & 1 & 0 & 0 \\ -1 & -0.2 & 0 & 1/\gamma \\ -1/\gamma & 0 & 0 & 1 \\ 0 & 0 & -1 & 0.2 \end{bmatrix}, \qquad r(t) = t^2 + 1.96\, t + 1 - \frac{1}{\gamma^2}.

The sum of the roots of rr is −1.96-1.96, so its real roots are negative whenever they exist, and they exist exactly when 1.962≥4(1−1/γ2)1.96^2 \ge 4(1 - 1/\gamma^2), that is γ≤1/0.0396=5.025189\gamma \le 1/\sqrt{0.0396} = 5.025189. This matches the exact norm, as the test promises. The same follows from ∣G(jω)∣2=1/((1−ω2)2+0.04 ω2)|G(j\omega)|^2 = 1/((1 - \omega^2)^2 + 0.04\,\omega^2) with t=−ω2t = -\omega^2.

The gramians are Wc=2.5 IW_c = 2.5\, I and Wo=[2.60.50.52.5]W_o = \begin{bmatrix} 2.6 & 0.5 \\ 0.5 & 2.5 \end{bmatrix}, and the Hankel singular values are 2.762472.76247 and 2.262472.26247. Line L6 gives lo=2.76247lo = 2.76247 and hi=2(2.76247+2.26247)=10.04988hi = 2(2.76247 + 2.26247) = 10.04988. The first passes of the bisection are:

pass γ frequencies of line L3 (rad/s) update
1 6.40617 none hi ← 6.40617
2 4.58432 0.94374, 1.03409 lo ← 4.58432
3 5.49525 none hi ← 5.49525
4 5.03978 none hi ← 5.03978
5 4.81205 0.95923, 1.01975 lo ← 4.81205
6 4.92592 0.96946, 1.01003 lo ← 4.92592
7 4.98285 0.97673, 1.00299 lo ← 4.98285
8 5.01132 0.98244, 0.99741 lo ← 5.01132

With ε=10−8\varepsilon = 10^{-8} the bisection stops after 27 passes with [5.0251890604,5.0251891147][5.0251890604, 5.0251891147]. The two crossing frequencies close in on the peak frequency from both sides as γ\gamma rises.

The level set method starts from lb=∣G(j⋅1)∣=5lb = |G(j \cdot 1)| = 5, because both poles have modulus 1, against ∣G(0)∣=1|G(0)| = 1 and σmax⁡(D)=0\sigma_{\max}(D) = 0.

pass γ frequencies midpoints new lower bound
1 5.0000001 0.979796, 1.000000 0, ±0.989898 5.02518842 at 0.989898
2 5.0251885 0.989902, 0.989997 0, ±0.989949 5.0251890763 at 0.989949
3 5.0251892 none stop

It returns [5.0251890763,5.0251891768][5.0251890763, 5.0251891768], and the lower end equals the exact norm to all printed digits. The error of the lower bound drops from 1.3×10−71.3 \times 10^{-7} (relative) after pass 1 to below 10−1510^{-15} after pass 2: the quadratic convergence of Boyd and Balakrishnan.

A realization that is not minimal. With A=[−4−8120−8000−16]A = \begin{bmatrix} -4 & -8 & 12 \\ 0 & -8 & 0 \\ 0 & 0 & -16 \end{bmatrix}, B=(1,0,0)TB = (1, 0, 0)^T, C=(1,1,1)C = (1, 1, 1) and D=0D = 0, the modes at −8-8 and −16-16 are not controllable, and G(s)=1/(s+4)G(s) = 1/(s + 4). The Hankel singular values are 0.1250.125, 00 and 00, and both methods return the norm 0.250.25, reached at ω=0\omega = 0.

A peak at infinity. For G(s)=(s+1)/(s+2)G(s) = (s + 1)/(s + 2), written as A=−2A = -2, B=1B = 1, C=−1C = -1, D=1D = 1, the gain ∣G(jω)∣|G(j\omega)| rises from 0.50.5 at ω=0\omega = 0 toward 1 and never reaches it. The norm is σmax⁡(D)=1\sigma_{\max}(D) = 1. No level above 1 gives an imaginary eigenvalue, so the bisection shrinks hihi to lo=1lo = 1, and the level set method stops at once with ω=∞\omega = \infty.

Correctness

The proofs are in the correctness proof. They hold in exact arithmetic.

  • Hamiltonian test (proved). If AA has no imaginary eigenvalue and γ\gamma is not a singular value of DD, then γ\gamma is a singular value of G(jω0)G(j\omega_0) if and only if jω0j\omega_0 is an eigenvalue of HγH_\gamma. The proof turns a pair of singular vectors (u,v)(u, v) into an eigenvector (x,q)(x, q) with x=(jω0I−A)−1Bux = (j\omega_0 I - A)^{-1} B u, and back.
  • Even polynomial (proved). JHγJ H_\gamma is symmetric for J=[0I−I0]J = \begin{bmatrix} 0 & I \\ -I & 0 \end{bmatrix}, so HγH_\gamma is similar to −HγT-H_\gamma^T and det⁡(sI−Hγ)\det(sI - H_\gamma) is a polynomial in s2s^2.
  • Level test (proved). For AA Hurwitz and γ>σmax⁡(D)\gamma > \sigma_{\max}(D): ∥G∥∞≥γ\|G\|_\infty \ge \gamma if and only if HγH_\gamma has an imaginary eigenvalue. The proof uses the continuity of σmax⁡(G(jω))\sigma_{\max}(G(j\omega)), its limit σmax⁡(D)\sigma_{\max}(D) at infinity, and the intermediate value theorem.
  • Bisection (proved). The interval [lo,hi][lo, hi] always holds the norm, and the loop runs at most ⌈log⁡2(n/ε)⌉\lceil \log_2(n/\varepsilon) \rceil times, because the start interval has width at most 2n lo2n\, lo.
  • Level set (proved). The lower bound is always a value of σmax⁡\sigma_{\max}, so it never exceeds the norm. A pass that does not stop raises it by a factor larger than 1+2ε1 + 2\varepsilon, so the method stops. At a stop the norm is at most γ\gamma.
Proof: The Hamiltonian bisection and the level set iteration return an interval that holds the H-infinity normfull

Let G(s)=C(sI−A)−1B+DG(s) = C(sI - A)^{-1}B + D with A∈Rn×nA \in \mathbb{R}^{n \times n}, 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}, and let ∥G∥∞=sup⁡ω∈Rσmax⁡(G(jω))\|G\|_\infty = \sup_{\omega \in \mathbb{R}} \sigma_{\max}(G(j\omega)). The two procedures on the page assume that AA is Hurwitz, so GG has no pole in the closed right half plane and the norm is finite. All statements below hold in exact arithmetic. The last section says what changes in floating point.

For γ>0\gamma > 0 that is not a singular value of DD, the matrix

Mγ=[D−γIp−γImDT]M_\gamma = \begin{bmatrix} D & -\gamma I_p \\ -\gamma I_m & D^T \end{bmatrix}

is invertible (a vector (u,v)(u, v) in its kernel has Du=γvD u = \gamma v and DTv=γuD^T v = \gamma u, so it is zero unless γ\gamma is a singular value of DD). Define

Hγ=[A00−AT]+[B00−CT]Mγ−1[−C00−BT].H_\gamma = \begin{bmatrix} A & 0 \\ 0 & -A^T \end{bmatrix} + \begin{bmatrix} B & 0 \\ 0 & -C^T \end{bmatrix} M_\gamma^{-1} \begin{bmatrix} -C & 0 \\ 0 & -B^T \end{bmatrix}.

For D=0D = 0 this is Hγ=[Aγ−1BBT−γ−1CTC−AT]H_\gamma = \begin{bmatrix} A & \gamma^{-1} B B^T \\ -\gamma^{-1} C^T C & -A^T \end{bmatrix}.

Lemma 1 (singular values and imaginary eigenvalues)

Assume that AA has no eigenvalue on the imaginary axis and that γ>0\gamma > 0 is not a singular value of DD. Then for every real ω0\omega_0, γ\gamma is a singular value of G(jω0)G(j\omega_0) if and only if jω0j\omega_0 is an eigenvalue of HγH_\gamma.

Proof. Write G∗G^* for the conjugate transpose. Since AA is real, G(jω0)∗=BT(−jω0I−AT)−1CT+DTG(j\omega_0)^* = B^T(-j\omega_0 I - A^T)^{-1} C^T + D^T.

(⇒\Rightarrow) Let γ\gamma be a singular value of G(jω0)G(j\omega_0). Then there are vectors u∈Cmu \in \mathbb{C}^m and v∈Cpv \in \mathbb{C}^p, not both zero, with G(jω0)u=γvG(j\omega_0) u = \gamma v and G(jω0)∗v=γuG(j\omega_0)^* v = \gamma u. Put x=(jω0I−A)−1Bux = (j\omega_0 I - A)^{-1} B u and q=(−jω0I−AT)−1CTvq = (-j\omega_0 I - A^T)^{-1} C^T v. Both inverses exist because AA has no imaginary eigenvalue. Then

jω0x=Ax+Bu,jω0q=−ATq−CTv,j\omega_0 x = A x + B u, \qquad j\omega_0 q = -A^T q - C^T v,

and the two singular value equations read Cx+Du−γv=0C x + D u - \gamma v = 0 and BTq+DTv−γu=0B^T q + D^T v - \gamma u = 0, that is

Mγ[uv]=[−Cx−BTq].M_\gamma \begin{bmatrix} u \\ v \end{bmatrix} = \begin{bmatrix} -C x \\ -B^T q \end{bmatrix}.

Solve this for (u,v)(u, v) and put it into the two differential equations. The result is Hγ(x,q)=jω0(x,q)H_\gamma (x, q) = j\omega_0 (x, q). The vector (x,q)(x, q) is not zero: if x=0x = 0 and q=0q = 0, the last display gives Mγ(u,v)=0M_\gamma (u, v) = 0, so (u,v)=0(u, v) = 0, which is false. So jω0j\omega_0 is an eigenvalue of HγH_\gamma.

(⇐\Leftarrow) Let Hγ(x,q)=jω0(x,q)H_\gamma (x, q) = j\omega_0 (x, q) with (x,q)≠0(x, q) \neq 0. Define (u,v)=Mγ−1(−Cx,−BTq)(u, v) = M_\gamma^{-1}(-C x, -B^T q). The two block rows of the eigenvalue equation say (jω0I−A)x=Bu(j\omega_0 I - A) x = B u and (−jω0I−AT)q=CTv(-j\omega_0 I - A^T) q = C^T v, so x=(jω0I−A)−1Bux = (j\omega_0 I - A)^{-1} B u and q=(−jω0I−AT)−1CTvq = (-j\omega_0 I - A^T)^{-1} C^T v. If (u,v)=0(u, v) = 0 then (x,q)=0(x, q) = 0, which is false. The definition of (u,v)(u, v) gives Cx+Du=γvC x + D u = \gamma v and BTq+DTv=γuB^T q + D^T v = \gamma u, that is G(jω0)u=γvG(j\omega_0) u = \gamma v and G(jω0)∗v=γuG(j\omega_0)^* v = \gamma u. If u=0u = 0, the first equation gives v=0v = 0; so u≠0u \neq 0, and G(jω0)∗G(jω0)u=γ2uG(j\omega_0)^* G(j\omega_0) u = \gamma^2 u. So γ\gamma is a singular value of G(jω0)G(j\omega_0). □\square

Lemma 2 (the characteristic polynomial is even)

Under the hypotheses of Lemma 1, det⁡(sI−Hγ)=r(s2)\det(sI - H_\gamma) = r(s^2) for a real polynomial rr of degree nn. Hence jω0j\omega_0 is an eigenvalue of HγH_\gamma if and only if t=−ω02t = -\omega_0^2 is a root of rr, and the imaginary eigenvalues of HγH_\gamma are exactly the numbers ±j−t\pm j\sqrt{-t} for the real roots t≤0t \le 0 of rr.

Proof. Let J=[0In−In0]J = \begin{bmatrix} 0 & I_n \\ -I_n & 0 \end{bmatrix}. We show that JHγJ H_\gamma is symmetric. First, J[A00−AT]=[0−AT−A0]J \begin{bmatrix} A & 0 \\ 0 & -A^T \end{bmatrix} = \begin{bmatrix} 0 & -A^T \\ -A & 0 \end{bmatrix} is symmetric. Next, write L=[B00−CT]L = \begin{bmatrix} B & 0 \\ 0 & -C^T \end{bmatrix} and R=[−C00−BT]R = \begin{bmatrix} -C & 0 \\ 0 & -B^T \end{bmatrix}. A direct product gives JL=RTPJ L = R^T P with the permutation P=[0IpIm0]P = \begin{bmatrix} 0 & I_p \\ I_m & 0 \end{bmatrix}, so JLMγ−1R=RT(PMγ−1)RJ L M_\gamma^{-1} R = R^T (P M_\gamma^{-1}) R. Now PMγ−1=(MγPT)−1P M_\gamma^{-1} = (M_\gamma P^T)^{-1} and

MγPT=[D−γIp−γImDT][0ImIp0]=[−γIpDDT−γIm],M_\gamma P^T = \begin{bmatrix} D & -\gamma I_p \\ -\gamma I_m & D^T \end{bmatrix} \begin{bmatrix} 0 & I_m \\ I_p & 0 \end{bmatrix} = \begin{bmatrix} -\gamma I_p & D \\ D^T & -\gamma I_m \end{bmatrix},

which is symmetric. The inverse of a symmetric matrix is symmetric, so JLMγ−1RJ L M_\gamma^{-1} R is symmetric, and so is JHγJ H_\gamma. Then (JHγ)T=JHγ(J H_\gamma)^T = J H_\gamma gives −HγTJ=JHγ-H_\gamma^T J = J H_\gamma, so JHγJ−1=−HγTJ H_\gamma J^{-1} = -H_\gamma^T. Thus HγH_\gamma is similar to −HγT-H_\gamma^T, and with p(s)=det⁡(sI−Hγ)p(s) = \det(sI - H_\gamma),

p(s)=det⁡(sI+HγT)=det⁡(sI+Hγ)=(−1)2ndet⁡(−sI−Hγ)=p(−s).p(s) = \det(sI + H_\gamma^T) = \det(sI + H_\gamma) = (-1)^{2n} \det(-sI - H_\gamma) = p(-s).

A polynomial of even degree 2n2n with p(s)=p(−s)p(s) = p(-s) has only even powers, so p(s)=r(s2)p(s) = r(s^2) with deg⁡r=n\deg r = n. The coefficients are real because HγH_\gamma is real. The equivalence for s=jω0s = j\omega_0 follows from s2=−ω02s^2 = -\omega_0^2. □\square

Lemma 3 (the level test)

Let AA be Hurwitz and γ>σmax⁡(D)\gamma > \sigma_{\max}(D). Then ∥G∥∞≥γ\|G\|_\infty \ge \gamma if and only if HγH_\gamma has an eigenvalue on the imaginary axis.

Proof. The function f(ω)=σmax⁡(G(jω))f(\omega) = \sigma_{\max}(G(j\omega)) is continuous on R\mathbb{R}, because GG has no pole on the imaginary axis and singular values depend continuously on the matrix. As ∣ω∣→∞|\omega| \to \infty, G(jω)→DG(j\omega) \to D, so f(ω)→σmax⁡(D)<γf(\omega) \to \sigma_{\max}(D) < \gamma.

If ∥G∥∞≥γ\|G\|_\infty \ge \gamma: there is R>0R > 0 with f<γf < \gamma for ∣ω∣≥R|\omega| \ge R, so the supremum of ff is its maximum on [−R,R][-R, R], reached at some ω1\omega_1 with f(ω1)≥γf(\omega_1) \ge \gamma. On [ω1,R][\omega_1, R] the continuous function ff goes from a value at least γ\gamma to a value below γ\gamma, so f(ω0)=γf(\omega_0) = \gamma for some ω0\omega_0. Then γ\gamma is a singular value of G(jω0)G(j\omega_0), and Lemma 1 gives the eigenvalue jω0j\omega_0. (Every singular value of DD is at most σmax⁡(D)<γ\sigma_{\max}(D) < \gamma, so Lemma 1 applies.)

If HγH_\gamma has an eigenvalue jω0j\omega_0: Lemma 1 says that γ\gamma is a singular value of G(jω0)G(j\omega_0), so ∥G∥∞≥f(ω0)≥γ\|G\|_\infty \ge f(\omega_0) \ge \gamma. □\square

Lemma 4 (the start interval of the bisection)

Let AA be Hurwitz, WcW_c and WoW_o the solutions of AWc+WcAT+BBT=0A W_c + W_c A^T + B B^T = 0 and ATWo+WoA+CTC=0A^T W_o + W_o A + C^T C = 0, and σ1≥⋯≥σn≥0\sigma_1 \ge \dots \ge \sigma_n \ge 0 the square roots of the eigenvalues of WcWoW_c W_o (the Hankel singular values). Then

max⁡(σmax⁡(D),σ1)≤∥G∥∞≤σmax⁡(D)+2(σ1+⋯+σn).\max(\sigma_{\max}(D), \sigma_1) \le \|G\|_\infty \le \sigma_{\max}(D) + 2(\sigma_1 + \dots + \sigma_n).

Proof. The first lower bound is the limit of ff at infinity. The second is the classical fact that the Hankel norm σ1\sigma_1 is the norm of the Hankel operator of GG, which maps past inputs to future outputs; this operator is a compression of the input-output map of GG on L2(−∞,∞)L_2(-\infty, \infty), whose induced norm is ∥G∥∞\|G\|_\infty (Glover 1984, also Zhou, Doyle and Glover 1996, the chapter on Hankel norm approximation). The upper bound is the error bound of balanced truncation, ∥G−Gr∥∞≤2(σr+1+⋯+σn)\|G - G_r\|_\infty \le 2(\sigma_{r+1} + \dots + \sigma_n), applied with r=0r = 0, where G0=DG_0 = D, together with the triangle inequality (see the balanced truncation error bound; Enns 1984 and Glover 1984). A non-minimal realization only adds zero values to the list, because the nonzero eigenvalues of WcWoW_c W_o are those of a minimal realization. □\square

Theorem 1 (bisection)

Let AA be Hurwitz and ε>0\varepsilon > 0. HINF-BISECTION stops, and it returns (lo,hi)(lo, hi) with lo≤∥G∥∞≤hilo \le \|G\|_\infty \le hi and hi−lo≤2ε lohi - lo \le 2\varepsilon\, lo. If lo0=max⁡(σmax⁡(D),σ1)>0lo_0 = \max(\sigma_{\max}(D), \sigma_1) > 0, the loop runs at most ⌈log⁡2(n/ε)⌉\lceil \log_2(n/\varepsilon) \rceil times.

Proof. Invariant: lo≤∥G∥∞≤hilo \le \|G\|_\infty \le hi and lo≥lo0lo \ge lo_0. It holds after line L6 by Lemma 4 (line L6 also sets hihi to at least lolo, which does not break the invariant, because then the norm equals lolo). In line L8, γ=(lo+hi)/2>lo≥σmax⁡(D)\gamma = (lo + hi)/2 > lo \ge \sigma_{\max}(D), because the loop runs only while hi>lohi > lo. So Lemma 3 applies to γ\gamma: if line L9 finds an imaginary eigenvalue, then ∥G∥∞≥γ\|G\|_\infty \ge \gamma and the new lo=γlo = \gamma keeps the invariant; if not, ∥G∥∞<γ\|G\|_\infty < \gamma and the new hi=γhi = \gamma keeps it.

Termination and count. If lo0=0lo_0 = 0, then D=0D = 0 and all σi=0\sigma_i = 0, so hi0=0hi_0 = 0 and the loop does not run; in this case G=0G = 0. Otherwise each pass halves hi−lohi - lo, and lolo never decreases. The start width is hi0−lo0≤σmax⁡(D)+2nσ1−lo0≤2n lo0hi_0 - lo_0 \le \sigma_{\max}(D) + 2 n \sigma_1 - lo_0 \le 2 n\, lo_0, since σmax⁡(D)≤lo0\sigma_{\max}(D) \le lo_0 and σ1≤lo0\sigma_1 \le lo_0. After kk passes the width is at most 2n lo0/2k≤2n lo/2k2n\, lo_0 / 2^k \le 2n\, lo / 2^k, which is at most 2ε lo2\varepsilon\, lo once 2k≥n/ε2^k \ge n/\varepsilon. At exit the loop condition is false, so hi−lo≤2ε lohi - lo \le 2\varepsilon\, lo. □\square

Theorem 2 (level set iteration)

Let AA be Hurwitz, ε>0\varepsilon > 0, and let the start value lb0lb_0 of line L11 be positive. HINF-LEVEL-SET stops after at most 1+log⁡(∥G∥∞/lb0)/log⁡(1+2ε)1 + \log(\|G\|_\infty / lb_0) / \log(1 + 2\varepsilon) passes of the loop, and it returns (lb,γ,ω)(lb, \gamma, \omega) with lb≤∥G∥∞≤γ=(1+2ε)lb′lb \le \|G\|_\infty \le \gamma = (1 + 2\varepsilon) lb' for the value lb′≤lblb' \le lb held at the start of the last pass, so γ−lb≤2ε lb\gamma - lb \le 2\varepsilon\, lb. Here lb=σmax⁡(G(jω))lb = \sigma_{\max}(G(j\omega)), or lb=σmax⁡(D)lb = \sigma_{\max}(D) with ω=∞\omega = \infty.

Proof. Invariant: lblb is a value of ff (or the limit σmax⁡(D)\sigma_{\max}(D)), so lb≤∥G∥∞lb \le \|G\|_\infty. Line L11 sets lblb this way, and line L15 replaces it only by a larger value of ff at a midpoint.

The level is valid. Since lb>0lb > 0 and lb≥σmax⁡(D)lb \ge \sigma_{\max}(D), the level γ=(1+2ε)lb\gamma = (1 + 2\varepsilon) lb is larger than σmax⁡(D)\sigma_{\max}(D), so Lemma 3 applies.

Exit at line L14. If HγH_\gamma has no imaginary eigenvalue, Lemma 3 gives ∥G∥∞<γ\|G\|_\infty < \gamma.

Exit at line L16. Suppose HγH_\gamma has imaginary eigenvalues but every midpoint value is at most γ\gamma. We show that ∥G∥∞≤γ\|G\|_\infty \le \gamma. Assume instead ∥G∥∞>γ\|G\|_\infty > \gamma. The set Ω={ω:f(ω)>γ}\Omega = \{\omega : f(\omega) > \gamma\} is open, not empty, and bounded (because f→σmax⁡(D)<γf \to \sigma_{\max}(D) < \gamma). Let (a,b)(a, b) be one of its components. Then aa and bb are finite, and f(a)=f(b)=γf(a) = f(b) = \gamma by continuity. By Lemma 1, jaja and jbjb are eigenvalues of HγH_\gamma, so aa and bb are in the sorted list ω1<⋯<ωk\omega_1 < \dots < \omega_k of line L15, which holds the frequencies of line L13 with both signs (the eigenvalues of the real matrix HγH_\gamma come in conjugate pairs, and f(−ω)=f(ω)f(-\omega) = f(\omega)). Let ωi=a\omega_i = a; then ωi+1≤b\omega_{i+1} \le b, and the midpoint (ωi+ωi+1)/2(\omega_i + \omega_{i+1})/2 lies in (a,b)⊂Ω(a, b) \subset \Omega. Its value is larger than γ\gamma, which is false. So ∥G∥∞≤γ\|G\|_\infty \le \gamma, and the returned lblb is at least the old lblb, so γ−lb≤2ε lb\gamma - lb \le 2\varepsilon\, lb.

Progress. If the loop does not exit, line L16 found a midpoint value larger than γ\gamma, so the new lblb is larger than (1+2ε)(1 + 2\varepsilon) times the old one. Since lb≤∥G∥∞lb \le \|G\|_\infty always, after kk such passes (1+2ε)klb0<∥G∥∞(1 + 2\varepsilon)^k lb_0 < \|G\|_\infty, which bounds kk. □\square

The count in Theorem 2 is a worst case that grows like 1/ε1/\varepsilon. Boyd and Balakrishnan (1990) proved much more: the lower bounds of the level set iteration converge quadratically to the norm. That result rests on the regularity of ff near a peak and is not reproved here.

Floating point

The implementation forms HγH_\gamma in floating point, computes det⁡(sI−Hγ)\det(sI - H_\gamma) with the Faddeev-LeVerrier recursion, keeps the even coefficients as rr, and finds the roots of rr with the Durand-Kerner method of the shared helper. A root tt counts as real when ∣Im⁡t∣≤10−6(1+∣t∣)|\operatorname{Im} t| \le 10^{-6}(1 + |t|), and as nonpositive when Re⁡t≤10−10(1+∣t∣)\operatorname{Re} t \le 10^{-10}(1 + |t|). When γ\gamma is far from ∥G∥∞\|G\|_\infty in relative terms, every root of rr is either clearly real and negative or clearly not, and the decision is the exact one. Near γ=∥G∥∞\gamma = \|G\|_\infty two real roots of rr merge into a double root, which the root finder computes with an error near 10−810^{-8}; the tolerance then accepts the pair as real, and a decision can be wrong only when γ\gamma is within about 10−1210^{-12} (relative) of the norm. Since the methods are stopped with ε≥10−10\varepsilon \ge 10^{-10} in practice, such an error moves the returned interval by much less than its width. The tests compare the floating point decision with an exact count of the nonpositive roots of rr in rational arithmetic (a Sturm sequence) on random systems.

Complexity

The model is the real RAM, with nn the state dimension, mm the number of inputs, pp the number of outputs and ε\varepsilon the relative accuracy. Dense factorizations count as O(k3)O(k^3) flops for a k×kk \times k matrix, and the eigenvalues of a 2n×2n2n \times 2n matrix count as O(n3)O(n^3), as is usual for the QR algorithm.

  • One test (lines L1 to L3). Solving with MγM_\gamma costs O((m+p)3+n(m+p)2)O((m + p)^3 + n (m + p)^2), the products cost O(n2(m+p))O(n^2 (m + p)), and the eigenvalues cost O(n3)O(n^3). The implementation instead spends O(n4)O(n^4) on the Faddeev-LeVerrier recursion and O(kn2)O(k n^2) on kk Durand-Kerner iterations.
  • Start of the bisection (lines L4 to L6). Two Lyapunov equations and the eigenvalues of WcWoW_c W_o cost O(n3)O(n^3) with the Bartels-Stewart method (see the Lyapunov equation). The implementation solves the n2×n2n^2 \times n^2 Kronecker system instead, in O(n6)O(n^6), which is fine for n≤3n \le 3.
  • Bisection. At most ⌈log⁡2(n/ε)⌉\lceil \log_2(n/\varepsilon) \rceil tests, so O((n+m+p)3log⁡(n/ε))O((n + m + p)^3 \log(n/\varepsilon)) in all. The convergence is linear: one bit of accuracy per pass.
  • Level set, per pass. One test, plus at most 2n−12n - 1 evaluations of GG at midpoints, because rr has at most nn roots. Each evaluation costs O(n3+n2(m+p)+nmp)O(n^3 + n^2 (m + p) + n m p) and a singular value computation O(mpmin⁡(m,p))O(m p \min(m, p)). After a one time reduction of AA to Hessenberg form, each evaluation of G(jω)G(j\omega) costs O(n2(m+p))O(n^2 (m + p)).
  • Level set, number of passes. The proved bound is 1+log⁡(∥G∥∞/lb0)/log⁡(1+2ε)1 + \log(\|G\|_\infty / lb_0) / \log(1 + 2\varepsilon), which is poor. The convergence result of Boyd and Balakrishnan (1990) is local and quadratic. In the tests of this page the level set method used 0 to 3 passes (a measurement, not a bound).
  • Space. O((n+m+p)2)O((n + m + p)^2) for the matrices.

Properties

  • Certified interval. In exact arithmetic the output interval holds the norm. A frequency sweep only gives a lower bound, and it can miss a narrow peak by any amount.
  • Independent of the realization. Uncontrollable or unobservable modes do not change GG, and they do not change the answer; they add eigenvalues of HγH_\gamma that are never on the imaginary axis when AA is Hurwitz.
  • Peak frequency. The level set method returns a frequency at which the lower bound is reached. The bisection returns only the interval, but the crossings of its last successful test bracket a frequency near the peak.
  • Not exact. The norm is in general an algebraic number with no closed form, so every method returns an interval.
  • Deterministic. The same input gives the same output.

Variants and improvements

  • Level set iteration. Lines L11 to L16, from Bruinsma and Steinbuch (1990) and Boyd and Balakrishnan (1990). It is the method used in practice, because it needs few passes.
  • Discrete time. For G(z)=C(zI−A)−1B+DG(z) = C(zI - A)^{-1}B + D with AA Schur, the frequencies are points ejθe^{j\theta} on the unit circle. The Hamiltonian matrix becomes a symplectic matrix or pencil, and the test looks for its eigenvalues of modulus 1. A bilinear transform to continuous time is another way.
  • Structure preserving eigenvalue solvers. A general eigenvalue solver can move a true imaginary eigenvalue of HγH_\gamma off the axis by rounding. Solvers that keep the Hamiltonian structure keep the eigenvalues in pairs λ,−λˉ\lambda, -\bar\lambda, so a simple imaginary eigenvalue stays on the axis.
  • Descriptor systems and large systems. The test extends to Ex′=Ax+BuE x' = A x + B u through a generalized eigenvalue problem with the QZ algorithm. For large sparse systems, only the eigenvalues near the imaginary axis are needed, and Krylov methods are used.
  • Related levels. The same idea tests other quantities: the distance of a Hurwitz matrix to the set of unstable matrices (with B=C=IB = C = I), and the bounded real lemma gives the Riccati and LMI forms of the same question "is the norm below gamma?".

When to use it

Use it whenever you need the H-infinity norm of a system with a state-space model: to check a robustness margin with the small-gain theorem, to report the peak of a sensitivity function, to check the result of an H-infinity synthesis, or as the inner test of a gamma iteration. For one lightly damped mode a sweep near the resonance gives a good lower bound, but only the Hamiltonian test certifies the upper bound. For the H2 norm no iteration is needed; one Lyapunov equation gives it.

Pitfalls

  • A must be Hurwitz. If AA has an imaginary eigenvalue the norm is infinite or the test of Lemma 1 fails, and if AA has an eigenvalue in the right half plane the supremum over jωj\omega is the L∞L_\infty norm, not the H-infinity norm. Check AA first, as lines L4 and L11 do.
  • Levels at or below the norm of D. At γ=σmax⁡(D)\gamma = \sigma_{\max}(D) the matrix MγM_\gamma is singular, and below it the test is not valid. The start values keep every level above σmax⁡(D)\sigma_{\max}(D).
  • Tangency is ill-conditioned. At γ=∥G∥∞\gamma = \|G\|_\infty two imaginary eigenvalues merge, and near this level they split by about the square root of the unit roundoff. A tolerance on the real part is needed; too small a tolerance turns a correct "yes" into "no" near the norm, and too large a tolerance turns a "no" into "yes". The implementation works on t=s2t = s^2, where a crossing at ω=0\omega = 0 is a simple root and stays well conditioned.
  • Crossings of other singular values. For a system with several inputs and outputs, a frequency in line L3 can be a crossing of a smaller singular value. The bisection does not care, but a level set code that only uses pairs of crossings as intervals must use consecutive crossings, as line L15 does, and not assume that they alternate between rising and falling.
  • Scaling. Badly scaled AA, BB, CC give a badly scaled HγH_\gamma. Balance the realization first.
  • Sweeps are lower bounds. A grid of frequencies can miss a peak of width about ζωn\zeta \omega_n by a large factor. Use a sweep only to check, never to bound the norm from above.

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()
h_infinity_norm_computation.py 170 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/h-infinity-norm-computation/. The authors are listed in prov/KBHPWA.jsonl.

"""H-infinity norm of a stable state-space system by Hamiltonian tests.

The system is x' = A x + B u, y = C x + D u with A Hurwitz (n by n), B
(n by m), C (p by n) and D (p by m). Matrices are lists of rows. The
transfer matrix is G(s) = C (s I - A)^(-1) B + D, and the H-infinity norm is
the supremum over real w of the largest singular value of G(j w).

The test behind both methods (pseudocode lines L1 to L3): for gamma larger
than the largest singular value of D, gamma is a singular value of G(j w)
if and only if j w is an eigenvalue of the Hamiltonian matrix

    H = [[A, 0], [0, -A^T]] + [[B, 0], [0, -C^T]] M^(-1) [[-C, 0], [0, -B^T]],
    M = [[D, -gamma I_p], [-gamma I_m, D^T]].

The characteristic polynomial of H is even, det(s I - H) = r(s^2), so the
imaginary eigenvalues j w are the real roots t = -w^2 <= 0 of r.

- hinf_norm_bisection: the bisection of Boyd, Balakrishnan and Kabamba
  (1989), lines L4 to L10.
- hinf_norm_level_set: the level set iteration of Bruinsma and Steinbuch
  (1990) and Boyd and Balakrishnan (1990), lines L11 to L16.

Both return an interval [lo, hi] that holds the norm, with
hi - lo <= 2 eps lo. Floating point tolerances: the characteristic
polynomial comes from ctlmat.charpoly and its roots from ctlmat.polyroots.
A root t of r is taken as real if |Im t| <= IMAG_TOL (1 + |t|), and as
nonpositive if Re t <= SIGN_TOL (1 + |t|). A double root of r (a tangent
of the singular value curve to the level gamma) is computed with an error
near 1e-8, so a decision can be wrong only when gamma is within about
1e-12 (relative) of the norm.
"""

import math

from ctlmat import (add, block, charpoly, eye, kron, mul, norm2, polyroots,
                    scale, solve, transpose, unvec, vec, zeros)

IMAG_TOL = 1e-6
SIGN_TOL = 1e-10
MAX_ITER = 500


def eigenvalues(a):
    """Eigenvalues of a small square matrix, as roots of its characteristic polynomial."""
    return polyroots(charpoly([[float(v) for v in row] for row in a]))


def is_hurwitz(a):
    """True if every eigenvalue of a has a negative real part."""
    return all(lam.real < 0 for lam in eigenvalues(a))


def freq_response(A, B, C, D, w):
    """Return G(j w) = C (j w I - A)^(-1) B + D as a complex matrix."""
    n = len(A)
    jwa = [[(1j * w if i == j else 0) - A[i][j] for j in range(n)] for i in range(n)]
    x = solve(jwa, [[complex(v) for v in row] for row in B])
    g = mul(C, x)
    return [[g[i][j] + D[i][j] for j in range(len(D[0]))] for i in range(len(D))]


def sigma_max(A, B, C, D, w):
    """Largest singular value of G(j w)."""
    return norm2(freq_response(A, B, C, D, w))


def hamiltonian(A, B, C, D, gamma):
    """The Hamiltonian matrix H_gamma (exact when the data and gamma are int or Fraction)."""
    n, m, p = len(A), len(B[0]), len(C)
    big_m = block([[D, scale(-gamma, eye(p))], [scale(-gamma, eye(m)), transpose(D)]])
    right = block([[scale(-1, C), zeros(p, n)], [zeros(m, n), scale(-1, transpose(B))]])
    left = block([[B, zeros(n, p)], [zeros(n, m), scale(-1, transpose(C))]])
    h0 = block([[A, zeros(n)], [zeros(n), scale(-1, transpose(A))]])
    return add(h0, mul(left, solve(big_m, right)))


def even_polynomial(h):
    """The coefficients of r with det(s I - h) = r(s^2), highest power first."""
    c = charpoly(h)
    return [c[k] for k in range(0, len(c), 2)]


def imaginary_frequencies(A, B, C, D, gamma):
    """The w >= 0 such that j w is an eigenvalue of H_gamma, sorted."""
    h = hamiltonian(A, B, C, D, gamma)  # @line L1
    r = even_polynomial([[float(v) for v in row] for row in h])  # @line L2
    out = []
    for t in polyroots(r):  # @line L3
        if abs(t.imag) <= IMAG_TOL * (1 + abs(t)) and t.real <= SIGN_TOL * (1 + abs(t)):
            out.append(math.sqrt(max(0.0, -t.real)))
    return sorted(out)


def gramians(A, B, C):
    """Controllability and observability gramians of a Hurwitz A.

    A W_c + W_c A^T + B B^T = 0 and A^T W_o + W_o A + C^T C = 0, solved
    through the Kronecker form (I kron A + A kron I) vec(W) = -vec(B B^T).
    """
    n = len(A)
    at = transpose(A)
    k_c = add(kron(eye(n), A), kron(A, eye(n)))
    k_o = add(kron(eye(n), at), kron(at, eye(n)))
    wc = unvec(solve(k_c, [-v for v in vec(mul(B, transpose(B)))]), n)
    wo = unvec(solve(k_o, [-v for v in vec(mul(transpose(C), C))]), n)
    return wc, wo


def hankel_singular_values(A, B, C):
    """Square roots of the eigenvalues of W_c W_o, largest first."""
    wc, wo = gramians(A, B, C)
    lam = eigenvalues(mul(wc, wo))
    return sorted((math.sqrt(max(v.real, 0.0)) for v in lam), reverse=True)


def hinf_norm_bisection(A, B, C, D, eps=1e-8):
    """Bisection on gamma. Returns (lo, hi, iterations) with lo <= norm <= hi."""
    if not is_hurwitz(A):  # @line L4
        raise ValueError("A is not Hurwitz")
    d = norm2(D)
    hsv = hankel_singular_values(A, B, C)  # @line L5
    lo = max(d, hsv[0])  # @line L6
    hi = max(lo, d + 2 * sum(hsv))
    iterations = 0
    while hi - lo > 2 * eps * lo:  # @line L7
        gamma = (lo + hi) / 2  # @line L8
        if imaginary_frequencies(A, B, C, D, gamma):  # @line L9
            lo = gamma
        else:
            hi = gamma
        iterations += 1
    return lo, hi, iterations  # @line L10


def hinf_norm_level_set(A, B, C, D, eps=1e-8):
    """Level set iteration. Returns (lo, hi, w, iterations).

    lo is the largest singular value of G(j w) at the returned w (w is
    math.inf when lo comes from D), and lo <= norm <= hi.
    """
    if not is_hurwitz(A):  # @line L11
        raise ValueError("A is not Hurwitz")
    lb, w_lb = norm2(D), math.inf
    for w in [0.0] + [abs(lam) for lam in eigenvalues(A)]:
        s = sigma_max(A, B, C, D, w)
        if s > lb:
            lb, w_lb = s, w
    if lb == 0:
        raise ValueError("G is zero at 0, at infinity and at the pole moduli; use the bisection")
    iterations = 0
    while iterations < MAX_ITER:  # @line L12
        gamma = (1 + 2 * eps) * lb  # @line L13
        freqs = imaginary_frequencies(A, B, C, D, gamma)
        if not freqs:  # @line L14
            return lb, gamma, w_lb, iterations
        iterations += 1
        ws = sorted([-w for w in freqs] + freqs)  # @line L15
        best, w_best = lb, w_lb
        for a, b in zip(ws, ws[1:]):
            mid = abs((a + b) / 2)
            s = sigma_max(A, B, C, D, mid)
            if s > best:
                best, w_best = s, mid
        if best <= gamma:  # @line L16
            return best, gamma, w_best, iterations
        lb, w_lb = best, w_best
    raise RuntimeError("level set iteration did not stop")
test_h_infinity_norm_computation.py 237 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/h-infinity-norm-computation/. The authors are listed in prov/KBHPWA.jsonl.

import math
import random
from fractions import Fraction

import pytest

from ctlmat import charpoly, mul, polyder, polyroots, transpose
from h_infinity_norm_computation import (even_polynomial, freq_response, hamiltonian,
                                         hankel_singular_values, hinf_norm_bisection,
                                         hinf_norm_level_set, imaginary_frequencies,
                                         sigma_max)

# Tolerances: both methods run with eps = 1e-8, so the returned interval has
# relative width at most 2e-8; values are compared with a relative
# tolerance of 1e-7. The frequency sweep is a lower bound of the norm; it
# must not exceed the upper end of the interval by more than 1e-9
# (relative), and on these systems it comes within 1e-6 of the lower end.

EPS = 1e-8
F = Fraction

FIRST_ORDER = ([[-1]], [[1]], [[1]], [[0]])                       # 1 / (s + 1)
LIGHT = ([[0, 1], [-1, F(-1, 5)]], [[0], [1]], [[1, 0]], [[0]])   # 1 / (s^2 + 0.2 s + 1)
NON_MINIMAL = ([[-4, -8, 12], [0, -8, 0], [0, 0, -16]], [[1], [0], [0]], [[1, 1, 1]], [[0]])
PEAK_AT_ZERO = ([[-1]], [[1]], [[1]], [[1]])                      # (s + 2) / (s + 1)
PEAK_AT_INFINITY = ([[-2]], [[1]], [[-1]], [[1]])                 # (s + 1) / (s + 2)

LIGHT_NORM = 1 / (0.2 * math.sqrt(1 - 0.01))                     # 1 / (2 zeta sqrt(1 - zeta^2))


def close(x, y, tol=1e-7):
    return abs(x - y) <= tol * max(1.0, abs(y))


def random_system(rng):
    """A random rational system with n <= 3, m, p <= 2 and A Hurwitz (max Re < -0.1)."""
    while True:
        n, m, p = rng.randint(1, 3), rng.randint(1, 2), rng.randint(1, 2)
        a = [[F(rng.randint(-6, 6), 4) for _ in range(n)] for _ in range(n)]
        for i in range(n):
            a[i][i] = F(-rng.randint(2, 12), 4)
        if max(r.real for r in polyroots(charpoly(a))) >= -0.1:
            continue
        b = [[F(rng.randint(-4, 4), 4) for _ in range(m)] for _ in range(n)]
        c = [[F(rng.randint(-4, 4), 4) for _ in range(n)] for _ in range(p)]
        d = [[F(rng.randint(-2, 2), 4) for _ in range(m)] for _ in range(p)]
        if all(v == 0 for row in b for v in row) or all(v == 0 for row in c for v in row):
            continue
        return a, b, c, d


def sweep(sys, points=1201):
    """A lower bound of the norm: a log grid from 1e-3 to 1e3, the value at 0
    and at infinity (sigma_max(D)), and a golden section refinement around the
    best grid point."""
    a, b, c, d = sys
    grid = [10 ** (-3 + 6 * k / (points - 1)) for k in range(points)]
    vals = [sigma_max(a, b, c, d, w) for w in grid]
    k = max(range(points), key=lambda i: vals[i])
    best = max(vals[k], sigma_max(a, b, c, d, 0.0), sigma_max(a, b, c, d, 1e9))
    lo, hi = grid[max(k - 1, 0)], grid[min(k + 1, points - 1)]
    g = (math.sqrt(5) - 1) / 2
    x1, x2 = hi - g * (hi - lo), lo + g * (hi - lo)
    f1, f2 = sigma_max(a, b, c, d, x1), sigma_max(a, b, c, d, x2)
    for _ in range(80):
        if f1 > f2:
            hi, x2, f2 = x2, x1, f1
            x1 = hi - g * (hi - lo)
            f1 = sigma_max(a, b, c, d, x1)
        else:
            lo, x1, f1 = x1, x2, f2
            x2 = lo + g * (hi - lo)
            f2 = sigma_max(a, b, c, d, x2)
    return max(best, f1, f2)


def singular_values(g):
    """Singular values of a complex matrix with at most 2 columns, from G^H G."""
    gh = [[v.conjugate() for v in row] for row in transpose(g)]
    q = mul(gh, g)
    if len(q) == 1:
        return [math.sqrt(max(q[0][0].real, 0.0))]
    a, d, b = q[0][0].real, q[1][1].real, q[0][1]
    mid, rad = (a + d) / 2, math.sqrt(((a - d) / 2) ** 2 + abs(b) ** 2)
    return [math.sqrt(max(mid + rad, 0.0)), math.sqrt(max(mid - rad, 0.0))]


def sturm_count_nonpositive(r):
    """Number of distinct real roots of the Fraction polynomial r in (-inf, 0]."""
    seq = [r, polyder(r)]
    while len(seq[-1]) > 1 or seq[-1][0] != 0:
        num, den = list(seq[-2]), seq[-1]
        if len(den) == 1 and den[0] == 0:
            break
        while len(num) >= len(den) and any(v != 0 for v in num):
            f = num[0] / den[0]
            for i in range(len(den)):
                num[i] -= f * den[i]
            num.pop(0)
        while len(num) > 1 and num[0] == 0:
            num.pop(0)
        if not num or all(v == 0 for v in num):
            break
        seq.append([-v for v in num])

    def changes(signs):
        s = [v for v in signs if v != 0]
        return sum(1 for x, y in zip(s, s[1:]) if (x > 0) != (y > 0))

    at_minus_inf = [p[0] * (-1) ** (len(p) - 1) for p in seq]
    at_zero = [p[-1] for p in seq]
    return changes(at_minus_inf) - changes(at_zero)


def test_check_value_first_order():
    lo, hi, _ = hinf_norm_bisection(*FIRST_ORDER, eps=EPS)
    assert lo <= 1.0 <= hi and hi - lo <= 2 * EPS * lo
    lo, hi, w, _ = hinf_norm_level_set(*FIRST_ORDER, eps=EPS)
    assert close(lo, 1.0) and w == 0.0


def test_check_value_light_damping():
    lo, hi, _ = hinf_norm_bisection(*LIGHT, eps=EPS)
    assert close(lo, LIGHT_NORM) and close(hi, LIGHT_NORM)
    assert close(LIGHT_NORM, 5.02519, 1e-6)
    lo, hi, w, _ = hinf_norm_level_set(*LIGHT, eps=EPS)
    assert close(lo, LIGHT_NORM) and close(w, math.sqrt(0.98), 1e-6)


def test_even_polynomial_exact():
    # r(t) = t^2 + 1.96 t + 1 - 1/gamma^2, in exact arithmetic.
    for gamma in (F(1), F(5), F(11, 2)):
        r = even_polynomial(hamiltonian(*LIGHT, gamma))
        assert r == [1, F(49, 25), 1 - 1 / gamma ** 2]


def test_level_crossings_light_damping():
    a, b, c, d = LIGHT
    assert close(imaginary_frequencies(a, b, c, d, 1.0)[-1], 1.4, 1e-9)
    w = imaginary_frequencies(a, b, c, d, 5.0)
    assert len(w) == 2 and close(w[0], math.sqrt(0.96), 1e-9) and close(w[1], 1.0, 1e-9)
    assert imaginary_frequencies(a, b, c, d, 5.03) == []


def test_non_minimal_realization():
    # G = 1/(s + 4): the modes at -8 and -16 cancel.
    for lo, hi in (hinf_norm_bisection(*NON_MINIMAL, eps=EPS)[:2],
                   hinf_norm_level_set(*NON_MINIMAL, eps=EPS)[:2]):
        assert close(lo, 0.25) and close(hi, 0.25)


def test_feedthrough():
    lo, hi, _ = hinf_norm_bisection(*PEAK_AT_ZERO, eps=EPS)
    assert close(lo, 2.0) and close(hi, 2.0)
    lo, hi, w, _ = hinf_norm_level_set(*PEAK_AT_ZERO, eps=EPS)
    assert close(lo, 2.0) and w == 0.0
    lo, hi, _ = hinf_norm_bisection(*PEAK_AT_INFINITY, eps=EPS)
    assert close(lo, 1.0) and close(hi, 1.0)
    lo, hi, w, _ = hinf_norm_level_set(*PEAK_AT_INFINITY, eps=EPS)
    assert close(lo, 1.0) and w == math.inf


def test_not_hurwitz():
    with pytest.raises(ValueError):
        hinf_norm_bisection([[1]], [[1]], [[1]], [[0]])
    with pytest.raises(ValueError):
        hinf_norm_level_set([[0, 1], [-1, 0]], [[0], [1]], [[1, 0]], [[0]])


def test_random_systems():
    rng = random.Random(20240611)
    for _ in range(12):
        sys = random_system(rng)
        a, b, c, d = sys
        n = len(a)
        lo1, hi1, it = hinf_norm_bisection(*sys, eps=EPS)
        lo2, hi2, w2, _ = hinf_norm_level_set(*sys, eps=EPS)
        # The difference of two close floats carries a relative error near 1e-8.
        assert hi1 - lo1 <= 2 * EPS * lo1 * (1 + 1e-6)
        assert hi2 - lo2 <= 2 * EPS * lo2 * (1 + 1e-6)
        # The two intervals hold the same number.
        assert max(lo1, lo2) <= min(hi1, hi2) * (1 + 1e-9)
        # The proved bound on the number of bisection steps.
        assert it <= math.ceil(math.log2(n / EPS))
        # The start interval of the bisection holds the norm.
        hsv = hankel_singular_values(a, b, c)
        sd = sigma_max(a, b, c, d, 1e12)
        assert max(sd, hsv[0]) <= hi1 * (1 + 1e-9)
        assert lo1 <= (sd + 2 * sum(hsv)) * (1 + 1e-9)
        # The level set lower bound is a value of sigma_max.
        if w2 != math.inf:
            assert close(sigma_max(a, b, c, d, w2), lo2, 1e-12)
        # A dense sweep never beats the upper bound, and it finds the peak.
        s = sweep(sys)
        assert s <= hi1 * (1 + 1e-9)
        assert s >= lo1 * (1 - 1e-6)


def test_decision_against_exact_sturm_count():
    rng = random.Random(7)
    checked = 0
    for _ in range(10):
        sys = random_system(rng)
        a, b, c, d = sys
        lo, hi, _ = hinf_norm_bisection(*sys, eps=EPS)
        sd = max(singular_values([[complex(v) for v in row] for row in d]))
        for factor in (F(1, 2), F(4, 5), F(19, 20), F(21, 20), F(5, 4), F(2)):
            gamma = F(lo).limit_denominator(10 ** 6) * factor
            if gamma <= sd * 1.001:
                continue
            exact = even_polynomial(hamiltonian(a, b, c, d, gamma))
            has_exact = sturm_count_nonpositive(exact) > 0
            assert has_exact == (factor < 1)
            assert bool(imaginary_frequencies(a, b, c, d, float(gamma))) == has_exact
            checked += 1
    assert checked >= 20


def test_frequencies_are_singular_values():
    rng = random.Random(11)
    for _ in range(10):
        sys = random_system(rng)
        a, b, c, d = sys
        lo, _, _ = hinf_norm_bisection(*sys, eps=EPS)
        sd = max(singular_values([[complex(v) for v in row] for row in d]))
        gamma = 0.8 * lo
        if gamma <= sd * 1.001:
            continue
        ws = imaginary_frequencies(a, b, c, d, gamma)
        assert ws
        for w in ws:
            g = freq_response(a, b, c, d, w)
            sv = singular_values(g) if len(g[0]) <= 2 else None
            assert min(abs(s - gamma) for s in sv) <= 1e-6 * gamma

History

Before 1989 the H-infinity norm was found by sweeping the frequency or by a gamma iteration on a Riccati equation. Boyd, Balakrishnan and Kabamba (1989) showed that the question "is the norm at least gamma?" has an exact answer from the imaginary eigenvalues of a Hamiltonian matrix, and they used it in a bisection with the Hankel singular value bounds as the start interval. They also noted that the test applies to related problems, such as the distance to instability. In 1990 Bruinsma and Steinbuch used the crossing frequencies to raise the level, and Boyd and Balakrishnan proved that this level set iteration converges quadratically, from a regularity result on the largest singular value near a peak. The level set method is now the standard way to compute the norm.

References

  1. Stephen Boyd, Venkataramanan Balakrishnan and Pierre Kabamba, A bisection method for computing the H-infinity norm of a transfer matrix and related problems, Mathematics of Control, Signals, and Systems 2(3) (1989) 207-219, the whole paper (the Hamiltonian test for a level gamma and the bisection on gamma)
  2. N. A. Bruinsma and M. Steinbuch, A fast algorithm to compute the H-infinity-norm of a transfer function matrix, Systems and Control Letters 14(4), 287-293, 1990, the whole paper (the level set iteration with midpoints of the imaginary eigenvalues, and its start value)
  3. Stephen Boyd and Venkataramanan Balakrishnan, A regularity result for the singular values of a transfer matrix and a quadratically convergent algorithm for computing its L-infinity-norm, Systems and Control Letters 15(1), 1-7, 1990, the whole paper (the regularity of the largest singular value and the quadratic convergence of the level set iteration)
  4. Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, Chapter 4, Performance Specifications (the computation of the H2 and H-infinity norms), and Chapter 8, Hankel Norm Approximation (the bounds by the Hankel singular values)

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