Algorithm Search⌘K

Algorithmadvanced

D-K iteration

Also called mu-synthesis by D-K iteration.

Designs a controller for robust performance. It alternates H-infinity synthesis with the scalings fixed and a fit of the scalings with the controller fixed.

Time
O(t (k (c n^3 + n^2 q) + f (n^3 + n^2 q) + g f q^3)) totalO(k (c n^3 + n^2 q) + f (n^3 + n^2 q) + g f q^3) per-iteration
Space
O(n^2 + n q + f q^2) extra
Where
c = the number of Newton steps of one matrix sign function; f = the number of grid frequencies; g = the number of golden section steps; k = the number of bisection steps on gamma; n = the number of plant states; q = the larger of the number of outputs z and inputs w; t = the number of D-K iterations
Properties
deterministicnot exactiterativeiterative
Origin
John C. Doyle, 1985

D-K iteration is the usual method for mu-synthesis: the design of a controller KK that makes the peak over frequency of the structured singular value μ\mu of the closed loop small. The exact problem is hard, because μ\mu itself is NP-hard to compute (Braatz et al. 1994). The method replaces μ\mu by its upper bound with diagonal scalings DD, and it minimizes ∥D Fl(P,K) D−1∥∞\|D\,\mathcal{F}_l(P, K)\,D^{-1}\|_\infty over KK and DD. This joint problem is not convex. But with DD fixed it is an H-infinity synthesis problem (the K-step), and with KK fixed it is a convex problem in log⁡D\log D at each frequency (the D-step). The method does the two steps in turn. Each step can only lower the bound, up to the tolerances, so the bound decreases. But the iteration can stop at a point that is not the global optimum, and no guarantee of the global optimum is known.

In plain words

You want a controller that keeps good performance for every plant in an uncertainty set. Such a set has structure: the uncertainty is a list of separate blocks. The structured singular value tests this, but it is hard to minimize. A simpler number is an upper bound that uses one scale factor per block. If you fix the scale factors, the best controller comes from standard H-infinity synthesis. If you fix the controller, the best scale factors come from a small convex search. Do the two steps in turn. The bound goes down at each step and soon stops changing. The result is usually good, but it can be a local optimum.

The problem

The generalized plant PP has inputs (w,u)(w, u) and outputs (z,y)(z, y), with u=Kyu = K y. The closed loop is the lower linear fractional transformation M=Fl(P,K)M = \mathcal{F}_l(P, K) from ww to zz. The uncertainty Δ\Delta closes a loop from some outputs zz to some inputs ww, and it has the block diagonal structure Δ={diag(Δ1,…,ΔF)}\boldsymbol\Delta = \{\mathrm{diag}(\Delta_1, \ldots, \Delta_F)\} with full complex blocks. For robust performance, one extra full block ΔP\Delta_P connects the performance outputs to the performance inputs. The design problem is

min⁡K stabilizing sup⁡ω μΔ(M(jω)).\min_{K \text{ stabilizing}} \ \sup_\omega \ \mu_{\boldsymbol\Delta}(M(j\omega)).

By the main loop theorem (Packard and Doyle 1993), if this peak is below β\beta, then for every structured uncertainty of size below 1/β1/\beta the loop is internally stable and the performance map has H-infinity norm below β\beta. For each frequency, μΔ(M)≤inf⁡Dσˉ(DMD−1)\mu_{\boldsymbol\Delta}(M) \le \inf_D \bar\sigma(D M D^{-1}), where D=diag(d1I,…,dFI,I)D = \mathrm{diag}(d_1 I, \ldots, d_F I, I) and every di>0d_i > 0. With one DD for all frequencies, this gives the problem that D-K iteration attacks:

min⁡K, D ∥D Fl(P,K) D−1∥∞.\min_{K,\ D} \ \|D\,\mathcal{F}_l(P, K)\,D^{-1}\|_\infty.

This page uses a constant DD in the K-step and in the D-step, which is the simplest case. The usual tools fit a rational D(s)D(s) to values of di(ω)d_i(\omega) found frequency by frequency (see Variants).

The implementation treats one uncertainty block and one performance block, so D=diag(dI,I)D = \mathrm{diag}(d I, I) with one scalar d>0d > 0. The plant has the normalized form of the two-Riccati page. The uncertainty channels must not touch uu or yy directly, that is, the rows of D12D_{12} and the columns of D21D_{21} for the uncertainty block are zero. Then the scaled plant is still normalized.

The algorithm

  1. DK-ITERATION(P, grid, iters, delta, tol)
  2. 1d ← 1
  3. 2for it ← 1 to iters do
  4. 3P_d ← P with z1 ← d z1 and w1 ← w1 / d
  5. 4K ← central controller of P_d at (1 + delta) · gamma_opt(P_d) ▷ K-step
  6. 5M(jw) ← closed loop F_l(P, K) at each w in grid
  7. 6search log d by golden section for the least max_w sigma_max(D M(jw) D^-1) ▷ D-step
  8. 7v ← the least value, d ← its argument
  9. 8if v went down by less than tol · v since the last pass then stop
  10. 9return the K and d with the least v

K-step. Line L3 moves the scaling into the plant: it multiplies the rows of C1C_1 and D12D_{12} for z1z_1 by dd, and it divides the columns of B1B_1 and D21D_{21} for w1w_1 by dd. Then Fl(Pd,K)=D Fl(P,K) D−1\mathcal{F}_l(P_d, K) = D\,\mathcal{F}_l(P, K)\,D^{-1} for every KK. Line L4 runs the two-Riccati synthesis on PdP_d: a bisection on γ\gamma finds γopt(Pd)\gamma_{\rm opt}(P_d), and the central controller at a level a little above it gives KK. The code repeats the functions of the two-Riccati page, so that the file stands alone.

