Algorithm Search⌘K

Algorithmadvanced

Kleinman iteration

Also called Newton-Kleinman method, Newton method for the Riccati equation.

Solves the algebraic Riccati equation by Newton's method, each step a Lyapunov equation, from a stabilizing initial gain.

Time
O(k (n^6 + m^3)) worstO(k (n^3 + m^3)) bartels_stewart
Space
O(n^4 + m^2) extra
Where
k = the number of Newton steps; m = the number of inputs; n = the number of states
Properties
deterministicnot exactiterativeiterative
Origin
David L. Kleinman, 1968

Kleinman iteration solves the continuous algebraic Riccati equation (CARE) ATP+PA−PBR−1BTP+Q=0A^T P + P A - P B R^{-1} B^T P + Q = 0 for its stabilizing solution by Newton's method. It starts from a gain K0K_0 that makes A−BK0A - B K_0 Hurwitz. Each step computes the cost matrix PkP_k of the current gain by one Lyapunov equation and then sets the new gain Kk+1=R−1BTPkK_{k+1} = R^{-1} B^T P_k. The cost matrices decrease monotonically to the solution, every gain on the way is stabilizing, and the convergence is quadratic. Hewer's version does the same for the discrete algebraic Riccati equation with a discrete Lyapunov equation per step. The method needs a stabilizing start, which the Schur method does not. In return each step is a linear problem, and a good start gives the solution in a few steps. In the language of dynamic programming, it is policy iteration for the infinite-horizon LQR problem.

In plain words

You already have a controller that keeps the system stable, but it is not optimal. First measure how much it costs: for a linear controller and a quadratic cost, the cost from every start state is held in one matrix, and that matrix solves a linear equation. Then design the controller that would be best if this cost matrix were the true one. The new controller is never worse, and it is still stable. Measure its cost, improve again, and repeat. Each round fixes most of the remaining error, so the number of correct digits roughly doubles per round once you are close.

The problem

Input: real matrices AA (n×nn \times n), BB (n×mn \times m), Q=QT≥0Q = Q^T \ge 0, R=RT>0R = R^T > 0, and a gain K0K_0 (m×nm \times n) with A−BK0A - B K_0 Hurwitz. Assume that (Q1/2,A)(Q^{1/2}, A) is detectable. Output: the stabilizing solution PP of the CARE and the optimal gain K=R−1BTPK = R^{-1} B^T P. The existence of K0K_0 means that (A,B)(A, B) is stabilizable, so by the stabilizing solution theorem the stabilizing solution exists; the proof of this page also shows it directly.

The algorithm

  1. KLEINMAN-ITERATION(A, B, Q, R, K_0)
  2. 1K ← K_0 ▷ A - B K_0 must be Hurwitz
  3. 2for k ← 0, 1, 2, ...
  4. 3A_k ← A - B K
  5. 4solve A_k^T P + P A_k + Q + K^T R K = 0 for P ▷ Lyapunov equation
  6. 5K ← R^(-1) B^T P
  7. 6if P is close to the previous P then return P, K

Line L1 takes the starting gain. The code checks that A−BK0A - B K_0 is Hurwitz from the roots of its characteristic polynomial and stops with an error otherwise. Line L3 forms the closed loop matrix of the current gain. Line L4 computes PkP_k, the cost matrix of the gain KkK_k: with u=−Kkxu = -K_k x, the cost ∫0∞(xTQx+uTRu) dt\int_0^\infty (x^T Q x + u^T R u)\, dt equals x0TPkx0x_0^T P_k x_0. The implementation solves it in the Kronecker form

(I⊗AkT+AkT⊗I)vec⁡P=−vec⁡(Q+KkTRKk),\left( I \otimes A_k^T + A_k^T \otimes I \right) \operatorname{vec} P = -\operatorname{vec}\left( Q + K_k^T R K_k \right),

a linear system of size n2n^2, with the Kronecker product. Line L5 is the improvement step: Kk+1K_{k+1} minimizes uTRu+2uTBTPkxu^T R u + 2 u^T B^T P_k x over uu for each xx. Line L6 stops when the largest entry of Pk−Pk−1P_k - P_{k-1} is at most 10−1310^{-13} times the largest entry of PkP_k, or after 50 steps. With exact rational data the code can run a fixed number of steps and returns exact fractions.

Line L4 is Newton's step for the map R(X)=ATX+XA−XGX+Q\mathcal{R}(X) = A^T X + X A - X G X + Q, with G=BR−1BTG = B R^{-1} B^T. Its derivative at Pk−1P_{k-1} is E↦(A−GPk−1)TE+E(A−GPk−1)E \mapsto (A - G P_{k-1})^T E + E (A - G P_{k-1}), and A−GPk−1=AkA - G P_{k-1} = A_k. The Newton equation R′(Pk−1)[Pk−Pk−1]=−R(Pk−1)\mathcal{R}'(P_{k-1})[P_k - P_{k-1}] = -\mathcal{R}(P_{k-1}) simplifies to AkTPk+PkAk+Q+Pk−1GPk−1=0A_k^T P_k + P_k A_k + Q + P_{k-1} G P_{k-1} = 0, which is line L4 because KkTRKk=Pk−1GPk−1K_k^T R K_k = P_{k-1} G P_{k-1}.

The discrete-time version (Hewer 1971) solves P=AkTPAk+Q+KkTRKkP = A_k^T P A_k + Q + K_k^T R K_k in line L4, with the Kronecker form (I−AkT⊗AkT)vec⁡P=vec⁡(Q+KkTRKk)(I - A_k^T \otimes A_k^T) \operatorname{vec} P = \operatorname{vec}(Q + K_k^T R K_k), and sets Kk+1=(R+BTPkB)−1BTPkAK_{k+1} = (R + B^T P_k B)^{-1} B^T P_k A in line L5. It needs A−BK0A - B K_0 Schur. The implementation has it as hewer.

Example

