Algorithm Search⌘K

Algorithmcore

Infinite-horizon LQR

Also called steady-state LQR, LQR.

Computes the constant optimal gain K = R^(-1)B^T P from the stabilizing solution P of the algebraic Riccati equation.

Time
O(j (n^3 + m^3)) worst
Space
O(n^2 + n m) extra
Where
j = the number of iterations of the recursion; m = the number of inputs; n = the number of states
Properties
deterministicnot exactofflineiterative
Origin
Rudolf E. Kalman, 1960

Infinite-horizon LQR is the solution of the linear quadratic regulator problem when the horizon has no end. The optimal input is a constant linear state feedback u=−Kxu = -K x. In continuous time K=R−1BTPK = R^{-1} B^T P, where PP is the stabilizing solution of the continuous algebraic Riccati equation (CARE). In discrete time K=(R+BTPB)−1BTPAK = (R + B^T P B)^{-1} B^T P A, where PP is the stabilizing solution of the discrete algebraic Riccati equation (DARE). The optimal cost from x0x_0 is x0TPx0x_0^T P x_0, and the closed loop A−BKA - B K is Hurwitz, or Schur in discrete time. This page computes PP as the limit of the finite-horizon costs, which is the definition of the problem. The Schur method and the Kleinman iteration are faster solvers of the same equations.

In plain words

A controller must keep a system near rest forever. Being away from rest costs something at every moment, and so does every push. The total cost is a sum over all time, so it is finite only if the system really goes to rest. The best controller turns out to be very simple: it measures the state and pushes back by a fixed multiple of it, the same multiple at all times. To find the multiple, solve the same problem for a long but finite time, and let the length grow. The answer settles down to a fixed value. That value tells the cost of every starting point and gives the gain. The settled gain always brings the system to rest, as long as every unstable motion can be pushed and every unstable motion is seen by the cost.

The problem

Continuous time. Input: A∈Rn×nA \in \mathbb{R}^{n \times n}, B∈Rn×mB \in \mathbb{R}^{n \times m}, Q=QT≥0Q = Q^T \ge 0 and R=RT>0R = R^T > 0, with (A,B)(A, B) stabilizable and (Q1/2,A)(Q^{1/2}, A) detectable. The plant is x˙=Ax+Bu\dot x = A x + B u and the cost is J(x0,u)=∫0∞(xTQx+uTRu) dtJ(x_0, u) = \int_0^\infty (x^T Q x + u^T R u)\, dt. Output: the matrix P=PT≥0P = P^T \ge 0 with min⁡uJ(x0,u)=x0TPx0\min_u J(x_0, u) = x_0^T P x_0 for all x0x_0, and the gain KK such that u=−Kxu = -K x attains the minimum. Discrete time: the same, with xk+1=Axk+Bukx_{k+1} = A x_k + B u_k and J=∑k≥0(xkTQxk+ukTRuk)J = \sum_{k \ge 0} (x_k^T Q x_k + u_k^T R u_k).

The two hypotheses are the ones of the stabilizing solution theorem. Stabilizability makes some input give a finite cost. Detectability makes every input with finite cost drive the state to 0, so that a finite cost means a stable closed loop. The cost has no cross term 2xTSu2 x^T S u here; with one, replace QQ by Q−SR−1STQ - S R^{-1} S^T and AA by A−BR−1STA - B R^{-1} S^T and add R−1STR^{-1} S^T to the gain.

The algorithm

The discrete-time version, by the backward recursion of the finite horizon run to its fixed point:

  1. INFINITE-HORIZON-LQR(A, B, Q, R, tol)
  2. 1P ← 0 ▷ the cost of horizon 0
  3. 2repeat
  4. 3K ← (R + B^T P B)^(-1) B^T P A ▷ solve, do not invert
  5. 4P_new ← Q + A^T P A - A^T P B K ▷ one step of the Riccati recursion
  6. 5δ ← ||P_new - P||_F; P ← P_new
  7. 6until δ ≤ tol · ||P||_F
  8. 7K ← (R + B^T P B)^(-1) B^T P A
  9. 8if A - B K is not Schur then fail; return (P, K)

After jj passes, PP is the cost matrix of the finite horizon jj with terminal weight 0. The loop stops when two horizons give nearly the same matrix. Line L8 checks the result, because the stopping test alone does not prove that the limit is the stabilizing solution: if (Q1/2,A)(Q^{1/2}, A) is not detectable, the iteration can stop at a solution that does not stabilize, and line L8 then reports the failure.

The continuous-time version runs the same idea on the Riccati differential equation. In the backward time τ\tau, it is dP/dτ=ATP+PA−PBR−1BTP+QdP/d\tau = A^T P + P A - P B R^{-1} B^T P + Q with P(0)=0P(0) = 0. The implementation integrates it with the classical RK4 method and the fixed step h=0.5/(1+∥H∥∞)h = 0.5 / (1 + \|H\|_\infty), where HH is the Hamiltonian matrix. It stops when the CARE residual, the right side of the equation, is below 10−1310^{-13} times the size of the data, then sets K=R−1BTPK = R^{-1} B^T P and checks that A−BKA - B K is Hurwitz. The step is chosen so that hh times each eigenvalue of the linearized flow near the solution lies inside the stability region of RK4.

Example

Continuous double integrator. For A=[0100]A = \begin{bmatrix} 0 & 1 \\ 0 & 0 \end{bmatrix}, B=[01]B = \begin{bmatrix} 0 \\ 1 \end{bmatrix}, Q=IQ = I and R=1R = 1, the code takes 102 RK4 steps of size 1/61/6 and returns

P=[3113]=[1.732051111.732051],K=[13],P = \begin{bmatrix} \sqrt 3 & 1 \\ 1 & \sqrt 3 \end{bmatrix} = \begin{bmatrix} 1.732051 & 1 \\ 1 & 1.732051 \end{bmatrix}, \qquad K = \begin{bmatrix} 1 & \sqrt 3 \end{bmatrix},

