Algorithm Search⌘K

Algorithmadvanced

H-infinity loop shaping

Also called Glover-McFarlane loop shaping, normalized coprime factor robust stabilization.

Shapes the open loop with weights and then robustly stabilizes the shaped plant against normalized coprime factor uncertainty.

Time
O(c n^3 + n^2 (m + p)) total
Space
O(n^2 + n (m + p)) extra
Where
c = the number of Newton steps of one matrix sign function; m = the number of plant inputs; n = the number of states of the shaped plant; p = the number of plant outputs
Properties
deterministicnot exactnot iterativeiterative
Origin
Duncan McFarlane, Keith Glover, 1992

H-infinity loop shaping, also called Glover-McFarlane loop shaping, is a design method for linear multivariable feedback in two steps. First the designer picks weights W1W_1 and W2W_2 so that the shaped plant Gs=W2GW1G_s = W_2 G W_1 has a good open loop shape: high gain at low frequency, low gain at high frequency and a moderate slope near crossover, as in classical loop shaping. Then a robust controller KsK_s stabilizes GsG_s with the largest possible margin against perturbations of a normalized coprime factorization of GsG_s. The final controller is K=W1KsW2K = W_1 K_s W_2. The second step is a special H-infinity control problem whose optimal level has a closed form from two Riccati equations, so no search on γ\gamma is needed.

In plain words

Classical loop shaping tells you what the loop gain should look like, but it does not tell you how to make the loop stable with good margins for a plant with many inputs and outputs. This method lets you shape the gain first, with simple weights, and then adds a controller that fixes stability and robustness near crossover. The robust step is cheap: two Riccati equations give the best margin in closed form. If the best margin is very small, the shape you asked for is not compatible with the plant, and you change the weights. If the margin is good, the robust step changes the shaped loop only a little.

The problem

Let Gs=(A,B,C,0)G_s = (A, B, C, 0) be a strictly proper shaped plant with mm inputs, pp outputs and nn states, with (A,B)(A, B) stabilizable and (C,A)(C, A) detectable. A normalized left coprime factorization Gs=M−1NG_s = M^{-1} N has MM and NN stable and NN∗+MM∗=IN N^* + M M^* = I on the imaginary axis. The perturbed plants are

GΔ=(M+ΔM)−1(N+ΔN),∥[ΔNΔM]∥∞<ε,G_\Delta = (M + \Delta_M)^{-1}(N + \Delta_N), \qquad \left\| \begin{bmatrix} \Delta_N & \Delta_M \end{bmatrix} \right\|_\infty < \varepsilon,

with ΔN\Delta_N and ΔM\Delta_M stable. The controller KsK_s is connected in negative feedback, u=−Ksyu = -K_s y. By the small gain theorem, KsK_s stabilizes every such GΔG_\Delta if and only if it stabilizes GsG_s internally and

γ(Gs,Ks)=∥[KsI](I+GsKs)−1[IGs]∥∞≤1ε.\gamma(G_s, K_s) = \left\| \begin{bmatrix} K_s \\ I \end{bmatrix} (I + G_s K_s)^{-1} \begin{bmatrix} I & G_s \end{bmatrix} \right\|_\infty \le \frac{1}{\varepsilon}.

The stability margin of the loop is b(Gs,Ks)=1/γ(Gs,Ks)b(G_s, K_s) = 1 / \gamma(G_s, K_s). The robust step asks for a controller with bb close to the largest value εmax⁡\varepsilon_{\max}.

Theorem (Glover and McFarlane 1989; Skogestad and Postlethwaite 2005, section 9.4). Let Z≥0Z \ge 0 be the stabilizing solution of the filter Riccati equation and X≥0X \ge 0 that of the control Riccati equation:

AZ+ZAT−ZCTCZ+BBT=0,ATX+XA−XBBTX+CTC=0.A Z + Z A^T - Z C^T C Z + B B^T = 0, \qquad A^T X + X A - X B B^T X + C^T C = 0.

Then the smallest achievable value of γ(Gs,Ks)\gamma(G_s, K_s) over all internally stabilizing controllers is

γmin⁡=1+ρ(XZ),εmax⁡=1γmin⁡=1−∥[NM]∥H2,\gamma_{\min} = \sqrt{1 + \rho(X Z)}, \qquad \varepsilon_{\max} = \frac{1}{\gamma_{\min}} = \sqrt{1 - \left\| \begin{bmatrix} N & M \end{bmatrix} \right\|_H^2},

where ρ\rho is the spectral radius and ∥⋅∥H\| \cdot \|_H is the Hankel norm. For every γ>γmin⁡\gamma > \gamma_{\min} a controller with γ(Gs,Ks)≤γ\gamma(G_s, K_s) \le \gamma is Ks=(AK,BK,CK,0)K_s = (A_K, B_K, C_K, 0) with

L=(1−γ2)I+XZ,BK=γ2(LT)−1ZCT,AK=A−BBTX+BKC,CK=−BTX.L = (1 - \gamma^2) I + X Z, \quad B_K = \gamma^2 (L^T)^{-1} Z C^T, \quad A_K = A - B B^T X + B_K C, \quad C_K = -B^T X.

Skogestad and Postlethwaite (2005) write this controller for positive feedback, u=Ksyu = K_s y, with CK=BTXC_K = B^T X. This page uses negative feedback, so the sign of CKC_K is changed once here and in the code.