Double integrator: 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 K0=[11]K_0 = \begin{bmatrix} 1 & 1 \end{bmatrix}, so A−BK0=[01−1−1]A - B K_0 = \begin{bmatrix} 0 & 1 \\ -1 & -1 \end{bmatrix} has the characteristic polynomial s2+s+1s^2 + s + 1 and is Hurwitz. The solution is P=[3113]P = \begin{bmatrix} \sqrt 3 & 1 \\ 1 & \sqrt 3 \end{bmatrix}. In exact arithmetic every PkP_k has the form [pk11pk]\begin{bmatrix} p_k & 1 \\ 1 & p_k \end{bmatrix}, and the next gain is Kk+1=[1pk]K_{k+1} = \begin{bmatrix} 1 & p_k \end{bmatrix}:

kk KkK_k det⁡(sI−Ak)\det(s I - A_k) pkp_k pk−3p_k - \sqrt 3
0 [1, 1][1,\ 1] s2+s+1s^2 + s + 1 22 2.68×10−12.68 \times 10^{-1}
1 [1, 2][1,\ 2] s2+2s+1s^2 + 2 s + 1 7/47/4 1.79×10−21.79 \times 10^{-2}
2 [1, 7/4][1,\ 7/4] s2+1.75s+1s^2 + 1.75 s + 1 97/5697/56 9.20×10−59.20 \times 10^{-5}
3 [1, 97/56][1,\ 97/56] s2+1.732143s+1s^2 + 1.732143 s + 1 18817/1086418817/10864 2.45×10−92.45 \times 10^{-9}
4 [1, 18817/10864][1,\ 18817/10864] s2+1.732051s+1s^2 + 1.732051 s + 1 1.73205080756887721.7320508075688772 below 10−1510^{-15}

To check row 0 by hand: with P0=[2112]P_0 = \begin{bmatrix} 2 & 1 \\ 1 & 2 \end{bmatrix}, A0TP0=[−1−21−1]A_0^T P_0 = \begin{bmatrix} -1 & -2 \\ 1 & -1 \end{bmatrix}, and A0TP0+P0A0=[−2−1−1−2]=−(Q+K0TK0)A_0^T P_0 + P_0 A_0 = \begin{bmatrix} -2 & -1 \\ -1 & -2 \end{bmatrix} = -(Q + K_0^T K_0). The values pkp_k decrease, every closed loop polynomial has positive coefficients and so is Hurwitz, and the error is roughly squared at each step: 0.2682/4≈0.0180.268^2 / 4 \approx 0.018. Here the iteration is exactly Newton's method for x2=3x^2 = 3, that is pk+1=(pk+3/pk)/2p_{k+1} = (p_k + 3 / p_k)/2.

In discrete time, Hewer's version for a=b=q=r=1a = b = q = r = 1 from K0=1K_0 = 1 gives pk=2,13/8,610/377,1346269/832040p_k = 2, 13/8, 610/377, 1346269/832040, ratios of Fibonacci numbers, which converge to the golden ratio (1+5)/2(1 + \sqrt 5)/2.

Correctness

The full proof is in proofs/correctness.md. Write Dk=Kk−Kk+1D_k = K_k - K_{k+1}. The key identity is

Ak+1TPk+PkAk+1+Q+Kk+1TRKk+1=−DkTRDk,A_{k+1}^T P_k + P_k A_{k+1} + Q + K_{k+1}^T R K_{k+1} = -D_k^T R D_k,

which follows from line L4 and BTPk=RKk+1B^T P_k = R K_{k+1}. It gives three facts. First, Ak+1A_{k+1} is Hurwitz: an eigenvector vv with Re⁡λ≥0\operatorname{Re} \lambda \ge 0 would give Qv=0Q v = 0 and Av=λvA v = \lambda v, which detectability excludes. Second, subtracting line L4 for step k+1k + 1 gives a Lyapunov equation for Pk−Pk+1P_k - P_{k+1} with right side DkTRDk≥0D_k^T R D_k \ge 0, so Pk≥Pk+1P_k \ge P_{k+1}. Third, the sequence is decreasing and bounded below by 0, so it converges, and the limit solves the CARE and is stabilizing. The error Ek=Pk−PE_k = P_k - P satisfies Ak+1TEk+1+Ek+1Ak+1+EkGEk=0A_{k+1}^T E_{k+1} + E_{k+1} A_{k+1} + E_k G E_k = 0, which gives Pk≥PP_k \ge P and ∥Ek+1∥≤c∥Ek∥2\|E_{k+1}\| \le c \|E_k\|^2.

The tests check the exact sequences of the example, check in exact rational arithmetic on random problems that every gain is stabilizing and that Pk−Pk+1P_k - P_{k+1} is positive semidefinite (all principal minors at least 0), check quadratic convergence on the double integrator, and compare 400 random problems with the stable eigenvalues of the Hamiltonian matrix and 80 discrete problems with the Riccati recursion.

Proof: Kleinman iteration stays stabilizing, decreases monotonically and converges quadratically to the stabilizing solution of the CAREfull

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 and R=RT>0R = R^T > 0, and put G=BR−1BTG = B R^{-1} B^T. Assume that (Q1/2,A)(Q^{1/2}, A) is detectable: there is no v≠0v \ne 0 with Av=λvA v = \lambda v, Re⁡λ≥0\operatorname{Re} \lambda \ge 0 and Qv=0Q v = 0 (the PBH test; Qv=0Q v = 0 is the same as Q1/2v=0Q^{1/2} v = 0 because Q≥0Q \ge 0). Let K0K_0 be a gain with A−BK0A - B K_0 Hurwitz. For k=0,1,2,…k = 0, 1, 2, \dots the algorithm sets Ak=A−BKkA_k = A - B K_k, solves

AkTPk+PkAk+Q+KkTRKk=0(1)A_k^T P_k + P_k A_k + Q + K_k^T R K_k = 0 \tag{1}

and sets Kk+1=R−1BTPkK_{k+1} = R^{-1} B^T P_k. Write Dk=Kk−Kk+1D_k = K_k - K_{k+1}.

Lemma 1: Lyapunov equations with a Hurwitz matrix