with an error below 10−1110^{-11}. The closed loop A−BK=[01−1−3]A - B K = \begin{bmatrix} 0 & 1 \\ -1 & -\sqrt 3 \end{bmatrix} has the characteristic polynomial s2+3 s+1s^2 + \sqrt 3\, s + 1, so the poles are −0.866025±0.5i-0.866025 \pm 0.5 i: natural frequency 1 and damping ratio 3/2\sqrt 3 / 2. From x0=(1,0.5)x_0 = (1, 0.5) the optimal cost is x0TPx0=3+1+0.253=3.165064x_0^T P x_0 = \sqrt 3 + 1 + 0.25 \sqrt 3 = 3.165064, and an RK4 simulation of the closed loop over 40 seconds gives the same value within 10−810^{-8}. The finite-horizon page shows how P(0)P(0) of horizon TT tends to this matrix.

Scalar cases. For a=b=q=r=1a = b = q = r = 1 in continuous time, the CARE is 2p−p2+1=02p - p^2 + 1 = 0, whose roots are 1±21 \pm \sqrt 2. The stabilizing one is p=1+2=2.414214p = 1 + \sqrt 2 = 2.414214, with K=2.414214K = 2.414214 and the closed loop 1−K=−21 - K = -\sqrt 2. In discrete time, the DARE is p=1+p−p2/(1+p)p = 1 + p - p^2/(1 + p), that is p2=p+1p^2 = p + 1, so p=(1+5)/2=1.618034p = (1 + \sqrt 5)/2 = 1.618034 and K=p/(1+p)=0.618034K = p/(1 + p) = 0.618034. The recursion from 0 meets the tolerance 10−1410^{-14} after 19 passes; its iterates are the Fibonacci ratios 1,3/2,8/5,21/13,…1, 3/2, 8/5, 21/13, \dots

Sampled double integrator. The ZOH model with period 1 is A=[1101]A = \begin{bmatrix} 1 & 1 \\ 0 & 1 \end{bmatrix}, B=[1/21]B = \begin{bmatrix} 1/2 \\ 1 \end{bmatrix}. With Q=IQ = I and R=1R = 1, the recursion stops after 22 passes with

P=[2.3671011.1180341.1180342.587483],K=[0.4344831.028466].P = \begin{bmatrix} 2.367101 & 1.118034 \\ 1.118034 & 2.587483 \end{bmatrix}, \qquad K = \begin{bmatrix} 0.434483 & 1.028466 \end{bmatrix}.

The off-diagonal entry is 5/2\sqrt 5 / 2. The closed loop has the eigenvalues 0.377146±0.215723i0.377146 \pm 0.215723 i, of modulus 0.4344830.434483, so it is Schur. A sum of the cost over 400 steps of the closed loop gives x0TPx0x_0^T P x_0 within 10−1010^{-10} (relative), and random nearby gains with a Schur closed loop all give a larger cost.

When the cost does not see the instability. Take a=2a = 2, b=1b = 1, q=0q = 0, r=1r = 1 in discrete time. Then (q1/2,a)=(0,2)(q^{1/2}, a) = (0, 2) is not detectable. Starting from P=0P = 0, every pass gives P=0P = 0 again, so the loop stops at once with K=0K = 0, and line L8 fails because a−bK=2a - bK = 2. The DARE p=4p−4p2/(1+p)p = 4p - 4p^2/(1 + p) has the two solutions p=0p = 0 and p=3p = 3. The second one stabilizes: K=1.5K = 1.5 and a−bK=0.5a - bK = 0.5. Starting the recursion from P=1P = 1 finds it. In words: with q=0q = 0 the cheapest input is no input at all, the cost is 0, and the state grows without bound.

Correctness

The full proof is in proofs/correctness.md. It has three parts. First, if P≥0P \ge 0 solves the Riccati equation and A−BKA - B K is Hurwitz (Schur), then for every input with finite cost J=x0TPx0+∫0∞(u+Kx)TR(u+Kx) dtJ = x_0^T P x_0 + \int_0^\infty (u + K x)^T R (u + K x)\, dt, or the same with a sum and R+BTPBR + B^T P B in discrete time. Detectability is used here: a finite cost forces x(t)→0x(t) \to 0, so the term x(t)TPx(t)x(t)^T P x(t) at the far end vanishes. So u=−Kxu = -K x is optimal and the minimum is x0TPx0x_0^T P x_0. Second, the finite-horizon costs from P=0P = 0 do not decrease with the horizon and are bounded by the cost of any stabilizing gain, so they converge, and the limit solves the Riccati equation because one step of the recursion is a continuous map. Third, the limit stabilizes: if (A−BK)v=λv(A - BK) v = \lambda v with ∣λ∣≥1|\lambda| \ge 1, the identity P=Q+KTRK+(A−BK)TP(A−BK)P = Q + K^T R K + (A - BK)^T P (A - BK) gives (1−∣λ∣2)v∗Pv=v∗(Q+KTRK)v(1 - |\lambda|^2) v^* P v = v^* (Q + K^T R K) v, so Q1/2v=0Q^{1/2} v = 0 and Kv=0K v = 0, hence Av=λvA v = \lambda v, which contradicts detectability by the PBH test.

The tests check the CARE and DARE residuals (at most 10−910^{-9} times the size of the data), the symmetry and positive semidefiniteness of PP, the closed-loop eigenvalues, the double integrator and scalar closed forms, the simulated cost in both time domains, a grid search over scalar gains, and the failure cases.

Proof: The limit of the finite-horizon Riccati recursion is the stabilizing solution, and its gain is optimal on the infinite horizonfull

Discrete time is treated in full; the continuous case follows the same three steps and is given at the end. Let A∈Rn×nA \in \mathbb{R}^{n \times n}, B∈Rn×mB \in \mathbb{R}^{n \times m}, Q=QT≥0Q = Q^T \ge 0, R=RT>0R = R^T > 0, and let C=Q1/2C = Q^{1/2}, so Q=CTCQ = C^T C. Assume (A,B)(A, B) is stabilizable and (C,A)(C, A) is detectable. The plant is xk+1=Axk+Bukx_{k+1} = A x_k + B u_k and the cost is J(x0,u)=∑k≥0(xkTQxk+ukTRuk)J(x_0, u) = \sum_{k \ge 0} (x_k^T Q x_k + u_k^T R u_k), which may be +∞+\infty.

For P=PT≥0P = P^T \ge 0 write S(P)=R+BTPBS(P) = R + B^T P B, K(P)=S(P)−1BTPAK(P) = S(P)^{-1} B^T P A and