The algorithm

  1. LOOP-SHAPING-DESIGN(G, W1, W2, f)
  2. 1Gs ← W2 G W1 ▷ shaped plant (A, B, C, 0)
  3. 2Z ← stabilizing solution of A Z + Z A^T - Z C^T C Z + B B^T = 0
  4. 3X ← stabilizing solution of A^T X + X A - X B B^T X + C^T C = 0
  5. 4γmin ← sqrt(1 + ρ(X Z))
  6. 5γ ← f · γmin ▷ f > 1, often 1.1
  7. 6L ← (1 - γ^2) I + X Z
  8. 7B_K ← γ^2 (L^T)^-1 Z C^T
  9. 8Ks ← (A - B B^T X + B_K C, B_K, -B^T X, 0)
  10. 9return γmin, γ, K = W1 Ks W2

The two Riccati equations are solved as on the two-Riccati synthesis page: the code takes the matrix sign function of the 2n×2n2n \times 2n Hamiltonian matrix by a scaled Newton iteration, reads off the stable invariant subspace, and accepts the solution only if the residual is small and the closed loop matrix is Hurwitz. The designer then checks γmin⁡\gamma_{\min}: a value above about 4 (εmax⁡\varepsilon_{\max} below 0.25) means the weights ask for a loop that this plant cannot give with good robustness. This is a rule of thumb from design practice (Skogestad and Postlethwaite 2005, section 9.4), not a theorem.

Example

Take Gs=1/sG_s = 1/s, so A=0A = 0 and B=C=1B = C = 1. Both Riccati equations reduce to 1−X2=01 - X^2 = 0, so X=Z=1X = Z = 1 and

γmin⁡=1+1=1.41421,εmax⁡=0.70711.\gamma_{\min} = \sqrt{1 + 1} = 1.41421, \qquad \varepsilon_{\max} = 0.70711.

With f=1.1f = 1.1, γ=1.55563\gamma = 1.55563 and γ2=2.42\gamma^2 = 2.42. Then L=−0.42L = -0.42, BK=2.42⋅1/(−0.42)=−5.76190B_K = 2.42 \cdot 1/(-0.42) = -5.76190, AK=−1−5.76190=−6.76190A_K = -1 - 5.76190 = -6.76190 and CK=−1C_K = -1. The controller for u=−Ksyu = -K_s y is

Ks(s)=5.76190s+6.76190.K_s(s) = \frac{5.76190}{s + 6.76190}.

The loop GsKsG_s K_s gives the closed loop polynomial s2+6.76190s+5.76190=(s+1)(s+5.76190)s^2 + 6.76190 s + 5.76190 = (s + 1)(s + 5.76190), so the loop is internally stable. A frequency sweep of the 2×22 \times 2 map in the definition of γ\gamma gives a peak of 1.541831.54183, reached as ω→0\omega \to 0, so b=0.64858b = 0.64858. This is above 1/γ=0.642821/\gamma = 0.64282 and below εmax⁡\varepsilon_{\max}, as the theorem says.

For this plant the static gain Ks=1K_s = 1 already reaches εmax⁡\varepsilon_{\max}: the map is ss+1[11/s11/s]\frac{s}{s + 1}\begin{bmatrix} 1 & 1/s \\ 1 & 1/s \end{bmatrix}, which has rank one and largest singular value 2\sqrt 2 at every frequency. As γ→γmin⁡\gamma \to \gamma_{\min}, LL becomes singular and the central controller degenerates; this is why the procedure backs off.

For Gs=1/(s+1)G_s = 1/(s + 1) the equations give X=Z=2−1X = Z = \sqrt 2 - 1, γmin⁡=4−22=1.08239\gamma_{\min} = \sqrt{4 - 2\sqrt 2} = 1.08239 and εmax⁡=cos⁡(π/8)=0.92388\varepsilon_{\max} = \cos(\pi/8) = 0.92388. With the integral weight W1=(s+2)/sW_1 = (s + 2)/s the shaped plant (s+2)/(s(s+1))(s + 2)/(s(s + 1)) has γmin⁡=1.55146\gamma_{\min} = 1.55146, and the final controller K=W1KsK = W_1 K_s has three states, an integrator, and gives an internally stable loop with the plant.

Correctness

The theorem above is cited; its proof combines three facts (Glover and McFarlane 1989; Zhou, Doyle and Glover 1996, chapter 18). First, the small gain theorem reduces robust stabilization against [ΔN,ΔM][\Delta_N, \Delta_M] to the bound on γ(Gs,Ks)\gamma(G_s, K_s). Second, for a normalized coprime factorization this bound is a two-block problem that reduces to a Nehari problem, whose optimum is given by the Hankel norm of [N M][N\ M]. Third, the state-space formulas for the normalized factors turn that Hankel norm into the gramians of a realization with the matrices XX and ZZ, which gives γmin⁡2=1+ρ(XZ)\gamma_{\min}^2 = 1 + \rho(XZ).

