Algorithm Search⌘K

Algorithmadvanced

Schur method for Riccati equations

Also called Laub's Schur method.

Solves the algebraic Riccati equation from an ordered real Schur form of the Hamiltonian matrix, whose first n Schur vectors span its stable subspace.

Time
O(c n^3) worstO(n^3) typical
Space
O(n^2) extra
Where
c = the largest number of QR steps spent on one eigenvalue; n = the number of states
Properties
deterministicnot exactiterativeiterative
Origin
Alan J. Laub, 1979

The Schur method 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. It forms the 2n×2n2n \times 2n Hamiltonian matrix HH, computes a Schur decomposition Z∗HZ=TZ^* H Z = T with a unitary ZZ, and reorders it so that the nn eigenvalues with negative real part come first. The first nn columns of ZZ then span the stable invariant subspace of HH, and if they are split as [U1U2]\begin{bmatrix} U_1 \\ U_2 \end{bmatrix}, the solution is P=U2U1−1P = U_2 U_1^{-1}. Laub (1979) introduced the method with the real Schur form, which has 2×22 \times 2 blocks for complex pairs. The implementation on this page uses the complex Schur form, which has only 1×11 \times 1 blocks. A variant with a symplectic matrix solves the discrete algebraic Riccati equation (DARE). The method differs from Kleinman iteration, which is Newton's method on the equation and needs a stabilizing start, and from the Riccati recursion of infinite-horizon LQR, which converges only linearly.

In plain words

The Riccati equation is quadratic in a matrix, so it cannot be solved by one linear solve. The trick is to double the size. The matrix HH of size 2n2n holds the data of the equation, and every solution of the equation is a "flat slice" of 2n2n-space that HH maps into itself. The slice we want is the one on which HH shrinks things: the span of the eigenvectors of the eigenvalues with negative real part. Eigenvectors can be badly conditioned, so the method does not compute them. It computes Schur vectors instead. These are orthonormal, and the first kk of them span the same space as the first kk eigenvectors in the Schur order. After the stable eigenvalues are moved to the front, the first nn Schur vectors give the slice, and one linear solve turns the slice into the matrix PP.

The problem

Input: real matrices AA (n×nn \times n), BB (n×mn \times m), Q=QTQ = Q^T (n×nn \times n) and R=RT>0R = R^T > 0 (m×mm \times m). Put G=BR−1BTG = B R^{-1} B^T and

H=[A−G−Q−AT].H = \begin{bmatrix} A & -G \\ -Q & -A^T \end{bmatrix}.

Output: the real symmetric PP with ATP+PA−PGP+Q=0A^T P + P A - P G P + Q = 0 and A−GPA - G P Hurwitz, and the gain K=R−1BTPK = R^{-1} B^T P, or an error if no such PP exists. By the stabilizing solution theorem, such a PP exists when (A,B)(A, B) is stabilizable and HH has no eigenvalue on the imaginary axis, for example when Q≥0Q \ge 0 and (Q1/2,A)(Q^{1/2}, A) is detectable.

The algorithm

  1. SCHUR-METHOD-RICCATI(A, B, Q, R)
  2. 1H ← [[A, -G], [-Q, -A^T]] with G = B R^(-1) B^T
  3. 2(T, Z) ← complex Schur form of H ▷ Z^* H Z = T, Z unitary, T upper triangular
  4. 3if some |Re T_ii| ≤ tol ‖H‖ then error ▷ eigenvalue on or near the imaginary axis
  5. 4swap adjacent diagonal entries of T, updating Z, until Re T_ii < 0 exactly for i ≤ n; error if the count is not n
  6. 5U_1 ← rows 1..n of the first n columns of Z; U_2 ← rows n+1..2n of them
  7. 6solve U_1^T X = U_2^T ▷ error if U_1 is singular or nearly so
  8. 7P ← real part of X^T
  9. 8return P, K = R^(-1) B^T P

Line L1 forms HH with one solve R−1BTR^{-1} B^T; R−1R^{-1} itself is not formed. Line L2 is the QR algorithm. The implementation reduces HH to upper Hessenberg form with Givens rotations (see Hessenberg reduction) and then runs the explicit shifted QR iteration with the Wilkinson shift and deflation. After every 10 steps without a deflation it uses an exceptional shift, and after 30 it stops with an error. Every rotation is applied to TT from both sides and to ZZ from the right, so H=ZTZ∗H = Z T Z^* holds at all times.

Line L3 rejects an eigenvalue whose real part is below 10−8∥H∥F10^{-8} \|H\|_F in absolute value. Such an eigenvalue cannot be put on the correct side of the axis with confidence, and in exact arithmetic an eigenvalue on the axis means that no stabilizing solution exists.

Line L4 moves each stable diagonal entry to the front by swaps of neighbours. One swap of t1=Tkkt_1 = T_{kk} and t2=Tk+1,k+1t_2 = T_{k+1,k+1} uses the rotation that maps the vector (Tk,k+1,t2−t1)(T_{k,k+1}, t_2 - t_1) to a multiple of e1e_1. That vector is the eigenvector of the 2×22 \times 2 block for t2t_2, so the rotated block has t2t_2 first and t1t_1 second.

Lines L5 to L7 compute P=U2U1−1P = U_2 U_1^{-1}. Since (U2U1−1)T=U1−TU2T(U_2 U_1^{-1})^T = U_1^{-T} U_2^T, line L6 is a single solve with nn right sides and no inverse. Before the solve, the code estimates the smallest singular value of U1U_1 and stops if it is below 10−1010^{-10}; a singular U1U_1 means that the stable subspace is not the graph of a matrix, and then no stabilizing solution exists. In exact arithmetic XTX^T is real and symmetric, so line L7 only removes rounding errors. The code also replaces PP by (P+PT)/2(P + P^T)/2.

Example

Scalar case: a=b=q=r=1a = b = q = r = 1. Then H=[1−1−1−1]H = \begin{bmatrix} 1 & -1 \\ -1 & -1 \end{bmatrix} with det⁡(sI−H)=s2−2\det(s I - H) = s^2 - 2, so the eigenvalues are ±2\pm \sqrt 2. The eigenvector for −2-\sqrt 2 solves (1+2)v1−v2=0(1 + \sqrt 2) v_1 - v_2 = 0, so v=(1,1+2)v = (1, 1 + \sqrt 2) up to a factor, and p=v2/v1=1+2≈2.414214p = v_2 / v_1 = 1 + \sqrt 2 \approx 2.414214. Check: 2p−p2+1=2+22−(3+22)+1=02 p - p^2 + 1 = 2 + 2\sqrt 2 - (3 + 2 \sqrt 2) + 1 = 0, and a−b2p/r=−2<0a - b^2 p / r = -\sqrt 2 < 0. In the implementation, one QR step with the Wilkinson shift gives T=diag⁡(2,−2)T = \operatorname{diag}(\sqrt 2, -\sqrt 2) up to the off-diagonal entry, one swap puts −2-\sqrt 2 first, and the first column of ZZ is a unit multiple of (sin⁡(π/8),cos⁡(π/8))(\sin(\pi/8), \cos(\pi/8)), whose ratio cot⁡(π/8)\cot(\pi/8) is 1+21 + \sqrt 2.

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. Here det⁡(sI−H)=s4−s2+1\det(s I - H) = s^4 - s^2 + 1, so s2=e±iπ/3s^2 = e^{\pm i \pi / 3} and the eigenvalues are ±3/2±i/2\pm \sqrt 3 / 2 \pm i / 2. The state of the run, with six decimals:

Step Line State
1 L1 H=[0100000−1−10000−1−10]H = \begin{bmatrix} 0 & 1 & 0 & 0 \\ 0 & 0 & 0 & -1 \\ -1 & 0 & 0 & 0 \\ 0 & -1 & -1 & 0 \end{bmatrix}
2 L2 diagonal of TT: 0.866025+0.5i0.866025 + 0.5 i, 0.866025−0.5i0.866025 - 0.5 i, −0.866025+0.5i-0.866025 + 0.5 i, −0.866025−0.5i-0.866025 - 0.5 i
3 L3 smallest ∣Re⁡Tii∣\lvert \operatorname{Re} T_{ii} \rvert is 0.8660250.866025, far from 0
4 L4 4 swaps; diagonal of TT: −0.866025+0.5i-0.866025 + 0.5 i, −0.866025−0.5i-0.866025 - 0.5 i, 0.866025+0.5i0.866025 + 0.5 i, 0.866025−0.5i0.866025 - 0.5 i; count 2
5 L5 U1U_1 is a complex 2×22 \times 2 matrix with smallest singular value 0.3437240.343724
6 L6 XTX^T has imaginary parts below 1.1×10−151.1 \times 10^{-15} and asymmetry below 1.4×10−151.4 \times 10^{-15}
7 L7 P=[1.732051111.732051]P = \begin{bmatrix} 1.732051 & 1 \\ 1 & 1.732051 \end{bmatrix}, that is [3113]\begin{bmatrix} \sqrt 3 & 1 \\ 1 & \sqrt 3 \end{bmatrix}
8 L8 K=[11.732051]K = \begin{bmatrix} 1 & 1.732051 \end{bmatrix}; A−BKA - B K has eigenvalues −0.866025±0.5i-0.866025 \pm 0.5 i

The closed loop eigenvalues are exactly the stable eigenvalues of HH, as the theory says. The CARE residual of the computed PP is 1.3×10−151.3 \times 10^{-15} in the largest entry.

Correctness

The full proof is in proofs/correctness.md. Every step is a unitary similarity, so after line L4 we have HU=UT11H U = U T_{11}, where U=[U1U2]U = \begin{bmatrix} U_1 \\ U_2 \end{bmatrix} has orthonormal columns and T11T_{11} is the leading n×nn \times n block of TT, with all eigenvalues in the open left half plane. This is the key invariant. If U1U_1 is invertible, multiply the two block rows of HU=UT11H U = U T_{11} by U1−1U_1^{-1} on the right. The first gives A−GP=U1T11U1−1A - G P = U_1 T_{11} U_1^{-1}, so A−GPA - G P is Hurwitz. The second gives −Q−ATP=P(A−GP)-Q - A^T P = P (A - G P), which is the CARE. The matrix W=U1∗U2−U2∗U1W = U_1^* U_2 - U_2^* U_1 solves WT11+T11∗W=0W T_{11} + T_{11}^* W = 0, a Sylvester equation with the unique solution W=0W = 0, so PP is Hermitian; it is real because the stable subspace of a real matrix is closed under conjugation. Conversely, if a stabilizing solution P+P_+ exists, the columns of [IP+]\begin{bmatrix} I \\ P_+ \end{bmatrix} span the same subspace, so U1U_1 is invertible and no check fails. The QR iteration has a step limit, so the algorithm always stops.

The tests check the Schur form on random matrices (unitary ZZ, ZTZ∗=MZ T Z^* = M, eigenvalues equal to the roots of the characteristic polynomial), check the CARE solution on 250 random problems against the stable roots of det⁡(sI−H)\det(s I - H) and on 250 against Newton's method with Kronecker-form Lyapunov solves, check the DARE variant on 100 problems against a long Riccati recursion, and check that the method raises an error on problems with no stabilizing solution.

Proof: The ordered Schur form of the Hamiltonian matrix gives 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=QTQ = Q^T and R=RT>0R = R^T > 0. Put G=BR−1BTG = B R^{-1} B^T, so G=GT≥0G = G^T \ge 0, and

H=[A−G−Q−AT],J=[0I−I0].H = \begin{bmatrix} A & -G \\ -Q & -A^T \end{bmatrix}, \qquad J = \begin{bmatrix} 0 & I \\ -I & 0 \end{bmatrix}.

A stabilizing solution of the CARE ATP+PA−PGP+Q=0A^T P + P A - P G P + Q = 0 is a solution PP for which A−GPA - G P is Hurwitz. The algorithm computes a unitary ZZ and an upper triangular TT with Z∗HZ=TZ^* H Z = T, moves the eigenvalues with negative real part to the first nn places of the diagonal, splits the first nn columns of ZZ as [U1U2]\begin{bmatrix} U_1 \\ U_2 \end{bmatrix}, and returns P=U2U1−1P = U_2 U_1^{-1} and K=R−1BTPK = R^{-1} B^T P. It stops with an error if a diagonal entry of TT lies on the imaginary axis, if the number of entries with negative real part is not nn, or if U1U_1 is singular.

The lemmas below are in exact arithmetic. The last section says what changes in floating point.

Lemma 1: the rotations are unitary similarities

Every step of the algorithm (the reduction to Hessenberg form, each QR step and each swap) replaces TT by GTG∗G T G^* and ZZ by ZG∗Z G^*, where GG is the identity except for a 2×22 \times 2 block [cs−sˉc]\begin{bmatrix} c & s \\ -\bar s & c \end{bmatrix} in rows and columns ii, i+1i + 1, with c≥0c \ge 0 real and c2+∣s∣2=1c^2 + |s|^2 = 1. So the invariant H=ZTZ∗H = Z T Z^* with Z∗Z=IZ^* Z = I holds after every step.

Proof. The block satisfies [cs−sˉc][c−ssˉc]=[c2+∣s∣200∣s∣2+c2]=I\begin{bmatrix} c & s \\ -\bar s & c \end{bmatrix} \begin{bmatrix} c & -s \\ \bar s & c \end{bmatrix} = \begin{bmatrix} c^2 + |s|^2 & 0 \\ 0 & |s|^2 + c^2 \end{bmatrix} = I, so GG is unitary. If H=ZTZ∗H = Z T Z^*, then H=(ZG∗)(GTG∗)(ZG∗)∗H = (Z G^*) (G T G^*) (Z G^*)^*. In a QR step the shift μ\mu is subtracted from the diagonal entries of the active window [l,h][l, h] and added back after the rotations. Each rotation of the step acts on two rows and two columns whose indices lie in the window. If DD is the diagonal matrix with ones on the window and zeros elsewhere, then GDG∗=DG D G^* = D for such a rotation, so G(T−μD)G∗+μD=GTG∗G (T - \mu D) G^* + \mu D = G T G^*, and subtracting and adding μ\mu on the window gives the similarity of the whole matrix. The code stores an entry that a rotation makes zero as an exact 0, and deflation sets a subdiagonal entry below a rounding level to 0. Both change TT by at most a rounding error, which the section on floating point covers; with exact zeros they change nothing. □\square