D-step. Lines L5 to L7 compute the frequency responses of the unscaled loop once and then minimize the function ϕ(t)=max⁡ωσˉ(DtM(jω)Dt−1)\phi(t) = \max_\omega \bar\sigma(D_t M(j\omega) D_t^{-1}) with Dt=diag(etI,I)D_t = \mathrm{diag}(e^t I, I). Each term is convex in tt (Sezginer and Overton 1990), so the maximum is convex, and the golden section search on [−8,8][-8, 8] finds its minimum to the tolerance.

Example

The plant is x˙=x+w1+w2+u\dot x = x + w_1 + w_2 + u, with z1=0.5xz_1 = 0.5 x, z2=xz_2 = x, z3=uz_3 = u and y=x+w3y = x + w_3. The uncertainty block is w1=Δz1w_1 = \Delta z_1: a complex scalar uncertainty that makes the pole 1+0.5 Δ1 + 0.5\,\Delta. The performance block maps (w2,w3)(w_2, w_3), a load and a sensor noise, to (z2,z3)(z_2, z_3). So A=1A = 1, B1=[1,1,0]B_1 = [1, 1, 0], B2=1B_2 = 1, C1=[0.5;1;0]C_1 = [0.5; 1; 0], D12=[0;0;1]D_{12} = [0; 0; 1], C2=1C_2 = 1 and D21=[0,0,1]D_{21} = [0, 0, 1]. The grid has 321 frequencies from 10−410^{-4} to 10410^4 and ω=0\omega = 0, and the K-step uses 1+δ=1.021 + \delta = 1.02.

pass dd in K-step γopt(Pd)\gamma_{\rm opt}(P_d) K(s)K(s) peak at old dd new dd vv
1 1 3.06155 −177.992/(s+60.0728)-177.992/(s + 60.0728) 3.12213 1.41421 3.09689
2 1.41421 3.00002 −173.692/(s+59.7749)-173.692/(s + 59.7749) 3.05938 1.41421 3.05938
3 1.41421 3.00002 same 3.05938 1.41421 3.05938

The third pass changes nothing, so the iteration stops. These are measurements of the code. The bound on the peak of μ\mu goes from 3.096893.09689 for the plain H-infinity controller to 3.059383.05938. The closed loop poles of the final controller are −56.768-56.768 and −2.007-2.007.

Here the K-step optimum can be checked by hand. With d=2d = \sqrt 2 the scaled plant has B1B1T=C1TC1=3/2B_1 B_1^T = C_1^T C_1 = 3/2, so both Riccati equations are (1−1.5 γ−2)X2−2X−1.5=0(1 - 1.5\,\gamma^{-2}) X^2 - 2X - 1.5 = 0. At γ=3\gamma = 3 this is 56X2−2X−1.5=0\tfrac56 X^2 - 2X - 1.5 = 0, with the stabilizing root X=Y=3X = Y = 3, so ρ(XY)=γ2\rho(XY) = \gamma^2 and γopt(P2)=3\gamma_{\rm opt}(P_{\sqrt 2}) = 3. The plant is symmetric under d→2/dd \to 2/d, and the scan of γopt(Pd)\gamma_{\rm opt}(P_d) over dd has its least value at d=2d = \sqrt 2. Since there are two full blocks, the scaled bound equals μ\mu at each frequency (Packard and Doyle 1993). But a constant dd for all frequencies can still be conservative.

Correctness

The method is a heuristic for the problem with μ\mu, and it is a descent method for the problem with constant scalings. Let J(K,d)=∥D Fl(P,K) D−1∥∞J(K, d) = \|D\,\mathcal{F}_l(P, K)\,D^{-1}\|_\infty. Three facts give the descent:

  1. Scaling the plant. Fl(Pd,K)=D Fl(P,K) D−1\mathcal{F}_l(P_d, K) = D\,\mathcal{F}_l(P, K)\,D^{-1}, because DD acts only on the channels z1z_1 and w1w_1, which do not touch uu and yy directly. So the K-step minimizes J(⋅,d)J(\cdot, d) over all stabilizing controllers, up to the bisection tolerance and the factor 1+δ1 + \delta.
  2. Convex D-step. t↦σˉ(etEMe−tE)t \mapsto \bar\sigma(e^{tE} M e^{-tE}) is convex for each fixed complex matrix MM and diagonal EE (Sezginer and Overton 1990). A maximum of convex functions is convex. So golden section search finds the minimum of the grid function to its tolerance, provided the minimum lies inside [−8,8][-8, 8].
  3. Descent. Take the true norm in place of the grid maximum and exact arithmetic. Let vk=J(Kk,dk)v_k = J(K_k, d_k) after pass kk. The next K-step gives γopt(Pdk)≤J(Kk,dk)=vk\gamma_{\rm opt}(P_{d_k}) \le J(K_k, d_k) = v_k, because KkK_k is one of the candidates. The new controller has J(Kk+1,dk)<(1+δ) γopt(Pdk)J(K_{k+1}, d_k) < (1 + \delta)\,\gamma_{\rm opt}(P_{d_k}), and the D-step can only lower this. So vk+1<(1+δ) vkv_{k+1} < (1 + \delta)\,v_k. With δ→0\delta \to 0 and exact steps the sequence is nonincreasing, and since it is bounded below by 0 it converges.

