Algorithm Search⌘K

Algorithmcore

Linear quadratic Gaussian control

Also called LQG, LQG regulator.

Combines a Kalman filter with LQR on the state estimate, which is optimal for linear systems with Gaussian noise by the separation theorem.

Time
O(i n^3 + n^2 (m + p)) worst
Space
O(n^2) extra
Where
i = the number of sign function iterations, usually 10 to 30; m = the number of inputs; n = the number of states; p = the number of outputs
Properties
deterministicnot exactofflineiterative
Origin
Rudolf E. Kalman, Richard S. Bucy, Peter D. Joseph, Julius T. Tou, Michael Athans, 1961

Linear quadratic Gaussian (LQG) control is the optimal output feedback for a linear plant with Gaussian white process and measurement noise and an average quadratic cost. The controller is a Kalman-Bucy filter that estimates the state, followed by the LQR gain applied to the estimate. The two gains come from two independent algebraic Riccati equations, one for the regulator and one for the filter. That the two designs can be done apart and still give the optimal controller is the separation theorem. The optimality is with respect to the noise model only: an LQG loop can have arbitrarily small gain and phase margins, as Doyle's example shows.

In plain words

We want to steer a machine whose state we cannot see directly. We only get noisy sensor readings, and random pushes act on the machine. LQG splits the job in two. The first part is an estimator: it runs a copy of the machine's model, compares the predicted reading with the real one, and corrects its guess by a fixed amount of the difference. The second part is the best controller for the case where the state is known, and it acts on the guess as if the guess were the truth. Each part is designed on its own by solving one matrix equation. With the noise model and the cost of the problem, no other controller does better on average. But "best on average" does not mean "robust": a small change in the machine can still break the loop.

The problem

Input: matrices A∈Rn×nA \in \mathbb{R}^{n \times n}, B∈Rn×mB \in \mathbb{R}^{n \times m}, C∈Rp×nC \in \mathbb{R}^{p \times n} of the plant

x˙=Ax+Bu+w,y=Cx+v,\dot x = A x + B u + w, \qquad y = C x + v,

where ww and vv are independent zero mean Gaussian white noises with intensities W=WT≥0W = W^T \ge 0 and V=VT>0V = V^T > 0, and the weights Q=QT≥0Q = Q^T \ge 0 and R=RT>0R = R^T > 0 of the cost

J=lim⁡T→∞1T E∫0T(xTQx+uTRu)dt.J = \lim_{T \to \infty} \frac1T\, \mathbb{E} \int_0^T \left(x^T Q x + u^T R u\right) dt.

Assumptions: (A,B)(A, B) stabilizable, (Q1/2,A)(Q^{1/2}, A) detectable, (C,A)(C, A) detectable and (A,W1/2)(A, W^{1/2}) stabilizable.

Output: a dynamic controller x^˙=Acx^+Bcy\dot{\hat x} = A_c \hat x + B_c y, u=−Ccx^u = -C_c \hat x, that uses only past outputs and minimizes JJ over all such causal output feedbacks.

The answer is u=−Kx^u = -K \hat x, where x^\hat x is the steady state Kalman-Bucy estimate. Here LoL_o is the filter gain; the letter LL alone is kept for loop transfer functions.

The algorithm

  1. LQG(A, B, C, Q, R, W, V)
  2. 1P ← CARE-SOLVE(A, B, Q, R) ▷ regulator: Aᵀ P + P A - P B R⁻¹ Bᵀ P + Q = 0
  3. 2K ← R⁻¹ Bᵀ P
  4. 3S ← CARE-SOLVE(Aᵀ, Cᵀ, W, V) ▷ filter: A S + S Aᵀ - S Cᵀ V⁻¹ C S + W = 0
  5. 4L_o ← S Cᵀ V⁻¹
  6. 5return controller x̂' = (A - B K - L_o C) x̂ + L_o y, u = -K x̂
  7. CARE-SOLVE(A, B, Q, R) ▷ stabilizing solution by the matrix sign function
  8. 6G ← B R⁻¹ Bᵀ; H ← [[A, -G], [-Q, -Aᵀ]] ▷ Hamiltonian matrix, 2n × 2n
  9. 7Z ← H; repeat c ← |det Z|^(-1/(2n)); Z ← (c Z + (c Z)⁻¹) / 2 until Z stops changing
  10. 8P ← least squares solution of [Z₁₂; Z₂₂ + I] P = -[Z₁₁ + I; Z₂₁]
  11. 9twice: P ← solution of (A - G P)ᵀ P' + P' (A - G P) + Q + P G P = 0

Lines L1 to L4 are the whole design: two Riccati equations, one for the regulator and one for the filter. Line L3 uses duality: the filter equation is the regulator equation for the data (AT,CT,W,V)(A^T, C^T, W, V), so the same solver serves both. Line L5 returns the controller in state-space form. Its order is nn, the order of the plant.

Any method for the stabilizing CARE solution can be used in lines L1 and L3, for example the Schur method. This page uses the matrix sign function (Roberts 1980). Line L7 is Newton's iteration for sign(H)\mathrm{sign}(H), with the determinant scaling of Byers (1987), which cuts the number of steps when the eigenvalues of HH are far from ±1\pm 1. The limit ZZ has Z+IZ + I equal to 0 on the stable invariant subspace of the Hamiltonian matrix, and that subspace is the range of [I;P][I; P]. Line L8 reads PP off from this fact. Line L9 runs two steps of Kleinman's iteration, which is Newton's method on the CARE and removes the rounding error of line L8. The code solves each Lyapunov equation by its Kronecker form, which is fine for the small nn of the tests.