When the algorithm leaves the QR iteration, TT is upper triangular, so T=Z∗HZT = Z^* H Z is a complex Schur form of HH and its diagonal holds the eigenvalues of HH with their algebraic multiplicities.

Lemma 2: one swap exchanges two diagonal entries

Let TT be upper triangular with t1=Tkk≠t2=Tk+1,k+1t_1 = T_{kk} \ne t_2 = T_{k+1,k+1} and x=Tk,k+1x = T_{k,k+1}. Let GG be the rotation with G[xt2−t1]=[r0]G \begin{bmatrix} x \\ t_2 - t_1 \end{bmatrix} = \begin{bmatrix} r \\ 0 \end{bmatrix}, r≠0r \ne 0, acting on rows and columns kk and k+1k + 1. Then GTG∗G T G^* is upper triangular, with t2t_2 in place kk and t1t_1 in place k+1k + 1.

Proof. Let T2=[t1x0t2]T_2 = \begin{bmatrix} t_1 & x \\ 0 & t_2 \end{bmatrix} and v=[xt2−t1]v = \begin{bmatrix} x \\ t_2 - t_1 \end{bmatrix}. Then T2v=[t1x+x(t2−t1)t2(t2−t1)]=t2vT_2 v = \begin{bmatrix} t_1 x + x (t_2 - t_1) \\ t_2 (t_2 - t_1) \end{bmatrix} = t_2 v. From Gv=re1G v = r e_1 we get G∗e1=v/rG^* e_1 = v / r, so GT2G∗e1=GT2v/r=t2Gv/r=t2e1G T_2 G^* e_1 = G T_2 v / r = t_2 G v / r = t_2 e_1. The first column of the block GT2G∗G T_2 G^* is (t2,0)(t_2, 0), and its trace is t1+t2t_1 + t_2, so its second diagonal entry is t1t_1. The rotation acts on rows kk, k+1k + 1 and columns kk, k+1k + 1 only. Rows kk and k+1k + 1 are zero in the columns before kk, and columns kk and k+1k + 1 are zero in the rows after k+1k + 1, so no other entry below the diagonal changes. □\square

By Lemmas 1 and 2, the reordering ends with HZ=ZTH Z = Z T, TT upper triangular, and the entries with negative real part in places 1,…,n1, \dots, n, provided there are exactly nn of them, which the algorithm checks. Write T11T_{11} for the leading n×nn \times n block of TT and U=[U1U2]U = \begin{bmatrix} U_1 \\ U_2 \end{bmatrix} for the first nn columns of ZZ. Because TT is upper triangular, the first nn columns of HZ=ZTH Z = Z T give

HU=UT11,U∗U=I,(1)H U = U T_{11}, \qquad U^* U = I, \tag{1}

and every eigenvalue of T11T_{11} has negative real part. So the columns of UU span an nn-dimensional invariant subspace V\mathcal{V} of HH, the stable invariant subspace. It is the sum of the generalized eigenspaces of the eigenvalues with negative real part, so it does not depend on the choices made by the QR iteration.

Lemma 3: an invertible U1 gives a stabilizing solution

If U1U_1 is invertible, then P=U2U1−1P = U_2 U_1^{-1} solves the CARE and A−GP=U1T11U1−1A - G P = U_1 T_{11} U_1^{-1}, so A−GPA - G P is Hurwitz.

Proof. The two block rows of (1) are AU1−GU2=U1T11A U_1 - G U_2 = U_1 T_{11} and −QU1−ATU2=U2T11-Q U_1 - A^T U_2 = U_2 T_{11}. Multiply both on the right by U1−1U_1^{-1}. The first gives A−GP=U1T11U1−1A - G P = U_1 T_{11} U_1^{-1}. The second gives −Q−ATP=PU1T11U1−1=P(A−GP)-Q - A^T P = P U_1 T_{11} U_1^{-1} = P (A - G P), which is ATP+PA−PGP+Q=0A^T P + P A - P G P + Q = 0. □\square

Lemma 4: P is real and symmetric

If U1U_1 is invertible, then P=U2U1−1P = U_2 U_1^{-1} is real and P=PTP = P^T.

Proof. Symmetric: the matrix JH=[−Q−AT−AG]J H = \begin{bmatrix} -Q & -A^T \\ -A & G \end{bmatrix} is real and symmetric, so (JH)∗=JH(J H)^* = J H. Since J∗=−JJ^* = -J, this reads −H∗J=JH-H^* J = J H, that is, H∗J=−JHH^* J = -J H. Let W=U∗JU=U1∗U2−U2∗U1W = U^* J U = U_1^* U_2 - U_2^* U_1. Then, by (1), T11∗W=T11∗U∗JU=(HU)∗JU=U∗H∗JU=−U∗JHU=−WT11T_{11}^* W = T_{11}^* U^* J U = (H U)^* J U = U^* H^* J U = -U^* J H U = -W T_{11}. Hence WT11+T11∗W=0W T_{11} + T_{11}^* W = 0. The eigenvalues of T11T_{11} and of −T11∗-T_{11}^* are in the open left and the open right half plane, so they are disjoint, and this Sylvester equation has the unique solution W=0W = 0. So U1∗U2=U2∗U1U_1^* U_2 = U_2^* U_1, and

P∗=U1−∗U2∗=U1−∗(U2∗U1)U1−1=U1−∗(U1∗U2)U1−1=P.P^* = U_1^{-*} U_2^* = U_1^{-*} (U_2^* U_1) U_1^{-1} = U_1^{-*} (U_1^* U_2) U_1^{-1} = P.

Real: HH is real, so complex conjugation maps an invariant subspace of HH to an invariant subspace of HH and maps the eigenvalues to their conjugates, which have the same real part. So Vˉ=V\bar{\mathcal{V}} = \mathcal{V}. Then Uˉ=UM\bar U = U M for an invertible n×nn \times n matrix MM, and Pˉ=Uˉ2Uˉ1−1=U2MM−1U1−1=P\bar P = \bar U_2 \bar U_1^{-1} = U_2 M M^{-1} U_1^{-1} = P. A real Hermitian matrix is real symmetric. □\square

The same computation shows that PP does not depend on the basis: any other basis of V\mathcal{V} is UMU M with MM invertible, and gives the same U2U1−1U_2 U_1^{-1}.

Lemma 5: the checks fail only when no stabilizing solution exists

If the CARE has a stabilizing solution P+P_+, then HH has no eigenvalue on the imaginary axis, it has exactly nn eigenvalues with negative real part, and U1U_1 is invertible.

