Algorithmadvanced
Kleinman iteration
Also called Newton-Kleinman method, Newton method for the Riccati equation.
Solves the algebraic Riccati equation by Newton's method, each step a Lyapunov equation, from a stabilizing initial gain.
- Time
- O(k (n^6 + m^3)) worstO(k (n^3 + m^3)) bartels_stewart
- Space
- O(n^4 + m^2) extra
- Where
- k = the number of Newton steps; m = the number of inputs; n = the number of states
- Model
- Real RAM
- Properties
- deterministicnot exactiterativeiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David L. Kleinman, 1968
Kleinman iteration solves the continuous algebraic Riccati equation (CARE) for its stabilizing solution by Newton's method. It starts from a gain that makes Hurwitz. Each step computes the cost matrix of the current gain by one Lyapunov equation and then sets the new gain . The cost matrices decrease monotonically to the solution, every gain on the way is stabilizing, and the convergence is quadratic. Hewer's version does the same for the discrete algebraic Riccati equation with a discrete Lyapunov equation per step. The method needs a stabilizing start, which the Schur method does not. In return each step is a linear problem, and a good start gives the solution in a few steps. In the language of dynamic programming, it is policy iteration for the infinite-horizon LQR problem.
In plain words
You already have a controller that keeps the system stable, but it is not optimal. First measure how much it costs: for a linear controller and a quadratic cost, the cost from every start state is held in one matrix, and that matrix solves a linear equation. Then design the controller that would be best if this cost matrix were the true one. The new controller is never worse, and it is still stable. Measure its cost, improve again, and repeat. Each round fixes most of the remaining error, so the number of correct digits roughly doubles per round once you are close.
The problem
Input: real matrices (), (), , , and a gain () with Hurwitz. Assume that is detectable. Output: the stabilizing solution of the CARE and the optimal gain . The existence of means that is stabilizable, so by the stabilizing solution theorem the stabilizing solution exists; the proof of this page also shows it directly.
The algorithm
KLEINMAN-ITERATION(A, B, Q, R, K_0)- 1
K ← K_0 ▷ A - B K_0 must be Hurwitz - 2
for k ← 0, 1, 2, ... - 3
A_k ← A - B K - 4
solve A_k^T P + P A_k + Q + K^T R K = 0 for P ▷ Lyapunov equation - 5
K ← R^(-1) B^T P - 6
if P is close to the previous P then return P, K
Line L1 takes the starting gain. The code checks that is Hurwitz from the roots of its characteristic polynomial and stops with an error otherwise. Line L3 forms the closed loop matrix of the current gain. Line L4 computes , the cost matrix of the gain : with , the cost equals . The implementation solves it in the Kronecker form
a linear system of size , with the Kronecker product. Line L5 is the improvement step: minimizes over for each . Line L6 stops when the largest entry of is at most times the largest entry of , or after 50 steps. With exact rational data the code can run a fixed number of steps and returns exact fractions.
Line L4 is Newton's step for the map , with . Its derivative at is , and . The Newton equation simplifies to , which is line L4 because .
The discrete-time version (Hewer 1971) solves in line L4, with the Kronecker form , and sets in line L5. It needs Schur. The implementation has it as hewer.
Example
Double integrator: , , , , and , so has the characteristic polynomial and is Hurwitz. The solution is . In exact arithmetic every has the form , and the next gain is :
| 0 | ||||
| 1 | ||||
| 2 | ||||
| 3 | ||||
| 4 | below |
To check row 0 by hand: with , , and . The values decrease, every closed loop polynomial has positive coefficients and so is Hurwitz, and the error is roughly squared at each step: . Here the iteration is exactly Newton's method for , that is .
In discrete time, Hewer's version for from gives , ratios of Fibonacci numbers, which converge to the golden ratio .
Correctness
The full proof is in proofs/correctness.md. Write . The key identity is
which follows from line L4 and . It gives three facts. First, is Hurwitz: an eigenvector with would give and , which detectability excludes. Second, subtracting line L4 for step gives a Lyapunov equation for with right side , so . Third, the sequence is decreasing and bounded below by 0, so it converges, and the limit solves the CARE and is stabilizing. The error satisfies , which gives and .
The tests check the exact sequences of the example, check in exact rational arithmetic on random problems that every gain is stabilizing and that is positive semidefinite (all principal minors at least 0), check quadratic convergence on the double integrator, and compare 400 random problems with the stable eigenvalues of the Hamiltonian matrix and 80 discrete problems with the Riccati recursion.
Proof: Kleinman iteration stays stabilizing, decreases monotonically and converges quadratically to the stabilizing solution of the CAREfull
Let , , and , and put . Assume that is detectable: there is no with , and (the PBH test; is the same as because ). Let be a gain with Hurwitz. For the algorithm sets , solves
and sets . Write .
Lemma 1: Lyapunov equations with a Hurwitz matrix
If is Hurwitz and , then has exactly one solution, . It is symmetric, and if .
Proof. The eigenvalues of the linear map are the sums of eigenvalues of , which have negative real part, so the map is invertible and the solution is unique. The integral converges because for some and . Its integrand satisfies , so . Symmetry and for are clear from the integrand.
Lemma 2: the improvement identity
If solves (1) and , then
Proof. , and . So . By (1) this is . Add and put :
Lemma 3: every gain stabilizes
For every , is Hurwitz and .
Proof. Induction on . For , is Hurwitz by assumption. Suppose is Hurwitz. By Lemma 1, (1) has a unique solution and , since . Let with . Multiply (2) by on the left and on the right:
If , the left side is at least 0 and the right side is at most 0, so both are 0. Then (as ) and (as ). So with and , which detectability excludes. Hence is Hurwitz.
Lemma 4: monotone decrease
For every , .
Proof. Equation (1) for reads . Subtract it from (2):
is Hurwitz by Lemma 3 and , so Lemma 1 gives .
Lemma 5: the limit is the stabilizing solution
The sequence converges to a matrix that solves the CARE , and is Hurwitz.
Proof. By Lemmas 3 and 4, . For each , the numbers decrease and are at least 0, so they converge. By polarization, converges for all , , so every entry of converges. Let be the limit. Then , and taking the limit in (1) gives . With and this is , the CARE. Also . For stability, let with ; the limit equation gives . If , both sides are 0, so and , hence , which detectability excludes.
A stabilizing solution of the CARE is unique (two of them, and , give , a Sylvester equation with a unique solution 0 because the two matrices are Hurwitz). So the limit is the stabilizing solution, whatever stabilizing is used.
Lemma 6: the error identity and quadratic convergence
Let . Then
so for , and there is a constant with for all .
Proof. Let . For any gain , the CARE can be written as
because the left side minus the right side equals after expanding with , and . Take and subtract this from (1) for . Since , the right side is , and (3) follows. As is Hurwitz and , Lemma 1 gives .
For the bound, let . Then and . The matrices converge to , which is Hurwitz, and , with , is continuous on the open set of Hurwitz matrices . A convergent sequence of Hurwitz matrices whose limit is Hurwitz stays in a compact subset of that set, so is bounded by some , and works.
Theorem
Under the assumptions above, Kleinman's iteration is well defined, every is Hurwitz, , and converges to the stabilizing solution of the CARE with . The implementation stops after at most max_iter steps, or when two successive matrices differ by at most tol times the size of the last one, which happens after finitely many steps because the sequence converges.
Proof. Lemma 3 gives well definedness and stability, Lemma 4 the monotone decrease, Lemma 5 the limit, Lemma 6 the lower bound for (and for from ) and the quadratic rate. Termination: the loop runs at most max_iter times.
The discrete-time version (Hewer)
Assume detectable in the discrete sense (no with , , ) and Schur. Hewer's iteration solves and sets with . The same steps hold with these changes.
- Lemma 1 becomes: for Schur, has the unique solution .
- Lemma 2 becomes . Proof: , and completing the square gives . Put , where .
- Lemma 3: for , the identity gives , and leads to the same contradiction.
- Lemma 4: .
- Lemma 5 is the same, with the limit equation , , which is the DARE.
- Lemma 6: with , the DARE gives , so . The gain is a smooth function of that equals at , so near the limit, and .
Complexity
In the real RAM, per step:
- Line L3 costs .
- Line L4 forms in and the Kronecker matrix of size in , and solves it by Gaussian elimination in .
- Line L5 solves with for right sides, .
- Line L6 costs .
Since , one step costs and steps cost . The Kronecker matrix takes space. With the Bartels-Stewart method, which reduces to Schur form and solves a triangular Sylvester equation, line L4 costs and the total is with space. The number of steps depends on how far is from the optimum; once the error is small, quadratic convergence means about of the number of correct digits, so a handful of steps.
Properties
- Every iterate is stabilizing. Each is a usable controller, so the iteration can be stopped at any step with a stable closed loop whose cost is known.
- Monotone. in the positive semidefinite order. The cost never increases.
- Quadratic convergence. , the usual rate of Newton's method; see quadratic convergence.
- Global from a stabilizing start. Unlike Newton's method for general equations, it converges from every stabilizing , not only from one close to the solution.
- Exact steps. With rational data each is rational, as the example shows, but the limit is not rational in general.
Variants and improvements
- Discrete time. Hewer (1971): a discrete Lyapunov equation per step, as above.
- Line search. Newton steps far from the solution can overshoot. An exact line search along the Newton direction keeps the first steps short when is poor.
- Bartels-Stewart solves. For larger , use a Schur based Lyapunov solver in line L4 in place of the Kronecker form.
- Low rank Newton. For large sparse and low rank and , solve each Lyapunov equation approximately with a low rank factor of , so is never formed.
- Refinement. Started from the result of the Schur method, one or two steps reduce the residual to the rounding level.
- Data driven. Policy iteration that estimates from measured data in place of the Lyapunov equation is used in adaptive and learning control.
When to use it
Use it when a stabilizing gain is known, for example the current controller of a plant, or the solution of a nearby problem when the data change slowly. It is also a good refinement step after a direct method. When no stabilizing gain is known, the Schur method is the direct alternative, and it needs no start. The Riccati recursion of infinite-horizon LQR needs no stabilizing start either, but converges only linearly. For an unstable , find a stabilizing first, for example by pole placement.
Pitfalls
- Unstable start. If is not Hurwitz, line L4 may have no solution or a solution that is not a cost, and the iteration can converge to a solution that does not stabilize, or diverge. Line L1 must check the start; works only when itself is Hurwitz.
- Wrong gain update. Using (the old matrix) in line L5 in place of the new breaks the identity of the proof and the monotone decrease. Line L5 must use the just computed in line L4.
- Wrong Kronecker form. With column stacking, and . Writing in line L4 in place of solves a different equation.
- Stopping on the gain only. Stopping when stops changing can stop early when is small. Line L6 should test , or the CARE residual.
- No detectability. If is not detectable, the gains can lose stability, and the limit may not be stabilizing. Check the closed loop at the end.
Implementations
Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Small dense linear algebra and polynomial routines for the control pages.
Conventions:
- A matrix is a list of rows. Entries are int, float, Fraction or complex.
- A vector is a flat list of scalars. matvec, dot, solve (with a vector
right side), vec and unvec use flat lists.
- A polynomial is a list of coefficients, highest power first, so
[1, 3, 2] is s^2 + 3 s + 2.
- Routines that divide (solve, inv, det, charpoly) compute in Fraction when
every entry is an int or a Fraction, so the result is exact. With float or
complex entries they compute in floating point.
- transpose does not conjugate complex entries.
Floating point tolerances:
- expm: scaling and squaring with a Taylor series; the scaled matrix has
infinity norm at most 1/2 and the series stops when a term is below
2^-60 times the sum. For matrices that are not far from normal the relative
error is near 1e-14.
- polyroots: Durand-Kerner iteration, then a Newton polish. Simple roots of a
well conditioned polynomial come out with a relative error near 1e-12 (the
tests ask for 1e-9). A root of multiplicity k is ill conditioned: its error
grows like 1e-16^(1/k), about 1e-8 for a double root and 1e-3 for a
fourfold root. For real coefficients the output is closed under
conjugation.
- is_pos_def with float entries: the matrix must be symmetric within
1e-12 times its largest entry, and the Cholesky pivots of A - margin I must
be positive.
This file holds no algorithm of a control page.
"""
import cmath
import math
from fractions import Fraction
__all__ = [
"zeros", "eye", "add", "sub", "scale", "mul", "transpose", "matvec",
"dot", "norm2", "block", "kron", "vec", "unvec", "solve", "inv", "det",
"trace", "charpoly", "polyval", "polyadd", "polymul", "polyder",
"polyroots", "expm", "mat_power", "is_symmetric", "is_pos_def",
]
def _is_exact(v):
return isinstance(v, (int, Fraction))
def _all_exact(*mats):
for m in mats:
for row in m:
if isinstance(row, list):
for v in row:
if not _is_exact(v):
return False
elif not _is_exact(row):
return False
return True
def _to_fraction(a):
return [[Fraction(v) for v in row] for row in a]
def _shape(a):
return len(a), (len(a[0]) if a else 0)
def zeros(n, m=None):
"""Return the n by m zero matrix (n by n if m is None), with int entries."""
if m is None:
m = n
return [[0] * m for _ in range(n)]
def eye(n):
"""Return the n by n identity matrix, with int entries."""
return [[1 if i == j else 0 for j in range(n)] for i in range(n)]
def add(a, b):
"""Return a + b."""
if _shape(a) != _shape(b):
raise ValueError("add: shapes differ")
return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def sub(a, b):
"""Return a - b."""
if _shape(a) != _shape(b):
raise ValueError("sub: shapes differ")
return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
def scale(c, a):
"""Return the scalar c times the matrix a."""
return [[c * x for x in row] for row in a]
def mul(a, b):
"""Return the matrix product a b."""
n, k = _shape(a)
k2, m = _shape(b)
if k != k2:
raise ValueError("mul: inner dimensions differ")
bt = list(zip(*b)) if b else []
out = []
for row in a:
out_row = []
for col in bt:
s = 0
for x, y in zip(row, col):
s += x * y
out_row.append(s)
out.append(out_row)
return out
def transpose(a):
"""Return the transpose of a (no complex conjugation)."""
return [list(col) for col in zip(*a)]
def matvec(a, x):
"""Return the vector a x, for a flat list x."""
if a and len(a[0]) != len(x):
raise ValueError("matvec: dimensions differ")
out = []
for row in a:
s = 0
for v, w in zip(row, x):
s += v * w
out.append(s)
return out
def dot(x, y):
"""Return sum of x_i y_i (no complex conjugation)."""
if len(x) != len(y):
raise ValueError("dot: lengths differ")
s = 0
for v, w in zip(x, y):
s += v * w
return s
def _sym_eigvals(s):
"""Eigenvalues of a real symmetric float matrix by cyclic Jacobi."""
n = len(s)
a = [list(map(float, row)) for row in s]
for _ in range(100):
off = sum(a[i][j] ** 2 for i in range(n) for j in range(n) if i != j)
diag = sum(a[i][i] ** 2 for i in range(n))
if off <= 1e-30 * max(diag, 1e-300):
break
for p in range(n - 1):
for q in range(p + 1, n):
if a[p][q] == 0.0:
continue
theta = (a[q][q] - a[p][p]) / (2.0 * a[p][q])
t = math.copysign(1.0, theta) / (abs(theta) + math.sqrt(theta * theta + 1.0))
c = 1.0 / math.sqrt(t * t + 1.0)
sn = t * c
for k in range(n):
akp, akq = a[k][p], a[k][q]
a[k][p] = c * akp - sn * akq
a[k][q] = sn * akp + c * akq
for k in range(n):
apk, aqk = a[p][k], a[q][k]
a[p][k] = c * apk - sn * aqk
a[q][k] = sn * apk + c * aqk
return [a[i][i] for i in range(n)]
def norm2(x):
"""Return the 2-norm.
For a flat vector this is the Euclidean norm. For a matrix it is the
induced 2-norm (the largest singular value), computed from the
eigenvalues of M^T M by the Jacobi method, where M is a real matrix with
the same singular values. The result is a float.
"""
if not x:
return 0.0
if not isinstance(x[0], list):
return math.sqrt(sum(abs(complex(v)) ** 2 for v in x))
if any(isinstance(v, complex) for row in x for v in row):
re = [[complex(v).real for v in row] for row in x]
im = [[complex(v).imag for v in row] for row in x]
m = block([[re, scale(-1, im)], [im, re]])
else:
m = [[float(v) for v in row] for row in x]
g = mul(transpose(m), m)
lam = max(_sym_eigvals(g))
return math.sqrt(max(lam, 0.0))
def block(rows):
"""Build a matrix from a list of rows of blocks.
A block is a matrix, or the int 0 for a zero block whose size is taken
from the other blocks in its block row and block column.
"""
heights = []
for r in rows:
h = None
for b in r:
if isinstance(b, list):
h = len(b)
break
if h is None:
raise ValueError("block: a block row has no matrix block")
heights.append(h)
ncols = len(rows[0])
widths = []
for j in range(ncols):
w = None
for r in rows:
if isinstance(r[j], list):
w = len(r[j][0]) if r[j] else 0
break
if w is None:
raise ValueError("block: a block column has no matrix block")
widths.append(w)
out = []
for r, h in zip(rows, heights):
if len(r) != ncols:
raise ValueError("block: block rows have different lengths")
for i in range(h):
line = []
for b, w in zip(r, widths):
if isinstance(b, list):
if len(b) != h or (b and len(b[0]) != w):
raise ValueError("block: block sizes do not match")
line.extend(b[i])
elif b == 0:
line.extend([0] * w)
else:
raise ValueError("block: a scalar block must be 0")
out.append(line)
return out
def kron(a, b):
"""Return the Kronecker product of a and b."""
n, m = _shape(a)
p, q = _shape(b)
return [[a[i // p][j // q] * b[i % p][j % q] for j in range(m * q)] for i in range(n * p)]
def vec(a):
"""Stack the columns of a into one flat list."""
n, m = _shape(a)
return [a[i][j] for j in range(m) for i in range(n)]
def unvec(v, n, m=None):
"""Inverse of vec: return the n by m matrix whose stacked columns are v."""
if m is None:
m = len(v) // n
if n * m != len(v):
raise ValueError("unvec: length does not match the shape")
return [[v[j * n + i] for j in range(m)] for i in range(n)]
def solve(a, b):
"""Solve a x = b by Gaussian elimination with partial pivoting.
b is a flat vector or a matrix; the result has the same form. With int
and Fraction entries the result is exact (Fraction). Raises ValueError
if a is singular (an exactly zero pivot).
"""
n, m = _shape(a)
if n != m:
raise ValueError("solve: matrix is not square")
is_vec = not (b and isinstance(b[0], list))
rhs = [[v] for v in b] if is_vec else [list(row) for row in b]
if len(rhs) != n:
raise ValueError("solve: right side has the wrong length")
if _all_exact(a, rhs):
aa = _to_fraction(a)
rhs = _to_fraction(rhs)
else:
aa = [list(row) for row in a]
k = len(rhs[0]) if rhs else 0
for c in range(n):
p = max(range(c, n), key=lambda r: abs(aa[r][c]))
if aa[p][c] == 0:
raise ValueError("solve: matrix is singular")
if p != c:
aa[c], aa[p] = aa[p], aa[c]
rhs[c], rhs[p] = rhs[p], rhs[c]
piv = aa[c][c]
for r in range(c + 1, n):
f = aa[r][c] / piv
if f == 0:
continue
row_r, row_c = aa[r], aa[c]
for j in range(c, n):
row_r[j] -= f * row_c[j]
rr, rc = rhs[r], rhs[c]
for j in range(k):
rr[j] -= f * rc[j]
x = [[0] * k for _ in range(n)]
for c in range(n - 1, -1, -1):
for j in range(k):
s = rhs[c][j]
for t in range(c + 1, n):
s -= aa[c][t] * x[t][j]
x[c][j] = s / aa[c][c]
return [row[0] for row in x] if is_vec else x
def inv(a):
"""Return the inverse of a (exact with int and Fraction entries)."""
return solve(a, eye(len(a)))
def det(a):
"""Return the determinant of a by elimination with partial pivoting.
With int and Fraction entries the result is an exact Fraction.
"""
n, m = _shape(a)
if n != m:
raise ValueError("det: matrix is not square")
aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
d = Fraction(1) if _all_exact(a) else 1.0
for c in range(n):
p = max(range(c, n), key=lambda r: abs(aa[r][c]))
if aa[p][c] == 0:
return d * 0
if p != c:
aa[c], aa[p] = aa[p], aa[c]
d = -d
piv = aa[c][c]
d *= piv
for r in range(c + 1, n):
f = aa[r][c] / piv
if f == 0:
continue
for j in range(c, n):
aa[r][j] -= f * aa[c][j]
return d
def trace(a):
"""Return the sum of the diagonal entries of a."""
s = 0
for i in range(len(a)):
s += a[i][i]
return s
def charpoly(a):
"""Return [1, a_1, ..., a_n] with det(s I - A) = s^n + a_1 s^(n-1) + ... + a_n.
Uses the Faddeev-LeVerrier recursion M_k = A M_(k-1) + a_(k-1) I,
a_k = -trace(A M_k) / k. Exact with int and Fraction entries.
"""
n, m = _shape(a)
if n != m:
raise ValueError("charpoly: matrix is not square")
aa = _to_fraction(a) if _all_exact(a) else [list(row) for row in a]
coeffs = [1]
mk = zeros(n)
for k in range(1, n + 1):
mk = mul(aa, mk)
c = coeffs[-1]
for i in range(n):
mk[i][i] += c
am = mul(aa, mk)
coeffs.append(-trace(am) / k)
return coeffs
def polyval(p, x):
"""Evaluate the polynomial p at x by Horner's rule."""
s = 0
for c in p:
s = s * x + c
return s
def _strip(p):
i = 0
while i < len(p) - 1 and p[i] == 0:
i += 1
return list(p[i:]) if p else [0]
def polyadd(p, q):
"""Return p + q, with exactly zero leading coefficients removed."""
n = max(len(p), len(q))
pp = [0] * (n - len(p)) + list(p)
qq = [0] * (n - len(q)) + list(q)
return _strip([x + y for x, y in zip(pp, qq)])
def polymul(p, q):
"""Return the product p q."""
if not p or not q:
return [0]
out = [0] * (len(p) + len(q) - 1)
for i, x in enumerate(p):
for j, y in enumerate(q):
out[i + j] += x * y
return _strip(out)
def polyder(p):
"""Return the derivative of p."""
n = len(p) - 1
if n <= 0:
return [0]
return _strip([c * (n - i) for i, c in enumerate(p[:-1])])
def polyroots(p, tol=1e-15, maxiter=1000):
"""Return the complex roots of p, sorted by real part, then imaginary part.
Durand-Kerner (Weierstrass) iteration from points on a circle, stopped
when every relative correction is below tol, then a Newton polish of
each root. For real coefficients the roots are made exactly real or
exact conjugate pairs. See the module notes for the accuracy.
"""
c = [complex(v) for v in p]
while c and c[0] == 0:
c.pop(0)
if not c:
raise ValueError("polyroots: zero polynomial")
real_coeffs = all(v.imag == 0 for v in c)
origin = 0
while len(c) > 1 and c[-1] == 0:
c.pop()
origin += 1
n = len(c) - 1
a = [v / c[0] for v in c]
if n == 0:
z = []
elif n == 1:
z = [-a[1]]
else:
r = 2.0 * max(abs(a[k]) ** (1.0 / k) for k in range(1, n + 1))
if r == 0:
r = 1.0
z = [r * cmath.exp(1j * (2 * math.pi * k / n + 0.4)) for k in range(n)]
for _ in range(maxiter):
worst = 0.0
for i in range(n):
den = 1.0 + 0j
for j in range(n):
if j != i:
den *= z[i] - z[j]
if den == 0:
z[i] += 1e-8 * (1 + abs(z[i])) * cmath.exp(1j * (i + 1))
worst = 1.0
continue
d = polyval(a, z[i]) / den
z[i] -= d
worst = max(worst, abs(d) / (1.0 + abs(z[i])))
if worst < tol:
break
dp = polyder(a)
for i in range(n):
zi = z[i]
fz = abs(polyval(a, zi))
for _ in range(5):
der = polyval(dp, zi)
if der == 0 or fz == 0:
break
step = polyval(a, zi) / der
if abs(step) > 1e-6 * (1.0 + abs(zi)):
break
znew = zi - step
fnew = abs(polyval(a, znew))
if fnew >= fz:
break
zi, fz = znew, fnew
z[i] = zi
z = z + [0j] * origin
if real_coeffs:
thr = 1e-9
upper = [v for v in z if v.imag > thr * (1 + abs(v))]
lower = [v for v in z if v.imag < -thr * (1 + abs(v))]
reals = [complex(v.real, 0.0) for v in z if abs(v.imag) <= thr * (1 + abs(v))]
# A cluster of close roots can leave more roots above the real axis
# than below it (or the other way). The extra roots nearest to the
# axis are then taken as real, so the output is closed under
# conjugation.
if len(upper) < len(lower):
upper, lower = [v.conjugate() for v in lower], [v.conjugate() for v in upper]
upper.sort(key=lambda v: v.imag)
extra = len(upper) - len(lower)
reals += [complex(v.real, 0.0) for v in upper[:extra]]
upper = upper[extra:]
out = list(reals)
rest = list(lower)
for u in upper:
w = min(rest, key=lambda v: abs(v - u.conjugate()))
rest.remove(w)
re = (u.real + w.real) / 2
im = (u.imag - w.imag) / 2
out.append(complex(re, im))
out.append(complex(re, -im))
z = out
return sorted(z, key=lambda v: (v.real, v.imag))
def _norm_inf(a):
return max((sum(abs(v) for v in row) for row in a), default=0.0)
def expm(a):
"""Return e^A in floating point by scaling and squaring with a Taylor series.
A is scaled by 2^-s so that its infinity norm is at most 1/2, the Taylor
series of the scaled matrix is summed until a term is below 2^-60 of the
sum, and the result is squared s times. Entries of the result are float
(complex if A has complex entries).
"""
n, m = _shape(a)
if n != m:
raise ValueError("expm: matrix is not square")
cplx = any(isinstance(v, complex) for row in a for v in row)
conv = complex if cplx else float
x = [[conv(v) for v in row] for row in a]
nrm = _norm_inf(x)
s = 0
while nrm > 0.5:
nrm /= 2.0
s += 1
x = scale(conv(2.0 ** -s), x)
e = [[conv(1.0 if i == j else 0.0) for j in range(n)] for i in range(n)]
term = [row[:] for row in e]
for k in range(1, 60):
term = scale(1.0 / k, mul(term, x))
e = add(e, term)
tn = _norm_inf(term)
if tn == 0.0 or tn <= 2.0 ** -60 * _norm_inf(e):
break
for _ in range(s):
e = mul(e, e)
return e
def mat_power(a, k):
"""Return A^k for an int k by repeated squaring (A^0 = I; k < 0 uses inv)."""
n, m = _shape(a)
if n != m:
raise ValueError("mat_power: matrix is not square")
if k < 0:
a = inv(a)
k = -k
result = eye(n)
base = [list(row) for row in a]
while k:
if k & 1:
result = mul(result, base)
k >>= 1
if k:
base = mul(base, base)
return result
def is_symmetric(a, tol=0):
"""Return True if a is square and |a_ij - a_ji| <= tol for all i, j."""
n, m = _shape(a)
if n != m:
return False
return all(abs(a[i][j] - a[j][i]) <= tol for i in range(n) for j in range(i + 1, n))
def is_pos_def(a, margin=0):
"""Return True if a is symmetric and a - margin I is positive definite.
With int and Fraction entries (and an exact margin) the test is exact:
every leading principal minor of a - margin I must be positive
(Sylvester's criterion), computed in Fraction. With float entries the
matrix must be symmetric within 1e-12 times its largest entry, and the
Cholesky factorization of a - margin I must have positive pivots.
Complex entries are not accepted.
"""
n, m = _shape(a)
if n != m:
return False
if any(isinstance(v, complex) for row in a for v in row):
raise ValueError("is_pos_def: complex entries are not accepted")
if _all_exact(a) and _is_exact(margin):
b = [[Fraction(a[i][j]) - (Fraction(margin) if i == j else 0) for j in range(n)] for i in range(n)]
if not is_symmetric(b):
return False
return all(det([row[:k] for row in b[:k]]) > 0 for k in range(1, n + 1))
b = [[float(a[i][j]) - (float(margin) if i == j else 0.0) for j in range(n)] for i in range(n)]
big = max((abs(float(v)) for row in a for v in row), default=0.0)
if not is_symmetric(b, 1e-12 * max(big, 1e-300)):
return False
low = [[0.0] * n for _ in range(n)]
for j in range(n):
d = b[j][j] - sum(low[j][k] ** 2 for k in range(j))
if not d > 0.0:
return False
low[j][j] = math.sqrt(d)
for i in range(j + 1, n):
low[i][j] = (b[i][j] - sum(low[i][k] * low[j][k] for k in range(j))) / low[j][j]
return True
def _self_test():
a = [[0, 1], [-2, -3]]
assert charpoly(a) == [1, 3, 2]
assert det(a) == 2
assert mul(inv(a), a) == eye(2)
assert solve(a, [1, 0]) == [Fraction(-3, 2), Fraction(1)]
r = polyroots([1, 3, 2])
assert abs(r[0] + 2) < 1e-12 and abs(r[1] + 1) < 1e-12
t = 0.7
e = expm([[0.0, t], [-t, 0.0]])
want = [[math.cos(t), math.sin(t)], [-math.sin(t), math.cos(t)]]
assert max(abs(e[i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-14
assert is_pos_def([[Fraction(5, 4), Fraction(1, 4)], [Fraction(1, 4), Fraction(1, 4)]])
assert not is_pos_def([[1, 2], [2, 1]])
assert abs(norm2([[3.0, 0.0], [0.0, -4.0]]) - 4.0) < 1e-12
return True
if __name__ == "__main__":
_self_test()
kleinman_iteration.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kleinman-iteration/. The authors are listed in prov/1GNVWG.jsonl.
"""Kleinman iteration: Newton's method for the algebraic Riccati equation.
Continuous time (Kleinman 1968). Start from a gain K_0 with A - B K_0
Hurwitz. For k = 0, 1, 2, ... solve the Lyapunov equation
(A - B K_k)^T P_k + P_k (A - B K_k) + Q + K_k^T R K_k = 0
and set K_(k+1) = R^(-1) B^T P_k. If (Q^(1/2), A) is detectable, every
A - B K_k is Hurwitz, P_0 >= P_1 >= ... >= P, and P_k converges
quadratically to the stabilizing solution P of the CARE
A^T P + P A - P B R^(-1) B^T P + Q = 0.
Discrete time (Hewer 1971). Start from K_0 with A - B K_0 Schur, solve the
Stein equation P_k = (A - B K_k)^T P_k (A - B K_k) + Q + K_k^T R K_k and set
K_(k+1) = (R + B^T P_k B)^(-1) B^T P_k A.
Each linear matrix equation is solved in its Kronecker form, a dense linear
system of size n^2, which costs O(n^6). This is fine for small n; a
Bartels-Stewart solver brings one step down to O(n^3). With int or Fraction
data the iteration is exact.
"""
from ctlmat import add, charpoly, eye, kron, mul, polyroots, solve, sub, transpose, unvec, vec
__all__ = ["lyap", "stein", "kleinman", "hewer", "care_residual", "dare_residual"]
def _is_float(a):
return any(isinstance(v, float) for row in a for v in row)
def _sym(p):
if not _is_float(p):
return p
return [[(p[i][j] + p[j][i]) / 2 for j in range(len(p))] for i in range(len(p))]
def _maxabs(a):
return max(abs(v) for row in a for v in row)
def lyap(F, W):
"""Return X with F^T X + X F + W = 0, from (I kron F^T + F^T kron I) vec X = -vec W.
The solution is unique when no two eigenvalues of F sum to 0, for
example when F is Hurwitz. Cost O(n^6).
"""
n = len(F)
ft = transpose(F)
big = add(kron(eye(n), ft), kron(ft, eye(n)))
return _sym(unvec(solve(big, [-v for v in vec(W)]), n))
def stein(F, W):
"""Return X with X = F^T X F + W, from (I - F^T kron F^T) vec X = vec W.
The solution is unique when no product of two eigenvalues of F is 1, for
example when F is Schur. Cost O(n^6).
"""
n = len(F)
ft = transpose(F)
big = sub(eye(n * n), kron(ft, ft))
return _sym(unvec(solve(big, vec(W)), n))
def _check_start(F, discrete):
eigs = polyroots(charpoly(F))
ok = all(abs(e) < 1 for e in eigs) if discrete else all(e.real < 0 for e in eigs)
if not ok:
raise ValueError("the initial gain K_0 does not stabilize A - B K_0")
def kleinman(A, B, Q, R, K0, tol=1e-13, max_iter=50, steps=None):
"""Return (P, K, Ps) by Kleinman's iteration for the CARE.
Ps is the list P_0, P_1, ... of the cost matrices of the gains K_0,
K_1, ...; P is the last of them and K = R^(-1) B^T P. The loop stops
when the largest entry of P_k - P_(k-1) is at most tol times the largest
entry of P_k, or after max_iter steps; with steps given it does exactly
that many steps (useful with exact data). Precondition: R > 0 and
A - B K0 Hurwitz (checked). Cost O(n^6 + n^2 m + m^3) per step with the
Kronecker solve.
"""
K = [list(row) for row in K0] # @line L1
_check_start(sub(A, mul(B, K)), False)
bt = transpose(B)
Ps = []
limit = steps if steps is not None else max_iter
for _ in range(limit): # @line L2
ak = sub(A, mul(B, K)) # @line L3
P = lyap(ak, add(Q, mul(transpose(K), mul(R, K)))) # @line L4
K = solve(R, mul(bt, P)) # @line L5
Ps.append(P)
if steps is None and len(Ps) > 1 and _maxabs(sub(P, Ps[-2])) <= tol * max(_maxabs(P), 1e-300): # @line L6
break
return Ps[-1], K, Ps
def hewer(A, B, Q, R, K0, tol=1e-13, max_iter=50, steps=None):
"""Return (P, K, Ps) by Hewer's iteration for the DARE.
Same conventions as kleinman. Precondition: R > 0 and A - B K0 Schur
(checked). K = (R + B^T P B)^(-1) B^T P A for the last P.
"""
K = [list(row) for row in K0]
_check_start(sub(A, mul(B, K)), True)
bt = transpose(B)
Ps = []
limit = steps if steps is not None else max_iter
for _ in range(limit):
ak = sub(A, mul(B, K))
P = stein(ak, add(Q, mul(transpose(K), mul(R, K))))
pb = mul(P, B)
K = solve(add(R, mul(bt, pb)), mul(transpose(pb), A))
Ps.append(P)
if steps is None and len(Ps) > 1 and _maxabs(sub(P, Ps[-2])) <= tol * max(_maxabs(P), 1e-300):
break
return Ps[-1], K, Ps
def care_residual(A, B, Q, R, P):
"""Return A^T P + P A - P B R^(-1) B^T P + Q."""
pb = mul(P, B)
return add(sub(add(mul(transpose(A), P), mul(P, A)), mul(pb, solve(R, transpose(pb)))), Q)
def dare_residual(A, B, Q, R, P):
"""Return A^T P A - A^T P B (R + B^T P B)^(-1) B^T P A + Q - P."""
pb = mul(P, B)
k = solve(add(R, mul(transpose(B), pb)), mul(transpose(pb), A))
at = transpose(A)
return sub(add(sub(mul(at, mul(P, A)), mul(at, mul(pb, k))), Q), P)
test_kleinman_iteration.py 208 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kleinman-iteration/. The authors are listed in prov/1GNVWG.jsonl.
import itertools
import math
import random
from fractions import Fraction
import pytest
import ctlmat as cm
from kleinman_iteration import care_residual, dare_residual, hewer, kleinman, lyap, stein
def maxabs(a):
return max(abs(v) for row in a for v in row)
def is_psd_exact(m):
"""All principal minors of an exact symmetric matrix are at least 0."""
n = len(m)
if any(m[i][j] != m[j][i] for i in range(n) for j in range(n)):
return False
for size in range(1, n + 1):
for idx in itertools.combinations(range(n), size):
if cm.det([[m[i][j] for j in idx] for i in idx]) < 0:
return False
return True
def match(xs, ys, tol):
rest = list(ys)
for x in xs:
y = min(rest, key=lambda v: abs(v - x))
if abs(y - x) > tol * (1 + abs(x)):
return False
rest.remove(y)
return not rest
def hurwitz(m):
return all(e.real < 0 for e in cm.polyroots(cm.charpoly(m)))
def schur_stable(m):
return all(abs(e) < 1 for e in cm.polyroots(cm.charpoly(m)))
def rand_mat(rng, n, m, lo=-2.0, hi=2.0):
return [[rng.uniform(lo, hi) for _ in range(m)] for _ in range(n)]
def rand_pd(rng, n, shift):
c = rand_mat(rng, n, n, -1.0, 1.0)
return cm.add(cm.mul(cm.transpose(c), c), cm.scale(shift, cm.eye(n)))
def hamiltonian(A, B, Q, R):
g = cm.mul(B, cm.solve(R, cm.transpose(B)))
return cm.block([[A, cm.scale(-1, g)], [cm.scale(-1, Q), cm.scale(-1, cm.transpose(A))]])
def random_problem(rng):
"""A random CARE with a stabilizing K0; half of the plants are unstable."""
n = rng.randint(1, 3)
A = rand_mat(rng, n, n)
if rng.random() < 0.5:
m = rng.randint(1, 2)
s = max(sum(abs(v) for v in row) for row in A) + 0.3
A = cm.sub(A, cm.scale(s, cm.eye(n)))
B = rand_mat(rng, n, m)
K0 = cm.zeros(m, n)
else:
m = n
B = cm.add(cm.eye(n), rand_mat(rng, n, n, -0.3, 0.3))
K0 = cm.solve(B, cm.add(A, cm.eye(n)))
return A, B, rand_pd(rng, n, 0.1), rand_pd(rng, m, 0.5), K0
def test_double_integrator_exact():
A, B, Q, R = [[0, 1], [0, 0]], [[0], [1]], cm.eye(2), [[1]]
P, K, Ps = kleinman(A, B, Q, R, [[1, 1]], steps=4)
diag = [p[0][0] for p in Ps]
assert diag == [2, Fraction(7, 4), Fraction(97, 56), Fraction(18817, 10864)]
assert all(p[0][1] == 1 and p[1][0] == 1 and p[1][1] == p[0][0] for p in Ps)
assert K == [[1, Fraction(18817, 10864)]]
# Newton's method for x^2 = 3 from 2 gives the same numbers.
x = Fraction(2)
for d in diag:
assert d == x
x = (x + 3 / x) / 2
def test_scalar_discrete_fibonacci():
P, K, Ps = hewer([[1]], [[1]], [[1]], [[1]], [[1]], steps=4)
assert [p[0][0] for p in Ps] == [2, Fraction(13, 8), Fraction(610, 377), Fraction(1346269, 832040)]
golden = (1 + math.sqrt(5)) / 2
assert abs(float(P[0][0]) - golden) < 1e-12
def test_quadratic_convergence():
A, B, Q, R = [[0.0, 1.0], [0.0, 0.0]], [[0.0], [1.0]], cm.eye(2), [[1.0]]
r3 = math.sqrt(3.0)
P, K, Ps = kleinman(A, B, Q, R, [[1.0, 1.0]])
errs = [maxabs(cm.sub(p, [[r3, 1.0], [1.0, r3]])) for p in Ps]
assert errs[-1] <= 1e-15
for e0, e1 in zip(errs, errs[1:]):
assert e1 <= 0.3 * e0 * e0 + 1e-15
assert len(Ps) <= 7
def test_lyap_and_stein():
rng = random.Random(3)
for _ in range(100):
n = rng.randint(1, 4)
F = rand_mat(rng, n, n)
s = max(sum(abs(v) for v in row) for row in F) + 0.1
Fh = cm.sub(F, cm.scale(s, cm.eye(n)))
W = rand_pd(rng, n, 0.0)
X = lyap(Fh, W)
assert maxabs(cm.add(cm.add(cm.mul(cm.transpose(Fh), X), cm.mul(X, Fh)), W)) <= 1e-10 * (1 + maxabs(X))
Fs = cm.scale(0.9 / s, F)
Y = stein(Fs, W)
assert maxabs(cm.sub(cm.add(cm.mul(cm.transpose(Fs), cm.mul(Y, Fs)), W), Y)) <= 1e-10 * (1 + maxabs(Y))
def test_exact_monotone_and_stabilizing():
rng = random.Random(17)
for _ in range(40):
n, m = rng.randint(1, 3), rng.randint(1, 2)
A = [[rng.randint(-3, 3) for _ in range(n)] for _ in range(n)]
s = max(sum(abs(v) for v in row) for row in A) + 1
A = cm.sub(A, cm.scale(s, cm.eye(n)))
B = [[rng.randint(-2, 2) for _ in range(m)] for _ in range(n)]
C = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(n)]
Q = cm.add(cm.mul(cm.transpose(C), C), cm.eye(n))
R = [[rng.randint(1, 3) if i == j else 0 for j in range(m)] for i in range(m)]
P, K, Ps = kleinman(A, B, Q, R, cm.zeros(m, n), steps=3)
Pf, _, _ = kleinman([[float(v) for v in row] for row in A], B, Q, R, cm.zeros(m, n))
Ks = [cm.zeros(m, n)] + [cm.solve(R, cm.mul(cm.transpose(B), p)) for p in Ps]
for p, k in zip(Ps, Ks):
assert all(isinstance(v, Fraction) for row in p for v in row)
assert hurwitz(cm.sub(A, cm.mul(B, k)))
assert all(v >= -1e-12 for v in vec_minors(cm.sub(p, Pf)))
for p0, p1 in zip(Ps, Ps[1:]):
assert is_psd_exact(cm.sub(p0, p1))
def vec_minors(m):
n = len(m)
out = []
for size in range(1, n + 1):
for idx in itertools.combinations(range(n), size):
out.append(cm.det([[float(m[i][j]) for j in idx] for i in idx]))
return out
def test_random_care_against_hamiltonian():
rng = random.Random(2025)
for _ in range(400):
A, B, Q, R, K0 = random_problem(rng)
P, K, Ps = kleinman(A, B, Q, R, K0)
assert len(Ps) < 50
assert maxabs(care_residual(A, B, Q, R, P)) <= 1e-9 * (1 + maxabs(P)) ** 2 * (1 + maxabs(A) + maxabs(B) ** 2)
assert cm.is_pos_def(P)
acl = cm.sub(A, cm.mul(B, K))
eigs = cm.polyroots(cm.charpoly(acl))
assert all(e.real < 0 for e in eigs)
hroots = cm.polyroots(cm.charpoly(hamiltonian(A, B, Q, R)))
assert match(eigs, [r for r in hroots if r.real < 0], 1e-6)
for p0, p1 in zip(Ps, Ps[1:]):
d = cm.sub(p0, p1)
assert min(cm._sym_eigvals(d)) >= -1e-9 * (1 + maxabs(p0))
def test_random_dare_against_recursion():
rng = random.Random(8)
for _ in range(100):
n, m = rng.randint(1, 3), rng.randint(1, 2)
A = rand_mat(rng, n, n, -1.0, 1.0)
s = max(sum(abs(v) for v in row) for row in A)
A = cm.scale(rng.uniform(0.2, 1.6) / max(s, 1e-9), A)
B = rand_mat(rng, n, m)
Q, R = rand_pd(rng, n, 0.2), rand_pd(rng, m, 0.5)
if not schur_stable(A):
continue
P, K, Ps = hewer(A, B, Q, R, cm.zeros(m, n))
ref = cm.zeros(n)
for _ in range(3000):
pb = cm.mul(ref, B)
k = cm.solve(cm.add(R, cm.mul(cm.transpose(B), pb)), cm.mul(cm.transpose(pb), A))
new = cm.sub(cm.add(Q, cm.mul(cm.transpose(A), cm.mul(ref, A))), cm.mul(cm.transpose(A), cm.mul(pb, k)))
done = maxabs(cm.sub(new, ref)) <= 1e-15 * maxabs(new)
ref = new
if done:
break
assert maxabs(cm.sub(P, ref)) <= 1e-8 * max(1.0, maxabs(ref))
assert maxabs(dare_residual(A, B, Q, R, P)) <= 1e-9 * max(1.0, maxabs(P))
assert schur_stable(cm.sub(A, cm.mul(B, K)))
def test_unstable_start_raises():
with pytest.raises(ValueError):
kleinman([[0, 1], [0, 0]], [[0], [1]], cm.eye(2), [[1]], [[0, 0]])
with pytest.raises(ValueError):
kleinman([[1]], [[1]], [[1]], [[1]], [[1]])
with pytest.raises(ValueError):
hewer([[2]], [[1]], [[1]], [[1]], [[0]])
History
Kleinman (1968) proposed the iteration for the CARE and proved that every gain stays stabilizing and that the cost matrices decrease to the solution. Hewer (1971) gave the discrete-time version for the steady state gains of the discrete regulator. Policy iteration in dynamic programming, due to Howard, has the same structure, and Kleinman's iteration is now often described as policy iteration for the linear quadratic problem.
References
- David L. Kleinman, On an iterative technique for Riccati equation computations, IEEE Transactions on Automatic Control 13(1), 114-115, 1968, the iteration, the stability of each gain and the monotone convergence
- G. A. Hewer, An iterative technique for the computation of the steady state gains for the discrete optimal regulator, IEEE Transactions on Automatic Control 16(4), 382-384, 1971, the discrete-time iteration with one discrete Lyapunov equation per step
- Peter Lancaster and Leiba Rodman, Algebraic Riccati Equations, Clarendon Press, Oxford, 1995, the Newton method for the continuous and the discrete equation
- Dario A. Bini, Bruno Iannazzo and Beatrice Meini, Numerical Solution of Algebraic Riccati Equations, SIAM, 2012, the chapter on Newton's method and its convergence
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 1GNVWG Edit this page History Report an error Markdown