Example

Take the double integrator with the position measured: A=[0100]A = \begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix}, B=[01]B = \begin{bmatrix} 0 \\ 1 \end{bmatrix}, C=[10]C = \begin{bmatrix} 1 & 0 \end{bmatrix}, with Q=IQ = I, R=1R = 1, W=IW = I and V=1V = 1. The two Riccati equations have the same solution, because the data are symmetric under duality:

P=S=[3113],K=[13],Lo=[31].P = S = \begin{bmatrix} \sqrt3 & 1 \\ 1 & \sqrt3 \end{bmatrix}, \qquad K = \begin{bmatrix} 1 & \sqrt3 \end{bmatrix}, \qquad L_o = \begin{bmatrix} \sqrt3 \\ 1 \end{bmatrix}.

Eigenvalues. A−BKA - B K and A−LoCA - L_o C both have the characteristic polynomial s2+3 s+1s^2 + \sqrt3\, s + 1, with roots −32±j2-\tfrac{\sqrt3}{2} \pm \tfrac{j}{2}. The closed loop of order 4 has the polynomial (s2+3 s+1)2(s^2 + \sqrt3\, s + 1)^2, as the separation principle says.

Controller. Ac=A−BK−LoC=[−31−2−3]A_c = A - B K - L_o C = \begin{bmatrix} -\sqrt3 & 1 \\ -2 & -\sqrt3 \end{bmatrix}, and the controller from yy to −u-u has the transfer function

C(s)=K(sI−Ac)−1Lo=23 s+1s2+23 s+5.C(s) = K (sI - A_c)^{-1} L_o = \frac{2\sqrt3\, s + 1}{s^2 + 2\sqrt3\, s + 5}.

Cost. The optimal cost is J∗=tr(PW)+tr(SKTRK)=23+63=83≈13.856J^* = \mathrm{tr}(P W) + \mathrm{tr}(S K^T R K) = 2\sqrt3 + 6\sqrt3 = 8\sqrt3 \approx 13.856. The first term is the cost with the full state known; the second is the price of the estimate. The stationary covariance of the closed loop, from a Lyapunov equation, gives the same number. Gains near KK and LoL_o give a higher cost.

Margins. Put a gain kk at the plant input. The closed-loop polynomial is s4+23 s3+5s2+23 k s+ks^4 + 2\sqrt3\, s^3 + 5 s^2 + 2\sqrt3\, k\, s + k. The Routh conditions are k>0k > 0 and 23 k(103−23 k)−12k=k(48−12k)>02\sqrt3\, k (10\sqrt3 - 2\sqrt3\, k) - 12 k = k (48 - 12 k) > 0, so the loop stays Hurwitz exactly for 0<k<40 < k < 4. The LQG loop L(s)=C(s)/s2L(s) = C(s)/s^2 has a phase margin of about 39.0 degrees at ω≈0.726\omega \approx 0.726 rad/s. The LQR loop K(sI−A)−1B=(3 s+1)/s2K (sI - A)^{-1} B = (\sqrt3\, s + 1)/s^2 with the full state keeps every gain k>0k > 0 and has a phase margin of about 72.4 degrees. The estimator costs margin. Loop transfer recovery is one way to get it back.

Correctness

The proof is in proofs/correctness.md. It shows four facts. The sign function iteration converges to sign(H)\mathrm{sign}(H), and line L8 returns the stabilizing CARE solution, because the null space of sign(H)+I\mathrm{sign}(H) + I is the stable invariant subspace of HH; Newton steps from the exact solution do not move it. Line L3 returns the stabilizing filter solution, by duality. In the coordinates (x,x−x^)(x, x - \hat x) the closed-loop matrix is block triangular with diagonal blocks A−BKA - BK and A−LoCA - L_o C. Finally, for any causal output feedback, completing the square with the CARE gives

J=tr(PW)+lim⁡T→∞1T∫0TE (u+Kx)TR(u+Kx) dt,J = \mathrm{tr}(P W) + \lim_{T \to \infty} \frac1T \int_0^T \mathbb{E}\,(u + K x)^T R (u + K x)\, dt,

and splitting x=x^+ex = \hat x + e, with the filter error ee orthogonal to every function of the past outputs, gives J≥tr(PW)+tr(SKTRK)J \ge \mathrm{tr}(P W) + \mathrm{tr}(S K^T R K) with equality exactly for u=−Kx^u = -K \hat x.

Proof: The two Riccati solutions give the LQG controller, its closed loop has the separated eigenvalues, and no output feedback has a lower average costfull

The plant is x˙=Ax+Bu+w\dot x = A x + B u + w, y=Cx+vy = C x + v, with ww and vv independent zero mean Gaussian white noises of intensities W≥0W \ge 0 and V>0V > 0, and x(0)x(0) Gaussian and independent of both. The cost is J=lim⁡T→∞1TE∫0T(xTQx+uTRu) dtJ = \lim_{T \to \infty} \frac1T \mathbb{E} \int_0^T (x^T Q x + u^T R u)\, dt with Q≥0Q \ge 0 and R>0R > 0. The standing assumptions are: (A,B)(A, B) stabilizable, (Q1/2,A)(Q^{1/2}, A) detectable, (C,A)(C, A) detectable and (A,W1/2)(A, W^{1/2}) stabilizable. The input u(t)u(t) may be any function of the past outputs y(s)y(s), s≤ts \le t, for which the closed loop has a stationary regime.