Proof. Since P+P_+ solves the CARE, H[IP+]=[A−GP+−Q−ATP+]=[IP+](A−GP+)H \begin{bmatrix} I \\ P_+ \end{bmatrix} = \begin{bmatrix} A - G P_+ \\ -Q - A^T P_+ \end{bmatrix} = \begin{bmatrix} I \\ P_+ \end{bmatrix} (A - G P_+), and with E=[I0P+I]E = \begin{bmatrix} I & 0 \\ P_+ & I \end{bmatrix} a short computation gives

E−1HE=[A−GP+−G0−(A−GP+)T].E^{-1} H E = \begin{bmatrix} A - G P_+ & -G \\ 0 & -(A - G P_+)^T \end{bmatrix}.

So the eigenvalues of HH are those of A−GP+A - G P_+, all in the open left half plane, and those of −(A−GP+)T-(A - G P_+)^T, all in the open right half plane. This gives the first two claims. The columns of [IP+]\begin{bmatrix} I \\ P_+ \end{bmatrix} span an invariant subspace of dimension nn whose eigenvalues all have negative real part, so it is contained in V\mathcal{V}, and both have dimension nn, so it equals V\mathcal{V}. Hence U=[IP+]MU = \begin{bmatrix} I \\ P_+ \end{bmatrix} M for an invertible MM, and U1=MU_1 = M is invertible. □\square

Theorem

If the algorithm returns, then PP is the real symmetric stabilizing solution of the CARE and A−BK=A−GPA - B K = A - G P is Hurwitz. It is the only stabilizing solution. The algorithm stops with an error exactly when the CARE has no stabilizing solution, or, in floating point, when the data is within the tolerances of such a case.

Proof. Lemmas 3 and 4 give the first sentence, since BK=BR−1BTP=GPB K = B R^{-1} B^T P = G P. If P′P' is another stabilizing solution, then by Lemma 5 the columns of [IP′]\begin{bmatrix} I \\ P' \end{bmatrix} span V\mathcal{V} too, so [IP′]=[IP]M\begin{bmatrix} I \\ P' \end{bmatrix} = \begin{bmatrix} I \\ P \end{bmatrix} M, which forces M=IM = I and P′=PP' = P. If no stabilizing solution exists, then by Lemma 3 the matrix U1U_1 cannot be invertible, or there is no nn-dimensional stable subspace; either way a check fails. If a stabilizing solution exists, Lemma 5 shows that no check fails. ■\blacksquare

The QR iteration is not proved to converge here. The implementation counts the QR steps since the last deflation, uses an exceptional shift after every 10 steps without a deflation, and raises an error after 30. So it always terminates, and when it returns, Lemmas 1 to 5 apply.

The discrete-time variant

For the DARE P=ATPA−ATPB(R+BTPB)−1BTPA+QP = A^T P A - A^T P B (R + B^T P B)^{-1} B^T P A + Q with AA invertible, the code uses

S=[A+GA−TQ−GA−T−A−TQA−T]=N−1L,L=[A0−QI],N=[IG0AT],S = \begin{bmatrix} A + G A^{-T} Q & -G A^{-T} \\ -A^{-T} Q & A^{-T} \end{bmatrix} = N^{-1} L, \qquad L = \begin{bmatrix} A & 0 \\ -Q & I \end{bmatrix}, \quad N = \begin{bmatrix} I & G \\ 0 & A^T \end{bmatrix},

and selects the eigenvalues with ∣λ∣<1|\lambda| < 1. Lemmas 1 and 2 do not depend on HH, so (1) holds with SS in place of HH, and ∣λ∣<1|\lambda| < 1 for every eigenvalue of T11T_{11}. If U1U_1 is invertible, multiply LU=NUT11L U = N U T_{11} on the right by U1−1U_1^{-1} and put Λ=U1T11U1−1\Lambda = U_1 T_{11} U_1^{-1}. The two block rows are A=(I+GP)ΛA = (I + G P) \Lambda and −Q+P=ATPΛ-Q + P = A^T P \Lambda. Since AA is invertible, so is I+GPI + G P, and Λ=(I+GP)−1A\Lambda = (I + G P)^{-1} A. By Sylvester's determinant identity, det⁡(I+BR−1BTP)=det⁡(I+R−1BTPB)\det(I + B R^{-1} B^T P) = \det(I + R^{-1} B^T P B), so R+BTPBR + B^T P B is invertible. Multiplying out shows (I+GP)(A−B(R+BTPB)−1BTPA)=A(I + G P)(A - B (R + B^T P B)^{-1} B^T P A) = A, so Λ=A−BK\Lambda = A - B K with K=(R+BTPB)−1BTPAK = (R + B^T P B)^{-1} B^T P A, and the second row becomes the DARE. The closed loop Λ\Lambda is similar to T11T_{11}, so it is Schur.

For the symmetry, SS is symplectic: STJS=JS^T J S = J, which follows from G=GTG = G^T and Q=QTQ = Q^T by multiplying out the blocks. With W=U∗JUW = U^* J U and SU=UT11S U = U T_{11} this gives T11∗WT11=U∗S∗JSU=WT_{11}^* W T_{11} = U^* S^* J S U = W, so W=(T11∗)kWT11kW = (T_{11}^*)^k W T_{11}^k for every kk, and W=0W = 0 because T11k→0T_{11}^k \to 0. The rest of Lemma 4 is the same, and Lemma 5 uses E−1SEE^{-1} S E, which is block upper triangular with diagonal blocks A−BKA - B K and (A−BK)−T(A - B K)^{-T} when PP is a stabilizing solution of the DARE.

Floating point

In floating point, Lemma 1 holds with a small error: the computed TT and ZZ satisfy ZTZ∗=H+EZ T Z^* = H + E, with ZZ unitary up to rounding and ∥E∥\|E\| a small multiple of the unit roundoff times ∥H∥\|H\|, because the algorithm uses only Givens rotations (Golub and Van Loan, Chapter 7). The computed basis UU is then an exact stable basis of a nearby matrix. The error in PP is controlled by this backward error and by the conditioning of U1U_1 and of the stable subspace. This is why the code refuses a U1U_1 with smallest singular value below 10−1010^{-10} and an eigenvalue whose real part is within 10−8∥H∥F10^{-8} \|H\|_F of 0. The imaginary part of the computed PP and its departure from symmetry are rounding errors; the code drops the first and averages PP with PTP^T for the second.

Complexity

In the floating point model, with N=2nN = 2n:

  • Line L1 costs O(n2m+m3)O(n^2 m + m^3), or O(n3)O(n^3) when m≤nm \le n.
  • The Hessenberg reduction in line L2 uses about N2/2N^2/2 rotations, each applied to two rows and two columns of length NN, so O(N3)=O(n3)O(N^3) = O(n^3).
  • One QR step on a window of size ww uses w−1w - 1 rotations on full rows and columns, O(Nw)=O(n2)O(N w) = O(n^2). Each of the NN deflations takes at most cc steps, so the iteration costs O(cn3)O(c n^3). In practice the Wilkinson shift gives deflation after a few steps per eigenvalue, so cc is a small constant and the cost is O(n3)O(n^3).
  • Line L4 needs at most n2n^2 swaps, since each of the nn stable entries passes at most nn unstable ones, and a swap costs O(N)O(N). So O(n3)O(n^3).
  • Lines L5 to L8 cost O(n3)O(n^3), including the singular value estimate of U1U_1.

