Algorithm Search⌘K

Algorithmadvanced

Two-Riccati H-infinity synthesis

Also called DGKF solution, Doyle-Glover-Khargonekar-Francis solution.

Solves the suboptimal H-infinity problem by two Riccati equations and a coupling condition on their spectral radius.

Time
O(k (c n^3 + n^2 (m + p))) totalO(c n^3 + n^2 (m + p)) per-gamma
Space
O(n^2 + n (m + p)) extra
Where
c = the number of Newton steps of one matrix sign function; k = the number of bisection steps on gamma; m = the number of inputs w and u together; n = the number of plant states; p = the number of outputs z and y together
Properties
deterministicnot exactiterativeiterative
Origin
John C. Doyle, Keith Glover, Pramod P. Khargonekar, Bruce A. Francis, 1989

Two-Riccati H-infinity synthesis solves the H-infinity control problem for a generalized plant in state-space form. For a level γ>0\gamma > 0 it either builds an internally stabilizing output feedback controller KK whose closed loop map from the disturbance ww to the error zz has H-infinity norm below γ\gamma, or it proves that no controller of any order can do this. The test needs two continuous algebraic Riccati equations of the same size nn as the plant: a control equation for XX and a filter equation for YY. A controller exists if and only if both have stabilizing solutions X≥0X \ge 0 and Y≥0Y \ge 0 and the spectral radius of XYXY is below γ2\gamma^2. Doyle, Glover, Khargonekar and Francis (1989) proved this, and the method is often called the DGKF solution. A bisection on γ\gamma then finds the optimal level γopt\gamma_{\rm opt} to any wanted accuracy. The controller has the structure of an observer with state feedback, as in LQG control, and it tends to the LQG controller as γ→∞\gamma \to \infty.

In plain words

You have a plant, a list of disturbances ww that act on it, and a list of errors zz that you want small. You fix a number γ\gamma and ask: is there a controller that keeps the energy of zz below γ\gamma times the energy of ww, for every disturbance? The answer comes from two Riccati equations, one for state feedback and one for state estimation, as in LQG. If both have the right kind of solution, and the two solutions are not too large together, the answer is yes, and a formula gives the controller. If not, no controller exists, of any order. Try smaller and smaller γ\gamma by bisection to find the best level.

The problem

The generalized plant has state x∈Rnx \in \mathbb{R}^n, disturbance ww, control input uu, error zz and measurement yy:

x˙=Ax+B1w+B2u,z=C1x+D12u,y=C2x+D21w.\dot x = A x + B_1 w + B_2 u, \qquad z = C_1 x + D_{12} u, \qquad y = C_2 x + D_{21} w.

The controller is a finite-dimensional linear system with input yy and output uu, and the loop is closed by u=Kyu = K y with no sign change. This is the lower linear fractional transformation Tzw=Fl(P,K)T_{zw} = \mathcal{F}_l(P, K). A classical loop with e=r−ye = r - y and u=Ceu = C e has K=−CK = -C. The page uses the normalized form of the original paper. The assumptions are:

  1. (A,B1)(A, B_1) is stabilizable and (C1,A)(C_1, A) is detectable.
  2. (A,B2)(A, B_2) is stabilizable and (C2,A)(C_2, A) is detectable.
  3. D12T[C1D12]=[0I]D_{12}^T \begin{bmatrix} C_1 & D_{12} \end{bmatrix} = \begin{bmatrix} 0 & I \end{bmatrix}: the control input enters every direction of zz that it can reach, with unit weight, and with no cross term with the state.
  4. [B1D21]D21T=[0I]\begin{bmatrix} B_1 \\ D_{21} \end{bmatrix} D_{21}^T = \begin{bmatrix} 0 \\ I \end{bmatrix}: every measurement has unit noise, independent of the process disturbance.
  5. D11=0D_{11} = 0 and D22=0D_{22} = 0.

Assumptions 3 and 4 imply that D12D_{12} has full column rank and D21D_{21} has full row rank. Together with assumption 1 they also imply the rank conditions on the imaginary axis: [A−jωIB2C1D12]\begin{bmatrix} A - j\omega I & B_2 \\ C_1 & D_{12} \end{bmatrix} has full column rank and [A−jωIB1C2D21]\begin{bmatrix} A - j\omega I & B_1 \\ C_2 & D_{21} \end{bmatrix} has full row rank for every real ω\omega. A plant with general DD matrices that satisfy the rank conditions is brought to this form by scaling and loop shifting (Zhou, Doyle and Glover 1996, chapter 17).

For γ>0\gamma > 0 define the two Hamiltonian matrices

H∞=[Aγ−2B1B1T−B2B2T−C1TC1−AT],J∞=[ATγ−2C1TC1−C2TC2−B1B1T−A].H_\infty = \begin{bmatrix} A & \gamma^{-2} B_1 B_1^T - B_2 B_2^T \\ -C_1^T C_1 & -A^T \end{bmatrix}, \qquad J_\infty = \begin{bmatrix} A^T & \gamma^{-2} C_1^T C_1 - C_2^T C_2 \\ -B_1 B_1^T & -A \end{bmatrix}.

X=Ric(H∞)X = \mathrm{Ric}(H_\infty) means: H∞H_\infty has no eigenvalue on the imaginary axis, its stable invariant subspace is the range of [IX]\begin{bmatrix} I \\ X \end{bmatrix}, and then XX is symmetric, solves ATX+XA+X(γ−2B1B1T−B2B2T)X+C1TC1=0A^T X + X A + X(\gamma^{-2} B_1 B_1^T - B_2 B_2^T)X + C_1^T C_1 = 0, and makes A+(γ−2B1B1T−B2B2T)XA + (\gamma^{-2} B_1 B_1^T - B_2 B_2^T) X Hurwitz. The same holds for Y=Ric(J∞)Y = \mathrm{Ric}(J_\infty) with the dual equation.