A limit of the sequence is a point where neither step can improve. Such a point need not be a global optimum of JJ, because JJ is not jointly convex in KK and DD. The proofs are in proofs/correctness.md; the convexity result and the two-Riccati theorem are cited.

Proof: The K-step and D-step of D-K iteration each lower the scaled bound, up to the back offfull

Notation is that of the page. The plant is in the normalized form of the two-Riccati page. The uncertainty block uses the first nzn_z outputs z1z_1 and the first nwn_w inputs w1w_1, and the rows of D12D_{12} for z1z_1 and the columns of D21D_{21} for w1w_1 are zero. For d>0d > 0 put Dz=diag(dInz,I)D_z = \mathrm{diag}(d I_{n_z}, I) and Dw=diag(dInw,I)D_w = \mathrm{diag}(d I_{n_w}, I), and J(K,d)=∥Dz Fl(P,K) Dw−1∥∞J(K, d) = \|D_z\,\mathcal{F}_l(P, K)\,D_w^{-1}\|_\infty. Two results are cited: the two-Riccati theorem (Doyle, Glover, Khargonekar and Francis 1989), with the bisection proof of its page, and the convexity theorem of Sezginer and Overton (1990).

Claim 1: scaling the plant scales the closed loop

Let PdP_d have C1d=DzC1C_1^d = D_z C_1, D12d=DzD12D_{12}^d = D_z D_{12}, B1d=B1Dw−1B_1^d = B_1 D_w^{-1} and D21d=D21Dw−1D_{21}^d = D_{21} D_w^{-1}, with AA, B2B_2 and C2C_2 unchanged. Then for every controller KK, Fl(Pd,K)=Dz Fl(P,K) Dw−1\mathcal{F}_l(P_d, K) = D_z\,\mathcal{F}_l(P, K)\,D_w^{-1}. If PP is normalized, so is PdP_d.

Proof. The closed loop of PP with K=(AK,BK,CK,DK)K = (A_K, B_K, C_K, D_K) has

Acl=[A+B2DKC2B2CKBKC2AK],Bcl=[B1+B2DKD21BKD21],Ccl=[C1+D12DKC2  D12CK],Dcl=D12DKD21.A_{\rm cl} = \begin{bmatrix} A + B_2 D_K C_2 & B_2 C_K \\ B_K C_2 & A_K \end{bmatrix}, \quad B_{\rm cl} = \begin{bmatrix} B_1 + B_2 D_K D_{21} \\ B_K D_{21} \end{bmatrix}, \quad C_{\rm cl} = [C_1 + D_{12} D_K C_2 \ \ D_{12} C_K], \quad D_{\rm cl} = D_{12} D_K D_{21}.

AclA_{\rm cl} uses only AA, B2B_2, C2C_2 and KK, so it does not change. Every term of BclB_{\rm cl} and DclD_{\rm cl} ends in B1B_1 or D21D_{21}, so in PdP_d it is multiplied by Dw−1D_w^{-1} on the right. Every term of CclC_{\rm cl} and DclD_{\rm cl} starts with C1C_1 or D12D_{12}, so it is multiplied by DzD_z on the left. Hence the transfer function Ccl(sI−Acl)−1Bcl+DclC_{\rm cl}(sI - A_{\rm cl})^{-1} B_{\rm cl} + D_{\rm cl} becomes Dz(⋅)Dw−1D_z(\cdot)D_w^{-1}.

For the normal form: D12dTD12d=D12TDz2D12=D12TD12D_{12}^{dT} D_{12}^d = D_{12}^T D_z^2 D_{12} = D_{12}^T D_{12}, because the rows of D12D_{12} that DzD_z scales are zero. In the same way D12dTC1d=D12TC1=0D_{12}^{dT} C_1^d = D_{12}^T C_1 = 0, D21dD21dT=D21D21TD_{21}^d D_{21}^{dT} = D_{21} D_{21}^T and B1dD21dT=B1Dw−2D21T=B1D21T=0B_1^d D_{21}^{dT} = B_1 D_w^{-2} D_{21}^T = B_1 D_{21}^T = 0, since the columns of D21D_{21} that DwD_w scales are zero. The stabilizability and detectability assumptions with B2B_2 and C2C_2 do not change. For (A,B1d)(A, B_1^d) and (C1d,A)(C_1^d, A), the scaling by an invertible matrix changes neither the controllable nor the observable subspace. □\square

So the K-step at scale dd solves min⁡KJ(K,d)\min_K J(K, d), up to the bisection and the back off: with γd=γopt(Pd)\gamma_d = \gamma_{\rm opt}(P_d), every stabilizing KK has J(K,d)≥γdJ(K, d) \ge \gamma_d, and the central controller at level γ\gamma with γ>γd\gamma > \gamma_d has J(K,d)<γJ(K, d) < \gamma.

Claim 2: the D-step function is convex in log d

For any finite set of complex matrices M1,…,MfM_1, \ldots, M_f of size p×mp \times m, the function ϕ(t)=max⁡iσˉ(Dz(et)MiDw(et)−1)\phi(t) = \max_i \bar\sigma(D_z(e^t) M_i D_w(e^t)^{-1}) is convex on R\mathbb{R}.