If FF is Hurwitz and W=WTW = W^T, then FTX+XF+W=0F^T X + X F + W = 0 has exactly one solution, X=∫0∞eFTtWeFt dtX = \int_0^\infty e^{F^T t} W e^{F t}\, dt. It is symmetric, and X≥0X \ge 0 if W≥0W \ge 0.

Proof. The eigenvalues of the linear map X↦FTX+XFX \mapsto F^T X + X F are the sums λi+λj\lambda_i + \lambda_j of eigenvalues of FF, which have negative real part, so the map is invertible and the solution is unique. The integral converges because ∥eFt∥≤ce−αt\|e^{F t}\| \le c e^{-\alpha t} for some cc and α>0\alpha > 0. Its integrand Y(t)=eFTtWeFtY(t) = e^{F^T t} W e^{F t} satisfies Y˙=FTY+YF\dot Y = F^T Y + Y F, so FTX+XF=∫0∞Y˙ dt=−Y(0)=−WF^T X + X F = \int_0^\infty \dot Y\, dt = -Y(0) = -W. Symmetry and X≥0X \ge 0 for W≥0W \ge 0 are clear from the integrand. □\square

Lemma 2: the improvement identity

If PkP_k solves (1) and Kk+1=R−1BTPkK_{k+1} = R^{-1} B^T P_k, then

Ak+1TPk+PkAk+1+Q+Kk+1TRKk+1=−DkTRDk.(2)A_{k+1}^T P_k + P_k A_{k+1} + Q + K_{k+1}^T R K_{k+1} = -D_k^T R D_k. \tag{2}

Proof. Ak+1=Ak+BDkA_{k+1} = A_k + B D_k, and BTPk=RKk+1B^T P_k = R K_{k+1}. So Ak+1TPk+PkAk+1=AkTPk+PkAk+DkTRKk+1+Kk+1TRDkA_{k+1}^T P_k + P_k A_{k+1} = A_k^T P_k + P_k A_k + D_k^T R K_{k+1} + K_{k+1}^T R D_k. By (1) this is −Q−KkTRKk+DkTRKk+1+Kk+1TRDk-Q - K_k^T R K_k + D_k^T R K_{k+1} + K_{k+1}^T R D_k. Add Q+Kk+1TRKk+1Q + K_{k+1}^T R K_{k+1} and put Kk=Kk+1+DkK_k = K_{k+1} + D_k:

−(Kk+1+Dk)TR(Kk+1+Dk)+DkTRKk+1+Kk+1TRDk+Kk+1TRKk+1=−DkTRDk.□-(K_{k+1} + D_k)^T R (K_{k+1} + D_k) + D_k^T R K_{k+1} + K_{k+1}^T R D_k + K_{k+1}^T R K_{k+1} = -D_k^T R D_k. \qquad \square

Lemma 3: every gain stabilizes

For every kk, AkA_k is Hurwitz and Pk≥0P_k \ge 0.

Proof. Induction on kk. For k=0k = 0, A0A_0 is Hurwitz by assumption. Suppose AkA_k is Hurwitz. By Lemma 1, (1) has a unique solution and Pk≥0P_k \ge 0, since Q+KkTRKk≥0Q + K_k^T R K_k \ge 0. Let Ak+1v=λvA_{k+1} v = \lambda v with v≠0v \ne 0. Multiply (2) by v∗v^* on the left and vv on the right:

2Re⁡(λ) v∗Pkv=−v∗Qv−(Kk+1v)∗R(Kk+1v)−(Dkv)∗R(Dkv).2 \operatorname{Re}(\lambda)\, v^* P_k v = -v^* Q v - (K_{k+1} v)^* R (K_{k+1} v) - (D_k v)^* R (D_k v).

If Re⁡λ≥0\operatorname{Re} \lambda \ge 0, the left side is at least 0 and the right side is at most 0, so both are 0. Then Qv=0Q v = 0 (as Q≥0Q \ge 0) and Kk+1v=0K_{k+1} v = 0 (as R>0R > 0). So Av=Ak+1v+BKk+1v=λvA v = A_{k+1} v + B K_{k+1} v = \lambda v with Qv=0Q v = 0 and Re⁡λ≥0\operatorname{Re} \lambda \ge 0, which detectability excludes. Hence Ak+1A_{k+1} is Hurwitz. □\square

Lemma 4: monotone decrease

For every kk, Pk−Pk+1≥0P_k - P_{k+1} \ge 0.

Proof. Equation (1) for k+1k + 1 reads Ak+1TPk+1+Pk+1Ak+1+Q+Kk+1TRKk+1=0A_{k+1}^T P_{k+1} + P_{k+1} A_{k+1} + Q + K_{k+1}^T R K_{k+1} = 0. Subtract it from (2):

Ak+1T(Pk−Pk+1)+(Pk−Pk+1)Ak+1+DkTRDk=0.A_{k+1}^T (P_k - P_{k+1}) + (P_k - P_{k+1}) A_{k+1} + D_k^T R D_k = 0.

Ak+1A_{k+1} is Hurwitz by Lemma 3 and DkTRDk≥0D_k^T R D_k \ge 0, so Lemma 1 gives Pk−Pk+1≥0P_k - P_{k+1} \ge 0. □\square

Lemma 5: the limit is the stabilizing solution

The sequence PkP_k converges to a matrix PP that solves the CARE ATP+PA−PGP+Q=0A^T P + P A - P G P + Q = 0, and A−GPA - G P is Hurwitz.