F(P)=Q+ATPA−ATPBK(P)=Q+KTRK+(A−BK)TP(A−BK),K=K(P).F(P) = Q + A^T P A - A^T P B K(P) = Q + K^T R K + (A - B K)^T P (A - B K), \qquad K = K(P).

The two forms are equal by Lemma 2 of the finite-horizon proof. The algorithm computes P0=0P_0 = 0 and Pj+1=F(Pj)P_{j+1} = F(P_j). By that proof, xTPjxx^T P_j x is the minimum of the cost of horizon jj with terminal weight 0.

Lemma 1: finite cost and detectability force xk→0x_k \to 0

If J(x0,u)<∞J(x_0, u) < \infty, then xk→0x_k \to 0.

Proof. Finite cost gives ∑k∣Cxk∣2<∞\sum_k |C x_k|^2 < \infty and ∑kukTRuk<∞\sum_k u_k^T R u_k < \infty, so Cxk→0C x_k \to 0 and uk→0u_k \to 0, and both sequences are square summable. By detectability there is LL with A−LCA - L C Schur. Write the plant as xk+1=(A−LC)xk+wkx_{k+1} = (A - L C) x_k + w_k with wk=LCxk+Bukw_k = L C x_k + B u_k. Then wkw_k is square summable, hence wk→0w_k \to 0. The solution is xk=(A−LC)kx0+∑i<k(A−LC)k−1−iwix_k = (A - LC)^k x_0 + \sum_{i < k} (A - LC)^{k-1-i} w_i. Since ∥(A−LC)k∥≤cθk\|(A - LC)^k\| \le c \theta^k for some cc and θ<1\theta < 1, the first term tends to 0, and the second is the convolution of a summable sequence with a sequence that tends to 0, which tends to 0. □\square

Lemma 2: a stabilizing solution gives the optimal cost

Let P=PT≥0P = P^T \ge 0 satisfy P=F(P)P = F(P), and let K=K(P)K = K(P) with A−BKA - B K Schur. Then for every x0x_0, min⁡uJ(x0,u)=x0TPx0\min_u J(x_0, u) = x_0^T P x_0, attained by uk=−Kxku_k = -K x_k and by no other input sequence.

Proof. For any xx and uu, completing the square as in Lemma 1 of the finite-horizon proof gives

xTQx+uTRu+(Ax+Bu)TP(Ax+Bu)=xTF(P)x+(u+Kx)TS(P)(u+Kx)=xTPx+(u+Kx)TS(P)(u+Kx).x^T Q x + u^T R u + (A x + B u)^T P (A x + B u) = x^T F(P) x + (u + K x)^T S(P) (u + K x) = x^T P x + (u + K x)^T S(P) (u + K x).

Sum this from k=0k = 0 to N−1N - 1 along a trajectory. The terms xkTPxkx_k^T P x_k telescope:

∑k=0N−1(xkTQxk+ukTRuk)=x0TPx0−xNTPxN+∑k=0N−1(uk+Kxk)TS(P)(uk+Kxk).\sum_{k=0}^{N-1} (x_k^T Q x_k + u_k^T R u_k) = x_0^T P x_0 - x_N^T P x_N + \sum_{k=0}^{N-1} (u_k + K x_k)^T S(P) (u_k + K x_k).

If J(x0,u)=∞J(x_0, u) = \infty there is nothing to prove. Otherwise xN→0x_N \to 0 by Lemma 1, so letting N→∞N \to \infty,

J(x0,u)=x0TPx0+∑k≥0(uk+Kxk)TS(P)(uk+Kxk)≥x0TPx0,J(x_0, u) = x_0^T P x_0 + \sum_{k \ge 0} (u_k + K x_k)^T S(P) (u_k + K x_k) \ge x_0^T P x_0,

because S(P)>0S(P) > 0. The feedback uk=−Kxku_k = -K x_k gives a Schur closed loop, so xk→0x_k \to 0 geometrically and its cost is finite; for it the sum is 0. Equality for another sequence would need uk=−Kxku_k = -K x_k for every kk. □\square

In particular there is at most one stabilizing solution: two of them would both equal the optimal cost matrix.

Lemma 3: the recursion from 0 converges

The sequence PjP_j is nondecreasing, there is a fixed matrix MM with 0≤Pj≤M0 \le P_j \le M for all jj, and the sequence converges to a matrix P∞≥0P_\infty \ge 0 with P∞=F(P∞)P_\infty = F(P_\infty).

Proof. Monotone: the cost of horizon j+1j + 1 restricted to its first jj steps is a cost of horizon jj with terminal weight 0, and the last term is nonnegative. Minimizing gives xTPj+1x≥xTPjxx^T P_{j+1} x \ge x^T P_j x for every xx.

Bounded: by stabilizability there is KsK_s with A−BKsA - B K_s Schur. The feedback u=−Ksxu = -K_s x has the finite infinite-horizon cost xTMxx^T M x, where M=∑k((A−BKs)T)k(Q+KsTRKs)(A−BKs)kM = \sum_k ((A - BK_s)^T)^k (Q + K_s^T R K_s) (A - BK_s)^k converges. Its cost over the first jj steps is at most xTMxx^T M x and at least xTPjxx^T P_j x, so Pj≤MP_j \le M.

Converges: for each xx, xTPjxx^T P_j x is nondecreasing and bounded, so it converges. By polarization, xTPy=14((x+y)TP(x+y)−(x−y)TP(x−y))x^T P y = \frac{1}{4}((x + y)^T P (x + y) - (x - y)^T P (x - y)) for symmetric PP, so every entry of PjP_j converges, and Pj→P∞P_j \to P_\infty with 0≤P∞≤M0 \le P_\infty \le M.

Fixed point: FF is continuous on the set of positive semidefinite matrices, because S(P)≥R>0S(P) \ge R > 0 is invertible there and inversion is continuous. Taking the limit in Pj+1=F(Pj)P_{j+1} = F(P_j) gives P∞=F(P∞)P_\infty = F(P_\infty). □\square

Lemma 4: the limit stabilizes

Let P=PT≥0P = P^T \ge 0 satisfy P=F(P)P = F(P) and let K=K(P)K = K(P). Then A−BKA - B K is Schur.

