Algorithm Search⌘K

Algorithmcore

Finite-horizon LQR

Also called Riccati recursion, backward Riccati recursion.

Computes the time-varying optimal gains of a finite-horizon LQ problem by a Riccati difference or differential equation run backward.

Time
O(N (n^3 + m^3)) worst
Space
O(N n m + n^2) extra
Where
N = the number of steps of the horizon; m = the number of inputs; n = the number of states
Properties
deterministicexactofflineiterative
Origin
Rudolf E. Kalman, 1960

Finite-horizon LQR computes the optimal input of the linear quadratic regulator problem on a horizon of NN steps, or on a time interval [0,T][0, T]. The answer is a linear state feedback uk=−Kkxku_k = -K_k x_k whose gain changes with time. In discrete time the gains come from a recursion on symmetric matrices PkP_k that starts at the terminal weight PN=QfP_N = Q_f and runs backward to k=0k = 0. In continuous time the same role is played by the Riccati differential equation, which is integrated backward from P(T)=QfP(T) = Q_f. The matrix PkP_k gives the optimal cost from step kk: it is xkTPkxkx_k^T P_k x_k. The page differs from infinite-horizon LQR, where the horizon is unbounded and the gain is constant, and from the discrete and continuous algebraic Riccati equations, which are the fixed points of the backward recursion.

In plain words

You must steer a system for a fixed number of steps. Each step costs something for being far from zero and something for pushing hard, and the final position has its own cost. The trick is to plan from the end. At the last step there is nothing left to decide, so the cost is known. One step earlier, you can try every push, see where it lands, and add the known cost of that landing point. The best push turns out to be a fixed multiple of the current state, and the best cost is again a simple bowl-shaped function of the state. So the same reasoning repeats, one step earlier each time, back to the start. The output is one gain per step, computed once, before the system runs. While the system runs, the controller only multiplies the measured state by the gain of the current step.

The problem

Discrete time. Input: A∈Rn×nA \in \mathbb{R}^{n \times n}, B∈Rn×mB \in \mathbb{R}^{n \times m}, weights Q=QT≥0Q = Q^T \ge 0, Qf=QfT≥0Q_f = Q_f^T \ge 0 and R=RT>0R = R^T > 0, and a horizon N≥0N \ge 0. The plant is xk+1=Axk+Bukx_{k+1} = A x_k + B u_k and the cost is

J(x0,u0,…,uN−1)=∑k=0N−1(xkTQxk+ukTRuk)+xNTQfxN.J(x_0, u_0, \dots, u_{N-1}) = \sum_{k=0}^{N-1} \left( x_k^T Q x_k + u_k^T R u_k \right) + x_N^T Q_f x_N.

Output: gains K0,…,KN−1∈Rm×nK_0, \dots, K_{N-1} \in \mathbb{R}^{m \times n} such that, for every initial state x0x_0, the inputs uk=−Kkxku_k = -K_k x_k minimize JJ over all input sequences, and matrices P0,…,PNP_0, \dots, P_N such that the minimum of the cost from step kk and state xx is xTPkxx^T P_k x.

Continuous time. The plant is x˙=Ax+Bu\dot x = A x + B u on [0,T][0, T], and the cost is ∫0T(xTQx+uTRu) dt+x(T)TQfx(T)\int_0^T (x^T Q x + u^T R u)\, dt + x(T)^T Q_f x(T). Output: the function P(t)P(t) on [0,T][0, T] and the gain K(t)=R−1BTP(t)K(t) = R^{-1} B^T P(t). This page has no cross term 2xTSu2 x^T S u in the cost; the Variants section gives the change for it. The plant data may also depend on kk or tt; the recursion then uses AkA_k, BkB_k, QkQ_k, RkR_k at step kk with no other change.

The algorithm

  1. FINITE-HORIZON-LQR(A, B, Q, R, Q_f, N)
  2. 1P_N ← Q_f
  3. 2for k ← N - 1 down to 0
  4. 3S_k ← R + B^T P_(k+1) B ▷ m by m, positive definite
  5. 4K_k ← S_k^(-1) B^T P_(k+1) A ▷ solve S_k K_k = B^T P_(k+1) A
  6. 5P_k ← Q + A^T P_(k+1) A - A^T P_(k+1) B K_k
  7. 6return (P_0, ..., P_N), (K_0, ..., K_(N-1))

Line L1 sets the cost of the last state. Lines L3 and L4 compute the optimal gain of step kk from the cost matrix of step k+1k + 1; line L4 solves SkKk=BTPk+1AS_k K_k = B^T P_{k+1} A and does not form Sk−1S_k^{-1}. Line L5 is the Riccati difference equation. It can also be written Pk=Q+KkTRKk+(A−BKk)TPk+1(A−BKk)P_k = Q + K_k^T R K_k + (A - B K_k)^T P_{k+1} (A - B K_k), which is a sum of positive semidefinite terms and keeps the symmetry better in floating point. The implementation also replaces each float PkP_k by (Pk+PkT)/2(P_k + P_k^T)/2.

In continuous time the backward step is replaced by the Riccati differential equation

−P˙(t)=ATP(t)+P(t)A−P(t)BR−1BTP(t)+Q,P(T)=Qf,-\dot P(t) = A^T P(t) + P(t) A - P(t) B R^{-1} B^T P(t) + Q, \qquad P(T) = Q_f,

with the feedback u(t)=−R−1BTP(t)x(t)u(t) = -R^{-1} B^T P(t) x(t). The implementation integrates it in the backward time τ=T−t\tau = T - t with the classical Runge-Kutta method of order 4 and a fixed step T/sT / s for ss steps. To apply the controller to a plant model in continuous time, it stores PP on a grid twice as fine as the simulation step, so every stage of the RK4 step of the plant has its own PP.

Example