The extra space is O(n2)O(n^2) for HH, TT and ZZ.

Properties

  • Direct up to the eigenvalue iteration. There is no iteration on PP. All the iteration is inside the QR algorithm, whose convergence is fast and well understood in practice, although not proved for every matrix.
  • Unitary transformations. All the work on HH is done with rotations, so the computed TT and ZZ are an exact Schur form of a nearby matrix H+EH + E with ∥E∥\|E\| a small multiple of the unit roundoff times ∥H∥\|H\| (backward error analysis). The error in PP then depends on how well conditioned U1U_1 and the stable subspace are.
  • No structure. The rotations do not preserve the Hamiltonian structure, so H+EH + E is not Hamiltonian in general, and the computed eigenvalues are not exactly symmetric about the imaginary axis. This is why the check of line L3 has a tolerance.
  • Other solutions. Lemma 3 of the proof does not use stability. Moving any nn eigenvalues to the front in line L4 gives a solution of the CARE whenever U1U_1 is invertible, though not always a real symmetric one. Selecting the eigenvalues with positive real part gives the anti-stabilizing solution, for the double integrator [−311−3]\begin{bmatrix} -\sqrt 3 & 1 \\ 1 & -\sqrt 3 \end{bmatrix}.
  • Closed loop for free. The diagonal of T11T_{11} holds the eigenvalues of A−BKA - B K.

Variants and improvements

  • Real Schur form. Laub's original method works in real arithmetic. The real Schur form has 2×22 \times 2 blocks for complex pairs, computed by the Francis double shift QR, and the reordering must swap blocks of size 1 and 2. It does half the arithmetic of the complex form on real data, and the Schur vectors are real, so PP is real without a final real part.
  • Discrete time. For the DARE, replace HH by the symplectic matrix S=[A+GA−TQ−GA−T−A−TQA−T]S = \begin{bmatrix} A + G A^{-T} Q & -G A^{-T} \\ -A^{-T} Q & A^{-T} \end{bmatrix} and select the eigenvalues inside the unit circle. The implementation has this as dare_schur. It needs AA invertible.
  • Generalized Schur form. Without inverting AA (discrete time) or RR (both cases), work with a matrix pencil and compute an ordered generalized Schur form with the QZ algorithm. This handles a singular or badly conditioned AA or RR; Van Dooren (1981) gave a method of this kind. See the generalized eigenvalue problem.
  • Structure preserving methods. Paige and Van Loan (1981) studied a Hamiltonian Schur form, computed with transformations that are both unitary and symplectic. Methods that keep the structure give eigenvalues that are exactly symmetric about the axis.
  • Balancing. Scaling HH or the data before the computation, as in matrix balancing, can reduce the error when the entries of AA, QQ and GG have very different sizes.
  • Newton refinement. One or two steps of Kleinman iteration started from the Schur solution often reduce the residual to the rounding level, since the Schur solution is stabilizing and close.

When to use it

Use it for dense problems of small and medium size, when no stabilizing gain is known in advance. It needs no starting point, it is the standard direct method, and it gives the closed loop eigenvalues as a by-product. Kleinman iteration needs a stabilizing start, but converges quadratically and is good for refining a solution or for tracking a slowly changing problem. The Riccati recursion of infinite-horizon LQR is simple but converges only linearly, and slowly when the closed loop is close to the stability boundary. For large sparse problems with a low rank QQ, dense O(n3)O(n^3) methods are too expensive, and low rank Newton or Krylov methods are used instead.

Pitfalls

  • Wrong half of the spectrum. If line L4 selects the eigenvalues with positive real part, the result is the anti-stabilizing solution, and A−BKA - B K is unstable. Line L4 must select Re⁡Tii<0\operatorname{Re} T_{ii} < 0 (or ∣Tii∣<1\lvert T_{ii} \rvert < 1 in discrete time).
  • Forming the inverse. Computing U1−1U_1^{-1} and then U2U1−1U_2 U_1^{-1} costs more and is less accurate than the solve of line L6. Check the conditioning of U1U_1 before line L6: a nearly singular U1U_1 gives a huge and meaningless PP, not an error.
  • No check on the axis. Without line L3, an eigenvalue close to the axis can fall on the wrong side by rounding, and the count in line L4 is then n±1n \pm 1, or the subspace is the wrong one. Line L3 must reject such cases, and the user should then check stabilizability and detectability.
  • Complex output. With the complex Schur form, line L7 must take the real part. Returning XTX^T as it is gives complex entries of size 10−1610^{-16}, and code that expects a real matrix can fail.
  • Eigenvectors instead of Schur vectors. Computing nn eigenvectors of HH in line L2 fails when HH has a multiple eigenvalue without a full set of eigenvectors, and is inaccurate when eigenvalues are close. Schur vectors always exist and are orthonormal.

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()
schur_method_riccati.py 298 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/schur-method-riccati/. The authors are listed in prov/TKPRJX.jsonl.

"""Schur method for the algebraic Riccati equations (Laub 1979).

Continuous time (CARE): A^T P + P A - P G P + Q = 0 with G = B R^(-1) B^T.
The Hamiltonian matrix H = [[A, -G], [-Q, -A^T]] is reduced to an upper
triangular Schur form T = Z^* H Z with a unitary Z. The diagonal of T is
reordered so that the n eigenvalues with negative real part come first.
Then the first n columns of Z, split as [U1; U2], span the stable invariant
subspace of H, and P = U2 U1^(-1). The gain is K = R^(-1) B^T P.

Discrete time (DARE): P = A^T P A - A^T P B (R + B^T P B)^(-1) B^T P A + Q.
The same steps are applied to the symplectic matrix

    S = [[A + G A^(-T) Q, -G A^(-T)], [-A^(-T) Q, A^(-T)]],

with the eigenvalues inside the unit circle put first. This form needs A to
be invertible.

Laub used the real Schur form, with 2 by 2 blocks for complex pairs. This
file uses the complex Schur form, which has only 1 by 1 blocks and so needs
only one kind of swap. The Schur form is computed by a reduction to
Hessenberg form with Givens rotations and an explicit shifted QR iteration
with the Wilkinson shift and deflation.

The functions raise ValueError if H (or S) has an eigenvalue on or near the
imaginary axis (or the unit circle), if the number of stable eigenvalues is
not n, or if U1 is singular or nearly singular. In each case the equation
has no stabilizing solution, or the data is too close to such a case.
"""

import cmath
import math

from ctlmat import add, block, inv, mul, norm2, scale, solve, sub, transpose

__all__ = [
    "hamiltonian", "symplectic", "schur_form", "swap", "reorder",
    "care_schur", "dare_schur", "care_residual", "dare_residual",
]

EPS = 2.0 ** -52


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


def _fro(a):
    return math.sqrt(sum(abs(v) ** 2 for row in a for v in row))


def _g(B, R):
    return _float(mul(B, solve(R, transpose(B))))


