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
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Alan J. Laub, 1979
The Schur method solves the continuous algebraic Riccati equation (CARE) for its stabilizing solution. It forms the Hamiltonian matrix , computes a Schur decomposition with a unitary , and reorders it so that the eigenvalues with negative real part come first. The first columns of then span the stable invariant subspace of , and if they are split as , the solution is . Laub (1979) introduced the method with the real Schur form, which has blocks for complex pairs. The implementation on this page uses the complex Schur form, which has only 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 of size holds the data of the equation, and every solution of the equation is a "flat slice" of -space that maps into itself. The slice we want is the one on which 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 of them span the same space as the first eigenvectors in the Schur order. After the stable eigenvalues are moved to the front, the first Schur vectors give the slice, and one linear solve turns the slice into the matrix .
The problem
Input: real matrices (), (), () and (). Put and
Output: the real symmetric with and Hurwitz, and the gain , or an error if no such exists. By the stabilizing solution theorem, such a exists when is stabilizable and has no eigenvalue on the imaginary axis, for example when and is detectable.
The algorithm
SCHUR-METHOD-RICCATI(A, B, Q, R)- 1
H ← [[A, -G], [-Q, -A^T]] with G = B R^(-1) B^T - 2
(T, Z) ← complex Schur form of H ▷ Z^* H Z = T, Z unitary, T upper triangular - 3
if some |Re T_ii| ≤ tol ‖H‖ then error ▷ eigenvalue on or near the imaginary axis - 4
swap adjacent diagonal entries of T, updating Z, until Re T_ii < 0 exactly for i ≤ n; error if the count is not n - 5
U_1 ← rows 1..n of the first n columns of Z; U_2 ← rows n+1..2n of them - 6
solve U_1^T X = U_2^T ▷ error if U_1 is singular or nearly so - 7
P ← real part of X^T - 8
return P, K = R^(-1) B^T P
Line L1 forms with one solve ; itself is not formed. Line L2 is the QR algorithm. The implementation reduces 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 from both sides and to from the right, so holds at all times.
Line L3 rejects an eigenvalue whose real part is below 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 and uses the rotation that maps the vector to a multiple of . That vector is the eigenvector of the block for , so the rotated block has first and second.
Lines L5 to L7 compute . Since , line L6 is a single solve with right sides and no inverse. Before the solve, the code estimates the smallest singular value of and stops if it is below ; a singular means that the stable subspace is not the graph of a matrix, and then no stabilizing solution exists. In exact arithmetic is real and symmetric, so line L7 only removes rounding errors. The code also replaces by .
Example
Scalar case: . Then with , so the eigenvalues are . The eigenvector for solves , so up to a factor, and . Check: , and . In the implementation, one QR step with the Wilkinson shift gives up to the off-diagonal entry, one swap puts first, and the first column of is a unit multiple of , whose ratio is .
Double integrator: , , , . Here , so and the eigenvalues are . The state of the run, with six decimals:
| Step | Line | State |
|---|---|---|
| 1 | L1 | |
| 2 | L2 | diagonal of : , , , |
| 3 | L3 | smallest is , far from 0 |
| 4 | L4 | 4 swaps; diagonal of : , , , ; count 2 |
| 5 | L5 | is a complex matrix with smallest singular value |
| 6 | L6 | has imaginary parts below and asymmetry below |
| 7 | L7 | , that is |
| 8 | L8 | ; has eigenvalues |
The closed loop eigenvalues are exactly the stable eigenvalues of , as the theory says. The CARE residual of the computed is 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 , where has orthonormal columns and is the leading block of , with all eigenvalues in the open left half plane. This is the key invariant. If is invertible, multiply the two block rows of by on the right. The first gives , so is Hurwitz. The second gives , which is the CARE. The matrix solves , a Sylvester equation with the unique solution , so is Hermitian; it is real because the stable subspace of a real matrix is closed under conjugation. Conversely, if a stabilizing solution exists, the columns of span the same subspace, so 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 , , eigenvalues equal to the roots of the characteristic polynomial), check the CARE solution on 250 random problems against the stable roots of 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 , , and . Put , so , and
A stabilizing solution of the CARE is a solution for which is Hurwitz. The algorithm computes a unitary and an upper triangular with , moves the eigenvalues with negative real part to the first places of the diagonal, splits the first columns of as , and returns and . It stops with an error if a diagonal entry of lies on the imaginary axis, if the number of entries with negative real part is not , or if 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 by and by , where is the identity except for a block in rows and columns , , with real and . So the invariant with holds after every step.
Proof. The block satisfies , so is unitary. If , then . In a QR step the shift is subtracted from the diagonal entries of the active window 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 is the diagonal matrix with ones on the window and zeros elsewhere, then for such a rotation, so , and subtracting and adding 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 by at most a rounding error, which the section on floating point covers; with exact zeros they change nothing.
When the algorithm leaves the QR iteration, is upper triangular, so is a complex Schur form of and its diagonal holds the eigenvalues of with their algebraic multiplicities.
Lemma 2: one swap exchanges two diagonal entries
Let be upper triangular with and . Let be the rotation with , , acting on rows and columns and . Then is upper triangular, with in place and in place .
Proof. Let and . Then . From we get , so . The first column of the block is , and its trace is , so its second diagonal entry is . The rotation acts on rows , and columns , only. Rows and are zero in the columns before , and columns and are zero in the rows after , so no other entry below the diagonal changes.
By Lemmas 1 and 2, the reordering ends with , upper triangular, and the entries with negative real part in places , provided there are exactly of them, which the algorithm checks. Write for the leading block of and for the first columns of . Because is upper triangular, the first columns of give
and every eigenvalue of has negative real part. So the columns of span an -dimensional invariant subspace of , 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 is invertible, then solves the CARE and , so is Hurwitz.
Proof. The two block rows of (1) are and . Multiply both on the right by . The first gives . The second gives , which is .
Lemma 4: P is real and symmetric
If is invertible, then is real and .
Proof. Symmetric: the matrix is real and symmetric, so . Since , this reads , that is, . Let . Then, by (1), . Hence . The eigenvalues of and of are in the open left and the open right half plane, so they are disjoint, and this Sylvester equation has the unique solution . So , and
Real: is real, so complex conjugation maps an invariant subspace of to an invariant subspace of and maps the eigenvalues to their conjugates, which have the same real part. So . Then for an invertible matrix , and . A real Hermitian matrix is real symmetric.
The same computation shows that does not depend on the basis: any other basis of is with invertible, and gives the same .
Lemma 5: the checks fail only when no stabilizing solution exists
If the CARE has a stabilizing solution , then has no eigenvalue on the imaginary axis, it has exactly eigenvalues with negative real part, and is invertible.
Proof. Since solves the CARE, , and with a short computation gives
So the eigenvalues of are those of , all in the open left half plane, and those of , all in the open right half plane. This gives the first two claims. The columns of span an invariant subspace of dimension whose eigenvalues all have negative real part, so it is contained in , and both have dimension , so it equals . Hence for an invertible , and is invertible.
Theorem
If the algorithm returns, then is the real symmetric stabilizing solution of the CARE and 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 . If is another stabilizing solution, then by Lemma 5 the columns of span too, so , which forces and . If no stabilizing solution exists, then by Lemma 3 the matrix cannot be invertible, or there is no -dimensional stable subspace; either way a check fails. If a stabilizing solution exists, Lemma 5 shows that no check fails.
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 with invertible, the code uses
and selects the eigenvalues with . Lemmas 1 and 2 do not depend on , so (1) holds with in place of , and for every eigenvalue of . If is invertible, multiply on the right by and put . The two block rows are and . Since is invertible, so is , and . By Sylvester's determinant identity, , so is invertible. Multiplying out shows , so with , and the second row becomes the DARE. The closed loop is similar to , so it is Schur.
For the symmetry, is symplectic: , which follows from and by multiplying out the blocks. With and this gives , so for every , and because . The rest of Lemma 4 is the same, and Lemma 5 uses , which is block upper triangular with diagonal blocks and when is a stabilizing solution of the DARE.
Floating point
In floating point, Lemma 1 holds with a small error: the computed and satisfy , with unitary up to rounding and a small multiple of the unit roundoff times , because the algorithm uses only Givens rotations (Golub and Van Loan, Chapter 7). The computed basis is then an exact stable basis of a nearby matrix. The error in is controlled by this backward error and by the conditioning of and of the stable subspace. This is why the code refuses a with smallest singular value below and an eigenvalue whose real part is within of 0. The imaginary part of the computed and its departure from symmetry are rounding errors; the code drops the first and averages with for the second.
Complexity
In the floating point model, with :
- Line L1 costs , or when .
- The Hessenberg reduction in line L2 uses about rotations, each applied to two rows and two columns of length , so .
- One QR step on a window of size uses rotations on full rows and columns, . Each of the deflations takes at most steps, so the iteration costs . In practice the Wilkinson shift gives deflation after a few steps per eigenvalue, so is a small constant and the cost is .
- Line L4 needs at most swaps, since each of the stable entries passes at most unstable ones, and a swap costs . So .
- Lines L5 to L8 cost , including the singular value estimate of .
The extra space is for , and .
Properties
- Direct up to the eigenvalue iteration. There is no iteration on . 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 is done with rotations, so the computed and are an exact Schur form of a nearby matrix with a small multiple of the unit roundoff times (backward error analysis). The error in then depends on how well conditioned and the stable subspace are.
- No structure. The rotations do not preserve the Hamiltonian structure, so 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 eigenvalues to the front in line L4 gives a solution of the CARE whenever 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 .
- Closed loop for free. The diagonal of holds the eigenvalues of .
Variants and improvements
- Real Schur form. Laub's original method works in real arithmetic. The real Schur form has 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 is real without a final real part.
- Discrete time. For the DARE, replace by the symplectic matrix and select the eigenvalues inside the unit circle. The implementation has this as
dare_schur. It needs invertible. - Generalized Schur form. Without inverting (discrete time) or (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 or ; 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 or the data before the computation, as in matrix balancing, can reduce the error when the entries of , and 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 , dense 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 is unstable. Line L4 must select (or in discrete time).
- Forming the inverse. Computing and then costs more and is less accurate than the solve of line L6. Check the conditioning of before line L6: a nearly singular gives a huge and meaningless , 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 , 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 as it is gives complex entries of size , and code that expects a real matrix can fail.
- Eigenvectors instead of Schur vectors. Computing eigenvectors of in line L2 fails when 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.
# 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 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 or .
References
- 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
- 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
- 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
- Peter Lancaster and Leiba Rodman, Algebraic Riccati Equations, Clarendon Press, Oxford, 1995, the description of solutions by invariant subspaces of the Hamiltonian matrix
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag TKPRJX Edit this page History Report an error Markdown