Proof. Let AK=A−BKA_K = A - B K, and let AKv=λvA_K v = \lambda v with v≠0v \ne 0 complex. The second form of FF gives P=Q+KTRK+AKTPAKP = Q + K^T R K + A_K^T P A_K. Multiply by v∗v^* on the left and vv on the right:

v∗Pv=v∗Qv+v∗KTRKv+∣λ∣2v∗Pv,so(1−∣λ∣2) v∗Pv=∣Cv∣2+(Kv)∗R(Kv).v^* P v = v^* Q v + v^* K^T R K v + |\lambda|^2 v^* P v, \qquad \text{so} \qquad (1 - |\lambda|^2)\, v^* P v = |C v|^2 + (K v)^* R (K v).

Suppose ∣λ∣≥1|\lambda| \ge 1. The left side is at most 0 and the right side is at least 0, so both are 0. Then Cv=0C v = 0 and, since R>0R > 0, Kv=0K v = 0. So Av=AKv+BKv=λvA v = A_K v + B K v = \lambda v with Cv=0C v = 0 and ∣λ∣≥1|\lambda| \ge 1. By the PBH test for detectability, no such vv exists. So every eigenvalue of AKA_K has ∣λ∣<1|\lambda| < 1. □\square

Theorem

Under the hypotheses, the recursion from P0=0P_0 = 0 converges to the unique stabilizing solution PP of the DARE, K(P)K(P) is the optimal constant gain, and x0TPx0x_0^T P x_0 is the optimal cost of the infinite horizon.

Proof. Lemma 3 gives the limit P∞P_\infty, Lemma 4 shows that it is stabilizing, and Lemma 2 shows that it gives the optimal cost and the optimal feedback. Uniqueness follows from Lemma 2. ■\blacksquare

What the code checks. The loop stops after finitely many passes, when ∥Pj+1−Pj∥F≤tol ∥Pj+1∥F\|P_{j+1} - P_j\|_F \le \text{tol}\, \|P_{j+1}\|_F, so the returned matrix is an approximation of P∞P_\infty. Line L8 tests the closed loop with the computed gain. If the hypotheses fail, Lemma 4 can fail: for a=2a = 2, b=1b = 1, q=0q = 0, r=1r = 1, Pj=0P_j = 0 for all jj and A−BK=2A - BK = 2, which is what the code reports.

Continuous time

The same steps work with x˙=Ax+Bu\dot x = A x + B u and J=∫0∞(xTQx+uTRu) dtJ = \int_0^\infty (x^T Q x + u^T R u)\, dt, with G=BR−1BTG = B R^{-1} B^T and R(P)=ATP+PA−PGP+Q\mathcal{R}(P) = A^T P + P A - P G P + Q.

  1. Finite cost forces x(t)→0x(t) \to 0. With LL such that A−LCA - L C is Hurwitz, xx solves x˙=(A−LC)x+w\dot x = (A - LC) x + w with w=LCx+Bu∈L2w = L C x + B u \in L^2, so x∈L2x \in L^2, and x˙\dot x is in L2L^2 as well. A function with x,x˙∈L2x, \dot x \in L^2 satisfies ∣x(t)∣2=∣x(s)∣2+2∫stxTx˙|x(t)|^2 = |x(s)|^2 + 2 \int_s^t x^T \dot x, so ∣x(t)∣2|x(t)|^2 has a limit, which must be 0 because x∈L2x \in L^2.
  2. If R(P)=0\mathcal{R}(P) = 0, P≥0P \ge 0 and A−GPA - G P is Hurwitz, then Lemma 4 of the finite-horizon proof gives ∫0T(xTQx+uTRu) dt=x0TPx0−x(T)TPx(T)+∫0T(u+Kx)TR(u+Kx) dt\int_0^T (x^T Q x + u^T R u)\, dt = x_0^T P x_0 - x(T)^T P x(T) + \int_0^T (u + K x)^T R (u + K x)\, dt with K=R−1BTPK = R^{-1} B^T P. Let T→∞T \to \infty and use step 1.
  3. The solution P(τ)P(\tau) of dP/dτ=R(P)dP/d\tau = \mathcal{R}(P), P(0)=0P(0) = 0, is the cost matrix of horizon τ\tau. It is nondecreasing in τ\tau and bounded by the cost of a stabilizing gain, so it converges to some P∞P_\infty. Its derivative R(P(τ))\mathcal{R}(P(\tau)) converges to R(P∞)\mathcal{R}(P_\infty); if this limit were not 0, P(τ)P(\tau) would grow without bound in some entry, so R(P∞)=0\mathcal{R}(P_\infty) = 0.
  4. With AK=A−BKA_K = A - B K, the CARE reads AKTP+PAK=−(Q+KTRK)A_K^T P + P A_K = -(Q + K^T R K). If AKv=λvA_K v = \lambda v, then 2Re⁡(λ) v∗Pv=−∣Cv∣2−(Kv)∗R(Kv)2 \operatorname{Re}(\lambda)\, v^* P v = -|C v|^2 - (Kv)^* R (Kv). If Re⁡λ≥0\operatorname{Re} \lambda \ge 0, both terms on the right vanish, so Cv=0C v = 0 and Av=λvA v = \lambda v, which contradicts detectability. So A−BKA - B K is Hurwitz.

The implementation integrates step 3 with RK4 and stops on the CARE residual. Its last check, that A−BKA - BK is Hurwitz, plays the role of Lemma 4 for the computed matrix.

Complexity

In the real RAM, with dense matrices:

  • One pass of lines L3 to L5 costs O(n3+m3)O(n^3 + m^3), the same as one step of the finite-horizon recursion. Line L8 costs O(n3)O(n^3) for the closed-loop matrix and its characteristic polynomial, plus the root finding.
  • Convergence is linear. If PP is the stabilizing solution and AK=A−BKA_K = A - B K, the error after jj passes behaves like ρ(AK)2j\rho(A_K)^{2j}, where ρ\rho is the spectral radius. The number of passes for a tolerance ϵ\epsilon is therefore about log⁡(1/ϵ)/(2log⁡(1/ρ(AK)))\log(1/\epsilon) / (2 \log(1/\rho(A_K))). It grows without bound as the closed loop approaches the unit circle. The pass counts in the examples are measurements, not bounds.
  • In continuous time, one RK4 step costs four evaluations of the Riccati right side, each O(n3+m3)O(n^3 + m^3). The error decays like e−2ατe^{-2 \alpha \tau}, where −α-\alpha is the largest real part of an eigenvalue of A−BKA - B K, and the step is at most of order 1/∥H∥1 / \|H\|. So the number of steps is of order ∥H∥/α\|H\| / \alpha times log⁡(1/ϵ)\log(1/\epsilon).