Scalar case. Take a=b=q=r=1a = b = q = r = 1, qf=0q_f = 0 and N=5N = 5. Then Sk=1+pk+1S_k = 1 + p_{k+1}, Kk=pk+1/(1+pk+1)K_k = p_{k+1} / (1 + p_{k+1}) and pk=1+pk+1/(1+pk+1)p_k = 1 + p_{k+1} / (1 + p_{k+1}). Starting from p5=0p_5 = 0:

kk 5 4 3 2 1 0
pkp_k 0 1 3/2 8/5 21/13 55/34
KkK_k 0 1/2 3/5 8/13 21/34

The values are ratios of Fibonacci numbers, pN−j=F2j/F2j−1p_{N-j} = F_{2j} / F_{2j-1} for j≥1j \ge 1. They increase toward the golden ratio (1+5)/2=1.618034(1 + \sqrt 5)/2 = 1.618034, and the gains increase toward 0.6180340.618034. These limits are the solution and the gain of the scalar DARE. The last gain K4K_4 is 0: with no terminal cost, the last input only costs and gains nothing.

Sampled double integrator. The zero-order hold model of y¨=u\ddot y = u 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}. Weight the position only, Q=Qf=[1000]Q = Q_f = \begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix}, with R=1R = 1 and N=3N = 3. At k=2k = 2, line L3 gives S2=1+1/4=5/4S_2 = 1 + 1/4 = 5/4, and BTP3A=[1/21/2]B^T P_3 A = \begin{bmatrix} 1/2 & 1/2 \end{bmatrix}, so line L4 gives K2=[2/52/5]K_2 = \begin{bmatrix} 2/5 & 2/5 \end{bmatrix}. Line L5 gives

P2=[1000]+[1111]−[1/51/51/51/5]=[9/54/54/54/5].P_2 = \begin{bmatrix} 1 & 0 \\ 0 & 0 \end{bmatrix} + \begin{bmatrix} 1 & 1 \\ 1 & 1 \end{bmatrix} - \begin{bmatrix} 1/5 & 1/5 \\ 1/5 & 1/5 \end{bmatrix} = \begin{bmatrix} 9/5 & 4/5 \\ 4/5 & 4/5 \end{bmatrix}.

Two more steps give K1=[34/6158/61]K_1 = \begin{bmatrix} 34/61 & 58/61 \end{bmatrix}, K0=[466/949938/949]K_0 = \begin{bmatrix} 466/949 & 938/949 \end{bmatrix} and P0=1949[18179009001388]P_0 = \frac{1}{949}\begin{bmatrix} 1817 & 900 \\ 900 & 1388 \end{bmatrix}. From x0=(1,0)x_0 = (1, 0) the optimal cost is 1817/949=1.9146471817/949 = 1.914647. The tests check P0P_0 exactly against the minimum of JJ over all three inputs, computed by one linear solve on the stacked input vector.

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, R=1R = 1 and Qf=0Q_f = 0, the Riccati differential equation gives these values of P(0)P(0):

TT P11(0)=P22(0)P_{11}(0) = P_{22}(0) P12(0)P_{12}(0)
1 0.964836 0.389571
2 1.536475 0.833236
5 1.730851 0.998961
10 1.732051 1.000000

As TT grows, P(0)P(0) tends to [3113]\begin{bmatrix} \sqrt 3 & 1 \\ 1 & \sqrt 3 \end{bmatrix}, the stabilizing solution of the CARE, and the gain tends to [13]\begin{bmatrix} 1 & \sqrt 3 \end{bmatrix}. For the scalar plant a=b=q=r=1a = b = q = r = 1 with qf=0q_f = 0, the equation is −p˙=2p−p2+1-\dot p = 2p - p^2 + 1, with the closed form p(t)=(p+−wp−)/(1−w)p(t) = (p_+ - w p_-)/(1 - w), where p±=1±2p_\pm = 1 \pm \sqrt 2 and w=(p+/p−) e−22(T−t)w = (p_+ / p_-)\, e^{-2\sqrt 2 (T - t)}. For T=1T = 1 it gives p(0)=1.689498p(0) = 1.689498; the limit for large TT is 1+2=2.4142141 + \sqrt 2 = 2.414214.

Correctness

The full proof is in proofs/correctness.md. In short, it is an induction on kk from NN down to 0, using the principle of optimality: the optimal cost Vk(x)V_k(x) from step kk satisfies the Bellman equation Vk(x)=min⁡u(xTQx+uTRu+Vk+1(Ax+Bu))V_k(x) = \min_u \left( x^T Q x + u^T R u + V_{k+1}(A x + B u) \right) with VN(x)=xTQfxV_N(x) = x^T Q_f x. If Vk+1(x)=xTPk+1xV_{k+1}(x) = x^T P_{k+1} x with Pk+1≥0P_{k+1} \ge 0, the expression in the minimum is uTSku+2uTBTPk+1Ax+xT(Q+ATPk+1A)xu^T S_k u + 2 u^T B^T P_{k+1} A x + x^T (Q + A^T P_{k+1} A) x. Because Sk≥R>0S_k \ge R > 0, it is a strictly convex quadratic in uu, and completing the square gives the unique minimizer u=−Kkxu = -K_k x and the value xTPkxx^T P_k x with PkP_k from line L5. The form Pk=Q+KkTRKk+(A−BKk)TPk+1(A−BKk)P_k = Q + K_k^T R K_k + (A - B K_k)^T P_{k+1} (A - B K_k) shows Pk≥0P_k \ge 0, which keeps the induction going. In continuous time, the identity ddt(xTPx)=−xTQx−uTRu+(u+Kx)TR(u+Kx)\frac{d}{dt} (x^T P x) = -x^T Q x - u^T R u + (u + K x)^T R (u + K x) along every trajectory, integrated from 0 to TT, gives J=x0TP(0)x0+∫0T(u+Kx)TR(u+Kx) dtJ = x_0^T P(0) x_0 + \int_0^T (u + K x)^T R (u + K x)\, dt. The proof file also shows that P(t)P(t) exists on all of [0,T][0, T].