The proof has four parts. Part 1 shows that lines L6 to L9 return the stabilizing solution of the CARE. Part 2 applies Part 1 to the filter equation by duality (lines L3 and L4). Part 3 gives the eigenvalues of the closed loop. Part 4 proves that u=−Kx^u = -K \hat x has the least cost.

Part 1: the sign function step

Let G=BR−1BTG = B R^{-1} B^T and H=[A−G−Q−AT]H = \begin{bmatrix} A & -G \\ -Q & -A^T \end{bmatrix}. With J0=[0I−I0]J_0 = \begin{bmatrix} 0 & I \\ -I & 0 \end{bmatrix}, the matrix J0HJ_0 H is symmetric, so HH is similar to −HT-H^T and its eigenvalues come in pairs λ,−λˉ\lambda, -\bar\lambda.

Lemma 1. Under the assumptions, HH has no eigenvalue on the imaginary axis, and the CARE has a unique stabilizing solution P=PT≥0P = P^T \ge 0. The stable invariant subspace of HH is the range of [IP]\begin{bmatrix} I \\ P \end{bmatrix}.

Proof. This is the theorem on the stabilizing Riccati solution (Kučera 1972). For the last claim: the CARE says H[IP]=[IP](A−GP)H \begin{bmatrix} I \\ P \end{bmatrix} = \begin{bmatrix} I \\ P \end{bmatrix} (A - G P), so the range is invariant under HH and HH acts on it as A−GPA - G P, which is Hurwitz. It has dimension nn, which is the number of eigenvalues of HH in the open left half plane. □\square

Lemma 2. Let H=T diag(J−,J+) T−1H = T \,\mathrm{diag}(J_-, J_+)\, T^{-1} with J−J_- holding the nn eigenvalues with negative real part and J+J_+ the nn with positive real part. The iteration Z0=HZ_0 = H, Zk+1=12(ckZk+ck−1Zk−1)Z_{k+1} = \frac12 (c_k Z_k + c_k^{-1} Z_k^{-1}) with ck>0c_k > 0 converges to sign(H)=T diag(−I,I) T−1\mathrm{sign}(H) = T\, \mathrm{diag}(-I, I)\, T^{-1}.