The code is correct if it computes the stabilizing XX and ZZ, and then applies the formulas. The Riccati step is the one proved on the two-Riccati synthesis page. The proof file proofs/correctness.md checks the scalar cases in closed form, shows that the series connection gives K=W1KsW2K = W_1 K_s W_2, and explains why the sign change gives the same loop as the positive feedback formulas of the source. The tests check γmin⁡\gamma_{\min} against a separate Hankel norm computation from two Lyapunov equations, and they check that no stabilizing static or first-order controller from a random sample has a margin above εmax⁡\varepsilon_{\max}.

Proof: The loop shaping code computes gamma_min and a controller that meets the levelfull

Notation is that of the page. The theorem of Glover and McFarlane (1989) is cited, not proved here: for the stabilizing solutions X≥0X \ge 0 and Z≥0Z \ge 0 of the two Riccati equations, γmin⁡=1+ρ(XZ)\gamma_{\min} = \sqrt{1 + \rho(XZ)} is the smallest achievable value of γ(Gs,Ks)\gamma(G_s, K_s), and for every γ>γmin⁡\gamma > \gamma_{\min} the central controller of the source reaches γ(Gs,Ks)≤γ\gamma(G_s, K_s) \le \gamma with an internally stable loop. What we prove is that the code computes the objects in that theorem and wires the result correctly.

Claim 1: the Riccati step returns the stabilizing solutions

Line L3 returns the unique symmetric XX with ATX+XA−XBBTX+CTC=0A^T X + X A - X B B^T X + C^T C = 0 and A−BBTXA - B B^T X Hurwitz. Line L2 returns the unique symmetric ZZ with AZ+ZAT−ZCTCZ+BBT=0A Z + Z A^T - Z C^T C Z + B B^T = 0 and A−ZCTCA - Z C^T C Hurwitz.

Proof. The routine riccati(a, r, q) is the same as on the two-Riccati synthesis page, where Claims 3 and 4 of its proof show that it returns the stabilizing solution of aTX+Xa+XrX+q=0a^T X + X a + X r X + q = 0, or nothing. Line L3 calls it with a=Aa = A, r=−BBTr = -B B^T, q=CTCq = C^T C, which is the control equation, and the routine checks that A−BBTXA - B B^T X is Hurwitz. Line L2 calls it with a=ATa = A^T, r=−CTCr = -C^T C, q=BBTq = B B^T. Then aTZ+Za+ZrZ+q=AZ+ZAT−ZCTCZ+BBTa^T Z + Z a + Z r Z + q = A Z + Z A^T - Z C^T C Z + B B^T, and the routine checks that AT−CTCZA^T - C^T C Z is Hurwitz, which holds if and only if its transpose A−ZCTCA - Z C^T C is Hurwitz. Stabilizability of (A,B)(A, B) and detectability of (C,A)(C, A) give existence and X,Z≥0X, Z \ge 0 (the stabilizing Riccati solution theorem). □\square

Line L4 then evaluates the formula of the theorem. XZ=(XZ1/2)Z1/2XZ = (X Z^{1/2}) Z^{1/2} has the same eigenvalues as Z1/2XZ1/2≥0Z^{1/2} X Z^{1/2} \ge 0, so its eigenvalues are real and nonnegative and ρ(XZ)\rho(XZ) is its largest eigenvalue.

Claim 2: the sign change gives the same loop and the same margin

Let K+=(AK,BK,BTX,0)K_+ = (A_K, B_K, B^T X, 0) be the controller of the source for positive feedback u=K+yu = K_+ y. The code returns K=(AK,BK,−BTX,0)K = (A_K, B_K, -B^T X, 0) for u=−Kyu = -K y. The two loops are the same, and γ(Gs,K)\gamma(G_s, K) equals the robustness level of the source for K+K_+.

Proof. The transfer matrix of KK is −K+-K_+, so −Ky=K+y-K y = K_+ y and the two loops have the same equations. The source states the level for K+K_+ as ∥[K+;I](I−GsK+)−1M−1∥∞\| [K_+; I](I - G_s K_+)^{-1} M^{-1} \|_\infty. Put K+=−KK_+ = -K:

[−KI](I+GsK)−1M−1=[−I00I][KI](I+GsK)−1M−1.\begin{bmatrix} -K \\ I \end{bmatrix} (I + G_s K)^{-1} M^{-1} = \begin{bmatrix} -I & 0 \\ 0 & I \end{bmatrix} \begin{bmatrix} K \\ I \end{bmatrix} (I + G_s K)^{-1} M^{-1}.

The left factor is a constant orthogonal matrix, so it does not change the largest singular value. Next, M−1[NM]=[GsI]M^{-1} \begin{bmatrix} N & M \end{bmatrix} = \begin{bmatrix} G_s & I \end{bmatrix}, and the normalized factors satisfy [NM][NM]∗=I\begin{bmatrix} N & M \end{bmatrix} \begin{bmatrix} N & M \end{bmatrix}^* = I on the imaginary axis. For any matrix TT and any VV with VV∗=IV V^* = I, (TV)(TV)∗=TT∗(T V)(T V)^* = T T^*, so TVT V and TT have the same largest singular value. With T=[K;I](I+GsK)−1M−1T = [K; I](I + G_s K)^{-1} M^{-1} and V=[N M]V = [N\ M], the norm in the source equals the norm of [K;I](I+GsK)−1[Gs I][K; I](I + G_s K)^{-1}[G_s\ I] at every frequency. Swapping the two block columns does not change the singular values, which gives γ(Gs,K)\gamma(G_s, K) as defined on the page. □\square