The extra space is O(n2+nm)O(n^2 + n m). For a fast solution use the Schur method, which costs O(n3)O(n^3) flops with a constant that does not depend on the closed loop, or the Kleinman iteration, which converges quadratically. The controller costs O(nm)O(n m) per step online.

Properties

  • Constant gain. The optimal feedback does not depend on time or on x0x_0. This is why it is used much more than the finite-horizon version.
  • Guaranteed stability. Under stabilizability and detectability, A−BKA - B K is Hurwitz (Schur). Pole placement gives any poles; LQR gives poles that are optimal for a cost, and the weights QQ and RR are the design knobs.
  • Robustness in continuous time. With one input, or a diagonal RR, the loop has a gain margin of (1/2,∞)(1/2, \infty) and a phase margin of at least 60 degrees in each channel. The LQR stability margins page proves this. Discrete-time LQR has smaller guaranteed margins, and LQG with an observer has none in general.
  • Monotone in the weights. If Q1≤Q2Q_1 \le Q_2, then P1≤P2P_1 \le P_2, because every cost with Q1Q_1 is at most the same cost with Q2Q_2.
  • Scaling. Multiplying QQ and RR by the same positive number multiplies PP by it and does not change KK. Only the ratio of the weights matters.
  • Symmetric root locus. For one input, Q=cTcQ = c^T c and R=ρ>0R = \rho > 0, let G(s)=c(sI−A)−1BG(s) = c (sI - A)^{-1} B. The closed-loop poles are the roots in the open left half plane of 1+G(−s)G(s)/ρ=01 + G(-s) G(s) / \rho = 0. As ρ→0\rho \to 0 (cheap control), some poles tend to the zeros of GG in the left half plane and to the mirror images of its zeros in the right half plane, and the others go to infinity in a Butterworth pattern. As ρ→∞\rho \to \infty (expensive control), the poles tend to the stable eigenvalues of AA and to the mirror images of the unstable ones.
  • Duality. With A→ATA \to A^T, B→CTB \to C^T, the same Riccati equation gives the steady-state gain of the Kalman filter in discrete time, and of the Kalman-Bucy filter in continuous time.