def hamiltonian(A, B, Q, R):
    """Return H = [[A, -G], [-Q, -A^T]] with G = B R^(-1) B^T, in float."""
    g = _g(B, R)
    a = _float(A)
    return block([[a, scale(-1.0, g)], [scale(-1.0, _float(Q)), scale(-1.0, transpose(a))]])


def symplectic(A, B, Q, R):
    """Return [[A + G A^(-T) Q, -G A^(-T)], [-A^(-T) Q, A^(-T)]] for the DARE.

    Raises ValueError if A is singular.
    """
    a = _float(A)
    q = _float(Q)
    g = _g(B, R)
    ait = transpose(inv(a))
    return block([
        [add(a, mul(g, mul(ait, q))), scale(-1.0, mul(g, ait))],
        [scale(-1.0, mul(ait, q)), ait],
    ])


def _rot(a, b):
    """Return (c, s) such that [[c, s], [-conj(s), c]] maps (a, b) to (r, 0)."""
    if b == 0:
        return 1.0, 0j
    if a == 0:
        return 0.0, 1 + 0j
    aa = abs(a)
    r = math.hypot(aa, abs(b))
    return aa / r, (a / aa) * b.conjugate() / r


def _left(t, i, j, c, s):
    """Rows i, j of t become c row_i + s row_j and -conj(s) row_i + c row_j."""
    ri, rj = t[i], t[j]
    sc = s.conjugate()
    for k in range(len(ri)):
        x, y = ri[k], rj[k]
        ri[k] = c * x + s * y
        rj[k] = -sc * x + c * y


def _right(t, i, j, c, s):
    """Multiply columns i, j of t on the right by the conjugate transpose of the rotation."""
    sc = s.conjugate()
    for row in t:
        x, y = row[i], row[j]
        row[i] = c * x + sc * y
        row[j] = -s * x + c * y


def _similar(t, z, i, j, c, s):
    _left(t, i, j, c, s)
    _right(t, i, j, c, s)
    _right(z, i, j, c, s)


def _wilkinson(a, b, c, d):
    """Return the eigenvalue of [[a, b], [c, d]] that is nearest to d."""
    h = (a - d) / 2
    disc = cmath.sqrt(h * h + b * c)
    den = h + disc if abs(h + disc) >= abs(h - disc) else h - disc
    if den == 0:
        return d
    return d - b * c / den


def schur_form(M, max_steps=30):
    """Return (T, Z) with Z unitary, T upper triangular and M = Z T Z^*.

    Entries are complex. Givens rotations reduce M to Hessenberg form, then
    the explicit shifted QR iteration with the Wilkinson shift reduces it to
    triangular form. A subdiagonal entry is set to 0 when it is below EPS
    times the sum of its two diagonal neighbours (or EPS times the norm of
    M). Raises ValueError after max_steps QR steps without a deflation.
    """
    n = len(M)
    t = [[complex(v) for v in row] for row in M]
    z = [[1 + 0j if i == j else 0j for j in range(n)] for i in range(n)]
    for j in range(n - 2):
        for i in range(n - 1, j + 1, -1):
            if t[i][j] != 0:
                c, s = _rot(t[i - 1][j], t[i][j])
                _similar(t, z, i - 1, i, c, s)
                t[i][j] = 0j
    hnorm = _fro(t)
    hi = n - 1
    steps = 0
    while hi > 0:
        l = hi
        while l > 0:
            sub_ = abs(t[l][l - 1])
            if sub_ <= EPS * (abs(t[l - 1][l - 1]) + abs(t[l][l])) or sub_ <= EPS * hnorm:
                t[l][l - 1] = 0j
                break
            l -= 1
        if l == hi:
            hi -= 1
            steps = 0
            continue
        steps += 1
        if steps > max_steps:
            raise ValueError("schur_form: the QR iteration does not converge")
        if steps % 10 == 0:
            mu = t[hi][hi] + abs(t[hi][hi - 1]) * (0.75 + 0.5j)
        else:
            mu = _wilkinson(t[hi - 1][hi - 1], t[hi - 1][hi], t[hi][hi - 1], t[hi][hi])
        for k in range(l, hi + 1):
            t[k][k] -= mu
        rots = []
        for k in range(l, hi):
            c, s = _rot(t[k][k], t[k + 1][k])
            _left(t, k, k + 1, c, s)
            t[k + 1][k] = 0j
            rots.append((k, c, s))
        for k, c, s in rots:
            _right(t, k, k + 1, c, s)
            _right(z, k, k + 1, c, s)
        for k in range(l, hi + 1):
            t[k][k] += mu
    for i in range(n):
        for j in range(i):
            t[i][j] = 0j
    return t, z


def swap(T, Z, k):
    """Swap the diagonal entries k and k + 1 of the triangular T in place.

    A Givens rotation G is built from the eigenvector (T[k][k+1], t2 - t1) of
    the 2 by 2 block, and T becomes G T G^*, Z becomes Z G^*.
    """
    t1, t2 = T[k][k], T[k + 1][k + 1]
    if t1 == t2:
        return
    c, s = _rot(T[k][k + 1], t2 - t1)
    _similar(T, Z, k, k + 1, c, s)
    T[k + 1][k] = 0j
    T[k][k] = t2
    T[k + 1][k + 1] = t1


def reorder(T, Z, select):
    """Move the diagonal entries d with select(d) true to the front, in place.

    Returns the number of selected entries. The relative order inside each
    group is kept.
    """
    pos = 0
    for i in range(len(T)):
        if select(T[i][i]):
            for k in range(i - 1, pos - 1, -1):
                swap(T, Z, k)
            pos += 1
    return pos


def _solve_basis(M, n, stable, margin, axis_tol, cond_tol):
    """Return P = U2 U1^(-1) from the stable invariant subspace of the 2n by 2n matrix M.

    stable(d) selects the wanted eigenvalues, and margin(d) is the distance
    of d from the stability boundary. Cost O(n^3) flops in the usual case.
    """
    T, Z = schur_form(M)  # @line L2
    scale_ = max(_fro(M), 1e-300)
    for i in range(2 * n):  # @line L3
        if margin(T[i][i]) <= axis_tol * scale_:
            raise ValueError("an eigenvalue lies on or near the stability boundary")
    count = reorder(T, Z, stable)  # @line L4
    if count != n:
        raise ValueError("the number of stable eigenvalues is not n")
    u1 = [row[:n] for row in Z[:n]]  # @line L5
    u2 = [row[:n] for row in Z[n:]]
    try:
        u1_inv = inv(u1)
    except ValueError:
        raise ValueError("U1 is singular: no stabilizing solution") from None
    if 1.0 / norm2(u1_inv) < cond_tol:
        raise ValueError("U1 is nearly singular: no stabilizing solution")
    pt = solve(transpose(u1), transpose(u2))  # @line L6
    p = [[v.real for v in row] for row in transpose(pt)]  # @line L7
    return p, T, Z