Claim 3: the final loop has the same closed loop matrix as the shaped loop

Let GsG_s = series(series(W1, G), W2) and KK = series(series(W2, Ks), W1). Then the closed loop state matrix of GG with u=−Kyu = -K y is equal, up to a permutation of the states, to the closed loop state matrix of GsG_s with us=−Ksysu_s = -K_s y_s. So the first loop is internally stable if and only if the second is.

Proof. series(s1, s2) builds the state (x1,x2)(x_1, x_2) with x˙1=A1x1+B1v\dot x_1 = A_1 x_1 + B_1 v, r=C1x1+D1vr = C_1 x_1 + D_1 v, x˙2=A2x2+B2r\dot x_2 = A_2 x_2 + B_2 r and output C2x2+D2rC_2 x_2 + D_2 r. This is the realization of s2s1s_2 s_1 whose state is the union of the two states, and the empty-state cases in the code are the same formulas with one part removed. So GsG_s is the chain W1→G→W2W_1 \to G \to W_2 and KK is the chain W2→Ks→W1W_2 \to K_s \to W_1, each with the states of its parts. Both closed loops are the ring W1→G→W2→Ks→(−1)→W1W_1 \to G \to W_2 \to K_s \to (-1) \to W_1 with the same four realizations. The closed loop equations list the same state equations in a different order, so the closed loop matrices are equal up to a permutation of the states. □\square

The level γ\gamma is a property of the shaped loop (Gs,Ks)(G_s, K_s), not of (G,K)(G, K). The page and the tests state it only for the shaped loop.

Claim 4: closed forms for first-order shaped plants

For Gs=1/(s−a)G_s = 1/(s - a), that is A=aA = a and B=C=1B = C = 1, X=Z=a+a2+1X = Z = a + \sqrt{a^2 + 1} and γmin⁡2=1+(a+a2+1)2\gamma_{\min}^2 = 1 + (a + \sqrt{a^2 + 1})^2. For a=0a = 0, γmin⁡=2\gamma_{\min} = \sqrt 2. For a=−1a = -1, γmin⁡=4−22\gamma_{\min} = \sqrt{4 - 2\sqrt 2} and 1/γmin⁡=cos⁡(π/8)1/\gamma_{\min} = \cos(\pi/8).

Proof. Both equations become −X2+2aX+1=0-X^2 + 2 a X + 1 = 0. The roots are a±a2+1a \pm \sqrt{a^2 + 1}, and a−X=−a2+1<0a - X = -\sqrt{a^2 + 1} < 0 only for the plus sign, so that is the stabilizing root. Then ρ(XZ)=X2\rho(XZ) = X^2. For a=0a = 0, X=1X = 1. For a=−1a = -1, X=2−1X = \sqrt 2 - 1 and X2=3−22X^2 = 3 - 2\sqrt 2, so γmin⁡2=4−22\gamma_{\min}^2 = 4 - 2\sqrt 2. Finally cos⁡2(π/8)=(1+cos⁡(π/4))/2=(2+2)/4\cos^2(\pi/8) = (1 + \cos(\pi/4))/2 = (2 + \sqrt 2)/4 and (4−22)(2+2)=8−4=4(4 - 2\sqrt 2)(2 + \sqrt 2) = 8 - 4 = 4, so γmin⁡−2=cos⁡2(π/8)\gamma_{\min}^{-2} = \cos^2(\pi/8). □\square

Claim 5: for 1/s the unity gain is optimal

For Gs=1/sG_s = 1/s and Ks=1K_s = 1, γ(Gs,Ks)=2=γmin⁡\gamma(G_s, K_s) = \sqrt 2 = \gamma_{\min}.

Proof. The loop 1/s1/s with unity negative feedback has the pole −1-1, so it is internally stable. At s=jωs = j\omega with ω≠0\omega \ne 0, (1+1/s)−1=s/(s+1)(1 + 1/s)^{-1} = s/(s + 1) and the map is ss+1[11][11/s]\frac{s}{s + 1} \begin{bmatrix} 1 \\ 1 \end{bmatrix} \begin{bmatrix} 1 & 1/s \end{bmatrix}. This has rank one, so its largest singular value is ∣ss+1∣21+1/ω2=2\left| \frac{s}{s + 1} \right| \sqrt 2 \sqrt{1 + 1/\omega^2} = \sqrt 2 for every ω\omega. By Claim 4 this equals γmin⁡\gamma_{\min}. □\square

The test checks this value with the code's frequency sweep, which tests the sweep and the definition of bb against a value known in closed form.

What the tests check

  • The values of Claim 4, and the Riccati residuals, positive semidefiniteness and Hurwitz checks of Claim 1 on four plants, one of them open loop unstable and two with a pole at 0.
  • γmin⁡\gamma_{\min} against an independent route: 1−∥[N M]∥H2=γmin⁡−21 - \|[N\ M]\|_H^2 = \gamma_{\min}^{-2}, with the Hankel norm from the controllability and observability gramians of the realization (A−ZCTC,[B,−ZCT],C,[0,I])(A - Z C^T C, [B, -Z C^T], C, [0, I]), each from a Kronecker form Lyapunov solve.
  • For each plant and γ=1.05,1.1,1.5\gamma = 1.05, 1.1, 1.5 times γmin⁡\gamma_{\min}: the closed loop is Hurwitz and the swept margin is between 1/γ1/\gamma and εmax⁡\varepsilon_{\max}.
  • Brute force: random static and first-order controllers for two plants. Every one that stabilizes has a swept margin at most εmax⁡\varepsilon_{\max}. The sweep uses a coarse grid, which can only miss the peak and so overstate the margin; the check is therefore on the safe side.
  • A full design with W1=(s+2)/sW_1 = (s + 2)/s: the final controller contains the integrator and the loop with the plant is Hurwitz.