The tests check the recursion in exact rational arithmetic against the stacked least squares minimum on random problems, check that the simulated cost of the feedback equals x0TP0x0x_0^T P_0 x_0 exactly and that random other inputs cost more, check the scalar closed forms, and check that a long horizon gives the DARE and CARE solutions within 10−910^{-9}.

Proof: The backward Riccati recursion gives the optimal feedback and the optimal cost of the finite-horizon LQ problemfull

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, Qf=QfT≥0Q_f = Q_f^T \ge 0, R=RT>0R = R^T > 0 and N≥0N \ge 0. The plant is xk+1=Axk+Bukx_{k+1} = A x_k + B u_k. For 0≤k≤N0 \le k \le N and a state xx, let Vk(x)V_k(x) be the infimum of

Jk(x;uk,…,uN−1)=∑j=kN−1(xjTQxj+ujTRuj)+xNTQfxN,xk=x,J_k(x; u_k, \dots, u_{N-1}) = \sum_{j=k}^{N-1} \left( x_j^T Q x_j + u_j^T R u_j \right) + x_N^T Q_f x_N, \qquad x_k = x,

over all input sequences. The algorithm sets PN=QfP_N = Q_f and, for k=N−1,…,0k = N - 1, \dots, 0,

Sk=R+BTPk+1B,Kk=Sk−1BTPk+1A,Pk=Q+ATPk+1A−ATPk+1BKk.S_k = R + B^T P_{k+1} B, \qquad K_k = S_k^{-1} B^T P_{k+1} A, \qquad P_k = Q + A^T P_{k+1} A - A^T P_{k+1} B K_k.

Lemma 1: completing the square

Let S=ST>0S = S^T > 0 be m×mm \times m, let g∈Rmg \in \mathbb{R}^m and c∈Rc \in \mathbb{R}. Then f(u)=uTSu+2uTg+cf(u) = u^T S u + 2 u^T g + c has the unique minimizer u∗=−S−1gu^* = -S^{-1} g, and f(u)=f(u∗)+(u−u∗)TS(u−u∗)f(u) = f(u^*) + (u - u^*)^T S (u - u^*) with f(u∗)=c−gTS−1gf(u^*) = c - g^T S^{-1} g.

Proof. Expand (u−u∗)TS(u−u∗)=uTSu+2uTg+gTS−1g(u - u^*)^T S (u - u^*) = u^T S u + 2 u^T g + g^T S^{-1} g, using Su∗=−gS u^* = -g and the symmetry of SS. So f(u)−(u−u∗)TS(u−u∗)=c−gTS−1gf(u) - (u - u^*)^T S (u - u^*) = c - g^T S^{-1} g, a constant. The term (u−u∗)TS(u−u∗)(u - u^*)^T S (u - u^*) is positive for u≠u∗u \ne u^* because S>0S > 0. □\square

Lemma 2: the algebra of one step

Let P=PT≥0P = P^T \ge 0, S=R+BTPBS = R + B^T P B, K=S−1BTPAK = S^{-1} B^T P A and P′=Q+ATPA−ATPBKP' = Q + A^T P A - A^T P B K. Then S>0S > 0, P′P' is symmetric, and

P′=Q+KTRK+(A−BK)TP(A−BK)≥0.P' = Q + K^T R K + (A - B K)^T P (A - B K) \ge 0.

Proof. For v≠0v \ne 0, vTSv=vTRv+(Bv)TP(Bv)≥vTRv>0v^T S v = v^T R v + (B v)^T P (B v) \ge v^T R v > 0. So SS is positive definite and invertible. Expand the right side:

(A−BK)TP(A−BK)+KTRK=ATPA−ATPBK−KTBTPA+KTSK.(A - BK)^T P (A - BK) + K^T R K = A^T P A - A^T P B K - K^T B^T P A + K^T S K.

Since SK=BTPAS K = B^T P A, we have KTSK=KTBTPAK^T S K = K^T B^T P A, so the last two terms cancel and the right side equals Q+ATPA−ATPBK=P′Q + A^T P A - A^T P B K = P'. The right side is a sum of symmetric matrices, and each of QQ, KTRKK^T R K and (A−BK)TP(A−BK)(A - BK)^T P (A - BK) is positive semidefinite. So P′P' is symmetric and P′≥0P' \ge 0. □\square

Theorem

For every kk and xx, Vk(x)=xTPkxV_k(x) = x^T P_k x. The minimum is attained, and an input sequence is optimal from (k,x)(k, x) if and only if uj=−Kjxju_j = -K_j x_j for j=k,…,N−1j = k, \dots, N - 1 along the trajectory it produces. All PkP_k are symmetric and positive semidefinite.

Proof. By induction on kk downward. For k=Nk = N there is no input and VN(x)=xTQfx=xTPNxV_N(x) = x^T Q_f x = x^T P_N x, and PN=QfP_N = Q_f is symmetric and positive semidefinite.

Let k<Nk < N and assume the claim for k+1k + 1. Fix xx and any inputs uk,…,uN−1u_k, \dots, u_{N-1}. Split the cost as

Jk(x;uk,… )=xTQx+ukTRuk+Jk+1(Ax+Buk;uk+1,… ).J_k(x; u_k, \dots) = x^T Q x + u_k^T R u_k + J_{k+1}(A x + B u_k; u_{k+1}, \dots).

By the induction hypothesis, Jk+1(y;… )≥yTPk+1yJ_{k+1}(y; \dots) \ge y^T P_{k+1} y for y=Ax+Buky = A x + B u_k, with equality if and only if uk+1,…u_{k+1}, \dots follow the feedback from step k+1k + 1. So