Variants and improvements

  • Other solvers. The Schur method (Laub 1979) computes the stable invariant subspace of the Hamiltonian matrix and is the standard direct method. The Kleinman iteration is Newton's method on the CARE; Hewer (1971) gave the discrete version. Both need fewer operations than the recursion when the closed loop is slow. The recursion on this page is the value iteration of dynamic programming, and Kleinman's method is the policy iteration.
  • Doubling. Doubling algorithms compute the cost of horizon 2j2j from the cost of horizon jj, so jj passes give horizon 2j2^j, and the convergence becomes quadratic (Bini, Iannazzo and Meini).
  • Cross term and discounting. A cross term 2xTSu2 x^T S u is removed by the change of variables in The problem. A discount factor γ<1\gamma < 1 in discrete time replaces AA and BB by γ A\sqrt\gamma\, A and γ B\sqrt\gamma\, B.
  • Integral action. To remove steady-state error for constant references, add the integral of the error to the state and apply LQR to the larger system; see integral state feedback.
  • Output feedback. When the state is not measured, combine the gain with a Kalman filter: this is LQG control, which has the same gain by the separation principle but no guaranteed margins (Doyle's counterexample).
  • H2 view. The LQR cost from a random initial state with covariance II is trace⁡P\operatorname{trace} P, which is the squared H2 norm of a closed-loop system; see H2 optimal control.

When to use it

Use it to regulate a linear plant, or a linearization about an equilibrium, when the state is measured and the task has no fixed end. It is the default first design for multivariable plants because it always gives a stabilizing gain, handles many inputs with no extra effort, and has the margins of the LQR stability margins page in continuous time. Use finite-horizon LQR for a fixed time or a time-varying plant, and linear MPC when the inputs or states have hard limits. To compute PP for a real plant, call a Schur-based solver; the recursion on this page is the clearest way to see why the answer is right, not the fastest way to get it.

Pitfalls

  • "Stable" needs the hypotheses. Without detectability of (Q1/2,A)(Q^{1/2}, A), the optimal cost can be finite while the state grows, and the iteration from 0 can return a gain that does not stabilize. The example above shows it. Always check the closed loop.
  • Slow convergence. If the closed loop has a pole near the unit circle (discrete) or near the imaginary axis (continuous), the recursion needs very many passes. A stopping test on the change δ\delta can then stop early, far from the solution. A test on the Riccati residual is better.
  • Weights are not specifications. The choice of QQ and RR is a design step. Bryson's rule, which sets each diagonal weight to one over the square of the largest allowed value of the variable, is a rule of thumb, not a result.
  • The discrete margins are smaller. Do not quote the 60 degree phase margin for a discrete-time LQR design or for LQG. Check the margins of the actual loop.
  • Sampling. A continuous design implemented with a sampler and a hold is a different loop. Either design in discrete time on the zero-order hold model, or check the sampled loop.
  • Symmetry. In floating point, symmetrize PP after each step. A slightly unsymmetric PP gives a slightly wrong gain and can make the stopping test fail.

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()
ctlsim.py 120 lines
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Fixed step simulation for the control pages.

Conventions:
- A continuous-time system is a function f(t, x, u) that returns x' as a
  flat list. x is a flat list. u is whatever the control returns (a flat
  list, a scalar, or None when there is no control).
- A discrete-time system is a function F(k, x, u) that returns x_(k+1).
- The integrator is the classical 4th order Runge-Kutta method with a fixed
  step dt. The input is held constant over each step.
- Time t_k = t0 + k dt is computed by multiplication, not by summation.
- The number of steps round((t1 - t0) / dt) and the hold ratio
  round(hold / dt) must match the real ratios within 1e-9 (relative), or
  ValueError is raised.

This file holds no controller or observer of a control page.
"""

__all__ = ["rk4_step", "simulate", "simulate_discrete", "lti"]


def _axpy(a, x, y):
    return [yi + a * xi for xi, yi in zip(x, y)]


def rk4_step(f, t, x, u, dt):
    """Return x(t + dt) after one RK4 step of x' = f(t, x, u), u held constant."""
    k1 = f(t, x, u)
    k2 = f(t + dt / 2, _axpy(dt / 2, k1, x), u)
    k3 = f(t + dt / 2, _axpy(dt / 2, k2, x), u)
    k4 = f(t + dt, _axpy(dt, k3, x), u)
    return [xi + dt / 6 * (a + 2 * b + 2 * c + d) for xi, a, b, c, d in zip(x, k1, k2, k3, k4)]


def _ratio(num, den, what):
    r = round(num / den)
    if abs(r * den - num) > 1e-9 * max(abs(num), abs(den)):
        raise ValueError(what + " is not an integer multiple of dt")
    return r


def simulate(f, x0, t0, t1, dt, control=None, hold=None):
    """Simulate x' = f(t, x, u) from x(t0) = x0 to t1 with RK4 and step dt.

    control(t, x) gives the input. It is called at each sampling instant
    t0 + j hold, and its value is held (zero-order hold) until the next
    instant. hold must be an integer multiple of dt; hold = None means
    hold = dt. With control = None the input is None.

    Returns (ts, xs, us): ts has N + 1 times, xs the N + 1 states, and us the
    N inputs, where us[k] acts on [ts[k], ts[k + 1]].
    """
    if dt <= 0:
        raise ValueError("dt must be positive")
    n_steps = _ratio(t1 - t0, dt, "t1 - t0")
    if n_steps < 0:
        raise ValueError("t1 is before t0")
    r = 1 if hold is None else _ratio(hold, dt, "hold")
    if r < 1:
        raise ValueError("hold must be at least dt")
    x = list(x0)
    ts = [t0]
    xs = [list(x)]
    us = []
    u = None
    for k in range(n_steps):
        t = t0 + k * dt
        if control is not None and k % r == 0:
            u = control(t, list(x))
        x = rk4_step(f, t, x, u, dt)
        ts.append(t0 + (k + 1) * dt)
        xs.append(x)
        us.append(u)
    return ts, xs, us


def simulate_discrete(F, x0, N, control=None):
    """Run x_(k+1) = F(k, x_k, u_k) for k = 0, ..., N - 1.

    u_k = control(k, x_k), or None if control is None. Returns (xs, us) with
    N + 1 states and N inputs. Exact if F and control are exact.
    """
    x = list(x0)
    xs = [list(x)]
    us = []
    for k in range(N):
        u = control(k, list(x)) if control is not None else None
        x = list(F(k, x, u))
        xs.append(x)
        us.append(u)
    return xs, us


def lti(A, B=None):
    """Return f(t, x, u) = A x + B u for the system x' = A x + B u.

    u may be a flat list, a scalar (one input) or None (zero input). B may
    be None for a system with no input.
    """
    def f(t, x, u):
        dx = [sum(a * xi for a, xi in zip(row, x)) for row in A]
        if B is None or u is None:
            return dx
        uu = u if isinstance(u, (list, tuple)) else [u]
        return [d + sum(b * ui for b, ui in zip(row, uu)) for d, row in zip(dx, B)]
    return f


def _self_test():
    import math
    f = lti([[-1.0]])
    _, xs, _ = simulate(f, [1.0], 0.0, 1.0, 0.01)
    assert abs(xs[-1][0] - math.exp(-1.0)) < 1e-9
    return True


if __name__ == "__main__":
    _self_test()
infinite_horizon_lqr.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/infinite-horizon-lqr/. The authors are listed in prov/G9RNJT.jsonl.

"""Infinite-horizon linear quadratic regulator, as the limit of the finite horizon.

Discrete time: x_(k+1) = A x_k + B u_k, cost sum_(k>=0) x_k^T Q x_k + u_k^T R u_k.
The finite-horizon cost matrices of horizon j, computed by the backward
Riccati recursion from P = P0 (default 0), converge to the stabilizing
solution of the DARE

    P = Q + A^T P A - A^T P B (R + B^T P B)^(-1) B^T P A

when (A, B) is stabilizable and (Q^(1/2), A) is detectable. The gain is
K = (R + B^T P B)^(-1) B^T P A, the control is u = -K x, and A - B K is Schur.

Continuous time: x' = A x + B u, cost integral of x^T Q x + u^T R u. The
Riccati differential equation dP/dtau = A^T P + P A - P B R^(-1) B^T P + Q
in the backward time tau is integrated from P(0) = P0 with RK4 until the
CARE residual is small. The gain is K = R^(-1) B^T P and A - B K is Hurwitz.

Both functions check the closed loop at the end and raise ValueError if it
is not Schur (or Hurwitz). This happens, for example, when (Q^(1/2), A) is
not detectable and the iteration from 0 stops at a solution that does not
stabilize.
"""

from ctlmat import add, charpoly, mul, polyroots, scale, solve, sub, transpose

__all__ = ["dlqr", "lqr", "dare_residual", "care_residual", "closed_loop_eigs"]


def _fro(a):
    return sum(abs(v) ** 2 for row in a for v in row) ** 0.5


def _sym(p):
    return [[(p[i][j] + p[j][i]) / 2 for j in range(len(p))] for i in range(len(p))]


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


def closed_loop_eigs(A, B, K):
    """Return the eigenvalues of A - B K, from its characteristic polynomial."""
    return polyroots(charpoly(sub(A, mul(B, K))))


def _dgain(A, B, R, P):
    pb = mul(P, B)
    return solve(add(R, mul(transpose(B), pb)), mul(transpose(pb), A))


def dare_residual(A, B, Q, R, P):
    """Return Q + A^T P A - A^T P B (R + B^T P B)^(-1) B^T P A - P."""
    k = _dgain(A, B, R, P)
    at = transpose(A)
    return sub(sub(add(Q, mul(at, mul(P, A))), mul(at, mul(mul(P, B), k))), P)


def care_residual(A, B, Q, R, P):
    """Return A^T P + P A - P B R^(-1) B^T P + Q."""
    pb = mul(P, B)
    return add(add(mul(transpose(A), P), mul(P, A)), sub(Q, mul(pb, solve(R, transpose(pb)))))


def dlqr(A, B, Q, R, P0=None, tol=1e-14, max_iter=100000):
    """Return (P, K, iterations) for the discrete-time infinite-horizon problem."""
    A, B, Q, R = _float(A), _float(B), _float(Q), _float(R)
    n = len(A)
    p = [[0.0] * n for _ in range(n)] if P0 is None else _float(P0)  # @line L1
    at = transpose(A)
    for it in range(1, max_iter + 1):  # @line L2
        k = _dgain(A, B, R, p)  # @line L3
        new = _sym(sub(add(Q, mul(at, mul(p, A))), mul(at, mul(mul(p, B), k))))  # @line L4
        delta = _fro(sub(new, p))  # @line L5
        p = new
        if delta <= tol * max(_fro(p), 1e-300):  # @line L6
            break
    else:
        raise ValueError("the Riccati recursion did not converge")
    k = _dgain(A, B, R, p)  # @line L7
    if max(abs(z) for z in closed_loop_eigs(A, B, k)) >= 1:  # @line L8
        raise ValueError("A - B K is not Schur: no stabilizing limit from this start")
    return p, k, it


def lqr(A, B, Q, R, P0=None, tol=1e-13, h=None, max_steps=200000):
    """Return (P, K, steps) for the continuous-time infinite-horizon problem.

    h is the RK4 step in the backward time. The default is
    0.5 / (1 + ||H||_inf) for the Hamiltonian matrix H, so that h times
    every eigenvalue of the linearized flow near the solution stays inside
    the stability region of RK4.
    """
    A, B, Q, R = _float(A), _float(B), _float(Q), _float(R)
    n = len(A)
    g = mul(B, solve(R, transpose(B)))
    if h is None:
        rows = [sum(abs(v) for v in A[i]) + sum(abs(v) for v in g[i]) for i in range(n)]
        rows += [sum(abs(v) for v in Q[i]) + sum(abs(A[j][i]) for j in range(n)) for i in range(n)]
        h = 0.5 / (1.0 + max(rows))
    p = [[0.0] * n for _ in range(n)] if P0 is None else _float(P0)

    def f(m):
        return care_residual(A, B, Q, R, m)

    scale_q = _fro(Q) + _fro(A) + _fro(g) + 1e-300
    for step in range(1, max_steps + 1):
        k1 = f(p)
        size = scale_q * (1.0 + _fro(p)) ** 2
        if _fro(k1) <= tol * size:
            break
        k2 = f(add(p, scale(h / 2, k1)))
        k3 = f(add(p, scale(h / 2, k2)))
        k4 = f(add(p, scale(h, k3)))
        p = _sym(add(p, scale(h / 6, add(add(k1, scale(2, k2)), add(scale(2, k3), k4)))))
    else:
        raise ValueError("the Riccati differential equation did not reach a steady state")
    k = solve(R, mul(transpose(B), p))
    if max(z.real for z in closed_loop_eigs(A, B, k)) >= 0:
        raise ValueError("A - B K is not Hurwitz: no stabilizing limit from this start")
    return p, k, step
test_infinite_horizon_lqr.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/infinite-horizon-lqr/. The authors are listed in prov/G9RNJT.jsonl.

import math
import random

import pytest

import ctlmat as cm
import ctlsim as cs
from infinite_horizon_lqr import care_residual, closed_loop_eigs, dare_residual, dlqr, lqr

R3 = math.sqrt(3.0)


def quad(m, v):
    return sum(v[i] * m[i][j] * v[j] for i in range(len(v)) for j in range(len(v)))


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


def data_norm(A, B, Q, R, P):
    g = cm.mul(B, cm.solve(R, cm.transpose(B)))
    return cm.norm2(Q) + 2 * cm.norm2(A) * cm.norm2(P) + cm.norm2(g) * cm.norm2(P) ** 2


def check_solution(A, B, Q, R, P, K, discrete):
    res = dare_residual(A, B, Q, R, P) if discrete else care_residual(A, B, Q, R, P)
    assert cm.norm2(res) <= 1e-9 * data_norm(A, B, Q, R, P)
    assert cm.is_symmetric(P, 1e-12 * cm.norm2(P))
    lam = [v.real for v in cm.polyroots(cm.charpoly(P))]
    assert min(lam) >= -1e-9 * cm.norm2(P)
    eig = closed_loop_eigs(A, B, K)
    if discrete:
        assert max(abs(z) for z in eig) < 1
    else:
        assert max(z.real for z in eig) < 0


def test_double_integrator_continuous():
    A, B, Q, R = [[0, 1], [0, 0]], [[0], [1]], [[1, 0], [0, 1]], [[1]]
    P, K, _ = lqr(A, B, Q, R)
    assert close(P, [[R3, 1.0], [1.0, R3]], 1e-9)
    assert close(K, [[1.0, R3]], 1e-9)
    check_solution(A, B, Q, R, P, K, False)


def test_scalar_care_and_dare():
    P, K, _ = lqr([[1]], [[1]], [[1]], [[1]])
    assert abs(P[0][0] - (1 + math.sqrt(2))) < 1e-9 and abs(K[0][0] - (1 + math.sqrt(2))) < 1e-9
    P, K, _ = dlqr([[1]], [[1]], [[1]], [[1]])
    phi = (1 + math.sqrt(5)) / 2
    assert abs(P[0][0] - phi) < 1e-12 and abs(K[0][0] - (phi - 1)) < 1e-12


def test_sampled_double_integrator():
    A, B, Q, R = [[1, 1], [0, 1]], [[0.5], [1]], [[1, 0], [0, 1]], [[1]]
    P, K, _ = dlqr(A, B, Q, R)
    check_solution(A, B, Q, R, P, K, True)
    assert abs(P[0][1] - math.sqrt(5) / 2) < 1e-12


def random_problem(rng, n, m):
    A = [[rng.uniform(-1.5, 1.5) for _ in range(n)] for _ in range(n)]
    B = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(n)]
    C = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
    Q = cm.add(cm.mul(cm.transpose(C), C), cm.scale(0.1, cm.eye(n)))
    D = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(m)]
    R = cm.add(cm.mul(cm.transpose(D), D), cm.scale(0.5, cm.eye(m)))
    return A, B, Q, R