def care_schur(A, B, Q, R, axis_tol=1e-8, cond_tol=1e-10, symmetrize=True):
    """Return (P, K) for the stabilizing solution of the CARE by the Schur method.

    P solves A^T P + P A - P B R^(-1) B^T P + Q = 0, K = R^(-1) B^T P and
    A - B K is Hurwitz. With symmetrize=False the computed P is returned
    without the final (P + P^T) / 2.

    Precondition: R is symmetric positive definite and Q is symmetric. The
    result exists if (A, B) is stabilizable and H has no eigenvalue on the
    imaginary axis (for example if (Q^(1/2), A) is detectable). Cost: O(n^3)
    flops when each eigenvalue needs a bounded number of QR steps, which is
    the usual case; O(c n^3) with at most c QR steps per eigenvalue.
    """
    n = len(A)
    h = hamiltonian(A, B, Q, R)  # @line L1
    p, _, _ = _solve_basis(h, n, lambda d: d.real < 0, lambda d: abs(d.real), axis_tol, cond_tol)
    if symmetrize:
        p = [[(p[i][j] + p[j][i]) / 2 for j in range(n)] for i in range(n)]
    k = _float(solve(R, mul(transpose(B), p)))
    return p, k  # @line L8


def dare_schur(A, B, Q, R, axis_tol=1e-8, cond_tol=1e-10, symmetrize=True):
    """Return (P, K) for the stabilizing solution of the DARE by the Schur method.

    P solves P = A^T P A - A^T P B (R + B^T P B)^(-1) B^T P A + Q,
    K = (R + B^T P B)^(-1) B^T P A and A - B K is Schur. A must be invertible.
    """
    n = len(A)
    try:
        s = symplectic(A, B, Q, R)
    except ValueError:
        raise ValueError("dare_schur: A is singular") from None
    p, _, _ = _solve_basis(s, n, lambda d: abs(d) < 1, lambda d: abs(abs(d) - 1), axis_tol, cond_tol)
    if symmetrize:
        p = [[(p[i][j] + p[j][i]) / 2 for j in range(n)] for i in range(n)]
    pb = mul(p, _float(B))
    k = solve(add(_float(R), mul(transpose(_float(B)), pb)), mul(transpose(pb), _float(A)))
    return p, k


def care_residual(A, B, Q, R, P):
    """Return A^T P + P A - P G P + Q with G = B R^(-1) B^T."""
    a = _float(A)
    g = _g(B, R)
    return add(sub(add(mul(transpose(a), P), mul(P, a)), mul(P, mul(g, P))), _float(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."""
    a = _float(A)
    b = _float(B)
    pb = mul(P, b)
    k = solve(add(_float(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))), _float(Q)), P)
test_schur_method_riccati.py 230 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/schur-method-riccati/. The authors are listed in prov/TKPRJX.jsonl.

import cmath
import math
import random

import pytest

import ctlmat as cm
from schur_method_riccati import (
    care_residual, care_schur, dare_residual, dare_schur, hamiltonian, reorder, schur_form, swap, symplectic,
)

R3 = math.sqrt(3.0)


def ctrans(a):
    return [[v.conjugate() if isinstance(v, complex) else v for v in row] for row in cm.transpose(a)]


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


def fro(a):
    return math.sqrt(sum(abs(v) ** 2 for row in a for v in row))


def check_schur(M, T, Z, tol):
    n = len(M)
    scale = max(fro(M), 1.0)
    assert maxabs(cm.sub(cm.mul(ctrans(Z), Z), cm.eye(n))) <= tol
    assert maxabs(cm.sub(cm.mul(Z, cm.mul(T, ctrans(Z))), M)) <= tol * scale
    assert all(T[i][j] == 0 for i in range(n) for j in range(i))


def match(xs, ys, tol):
    """Return True if the two lists of complex numbers are equal as multisets, within 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 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 newton_care(A, B, Q, R):
    """Reference: Newton's method on the CARE from K = 0 (A must be Hurwitz).

    Each step solves the Lyapunov equation by its Kronecker form.
    """
    n, m = len(A), len(B[0])
    K = cm.zeros(m, n)
    P = cm.zeros(n)
    for _ in range(60):
        acl = cm.sub(A, cm.mul(B, K))
        w = cm.add(Q, cm.mul(cm.transpose(K), cm.mul(R, K)))
        act = cm.transpose(acl)
        big = cm.add(cm.kron(cm.eye(n), act), cm.kron(act, cm.eye(n)))
        new = cm.unvec(cm.solve(big, [-v for v in cm.vec(w)]), n)
        done = maxabs(cm.sub(new, P)) <= 1e-14 * max(1.0, maxabs(new))
        P = new
        K = cm.solve(R, cm.mul(cm.transpose(B), P))
        if done:
            break
    return P


def riccati_iteration(A, B, Q, R, steps):
    """Reference: the backward Riccati recursion of the DARE from P = 0."""
    n = len(A)
    P = cm.zeros(n)
    at = cm.transpose(A)
    for _ in range(steps):
        pb = cm.mul(P, 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(at, cm.mul(P, A))), cm.mul(at, cm.mul(pb, k)))
        new = [[(new[i][j] + new[j][i]) / 2 for j in range(n)] for i in range(n)]
        if maxabs(cm.sub(new, P)) <= 1e-15 * maxabs(new):
            return new
        P = new
    return P


def test_double_integrator_and_scalar():
    P, K = care_schur([[0, 1], [0, 0]], [[0], [1]], cm.eye(2), [[1]])
    assert maxabs(cm.sub(P, [[R3, 1.0], [1.0, R3]])) <= 1e-12
    assert maxabs(cm.sub(K, [[1.0, R3]])) <= 1e-12
    P, K = care_schur([[1]], [[1]], [[1]], [[1]])
    assert abs(P[0][0] - (1 + math.sqrt(2))) <= 1e-12
    # (a, b) = (-1, 0) is stabilizable but not controllable: P solves -2 p + q = 0.
    P, K = care_schur([[-1]], [[0]], [[3]], [[1]])
    assert abs(P[0][0] - 1.5) <= 1e-12 and K[0][0] == 0


def test_dare_examples():
    P, K = dare_schur([[1]], [[1]], [[1]], [[1]])
    assert abs(P[0][0] - (1 + math.sqrt(5)) / 2) <= 1e-12
    P, K = dare_schur([[2]], [[1]], [[1]], [[1]])
    assert abs(P[0][0] - (2 + math.sqrt(5))) <= 1e-12
    A, B = [[1, 1], [0, 1]], [[0.5], [1]]
    P, K = dare_schur(A, B, cm.eye(2), [[1]])
    assert maxabs(cm.sub(P, [[2.367101490947877, math.sqrt(5) / 2], [math.sqrt(5) / 2, 2.587482927325332]])) <= 1e-11
    assert maxabs(dare_residual(A, B, cm.eye(2), [[1]], P)) <= 1e-12


def test_swap_and_reorder():
    T = [[1 + 0j, 2 + 0j], [0j, 3 + 0j]]
    Z = [[1 + 0j, 0j], [0j, 1 + 0j]]
    M = [[1.0, 2.0], [0.0, 3.0]]
    swap(T, Z, 0)
    assert T[0][0] == 3 and T[1][1] == 1
    check_schur(M, T, Z, 1e-14)
    rng = random.Random(11)
    for _ in range(50):
        n = rng.randint(2, 6)
        M = rand_mat(rng, n, n)
        T, Z = schur_form(M)
        diag = [T[i][i] for i in range(n)]
        count = reorder(T, Z, lambda d: d.real < 0)
        check_schur(M, T, Z, 1e-12)
        assert count == sum(1 for d in diag if d.real < 0)
        assert all(T[i][i].real < 0 for i in range(count))
        assert all(T[i][i].real >= 0 for i in range(count, n))
        assert match([T[i][i] for i in range(n)], diag, 1e-12)


def test_schur_form_special():
    for M in ([[0.0]], cm.zeros(3), cm.eye(3), [[0, 1], [0, 0]], [[0, 0, 1], [1, 0, 0], [0, 1, 0]],
              [[0, -1], [1, 0]], [[2, 1, 0], [0, 2, 1], [0, 0, 2]]):
        T, Z = schur_form(M)
        check_schur(M, T, Z, 1e-13)
    T, _ = schur_form([[0, 0, 1], [1, 0, 0], [0, 1, 0]])
    roots = [cmath.exp(2j * math.pi * k / 3) for k in range(3)]
    assert match([T[i][i] for i in range(3)], roots, 1e-12)


def test_schur_form_random_against_charpoly():
    rng = random.Random(2024)
    for _ in range(100):
        n = rng.randint(1, 7)
        M = rand_mat(rng, n, n)
        if rng.random() < 0.3:
            M = [[complex(v, rng.uniform(-1, 1)) for v in row] for row in M]
        T, Z = schur_form(M)
        check_schur(M, T, Z, 1e-12)
        if all(not isinstance(v, complex) for row in M for v in row):
            assert match([T[i][i] for i in range(n)], cm.polyroots(cm.charpoly(M)), 1e-7)


def test_care_random_against_eigenvalues():
    rng = random.Random(7)
    for _ in range(250):
        n, m = rng.randint(1, 3), rng.randint(1, 2)
        A, B = rand_mat(rng, n, n), rand_mat(rng, n, m)
        Q, R = rand_pd(rng, n, 0.1), rand_pd(rng, m, 0.5)
        P0, _ = care_schur(A, B, Q, R, symmetrize=False)
        size = fro(Q) + 2 * fro(A) * fro(P0) + fro(hamiltonian(A, B, Q, R)) * fro(P0) ** 2
        assert maxabs(cm.sub(P0, cm.transpose(P0))) <= 1e-9 * max(1.0, fro(P0))
        P, K = care_schur(A, B, Q, R)
        assert maxabs(care_residual(A, B, Q, R, P)) <= 1e-9 * size
        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)