Proof. Embed MiM_i in the square matrix Ni=[0Mi00]N_i = \begin{bmatrix} 0 & M_i \\ 0 & 0 \end{bmatrix} of size p+mp + m, and let E=diag(Ez,Ew)E = \mathrm{diag}(E_z, E_w) with Ez=diag(Inz,0)E_z = \mathrm{diag}(I_{n_z}, 0) and Ew=diag(Inw,0)E_w = \mathrm{diag}(I_{n_w}, 0). Then etENie−tE=[0DzMiDw−100]e^{tE} N_i e^{-tE} = \begin{bmatrix} 0 & D_z M_i D_w^{-1} \\ 0 & 0 \end{bmatrix}, which has the same largest singular value as DzMiDw−1D_z M_i D_w^{-1}. The matrices tEtE for t∈Rt \in \mathbb{R} are diagonal, so they commute and form a convex set. By the theorem of Sezginer and Overton (1990), t↦σˉ(etENie−tE)t \mapsto \bar\sigma(e^{tE} N_i e^{-tE}) is convex. The pointwise maximum of finitely many convex functions is convex. □\square

Claim 3: golden section search finds the minimum of a convex function

Let ϕ\phi be convex and continuous on [a,b][a, b]. Golden section search keeps an interval that contains a minimizer of ϕ\phi on [a,b][a, b], and the interval shrinks by the factor r=(5−1)/2r = (\sqrt5 - 1)/2 at each step.

Proof. Let a<x1<x2<ba < x_1 < x_2 < b be the two inner points, and let ϕ(x1)≤ϕ(x2)\phi(x_1) \le \phi(x_2). Take any x∈(x2,b]x \in (x_2, b] and write x2=λx1+(1−λ)xx_2 = \lambda x_1 + (1 - \lambda) x with λ∈(0,1)\lambda \in (0, 1). Convexity gives ϕ(x2)≤λϕ(x1)+(1−λ)ϕ(x)\phi(x_2) \le \lambda \phi(x_1) + (1 - \lambda) \phi(x). If ϕ(x)<ϕ(x2)\phi(x) < \phi(x_2), the right side is below λϕ(x2)+(1−λ)ϕ(x2)=ϕ(x2)\lambda \phi(x_2) + (1 - \lambda) \phi(x_2) = \phi(x_2), which is impossible. So ϕ(x)≥ϕ(x2)≥ϕ(x1)\phi(x) \ge \phi(x_2) \ge \phi(x_1) for every x>x2x > x_2, and a minimizer on [a,b][a, b] lies in [a,x2][a, x_2], which the code keeps. The other case is symmetric. The choice x1=b−r(b−a)x_1 = b - r(b - a), x2=a+r(b−a)x_2 = a + r(b - a) with r2=1−rr^2 = 1 - r makes the kept inner point one of the new inner points, so the new interval has length r(b−a)r(b - a). □\square

If the minimizer of ϕ\phi on R\mathbb{R} lies outside [−8,8][-8, 8], the search returns the best point of the interval, near an end. The page lists this as a pitfall.

Claim 4: descent up to the back off

Use the true norm in place of the grid maximum, and exact arithmetic. Let pass kk end with (Kk,dk)(K_k, d_k) and vk=J(Kk,dk)=min⁡dJ(Kk,d)v_k = J(K_k, d_k) = \min_d J(K_k, d). Let the next K-step use the level γ=(1+δ) h\gamma = (1 + \delta)\,h with γdk≤h≤(1+ϵ) γdk\gamma_{d_k} \le h \le (1 + \epsilon)\,\gamma_{d_k} from the bisection. Then γdk≤vk\gamma_{d_k} \le v_k and vk+1<(1+δ)(1+ϵ) vkv_{k+1} < (1 + \delta)(1 + \epsilon)\,v_k.

Proof. KkK_k stabilizes the plant, so by Claim 1 it is one candidate for min⁡KJ(K,dk)\min_K J(K, d_k), and γdk≤J(Kk,dk)=vk\gamma_{d_k} \le J(K_k, d_k) = v_k. The central controller Kk+1K_{k+1} at level γ>γdk\gamma > \gamma_{d_k} has J(Kk+1,dk)<γ≤(1+δ)(1+ϵ) γdkJ(K_{k+1}, d_k) < \gamma \le (1 + \delta)(1 + \epsilon)\,\gamma_{d_k}. The D-step minimizes J(Kk+1,⋅)J(K_{k+1}, \cdot), so vk+1≤J(Kk+1,dk)v_{k+1} \le J(K_{k+1}, d_k). Put the three bounds together. □\square

With δ=ϵ=0\delta = \epsilon = 0 in the limit, the sequence vkv_k is nonincreasing and bounded below by 0, so it converges. Nothing in the proof says that the limit is the minimum of JJ over (K,d)(K, d); a point where neither step improves can be a local optimum of a nonconvex function.

Claim 5: the K-step optimum of the example at d = sqrt 2 is 3

For the example plant with d=2d = \sqrt 2, γopt(Pd)=3\gamma_{\rm opt}(P_d) = 3.