Proof. By Lemmas 3 and 4, P0≥P1≥⋯≥0P_0 \ge P_1 \ge \dots \ge 0. For each xx, the numbers xTPkxx^T P_k x decrease and are at least 0, so they converge. By polarization, xTPky=14((x+y)TPk(x+y)−(x−y)TPk(x−y))x^T P_k y = \frac14 ((x + y)^T P_k (x + y) - (x - y)^T P_k (x - y)) converges for all xx, yy, so every entry of PkP_k converges. Let PP be the limit. Then Kk+1=R−1BTPk→K:=R−1BTPK_{k+1} = R^{-1} B^T P_k \to K := R^{-1} B^T P, and taking the limit in (1) gives (A−BK)TP+P(A−BK)+Q+KTRK=0(A - B K)^T P + P (A - B K) + Q + K^T R K = 0. With BK=GPB K = G P and KTRK=PGPK^T R K = P G P this is ATP+PA−2PGP+PGP+Q=0A^T P + P A - 2 P G P + P G P + Q = 0, the CARE. Also P≥0P \ge 0. For stability, let (A−GP)v=λv(A - G P) v = \lambda v with v≠0v \ne 0; the limit equation gives 2Re⁡(λ)v∗Pv=−v∗Qv−(Kv)∗R(Kv)2 \operatorname{Re}(\lambda) v^* P v = -v^* Q v - (K v)^* R (K v). If Re⁡λ≥0\operatorname{Re} \lambda \ge 0, both sides are 0, so Qv=0Q v = 0 and Kv=0K v = 0, hence Av=λvA v = \lambda v, which detectability excludes. □\square

A stabilizing solution of the CARE is unique (two of them, PP and P′P', give (A−GP)T(P−P′)+(P−P′)(A−GP′)=0(A - G P)^T (P - P') + (P - P')(A - G P') = 0, a Sylvester equation with a unique solution 0 because the two matrices are Hurwitz). So the limit is the stabilizing solution, whatever stabilizing K0K_0 is used.

Lemma 6: the error identity and quadratic convergence

Let Ek=Pk−PE_k = P_k - P. Then

Ak+1TEk+1+Ek+1Ak+1+EkGEk=0,(3)A_{k+1}^T E_{k+1} + E_{k+1} A_{k+1} + E_k G E_k = 0, \tag{3}

so Ek≥0E_k \ge 0 for k≥1k \ge 1, and there is a constant cc with ∥Ek+1∥≤c∥Ek∥2\|E_{k+1}\| \le c \|E_k\|^2 for all kk.

Proof. Let K=R−1BTPK = R^{-1} B^T P. For any gain LL, the CARE can be written as

(A−BL)TP+P(A−BL)+Q+LTRL=(L−K)TR(L−K),(A - B L)^T P + P (A - B L) + Q + L^T R L = (L - K)^T R (L - K),

because the left side minus the right side equals ATP+PA+Q−KTRKA^T P + P A + Q - K^T R K after expanding with BTP=RKB^T P = R K, and KTRK=PGPK^T R K = P G P. Take L=Kk+1L = K_{k+1} and subtract this from (1) for k+1k + 1. Since Kk+1−K=R−1BT(Pk−P)=R−1BTEkK_{k+1} - K = R^{-1} B^T (P_k - P) = R^{-1} B^T E_k, the right side is EkBR−1RR−1BTEk=EkGEkE_k B R^{-1} R R^{-1} B^T E_k = E_k G E_k, and (3) follows. As Ak+1A_{k+1} is Hurwitz and EkGEk≥0E_k G E_k \ge 0, Lemma 1 gives Ek+1≥0E_{k+1} \ge 0.

For the bound, let Lk(X)=AkTX+XAk\mathcal{L}_k(X) = A_k^T X + X A_k. Then Ek+1=−Lk+1−1(EkGEk)E_{k+1} = -\mathcal{L}_{k+1}^{-1}(E_k G E_k) and ∥Ek+1∥≤∥Lk+1−1∥∥G∥∥Ek∥2\|E_{k+1}\| \le \|\mathcal{L}_{k+1}^{-1}\| \|G\| \|E_k\|^2. The matrices Ak+1=A−GPkA_{k+1} = A - G P_k converge to A−GPA - G P, which is Hurwitz, and F↦∥LF−1∥F \mapsto \|\mathcal{L}_F^{-1}\|, with LF(X)=FTX+XF\mathcal{L}_F(X) = F^T X + X F, is continuous on the open set of Hurwitz matrices FF. A convergent sequence of Hurwitz matrices whose limit is Hurwitz stays in a compact subset of that set, so ∥Lk+1−1∥\|\mathcal{L}_{k+1}^{-1}\| is bounded by some MM, and c=M∥G∥c = M \|G\| works. □\square

Theorem

Under the assumptions above, Kleinman's iteration is well defined, every A−BKkA - B K_k is Hurwitz, P0≥P1≥P2≥⋯≥PP_0 \ge P_1 \ge P_2 \ge \dots \ge P, and PkP_k converges to the stabilizing solution PP of the CARE with ∥Pk−P∥≤c∥Pk−1−P∥2\|P_k - P\| \le c \|P_{k-1} - P\|^2. The implementation stops after at most max_iter steps, or when two successive matrices differ by at most tol times the size of the last one, which happens after finitely many steps because the sequence converges.

Proof. Lemma 3 gives well definedness and stability, Lemma 4 the monotone decrease, Lemma 5 the limit, Lemma 6 the lower bound Pk≥PP_k \ge P for k≥1k \ge 1 (and for k=0k = 0 from P0≥P1P_0 \ge P_1) and the quadratic rate. Termination: the loop runs at most max_iter times. ■\blacksquare

The discrete-time version (Hewer)