@pytest.mark.parametrize("seed", [1, 2, 3, 4])
def test_random_continuous(seed):
    rng = random.Random(seed)
    A, B, Q, R = random_problem(rng, 3, rng.choice([1, 2]))
    P, K, _ = lqr(A, B, Q, R)
    check_solution(A, B, Q, R, P, K, False)


@pytest.mark.parametrize("seed", [5, 6, 7, 8])
def test_random_discrete(seed):
    rng = random.Random(seed)
    A, B, Q, R = random_problem(rng, 3, rng.choice([1, 2]))
    P, K, _ = dlqr(A, B, Q, R)
    check_solution(A, B, Q, R, P, K, True)


def test_discrete_cost_by_simulation_and_other_gains():
    A, B, Q, R = [[1, 1], [0, 1]], [[0.5], [1]], [[1, 0], [0, 1]], [[1]]
    P, K, _ = dlqr(A, B, Q, R)

    def cost(gain, x0):
        def step(k, x, u):
            return [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]
        xs, us = cs.simulate_discrete(step, x0, 400, lambda k, x: [-v for v in cm.matvec(gain, x)])
        return sum(quad(Q, x) + quad(R, u) for x, u in zip(xs, us))

    rng = random.Random(3)
    for _ in range(3):
        x0 = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
        best = cost(K, x0)
        assert abs(best - quad(P, x0)) < 1e-10 * quad(P, x0)
        for _ in range(5):
            other = [[K[0][0] + rng.uniform(-0.1, 0.1), K[0][1] + rng.uniform(-0.1, 0.1)]]
            if max(abs(z) for z in closed_loop_eigs(A, B, other)) < 0.95:
                assert cost(other, x0) >= best