Proof. The scaled plant has B1d=[1/2,1,0]B_1^d = [1/\sqrt 2, 1, 0] and C1d=[1/2;1;0]C_1^d = [1/\sqrt 2; 1; 0], so B1dB1dT=C1dTC1d=3/2B_1^d B_1^{dT} = C_1^{dT} C_1^d = 3/2, and B2=C2=1B_2 = C_2 = 1, A=1A = 1. Both Riccati equations are (1.5 γ−2−1)X2+2X+1.5=0(1.5\,\gamma^{-2} - 1) X^2 + 2X + 1.5 = 0, so Y=XY = X. For γ2>1.5\gamma^2 > 1.5 put c=1−1.5 γ−2>0c = 1 - 1.5\,\gamma^{-2} > 0. The stabilizing root is X=(1+1+1.5c)/c>0X = (1 + \sqrt{1 + 1.5c})/c > 0, since then A+RX=1−cX=−1+1.5c<0A + RX = 1 - cX = -\sqrt{1 + 1.5c} < 0. The coupling condition is X2<γ2X^2 < \gamma^2, that is X<γX < \gamma. Now X(γ)X(\gamma) decreases as γ\gamma grows, because cc grows and XX is decreasing in cc, while γ\gamma grows. At γ=3\gamma = 3: c=5/6c = 5/6 and X=(1+2.25)⋅6/5=3X = (1 + \sqrt{2.25}) \cdot 6/5 = 3, so X=γX = \gamma. So the conditions hold exactly for γ>3\gamma > 3. For γ2≤1.5\gamma^2 \le 1.5 the first condition fails, since then the Riccati equation has no stabilizing solution with X≥0X \ge 0: with c≤0c \le 0 the closed loop 1−cX≥11 - cX \ge 1 for X≥0X \ge 0. □\square

What the tests check

  • Claim 1 numerically: the frequency response of the scaled loop equals DzMDw−1D_z M D_w^{-1} entry by entry at three frequencies and three values of dd, and the scaled plant keeps D12TC1=0D_{12}^T C_1 = 0 and B1D21T=0B_1 D_{21}^T = 0.
  • Claim 5: the bisection gives γopt(P2)=3\gamma_{\rm opt}(P_{\sqrt 2}) = 3 within 10−810^{-8}, and γopt(Pd)=γopt(P2/d)>3\gamma_{\rm opt}(P_d) = \gamma_{\rm opt}(P_{2/d}) > 3 for three other values of dd.
  • Claims 2 and 3 against brute force: for two plants, the golden section result is at least as good as each of 31 values of log⁡d\log d in [−3,3][-3, 3], and the sampled function satisfies the midpoint convexity inequality.
  • Claim 4: along the iteration for two plants, γdk≤vk\gamma_{d_k} \le v_k and vk+1≤1.02 vkv_{k+1} \le 1.02\,v_k (with a relative slack of 10−310^{-3} for the grid), and each vkv_k lies between the K-step optimum and 1.021.02 times it.
  • The final controller gives a Hurwitz closed loop, and its scaled bound is at most the unscaled peak of the plain H-infinity controller.
  • The example values on the page: d=2d = \sqrt 2, the first K-step optimum 3.061553.06155 and the last one 33.

Complexity

Let nn be the number of plant states, qq the larger of the number of outputs zz and inputs ww, and ff the number of grid frequencies. These bounds are for the real-RAM model with dense factorizations.

Per iteration. The K-step costs O(k(cn3+n2q))O(k(c n^3 + n^2 q)) as on the two-Riccati page, with kk bisection steps and cc Newton steps per sign function. The closed loop has 2n2n states, so the frequency responses cost O(f(n3+n2q))O(f(n^3 + n^2 q)). Each value of ϕ\phi costs ff largest singular values of q×qq \times q matrices, O(fq3)O(f q^3) with a bounded number of Jacobi sweeps. Golden section needs g=O(log⁡(16/tol))g = O(\log(16/\text{tol})) values. The total per iteration is O(k(cn3+n2q)+f(n3+n2q)+gfq3)O(k(c n^3 + n^2 q) + f(n^3 + n^2 q) + g f q^3).

Number of iterations. No useful bound on the number of passes tt is known. The convergence result above only says that the bounds decrease and converge, not how fast or to what. In practice a few passes are typical (rule of thumb); the example stops after three.

Properties

  • The bound vkv_k is an upper bound on sup⁡ωμΔ(M(jω))\sup_\omega \mu_{\boldsymbol\Delta}(M(j\omega)) only on the grid. Between grid points the true peak can be larger.
  • With full complex blocks only and 2S+F≤32S + F \le 3, where SS is the number of repeated scalar blocks and FF the number of full blocks, the scaled bound is equal to μ\mu at each frequency (Packard and Doyle 1993). With more blocks it can be strictly larger.
  • The controller order is the order of PP plus the order of the scalings. A constant DD adds no states, but a rational D(s)D(s) of order rr adds 2r2r states per block, one copy on each side.
  • The method is deterministic, and it depends on the start d=1d = 1. A different start can give a different limit.

Variants and improvements

  • Frequency-dependent scalings. The standard method solves the D-step separately at each grid frequency, which gives values d(ω)d(\omega), then fits a stable, minimum phase rational D(s)D(s) to them, and it puts D(s)D(s) into the plant for the next K-step (Skogestad and Postlethwaite 2005, section 8.12). This is less conservative than a constant DD but the fit adds states and can break the descent property.
  • LMI K-step. The K-step can use LMI-based synthesis, which needs no rank assumptions on the scaled plant.
  • Real uncertainty. For real parametric blocks, the upper bound of Fan, Tits and Doyle (1991) adds a second scaling GG. Synthesis methods use this bound in place of the D-scale bound, with a similar alternation.

When to use it

Use D-K iteration when the uncertainty has a clear block structure, a robust performance specification is needed, and plain mixed sensitivity design is too conservative because it treats all uncertainty as one block. Check the result by mu-analysis with both bounds on a fine grid. If the uncertainty is a single full block, plain H-infinity synthesis is enough, because then μ=σˉ\mu = \bar\sigma.