Jk≥xTQx+ukTRuk+(Ax+Buk)TPk+1(Ax+Buk)=ukTSkuk+2ukTBTPk+1Ax+xT(Q+ATPk+1A)x.J_k \ge x^T Q x + u_k^T R u_k + (A x + B u_k)^T P_{k+1} (A x + B u_k) = u_k^T S_k u_k + 2 u_k^T B^T P_{k+1} A x + x^T (Q + A^T P_{k+1} A) x.

This is f(uk)f(u_k) of Lemma 1 with S=SkS = S_k, g=BTPk+1Axg = B^T P_{k+1} A x and c=xT(Q+ATPk+1A)xc = x^T (Q + A^T P_{k+1} A) x; Lemma 2 gives Sk>0S_k > 0. Lemma 1 gives f(uk)≥f(−Kkx)f(u_k) \ge f(-K_k x) with equality if and only if uk=−Kkxu_k = -K_k x, and

f(−Kkx)=xT(Q+ATPk+1A)x−xTATPk+1BSk−1BTPk+1Ax=xTPkx.f(-K_k x) = x^T (Q + A^T P_{k+1} A) x - x^T A^T P_{k+1} B S_k^{-1} B^T P_{k+1} A x = x^T P_k x.

So Jk≥xTPkxJ_k \ge x^T P_k x for every input sequence. Equality holds if and only if uk=−Kkxu_k = -K_k x and the later inputs are optimal from (k+1,Ax+Buk)(k + 1, A x + B u_k), which by the induction hypothesis means that they follow the feedback. This choice exists, so Vk(x)=xTPkxV_k(x) = x^T P_k x and the minimum is attained. Lemma 2 with P=Pk+1P = P_{k+1} gives that PkP_k is symmetric and Pk≥0P_k \ge 0. ■\blacksquare

This is the principle of optimality for this problem: the tail of an optimal sequence is optimal for the tail problem, and VkV_k satisfies the Bellman equation Vk(x)=min⁡u(xTQx+uTRu+Vk+1(Ax+Bu))V_k(x) = \min_u \left( x^T Q x + u^T R u + V_{k+1}(A x + B u) \right).

Exact arithmetic. Each step uses only sums, products and one linear solve with the matrix SkS_k, which is invertible by Lemma 2. So with rational data every PkP_k and KkK_k is rational, and the implementation computes them exactly in Fraction.

Continuous time

Let QQ, QfQ_f, RR be as above and T>0T > 0. Consider x˙=Ax+Bu\dot x = A x + B u on [0,T][0, T] with a measurable, square integrable input uu, and the cost J=∫0T(xTQx+uTRu) dt+x(T)TQfx(T)J = \int_0^T (x^T Q x + u^T R u)\, dt + x(T)^T Q_f x(T). Let G=BR−1BTG = B R^{-1} B^T.

Lemma 3: the Riccati differential equation has a solution on all of [0,T][0, T]. The equation −P˙=ATP+PA−PGP+Q-\dot P = A^T P + P A - P G P + Q, P(T)=QfP(T) = Q_f, has a unique solution on [0,T][0, T], and 0≤P(t)≤Π(t)0 \le P(t) \le \Pi(t), where Π\Pi solves the linear equation −Π˙=ATΠ+ΠA+Q-\dot \Pi = A^T \Pi + \Pi A + Q, Π(T)=Qf\Pi(T) = Q_f.

Proof. The right side is a polynomial in the entries of PP, so it is locally Lipschitz, and a unique solution exists on a maximal interval (t∗,T](t_*, T]. If t∗≥0t_* \ge 0, the solution must be unbounded as t↓t∗t \downarrow t_*. We show that it stays between 00 and Π\Pi, which is bounded on [0,T][0, T], so t∗<0t_* < 0. On (t∗,T](t_*, T], the identity of Lemma 4 below holds for every input, because its proof uses only the equation on the interval [t,T][t, T]. Taking any s∈(t∗,T]s \in (t_*, T] and starting the plant at time ss from xx, it gives xTP(s)x=Js(x,u)−∫sT(u+Kx)TR(u+Kx) dtx^T P(s) x = J_s(x, u) - \int_s^T (u + K x)^T R (u + K x)\, dt for every input. With the feedback u=−Kxu = -K x, which gives a linear equation with continuous coefficients and so a solution on [s,T][s, T], the integral vanishes and xTP(s)xx^T P(s) x is a cost, hence at least 0. With the input u=0u = 0, xTP(s)x≤Js(x,0)=xTΠ(s)xx^T P(s) x \le J_s(x, 0) = x^T \Pi(s) x, where the last equality holds because, for u=0u = 0, ddt(xTΠx)=xT(Π˙+ATΠ+ΠA)x=−xTQx\frac{d}{dt}(x^T \Pi x) = x^T (\dot \Pi + A^T \Pi + \Pi A) x = -x^T Q x, and the integral of this from ss to TT gives x(T)TQfx(T)−xTΠ(s)x=−∫sTxTQx dtx(T)^T Q_f x(T) - x^T \Pi(s) x = -\int_s^T x^T Q x\, dt. Both bounds hold for every xx, so 0≤P(s)≤Π(s)0 \le P(s) \le \Pi(s). □\square

Lemma 4: the cost identity. Let K(t)=R−1BTP(t)K(t) = R^{-1} B^T P(t). For every input uu and every trajectory,

J=x(0)TP(0)x(0)+∫0T(u+Kx)TR(u+Kx) dt.J = x(0)^T P(0) x(0) + \int_0^T (u + K x)^T R (u + K x)\, dt.

Proof. Along a trajectory, using the symmetry of PP,

ddt(xTPx)=xTP˙x+2xTP(Ax+Bu)=xT(P˙+ATP+PA)x+2xTPBu=xT(PGP−Q)x+2xTPBu.\frac{d}{dt} \left( x^T P x \right) = x^T \dot P x + 2 x^T P (A x + B u) = x^T (\dot P + A^T P + P A) x + 2 x^T P B u = x^T (P G P - Q) x + 2 x^T P B u.