Complexity

Let nn be the number of states of the shaped plant, which is the plant order plus the weight orders. The method needs two Riccati equations of size nn and one eigenvalue problem for XZXZ. With cc Newton steps per matrix sign function, each step O(n3)O(n^3), the time is O(cn3+n2(m+p))O(c n^3 + n^2(m + p)) and the extra space is O(n2+n(m+p))O(n^2 + n(m + p)). There is no bisection on γ\gamma, unlike general H-infinity synthesis, because γmin⁡\gamma_{\min} has a closed form. The final controller has nn states plus the states of W1W_1 and W2W_2, before any reduction.

Properties

  • γmin⁡≥1\gamma_{\min} \ge 1 always, so εmax⁡≤1\varepsilon_{\max} \le 1.
  • The margin b(G,K)b(G, K) is the same quantity that the nu-gap metric theory uses: if b(G,K)>βb(G, K) > \beta, then KK stabilizes every plant whose ν\nu-gap from GG is at most β\beta (Vinnicombe 1993).
  • The robust step changes the loop only where it must: McFarlane and Glover (1992) give bounds, in terms of ε\varepsilon, on the change of the loop gain at frequencies where the shaped loop gain is large or small. The bounds are theorems; how close the final loop stays to the shaped loop is a measurement on each design.
  • γ(Gs,Ks)\gamma(G_s, K_s) bounds the four closed loop maps (I+GsKs)−1(I + G_s K_s)^{-1}, (I+GsKs)−1Gs(I + G_s K_s)^{-1} G_s, Ks(I+GsKs)−1K_s (I + G_s K_s)^{-1} and Ks(I+GsKs)−1GsK_s (I + G_s K_s)^{-1} G_s at once, because each one is a block of the 2×22 \times 2 block map in the definition. So γmin⁡\gamma_{\min} also limits the peaks of the sensitivity and complementary sensitivity of the shaped loop.
  • Like all H-infinity central controllers, KsK_s is observer based and has the order of the shaped plant.

Variants and improvements

  • Nonzero D. If the shaped plant has D≠0D \ne 0, the Riccati equations get extra terms with R=I+DTDR = I + D^T D and S=I+DDTS = I + D D^T (Skogestad and Postlethwaite 2005, section 9.4). This code needs D=0D = 0.
  • Observer form. The controller can be written in observer form, which makes gain scheduling and anti-windup easier (Skogestad and Postlethwaite 2005, section 9.4).
  • Two degrees of freedom. A reference model can be added to the robust step to improve tracking, as in Skogestad and Postlethwaite (2005, section 9.4).
  • Discrete time. The same procedure works with discrete Riccati equations.
  • Weight choice by optimization. Some methods tune the weights to meet given margins; the second step stays the same.

When to use it

Use it for multivariable plants when you can say what the loop gain should look like, and you want a robust controller without building a weighted generalized plant as in mixed sensitivity design. It is a good first design because it needs only the two weights and one number, γmin⁡\gamma_{\min}, tells you if they are reasonable. It is less direct when the specifications are about particular closed loop maps, or when there is structured uncertainty; then use mixed sensitivity or D-K iteration.

Pitfalls

  • Bad weights. If γmin⁡\gamma_{\min} is large, the robust step changes the loop a lot near crossover and the final loop is not the one you shaped. Fix the weights; do not accept the result.
  • Unscaled plants. The robustness measure mixes all inputs and outputs, so scale the plant to sensible units before you shape it.
  • Sign conventions. Formulas from books on this method are often for positive feedback. A controller with the wrong sign makes the loop unstable even though the numbers look right.
  • Integrators. A pure integrator in W1W_1 gives a shaped plant with a pole at 0. The Riccati equations still work, but a frequency sweep at ω=0\omega = 0 fails; sweep over positive frequencies.
  • Controller order. The controller has as many states as the shaped plant. Use model order reduction and check the margin again after the reduction.

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_loop_shaping.py 189 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/h-infinity-loop-shaping/. The authors are listed in prov/5JS87D.jsonl.

"""H-infinity loop shaping (McFarlane and Glover 1992).

A system is a tuple (A, B, C, D) of lists of rows. The shaped plant
Gs = W2 G W1 must have D = 0 here, as in the simplest form of the
formulas. The robust stabilization step follows Glover and McFarlane
(1989) in the form of Skogestad and Postlethwaite (2005, section 9.4):

    GCARE  A Z + Z A^T - Z C^T C Z + B B^T = 0
    GFARE  A^T X + X A - X B B^T X + C^T C = 0
    gamma_min = sqrt(1 + rho(X Z)),  eps_max = 1 / gamma_min

The central controller of that book is for positive feedback, u = Ks y.
The function controller() returns it in the negative feedback form of
this site, u = -C y (so C = -Ks), with the loop L = G C.
"""