Assume (Q1/2,A)(Q^{1/2}, A) detectable in the discrete sense (no v≠0v \ne 0 with Av=λvA v = \lambda v, ∣λ∣≥1|\lambda| \ge 1, Qv=0Q v = 0) and A−BK0A - B K_0 Schur. Hewer's iteration solves Pk=AkTPkAk+Q+KkTRKkP_k = A_k^T P_k A_k + Q + K_k^T R K_k and sets Kk+1=Sk−1BTPkAK_{k+1} = S_k^{-1} B^T P_k A with Sk=R+BTPkBS_k = R + B^T P_k B. The same steps hold with these changes.

  • Lemma 1 becomes: for FF Schur, X=FTXF+WX = F^T X F + W has the unique solution ∑j≥0(FT)jWFj\sum_{j \ge 0} (F^T)^j W F^j.
  • Lemma 2 becomes Ak+1TPkAk+1+Q+Kk+1TRKk+1=Pk−DkTSkDkA_{k+1}^T P_k A_{k+1} + Q + K_{k+1}^T R K_{k+1} = P_k - D_k^T S_k D_k. Proof: f(L)=(A−BL)TPk(A−BL)+Q+LTRL=LTSkL−LTBTPkA−ATPkBL+ATPkA+Qf(L) = (A - B L)^T P_k (A - B L) + Q + L^T R L = L^T S_k L - L^T B^T P_k A - A^T P_k B L + A^T P_k A + Q, and completing the square gives f(L)=f(Kk+1)+(L−Kk+1)TSk(L−Kk+1)f(L) = f(K_{k+1}) + (L - K_{k+1})^T S_k (L - K_{k+1}). Put L=KkL = K_k, where f(Kk)=Pkf(K_k) = P_k.
  • Lemma 3: for Ak+1v=λvA_{k+1} v = \lambda v, the identity gives (∣λ∣2−1)v∗Pkv=−v∗Qv−(Kk+1v)∗R(Kk+1v)−(Dkv)∗Sk(Dkv)(|\lambda|^2 - 1) v^* P_k v = -v^* Q v - (K_{k+1} v)^* R (K_{k+1} v) - (D_k v)^* S_k (D_k v), and ∣λ∣≥1|\lambda| \ge 1 leads to the same contradiction.
  • Lemma 4: Pk−Pk+1=Ak+1T(Pk−Pk+1)Ak+1+DkTSkDk≥0P_k - P_{k+1} = A_{k+1}^T (P_k - P_{k+1}) A_{k+1} + D_k^T S_k D_k \ge 0.
  • Lemma 5 is the same, with the limit equation P=(A−BK)TP(A−BK)+Q+KTRKP = (A - B K)^T P (A - B K) + Q + K^T R K, K=(R+BTPB)−1BTPAK = (R + B^T P B)^{-1} B^T P A, which is the DARE.
  • Lemma 6: with S=R+BTPBS = R + B^T P B, the DARE gives (A−BL)TP(A−BL)+Q+LTRL=P+(L−K)TS(L−K)(A - B L)^T P (A - B L) + Q + L^T R L = P + (L - K)^T S (L - K), so Ek+1=Ak+1TEk+1Ak+1+(Kk+1−K)TS(Kk+1−K)E_{k+1} = A_{k+1}^T E_{k+1} A_{k+1} + (K_{k+1} - K)^T S (K_{k+1} - K). The gain Kk+1=Sk−1BTPkAK_{k+1} = S_k^{-1} B^T P_k A is a smooth function of PkP_k that equals KK at Pk=PP_k = P, so ∥Kk+1−K∥≤c′∥Ek∥\|K_{k+1} - K\| \le c' \|E_k\| near the limit, and ∥Ek+1∥≤c∥Ek∥2\|E_{k+1}\| \le c \|E_k\|^2.

Complexity

In the real RAM, per step:

  • Line L3 costs O(n2m)O(n^2 m).
  • Line L4 forms Q+KTRKQ + K^T R K in O(nm2+n2m)O(n m^2 + n^2 m) and the Kronecker matrix of size n2n^2 in O(n4)O(n^4), and solves it by Gaussian elimination in O(n6)O(n^6).
  • Line L5 solves with RR for nn right sides, O(m3+m2n+n2m)O(m^3 + m^2 n + n^2 m).
  • Line L6 costs O(n2)O(n^2).

Since nm2+n2m≤2(n3+m3)n m^2 + n^2 m \le 2 (n^3 + m^3), one step costs O(n6+m3)O(n^6 + m^3) and kk steps cost O(k(n6+m3))O(k (n^6 + m^3)). The Kronecker matrix takes O(n4)O(n^4) space. With the Bartels-Stewart method, which reduces AkA_k to Schur form and solves a triangular Sylvester equation, line L4 costs O(n3)O(n^3) and the total is O(k(n3+m3))O(k (n^3 + m^3)) with O(n2+m2)O(n^2 + m^2) space. The number of steps kk depends on how far K0K_0 is from the optimum; once the error is small, quadratic convergence means about log⁡2\log_2 of the number of correct digits, so a handful of steps.

Properties

  • Every iterate is stabilizing. Each KkK_k is a usable controller, so the iteration can be stopped at any step with a stable closed loop whose cost xTPkxx^T P_k x is known.
  • Monotone. P0≥P1≥⋯≥PP_0 \ge P_1 \ge \dots \ge P in the positive semidefinite order. The cost never increases.
  • Quadratic convergence. ∥Pk+1−P∥≤c∥Pk−P∥2\|P_{k+1} - P\| \le c \|P_k - P\|^2, the usual rate of Newton's method; see quadratic convergence.
  • Global from a stabilizing start. Unlike Newton's method for general equations, it converges from every stabilizing K0K_0, not only from one close to the solution.
  • Exact steps. With rational data each PkP_k is rational, as the example shows, but the limit is not rational in general.

Variants and improvements

  • Discrete time. Hewer (1971): a discrete Lyapunov equation per step, as above.
  • Line search. Newton steps far from the solution can overshoot. An exact line search along the Newton direction keeps the first steps short when K0K_0 is poor.
  • Bartels-Stewart solves. For larger nn, use a Schur based Lyapunov solver in line L4 in place of the Kronecker form.
  • Low rank Newton. For large sparse AA and low rank QQ and BB, solve each Lyapunov equation approximately with a low rank factor of PkP_k, so PkP_k is never formed.
  • Refinement. Started from the result of the Schur method, one or two steps reduce the residual to the rounding level.
  • Data driven. Policy iteration that estimates PkP_k from measured data in place of the Lyapunov equation is used in adaptive and learning control.

When to use it

Use it when a stabilizing gain is known, for example the current controller of a plant, or the solution of a nearby problem when the data change slowly. It is also a good refinement step after a direct method. When no stabilizing gain is known, the Schur method is the direct alternative, and it needs no start. The Riccati recursion of infinite-horizon LQR needs no stabilizing start either, but converges only linearly. For an unstable AA, find a stabilizing K0K_0 first, for example by pole placement.