Pitfalls

  • Local optima. The joint problem is not convex. Try other starting scalings, and compare with an upper bound from analysis.
  • Back off. Near γopt\gamma_{\rm opt} the central controller has very fast poles. The factor 1+δ1 + \delta is a rule of thumb; it makes the descent hold only up to that factor, so do not stop on a single small rise.
  • Grid. A coarse grid can miss a sharp peak. The bound vv is then too optimistic.
  • Fit order. With frequency-dependent scalings, a high order fit gives a high order controller, and a low order fit can make the bound worse than the values d(ω)d(\omega) predict.
  • Scaling range. If the best dd is near the end of the search interval, the uncertainty channel is almost decoupled from the performance channel. Then widen the interval or check the plant.
  • Sign conventions. The controller is wired as u=Kyu = K y. Convert from sources that use u=−Kyu = -K y or positive feedback before you compare.

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()
dk_iteration.py 239 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dk-iteration/. The authors are listed in prov/QSHHP3.jsonl.

"""D-K iteration with constant D scales.

The generalized plant has the normalized form of the two-Riccati 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". The controller is wired as u = K y.

The uncertainty structure has two full complex blocks: the first nz rows
of z feed the first nw entries of w through the uncertainty Delta, and
the rest of z and w form the performance block. The D scale is
diag(d I, I) on z and diag(d I, I) on w, with d > 0. The rows of z
reached by u and the entries of w that reach y must be in the
performance block, so that scaling keeps the normalized form.

The K-step is the two-Riccati synthesis of the scaled plant (bisection
on gamma and the central controller). It repeats the code of the
two-Riccati page so that this file stands alone. The D-step minimizes the
peak over a frequency grid of the largest singular value of
D M(jw) D^-1 over log d by golden section search.
"""

import math

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

__all__ = [
    "riccati", "is_hurwitz", "gamma_feasible", "optimal_gamma",
    "central_controller", "closed_loop", "scale_plant", "responses",
    "scaled_peak", "d_step", "k_step", "dk_iteration",
]


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)


# ------------------------------------------- K-step: two-Riccati synthesis

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 _rho(m):
    return max(abs(r) for r in polyroots(charpoly(_flo(m))))


def riccati(a, r, q):
    """Stabilizing X of A^T X + X A + X R X + Q = 0 (A + R X Hurwitz), or None."""
    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 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 gamma_feasible(p, gamma):
    """The three conditions of Doyle, Glover, Khargonekar and Francis. 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)
    x = riccati(a, sub(scale(g2, mul(b1, transpose(b1))), mul(b2, transpose(b2))),
                mul(transpose(c1), c1))
    if x is None or not is_pos_def(x, -1e-9 * (1.0 + _big(x))):
        return False, x, None
    y = riccati(transpose(a), sub(scale(g2, mul(transpose(c1), c1)), mul(transpose(c2), c2)),
                mul(b1, transpose(b1)))
    if y is None or not is_pos_def(y, -1e-9 * (1.0 + _big(y))):
        return False, x, y
    return _rho(mul(x, y)) < gamma * gamma * (1.0 - 1e-9), x, y


def optimal_gamma(p, rtol=1e-5):
    """Bisection for the smallest gamma that passes gamma_feasible."""
    lo, hi = 0.0, 1.0
    while not gamma_feasible(p, hi)[0]:
        lo, hi = hi, 2.0 * hi
        if hi > 1e8:
            raise ValueError("no gamma below 1e8 passes the test")
    while hi - lo > rtol * hi:
        g = 0.5 * (lo + hi)
        if gamma_feasible(p, g)[0]:
            hi = g
        else:
            lo = g
    return hi


def central_controller(p, gamma):
    """(A_K, B_K, C_K, D_K) of the central controller at gamma."""
    ok, x, y = gamma_feasible(p, gamma)
    if not ok:
        raise ValueError("gamma does not pass the three 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))
    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))), add(mul(b2, f), mul(mul(z, l), c2)))
    return ak, scale(-1.0, mul(z, l)), f, zeros(len(f), len(c2))


def closed_loop(p, k):
    """(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)]])
    return acl, bcl, ccl, mul(mul(d12, dk), d21)


# ------------------------------------------------------------ the D scales

def scale_plant(p, d, nz, nw):
    """Plant with z1 -> d z1 (first nz rows of z) and w1 -> w1 / d (first nw entries of w)."""
    q = {k: _flo(v) for k, v in p.items()}
    q["C1"] = [[(d if i < nz else 1.0) * v for v in row] for i, row in enumerate(q["C1"])]
    q["D12"] = [[(d if i < nz else 1.0) * v for v in row] for i, row in enumerate(q["D12"])]
    q["B1"] = [[v / d if j < nw else v for j, v in enumerate(row)] for row in q["B1"]]
    q["D21"] = [[v / d if j < nw else v for j, v in enumerate(row)] for row in q["D21"]]
    return q


def responses(sys, freqs):
    """The complex matrices M(j w) = C (j w I - A)^-1 B + D for w in freqs."""
    a, b, c, d = sys
    n = len(a)
    bc = [[complex(v) for v in row] for row in b]
    out = []
    for w in freqs:
        m = [[(1j * w if i == j else 0.0) - a[i][j] for j in range(n)] for i in range(n)]
        out.append(add(mul(c, solve(m, bc)), d))
    return out