import math

from ctlmat import (
    add, block, charpoly, det, eye, inv, mul, norm2, polyroots, scale, solve,
    sub, transpose, zeros,
)

__all__ = [
    "riccati", "is_hurwitz", "gamma_min", "controller", "series",
    "feedback_a", "margin_at", "stability_margin", "loop_shaping_design",
]


def _flo(a):
    return [[float(v) for v in row] for row in a]


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


def _sign(h, tol=1e-13, maxiter=100):
    n = len(h)
    z = _flo(h)
    for _ in range(maxiter):
        d = abs(det(z))
        if not d > 0.0 or not math.isfinite(d):
            return None
        mu = d ** (-1.0 / n)
        zi = inv(z)
        znew = [[0.5 * (mu * z[i][j] + zi[i][j] / mu) for j in range(n)] for i in range(n)]
        diff = _big(sub(znew, z))
        z = znew
        if diff <= tol * max(1.0, _big(z)):
            break
    if _big(sub(mul(z, z), eye(n))) > 1e-8:
        return None
    return z


def is_hurwitz(m, tol=1e-9):
    """Return True if every eigenvalue of m has real part below -tol."""
    return max(r.real for r in polyroots(charpoly(_flo(m)))) < -tol


def riccati(a, r, q):
    """Stabilizing X of A^T X + X A + X R X + Q = 0 (A + R X Hurwitz), or None.

    The stable invariant subspace of [[A, R], [-Q, -A^T]] is the kernel of
    sign(H) + I, and it is the range of [I; X].
    """
    n = len(a)
    a, r, q = _flo(a), _flo(r), _flo(q)
    h = block([[a, r], [scale(-1.0, q), scale(-1.0, transpose(a))]])
    w = _sign(h)
    if w is None:
        return None
    wp = add(w, eye(2 * n))
    lhs = [row[n:] for row in wp]
    rhs = [[-v for v in row[:n]] for row in wp]
    lt = transpose(lhs)
    try:
        x = solve(mul(lt, lhs), mul(lt, rhs))
    except ValueError:
        return None
    x = [[0.5 * (x[i][j] + x[j][i]) for j in range(n)] for i in range(n)]
    res = add(add(mul(transpose(a), x), mul(x, a)), add(mul(mul(x, r), x), q))
    size = 1.0 + _big(mul(transpose(a), x)) + _big(mul(mul(x, r), x)) + _big(q)
    if _big(res) > 1e-8 * size or not is_hurwitz(add(a, mul(r, x))):
        return None
    return x


def _rho(m):
    return max(abs(v) for v in polyroots(charpoly(_flo(m))))


def gamma_min(gs):
    """Return (gamma_min, X, Z) for the shaped plant gs = (A, B, C, 0)."""
    a, b, c, d = (_flo(m) for m in gs)
    if _big(d) != 0.0:
        raise ValueError("this implementation needs D = 0")
    z = riccati(transpose(a), scale(-1.0, mul(transpose(c), c)), mul(b, transpose(b)))  # @line L2
    x = riccati(a, scale(-1.0, mul(b, transpose(b))), mul(transpose(c), c))  # @line L3
    if x is None or z is None:
        raise ValueError("the shaped plant must be stabilizable and detectable")
    return math.sqrt(1.0 + _rho(mul(x, z))), x, z  # @line L4


def controller(gs, gamma):
    """Return the central controller (A_K, B_K, C_K, D_K) for u = -C y.

    gamma must be larger than gamma_min. Then the loop of gs and C is
    internally stable and ||[C; I] (I + gs C)^-1 [I, gs]||_inf <= gamma.
    """
    gmin, x, z = gamma_min(gs)
    if not gamma > gmin:
        raise ValueError("gamma must exceed gamma_min")
    a, b, c, _ = (_flo(m) for m in gs)
    n = len(a)
    g2 = gamma * gamma
    l = add(scale(1.0 - g2, eye(n)), mul(x, z))  # @line L6
    lti = inv(transpose(l))
    bk = scale(g2, mul(mul(lti, z), transpose(c)))  # @line L7
    ak = add(sub(a, mul(mul(b, transpose(b)), x)), mul(bk, c))
    ck = mul(transpose(b), x)
    # Positive feedback Ks = (ak, bk, ck, 0); negative feedback C = -Ks.
    return ak, bk, scale(-1.0, ck), zeros(len(ck), len(c))  # @line L8


def series(s1, s2):
    """Return s2 s1: the input goes through s1 first, then through s2."""
    a1, b1, c1, d1 = (_flo(m) for m in s1)
    a2, b2, c2, d2 = (_flo(m) for m in s2)
    if not a1:
        a = a2
        b = mul(b2, d1)
        c = c2
        return a, b, c, mul(d2, d1)
    if not a2:
        return a1, b1, mul(d2, c1), mul(d2, d1)
    a = block([[a1, zeros(len(a1), len(a2))], [mul(b2, c1), a2]])
    b = block([[b1], [mul(b2, d1)]])
    c = block([[mul(d2, c1), c2]])
    return a, b, c, mul(d2, d1)