Pitfalls

  • Unstable start. If A−BK0A - B K_0 is not Hurwitz, line L4 may have no solution or a solution that is not a cost, and the iteration can converge to a solution that does not stabilize, or diverge. Line L1 must check the start; K0=0K_0 = 0 works only when AA itself is Hurwitz.
  • Wrong gain update. Using K←R−1BTPk−1K \leftarrow R^{-1} B^T P_{k-1} (the old matrix) in line L5 in place of the new PP breaks the identity of the proof and the monotone decrease. Line L5 must use the PP just computed in line L4.
  • Wrong Kronecker form. With column stacking, vec⁡(MX)=(I⊗M)vec⁡X\operatorname{vec}(M X) = (I \otimes M) \operatorname{vec} X and vec⁡(XM)=(MT⊗I)vec⁡X\operatorname{vec}(X M) = (M^T \otimes I) \operatorname{vec} X. Writing Ak⊗IA_k \otimes I in line L4 in place of AkT⊗IA_k^T \otimes I solves a different equation.
  • Stopping on the gain only. Stopping when KK stops changing can stop early when BB is small. Line L6 should test PP, or the CARE residual.
  • No detectability. If (Q1/2,A)(Q^{1/2}, A) is not detectable, the gains can lose stability, and the limit may not be stabilizing. Check the closed loop at the end.

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()
kleinman_iteration.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kleinman-iteration/. The authors are listed in prov/1GNVWG.jsonl.

"""Kleinman iteration: Newton's method for the algebraic Riccati equation.

Continuous time (Kleinman 1968). Start from a gain K_0 with A - B K_0
Hurwitz. For k = 0, 1, 2, ... solve the Lyapunov equation

    (A - B K_k)^T P_k + P_k (A - B K_k) + Q + K_k^T R K_k = 0

and set K_(k+1) = R^(-1) B^T P_k. If (Q^(1/2), A) is detectable, every
A - B K_k is Hurwitz, P_0 >= P_1 >= ... >= P, and P_k converges
quadratically to the stabilizing solution P of the CARE
A^T P + P A - P B R^(-1) B^T P + Q = 0.

Discrete time (Hewer 1971). Start from K_0 with A - B K_0 Schur, solve the
Stein equation P_k = (A - B K_k)^T P_k (A - B K_k) + Q + K_k^T R K_k and set
K_(k+1) = (R + B^T P_k B)^(-1) B^T P_k A.

Each linear matrix equation is solved in its Kronecker form, a dense linear
system of size n^2, which costs O(n^6). This is fine for small n; a
Bartels-Stewart solver brings one step down to O(n^3). With int or Fraction
data the iteration is exact.
"""

from ctlmat import add, charpoly, eye, kron, mul, polyroots, solve, sub, transpose, unvec, vec

__all__ = ["lyap", "stein", "kleinman", "hewer", "care_residual", "dare_residual"]


def _is_float(a):
    return any(isinstance(v, float) for row in a for v in row)


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


def _maxabs(a):
    return max(abs(v) for row in a for v in row)


def lyap(F, W):
    """Return X with F^T X + X F + W = 0, from (I kron F^T + F^T kron I) vec X = -vec W.

    The solution is unique when no two eigenvalues of F sum to 0, for
    example when F is Hurwitz. Cost O(n^6).
    """
    n = len(F)
    ft = transpose(F)
    big = add(kron(eye(n), ft), kron(ft, eye(n)))
    return _sym(unvec(solve(big, [-v for v in vec(W)]), n))


def stein(F, W):
    """Return X with X = F^T X F + W, from (I - F^T kron F^T) vec X = vec W.

    The solution is unique when no product of two eigenvalues of F is 1, for
    example when F is Schur. Cost O(n^6).
    """
    n = len(F)
    ft = transpose(F)
    big = sub(eye(n * n), kron(ft, ft))
    return _sym(unvec(solve(big, vec(W)), n))


def _check_start(F, discrete):
    eigs = polyroots(charpoly(F))
    ok = all(abs(e) < 1 for e in eigs) if discrete else all(e.real < 0 for e in eigs)
    if not ok:
        raise ValueError("the initial gain K_0 does not stabilize A - B K_0")


def kleinman(A, B, Q, R, K0, tol=1e-13, max_iter=50, steps=None):
    """Return (P, K, Ps) by Kleinman's iteration for the CARE.

    Ps is the list P_0, P_1, ... of the cost matrices of the gains K_0,
    K_1, ...; P is the last of them and K = R^(-1) B^T P. The loop stops
    when the largest entry of P_k - P_(k-1) is at most tol times the largest
    entry of P_k, or after max_iter steps; with steps given it does exactly
    that many steps (useful with exact data). Precondition: R > 0 and
    A - B K0 Hurwitz (checked). Cost O(n^6 + n^2 m + m^3) per step with the
    Kronecker solve.
    """
    K = [list(row) for row in K0]  # @line L1
    _check_start(sub(A, mul(B, K)), False)
    bt = transpose(B)
    Ps = []
    limit = steps if steps is not None else max_iter
    for _ in range(limit):  # @line L2
        ak = sub(A, mul(B, K))  # @line L3
        P = lyap(ak, add(Q, mul(transpose(K), mul(R, K))))  # @line L4
        K = solve(R, mul(bt, P))  # @line L5
        Ps.append(P)
        if steps is None and len(Ps) > 1 and _maxabs(sub(P, Ps[-2])) <= tol * max(_maxabs(P), 1e-300):  # @line L6
            break
    return Ps[-1], K, Ps


def hewer(A, B, Q, R, K0, tol=1e-13, max_iter=50, steps=None):
    """Return (P, K, Ps) by Hewer's iteration for the DARE.

    Same conventions as kleinman. Precondition: R > 0 and A - B K0 Schur
    (checked). K = (R + B^T P B)^(-1) B^T P A for the last P.
    """
    K = [list(row) for row in K0]
    _check_start(sub(A, mul(B, K)), True)
    bt = transpose(B)
    Ps = []
    limit = steps if steps is not None else max_iter
    for _ in range(limit):
        ak = sub(A, mul(B, K))
        P = stein(ak, add(Q, mul(transpose(K), mul(R, K))))
        pb = mul(P, B)
        K = solve(add(R, mul(bt, pb)), mul(transpose(pb), A))
        Ps.append(P)
        if steps is None and len(Ps) > 1 and _maxabs(sub(P, Ps[-2])) <= tol * max(_maxabs(P), 1e-300):
            break
    return Ps[-1], K, Ps


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(sub(add(mul(transpose(A), P), mul(P, A)), mul(pb, solve(R, transpose(pb)))), Q)