def scaled_peak(ms, d, nz, nw):
    """max over the grid of the largest singular value of D M D^-1."""
    best = 0.0
    for m in ms:
        sm = [[v * (d if i < nz else 1.0) / (d if j < nw else 1.0) for j, v in enumerate(row)]
              for i, row in enumerate(m)]
        best = max(best, norm2(sm))
    return best


def d_step(ms, nz, nw, lo=-8.0, hi=8.0, tol=1e-6):
    """Golden section search on log d. Return (d, peak)."""
    f = (lambda t: scaled_peak(ms, math.exp(t), nz, nw))
    r = (math.sqrt(5.0) - 1.0) / 2.0
    a, b = lo, hi
    x1, x2 = b - r * (b - a), a + r * (b - a)
    f1, f2 = f(x1), f(x2)
    while b - a > tol:  # @line L6
        if f1 <= f2:
            b, x2, f2 = x2, x1, f1
            x1 = b - r * (b - a)
            f1 = f(x1)
        else:
            a, x1, f1 = x1, x2, f2
            x2 = a + r * (b - a)
            f2 = f(x2)
    t = x1 if f1 <= f2 else x2
    return math.exp(t), min(f1, f2)  # @line L7


def k_step(p, d, nz, nw, backoff=1.02):
    """Two-Riccati synthesis on the scaled plant. Return (gamma_opt, gamma, K)."""
    ps = scale_plant(p, d, nz, nw)  # @line L3
    gopt = optimal_gamma(ps)
    g = backoff * gopt
    return gopt, g, central_controller(ps, g)  # @line L4


def dk_iteration(p, nz, nw, freqs, iters=6, backoff=1.02, rtol=1e-3):
    """Return (K, d, history). history[i] = (gamma_opt of K-step, peak after D-step, d)."""
    d = 1.0  # @line L1
    history = []
    best = None
    for _ in range(iters):  # @line L2
        gopt, g, k = k_step(p, d, nz, nw, backoff)
        ms = responses(closed_loop(p, k), freqs)  # @line L5
        d, peak = d_step(ms, nz, nw)
        history.append((gopt, peak, d))
        if best is None or peak < best[0]:
            best = (peak, k, d)
        if len(history) > 1 and history[-2][1] - peak <= rtol * peak:  # @line L8
            break
    return best[1], best[2], history  # @line L9
test_dk_iteration.py 129 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/dk-iteration/. The authors are listed in prov/QSHHP3.jsonl.

import math
import random

import ctlmat as cm
from dk_iteration import (
    central_controller,
    closed_loop,
    d_step,
    dk_iteration,
    is_hurwitz,
    optimal_gamma,
    responses,
    scale_plant,
    scaled_peak,
)

# x' = x + w1 + w2 + u. The uncertainty block maps z1 = 0.5 x to w1. The
# performance block maps w2 (load) and w3 (sensor noise) to z2 = x and z3 = u.
PLANT = {"A": [[1]], "B1": [[1, 1, 0]], "B2": [[1]], "C1": [[0.5], [1], [0]],
         "C2": [[1]], "D12": [[0], [0], [1]], "D21": [[0, 0, 1]]}

# A two-state plant with the same block structure.
PLANT2 = {"A": [[0, 1], [2, -1]], "B1": [[0.3, 1, 0], [1, 0, 0]], "B2": [[0], [1]],
          "C1": [[2, 0], [1, 0], [0, 1], [0, 0]], "C2": [[1, 0]],
          "D12": [[0], [0], [0], [1]], "D21": [[0, 0, 1]]}

# A coarse grid keeps the test fast. For both plants the peak of the final
# loop is at w = 0, which the grid contains.
FREQS = [10 ** (e / 4) for e in range(-8, 9)] + [0.0]
BACKOFF = 1.02

_CACHE = {}


def run(p):
    if id(p) not in _CACHE:
        _CACHE[id(p)] = dk_iteration(p, 1, 1, FREQS, iters=3, backoff=BACKOFF)
    return _CACHE[id(p)]


def plain(p):
    # The H-infinity controller with no scaling, d = 1.
    key = ("plain", id(p))
    if key not in _CACHE:
        g = BACKOFF * optimal_gamma(p)
        _CACHE[key] = central_controller(p, g)
    return _CACHE[key]


def test_ctlmat_self_test():
    assert cm._self_test()


def test_scaled_plant_is_the_scaled_closed_loop():
    # A controller for the scaled plant gives the closed loop D M D^-1.
    rng = random.Random(5)
    k = plain(PLANT)
    for d in (0.3, 1.7, 4.0):
        ms = responses(closed_loop(PLANT, k), [0.0, 0.7, 3.0])
        ss = responses(closed_loop(scale_plant(PLANT, d, 1, 1), k), [0.0, 0.7, 3.0])
        for m, s in zip(ms, ss):
            for i in range(3):
                for j in range(3):
                    want = m[i][j] * (d if i == 0 else 1) / (d if j == 0 else 1)
                    assert abs(s[i][j] - want) < 1e-12 * (1 + abs(want))
        # The scaled plant keeps the normalized form.
        q = scale_plant(PLANT, d * rng.uniform(0.5, 2), 1, 1)
        assert cm.mul(cm.transpose(q["D12"]), q["C1"]) == [[0.0]]
        assert cm.mul(q["B1"], cm.transpose(q["D21"])) == [[0.0]]