def feedback_a(g, k):
    """State matrix of the negative feedback loop u = -K y around G (D_G = 0)."""
    ag, bg, cg, dg = (_flo(m) for m in g)
    ak, bk, ck, dk = (_flo(m) for m in k)
    if _big(dg) != 0.0:
        raise ValueError("the plant must be strictly proper")
    return block([[sub(ag, mul(mul(bg, dk), cg)), scale(-1.0, mul(bg, ck))],
                  [mul(bk, cg), ak]]) if ak else sub(ag, mul(mul(bg, dk), cg))


def _resp(sys, s):
    a, b, c, d = sys
    n = len(a)
    if n == 0:
        return [[complex(v) for v in row] for row in d]
    m = [[(s if i == j else 0.0) - a[i][j] for j in range(n)] for i in range(n)]
    return add(mul(c, solve(m, [[complex(v) for v in row] for row in b])), d)


def margin_at(g, k, w):
    """Largest singular value of [K; I] (I + G K)^-1 [I, G] at s = j w."""
    gs = _resp(tuple(_flo(m) for m in g), 1j * w)
    ks = _resp(tuple(_flo(m) for m in k), 1j * w)
    p = len(gs)
    sinv = inv(add(eye(p), mul(gs, ks)))
    left = block([[ks], [eye(p)]])
    right = block([[eye(p), gs]])
    return norm2(mul(mul(left, sinv), right))


def stability_margin(g, k, freqs):
    """b(G, K) = 1 / max over freqs of margin_at; the loop must be stable."""
    return 1.0 / max(margin_at(g, k, w) for w in freqs)


def loop_shaping_design(g, w1, w2, factor=1.1):
    """McFarlane-Glover design. Return (gamma_min, gamma, K) with K = W1 Ks W2."""
    gs = series(series(w1, g), w2)  # @line L1
    gmin = gamma_min(gs)[0]
    gamma = factor * gmin  # @line L5
    ks = controller(gs, gamma)
    k = series(series(w2, ks), w1)  # @line L9
    return gmin, gamma, k
test_h_infinity_loop_shaping.py 143 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/h-infinity-loop-shaping/. The authors are listed in prov/5JS87D.jsonl.

import math
import random

import ctlmat as cm
from h_infinity_loop_shaping import (
    controller,
    feedback_a,
    gamma_min,
    is_hurwitz,
    loop_shaping_design,
    series,
    stability_margin,
)

INTEGRATOR = ([[0]], [[1]], [[1]], [[0]])          # 1 / s
LAG = ([[-1]], [[1]], [[1]], [[0]])                # 1 / (s + 1)
MOTOR = ([[0, 1], [0, -1]], [[0], [1]], [[2, 0]], [[0]])   # 2 / (s (s + 1))
UNSTABLE = ([[1, 1], [0, -2]], [[0], [1]], [[1, 0]], [[0]])  # 1 / ((s - 1) (s + 2))
PLANTS = (INTEGRATOR, LAG, MOTOR, UNSTABLE)

FREQS = [10 ** (e / 40) for e in range(-160, 161)]


def static(k):
    return ([], [], [], [[k]])


def lyap(a, q):
    # Solve A P + P A^T + Q = 0 by the Kronecker form (I x A + A x I) vec P = -vec Q.
    n = len(a)
    big = cm.add(cm.kron(cm.eye(n), a), cm.kron(a, cm.eye(n)))
    return cm.unvec(cm.solve(big, [-v for v in cm.vec(q)]), n)


def test_ctlmat_self_test():
    assert cm._self_test()


def test_integrator_values():
    g, x, z = gamma_min(INTEGRATOR)
    assert abs(x[0][0] - 1) < 1e-12 and abs(z[0][0] - 1) < 1e-12
    assert abs(g - math.sqrt(2)) < 1e-12


def test_first_order_lag_values():
    g, x, z = gamma_min(LAG)
    r = math.sqrt(2) - 1
    assert abs(x[0][0] - r) < 1e-12 and abs(z[0][0] - r) < 1e-12
    assert abs(g - math.sqrt(4 - 2 * math.sqrt(2))) < 1e-12
    assert abs(1 / g - math.cos(math.pi / 8)) < 1e-12


def test_riccati_residuals():
    for gs in PLANTS:
        a, b, c, _ = (cm.scale(1.0, m) for m in gs)
        _, x, z = gamma_min(gs)
        bb = cm.mul(b, cm.transpose(b))
        cc = cm.mul(cm.transpose(c), c)
        rx = cm.add(cm.sub(cm.add(cm.mul(cm.transpose(a), x), cm.mul(x, a)), cm.mul(cm.mul(x, bb), x)), cc)
        rz = cm.add(cm.sub(cm.add(cm.mul(a, z), cm.mul(z, cm.transpose(a))), cm.mul(cm.mul(z, cc), z)), bb)
        assert max(abs(v) for row in rx + rz for v in row) < 1e-9
        assert cm.is_pos_def(x, -1e-12) and cm.is_pos_def(z, -1e-12)
        assert is_hurwitz(cm.sub(a, cm.mul(bb, x)))
        assert is_hurwitz(cm.sub(a, cm.mul(z, cc)))