Now (u+Kx)TR(u+Kx)=uTRu+2xTPBu+xTPGPx(u + K x)^T R (u + K x) = u^T R u + 2 x^T P B u + x^T P G P x, because KTRK=PBR−1BTP=PGPK^T R K = P B R^{-1} B^T P = P G P and xTKTRu=xTPBux^T K^T R u = x^T P B u. So

ddt(xTPx)=−xTQx−uTRu+(u+Kx)TR(u+Kx).\frac{d}{dt} \left( x^T P x \right) = -x^T Q x - u^T R u + (u + K x)^T R (u + K x).

Integrate from 0 to TT and use P(T)=QfP(T) = Q_f:

x(T)TQfx(T)−x(0)TP(0)x(0)=−∫0T(xTQx+uTRu) dt+∫0T(u+Kx)TR(u+Kx) dt.x(T)^T Q_f x(T) - x(0)^T P(0) x(0) = -\int_0^T (x^T Q x + u^T R u)\, dt + \int_0^T (u + K x)^T R (u + K x)\, dt.

Rearranging gives the identity. □\square

Theorem (continuous time). The minimum of JJ from x(0)=x0x(0) = x_0 is x0TP(0)x0x_0^T P(0) x_0. It is attained by the feedback u(t)=−K(t)x(t)u(t) = -K(t) x(t), and every optimal input equals −K(t)x(t)-K(t) x(t) for almost every tt.

Proof. By Lemma 4, J≥x0TP(0)x0J \ge x_0^T P(0) x_0, because R>0R > 0 makes the integral nonnegative. The feedback makes the integral 0. If the integral is 0 for some input, then u+Kx=0u + K x = 0 almost everywhere, again because R>0R > 0. □\square

The numerical method. The implementation integrates the equation in τ=T−t\tau = T - t, where it reads dP/dτ=ATP+PA−PGP+QdP / d\tau = A^T P + P A - P G P + Q, with the classical RK4 method and a fixed step hh. RK4 has global error O(h4)O(h^4) on a bounded interval for a smooth right side, and Lemma 3 shows that the exact solution stays in a bounded set, so for hh small enough the computed PP is within O(h4)O(h^4) of P(t)P(t) at the grid points. The tests compare it with the scalar closed form within 10−910^{-9}. This part is a property of the integrator, not of the LQ problem.

Complexity

In the real RAM, with dense matrices and flops counted as O(n3)O(n^3) for a dense product or factorization of size nn:

  • Line L3 costs O(n2m+nm2)O(n^2 m + n m^2).
  • Line L4 costs O(n2m)O(n^2 m) for the right side and O(m3+m2n)O(m^3 + m^2 n) for the solve with nn right sides.
  • Line L5 costs O(n3+n2m)O(n^3 + n^2 m).

One step costs O(n3+n2m+nm2+m3)O(n^3 + n^2 m + n m^2 + m^3), which is O(n3+m3)O(n^3 + m^3), and the whole recursion costs O(N(n3+m3))O(N (n^3 + m^3)). Storing all gains takes O(Nnm)O(N n m) space; the recursion itself needs O(n2+nm)O(n^2 + n m). A controller that runs online pays O(nm)O(n m) per step for uk=−Kkxku_k = -K_k x_k. In continuous time, one RK4 step costs four evaluations of the right side, each O(n3+m3)O(n^3 + m^3), and the number of steps is set by the accuracy wanted and by the stiffness of the equation, not by nn.

The stacked formulation, which treats (u0,…,uN−1)(u_0, \dots, u_{N-1}) as one vector of size NmN m, costs O(N3m3)O(N^3 m^3) for a dense solve. The backward recursion uses the stage structure and is linear in NN.

Properties

  • Feedback, not a fixed sequence. The gains do not depend on x0x_0. The same gains are optimal from every initial state, and from every state reached at step kk.
  • Symmetric and positive semidefinite. Every PkP_k is symmetric and Pk≥0P_k \ge 0, by the induction in the proof. If Q>0Q > 0, then Pk≥Q>0P_k \ge Q > 0 for k<Nk < N.
  • Monotone in the horizon. With Qf=0Q_f = 0, the cost matrix P0P_0 of horizon NN does not decrease when NN grows, because a longer horizon adds nonnegative terms to the cost. The scalar example shows this.
  • Convergence for a long horizon. If (A,B)(A, B) is stabilizable and (Q1/2,A)(Q^{1/2}, A) is detectable, then P0→PP_0 \to P as N→∞N \to \infty, where PP is the stabilizing solution of the DARE, for every Qf≥0Q_f \ge 0. Bertsekas (Section 3.1) proves this under the stronger hypotheses that (A,B)(A, B) is controllable and (Q1/2,A)(Q^{1/2}, A) is observable; the stabilizing solution theorem gives the limit. With Qf=PQ_f = P the recursion stays at PP and the gain is constant.
  • Certainty equivalence. If zero mean independent noise wkw_k with finite covariance is added to the plant, the same gains minimize the expected cost (Bertsekas, Section 3.1). The noise only adds a constant to the cost.
  • Duality with the Kalman filter. With A→ATA \to A^T, B→CTB \to C^T, Q→Q \to process noise covariance and R→R \to measurement noise covariance, line L5 becomes the covariance recursion of the Kalman filter, which runs forward in time.