Theorem (Doyle, Glover, Khargonekar and Francis 1989; Zhou, Doyle and Glover 1996, chapter 16). Under assumptions 1 to 5, an internally stabilizing controller with ∥Tzw∥∞<γ\|T_{zw}\|_\infty < \gamma exists if and only if

  1. X=Ric(H∞)X = \mathrm{Ric}(H_\infty) exists and X≥0X \ge 0,
  2. Y=Ric(J∞)Y = \mathrm{Ric}(J_\infty) exists and Y≥0Y \ge 0,
  3. ρ(XY)<γ2\rho(XY) < \gamma^2, where ρ\rho is the spectral radius.

When they hold, one such controller is the central controller

x^˙=A^x^−ZLy,u=Fx^,\dot{\hat x} = \hat A \hat x - Z L y, \qquad u = F \hat x,

with F=−B2TXF = -B_2^T X, L=−YC2TL = -Y C_2^T, Z=(I−γ−2YX)−1Z = (I - \gamma^{-2} Y X)^{-1} and A^=A+γ−2B1B1TX+B2F+ZLC2\hat A = A + \gamma^{-2} B_1 B_1^T X + B_2 F + Z L C_2. It has nn states.

The algorithm

  1. DGKF-SYNTHESIS(A, B1, B2, C1, C2, tol, delta)
  2. 1lo ← 0, hi ← 1
  3. 2while not FEASIBLE(hi) do lo ← hi, hi ← 2 hi
  4. 3while hi - lo > tol · hi do
  5. 4g ← (lo + hi) / 2
  6. 5if FEASIBLE(g) then hi ← g else lo ← g
  7. 6g ← (1 + delta) · hi ▷ back off from the optimum
  8. 7(X, Y) ← the solutions found by FEASIBLE(g)
  9. 8F ← -B2^T X, L ← -Y C2^T, Z ← (I - g^-2 Y X)^-1
  10. 9Â ← A + g^-2 B1 B1^T X + B2 F + Z L C2
  11. 10return hi, controller (Â, -Z L, F, 0)
  12. FEASIBLE(g)
  13. 11X ← Ric(H∞(g)); fail if it does not exist or X is not ≥ 0
  14. 12Y ← Ric(J∞(g)); fail if it does not exist or Y is not ≥ 0
  15. 13return ρ(X Y) < g^2

Computing Ric. The implementation forms the 2n×2n2n \times 2n Hamiltonian HH and computes its matrix sign function W=sign(H)W = \mathrm{sign}(H) by the scaled Newton iteration W←12(μW+μ−1W−1)W \leftarrow \tfrac12(\mu W + \mu^{-1} W^{-1}) with μ=∣det⁡W∣−1/(2n)\mu = |\det W|^{-1/(2n)}. The iteration converges when HH has no eigenvalue on the imaginary axis. The stable invariant subspace of HH is the kernel of W+IW + I. Split W+IW + I into n×nn \times n blocks. Then (W+I)[IX]=0(W + I)\begin{bmatrix} I \\ X \end{bmatrix} = 0 gives the overdetermined linear system

[W12W22+I]X=−[W11+IW21],\begin{bmatrix} W_{12} \\ W_{22} + I \end{bmatrix} X = -\begin{bmatrix} W_{11} + I \\ W_{21} \end{bmatrix},

which the code solves by the normal equations. The code then makes XX symmetric, and it accepts XX only if the Riccati residual is below 10−710^{-7} times the size of the terms and A+RXA + R X is Hurwitz. These checks catch a stable subspace that is not the range of some [IX]\begin{bmatrix} I \\ X \end{bmatrix}. A production code uses the ordered Schur decomposition of HH instead, as in the Schur method; the sign function keeps the code short.

Example

Take the scalar plant x˙=x+w1+u\dot x = x + w_1 + u with errors z=(x,u)z = (x, u) and measurement y=x+w2y = x + w_2. So A=1A = 1, B1=[1,0]B_1 = [1, 0], B2=1B_2 = 1, C1=[1;0]C_1 = [1; 0], D12=[0;1]D_{12} = [0; 1], C2=1C_2 = 1 and D21=[0,1]D_{21} = [0, 1]. All five assumptions hold. With c=1−γ−2c = 1 - \gamma^{-2} the control equation is −cX2+2X+1=0-c X^2 + 2X + 1 = 0, and the filter equation is the same, so Y=XY = X. For c>0c > 0 the stabilizing root is X=(1+1+c)/cX = (1 + \sqrt{1 + c})/c, and condition 3 is X2<γ2X^2 < \gamma^2.

γ\gamma X=YX = Y ρ(XY)\rho(XY) γ2\gamma^2 feasible
2.5 2.80532 7.86980 6.25 no
2.7 2.74082 7.51212 7.29 no
2.75 2.72730 7.43815 7.5625 yes
3 2.67116 7.13512 9 yes

Conditions 1 and 2 hold for every γ>1\gamma > 1 here; only the coupling condition fails for small γ\gamma. Set X=γX = \gamma and solve: cγ−1=1+cc\gamma - 1 = \sqrt{1 + c} gives cγ2−2γ=1c\gamma^2 - 2\gamma = 1, so γ2−2γ−2=0\gamma^2 - 2\gamma - 2 = 0 and γopt=1+3=2.73205\gamma_{\rm opt} = 1 + \sqrt 3 = 2.73205. In general γopt=a+a2+2\gamma_{\rm opt} = a + \sqrt{a^2 + 2} for A=aA = a, and bisection in the code reproduces this to six digits for a=−1,0,1,2a = -1, 0, 1, 2.

At γ=3\gamma = 3: F=−2.67116F = -2.67116, L=−2.67116L = -2.67116, Z=4.82603Z = 4.82603, A^=−14.26554\hat A = -14.26554 and −ZL=12.89117-ZL = 12.89117. The controller is

K(s)=−34.43444s+14.26554,K(s) = \frac{-34.43444}{s + 14.26554},