def test_gamma_min_matches_the_hankel_norm():
    # Reference: eps_max^2 = 1 - ||[N M]||_H^2 for the normalized left
    # coprime factors [N M] = (A - Z C^T C, [B, -Z C^T], C, [0, I]),
    # with the Hankel norm from two Lyapunov equations.
    for gs in PLANTS:
        a, b, c, _ = (cm.scale(1.0, m) for m in gs)
        g, _, z = gamma_min(gs)
        ah = cm.sub(a, cm.mul(cm.mul(z, cm.transpose(c)), c))
        bh = cm.block([[b, cm.scale(-1.0, cm.mul(z, cm.transpose(c)))]])
        p = lyap(ah, cm.mul(bh, cm.transpose(bh)))
        q = lyap(cm.transpose(ah), cm.mul(cm.transpose(c), c))
        hankel2 = max(abs(v) for v in cm.polyroots(cm.charpoly(cm.mul(p, q))))
        assert abs((1 - hankel2) - 1 / g ** 2) < 1e-9


def test_central_controller_reaches_the_level():
    for gs in PLANTS:
        g0 = gamma_min(gs)[0]
        for f in (1.05, 1.1, 1.5):
            k = controller(gs, f * g0)
            assert is_hurwitz(feedback_a(gs, k))
            b = stability_margin(gs, k, FREQS)
            assert b >= 1 / (f * g0) - 1e-9
            assert b <= 1 / g0 + 1e-9


def test_static_gain_for_the_integrator_is_optimal():
    # For G = 1/s and C = 1, b(G, C) = 1/sqrt(2) = eps_max.
    b = stability_margin(INTEGRATOR, static(1.0), FREQS)
    assert abs(b - 1 / math.sqrt(2)) < 1e-9


def test_no_random_controller_beats_eps_max():
    # A coarse grid can only miss the peak, which makes the computed
    # margin larger, so the check below is on the safe side.
    coarse = [10 ** (e / 10) for e in range(-30, 31)] + [0.0]
    rng = random.Random(11)
    for gs in (LAG, UNSTABLE):
        eps = 1 / gamma_min(gs)[0]
        found = 0
        for _ in range(60):
            if rng.random() < 0.5:
                k = static(rng.uniform(-1, 6))
            else:
                pole = rng.uniform(0.1, 10)
                k = ([[-pole]], [[1.0]], [[rng.uniform(-5, 20)]], [[rng.uniform(-1, 5)]])
            if not is_hurwitz(feedback_a(gs, k)):
                continue
            found += 1
            assert stability_margin(gs, k, coarse) <= eps + 1e-9
        assert found > 15


def test_series_connection():
    w1 = ([[0]], [[1]], [[2]], [[1]])      # (s + 2) / s
    gs = series(w1, LAG)                    # (s + 2) / (s (s + 1))
    a, b, c, d = gs
    s = 0.7j
    m = [[s - a[i][j] if i == j else -a[i][j] for j in range(2)] for i in range(2)]
    val = cm.mul(c, cm.solve(m, [[complex(v) for v in row] for row in b]))[0][0] + d[0][0]
    assert abs(val - (s + 2) / (s * (s + 1))) < 1e-12


def test_full_design_with_an_integral_weight():
    w1 = ([[0]], [[1]], [[2]], [[1]])      # W1 = (s + 2) / s
    w2 = static(1.0)
    gmin, gamma, k = loop_shaping_design(LAG, w1, w2, 1.1)
    assert abs(gamma - 1.1 * gmin) < 1e-12
    assert is_hurwitz(feedback_a(LAG, k))
    # The weight puts an integrator in K: K has an eigenvalue at 0.
    assert min(abs(r) for r in cm.polyroots(cm.charpoly(k[0]))) < 1e-9
    gs = series(w1, LAG)
    ks = controller(gs, gamma)
    assert stability_margin(gs, ks, FREQS) >= 1 / gamma - 1e-9

History

Glover and McFarlane (1989) solved the robust stabilization problem for normalized coprime factor perturbations and found that the optimal level has a closed form, unlike general H-infinity problems. McFarlane and Glover (1992) built the loop shaping design procedure on it, with weights that carry the performance goals and a robust step that needs no tuning. Vinnicombe (1993) linked the stability margin b(G,K)b(G, K) to the ν\nu-gap metric, which gave the margin a clear meaning in terms of plant uncertainty.

References

  1. Keith Glover and Duncan McFarlane, Robust stabilization of normalized coprime factor plant descriptions with H-infinity-bounded uncertainty, IEEE Transactions on Automatic Control 34(8), 821-830, 1989, the closed form of the largest stability margin and the controllers that reach it
  2. Duncan McFarlane and Keith Glover, A loop-shaping design procedure using H-infinity synthesis, IEEE Transactions on Automatic Control 37(6), 759-769, 1992, the design procedure with pre and post weights and the bounds on how much the robust controller changes the shaped loop
  3. Sigurd Skogestad and Ian Postlethwaite, Multivariable Feedback Control, Analysis and Design, second edition, Wiley, 2005, Section 9.4, H-infinity loop-shaping design (the two Riccati equations, gamma_min and the central controller for positive feedback)
  4. Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, Chapter 18, H-infinity Loop Shaping
  5. Glenn Vinnicombe, Frequency domain uncertainty and the graph topology, IEEE Transactions on Automatic Control 38(9), 1371-1383, 1993, the nu-gap metric and the robust stability result in terms of b(G, K)

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.total
  • 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