Variants and improvements

  • Time-varying data. For xk+1=Akxk+Bkukx_{k+1} = A_k x_k + B_k u_k and weights QkQ_k, RkR_k, use the data of step kk in lines L3 to L5. In continuous time this is the linear time-varying system case.
  • Cross term. For a cost term 2xkTSuk2 x_k^T S u_k, replace BTPk+1AB^T P_{k+1} A by BTPk+1A+STB^T P_{k+1} A + S^T in line L4, and line L5 becomes Pk=Q+ATPk+1A−(ATPk+1B+S)KkP_k = Q + A^T P_{k+1} A - (A^T P_{k+1} B + S) K_k. The weight matrix [QSSTR]\begin{bmatrix} Q & S \\ S^T & R \end{bmatrix} must be positive semidefinite with R>0R > 0.
  • Tracking. To follow a known reference, add an affine term: the value function becomes xTPkx+2qkTx+ckx^T P_k x + 2 q_k^T x + c_k, and qkq_k follows a linear backward recursion next to PkP_k.
  • Sampled continuous cost. To minimize a continuous cost with a held input, sample the plant with the zero-order hold and compute the matching QQ, SS and RR by one block matrix exponential (Van Loan 1978). The result has a cross term even when the continuous cost has none.
  • Square root forms. For poorly conditioned data, propagate a Cholesky factor of PkP_k with orthogonal transformations instead of PkP_k itself, as in square root Kalman filters.
  • Constraints. With bounds on uku_k or xkx_k the value function is no longer quadratic, and the problem becomes a quadratic program; see linear MPC, which repeats a finite-horizon problem at every sampling instant.

When to use it

Use it when the task has a natural end: a maneuver with a fixed duration, a landing, a batch process, or the inner problem of model predictive control without constraints. It is also the right tool for time-varying plants, where no constant gain exists, for example a trajectory that was linearized along a nominal path. For regulation about an equilibrium over a long time, use infinite-horizon LQR instead. Its constant gain is simpler to implement, and it comes with the stability guarantee that a finite horizon does not give.

Pitfalls

  • Wrong direction. The recursion runs backward from QfQ_f. Running line L5 forward from P0=QfP_0 = Q_f computes the gains of a different problem. In continuous time, integrating the Riccati differential equation forward from P(0)=QfP(0) = Q_f is a sign error, and the solution can blow up.
  • Index shift. The gain KkK_k uses Pk+1P_{k+1}, not PkP_k. An off-by-one error here gives a feedback that looks reasonable and is not optimal.
  • No stability from a finite horizon. The time-varying gains are optimal for the horizon, but the gains near the end are small (here KN−1=0K_{N-1} = 0 when Qf=0Q_f = 0). Repeating the first gain K0K_0 forever as a constant feedback is not guaranteed to give a Schur closed loop unless QfQ_f is chosen well, for example equal to the DARE solution. This is the stability problem of receding horizon control that the MPC stability theorem addresses.
  • Loss of symmetry. In floating point, the form in line L5 can lose symmetry and even positive semidefiniteness. Symmetrize, or use the form Q+KkTRKk+(A−BKk)TPk+1(A−BKk)Q + K_k^T R K_k + (A - B K_k)^T P_{k+1} (A - B K_k).
  • Stiff differential equation. The Riccati differential equation can be stiff when the closed loop has fast and slow modes. A fixed step explicit method then needs a small step. The tests use RK4 with steps of at most 0.010.01 on plants with eigenvalues of size about 1.
  • The name. "Riccati recursion" also names the covariance update of the Kalman filter, so say which one is meant.

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()
finite_horizon_lqr.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/finite-horizon-lqr/. The authors are listed in prov/6S5J80.jsonl.

"""Finite-horizon linear quadratic regulator.

Discrete time. The plant is x_(k+1) = A x_k + B u_k for k = 0, ..., N - 1,
and the cost is

    J = sum_(k=0)^(N-1) (x_k^T Q x_k + u_k^T R u_k) + x_N^T Q_f x_N,

with Q >= 0, Q_f >= 0 and R > 0. The backward recursion

    P_N = Q_f,
    K_k = (R + B^T P_(k+1) B)^(-1) B^T P_(k+1) A,
    P_k = Q + A^T P_(k+1) A - A^T P_(k+1) B K_k,

gives the optimal feedback u_k = -K_k x_k and the optimal cost x_0^T P_0 x_0.
With int or Fraction data every step is exact.

Continuous time. The plant is x' = A x + B u on [0, T], and the cost is the
integral of x^T Q x + u^T R u plus x(T)^T Q_f x(T). The Riccati differential
equation

    -P'(t) = A^T P + P A - P B R^(-1) B^T P + Q,    P(T) = Q_f,

is integrated backward from T with the classical RK4 method and a fixed
step. The optimal feedback is u(t) = -R^(-1) B^T P(t) x(t).
"""

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

__all__ = ["riccati_backward", "lqr_cost", "riccati_ode", "rde_rhs"]


def _sym(p):
    """Return (P + P^T) / 2 for a float matrix; exact matrices are returned as they are."""
    return [[(p[i][j] + p[j][i]) / 2 if isinstance(p[i][j], float) else p[i][j]
             for j in range(len(p))] for i in range(len(p))]


def riccati_backward(A, B, Q, R, Qf, N):
    """Return (Ps, Ks): Ps[k] = P_k for k = 0, ..., N and Ks[k] = K_k for k < N."""
    if N < 0:
        raise ValueError("the horizon N must be at least 0")
    at, bt = transpose(A), transpose(B)
    Ps = [None] * (N + 1)
    Ks = [None] * N
    p = [list(row) for row in Qf]  # @line L1
    Ps[N] = p
    for k in range(N - 1, -1, -1):  # @line L2
        pb = mul(p, B)
        s = add(R, mul(bt, pb))  # @line L3
        kk = solve(s, mul(transpose(pb), A))  # @line L4
        p = sub(add(Q, mul(at, mul(p, A))), mul(at, mul(pb, kk)))  # @line L5
        Ps[k] = _sym(p)
        Ks[k] = kk
        p = Ps[k]
    return Ps, Ks  # @line L6


def lqr_cost(A, B, Q, R, Qf, xs, us):
    """Return the cost J of the trajectory xs (N + 1 states) and inputs us (N inputs)."""
    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)))
    total = 0
    for x, u in zip(xs, us):
        total += quad(Q, x) + quad(R, u)
    return total + quad(Qf, xs[-1])


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