def test_care_random_against_newton():
    rng = random.Random(99)
    for _ in range(250):
        n, m = rng.randint(1, 3), rng.randint(1, 2)
        A = rand_mat(rng, n, n)
        shift = max(sum(abs(v) for v in row) for row in A) + 0.2
        A = cm.sub(A, cm.scale(shift, cm.eye(n)))
        B = rand_mat(rng, n, m)
        Q, R = rand_pd(rng, n, 0.0), rand_pd(rng, m, 0.5)
        P, _ = care_schur(A, B, Q, R)
        ref = newton_care(A, B, Q, R)
        assert maxabs(cm.sub(P, ref)) <= 1e-9 * max(1.0, maxabs(ref))


def test_dare_random_against_recursion():
    rng = random.Random(5)
    done = 0
    while done < 100:
        n, m = rng.randint(1, 3), rng.randint(1, 2)
        A, B = rand_mat(rng, n, n, -1.2, 1.2), rand_mat(rng, n, m)
        if abs(cm.det(A)) < 0.05:
            continue
        Q, R = rand_pd(rng, n, 0.2), rand_pd(rng, m, 0.5)
        P, K = dare_schur(A, B, Q, R)
        ref = riccati_iteration(A, B, Q, R, 3000)
        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(ref)) * (1 + maxabs(A)) ** 2
        acl = cm.sub(A, cm.mul(B, K))
        eigs = cm.polyroots(cm.charpoly(acl))
        assert all(abs(e) < 1 for e in eigs)
        sroots = cm.polyroots(cm.charpoly(symplectic(A, B, Q, R)))
        assert match(eigs, [r for r in sroots if abs(r) < 1], 1e-6)
        done += 1


def test_no_stabilizing_solution():
    # a = 0, q = 0: H = [[0, -1], [0, 0]] has the double eigenvalue 0 on the axis.
    with pytest.raises(ValueError):
        care_schur([[0]], [[1]], [[0]], [[1]])
    # b = 0 and a = 1: the unstable mode cannot be moved, U1 = 0.
    with pytest.raises(ValueError):
        care_schur([[1]], [[0]], [[1]], [[1]])
    # Undamped oscillator with q = 0: eigenvalues of H at +i and -i.
    with pytest.raises(ValueError):
        care_schur([[0, 1], [-1, 0]], [[0], [1]], cm.zeros(2), [[1]])
    # Discrete: a = 1, q = 0 puts both eigenvalues of S on the unit circle.
    with pytest.raises(ValueError):
        dare_schur([[1]], [[1]], [[0]], [[1]])
    with pytest.raises(ValueError):
        dare_schur([[0]], [[1]], [[1]], [[1]])

History

Earlier methods computed the stable invariant subspace of HH from its eigenvectors, which fails or loses accuracy when eigenvalues are multiple or close. Laub (1979) replaced the eigenvectors by Schur vectors from the ordered real Schur form, computed with the QR algorithm and a reordering of the diagonal blocks, and gave the discrete-time version with a symplectic matrix. The method became the standard way to solve the CARE and the DARE for dense problems. Paige and Van Loan (1981) studied the Hamiltonian Schur form, which started the work on structure preserving methods, and the extended pencil methods of Van Dooren removed the need to invert RR or AA.

References

  1. Alan J. Laub, A Schur method for solving algebraic Riccati equations, IEEE Transactions on Automatic Control 24(6), 913-921, 1979, the method, the ordered real Schur form of the Hamiltonian matrix and the discrete-time version
  2. Gene H. Golub and Charles F. Van Loan, Matrix Computations, fourth edition, Johns Hopkins University Press, 2013, Chapter 7, on the QR iteration, the Schur form and the reordering of eigenvalues
  3. Chris Paige and Charles Van Loan, A Schur decomposition for Hamiltonian matrices, Linear Algebra and its Applications 41, 11-32, 1981, the Hamiltonian Schur form and its relation to the Riccati equation
  4. Peter Lancaster and Leiba Rodman, Algebraic Riccati Equations, Clarendon Press, Oxford, 1995, the description of solutions by invariant subspaces of the Hamiltonian matrix
  5. Dario A. Bini, Bruno Iannazzo and Beatrice Meini, Numerical Solution of Algebraic Riccati Equations, SIAM, 2012, the chapter on Schur methods and the comparison with Newton and doubling methods

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