def test_scalar_gain_grid_search():
    # Cost of the constant gain k for a = 2, b = 1, q = r = 1, from x0 = 1:
    # sum of (1 + k^2)(2 - k)^(2j) = (1 + k^2) / (1 - (2 - k)^2) for |2 - k| < 1.
    P, K, _ = dlqr([[2]], [[1]], [[1]], [[1]])
    grid = [1.0 + 2.0 * i / 20000 for i in range(1, 20000)]
    best = min(grid, key=lambda k: (1 + k * k) / (1 - (2 - k) ** 2))
    assert abs(best - K[0][0]) < 2e-4
    assert abs((1 + K[0][0] ** 2) / (1 - (2 - K[0][0]) ** 2) - P[0][0]) < 1e-12


def test_continuous_cost_by_simulation():
    A, B, Q, R = [[0, 1], [0, 0]], [[0], [1]], [[1, 0], [0, 1]], [[1]]
    P, K, _ = lqr(A, B, Q, R)

    def f(t, xa, u):
        x = xa[:2]
        uu = [-v for v in cm.matvec(K, x)]
        dx = [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, uu))]
        return dx + [quad(Q, x) + quad(R, uu)]

    x0 = [1.0, 0.5]
    _, xs, _ = cs.simulate(f, x0 + [0.0], 0.0, 40.0, 0.01)
    assert abs(xs[-1][2] - quad(P, x0)) < 1e-8


def test_not_detectable_start_from_zero_fails():
    # Q = 0: P = 0 is a fixed point, and A - B K = A is not stable.
    with pytest.raises(ValueError):
        dlqr([[2]], [[1]], [[0]], [[1]])
    with pytest.raises(ValueError):
        lqr([[1]], [[1]], [[0]], [[1]])
    # The stabilizing solutions exist: p = 3 (discrete) and p = 2 (continuous).
    P, K, _ = dlqr([[2]], [[1]], [[0]], [[1]], P0=[[1]])
    assert abs(P[0][0] - 3) < 1e-12 and abs(K[0][0] - 1.5) < 1e-12
    P, K, _ = lqr([[1]], [[1]], [[0]], [[1]], P0=[[1]])
    assert abs(P[0][0] - 2) < 1e-9


def test_not_stabilizable_fails():
    with pytest.raises(ValueError):
        dlqr([[1]], [[0]], [[1]], [[1]], max_iter=500)

History

Kalman (1960) posed the linear quadratic regulator problem, solved it on a finite interval with the Riccati differential equation, and showed that under controllability and observability the solution has a limit as the interval grows. The limit gives a constant feedback that stabilizes the plant. Wonham (1968) and Kučera (1972) weakened the hypotheses to stabilizability and detectability. Kleinman (1968) gave a Newton iteration for the algebraic equation, and Laub (1979) gave the Schur method, which became the standard numerical solver. Kalman (1964) showed that LQR loops satisfy the return difference inequality, which gives the classical robustness of the design.

References

  1. R. E. Kalman, Contributions to the theory of optimal control, Boletín de la Sociedad Matemática Mexicana 5(2), 102-119, 1960, the regulator problem on an unbounded interval, as the limit of the finite interval problem
  2. Daniel Liberzon, Calculus of Variations and Optimal Control Theory, A Concise Introduction, Princeton University Press, 2012, Section 6.2, Infinite-horizon LQR problem
  3. Dimitri P. Bertsekas, Dynamic Programming and Optimal Control, Volume I, fourth edition, Athena Scientific, 2017, Section 3.1, Linear Systems and Quadratic Cost, on the convergence of the Riccati recursion
  4. Brian D. O. Anderson and John B. Moore, Optimal Control, Linear Quadratic Methods, Prentice Hall, 1990 (Dover reprint, 2007), the infinite-time regulator problem and the stability of the closed loop, in the chapters on the standard regulator problem
  5. Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, Chapter 13, Algebraic Riccati Equations; Chapter 14, H2 Optimal Control
  6. Dario A. Bini, Bruno Iannazzo and Beatrice Meini, Numerical Solution of Algebraic Riccati Equations, SIAM, 2012, the doubling algorithms and their quadratic convergence

Where this leads

About this page

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

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