Algorithmcore
Linear quadratic Gaussian control
Also called LQG, LQG regulator.
Combines a Kalman filter with LQR on the state estimate, which is optimal for linear systems with Gaussian noise by the separation theorem.
- Time
- O(i n^3 + n^2 (m + p)) worst
- Space
- O(n^2) extra
- Where
- i = the number of sign function iterations, usually 10 to 30; m = the number of inputs; n = the number of states; p = the number of outputs
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Rudolf E. Kalman, Richard S. Bucy, Peter D. Joseph, Julius T. Tou, Michael Athans, 1961
Linear quadratic Gaussian (LQG) control is the optimal output feedback for a linear plant with Gaussian white process and measurement noise and an average quadratic cost. The controller is a Kalman-Bucy filter that estimates the state, followed by the LQR gain applied to the estimate. The two gains come from two independent algebraic Riccati equations, one for the regulator and one for the filter. That the two designs can be done apart and still give the optimal controller is the separation theorem. The optimality is with respect to the noise model only: an LQG loop can have arbitrarily small gain and phase margins, as Doyle's example shows.
In plain words
We want to steer a machine whose state we cannot see directly. We only get noisy sensor readings, and random pushes act on the machine. LQG splits the job in two. The first part is an estimator: it runs a copy of the machine's model, compares the predicted reading with the real one, and corrects its guess by a fixed amount of the difference. The second part is the best controller for the case where the state is known, and it acts on the guess as if the guess were the truth. Each part is designed on its own by solving one matrix equation. With the noise model and the cost of the problem, no other controller does better on average. But "best on average" does not mean "robust": a small change in the machine can still break the loop.
The problem
Input: matrices , , of the plant
where and are independent zero mean Gaussian white noises with intensities and , and the weights and of the cost
Assumptions: stabilizable, detectable, detectable and stabilizable.
Output: a dynamic controller , , that uses only past outputs and minimizes over all such causal output feedbacks.
The answer is , where is the steady state Kalman-Bucy estimate. Here is the filter gain; the letter alone is kept for loop transfer functions.
The algorithm
LQG(A, B, C, Q, R, W, V)- 1
P ← CARE-SOLVE(A, B, Q, R) ▷ regulator: Aᵀ P + P A - P B R⁻¹ Bᵀ P + Q = 0 - 2
K ← R⁻¹ Bᵀ P - 3
S ← CARE-SOLVE(Aᵀ, Cᵀ, W, V) ▷ filter: A S + S Aᵀ - S Cᵀ V⁻¹ C S + W = 0 - 4
L_o ← S Cᵀ V⁻¹ - 5
return controller x̂' = (A - B K - L_o C) x̂ + L_o y, u = -K x̂ CARE-SOLVE(A, B, Q, R) ▷ stabilizing solution by the matrix sign function- 6
G ← B R⁻¹ Bᵀ; H ← [[A, -G], [-Q, -Aᵀ]] ▷ Hamiltonian matrix, 2n × 2n - 7
Z ← H; repeat c ← |det Z|^(-1/(2n)); Z ← (c Z + (c Z)⁻¹) / 2 until Z stops changing - 8
P ← least squares solution of [Z₁₂; Z₂₂ + I] P = -[Z₁₁ + I; Z₂₁] - 9
twice: P ← solution of (A - G P)ᵀ P' + P' (A - G P) + Q + P G P = 0
Lines L1 to L4 are the whole design: two Riccati equations, one for the regulator and one for the filter. Line L3 uses duality: the filter equation is the regulator equation for the data , so the same solver serves both. Line L5 returns the controller in state-space form. Its order is , the order of the plant.
Any method for the stabilizing CARE solution can be used in lines L1 and L3, for example the Schur method. This page uses the matrix sign function (Roberts 1980). Line L7 is Newton's iteration for , with the determinant scaling of Byers (1987), which cuts the number of steps when the eigenvalues of are far from . The limit has equal to 0 on the stable invariant subspace of the Hamiltonian matrix, and that subspace is the range of . Line L8 reads off from this fact. Line L9 runs two steps of Kleinman's iteration, which is Newton's method on the CARE and removes the rounding error of line L8. The code solves each Lyapunov equation by its Kronecker form, which is fine for the small of the tests.
Example
Take the double integrator with the position measured: , , , with , , and . The two Riccati equations have the same solution, because the data are symmetric under duality:
Eigenvalues. and both have the characteristic polynomial , with roots . The closed loop of order 4 has the polynomial , as the separation principle says.
Controller. , and the controller from to has the transfer function
Cost. The optimal cost is . The first term is the cost with the full state known; the second is the price of the estimate. The stationary covariance of the closed loop, from a Lyapunov equation, gives the same number. Gains near and give a higher cost.
Margins. Put a gain at the plant input. The closed-loop polynomial is . The Routh conditions are and , so the loop stays Hurwitz exactly for . The LQG loop has a phase margin of about 39.0 degrees at rad/s. The LQR loop with the full state keeps every gain and has a phase margin of about 72.4 degrees. The estimator costs margin. Loop transfer recovery is one way to get it back.
Correctness
The proof is in proofs/correctness.md. It shows four facts. The sign function iteration converges to , and line L8 returns the stabilizing CARE solution, because the null space of is the stable invariant subspace of ; Newton steps from the exact solution do not move it. Line L3 returns the stabilizing filter solution, by duality. In the coordinates the closed-loop matrix is block triangular with diagonal blocks and . Finally, for any causal output feedback, completing the square with the CARE gives
and splitting , with the filter error orthogonal to every function of the past outputs, gives with equality exactly for .
Proof: The two Riccati solutions give the LQG controller, its closed loop has the separated eigenvalues, and no output feedback has a lower average costfull
The plant is , , with and independent zero mean Gaussian white noises of intensities and , and Gaussian and independent of both. The cost is with and . The standing assumptions are: stabilizable, detectable, detectable and stabilizable. The input may be any function of the past outputs , , for which the closed loop has a stationary regime.
The proof has four parts. Part 1 shows that lines L6 to L9 return the stabilizing solution of the CARE. Part 2 applies Part 1 to the filter equation by duality (lines L3 and L4). Part 3 gives the eigenvalues of the closed loop. Part 4 proves that has the least cost.
Part 1: the sign function step
Let and . With , the matrix is symmetric, so is similar to and its eigenvalues come in pairs .
Lemma 1. Under the assumptions, has no eigenvalue on the imaginary axis, and the CARE has a unique stabilizing solution . The stable invariant subspace of is the range of .
Proof. This is the theorem on the stabilizing Riccati solution (Kučera 1972). For the last claim: the CARE says , so the range is invariant under and acts on it as , which is Hurwitz. It has dimension , which is the number of eigenvalues of in the open left half plane.
Lemma 2. Let with holding the eigenvalues with negative real part and the with positive real part. The iteration , with converges to .
Proof. Every is a rational function of , so , and it suffices to look at one eigenvalue . The map keeps the sign of the real part: if then and . Write with . Then , and when . So the eigenvalues go to in the right half plane and to in the left, quadratically once they are close. The scaling only moves the starting point of each step; it does not change the limit (Byers 1987). For a nontrivial Jordan block the same argument holds on the block, because the iteration is a matrix function.
Lemma 3. Let . Then , and this overdetermined system has exactly one solution.
Proof. , so the null space of is the stable invariant subspace of , which is the range of by Lemma 1. Writing in blocks gives the system. The matrix has rank , and its range is spanned by its columns; the columns of are independent, because a vector in the null space of must be of the form , which forces and . So the solution is unique, and the normal equations of line L8 return it.
Lemma 4. Line L9 does not move an exact stabilizing solution, and from a nearby matrix it converges quadratically to it.
Proof. Line L9 is one step of Kleinman's iteration: given with Hurwitz, solves . If , the CARE says that solves this equation, and the solution is unique because is Hurwitz. Kleinman's iteration is Newton's method on the CARE (Kleinman 1968), so near the error is squared at each step. The steps remove the rounding error of the least squares solve.
So CARE-SOLVE returns in exact arithmetic, and lines L1 and L2 give and with Hurwitz.
Part 2: the filter equation by duality
Transpose the filter equation . It reads , which is the CARE for the data . is stabilizable if and only if is detectable, and is detectable if and only if is stabilizable. So Part 1 applies, line L3 returns the stabilizing , and with from line L4 the matrix is Hurwitz.
Part 3: the eigenvalues of the closed loop
The controller of line L5 is , . In the coordinates with :
The matrix is block upper triangular, so its characteristic polynomial is . Both factors are Hurwitz by Parts 1 and 2, so the closed loop is internally Hurwitz. This is the separation principle for eigenvalues. It says nothing about margins.
Part 4: optimality
Let be any admissible input and the resulting state. The Itô formula for gives
where is the Wiener process with . Use the CARE, , and complete the square with :
after taking expectations (the Itô integral has mean 0). Average over and let . In a stationary regime , so
Let and . For a linear Gaussian plant the input is known from the outputs, so does not depend on the choice of : it is the error of the Kalman-Bucy filter, whose covariance tends to . is a function of the past outputs, and is orthogonal to every such function. So
The second term tends to for every admissible , and the first is at least 0, with equality if and only if . With (1),
with equality for the controller of line L5. For that controller the filter of line L5 is the steady state Kalman-Bucy filter, which gives the conditional mean in the stationary regime.
Remark. The two terms of show the split: is the cost of LQR with the full state, and is the price of using an estimate. The same number is the square of the norm of the closed loop from the scaled noise to the scaled output , which is why H2 optimal control has the same solution. The test computes for the loop from the stationary covariance of , the solution of , and compares it with .
Complexity
Each sign function step inverts a matrix and costs . The iteration converges quadratically once the eigenvalues are near ; with determinant scaling, 10 to 30 steps are usual, and more are needed when has eigenvalues near the imaginary axis, which is the case when the problem is close to losing stabilizability or detectability. Lines L2 and L4 cost with and factored once. A Kleinman step with a Bartels-Stewart Lyapunov solver costs ; the code uses the Kronecker form, which costs and is only meant for small . The controller itself costs per evaluation of its right-hand side.
Properties
- Separation. does not depend on , or , and does not depend on , or . The closed-loop eigenvalues are those of together with those of .
- Order. The controller has the order of the plant. Lower order controllers that minimize have no such closed form.
- Certainty equivalence. The controller acts on as LQR acts on . This holds for the linear plant with Gaussian noise and quadratic cost; it fails in general for nonlinear plants or other costs.
- Same as H2. With the noise and the weighted outputs put into one generalized plant, is the squared H2 norm of the closed loop, and the LQG controller is the H2 optimal controller.
- No guaranteed margins. LQR with the full state has the gain margin and at least 60 degrees of phase margin (LQR stability margins). The LQG loop has no such bounds: Doyle (1978) gave a plant where the gain margin shrinks to 1 as the weights grow.
Variants and improvements
- Discrete time. Use the DARE for both gains and the discrete Kalman filter. The predictor form uses ; the current estimator form uses and is the optimal one when the computation delay is short.
- Finite horizon. Run the regulator Riccati equation backward from the final time and the filter Riccati equation forward from the initial covariance. The gains then vary in time.
- Correlated noise and cross terms. A cross covariance between and , or a cross term in the cost, changes the gains to and , with modified Riccati equations.
- Loop transfer recovery. Make the filter fast with fictitious input noise so that the loop tends to the LQR loop (LTR), or do the dual at the output.
- Integral action. Add the integral of the tracking error as a state, or estimate a constant disturbance, so that the loop has zero steady state error; see integral state feedback.
- Robust synthesis. When margins matter, use H-infinity design, of which LQG is the limit as the bound goes to infinity in the central controller.
When to use it
Use LQG when only some states are measured, the plant is linear near the operating point, and the disturbances and sensor noise can be modeled as white noise with known intensities, possibly after shaping filters. It gives a first controller of full order with one design knob per weight, and it is the base for LTR and for estimators in MPC. Check the margins of every LQG design, at the plant input and at the output. If the plant model is uncertain in a known way, prefer an H-infinity or design. If the inputs or states have hard limits, use the filter with MPC instead of the static gain .
Pitfalls
- Assuming LQR margins. The 60 degree and margins of LQR do not survive the estimator. In the example the upper gain margin drops from infinity to 4. Compute the margins of the actual loop.
- Breaking the loop at the wrong point. Margins at the plant input and at the plant output are different for multivariable plants. Check both.
- Fast filters with poor models. A large gives a fast filter that relies on the model. Unmodeled dynamics at high frequencies then reduce robustness.
- Noise intensities as tuning knobs. and are rarely known. Treat them as design parameters and check the result, not as facts.
- Ill conditioned Hamiltonians. When is close to losing stabilizability or is close to losing detectability, has eigenvalues near the imaginary axis, the sign iteration is slow, and or is large. Scale the problem and check the Riccati residuals.
- Plant and controller unstable together. The LQG controller can itself have eigenvalues with positive real part even when the plant is open-loop Hurwitz. The loop is fine as long as the closed loop is Hurwitz, but startup and saturation then need care.
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()
lqg_control.py 131 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lqg-control/. The authors are listed in prov/WY53ER.jsonl.
"""Linear quadratic Gaussian (LQG) control in continuous time.
Plant: x' = A x + B u + w, y = C x + v, with x in R^n, u in R^m, y in R^p.
The noises w and v are white, zero mean and uncorrelated, with intensities
W >= 0 and V > 0. The cost is the average
J = lim_(T -> inf) (1/T) E integral_0^T (x^T Q x + u^T R u) dt,
with Q >= 0 and R > 0. No cross terms are used.
The LQG controller is u = -K xhat with the observer
xhat' = A xhat + B u + L (y - C xhat),
where K = R^-1 B^T P from the CARE A^T P + P A - P B R^-1 B^T P + Q = 0
and L = S C^T V^-1 from the filter Riccati equation
A S + S A^T - S C^T V^-1 C S + W = 0. Both are the stabilizing solutions.
The Riccati equations are solved by the matrix sign function of the
Hamiltonian matrix, followed by two Newton (Kleinman) steps that remove the
rounding error of the least squares step. Lyapunov equations are solved
with a Kronecker product, which is fine for the small n of the examples.
"""
from ctlmat import add, block, det, eye, inv, kron, mul, scale, solve, sub, trace, transpose, unvec, vec
__all__ = ["lyap", "care", "filter_are", "lqg", "closed_loop", "lqg_cost", "optimal_cost"]
def lyap(F, M):
"""Return X with F X + X F^T + M = 0 (F must have no eigenvalue pair summing to 0)."""
n = len(F)
big = add(kron(eye(n), F), kron(F, eye(n)))
x = solve(big, [-v for v in vec(M)])
X = unvec(x, n, n)
return [[(X[i][j] + X[j][i]) / 2 for j in range(n)] for i in range(n)]
def _sign(Z, tol, max_iter):
n = len(Z)
for _ in range(max_iter):
Zi = inv(Z)
d = abs(det(Z)) ** (-1.0 / n) # determinant scaling for faster convergence
Zn = scale(0.5, add(scale(d, Z), scale(1.0 / d, Zi)))
diff = max(abs(a - b) for ra, rb in zip(Zn, Z) for a, b in zip(ra, rb))
size = max(abs(a) for r in Zn for a in r)
Z = Zn
if diff <= tol * size:
break
else:
raise ArithmeticError("sign iteration did not converge (eigenvalue on the imaginary axis?)")
return Z
def care(A, B, Q, R, tol=1e-13, max_iter=100):
"""Return the stabilizing solution P of A^T P + P A - P B R^-1 B^T P + Q = 0."""
n = len(A)
A = [[float(v) for v in r] for r in A]
G = mul(mul(B, inv(R)), transpose(B))
G = [[float(v) for v in r] for r in G]
Q = [[float(v) for v in r] for r in Q]
H = block([[A, scale(-1.0, G)], [scale(-1.0, Q), scale(-1.0, transpose(A))]]) # @line L6
Wm = _sign(H, tol, max_iter) # @line L7
W11 = [r[:n] for r in Wm[:n]]
W12 = [r[n:] for r in Wm[:n]]
W21 = [r[:n] for r in Wm[n:]]
W22 = [r[n:] for r in Wm[n:]]
M = W12 + add(W22, eye(n)) # (W + I) [I; P] = 0 gives M P = rhs
rhs = scale(-1.0, add(W11, eye(n)) + W21)
Mt = transpose(M)
P = solve(mul(Mt, M), mul(Mt, rhs)) # @line L8
P = [[(P[i][j] + P[j][i]) / 2 for j in range(n)] for i in range(n)]
for _ in range(2): # @line L9
Ak = sub(A, mul(G, P))
P = lyap(transpose(Ak), add(Q, mul(mul(P, G), P)))
return P
def filter_are(A, C, W, V, **kw):
"""Return the stabilizing solution S of A S + S A^T - S C^T V^-1 C S + W = 0 (by duality)."""
return care(transpose(A), transpose(C), W, V, **kw)
def lqg(A, B, C, Q, R, W, V):
"""Return (K, L, P, S) of the LQG controller u = -K xhat."""
P = care(A, B, Q, R) # @line L1
K = mul(mul(inv(R), transpose(B)), P) # @line L2
S = filter_are(A, C, W, V) # @line L3
L = mul(mul(S, transpose(C)), inv(V)) # @line L4
return K, L, P, S # @line L5
def controller(A, B, C, K, L):
"""Return (Ac, Bc, Cc): xhat' = Ac xhat + Bc y, u = -Cc xhat."""
Ac = sub(sub(A, mul(B, K)), mul(L, C))
return Ac, L, K
def closed_loop(A, B, C, K, L, gain=None):
"""Return the 2n by 2n matrix of (x, xhat) when u = -gain K xhat (gain is an m by m matrix, I if None)."""
m = len(B[0])
Gm = gain if gain is not None else eye(m)
BGK = mul(mul(B, Gm), K)
Ac, _, _ = controller(A, B, C, K, L)
return block([[A, scale(-1, BGK)], [mul(L, C), Ac]])
def lqg_cost(A, B, C, Q, R, W, V, K, L):
"""Return the average cost J of the loop with gains K and L, from a Lyapunov equation.
The closed-loop matrix must be Hurwitz. The noise (w, v) enters (x, xhat)
through [[I, 0], [0, L]], and J = trace(Q X11) + trace(K^T R K X22) with
X the stationary covariance of (x, xhat).
"""
n, p = len(A), len(C)
Acl = closed_loop(A, B, C, K, L)
Bn = block([[eye(n), [[0] * p for _ in range(n)]], [[[0] * n for _ in range(n)], L]])
N = block([[W, [[0] * p for _ in range(n)]], [[[0] * n for _ in range(p)], V]])
X = lyap(Acl, mul(mul(Bn, N), transpose(Bn)))
X11 = [r[:n] for r in X[:n]]
X22 = [r[n:] for r in X[n:]]
KRK = mul(mul(transpose(K), R), K)
return trace(mul(Q, X11)) + trace(mul(KRK, X22))
def optimal_cost(B, R, W, K, P, S):
"""Return trace(P W) + trace(S K^T R K), the optimal LQG cost."""
return trace(mul(P, W)) + trace(mul(S, mul(mul(transpose(K), R), K)))
test_lqg_control.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/lqg-control/. The authors are listed in prov/WY53ER.jsonl.
import math
import random
import ctlmat as cm
from lqg_control import care, closed_loop, filter_are, lqg, lqg_cost, lyap, optimal_cost
R3 = math.sqrt(3.0)
# Double integrator, position measured, Q = I, R = 1, W = I, V = 1.
A = [[0, 1], [0, 0]]
B = [[0], [1]]
C = [[1, 0]]
Q = cm.eye(2)
R = [[1]]
W = cm.eye(2)
V = [[1]]
def close(X, Y, tol):
return all(abs(a - b) <= tol for ra, rb in zip(X, Y) for a, b in zip(ra, rb))
def max_real(M):
return max(z.real for z in cm.polyroots(cm.charpoly(M)))
def care_residual(A, B, Q, R, P):
G = cm.mul(cm.mul(B, cm.inv(R)), cm.transpose(B))
res = cm.add(cm.add(cm.mul(cm.transpose(A), P), cm.mul(P, A)), cm.sub(Q, cm.mul(cm.mul(P, G), P)))
return max(abs(v) for row in res for v in row)
def test_double_integrator_closed_form():
K, L, P, S = lqg(A, B, C, Q, R, W, V)
want = [[R3, 1.0], [1.0, R3]]
assert close(P, want, 1e-9) and close(S, want, 1e-9)
assert close(K, [[1.0, R3]], 1e-9)
assert close(L, [[R3], [1.0]], 1e-9)
def test_scalar_closed_form():
# x' = a x + u + w, y = x + v: P = a + sqrt(a^2 + q) with r = 1, S = a + sqrt(a^2 + w) with v = 1.
for a, q, w in [(1.0, 1.0, 1.0), (-2.0, 3.0, 0.5), (0.0, 4.0, 9.0)]:
K, L, P, S = lqg([[a]], [[1.0]], [[1.0]], [[q]], [[1.0]], [[w]], [[1.0]])
assert abs(P[0][0] - (a + math.sqrt(a * a + q))) < 1e-9
assert abs(S[0][0] - (a + math.sqrt(a * a + w))) < 1e-9
def test_riccati_residuals_on_random_plants():
rng = random.Random(11)
for _ in range(6):
n = rng.choice([2, 3])
A_ = [[rng.uniform(-2, 2) for _ in range(n)] for _ in range(n)]
B_ = [[rng.uniform(-1, 1)] for _ in range(n)]
C_ = [[rng.uniform(-1, 1) for _ in range(n)]]
Q_ = cm.eye(n)
W_ = cm.eye(n)
K, L, P, S = lqg(A_, B_, C_, Q_, [[1.0]], W_, [[0.5]])
scale = 1.0 + max(abs(v) for row in P for v in row) ** 2
assert care_residual(A_, B_, Q_, [[1.0]], P) <= 1e-9 * scale
At, Ct = cm.transpose(A_), cm.transpose(C_)
scale = 1.0 + max(abs(v) for row in S for v in row) ** 2
assert care_residual(At, Ct, W_, [[0.5]], S) <= 1e-9 * scale
assert cm.is_symmetric(P, 1e-12) and cm.is_pos_def(P)
assert max_real(cm.sub(A_, cm.mul(B_, K))) < 0
assert max_real(cm.sub(A_, cm.mul(L, C_))) < 0
def test_separation_of_eigenvalues():
rng = random.Random(5)
for _ in range(4):
n = 3
A_ = [[rng.uniform(-1.5, 1.5) for _ in range(n)] for _ in range(n)]
B_ = [[rng.uniform(-1, 1)] for _ in range(n)]
C_ = [[rng.uniform(-1, 1) for _ in range(n)]]
K, L, P, S = lqg(A_, B_, C_, cm.eye(n), [[1.0]], cm.eye(n), [[1.0]])
got = cm.charpoly(closed_loop(A_, B_, C_, K, L))
want = cm.polymul(cm.charpoly(cm.sub(A_, cm.mul(B_, K))), cm.charpoly(cm.sub(A_, cm.mul(L, C_))))
assert all(abs(g - w) <= 1e-8 * (1 + abs(w)) for g, w in zip(got, want))
def test_optimal_cost_and_perturbed_gains():
K, L, P, S = lqg(A, B, C, Q, R, W, V)
j_opt = optimal_cost(B, R, W, K, P, S)
assert abs(j_opt - 8 * R3) < 1e-9
assert abs(lqg_cost(A, B, C, Q, R, W, V, K, L) - j_opt) < 1e-8
rng = random.Random(3)
tried = 0
while tried < 15:
Kp = [[k + rng.uniform(-0.3, 0.3) for k in K[0]]]
Lp = [[l[0] + rng.uniform(-0.3, 0.3)] for l in L]
if max_real(closed_loop(A, B, C, Kp, Lp)) >= -1e-3:
continue
tried += 1
assert lqg_cost(A, B, C, Q, R, W, V, Kp, Lp) > j_opt - 1e-9
def test_gain_margin_of_the_lqg_loop_is_finite():
# Closed loop with input gain k: s^4 + 2 sqrt3 s^3 + 5 s^2 + 2 sqrt3 k s + k, Hurwitz iff 0 < k < 4.
K, L, P, S = lqg(A, B, C, Q, R, W, V)
for k, ok in [(0.05, True), (1.0, True), (3.9, True), (4.1, False), (6.0, False)]:
assert (max_real(closed_loop(A, B, C, K, L, gain=[[k]])) < 0) == ok
# The LQR loop alone keeps every gain k >= 1/2 (here every k > 0).
for k in [0.5, 4.1, 100.0]:
assert max_real(cm.sub(A, cm.scale(k, cm.mul(B, K)))) < 0
def test_doyle_example_has_a_tiny_gain_margin():
q = sig = 60
A_ = [[1, 1], [0, 1]]
Q_ = [[q, q], [q, q]]
W_ = [[sig, sig], [sig, sig]]
K, L, P, S = lqg(A_, B, C, Q_, R, W_, V)
assert close(K, [[10.0, 10.0]], 1e-8) and close(L, [[10.0], [10.0]], 1e-8)
m_low = (97 - 8 * math.sqrt(85)) / 25
for m, ok in [(1.0, True), (1.009, True), (1.011, False), (m_low + 1e-4, True), (m_low - 1e-4, False)]:
assert (max_real(closed_loop(A_, B, C, K, L, gain=[[m]])) < 0) == ok
def test_noise_free_closed_loop_goes_to_zero():
K, L, P, S = lqg(A, B, C, Q, R, W, V)
Acl = closed_loop(A, B, C, K, L)
E = cm.expm(cm.scale(30.0, Acl))
z = cm.matvec(E, [1.0, -1.0, 0.0, 0.0])
assert cm.norm2(z) < 1e-6
def test_lyap_solves_its_equation():
F = [[-1.0, 2.0], [0.0, -3.0]]
M = [[1.0, 0.5], [0.5, 2.0]]
X = lyap(F, M)
res = cm.add(cm.add(cm.mul(F, X), cm.mul(X, cm.transpose(F))), M)
assert max(abs(v) for row in res for v in row) < 1e-12
def test_filter_are_is_the_dual_care():
S = filter_are(A, C, W, V)
P = care(cm.transpose(A), cm.transpose(C), W, V)
assert close(S, P, 0.0)
History
Kalman (1960) solved the linear quadratic regulator, and Kalman and Bucy (1961) gave the continuous-time filter and noted its duality with the regulator. That the optimal stochastic controller is the deterministic regulator acting on the filter estimate was shown by Joseph and Tou (1961) and by Gunckel and Franklin (1963), and in more generality by Wonham (1968). Athans (1971) edited a special issue of IEEE Transactions on Automatic Control on the LQG problem and presented it as a design method. Doyle (1978) then showed with a two-state example that LQG regulators can have arbitrarily small margins, which led to loop transfer recovery (Doyle and Stein 1979, 1981) and to H-infinity control. The matrix sign function for Riccati equations goes back to a 1971 report by Roberts, published in 1980.
References
- Michael Athans, The role and use of the stochastic linear-quadratic-Gaussian problem in control system design, IEEE Transactions on Automatic Control 16(6), 529-552, 1971, the LQG problem, the separation of the filter and the regulator, and its use as a design method
- R. E. Kalman and R. S. Bucy, New results in linear filtering and prediction theory, Journal of Basic Engineering 83(1), 95-108, 1961, the continuous-time filter and the duality between filtering and the regulator problem
- John C. Doyle, Guaranteed margins for LQG regulators, IEEE Transactions on Automatic Control 23(4), 756-757, 1978, the example that shows that LQG regulators have no guaranteed margins
- J. D. Roberts, Linear model reduction and solution of the algebraic Riccati equation by use of the sign function, International Journal of Control 32(4), 677-687, 1980, the matrix sign function and its use to find the stable invariant subspace of the Hamiltonian matrix
- Ralph Byers, Solving the algebraic Riccati equation with the matrix sign function, Linear Algebra and its Applications 85, 267-279, 1987, the determinant scaling of the Newton iteration for the sign function
- Brian D. O. Anderson and John B. Moore, Optimal Control, Linear Quadratic Methods, Prentice Hall, 1990 (Dover reprint, 2007), the chapters on state estimator design and on the linear quadratic Gaussian controller
- Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, the chapter on H2 optimal control, where the LQG controller is the H2 optimal controller
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| 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 WY53ER Edit this page History Report an error Markdown