def riccati_ode(A, B, Q, R, Qf, T, steps):
    """Integrate the Riccati differential equation backward from P(T) = Qf.

    Uses `steps` RK4 steps of size T / steps. Returns (ts, Ps) with
    ts[j] = j T / steps and Ps[j] approximately P(ts[j]), so Ps[0] is P(0).
    The cost of the optimal control from x(0) = x_0 is x_0^T P(0) x_0.
    """
    if steps < 1 or T <= 0:
        raise ValueError("T must be positive and steps at least 1")
    h = T / steps
    p = [[float(v) for v in row] for row in Qf]
    Ps = [None] * (steps + 1)
    Ps[steps] = p

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

    for j in range(steps, 0, -1):
        # In backward time tau = T - t the equation is dP/dtau = f(P).
        k1 = f(p)
        k2 = f(add(p, scale(h / 2, k1)))
        k3 = f(add(p, scale(h / 2, k2)))
        k4 = f(add(p, scale(h, k3)))
        inc = add(add(k1, scale(2, k2)), add(scale(2, k3), k4))
        p = _sym(add(p, scale(h / 6, inc)))
        Ps[j - 1] = p
    return [j * h for j in range(steps + 1)], Ps
test_finite_horizon_lqr.py 193 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/finite-horizon-lqr/. The authors are listed in prov/6S5J80.jsonl.

import math
import random
from fractions import Fraction

import pytest

import ctlmat as cm
import ctlsim as cs
from finite_horizon_lqr import lqr_cost, rde_rhs, riccati_backward, riccati_ode


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 batch_value_matrix(A, B, Q, R, Qf, N):
    """Minimum of J over all input sequences, as x0^T W x0, by stacking the inputs.

    x_k = Phi_k x0 + Gamma_k U with U = (u_0, ..., u_(N-1)). J is a quadratic
    form in (x0, U), and the minimum over U is x0^T (M - G^T H^(-1) G) x0.
    This is the brute force reference: one linear solve of size N m, no recursion.
    """
    n, m = len(A), len(B[0])
    phi = cm.eye(n)
    gam = cm.zeros(n, N * m)
    H = cm.zeros(N * m)
    for k in range(N):
        for i in range(m):
            H[k * m + i][k * m:(k + 1) * m] = list(R[i])
    G = cm.zeros(N * m, n)
    M = cm.zeros(n)
    for k in range(N + 1):
        w = Qf if k == N else Q
        gtw = cm.mul(cm.transpose(gam), w)
        H = cm.add(H, cm.mul(gtw, gam))
        G = cm.add(G, cm.mul(gtw, phi))
        M = cm.add(M, cm.mul(cm.transpose(phi), cm.mul(w, phi)))
        if k < N:
            gam = cm.mul(A, gam)
            for i in range(n):
                for j in range(m):
                    gam[i][k * m + j] += B[i][j]
            phi = cm.mul(A, phi)
    return cm.sub(M, cm.mul(cm.transpose(G), cm.solve(H, G))), H


def closed_loop(A, B, Ks):
    def step(k, x, u):
        return [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]

    def control(k, x):
        return [-v for v in cm.matvec(Ks[k], x)]
    return step, control


def test_scalar_fibonacci():
    Ps, Ks = riccati_backward([[1]], [[1]], [[1]], [[1]], [[0]], 5)
    assert [p[0][0] for p in Ps] == [Fraction(55, 34), Fraction(21, 13), Fraction(8, 5),
                                     Fraction(3, 2), 1, 0]
    assert [k[0][0] for k in Ks] == [Fraction(21, 34), Fraction(8, 13), Fraction(3, 5),
                                     Fraction(1, 2), 0]


def test_scalar_limit_is_golden_ratio():
    Ps, Ks = riccati_backward([[1.0]], [[1.0]], [[1.0]], [[1.0]], [[0.0]], 40)
    phi = (1 + math.sqrt(5)) / 2
    assert abs(Ps[0][0][0] - phi) < 1e-12
    assert abs(Ks[0][0][0] - (phi - 1)) < 1e-12


def test_double_integrator_steps_exact():
    A = [[1, 1], [0, 1]]
    B = [[Fraction(1, 2)], [1]]
    Q = [[1, 0], [0, 0]]
    Ps, Ks = riccati_backward(A, B, Q, [[1]], Q, 3)
    assert Ps[2] == [[Fraction(9, 5), Fraction(4, 5)], [Fraction(4, 5), Fraction(4, 5)]]
    assert Ks[2] == [[Fraction(2, 5), Fraction(2, 5)]]
    assert Ps[0] == [[Fraction(1817, 949), Fraction(900, 949)], [Fraction(900, 949), Fraction(1388, 949)]]


def random_problem(rng, n, m):
    A = [[Fraction(rng.randint(-4, 4), 2) for _ in range(n)] for _ in range(n)]
    B = [[Fraction(rng.randint(-3, 3), 2) for _ in range(m)] for _ in range(n)]
    C = [[Fraction(rng.randint(-2, 2)) for _ in range(n)] for _ in range(n)]
    Q = cm.mul(cm.transpose(C), C)
    D = [[Fraction(rng.randint(-2, 2)) for _ in range(m)] for _ in range(m)]
    R = cm.add(cm.mul(cm.transpose(D), D), cm.eye(m))
    E = [[Fraction(rng.randint(-1, 1)) for _ in range(n)] for _ in range(n)]
    Qf = cm.mul(cm.transpose(E), E)
    return A, B, Q, R, Qf