def dare_residual(A, B, Q, R, P):
    """Return A^T P A - A^T P B (R + B^T P B)^(-1) B^T P A + Q - P."""
    pb = mul(P, B)
    k = solve(add(R, mul(transpose(B), pb)), mul(transpose(pb), A))
    at = transpose(A)
    return sub(add(sub(mul(at, mul(P, A)), mul(at, mul(pb, k))), Q), P)
test_kleinman_iteration.py 208 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kleinman-iteration/. The authors are listed in prov/1GNVWG.jsonl.

import itertools
import math
import random
from fractions import Fraction

import pytest

import ctlmat as cm
from kleinman_iteration import care_residual, dare_residual, hewer, kleinman, lyap, stein


def maxabs(a):
    return max(abs(v) for row in a for v in row)


def is_psd_exact(m):
    """All principal minors of an exact symmetric matrix are at least 0."""
    n = len(m)
    if any(m[i][j] != m[j][i] for i in range(n) for j in range(n)):
        return False
    for size in range(1, n + 1):
        for idx in itertools.combinations(range(n), size):
            if cm.det([[m[i][j] for j in idx] for i in idx]) < 0:
                return False
    return True


def match(xs, ys, tol):
    rest = list(ys)
    for x in xs:
        y = min(rest, key=lambda v: abs(v - x))
        if abs(y - x) > tol * (1 + abs(x)):
            return False
        rest.remove(y)
    return not rest


def hurwitz(m):
    return all(e.real < 0 for e in cm.polyroots(cm.charpoly(m)))


def schur_stable(m):
    return all(abs(e) < 1 for e in cm.polyroots(cm.charpoly(m)))


def rand_mat(rng, n, m, lo=-2.0, hi=2.0):
    return [[rng.uniform(lo, hi) for _ in range(m)] for _ in range(n)]


def rand_pd(rng, n, shift):
    c = rand_mat(rng, n, n, -1.0, 1.0)
    return cm.add(cm.mul(cm.transpose(c), c), cm.scale(shift, cm.eye(n)))


def hamiltonian(A, B, Q, R):
    g = cm.mul(B, cm.solve(R, cm.transpose(B)))
    return cm.block([[A, cm.scale(-1, g)], [cm.scale(-1, Q), cm.scale(-1, cm.transpose(A))]])


def random_problem(rng):
    """A random CARE with a stabilizing K0; half of the plants are unstable."""
    n = rng.randint(1, 3)
    A = rand_mat(rng, n, n)
    if rng.random() < 0.5:
        m = rng.randint(1, 2)
        s = max(sum(abs(v) for v in row) for row in A) + 0.3
        A = cm.sub(A, cm.scale(s, cm.eye(n)))
        B = rand_mat(rng, n, m)
        K0 = cm.zeros(m, n)
    else:
        m = n
        B = cm.add(cm.eye(n), rand_mat(rng, n, n, -0.3, 0.3))
        K0 = cm.solve(B, cm.add(A, cm.eye(n)))
    return A, B, rand_pd(rng, n, 0.1), rand_pd(rng, m, 0.5), K0


def test_double_integrator_exact():
    A, B, Q, R = [[0, 1], [0, 0]], [[0], [1]], cm.eye(2), [[1]]
    P, K, Ps = kleinman(A, B, Q, R, [[1, 1]], steps=4)
    diag = [p[0][0] for p in Ps]
    assert diag == [2, Fraction(7, 4), Fraction(97, 56), Fraction(18817, 10864)]
    assert all(p[0][1] == 1 and p[1][0] == 1 and p[1][1] == p[0][0] for p in Ps)
    assert K == [[1, Fraction(18817, 10864)]]
    # Newton's method for x^2 = 3 from 2 gives the same numbers.
    x = Fraction(2)
    for d in diag:
        assert d == x
        x = (x + 3 / x) / 2


def test_scalar_discrete_fibonacci():
    P, K, Ps = hewer([[1]], [[1]], [[1]], [[1]], [[1]], steps=4)
    assert [p[0][0] for p in Ps] == [2, Fraction(13, 8), Fraction(610, 377), Fraction(1346269, 832040)]
    golden = (1 + math.sqrt(5)) / 2
    assert abs(float(P[0][0]) - golden) < 1e-12


def test_quadratic_convergence():
    A, B, Q, R = [[0.0, 1.0], [0.0, 0.0]], [[0.0], [1.0]], cm.eye(2), [[1.0]]
    r3 = math.sqrt(3.0)
    P, K, Ps = kleinman(A, B, Q, R, [[1.0, 1.0]])
    errs = [maxabs(cm.sub(p, [[r3, 1.0], [1.0, r3]])) for p in Ps]
    assert errs[-1] <= 1e-15
    for e0, e1 in zip(errs, errs[1:]):
        assert e1 <= 0.3 * e0 * e0 + 1e-15
    assert len(Ps) <= 7


def test_lyap_and_stein():
    rng = random.Random(3)
    for _ in range(100):
        n = rng.randint(1, 4)
        F = rand_mat(rng, n, n)
        s = max(sum(abs(v) for v in row) for row in F) + 0.1
        Fh = cm.sub(F, cm.scale(s, cm.eye(n)))
        W = rand_pd(rng, n, 0.0)
        X = lyap(Fh, W)
        assert maxabs(cm.add(cm.add(cm.mul(cm.transpose(Fh), X), cm.mul(X, Fh)), W)) <= 1e-10 * (1 + maxabs(X))
        Fs = cm.scale(0.9 / s, F)
        Y = stein(Fs, W)
        assert maxabs(cm.sub(cm.add(cm.mul(cm.transpose(Fs), cm.mul(Y, Fs)), W), Y)) <= 1e-10 * (1 + maxabs(Y))