Proof. Every ZkZ_k is a rational function of HH, so Zk=T diag(fk(J−),fk(J+)) T−1Z_k = T\, \mathrm{diag}(f_k(J_-), f_k(J_+))\, T^{-1}, and it suffices to look at one eigenvalue zz. The map z↦12(cz+1/(cz))z \mapsto \frac12 (c z + 1/(c z)) keeps the sign of the real part: if Re z>0\mathrm{Re}\, z > 0 then Re (cz)>0\mathrm{Re}\, (c z) > 0 and Re (1/(cz))>0\mathrm{Re}\, (1 / (cz)) > 0. Write z′=12(y+1/y)z' = \frac12 (y + 1/y) with y=czy = c z. Then z′−1z′+1=(y−1y+1)2\frac{z' - 1}{z' + 1} = \left(\frac{y - 1}{y + 1}\right)^2, and ∣(y−1)/(y+1)∣<1|(y - 1)/(y + 1)| < 1 when Re y>0\mathrm{Re}\, y > 0. So the eigenvalues go to 11 in the right half plane and to −1-1 in the left, quadratically once they are close. The scaling ck=∣det⁡Zk∣−1/(2n)c_k = |\det Z_k|^{-1/(2n)} only moves the starting point of each step; it does not change the limit (Byers 1987). For a nontrivial Jordan block the same argument holds on the block, because the iteration is a matrix function. □\square

Lemma 3. Let Z=sign(H)Z = \mathrm{sign}(H). Then [Z12Z22+I]P=−[Z11+IZ21]\begin{bmatrix} Z_{12} \\ Z_{22} + I \end{bmatrix} P = -\begin{bmatrix} Z_{11} + I \\ Z_{21} \end{bmatrix}, and this overdetermined system has exactly one solution.

Proof. Z+I=T diag(0,2I) T−1Z + I = T\, \mathrm{diag}(0, 2 I)\, T^{-1}, so the null space of Z+IZ + I is the stable invariant subspace of HH, which is the range of [IP]\begin{bmatrix} I \\ P \end{bmatrix} by Lemma 1. Writing (Z+I)[IP]=0(Z + I) \begin{bmatrix} I \\ P \end{bmatrix} = 0 in blocks gives the system. The matrix Z+IZ + I has rank nn, and its range is spanned by its columns; the columns of [Z12Z22+I]\begin{bmatrix} Z_{12} \\ Z_{22} + I \end{bmatrix} are independent, because a vector [0ξ]\begin{bmatrix} 0 \\ \xi \end{bmatrix} in the null space of Z+IZ + I must be of the form [IP]η\begin{bmatrix} I \\ P \end{bmatrix} \eta, which forces η=0\eta = 0 and ξ=0\xi = 0. So the solution is unique, and the normal equations of line L8 return it. □\square

Lemma 4. Line L9 does not move an exact stabilizing solution, and from a nearby matrix it converges quadratically to it.

Proof. Line L9 is one step of Kleinman's iteration: given PkP_k with A−GPkA - G P_k Hurwitz, Pk+1P_{k+1} solves (A−GPk)TPk+1+Pk+1(A−GPk)+Q+PkGPk=0(A - G P_k)^T P_{k+1} + P_{k+1} (A - G P_k) + Q + P_k G P_k = 0. If Pk=PP_k = P, the CARE says that PP solves this equation, and the solution is unique because A−GPA - G P is Hurwitz. Kleinman's iteration is Newton's method on the CARE (Kleinman 1968), so near PP the error is squared at each step. The steps remove the rounding error of the least squares solve. □\square

So CARE-SOLVE returns PP in exact arithmetic, and lines L1 and L2 give PP and K=R−1BTPK = R^{-1} B^T P with A−BKA - B K Hurwitz.

Part 2: the filter equation by duality

Transpose the filter equation AS+SAT−SCTV−1CS+W=0A S + S A^T - S C^T V^{-1} C S + W = 0. It reads (AT)TS+SAT−S(CT)V−1(CT)TS+W=0(A^T)^T S + S A^T - S (C^T) V^{-1} (C^T)^T S + W = 0, which is the CARE for the data (AT,CT,W,V)(A^T, C^T, W, V). (AT,CT)(A^T, C^T) is stabilizable if and only if (C,A)(C, A) is detectable, and (W1/2,AT)(W^{1/2}, A^T) is detectable if and only if (A,W1/2)(A, W^{1/2}) is stabilizable. So Part 1 applies, line L3 returns the stabilizing S≥0S \ge 0, and with Lo=SCTV−1L_o = S C^T V^{-1} from line L4 the matrix (AT−CTLoT)T=A−LoC(A^T - C^T L_o^T)^T = A - L_o C is Hurwitz.

Part 3: the eigenvalues of the closed loop

The controller of line L5 is x^˙=Ax^+Bu+Lo(y−Cx^)\dot{\hat x} = A \hat x + B u + L_o (y - C \hat x), u=−Kx^u = -K \hat x. In the coordinates (x,e)(x, e) with e=x−x^e = x - \hat x:

ddt[xe]=[A−BKBK0A−LoC][xe]+[ww−Lov].\frac{d}{dt}\begin{bmatrix} x \\ e \end{bmatrix} = \begin{bmatrix} A - B K & B K \\ 0 & A - L_o C \end{bmatrix} \begin{bmatrix} x \\ e \end{bmatrix} + \begin{bmatrix} w \\ w - L_o v \end{bmatrix}.

The matrix is block upper triangular, so its characteristic polynomial is det⁡(sI−A+BK)det⁡(sI−A+LoC)\det(sI - A + BK) \det(sI - A + L_o C). Both factors are Hurwitz by Parts 1 and 2, so the closed loop is internally Hurwitz. This is the separation principle for eigenvalues. It says nothing about margins.

Part 4: optimality

Let uu be any admissible input and xx the resulting state. The Itô formula for xTPxx^T P x gives

d(xTPx)=(xT(ATP+PA)x+2uTBTPx+tr(PW))dt+2xTP dwt,d(x^T P x) = \left(x^T (A^T P + P A) x + 2 u^T B^T P x + \mathrm{tr}(P W)\right) dt + 2 x^T P\, dw_t,

where wtw_t is the Wiener process with dwt=w dtdw_t = w\,dt. Use the CARE, ATP+PA=−Q+PGPA^T P + P A = -Q + P G P, and complete the square with K=R−1BTPK = R^{-1} B^T P:

xTQx+uTRu=(u+Kx)TR(u+Kx)+tr(PW)−ddt E (xTPx),x^T Q x + u^T R u = (u + K x)^T R (u + K x) + \mathrm{tr}(P W) - \frac{d}{dt}\, \mathbb{E}\,(x^T P x),

after taking expectations (the Itô integral has mean 0). Average over [0,T][0, T] and let T→∞T \to \infty. In a stationary regime 1TE x(T)TPx(T)→0\frac1T \mathbb{E}\, x(T)^T P x(T) \to 0, so

J=tr(PW)+lim⁡T→∞1T∫0TE (u+Kx)TR(u+Kx) dt.(1)J = \mathrm{tr}(P W) + \lim_{T \to \infty} \frac1T \int_0^T \mathbb{E}\,(u + K x)^T R (u + K x)\, dt. \tag{1}

Let x^(t)=E[x(t)∣y(s),s≤t]\hat x(t) = \mathbb{E}[x(t) \mid y(s), s \le t] and e=x−x^e = x - \hat x. For a linear Gaussian plant the input is known from the outputs, so ee does not depend on the choice of uu: it is the error of the Kalman-Bucy filter, whose covariance tends to SS. u+Kx^u + K \hat x is a function of the past outputs, and ee is orthogonal to every such function. So

E (u+Kx)TR(u+Kx)=E (u+Kx^)TR(u+Kx^)+tr(KTRK E eeT).\mathbb{E}\,(u + K x)^T R (u + K x) = \mathbb{E}\,(u + K \hat x)^T R (u + K \hat x) + \mathrm{tr}(K^T R K\, \mathbb{E}\, e e^T).

The second term tends to tr(KTRKS)\mathrm{tr}(K^T R K S) for every admissible uu, and the first is at least 0, with equality if and only if u=−Kx^u = -K \hat x. With (1),

J≥J∗=tr(PW)+tr(SKTRK),J \ge J^* = \mathrm{tr}(P W) + \mathrm{tr}(S K^T R K),

with equality for the controller of line L5. For that controller the filter of line L5 is the steady state Kalman-Bucy filter, which gives the conditional mean in the stationary regime. □\square

Remark. The two terms of J∗J^* show the split: tr(PW)\mathrm{tr}(P W) is the cost of LQR with the full state, and tr(SKTRK)\mathrm{tr}(S K^T R K) is the price of using an estimate. The same number is the square of the H2H_2 norm of the closed loop from the scaled noise to the scaled output (Q1/2x,R1/2u)(Q^{1/2} x, R^{1/2} u), which is why H2 optimal control has the same solution. The test computes JJ for the loop from the stationary covariance XX of (x,x^)(x, \hat x), the solution of AclX+XAclT+BnNBnT=0A_{cl} X + X A_{cl}^T + B_n N B_n^T = 0, and compares it with J∗J^*.

Complexity

Each sign function step inverts a 2n×2n2n \times 2n matrix and costs O(n3)O(n^3). The iteration converges quadratically once the eigenvalues are near ±1\pm 1; with determinant scaling, 10 to 30 steps are usual, and more are needed when HH has eigenvalues near the imaginary axis, which is the case when the problem is close to losing stabilizability or detectability. Lines L2 and L4 cost O(n2(m+p))O(n^2 (m + p)) with RR and VV factored once. A Kleinman step with a Bartels-Stewart Lyapunov solver costs O(n3)O(n^3); the code uses the Kronecker form, which costs O(n6)O(n^6) and is only meant for small nn. The controller itself costs O(n2+n(m+p))O(n^2 + n (m + p)) per evaluation of its right-hand side.

Properties

  • Separation. KK does not depend on CC, WW or VV, and LoL_o does not depend on BB, QQ or RR. The closed-loop eigenvalues are those of A−BKA - B K together with those of A−LoCA - L_o C.
  • Order. The controller has the order nn of the plant. Lower order controllers that minimize JJ have no such closed form.
  • Certainty equivalence. The controller acts on x^\hat x as LQR acts on xx. This holds for the linear plant with Gaussian noise and quadratic cost; it fails in general for nonlinear plants or other costs.
  • Same as H2. With the noise and the weighted outputs put into one generalized plant, J∗J^* is the squared H2 norm of the closed loop, and the LQG controller is the H2 optimal controller.
  • No guaranteed margins. LQR with the full state has the gain margin (1/2,∞)(1/2, \infty) and at least 60 degrees of phase margin (LQR stability margins). The LQG loop has no such bounds: Doyle (1978) gave a plant where the gain margin shrinks to 1 as the weights grow.

Variants and improvements

  • Discrete time. Use the DARE for both gains and the discrete Kalman filter. The predictor form uses x^k∣k−1\hat x_{k|k-1}; the current estimator form uses x^k∣k\hat x_{k|k} and is the optimal one when the computation delay is short.
  • Finite horizon. Run the regulator Riccati equation backward from the final time and the filter Riccati equation forward from the initial covariance. The gains then vary in time.
  • Correlated noise and cross terms. A cross covariance between ww and vv, or a cross term 2xTNu2 x^T N u in the cost, changes the gains to K=R−1(BTP+NT)K = R^{-1}(B^T P + N^T) and Lo=(SCT+M)V−1L_o = (S C^T + M) V^{-1}, with modified Riccati equations.
  • Loop transfer recovery. Make the filter fast with fictitious input noise so that the loop tends to the LQR loop (LTR), or do the dual at the output.
  • Integral action. Add the integral of the tracking error as a state, or estimate a constant disturbance, so that the loop has zero steady state error; see integral state feedback.
  • Robust synthesis. When margins matter, use H-infinity design, of which LQG is the limit as the bound γ\gamma goes to infinity in the central controller.

When to use it

Use LQG when only some states are measured, the plant is linear near the operating point, and the disturbances and sensor noise can be modeled as white noise with known intensities, possibly after shaping filters. It gives a first controller of full order with one design knob per weight, and it is the base for LTR and for estimators in MPC. Check the margins of every LQG design, at the plant input and at the output. If the plant model is uncertain in a known way, prefer an H-infinity or μ\mu design. If the inputs or states have hard limits, use the filter with MPC instead of the static gain KK.

Pitfalls

  • Assuming LQR margins. The 60 degree and (1/2,∞)(1/2, \infty) margins of LQR do not survive the estimator. In the example the upper gain margin drops from infinity to 4. Compute the margins of the actual loop.
  • Breaking the loop at the wrong point. Margins at the plant input and at the plant output are different for multivariable plants. Check both.
  • Fast filters with poor models. A large WW gives a fast filter that relies on the model. Unmodeled dynamics at high frequencies then reduce robustness.
  • Noise intensities as tuning knobs. WW and VV are rarely known. Treat them as design parameters and check the result, not as facts.
  • Ill conditioned Hamiltonians. When (A,B)(A, B) is close to losing stabilizability or (C,A)(C, A) is close to losing detectability, HH has eigenvalues near the imaginary axis, the sign iteration is slow, and PP or SS is large. Scale the problem and check the Riccati residuals.
  • Plant and controller unstable together. The LQG controller can itself have eigenvalues with positive real part even when the plant is open-loop Hurwitz. The loop is fine as long as the closed loop is Hurwitz, but startup and saturation then need care.

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()
lqg_control.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lqg-control/. The authors are listed in prov/WY53ER.jsonl.

"""Linear quadratic Gaussian (LQG) control in continuous time.

Plant: x' = A x + B u + w, y = C x + v, with x in R^n, u in R^m, y in R^p.
The noises w and v are white, zero mean and uncorrelated, with intensities
W >= 0 and V > 0. The cost is the average

    J = lim_(T -> inf) (1/T) E integral_0^T (x^T Q x + u^T R u) dt,

with Q >= 0 and R > 0. No cross terms are used.

The LQG controller is u = -K xhat with the observer

    xhat' = A xhat + B u + L (y - C xhat),

where K = R^-1 B^T P from the CARE A^T P + P A - P B R^-1 B^T P + Q = 0
and L = S C^T V^-1 from the filter Riccati equation
A S + S A^T - S C^T V^-1 C S + W = 0. Both are the stabilizing solutions.

The Riccati equations are solved by the matrix sign function of the
Hamiltonian matrix, followed by two Newton (Kleinman) steps that remove the
rounding error of the least squares step. Lyapunov equations are solved
with a Kronecker product, which is fine for the small n of the examples.
"""

from ctlmat import add, block, det, eye, inv, kron, mul, scale, solve, sub, trace, transpose, unvec, vec

__all__ = ["lyap", "care", "filter_are", "lqg", "closed_loop", "lqg_cost", "optimal_cost"]


def lyap(F, M):
    """Return X with F X + X F^T + M = 0 (F must have no eigenvalue pair summing to 0)."""
    n = len(F)
    big = add(kron(eye(n), F), kron(F, eye(n)))
    x = solve(big, [-v for v in vec(M)])
    X = unvec(x, n, n)
    return [[(X[i][j] + X[j][i]) / 2 for j in range(n)] for i in range(n)]


def _sign(Z, tol, max_iter):
    n = len(Z)
    for _ in range(max_iter):
        Zi = inv(Z)
        d = abs(det(Z)) ** (-1.0 / n)  # determinant scaling for faster convergence
        Zn = scale(0.5, add(scale(d, Z), scale(1.0 / d, Zi)))
        diff = max(abs(a - b) for ra, rb in zip(Zn, Z) for a, b in zip(ra, rb))
        size = max(abs(a) for r in Zn for a in r)
        Z = Zn
        if diff <= tol * size:
            break
    else:
        raise ArithmeticError("sign iteration did not converge (eigenvalue on the imaginary axis?)")
    return Z


def care(A, B, Q, R, tol=1e-13, max_iter=100):
    """Return the stabilizing solution P of A^T P + P A - P B R^-1 B^T P + Q = 0."""
    n = len(A)
    A = [[float(v) for v in r] for r in A]
    G = mul(mul(B, inv(R)), transpose(B))
    G = [[float(v) for v in r] for r in G]
    Q = [[float(v) for v in r] for r in Q]
    H = block([[A, scale(-1.0, G)], [scale(-1.0, Q), scale(-1.0, transpose(A))]])  # @line L6
    Wm = _sign(H, tol, max_iter)  # @line L7
    W11 = [r[:n] for r in Wm[:n]]
    W12 = [r[n:] for r in Wm[:n]]
    W21 = [r[:n] for r in Wm[n:]]
    W22 = [r[n:] for r in Wm[n:]]
    M = W12 + add(W22, eye(n))  # (W + I) [I; P] = 0 gives M P = rhs
    rhs = scale(-1.0, add(W11, eye(n)) + W21)
    Mt = transpose(M)
    P = solve(mul(Mt, M), mul(Mt, rhs))  # @line L8
    P = [[(P[i][j] + P[j][i]) / 2 for j in range(n)] for i in range(n)]
    for _ in range(2):  # @line L9
        Ak = sub(A, mul(G, P))
        P = lyap(transpose(Ak), add(Q, mul(mul(P, G), P)))
    return P


def filter_are(A, C, W, V, **kw):
    """Return the stabilizing solution S of A S + S A^T - S C^T V^-1 C S + W = 0 (by duality)."""
    return care(transpose(A), transpose(C), W, V, **kw)


def lqg(A, B, C, Q, R, W, V):
    """Return (K, L, P, S) of the LQG controller u = -K xhat."""
    P = care(A, B, Q, R)  # @line L1
    K = mul(mul(inv(R), transpose(B)), P)  # @line L2
    S = filter_are(A, C, W, V)  # @line L3
    L = mul(mul(S, transpose(C)), inv(V))  # @line L4
    return K, L, P, S  # @line L5


def controller(A, B, C, K, L):
    """Return (Ac, Bc, Cc): xhat' = Ac xhat + Bc y, u = -Cc xhat."""
    Ac = sub(sub(A, mul(B, K)), mul(L, C))
    return Ac, L, K


def closed_loop(A, B, C, K, L, gain=None):
    """Return the 2n by 2n matrix of (x, xhat) when u = -gain K xhat (gain is an m by m matrix, I if None)."""
    m = len(B[0])
    Gm = gain if gain is not None else eye(m)
    BGK = mul(mul(B, Gm), K)
    Ac, _, _ = controller(A, B, C, K, L)
    return block([[A, scale(-1, BGK)], [mul(L, C), Ac]])


def lqg_cost(A, B, C, Q, R, W, V, K, L):
    """Return the average cost J of the loop with gains K and L, from a Lyapunov equation.

    The closed-loop matrix must be Hurwitz. The noise (w, v) enters (x, xhat)
    through [[I, 0], [0, L]], and J = trace(Q X11) + trace(K^T R K X22) with
    X the stationary covariance of (x, xhat).
    """
    n, p = len(A), len(C)
    Acl = closed_loop(A, B, C, K, L)
    Bn = block([[eye(n), [[0] * p for _ in range(n)]], [[[0] * n for _ in range(n)], L]])
    N = block([[W, [[0] * p for _ in range(n)]], [[[0] * n for _ in range(p)], V]])
    X = lyap(Acl, mul(mul(Bn, N), transpose(Bn)))
    X11 = [r[:n] for r in X[:n]]
    X22 = [r[n:] for r in X[n:]]
    KRK = mul(mul(transpose(K), R), K)
    return trace(mul(Q, X11)) + trace(mul(KRK, X22))


def optimal_cost(B, R, W, K, P, S):
    """Return trace(P W) + trace(S K^T R K), the optimal LQG cost."""
    return trace(mul(P, W)) + trace(mul(S, mul(mul(transpose(K), R), K)))
test_lqg_control.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lqg-control/. The authors are listed in prov/WY53ER.jsonl.

import math
import random

import ctlmat as cm
from lqg_control import care, closed_loop, filter_are, lqg, lqg_cost, lyap, optimal_cost

R3 = math.sqrt(3.0)

# Double integrator, position measured, Q = I, R = 1, W = I, V = 1.
A = [[0, 1], [0, 0]]
B = [[0], [1]]
C = [[1, 0]]
Q = cm.eye(2)
R = [[1]]
W = cm.eye(2)
V = [[1]]


def close(X, Y, tol):
    return all(abs(a - b) <= tol for ra, rb in zip(X, Y) for a, b in zip(ra, rb))


def max_real(M):
    return max(z.real for z in cm.polyroots(cm.charpoly(M)))


def care_residual(A, B, Q, R, P):
    G = cm.mul(cm.mul(B, cm.inv(R)), cm.transpose(B))
    res = cm.add(cm.add(cm.mul(cm.transpose(A), P), cm.mul(P, A)), cm.sub(Q, cm.mul(cm.mul(P, G), P)))
    return max(abs(v) for row in res for v in row)


def test_double_integrator_closed_form():
    K, L, P, S = lqg(A, B, C, Q, R, W, V)
    want = [[R3, 1.0], [1.0, R3]]
    assert close(P, want, 1e-9) and close(S, want, 1e-9)
    assert close(K, [[1.0, R3]], 1e-9)
    assert close(L, [[R3], [1.0]], 1e-9)


def test_scalar_closed_form():
    # x' = a x + u + w, y = x + v: P = a + sqrt(a^2 + q) with r = 1, S = a + sqrt(a^2 + w) with v = 1.
    for a, q, w in [(1.0, 1.0, 1.0), (-2.0, 3.0, 0.5), (0.0, 4.0, 9.0)]:
        K, L, P, S = lqg([[a]], [[1.0]], [[1.0]], [[q]], [[1.0]], [[w]], [[1.0]])
        assert abs(P[0][0] - (a + math.sqrt(a * a + q))) < 1e-9
        assert abs(S[0][0] - (a + math.sqrt(a * a + w))) < 1e-9


def test_riccati_residuals_on_random_plants():
    rng = random.Random(11)
    for _ in range(6):
        n = rng.choice([2, 3])
        A_ = [[rng.uniform(-2, 2) for _ in range(n)] for _ in range(n)]
        B_ = [[rng.uniform(-1, 1)] for _ in range(n)]
        C_ = [[rng.uniform(-1, 1) for _ in range(n)]]
        Q_ = cm.eye(n)
        W_ = cm.eye(n)
        K, L, P, S = lqg(A_, B_, C_, Q_, [[1.0]], W_, [[0.5]])
        scale = 1.0 + max(abs(v) for row in P for v in row) ** 2
        assert care_residual(A_, B_, Q_, [[1.0]], P) <= 1e-9 * scale
        At, Ct = cm.transpose(A_), cm.transpose(C_)
        scale = 1.0 + max(abs(v) for row in S for v in row) ** 2
        assert care_residual(At, Ct, W_, [[0.5]], S) <= 1e-9 * scale
        assert cm.is_symmetric(P, 1e-12) and cm.is_pos_def(P)
        assert max_real(cm.sub(A_, cm.mul(B_, K))) < 0
        assert max_real(cm.sub(A_, cm.mul(L, C_))) < 0


def test_separation_of_eigenvalues():
    rng = random.Random(5)
    for _ in range(4):
        n = 3
        A_ = [[rng.uniform(-1.5, 1.5) for _ in range(n)] for _ in range(n)]
        B_ = [[rng.uniform(-1, 1)] for _ in range(n)]
        C_ = [[rng.uniform(-1, 1) for _ in range(n)]]
        K, L, P, S = lqg(A_, B_, C_, cm.eye(n), [[1.0]], cm.eye(n), [[1.0]])
        got = cm.charpoly(closed_loop(A_, B_, C_, K, L))
        want = cm.polymul(cm.charpoly(cm.sub(A_, cm.mul(B_, K))), cm.charpoly(cm.sub(A_, cm.mul(L, C_))))
        assert all(abs(g - w) <= 1e-8 * (1 + abs(w)) for g, w in zip(got, want))


def test_optimal_cost_and_perturbed_gains():
    K, L, P, S = lqg(A, B, C, Q, R, W, V)
    j_opt = optimal_cost(B, R, W, K, P, S)
    assert abs(j_opt - 8 * R3) < 1e-9
    assert abs(lqg_cost(A, B, C, Q, R, W, V, K, L) - j_opt) < 1e-8
    rng = random.Random(3)
    tried = 0
    while tried < 15:
        Kp = [[k + rng.uniform(-0.3, 0.3) for k in K[0]]]
        Lp = [[l[0] + rng.uniform(-0.3, 0.3)] for l in L]
        if max_real(closed_loop(A, B, C, Kp, Lp)) >= -1e-3:
            continue
        tried += 1
        assert lqg_cost(A, B, C, Q, R, W, V, Kp, Lp) > j_opt - 1e-9


def test_gain_margin_of_the_lqg_loop_is_finite():
    # Closed loop with input gain k: s^4 + 2 sqrt3 s^3 + 5 s^2 + 2 sqrt3 k s + k, Hurwitz iff 0 < k < 4.
    K, L, P, S = lqg(A, B, C, Q, R, W, V)
    for k, ok in [(0.05, True), (1.0, True), (3.9, True), (4.1, False), (6.0, False)]:
        assert (max_real(closed_loop(A, B, C, K, L, gain=[[k]])) < 0) == ok
    # The LQR loop alone keeps every gain k >= 1/2 (here every k > 0).
    for k in [0.5, 4.1, 100.0]:
        assert max_real(cm.sub(A, cm.scale(k, cm.mul(B, K)))) < 0


def test_doyle_example_has_a_tiny_gain_margin():
    q = sig = 60
    A_ = [[1, 1], [0, 1]]
    Q_ = [[q, q], [q, q]]
    W_ = [[sig, sig], [sig, sig]]
    K, L, P, S = lqg(A_, B, C, Q_, R, W_, V)
    assert close(K, [[10.0, 10.0]], 1e-8) and close(L, [[10.0], [10.0]], 1e-8)
    m_low = (97 - 8 * math.sqrt(85)) / 25
    for m, ok in [(1.0, True), (1.009, True), (1.011, False), (m_low + 1e-4, True), (m_low - 1e-4, False)]:
        assert (max_real(closed_loop(A_, B, C, K, L, gain=[[m]])) < 0) == ok


def test_noise_free_closed_loop_goes_to_zero():
    K, L, P, S = lqg(A, B, C, Q, R, W, V)
    Acl = closed_loop(A, B, C, K, L)
    E = cm.expm(cm.scale(30.0, Acl))
    z = cm.matvec(E, [1.0, -1.0, 0.0, 0.0])
    assert cm.norm2(z) < 1e-6


def test_lyap_solves_its_equation():
    F = [[-1.0, 2.0], [0.0, -3.0]]
    M = [[1.0, 0.5], [0.5, 2.0]]
    X = lyap(F, M)
    res = cm.add(cm.add(cm.mul(F, X), cm.mul(X, cm.transpose(F))), M)
    assert max(abs(v) for row in res for v in row) < 1e-12


def test_filter_are_is_the_dual_care():
    S = filter_are(A, C, W, V)
    P = care(cm.transpose(A), cm.transpose(C), W, V)
    assert close(S, P, 0.0)

History

Kalman (1960) solved the linear quadratic regulator, and Kalman and Bucy (1961) gave the continuous-time filter and noted its duality with the regulator. That the optimal stochastic controller is the deterministic regulator acting on the filter estimate was shown by Joseph and Tou (1961) and by Gunckel and Franklin (1963), and in more generality by Wonham (1968). Athans (1971) edited a special issue of IEEE Transactions on Automatic Control on the LQG problem and presented it as a design method. Doyle (1978) then showed with a two-state example that LQG regulators can have arbitrarily small margins, which led to loop transfer recovery (Doyle and Stein 1979, 1981) and to H-infinity control. The matrix sign function for Riccati equations goes back to a 1971 report by Roberts, published in 1980.

References

  1. Michael Athans, The role and use of the stochastic linear-quadratic-Gaussian problem in control system design, IEEE Transactions on Automatic Control 16(6), 529-552, 1971, the LQG problem, the separation of the filter and the regulator, and its use as a design method
  2. R. E. Kalman and R. S. Bucy, New results in linear filtering and prediction theory, Journal of Basic Engineering 83(1), 95-108, 1961, the continuous-time filter and the duality between filtering and the regulator problem
  3. John C. Doyle, Guaranteed margins for LQG regulators, IEEE Transactions on Automatic Control 23(4), 756-757, 1978, the example that shows that LQG regulators have no guaranteed margins
  4. J. D. Roberts, Linear model reduction and solution of the algebraic Riccati equation by use of the sign function, International Journal of Control 32(4), 677-687, 1980, the matrix sign function and its use to find the stable invariant subspace of the Hamiltonian matrix
  5. Ralph Byers, Solving the algebraic Riccati equation with the matrix sign function, Linear Algebra and its Applications 85, 267-279, 1987, the determinant scaling of the Newton iteration for the sign function
  6. Brian D. O. Anderson and John B. Moore, Optimal Control, Linear Quadratic Methods, Prentice Hall, 1990 (Dover reprint, 2007), the chapters on state estimator design and on the linear quadratic Gaussian controller
  7. Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, the chapter on H2 optimal control, where the LQG controller is the H2 optimal controller

Where this leads

About this page

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

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example