@pytest.mark.parametrize("seed", [1, 2, 3, 4, 5])
def test_matches_batch_minimum_exactly(seed):
    rng = random.Random(seed)
    n, m = rng.choice([(2, 1), (3, 1), (3, 2)])
    N = rng.randint(1, 4)
    A, B, Q, R, Qf = random_problem(rng, n, m)
    Ps, Ks = riccati_backward(A, B, Q, R, Qf, N)
    W, _ = batch_value_matrix(A, B, Q, R, Qf, N)
    assert Ps[0] == W
    for p in Ps:
        assert cm.is_symmetric(p)


@pytest.mark.parametrize("seed", [11, 12, 13])
def test_feedback_cost_and_perturbations(seed):
    rng = random.Random(seed)
    n, m, N = 3, 2, 4
    A, B, Q, R, Qf = random_problem(rng, n, m)
    Ps, Ks = riccati_backward(A, B, Q, R, Qf, N)
    step, control = closed_loop(A, B, Ks)
    x0 = [Fraction(rng.randint(-3, 3)) for _ in range(n)]
    xs, us = cs.simulate_discrete(step, x0, N, control)
    best = lqr_cost(A, B, Q, R, Qf, xs, us)
    assert best == quad(Ps[0], x0)
    for _ in range(10):
        vs = [[u[i] + Fraction(rng.randint(-2, 2), 3) for i in range(m)] for u in us]
        if vs == us:
            continue
        ys, _ = cs.simulate_discrete(step, x0, N, lambda k, x: vs[k])
        assert lqr_cost(A, B, Q, R, Qf, ys, vs) > best


def test_long_horizon_solves_the_dare():
    A = [[1.0, 1.0], [0.0, 1.0]]
    B = [[0.5], [1.0]]
    Q = [[1.0, 0.0], [0.0, 1.0]]
    R = [[1.0]]
    Ps, Ks = riccati_backward(A, B, Q, R, [[0.0, 0.0], [0.0, 0.0]], 80)
    P = Ps[0]
    pb = cm.mul(P, B)
    s = cm.add(R, cm.mul(cm.transpose(B), pb))
    rhs = cm.sub(cm.add(Q, cm.mul(cm.transpose(A), cm.mul(P, A))),
                 cm.mul(cm.mul(cm.transpose(A), pb), cm.solve(s, cm.mul(cm.transpose(pb), A))))
    assert cm.norm2(cm.sub(rhs, P)) < 1e-12 * cm.norm2(P)
    acl = cm.sub(A, cm.mul(B, Ks[0]))
    assert max(abs(z) for z in cm.polyroots(cm.charpoly(acl))) < 1


def test_zero_horizon():
    Ps, Ks = riccati_backward([[2]], [[1]], [[1]], [[1]], [[3]], 0)
    assert Ps == [[[3]]] and Ks == []
    with pytest.raises(ValueError):
        riccati_backward([[2]], [[1]], [[1]], [[1]], [[3]], -1)


def test_scalar_riccati_ode_closed_form():
    T = 1.0
    ts, Ps = riccati_ode([[1.0]], [[1.0]], [[1.0]], [[1.0]], [[0.0]], T, 200)
    s = math.sqrt(2.0)
    pp, pm = 1 + s, 1 - s
    for t, P in zip(ts[::20], Ps[::20]):
        w = (pp / pm) * math.exp(-2 * s * (T - t))
        assert abs(P[0][0] - (pp - w * pm) / (1 - w)) < 1e-9


def test_riccati_ode_long_horizon_tends_to_care():
    A = [[0.0, 1.0], [0.0, 0.0]]
    B = [[0.0], [1.0]]
    Q = [[1.0, 0.0], [0.0, 1.0]]
    _, Ps = riccati_ode(A, B, Q, [[1.0]], [[0.0, 0.0], [0.0, 0.0]], 30.0, 3000)
    r3 = math.sqrt(3.0)
    want = [[r3, 1.0], [1.0, r3]]
    assert max(abs(Ps[0][i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-9
    assert cm.norm2(rde_rhs(A, B, Q, [[1.0]], Ps[0])) < 1e-9


def test_continuous_simulated_cost_equals_value():
    A = [[0.0, 1.0], [-1.0, 0.5]]
    B = [[0.0], [1.0]]
    Q = [[2.0, 0.0], [0.0, 1.0]]
    R = [[0.5]]
    Qf = [[1.0, 0.0], [0.0, 3.0]]
    T, S = 2.0, 400
    _, Ps = riccati_ode(A, B, Q, R, Qf, T, 2 * S)
    half = T / (2 * S)

    def f(t, xa, u):
        x = xa[:2]
        P = Ps[round(t / half)]
        k = cm.solve(R, cm.mul(cm.transpose(B), P))
        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, T, T / S)
    cost = xs[-1][2] + quad(Qf, xs[-1][:2])
    assert abs(cost - quad(Ps[0], x0)) < 1e-8 * quad(Ps[0], x0)

History

Kalman (1960) posed the regulator problem for linear systems with a quadratic cost and showed that the optimal control on a finite interval is a linear feedback whose gain comes from a Riccati differential equation solved backward from the terminal time. The discrete version follows from Bellman's dynamic programming, which was developed in the 1950s. Kalman's paper also studied the limit of an unbounded horizon. The textbooks of Anderson and Moore made the backward Riccati equation the standard tool of the area; their 1990 book is the one cited here.

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 a finite interval and the Riccati differential equation of the optimal cost
  2. Brian D. O. Anderson and John B. Moore, Optimal Control, Linear Quadratic Methods, Prentice Hall, 1990 (Dover reprint, 2007), Chapter 2, The Standard Regulator Problem I
  3. Daniel Liberzon, Calculus of Variations and Optimal Control Theory, A Concise Introduction, Princeton University Press, 2012, Section 6.1, Finite-horizon LQR problem, with Section 6.1.2 on the Riccati differential equation
  4. Dimitri P. Bertsekas, Dynamic Programming and Optimal Control, Volume I, fourth edition, Athena Scientific, 2017, Section 3.1, Linear Systems and Quadratic Cost

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