with K(0)=−2.41383K(0) = -2.41383. The closed loop poles are −11.51383-11.51383 and −1.75171-1.75171, so the loop is internally stable. A frequency sweep of the 2×22 \times 2 closed loop map gives its largest singular value 2.986322.98632 at ω=0\omega = 0, below γ=3\gamma = 3, as the theorem says.

Correctness

The theorem gives the meaning of FEASIBLE: it returns true at gg if and only if some controller reaches ∥Tzw∥∞<g\|T_{zw}\|_\infty < g. That set of levels is closed upward, so it is the open interval (γopt,∞)(\gamma_{\rm opt}, \infty). Bisection keeps the invariant that lo is infeasible (or 0) and hi is feasible, so after the loop γopt∈[lo,hi]\gamma_{\rm opt} \in [\text{lo}, \text{hi}] and hi−lo≤tol⋅hi\text{hi} - \text{lo} \le \text{tol} \cdot \text{hi}. The Riccati routine returns the stabilizing solution or nothing, because a stabilizing solution is unique and the code checks the equation and the Hurwitz property directly. The central controller at (1+δ) hi(1 + \delta)\,\text{hi} meets the bound by the theorem. The proofs of the bisection invariant, of the subspace step and of the scalar formula are in proofs/correctness.md; the theorem itself is cited.

The proof of the theorem in Zhou, Doyle and Glover (1996, chapter 16) has two parts. Sufficiency: with u=Fxu = F x and the worst disturbance w=γ−2B1TXxw = \gamma^{-2} B_1^T X x, a completion of squares shows that ∥z∥22−γ2∥w∥22\|z\|_2^2 - \gamma^2 \|w\|_2^2 splits into a term that the controller can cancel and a term that only depends on an estimation error. This reduces the output feedback problem to an estimation problem for a modified plant, whose Riccati solution is Y(I−γ−2XY)−1Y(I - \gamma^{-2} X Y)^{-1}; this is where ρ(XY)<γ2\rho(XY) < \gamma^2 appears. Necessity goes through the same split into a full information problem and an output estimation problem, which is the H-infinity form of the separation principle. The bounded real lemma links the norm bound to the Riccati equations in each step.

Proof: The bisection finds the optimal H-infinity level and the Riccati step returns the stabilizing solutionfull

Notation is that of the page. The plant satisfies assumptions 1 to 5. We use the DGKF theorem as a cited result: for γ>0\gamma > 0, FEASIBLE(γ)(\gamma) in exact arithmetic returns true if and only if some internally stabilizing controller gives ∥Tzw∥∞<γ\|T_{zw}\|_\infty < \gamma (Doyle, Glover, Khargonekar and Francis 1989; Zhou, Doyle and Glover 1996, chapter 16). Let γopt\gamma_{\rm opt} be the infimum of ∥Tzw∥∞\|T_{zw}\|_\infty over all internally stabilizing controllers.

Claim 1: the feasible levels form the interval above the optimum

FEASIBLE(γ)(\gamma) is true if and only if γ>γopt\gamma > \gamma_{\rm opt}.

Proof. If γ>γopt\gamma > \gamma_{\rm opt}, the definition of the infimum gives a controller with ∥Tzw∥∞<γ\|T_{zw}\|_\infty < \gamma, so FEASIBLE(γ)(\gamma) is true. If FEASIBLE(γ)(\gamma) is true, some controller has norm ν<γ\nu < \gamma, so γopt≤ν<γ\gamma_{\rm opt} \le \nu < \gamma. □\square

Claim 2: the bisection brackets the optimum

After line L2, lo is 0 or infeasible and hi is feasible. After the loop of lines L3 to L5, lo≤γopt≤hi\text{lo} \le \gamma_{\rm opt} \le \text{hi} and hi−lo≤tol⋅hi\text{hi} - \text{lo} \le \text{tol} \cdot \text{hi}.

Proof. Line L1 sets lo =0≤γopt= 0 \le \gamma_{\rm opt}. Line L2 doubles hi and moves the old hi into lo only when the old hi is infeasible, so by Claim 1 each value of lo is at most γopt\gamma_{\rm opt}. The loop of L2 ends: assumptions 1 and 2 give a stabilizing controller, its norm is finite, and every larger level is feasible. At the end of L2, hi is feasible, so γopt<hi\gamma_{\rm opt} < \text{hi}. Inside L3 to L5 the midpoint gg replaces hi only if it is feasible (γopt<g\gamma_{\rm opt} < g) and replaces lo only if it is infeasible (g≤γoptg \le \gamma_{\rm opt}). So the invariant lo≤γopt<hi\text{lo} \le \gamma_{\rm opt} < \text{hi} holds after each step. Each step halves hi−lo\text{hi} - \text{lo}, and hi does not drop below γopt\gamma_{\rm opt}, so the loop ends after at most ⌈log⁡2(hi0/(tol γopt))⌉\lceil \log_2(\text{hi}_0/(\text{tol}\,\gamma_{\rm opt})) \rceil steps when γopt>0\gamma_{\rm opt} > 0. □\square