def test_k_step_closed_form_at_the_best_scale():
    # With d = sqrt(2) both Riccati equations equal X^2 (5/6) - 2 X - 3/2 = 0
    # at gamma = 3, so X = Y = 3 and rho(XY) = gamma^2: gamma_opt = 3.
    g = optimal_gamma(scale_plant(PLANT, math.sqrt(2), 1, 1), 1e-9)
    assert abs(g - 3.0) < 1e-8
    # The plant is symmetric under d -> 2 / d.
    for d in (0.7, 1.0, 1.9):
        g1 = optimal_gamma(scale_plant(PLANT, d, 1, 1), 1e-9)
        g2 = optimal_gamma(scale_plant(PLANT, 2 / d, 1, 1), 1e-9)
        assert abs(g1 - g2) < 1e-7 * g1 and g1 > 3.0


def test_d_step_matches_a_brute_force_grid():
    for p in (PLANT, PLANT2):
        ms = responses(closed_loop(p, plain(p)), FREQS)
        d, v = d_step(ms, 1, 1)
        ts = [i / 5 for i in range(-15, 16)]
        vals = [scaled_peak(ms, math.exp(t), 1, 1) for t in ts]
        # Golden section is at least as good as every grid point, up to the tolerance.
        assert v <= min(vals) * (1 + 1e-9)
        assert abs(v - scaled_peak(ms, d, 1, 1)) < 1e-12
        # The sampled function is convex in log d (Sezginer and Overton).
        for i in range(1, len(vals) - 1):
            assert vals[i] <= 0.5 * (vals[i - 1] + vals[i + 1]) + 1e-12


def test_iteration_is_monotone_up_to_the_backoff():
    for p in (PLANT, PLANT2):
        _, _, hist = run(p)
        for (g0, v0, _), (g1, v1, _) in zip(hist, hist[1:]):
            # gamma_opt of the next K-step is at most the last scaled peak,
            # and the next peak exceeds gamma_opt by at most the backoff.
            assert g1 <= v0 * (1 + 1e-3)
            assert v1 <= BACKOFF * v0 * (1 + 1e-3)
        for g, v, _ in hist:
            assert g * (1 - 1e-3) <= v <= BACKOFF * g * (1 + 1e-3)


def test_result_is_stabilizing_and_beats_plain_h_infinity():
    for p in (PLANT, PLANT2):
        k, d, hist = run(p)
        cl = closed_loop(p, k)
        assert is_hurwitz(cl[0])
        best = scaled_peak(responses(cl, FREQS), d, 1, 1)
        unscaled = scaled_peak(responses(closed_loop(p, plain(p)), FREQS), 1.0, 1, 1)
        assert best <= unscaled
        assert abs(best - min(v for _, v, _ in hist)) < 1e-9 * best


def test_example_values():
    k, d, hist = run(PLANT)
    assert abs(d - math.sqrt(2)) < 1e-5
    assert abs(hist[0][0] - 3.0615528) < 1e-4
    assert abs(hist[-1][0] - 3.0) < 1e-4
    assert hist[-1][1] < BACKOFF * 3.0 * (1 + 1e-4)

History

Doyle (1982) defined the structured singular value and gave its upper bound with diagonal scalings. Safonov (1982) gave a related stability margin for diagonal perturbations. Doyle (1985) is usually cited as the start of mu-synthesis, where the controller and the scalings are improved in turn. Sezginer and Overton (1990) proved the convexity in the logarithm of the scaling that makes the D-step a convex problem. Packard and Doyle (1993) surveyed the complex structured singular value and the cases where the scaled bound is exact. Braatz, Young, Doyle and Morari (1994) proved that computing μ\mu is NP-hard, which explains why synthesis works with the bound.

References

  1. John C. Doyle, Analysis of feedback systems with structured uncertainties, IEE Proceedings D 129(6), 242, 1982, the definition of the structured singular value and the upper bound by diagonal scalings
  2. John C. Doyle, Structured uncertainty in control system design, Proceedings of the 24th IEEE Conference on Decision and Control, 260-265, 1985, the design of controllers against structured uncertainty with the structured singular value
  3. Andrew Packard and John C. Doyle, The complex structured singular value, Automatica 29(1), 71-109, 1993, the upper bound by D scales, the cases where it is exact, and the main loop theorem
  4. R. S. Sezginer and Michael L. Overton, The largest singular value of e^X A e^-X is convex on convex sets of commuting matrices, IEEE Transactions on Automatic Control 35(2), 229-230, 1990, the convexity of the scaled largest singular value in the logarithm of the scaling
  5. Richard D. Braatz, Peter M. Young, John C. Doyle and Manfred Morari, Computational complexity of mu calculation, IEEE Transactions on Automatic Control 39(5), 1000-1002, 1994, the NP-hardness of computing mu
  6. Michael G. Safonov, Stability margins of diagonally perturbed multivariable feedback systems, IEE Proceedings D 129(6), 251, 1982, the multivariable stability margin for diagonal perturbations
  7. Michael K. H. Fan, Andre L. Tits and John C. Doyle, Robustness in the presence of mixed parametric uncertainty and unmodeled dynamics, IEEE Transactions on Automatic Control 36(1), 25-38, 1991, the upper bound for mixed real and complex uncertainty with D and G scalings
  8. Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, Chapter 11, Structured Singular Value
  9. Sigurd Skogestad and Ian Postlethwaite, Multivariable Feedback Control, Analysis and Design, second edition, Wiley, 2005, Section 8.12, mu-synthesis and DK-iteration

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-iteration
  • 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