def test_exact_monotone_and_stabilizing():
    rng = random.Random(17)
    for _ in range(40):
        n, m = rng.randint(1, 3), rng.randint(1, 2)
        A = [[rng.randint(-3, 3) for _ in range(n)] for _ in range(n)]
        s = max(sum(abs(v) for v in row) for row in A) + 1
        A = cm.sub(A, cm.scale(s, cm.eye(n)))
        B = [[rng.randint(-2, 2) for _ in range(m)] for _ in range(n)]
        C = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(n)]
        Q = cm.add(cm.mul(cm.transpose(C), C), cm.eye(n))
        R = [[rng.randint(1, 3) if i == j else 0 for j in range(m)] for i in range(m)]
        P, K, Ps = kleinman(A, B, Q, R, cm.zeros(m, n), steps=3)
        Pf, _, _ = kleinman([[float(v) for v in row] for row in A], B, Q, R, cm.zeros(m, n))
        Ks = [cm.zeros(m, n)] + [cm.solve(R, cm.mul(cm.transpose(B), p)) for p in Ps]
        for p, k in zip(Ps, Ks):
            assert all(isinstance(v, Fraction) for row in p for v in row)
            assert hurwitz(cm.sub(A, cm.mul(B, k)))
            assert all(v >= -1e-12 for v in vec_minors(cm.sub(p, Pf)))
        for p0, p1 in zip(Ps, Ps[1:]):
            assert is_psd_exact(cm.sub(p0, p1))


def vec_minors(m):
    n = len(m)
    out = []
    for size in range(1, n + 1):
        for idx in itertools.combinations(range(n), size):
            out.append(cm.det([[float(m[i][j]) for j in idx] for i in idx]))
    return out


def test_random_care_against_hamiltonian():
    rng = random.Random(2025)
    for _ in range(400):
        A, B, Q, R, K0 = random_problem(rng)
        P, K, Ps = kleinman(A, B, Q, R, K0)
        assert len(Ps) < 50
        assert maxabs(care_residual(A, B, Q, R, P)) <= 1e-9 * (1 + maxabs(P)) ** 2 * (1 + maxabs(A) + maxabs(B) ** 2)
        assert cm.is_pos_def(P)
        acl = cm.sub(A, cm.mul(B, K))
        eigs = cm.polyroots(cm.charpoly(acl))
        assert all(e.real < 0 for e in eigs)
        hroots = cm.polyroots(cm.charpoly(hamiltonian(A, B, Q, R)))
        assert match(eigs, [r for r in hroots if r.real < 0], 1e-6)
        for p0, p1 in zip(Ps, Ps[1:]):
            d = cm.sub(p0, p1)
            assert min(cm._sym_eigvals(d)) >= -1e-9 * (1 + maxabs(p0))


def test_random_dare_against_recursion():
    rng = random.Random(8)
    for _ in range(100):
        n, m = rng.randint(1, 3), rng.randint(1, 2)
        A = rand_mat(rng, n, n, -1.0, 1.0)
        s = max(sum(abs(v) for v in row) for row in A)
        A = cm.scale(rng.uniform(0.2, 1.6) / max(s, 1e-9), A)
        B = rand_mat(rng, n, m)
        Q, R = rand_pd(rng, n, 0.2), rand_pd(rng, m, 0.5)
        if not schur_stable(A):
            continue
        P, K, Ps = hewer(A, B, Q, R, cm.zeros(m, n))
        ref = cm.zeros(n)
        for _ in range(3000):
            pb = cm.mul(ref, B)
            k = cm.solve(cm.add(R, cm.mul(cm.transpose(B), pb)), cm.mul(cm.transpose(pb), A))
            new = cm.sub(cm.add(Q, cm.mul(cm.transpose(A), cm.mul(ref, A))), cm.mul(cm.transpose(A), cm.mul(pb, k)))
            done = maxabs(cm.sub(new, ref)) <= 1e-15 * maxabs(new)
            ref = new
            if done:
                break
        assert maxabs(cm.sub(P, ref)) <= 1e-8 * max(1.0, maxabs(ref))
        assert maxabs(dare_residual(A, B, Q, R, P)) <= 1e-9 * max(1.0, maxabs(P))
        assert schur_stable(cm.sub(A, cm.mul(B, K)))


def test_unstable_start_raises():
    with pytest.raises(ValueError):
        kleinman([[0, 1], [0, 0]], [[0], [1]], cm.eye(2), [[1]], [[0, 0]])
    with pytest.raises(ValueError):
        kleinman([[1]], [[1]], [[1]], [[1]], [[1]])
    with pytest.raises(ValueError):
        hewer([[2]], [[1]], [[1]], [[1]], [[0]])

History

Kleinman (1968) proposed the iteration for the CARE and proved that every gain stays stabilizing and that the cost matrices decrease to the solution. Hewer (1971) gave the discrete-time version for the steady state gains of the discrete regulator. Policy iteration in dynamic programming, due to Howard, has the same structure, and Kleinman's iteration is now often described as policy iteration for the linear quadratic problem.

References

  1. David L. Kleinman, On an iterative technique for Riccati equation computations, IEEE Transactions on Automatic Control 13(1), 114-115, 1968, the iteration, the stability of each gain and the monotone convergence
  2. G. A. Hewer, An iterative technique for the computation of the steady state gains for the discrete optimal regulator, IEEE Transactions on Automatic Control 16(4), 382-384, 1971, the discrete-time iteration with one discrete Lyapunov equation per step
  3. Peter Lancaster and Leiba Rodman, Algebraic Riccati Equations, Clarendon Press, Oxford, 1995, the Newton method for the continuous and the discrete equation
  4. Dario A. Bini, Bruno Iannazzo and Beatrice Meini, Numerical Solution of Algebraic Riccati Equations, SIAM, 2012, the chapter on Newton's method and its convergence

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.bartels_stewart
  • 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