Line L6 takes g=(1+δ) hi>γoptg = (1 + \delta)\,\text{hi} > \gamma_{\rm opt}, so FEASIBLE(g)(g) is true and the theorem gives that the central controller of lines L8 to L10 is internally stabilizing with ∥Tzw∥∞<g≤(1+δ)(1+tol′)γopt\|T_{zw}\|_\infty < g \le (1 + \delta)(1 + \text{tol}')\gamma_{\rm opt}, where tol′=tol/(1−tol)\text{tol}' = \text{tol}/(1 - \text{tol}).

Claim 3: a stabilizing Riccati solution is unique

Let RR and QQ be symmetric. If X1X_1 and X2X_2 are symmetric, both solve ATX+XA+XRX+Q=0A^T X + X A + X R X + Q = 0, and both A+RX1A + R X_1 and A+RX2A + R X_2 are Hurwitz, then X1=X2X_1 = X_2.

Proof. Let D=X1−X2D = X_1 - X_2. Subtract the two equations and use X1RX1−X2RX2=X1RD+DRX2X_1 R X_1 - X_2 R X_2 = X_1 R D + D R X_2:

(A+RX1)TD+D(A+RX2)=0.(A + R X_1)^T D + D (A + R X_2) = 0.

This is a Sylvester equation MTD+DN=0M^T D + D N = 0 with MM and NN Hurwitz. It has a unique solution when MTM^T and −N-N have no common eigenvalue. The eigenvalues of MTM^T are in the open left half plane and those of −N-N in the open right half plane, so D=0D = 0 is the only solution. □\square

The routine riccati returns a matrix only after it checks the residual and that A+RXA + R X is Hurwitz. By Claim 3, in exact arithmetic that matrix is Ric(H)\mathrm{Ric}(H). In floating point the checks hold with the stated tolerances.

Claim 4: the sign function gives the stable subspace

Assume H=[AR−Q−AT]H = \begin{bmatrix} A & R \\ -Q & -A^T \end{bmatrix} has no eigenvalue on the imaginary axis and W=sign(H)W = \mathrm{sign}(H). If the stable invariant subspace of HH is the range of [IX]\begin{bmatrix} I \\ X \end{bmatrix}, then XX is the unique solution of the linear system [W12W22+I]X=−[W11+IW21]\begin{bmatrix} W_{12} \\ W_{22} + I \end{bmatrix} X = -\begin{bmatrix} W_{11} + I \\ W_{21} \end{bmatrix}, and XX solves the Riccati equation with A+RXA + R X Hurwitz.

Proof. Write H=V diag(J−,J+) V−1H = V \,\mathrm{diag}(J_-, J_+)\, V^{-1} with the eigenvalues of J−J_- in the open left half plane and those of J+J_+ in the open right half plane. Then W=V diag(−I,I) V−1W = V \,\mathrm{diag}(-I, I)\, V^{-1}, so W+I=V diag(0,2I) V−1W + I = V\,\mathrm{diag}(0, 2I)\,V^{-1}, whose kernel is the span of the first block of columns of VV, the stable invariant subspace. Since that subspace is the range of [IX]\begin{bmatrix} I \\ X \end{bmatrix}, we have (W+I)[IX]=0(W + I)\begin{bmatrix} I \\ X \end{bmatrix} = 0. The block rows of this identity are the stated system. The solution is unique: if [W12W22+I]v=0\begin{bmatrix} W_{12} \\ W_{22} + I \end{bmatrix} v = 0, then [0v]\begin{bmatrix} 0 \\ v \end{bmatrix} is in the kernel of W+IW + I, so it equals [uXu]\begin{bmatrix} u \\ X u \end{bmatrix} for some uu, which gives u=0u = 0 and v=0v = 0. So the matrix has full column rank and the normal equations have the same unique solution.

The subspace is invariant, so H[IX]=[IX]ΛH\begin{bmatrix} I \\ X \end{bmatrix} = \begin{bmatrix} I \\ X \end{bmatrix} \Lambda for some Λ\Lambda whose eigenvalues are the stable eigenvalues of HH. The first block row gives Λ=A+RX\Lambda = A + R X, so A+RXA + R X is Hurwitz. The second block row gives −Q−ATX=X(A+RX)-Q - A^T X = X(A + R X), which is the Riccati equation. □\square

The scaled Newton iteration W←12(μW+μ−1W−1)W \leftarrow \frac12(\mu W + \mu^{-1} W^{-1}) with μ>0\mu > 0 converges to sign(H)\mathrm{sign}(H) when HH has no eigenvalue on the imaginary axis (Higham 2008, chapter 5). The code stops when the change is below 10−1310^{-13} relative and then checks ∥W2−I∥≤10−8\|W^2 - I\| \le 10^{-8}.

Claim 5: the scalar example has optimum a + sqrt(a^2 + 2)

For A=aA = a, B1=[1,0]B_1 = [1, 0], B2=1B_2 = 1, C1=[1;0]C_1 = [1; 0], D12=[0;1]D_{12} = [0; 1], C2=1C_2 = 1 and D21=[0,1]D_{21} = [0, 1], the optimal level is γopt=a+a2+2\gamma_{\rm opt} = a + \sqrt{a^2 + 2}.

Proof. Let c=1−γ−2c = 1 - \gamma^{-2}. Both Hamiltonians equal [a−c−1−a]\begin{bmatrix} a & -c \\ -1 & -a \end{bmatrix}, with eigenvalues ±a2+c\pm\sqrt{a^2 + c}. So condition 1 needs a2+c>0a^2 + c > 0, and then X=YX = Y is the root of −cX2+2aX+1=0-cX^2 + 2aX + 1 = 0 with a−cX=−a2+ca - cX = -\sqrt{a^2 + c}, that is X=(a+a2+c)/cX = (a + \sqrt{a^2 + c})/c for c≠0c \ne 0 and X=−1/(2a)X = -1/(2a) for c=0c = 0. Condition 3 is X<γX < \gamma, since X≥0X \ge 0 is needed anyway.

Write fγ(t)=−ct2+2at+1f_\gamma(t) = -c t^2 + 2a t + 1, so X(γ)X(\gamma) is the root of fγf_\gamma with fγ′(X)=2(a−cX)<0f_\gamma'(X) = 2(a - cX) < 0. The key identity is

fγ(γ)=−(1−γ−2)γ2+2aγ+1=−(γ2−2aγ−2),f_\gamma(\gamma) = -(1 - \gamma^{-2})\gamma^2 + 2a\gamma + 1 = -(\gamma^2 - 2a\gamma - 2),

which is negative for γ>γ∗\gamma > \gamma^* and positive for 0<γ<γ∗0 < \gamma < \gamma^*, where γ∗=a+a2+2\gamma^* = a + \sqrt{a^2 + 2} is the positive root of γ2−2aγ−2\gamma^2 - 2a\gamma - 2.

At γ=γ∗\gamma = \gamma^* the value t=γ∗t = \gamma^* is a root of fγ∗f_{\gamma^*}, and a=(γ∗−2/γ∗)/2a = (\gamma^* - 2/\gamma^*)/2 gives a−c∗γ∗=a−γ∗+1/γ∗=−γ∗/2<0a - c^*\gamma^* = a - \gamma^* + 1/\gamma^* = -\gamma^*/2 < 0. So γ∗\gamma^* is the stabilizing root: X(γ∗)=γ∗X(\gamma^*) = \gamma^*, and a2+c∗=(γ∗/2)2>0a^2 + c^* = (\gamma^*/2)^2 > 0. By continuity there is a neighborhood UU of γ∗\gamma^* and an interval II around γ∗\gamma^* such that, for γ∈U\gamma \in U, the Hamiltonian has no imaginary eigenvalue, X(γ)∈IX(\gamma) \in I, γ∈I\gamma \in I, X(γ)>0X(\gamma) > 0, and fγ′<0f_\gamma' < 0 on all of II. On II the function fγf_\gamma is strictly decreasing and is 0 at X(γ)X(\gamma). So for γ∈U\gamma \in U: X(γ)<γX(\gamma) < \gamma if and only if fγ(γ)<0f_\gamma(\gamma) < 0, that is, if and only if γ>γ∗\gamma > \gamma^*. Conditions 1 and 2 hold in UU, so levels just above γ∗\gamma^* are feasible and levels just below are not. By Claim 1 the feasible set is (γopt,∞)(\gamma_{\rm opt}, \infty), so γopt=γ∗\gamma_{\rm opt} = \gamma^*. For a=1a = 1 this is 1+3=2.732051 + \sqrt 3 = 2.73205, and the table on the page shows the change of sign of γ2−X2\gamma^2 - X^2 between γ=2.7\gamma = 2.7 and 2.752.75. □\square

The test checks Claim 5 for a=−1,0,1,2a = -1, 0, 1, 2 against the bisection, with relative error at most 10−610^{-6}.

What the tests check

  • The Riccati residual is below 10−910^{-9}, XX is symmetric and positive definite, and A+RXA + R X is Hurwitz, on a plant with two states.
  • The three conditions fail at 0.99 γopt0.99\,\gamma_{\rm opt} and hold at 1.01 γopt1.01\,\gamma_{\rm opt}.
  • The central controller gives a Hurwitz closed loop matrix and a frequency sweep peak below γ\gamma and at least γopt(1−10−4)\gamma_{\rm opt}(1 - 10^{-4}).
  • Brute force: 150 random first-order controllers K(s)=(k1s+k0)/(s+p)K(s) = (k_1 s + k_0)/(s + p) for each of two scalar plants. Every one that stabilizes has a sweep peak of at least γopt(1−10−3)\gamma_{\rm opt}(1 - 10^{-3}).

Complexity

Let nn be the number of states, mm the number of inputs (w,u)(w, u) and pp the number of outputs (z,y)(z, y). In the real-RAM model with dense factorizations at O(n3)O(n^3) flops, one test of FEASIBLE forms the Hamiltonians in O(n2(m+p))O(n^2(m + p)) and computes two sign functions, each with cc Newton steps of O(n3)O(n^3). Near convergence the Newton iteration converges quadratically (Higham 2008, chapter 5); cc depends on how close the eigenvalues of HH are to the imaginary axis, so it is not bounded by a function of nn alone. The bisection needs k=⌈log⁡2(hi0/(tol⋅γopt))⌉k = \lceil \log_2(\text{hi}_0 / (\text{tol} \cdot \gamma_{\rm opt})) \rceil tests, up to a constant. The total is O(k(cn3+n2(m+p)))O(k(c n^3 + n^2(m + p))) time and O(n2+n(m+p))O(n^2 + n(m + p)) extra space. The controller itself costs O(n3)O(n^3) once.

Properties

  • The test is exact in real arithmetic: it decides the existence of a controller of any order, not only of order nn.
  • The central controller has the same order nn as the generalized plant, which includes the weights.
  • As γ→∞\gamma \to \infty, XX and YY tend to the solutions of the LQR and Kalman filter Riccati equations, Z→IZ \to I, and the central controller tends to the H2-optimal (LQG) controller. In the example, the static gain K(0)=−2.414K(0) = -2.414 at γ=3\gamma = 3 is already close to the LQR gain 1+2=2.414211 + \sqrt 2 = 2.41421 of the scalar problem with a=b=q=r=1a = b = q = r = 1.
  • The controller is observer-based: x^\hat x estimates the state under the worst-case disturbance γ−2B1TXx\gamma^{-2} B_1^T X x.
  • Every suboptimal controller is K=Fl(Ka,Q)K = \mathcal{F}_l(K_a, Q) for a fixed system KaK_a and some stable QQ with ∥Q∥∞<γ\|Q\|_\infty < \gamma (Glover and Doyle 1988). Q=0Q = 0 gives the central controller.

Variants and improvements

  • General D matrices. Loop shifting and scaling remove D11D_{11} and normalize D12D_{12} and D21D_{21}, at the price of a condition on γ\gamma from D11D_{11} (Zhou, Doyle and Glover 1996, chapter 17).
  • Singular problems. If D12D_{12} or D21D_{21} loses rank, or the plant has zeros on the imaginary axis, the Riccati approach fails. LMI-based H-infinity synthesis needs no rank assumptions.
  • Discrete time. The same structure holds with two discrete Riccati equations and a coupling condition; the formulas are longer.
  • Special structure. H-infinity loop shaping has a closed form for the optimal level, so no bisection is needed.
  • Design use. Mixed sensitivity design builds the generalized plant from weights; D-K iteration calls this algorithm once per iteration on a scaled plant.

When to use it

Use it when the plant model is linear and finite-dimensional, the requirements can be written as a bound on the H-infinity norm of a weighted closed loop map, and the normalization assumptions hold or can be reached by loop shifting. It is fast and gives the exact optimal level up to the bisection tolerance. If the assumptions fail, or extra constraints such as pole regions or several objectives are needed, use the LMI method. If the controller must have a low fixed order, neither method applies directly; that problem is harder (see the problem page).

Pitfalls

  • Controller at the optimum. As γ→γopt\gamma \to \gamma_{\rm opt} with coupling active, I−γ−2YXI - \gamma^{-2} Y X becomes singular and the central controller gets very fast poles. In the example the controller pole is at −14.3-14.3 for γ=3\gamma = 3 and at −111-111 for γ=1.01 γopt\gamma = 1.01\,\gamma_{\rm opt}. Back off a few percent; the choice of δ\delta is a rule of thumb.
  • Forgetting X ≥ 0. The Riccati equation can have a stabilizing solution that is not positive semidefinite. Then the test fails, even if the coupling condition holds.
  • Imaginary axis eigenvalues. Near the boundary of condition 1 or 2, the Hamiltonian has eigenvalues close to the imaginary axis, and the sign iteration or the Schur method loses accuracy. A floating point decision near γopt\gamma_{\rm opt} can be wrong in either direction; the bisection result is accurate to about the size of this region.
  • Normalization. The formulas above are only valid in the normalized form. Applying them to a plant with D12TD12≠ID_{12}^T D_{12} \ne I or D12TC1≠0D_{12}^T C_1 \ne 0 gives wrong answers without any warning.
  • Sign conventions. The controller is wired as u=Kyu = K y. Books on loop shaping use positive feedback, and classical loops use u=C(r−y)u = C(r - y); check the sign before using a controller from another source.
  • Weights in the plant. The order of the controller is the order of the plant plus all weights. High order weights give high order controllers, which may need model order 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()
dgkf_h_infinity_synthesis.py 199 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dgkf-h-infinity-synthesis/. The authors are listed in prov/DM08Z2.jsonl.

"""Two-Riccati H-infinity synthesis (Doyle, Glover, Khargonekar, Francis 1989).

The generalized plant has the normalized form of the page:

    x' = A x + B1 w + B2 u
    z  = C1 x + D12 u          with D12^T [C1 D12] = [0 I]
    y  = C2 x + D21 w          with [B1; D21] D21^T = [0; I]

and D11 = 0, D22 = 0. A plant is a dict with the keys "A", "B1", "B2",
"C1", "C2", "D12", "D21" (lists of rows). The controller is wired as
u = K y, the lower linear fractional transformation, with no sign change.

Each Riccati equation is solved from the stable invariant subspace of its
Hamiltonian matrix, found with the matrix sign function (Newton iteration
with determinant scaling). All results are floats.
"""

import math

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

__all__ = [
    "matrix_sign", "riccati", "is_hurwitz", "spectral_radius",
    "gamma_feasible", "optimal_gamma", "central_controller", "closed_loop",
    "freq_gain", "dgkf_synthesis",
]


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 matrix_sign(h, tol=1e-13, maxiter=100):
    """Return sign(H) by the scaled Newton iteration, or None.

    None means that the iteration did not converge, which happens when H
    has an eigenvalue on or very near the imaginary axis.
    """
    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."""
    roots = polyroots(charpoly(_flo(m)))
    return max(r.real for r in roots) < -tol


def spectral_radius(m):
    """Return the largest modulus of an eigenvalue of m."""
    return max(abs(r) for r in polyroots(charpoly(_flo(m))))


def riccati(a, r, q):
    """Return the stabilizing solution X of A^T X + X A + X R X + Q = 0, or None.

    R and Q are symmetric. The solution is X = Ric(H) for the Hamiltonian
    H = [[A, R], [-Q, -A^T]]: the stable invariant subspace of H is the
    range of [I; X], and A + R X is Hurwitz. None means that H has an
    eigenvalue on the imaginary axis or that the stable subspace is not a
    graph over its first n coordinates.
    """
    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 = matrix_sign(h)
    if w is None:
        return None
    # The stable subspace is the kernel of W + I, so (W + I) [I; X] = 0.
    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 not math.isfinite(_big(x)) or _big(res) > 1e-7 * size:
        return None
    if not is_hurwitz(add(a, mul(r, x))):
        return None
    return x


def _psd(x, rel=1e-9):
    return is_pos_def(x, -rel * (1.0 + _big(x)))


def gamma_feasible(p, gamma):
    """Test the three DGKF conditions at gamma. Return (ok, X, Y)."""
    a, b1, b2, c1, c2 = (_flo(p[k]) for k in ("A", "B1", "B2", "C1", "C2"))
    g2 = 1.0 / (gamma * gamma)
    rx = sub(scale(g2, mul(b1, transpose(b1))), mul(b2, transpose(b2)))
    x = riccati(a, rx, mul(transpose(c1), c1))  # @line L11
    if x is None or not _psd(x):
        return False, x, None
    ry = sub(scale(g2, mul(transpose(c1), c1)), mul(transpose(c2), c2))
    y = riccati(transpose(a), ry, mul(b1, transpose(b1)))  # @line L12
    if y is None or not _psd(y):
        return False, x, y
    ok = spectral_radius(mul(x, y)) < gamma * gamma * (1.0 - 1e-9)  # @line L13
    return ok, x, y


def optimal_gamma(p, rtol=1e-6):
    """Bisect for the smallest gamma that passes gamma_feasible."""
    lo, hi = 0.0, 1.0  # @line L1
    while not gamma_feasible(p, hi)[0]:  # @line L2
        lo, hi = hi, 2.0 * hi
        if hi > 1e8:
            raise ValueError("no gamma below 1e8 passes the test")
    while hi - lo > rtol * hi:  # @line L3
        g = 0.5 * (lo + hi)  # @line L4
        if gamma_feasible(p, g)[0]:  # @line L5
            hi = g
        else:
            lo = g
    return hi


def central_controller(p, gamma):
    """Return (A_K, B_K, C_K, D_K) of the central controller at gamma.

    Raises ValueError if gamma does not pass the three conditions.
    """
    ok, x, y = gamma_feasible(p, gamma)  # @line L7
    if not ok:
        raise ValueError("gamma does not pass the DGKF conditions")
    a, b1, b2, c2 = (_flo(p[k]) for k in ("A", "B1", "B2", "C2"))
    n = len(a)
    g2 = 1.0 / (gamma * gamma)
    f = scale(-1.0, mul(transpose(b2), x))  # @line L8
    l = scale(-1.0, mul(y, transpose(c2)))
    z = inv(sub(eye(n), scale(g2, mul(y, x))))
    ak = add(add(a, scale(g2, mul(mul(b1, transpose(b1)), x))),  # @line L9
             add(mul(b2, f), mul(mul(z, l), c2)))
    bk = scale(-1.0, mul(z, l))
    dk = zeros(len(f), len(bk[0]))
    return ak, bk, f, dk  # @line L10


def closed_loop(p, k):
    """Return (A, B, C, D) of the map w -> z with u = K y."""
    a, b1, b2, c1, c2, d12, d21 = (_flo(p[s]) for s in ("A", "B1", "B2", "C1", "C2", "D12", "D21"))
    ak, bk, ck, dk = (_flo(m) for m in k)
    acl = block([[add(a, mul(mul(b2, dk), c2)), mul(b2, ck)],
                 [mul(bk, c2), ak]])
    bcl = block([[add(b1, mul(mul(b2, dk), d21))], [mul(bk, d21)]])
    ccl = block([[add(c1, mul(mul(d12, dk), c2)), mul(d12, ck)]])
    dcl = mul(mul(d12, dk), d21)
    return acl, bcl, ccl, dcl


def freq_gain(sys, w):
    """Return the largest singular value of C (j w I - A)^-1 B + D."""
    a, b, c, d = sys
    n = len(a)
    m = [[(1j * w if i == j else 0.0) - a[i][j] for j in range(n)] for i in range(n)]
    g = add(mul(c, solve(m, [[complex(v) for v in row] for row in b])), d)
    return norm2(g)


def dgkf_synthesis(p, rtol=1e-6, backoff=1.01):
    """Return (gamma_opt, gamma_used, controller).

    gamma_opt is the bisection estimate of the optimal level. The
    controller is the central one at gamma_used = backoff * gamma_opt,
    since the central controller degenerates at the optimum itself.
    """
    gopt = optimal_gamma(p, rtol)
    g = backoff * gopt  # @line L6
    return gopt, g, central_controller(p, g)
test_dgkf_h_infinity_synthesis.py 163 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dgkf-h-infinity-synthesis/. The authors are listed in prov/DM08Z2.jsonl.

import math
import random

import ctlmat as cm
from dgkf_h_infinity_synthesis import (
    central_controller,
    closed_loop,
    dgkf_synthesis,
    freq_gain,
    gamma_feasible,
    is_hurwitz,
    matrix_sign,
    optimal_gamma,
    riccati,
    spectral_radius,
)


def scalar_plant(a):
    # x' = a x + w1 + u, z = (x, u), y = x + w2
    return {"A": [[a]], "B1": [[1, 0]], "B2": [[1]], "C1": [[1], [0]],
            "C2": [[1]], "D12": [[0], [1]], "D21": [[0, 1]]}


# Second-order plant with an unstable pole at s = 1.
PLANT2 = {"A": [[0, 1], [2, -1]], "B1": [[1, 0, 0], [0, 1, 0]],
          "B2": [[0], [1]], "C1": [[1, 0], [0, 1], [0, 0]],
          "C2": [[1, 0]], "D12": [[0], [0], [1]], "D21": [[0, 0, 1]]}

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


def peak(sys):
    return max(freq_gain(sys, w) for w in FREQS + [0.0])


def test_ctlmat_self_test():
    assert cm._self_test()


def test_normalizations_of_the_examples():
    for p in (scalar_plant(0), PLANT2):
        d12, c1, b1, d21 = p["D12"], p["C1"], p["B1"], p["D21"]
        m = len(d12[0])
        assert cm.mul(cm.transpose(d12), c1) == cm.zeros(m, len(c1[0]))
        assert cm.mul(cm.transpose(d12), d12) == cm.eye(m)
        assert cm.mul(b1, cm.transpose(d21)) == cm.zeros(len(b1), len(d21))
        assert cm.mul(d21, cm.transpose(d21)) == cm.eye(len(d21))


def test_matrix_sign_of_a_diagonalizable_matrix():
    h = [[1.0, 2.0], [0.0, -3.0]]
    s = matrix_sign(h)
    # sign(H) = V diag(1, -1) V^-1 with V = [[1, 1], [0, -2]].
    want = [[1.0, 1.0], [0.0, -1.0]]
    assert max(abs(s[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-12
    assert matrix_sign([[0.0, 1.0], [-1.0, 0.0]]) is None


def test_riccati_against_the_scalar_formula():
    # a^T x + x a + x r x + q = 0 with r < 0 has the stabilizing root below.
    for a, r, q in ((0.0, -1.0, 1.0), (1.0, -0.5, 2.0), (-2.0, -3.0, 0.5)):
        x = riccati([[a]], [[r]], [[q]])[0][0]
        want = (-a - math.sqrt(a * a - r * q)) / r
        assert abs(x - want) < 1e-10 * (1 + abs(want))
        assert a + r * x < 0


def test_riccati_residual_and_closed_loop_on_plant2():
    g = 8.0
    ok, x, y = gamma_feasible(PLANT2, g)
    assert ok
    a = [[float(v) for v in row] for row in PLANT2["A"]]
    b1, b2, c1 = PLANT2["B1"], PLANT2["B2"], PLANT2["C1"]
    r = cm.sub(cm.scale(1 / g ** 2, cm.mul(b1, cm.transpose(b1))), cm.mul(b2, cm.transpose(b2)))
    res = cm.add(cm.add(cm.mul(cm.transpose(a), x), cm.mul(x, a)),
                 cm.add(cm.mul(cm.mul(x, r), x), cm.mul(cm.transpose(c1), c1)))
    assert max(abs(v) for row in res for v in row) < 1e-9
    assert cm.is_symmetric(x, 1e-12) and cm.is_pos_def(x)
    assert cm.is_pos_def(y)
    assert is_hurwitz(cm.add(a, cm.mul(r, x)))
    assert spectral_radius(cm.mul(x, y)) < g * g


def test_optimal_gamma_matches_the_closed_form():
    # For the scalar plant the three conditions give gamma_opt = a + sqrt(a^2 + 2).
    for a in (-1, 0, 1, 2):
        g = optimal_gamma(scalar_plant(a), rtol=1e-7)
        assert abs(g - (a + math.sqrt(a * a + 2))) < 1e-6 * g


def test_conditions_fail_below_and_hold_above_the_optimum():
    for p in (scalar_plant(1), PLANT2):
        g = optimal_gamma(p)
        assert not gamma_feasible(p, 0.99 * g)[0]
        assert gamma_feasible(p, 1.01 * g)[0]


def test_central_controller_meets_the_bound():
    for p in (scalar_plant(-1), scalar_plant(0), scalar_plant(2), PLANT2):
        gopt, g, k = dgkf_synthesis(p)
        cl = closed_loop(p, k)
        assert is_hurwitz(cl[0])
        pk = peak(cl)
        assert pk < g
        assert pk >= gopt * (1 - 1e-4)


def test_central_controller_at_a_loose_level():
    g = 3 * optimal_gamma(PLANT2)
    cl = closed_loop(PLANT2, central_controller(PLANT2, g))
    assert is_hurwitz(cl[0])
    assert peak(cl) < g


def _peak_scalar(a, k1, k0, p):
    # Closed loop of the scalar plant with K(s) = (k1 s + k0) / (s + p),
    # written with D = s - a - K so that s = a gives no division by zero.
    # The largest singular value of the 2 by 2 matrix comes from its
    # Frobenius norm and its determinant.
    best = 0.0
    for w in FREQS + [0.0]:
        s = 1j * w
        k = (k1 * s + k0) / (s + p)
        dd = s - a - k
        t = [[1 / dd, k / dd], [k / dd, k * (s - a) / dd]]
        f = sum(abs(v) ** 2 for row in t for v in row)
        dt = abs(t[0][0] * t[1][1] - t[0][1] * t[1][0])
        best = max(best, math.sqrt((f + math.sqrt(max(f * f - 4 * dt * dt, 0.0))) / 2))
    return best


def test_no_first_order_controller_beats_the_optimum():
    rng = random.Random(7)
    for a in (0, 1):
        p = scalar_plant(a)
        gopt = a + math.sqrt(a * a + 2)
        found = 0
        best = math.inf
        for _ in range(150):
            k1 = rng.uniform(-3, 1)
            k0 = rng.uniform(-8, 1)
            pole = rng.uniform(0.01, 10)
            k = ([[-pole]], [[1]], [[k0 - k1 * pole]], [[k1]])
            cl = closed_loop(p, k)
            if not is_hurwitz(cl[0]):
                continue
            found += 1
            best = min(best, _peak_scalar(a, k1, k0, pole))
        assert found > 20
        assert best >= gopt * (1 - 1e-3)
        assert best < 2 * gopt


def test_both_sweeps_agree():
    p = scalar_plant(1)
    k = ([[-2.0]], [[1.0]], [[-3.0 + 2.0 * 0.5]], [[-0.5]])
    cl = closed_loop(p, k)
    assert is_hurwitz(cl[0])
    assert abs(peak(cl) - _peak_scalar(1, -0.5, -3.0, 2.0)) < 1e-9

History

Zames (1981) posed the problem of minimizing a weighted sensitivity in the H-infinity norm. The first solutions in the early 1980s used the Youla parametrization and Nehari or Nevanlinna-Pick interpolation, and they gave controllers of high order. Glover and Doyle (1988) gave state-space formulas for all suboptimal controllers. Doyle, Glover, Khargonekar and Francis (1989) gave the full proof of the two-Riccati solution, together with the H2 case, in one paper. The LMI approach of Gahinet and Apkarian (1994) and Iwasaki and Skelton (1994) later removed the rank assumptions.

References

  1. John C. Doyle, Keith Glover, Pramod P. Khargonekar and Bruce A. Francis, State-space solutions to standard H2 and H-infinity control problems, IEEE Transactions on Automatic Control 34(8), 831-847, 1989, the normalized output feedback problem, its assumptions, the three conditions on X and Y, and the central controller
  2. Keith Glover and John C. Doyle, State-space formulae for all stabilizing controllers that satisfy an H-infinity norm bound and relations to risk sensitivity, Systems and Control Letters 11(3), 167-172, 1988, the parametrization of all suboptimal controllers and the link to risk-sensitive control
  3. Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, Chapter 16, H-infinity Control, Simple Case (the theorem and the central controller), and Chapter 17, H-infinity Control, General Case (loop shifting for general D matrices)
  4. Sigurd Skogestad and Ian Postlethwaite, Multivariable Feedback Control, Analysis and Design, second edition, Wiley, 2005, Section 9.3.4, H-infinity optimal control (the formulas and the gamma iteration as used in design)
  5. Nicholas J. Higham, Functions of Matrices, Theory and Computation, SIAM, 2008, Chapter 5, Matrix Sign Function (the scaled Newton iteration and its convergence)

Where this leads

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.per-gamma
  • 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