Algorithmcore
Infinite-horizon LQR
Also called steady-state LQR, LQR.
Computes the constant optimal gain K = R^(-1)B^T P from the stabilizing solution P of the algebraic Riccati equation.
- Time
- O(j (n^3 + m^3)) worst
- Space
- O(n^2 + n m) extra
- Where
- j = the number of iterations of the recursion; m = the number of inputs; n = the number of states
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Rudolf E. Kalman, 1960
Infinite-horizon LQR is the solution of the linear quadratic regulator problem when the horizon has no end. The optimal input is a constant linear state feedback . In continuous time , where is the stabilizing solution of the continuous algebraic Riccati equation (CARE). In discrete time , where is the stabilizing solution of the discrete algebraic Riccati equation (DARE). The optimal cost from is , and the closed loop is Hurwitz, or Schur in discrete time. This page computes as the limit of the finite-horizon costs, which is the definition of the problem. The Schur method and the Kleinman iteration are faster solvers of the same equations.
In plain words
A controller must keep a system near rest forever. Being away from rest costs something at every moment, and so does every push. The total cost is a sum over all time, so it is finite only if the system really goes to rest. The best controller turns out to be very simple: it measures the state and pushes back by a fixed multiple of it, the same multiple at all times. To find the multiple, solve the same problem for a long but finite time, and let the length grow. The answer settles down to a fixed value. That value tells the cost of every starting point and gives the gain. The settled gain always brings the system to rest, as long as every unstable motion can be pushed and every unstable motion is seen by the cost.
The problem
Continuous time. Input: , , and , with stabilizable and detectable. The plant is and the cost is . Output: the matrix with for all , and the gain such that attains the minimum. Discrete time: the same, with and .
The two hypotheses are the ones of the stabilizing solution theorem. Stabilizability makes some input give a finite cost. Detectability makes every input with finite cost drive the state to 0, so that a finite cost means a stable closed loop. The cost has no cross term here; with one, replace by and by and add to the gain.
The algorithm
The discrete-time version, by the backward recursion of the finite horizon run to its fixed point:
INFINITE-HORIZON-LQR(A, B, Q, R, tol)- 1
P ← 0 ▷ the cost of horizon 0 - 2
repeat - 3
K ← (R + B^T P B)^(-1) B^T P A ▷ solve, do not invert - 4
P_new ← Q + A^T P A - A^T P B K ▷ one step of the Riccati recursion - 5
δ ← ||P_new - P||_F; P ← P_new - 6
until δ ≤ tol · ||P||_F - 7
K ← (R + B^T P B)^(-1) B^T P A - 8
if A - B K is not Schur then fail; return (P, K)
After passes, is the cost matrix of the finite horizon with terminal weight 0. The loop stops when two horizons give nearly the same matrix. Line L8 checks the result, because the stopping test alone does not prove that the limit is the stabilizing solution: if is not detectable, the iteration can stop at a solution that does not stabilize, and line L8 then reports the failure.
The continuous-time version runs the same idea on the Riccati differential equation. In the backward time , it is with . The implementation integrates it with the classical RK4 method and the fixed step , where is the Hamiltonian matrix. It stops when the CARE residual, the right side of the equation, is below times the size of the data, then sets and checks that is Hurwitz. The step is chosen so that times each eigenvalue of the linearized flow near the solution lies inside the stability region of RK4.
Example
Continuous double integrator. For , , and , the code takes 102 RK4 steps of size and returns
with an error below . The closed loop has the characteristic polynomial , so the poles are : natural frequency 1 and damping ratio . From the optimal cost is , and an RK4 simulation of the closed loop over 40 seconds gives the same value within . The finite-horizon page shows how of horizon tends to this matrix.
Scalar cases. For in continuous time, the CARE is , whose roots are . The stabilizing one is , with and the closed loop . In discrete time, the DARE is , that is , so and . The recursion from 0 meets the tolerance after 19 passes; its iterates are the Fibonacci ratios
Sampled double integrator. The ZOH model with period 1 is , . With and , the recursion stops after 22 passes with
The off-diagonal entry is . The closed loop has the eigenvalues , of modulus , so it is Schur. A sum of the cost over 400 steps of the closed loop gives within (relative), and random nearby gains with a Schur closed loop all give a larger cost.
When the cost does not see the instability. Take , , , in discrete time. Then is not detectable. Starting from , every pass gives again, so the loop stops at once with , and line L8 fails because . The DARE has the two solutions and . The second one stabilizes: and . Starting the recursion from finds it. In words: with the cheapest input is no input at all, the cost is 0, and the state grows without bound.
Correctness
The full proof is in proofs/correctness.md. It has three parts. First, if solves the Riccati equation and is Hurwitz (Schur), then for every input with finite cost , or the same with a sum and in discrete time. Detectability is used here: a finite cost forces , so the term at the far end vanishes. So is optimal and the minimum is . Second, the finite-horizon costs from do not decrease with the horizon and are bounded by the cost of any stabilizing gain, so they converge, and the limit solves the Riccati equation because one step of the recursion is a continuous map. Third, the limit stabilizes: if with , the identity gives , so and , hence , which contradicts detectability by the PBH test.
The tests check the CARE and DARE residuals (at most times the size of the data), the symmetry and positive semidefiniteness of , the closed-loop eigenvalues, the double integrator and scalar closed forms, the simulated cost in both time domains, a grid search over scalar gains, and the failure cases.
Proof: The limit of the finite-horizon Riccati recursion is the stabilizing solution, and its gain is optimal on the infinite horizonfull
Discrete time is treated in full; the continuous case follows the same three steps and is given at the end. Let , , , , and let , so . Assume is stabilizable and is detectable. The plant is and the cost is , which may be .
For write , and
The two forms are equal by Lemma 2 of the finite-horizon proof. The algorithm computes and . By that proof, is the minimum of the cost of horizon with terminal weight 0.
Lemma 1: finite cost and detectability force
If , then .
Proof. Finite cost gives and , so and , and both sequences are square summable. By detectability there is with Schur. Write the plant as with . Then is square summable, hence . The solution is . Since for some and , the first term tends to 0, and the second is the convolution of a summable sequence with a sequence that tends to 0, which tends to 0.
Lemma 2: a stabilizing solution gives the optimal cost
Let satisfy , and let with Schur. Then for every , , attained by and by no other input sequence.
Proof. For any and , completing the square as in Lemma 1 of the finite-horizon proof gives
Sum this from to along a trajectory. The terms telescope:
If there is nothing to prove. Otherwise by Lemma 1, so letting ,
because . The feedback gives a Schur closed loop, so geometrically and its cost is finite; for it the sum is 0. Equality for another sequence would need for every .
In particular there is at most one stabilizing solution: two of them would both equal the optimal cost matrix.
Lemma 3: the recursion from 0 converges
The sequence is nondecreasing, there is a fixed matrix with for all , and the sequence converges to a matrix with .
Proof. Monotone: the cost of horizon restricted to its first steps is a cost of horizon with terminal weight 0, and the last term is nonnegative. Minimizing gives for every .
Bounded: by stabilizability there is with Schur. The feedback has the finite infinite-horizon cost , where converges. Its cost over the first steps is at most and at least , so .
Converges: for each , is nondecreasing and bounded, so it converges. By polarization, for symmetric , so every entry of converges, and with .
Fixed point: is continuous on the set of positive semidefinite matrices, because is invertible there and inversion is continuous. Taking the limit in gives .
Lemma 4: the limit stabilizes
Let satisfy and let . Then is Schur.
Proof. Let , and let with complex. The second form of gives . Multiply by on the left and on the right:
Suppose . The left side is at most 0 and the right side is at least 0, so both are 0. Then and, since , . So with and . By the PBH test for detectability, no such exists. So every eigenvalue of has .
Theorem
Under the hypotheses, the recursion from converges to the unique stabilizing solution of the DARE, is the optimal constant gain, and is the optimal cost of the infinite horizon.
Proof. Lemma 3 gives the limit , Lemma 4 shows that it is stabilizing, and Lemma 2 shows that it gives the optimal cost and the optimal feedback. Uniqueness follows from Lemma 2.
What the code checks. The loop stops after finitely many passes, when , so the returned matrix is an approximation of . Line L8 tests the closed loop with the computed gain. If the hypotheses fail, Lemma 4 can fail: for , , , , for all and , which is what the code reports.
Continuous time
The same steps work with and , with and .
- Finite cost forces . With such that is Hurwitz, solves with , so , and is in as well. A function with satisfies , so has a limit, which must be 0 because .
- If , and is Hurwitz, then Lemma 4 of the finite-horizon proof gives with . Let and use step 1.
- The solution of , , is the cost matrix of horizon . It is nondecreasing in and bounded by the cost of a stabilizing gain, so it converges to some . Its derivative converges to ; if this limit were not 0, would grow without bound in some entry, so .
- With , the CARE reads . If , then . If , both terms on the right vanish, so and , which contradicts detectability. So is Hurwitz.
The implementation integrates step 3 with RK4 and stops on the CARE residual. Its last check, that is Hurwitz, plays the role of Lemma 4 for the computed matrix.
Complexity
In the real RAM, with dense matrices:
- One pass of lines L3 to L5 costs , the same as one step of the finite-horizon recursion. Line L8 costs for the closed-loop matrix and its characteristic polynomial, plus the root finding.
- Convergence is linear. If is the stabilizing solution and , the error after passes behaves like , where is the spectral radius. The number of passes for a tolerance is therefore about . It grows without bound as the closed loop approaches the unit circle. The pass counts in the examples are measurements, not bounds.
- In continuous time, one RK4 step costs four evaluations of the Riccati right side, each . The error decays like , where is the largest real part of an eigenvalue of , and the step is at most of order . So the number of steps is of order times .
The extra space is . For a fast solution use the Schur method, which costs flops with a constant that does not depend on the closed loop, or the Kleinman iteration, which converges quadratically. The controller costs per step online.
Properties
- Constant gain. The optimal feedback does not depend on time or on . This is why it is used much more than the finite-horizon version.
- Guaranteed stability. Under stabilizability and detectability, is Hurwitz (Schur). Pole placement gives any poles; LQR gives poles that are optimal for a cost, and the weights and are the design knobs.
- Robustness in continuous time. With one input, or a diagonal , the loop has a gain margin of and a phase margin of at least 60 degrees in each channel. The LQR stability margins page proves this. Discrete-time LQR has smaller guaranteed margins, and LQG with an observer has none in general.
- Monotone in the weights. If , then , because every cost with is at most the same cost with .
- Scaling. Multiplying and by the same positive number multiplies by it and does not change . Only the ratio of the weights matters.
- Symmetric root locus. For one input, and , let . The closed-loop poles are the roots in the open left half plane of . As (cheap control), some poles tend to the zeros of in the left half plane and to the mirror images of its zeros in the right half plane, and the others go to infinity in a Butterworth pattern. As (expensive control), the poles tend to the stable eigenvalues of and to the mirror images of the unstable ones.
- Duality. With , , the same Riccati equation gives the steady-state gain of the Kalman filter in discrete time, and of the Kalman-Bucy filter in continuous time.
Variants and improvements
- Other solvers. The Schur method (Laub 1979) computes the stable invariant subspace of the Hamiltonian matrix and is the standard direct method. The Kleinman iteration is Newton's method on the CARE; Hewer (1971) gave the discrete version. Both need fewer operations than the recursion when the closed loop is slow. The recursion on this page is the value iteration of dynamic programming, and Kleinman's method is the policy iteration.
- Doubling. Doubling algorithms compute the cost of horizon from the cost of horizon , so passes give horizon , and the convergence becomes quadratic (Bini, Iannazzo and Meini).
- Cross term and discounting. A cross term is removed by the change of variables in The problem. A discount factor in discrete time replaces and by and .
- Integral action. To remove steady-state error for constant references, add the integral of the error to the state and apply LQR to the larger system; see integral state feedback.
- Output feedback. When the state is not measured, combine the gain with a Kalman filter: this is LQG control, which has the same gain by the separation principle but no guaranteed margins (Doyle's counterexample).
- H2 view. The LQR cost from a random initial state with covariance is , which is the squared H2 norm of a closed-loop system; see H2 optimal control.
When to use it
Use it to regulate a linear plant, or a linearization about an equilibrium, when the state is measured and the task has no fixed end. It is the default first design for multivariable plants because it always gives a stabilizing gain, handles many inputs with no extra effort, and has the margins of the LQR stability margins page in continuous time. Use finite-horizon LQR for a fixed time or a time-varying plant, and linear MPC when the inputs or states have hard limits. To compute for a real plant, call a Schur-based solver; the recursion on this page is the clearest way to see why the answer is right, not the fastest way to get it.
Pitfalls
- "Stable" needs the hypotheses. Without detectability of , the optimal cost can be finite while the state grows, and the iteration from 0 can return a gain that does not stabilize. The example above shows it. Always check the closed loop.
- Slow convergence. If the closed loop has a pole near the unit circle (discrete) or near the imaginary axis (continuous), the recursion needs very many passes. A stopping test on the change can then stop early, far from the solution. A test on the Riccati residual is better.
- Weights are not specifications. The choice of and is a design step. Bryson's rule, which sets each diagonal weight to one over the square of the largest allowed value of the variable, is a rule of thumb, not a result.
- The discrete margins are smaller. Do not quote the 60 degree phase margin for a discrete-time LQR design or for LQG. Check the margins of the actual loop.
- Sampling. A continuous design implemented with a sampler and a hold is a different loop. Either design in discrete time on the zero-order hold model, or check the sampled loop.
- Symmetry. In floating point, symmetrize after each step. A slightly unsymmetric gives a slightly wrong gain and can make the stopping test fail.
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()
ctlsim.py 120 lines
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Fixed step simulation for the control pages.
Conventions:
- A continuous-time system is a function f(t, x, u) that returns x' as a
flat list. x is a flat list. u is whatever the control returns (a flat
list, a scalar, or None when there is no control).
- A discrete-time system is a function F(k, x, u) that returns x_(k+1).
- The integrator is the classical 4th order Runge-Kutta method with a fixed
step dt. The input is held constant over each step.
- Time t_k = t0 + k dt is computed by multiplication, not by summation.
- The number of steps round((t1 - t0) / dt) and the hold ratio
round(hold / dt) must match the real ratios within 1e-9 (relative), or
ValueError is raised.
This file holds no controller or observer of a control page.
"""
__all__ = ["rk4_step", "simulate", "simulate_discrete", "lti"]
def _axpy(a, x, y):
return [yi + a * xi for xi, yi in zip(x, y)]
def rk4_step(f, t, x, u, dt):
"""Return x(t + dt) after one RK4 step of x' = f(t, x, u), u held constant."""
k1 = f(t, x, u)
k2 = f(t + dt / 2, _axpy(dt / 2, k1, x), u)
k3 = f(t + dt / 2, _axpy(dt / 2, k2, x), u)
k4 = f(t + dt, _axpy(dt, k3, x), u)
return [xi + dt / 6 * (a + 2 * b + 2 * c + d) for xi, a, b, c, d in zip(x, k1, k2, k3, k4)]
def _ratio(num, den, what):
r = round(num / den)
if abs(r * den - num) > 1e-9 * max(abs(num), abs(den)):
raise ValueError(what + " is not an integer multiple of dt")
return r
def simulate(f, x0, t0, t1, dt, control=None, hold=None):
"""Simulate x' = f(t, x, u) from x(t0) = x0 to t1 with RK4 and step dt.
control(t, x) gives the input. It is called at each sampling instant
t0 + j hold, and its value is held (zero-order hold) until the next
instant. hold must be an integer multiple of dt; hold = None means
hold = dt. With control = None the input is None.
Returns (ts, xs, us): ts has N + 1 times, xs the N + 1 states, and us the
N inputs, where us[k] acts on [ts[k], ts[k + 1]].
"""
if dt <= 0:
raise ValueError("dt must be positive")
n_steps = _ratio(t1 - t0, dt, "t1 - t0")
if n_steps < 0:
raise ValueError("t1 is before t0")
r = 1 if hold is None else _ratio(hold, dt, "hold")
if r < 1:
raise ValueError("hold must be at least dt")
x = list(x0)
ts = [t0]
xs = [list(x)]
us = []
u = None
for k in range(n_steps):
t = t0 + k * dt
if control is not None and k % r == 0:
u = control(t, list(x))
x = rk4_step(f, t, x, u, dt)
ts.append(t0 + (k + 1) * dt)
xs.append(x)
us.append(u)
return ts, xs, us
def simulate_discrete(F, x0, N, control=None):
"""Run x_(k+1) = F(k, x_k, u_k) for k = 0, ..., N - 1.
u_k = control(k, x_k), or None if control is None. Returns (xs, us) with
N + 1 states and N inputs. Exact if F and control are exact.
"""
x = list(x0)
xs = [list(x)]
us = []
for k in range(N):
u = control(k, list(x)) if control is not None else None
x = list(F(k, x, u))
xs.append(x)
us.append(u)
return xs, us
def lti(A, B=None):
"""Return f(t, x, u) = A x + B u for the system x' = A x + B u.
u may be a flat list, a scalar (one input) or None (zero input). B may
be None for a system with no input.
"""
def f(t, x, u):
dx = [sum(a * xi for a, xi in zip(row, x)) for row in A]
if B is None or u is None:
return dx
uu = u if isinstance(u, (list, tuple)) else [u]
return [d + sum(b * ui for b, ui in zip(row, uu)) for d, row in zip(dx, B)]
return f
def _self_test():
import math
f = lti([[-1.0]])
_, xs, _ = simulate(f, [1.0], 0.0, 1.0, 0.01)
assert abs(xs[-1][0] - math.exp(-1.0)) < 1e-9
return True
if __name__ == "__main__":
_self_test()
infinite_horizon_lqr.py 123 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/infinite-horizon-lqr/. The authors are listed in prov/G9RNJT.jsonl.
"""Infinite-horizon linear quadratic regulator, as the limit of the finite horizon.
Discrete time: x_(k+1) = A x_k + B u_k, cost sum_(k>=0) x_k^T Q x_k + u_k^T R u_k.
The finite-horizon cost matrices of horizon j, computed by the backward
Riccati recursion from P = P0 (default 0), converge to the stabilizing
solution of the DARE
P = Q + A^T P A - A^T P B (R + B^T P B)^(-1) B^T P A
when (A, B) is stabilizable and (Q^(1/2), A) is detectable. The gain is
K = (R + B^T P B)^(-1) B^T P A, the control is u = -K x, and A - B K is Schur.
Continuous time: x' = A x + B u, cost integral of x^T Q x + u^T R u. The
Riccati differential equation dP/dtau = A^T P + P A - P B R^(-1) B^T P + Q
in the backward time tau is integrated from P(0) = P0 with RK4 until the
CARE residual is small. The gain is K = R^(-1) B^T P and A - B K is Hurwitz.
Both functions check the closed loop at the end and raise ValueError if it
is not Schur (or Hurwitz). This happens, for example, when (Q^(1/2), A) is
not detectable and the iteration from 0 stops at a solution that does not
stabilize.
"""
from ctlmat import add, charpoly, mul, polyroots, scale, solve, sub, transpose
__all__ = ["dlqr", "lqr", "dare_residual", "care_residual", "closed_loop_eigs"]
def _fro(a):
return sum(abs(v) ** 2 for row in a for v in row) ** 0.5
def _sym(p):
return [[(p[i][j] + p[j][i]) / 2 for j in range(len(p))] for i in range(len(p))]
def _float(a):
return [[float(v) for v in row] for row in a]
def closed_loop_eigs(A, B, K):
"""Return the eigenvalues of A - B K, from its characteristic polynomial."""
return polyroots(charpoly(sub(A, mul(B, K))))
def _dgain(A, B, R, P):
pb = mul(P, B)
return solve(add(R, mul(transpose(B), pb)), mul(transpose(pb), A))
def dare_residual(A, B, Q, R, P):
"""Return Q + A^T P A - A^T P B (R + B^T P B)^(-1) B^T P A - P."""
k = _dgain(A, B, R, P)
at = transpose(A)
return sub(sub(add(Q, mul(at, mul(P, A))), mul(at, mul(mul(P, B), k))), P)
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(add(mul(transpose(A), P), mul(P, A)), sub(Q, mul(pb, solve(R, transpose(pb)))))
def dlqr(A, B, Q, R, P0=None, tol=1e-14, max_iter=100000):
"""Return (P, K, iterations) for the discrete-time infinite-horizon problem."""
A, B, Q, R = _float(A), _float(B), _float(Q), _float(R)
n = len(A)
p = [[0.0] * n for _ in range(n)] if P0 is None else _float(P0) # @line L1
at = transpose(A)
for it in range(1, max_iter + 1): # @line L2
k = _dgain(A, B, R, p) # @line L3
new = _sym(sub(add(Q, mul(at, mul(p, A))), mul(at, mul(mul(p, B), k)))) # @line L4
delta = _fro(sub(new, p)) # @line L5
p = new
if delta <= tol * max(_fro(p), 1e-300): # @line L6
break
else:
raise ValueError("the Riccati recursion did not converge")
k = _dgain(A, B, R, p) # @line L7
if max(abs(z) for z in closed_loop_eigs(A, B, k)) >= 1: # @line L8
raise ValueError("A - B K is not Schur: no stabilizing limit from this start")
return p, k, it
def lqr(A, B, Q, R, P0=None, tol=1e-13, h=None, max_steps=200000):
"""Return (P, K, steps) for the continuous-time infinite-horizon problem.
h is the RK4 step in the backward time. The default is
0.5 / (1 + ||H||_inf) for the Hamiltonian matrix H, so that h times
every eigenvalue of the linearized flow near the solution stays inside
the stability region of RK4.
"""
A, B, Q, R = _float(A), _float(B), _float(Q), _float(R)
n = len(A)
g = mul(B, solve(R, transpose(B)))
if h is None:
rows = [sum(abs(v) for v in A[i]) + sum(abs(v) for v in g[i]) for i in range(n)]
rows += [sum(abs(v) for v in Q[i]) + sum(abs(A[j][i]) for j in range(n)) for i in range(n)]
h = 0.5 / (1.0 + max(rows))
p = [[0.0] * n for _ in range(n)] if P0 is None else _float(P0)
def f(m):
return care_residual(A, B, Q, R, m)
scale_q = _fro(Q) + _fro(A) + _fro(g) + 1e-300
for step in range(1, max_steps + 1):
k1 = f(p)
size = scale_q * (1.0 + _fro(p)) ** 2
if _fro(k1) <= tol * size:
break
k2 = f(add(p, scale(h / 2, k1)))
k3 = f(add(p, scale(h / 2, k2)))
k4 = f(add(p, scale(h, k3)))
p = _sym(add(p, scale(h / 6, add(add(k1, scale(2, k2)), add(scale(2, k3), k4)))))
else:
raise ValueError("the Riccati differential equation did not reach a steady state")
k = solve(R, mul(transpose(B), p))
if max(z.real for z in closed_loop_eigs(A, B, k)) >= 0:
raise ValueError("A - B K is not Hurwitz: no stabilizing limit from this start")
return p, k, step
test_infinite_horizon_lqr.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/infinite-horizon-lqr/. The authors are listed in prov/G9RNJT.jsonl.
import math
import random
import pytest
import ctlmat as cm
import ctlsim as cs
from infinite_horizon_lqr import care_residual, closed_loop_eigs, dare_residual, dlqr, lqr
R3 = math.sqrt(3.0)
def quad(m, v):
return sum(v[i] * m[i][j] * v[j] for i in range(len(v)) for j in range(len(v)))
def close(a, b, tol):
return all(abs(x - y) <= tol for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def data_norm(A, B, Q, R, P):
g = cm.mul(B, cm.solve(R, cm.transpose(B)))
return cm.norm2(Q) + 2 * cm.norm2(A) * cm.norm2(P) + cm.norm2(g) * cm.norm2(P) ** 2
def check_solution(A, B, Q, R, P, K, discrete):
res = dare_residual(A, B, Q, R, P) if discrete else care_residual(A, B, Q, R, P)
assert cm.norm2(res) <= 1e-9 * data_norm(A, B, Q, R, P)
assert cm.is_symmetric(P, 1e-12 * cm.norm2(P))
lam = [v.real for v in cm.polyroots(cm.charpoly(P))]
assert min(lam) >= -1e-9 * cm.norm2(P)
eig = closed_loop_eigs(A, B, K)
if discrete:
assert max(abs(z) for z in eig) < 1
else:
assert max(z.real for z in eig) < 0
def test_double_integrator_continuous():
A, B, Q, R = [[0, 1], [0, 0]], [[0], [1]], [[1, 0], [0, 1]], [[1]]
P, K, _ = lqr(A, B, Q, R)
assert close(P, [[R3, 1.0], [1.0, R3]], 1e-9)
assert close(K, [[1.0, R3]], 1e-9)
check_solution(A, B, Q, R, P, K, False)
def test_scalar_care_and_dare():
P, K, _ = lqr([[1]], [[1]], [[1]], [[1]])
assert abs(P[0][0] - (1 + math.sqrt(2))) < 1e-9 and abs(K[0][0] - (1 + math.sqrt(2))) < 1e-9
P, K, _ = dlqr([[1]], [[1]], [[1]], [[1]])
phi = (1 + math.sqrt(5)) / 2
assert abs(P[0][0] - phi) < 1e-12 and abs(K[0][0] - (phi - 1)) < 1e-12
def test_sampled_double_integrator():
A, B, Q, R = [[1, 1], [0, 1]], [[0.5], [1]], [[1, 0], [0, 1]], [[1]]
P, K, _ = dlqr(A, B, Q, R)
check_solution(A, B, Q, R, P, K, True)
assert abs(P[0][1] - math.sqrt(5) / 2) < 1e-12
def random_problem(rng, n, m):
A = [[rng.uniform(-1.5, 1.5) for _ in range(n)] for _ in range(n)]
B = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(n)]
C = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
Q = cm.add(cm.mul(cm.transpose(C), C), cm.scale(0.1, cm.eye(n)))
D = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(m)]
R = cm.add(cm.mul(cm.transpose(D), D), cm.scale(0.5, cm.eye(m)))
return A, B, Q, R
@pytest.mark.parametrize("seed", [1, 2, 3, 4])
def test_random_continuous(seed):
rng = random.Random(seed)
A, B, Q, R = random_problem(rng, 3, rng.choice([1, 2]))
P, K, _ = lqr(A, B, Q, R)
check_solution(A, B, Q, R, P, K, False)
@pytest.mark.parametrize("seed", [5, 6, 7, 8])
def test_random_discrete(seed):
rng = random.Random(seed)
A, B, Q, R = random_problem(rng, 3, rng.choice([1, 2]))
P, K, _ = dlqr(A, B, Q, R)
check_solution(A, B, Q, R, P, K, True)
def test_discrete_cost_by_simulation_and_other_gains():
A, B, Q, R = [[1, 1], [0, 1]], [[0.5], [1]], [[1, 0], [0, 1]], [[1]]
P, K, _ = dlqr(A, B, Q, R)
def cost(gain, x0):
def step(k, x, u):
return [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]
xs, us = cs.simulate_discrete(step, x0, 400, lambda k, x: [-v for v in cm.matvec(gain, x)])
return sum(quad(Q, x) + quad(R, u) for x, u in zip(xs, us))
rng = random.Random(3)
for _ in range(3):
x0 = [rng.uniform(-1, 1), rng.uniform(-1, 1)]
best = cost(K, x0)
assert abs(best - quad(P, x0)) < 1e-10 * quad(P, x0)
for _ in range(5):
other = [[K[0][0] + rng.uniform(-0.1, 0.1), K[0][1] + rng.uniform(-0.1, 0.1)]]
if max(abs(z) for z in closed_loop_eigs(A, B, other)) < 0.95:
assert cost(other, x0) >= best
def test_scalar_gain_grid_search():
# Cost of the constant gain k for a = 2, b = 1, q = r = 1, from x0 = 1:
# sum of (1 + k^2)(2 - k)^(2j) = (1 + k^2) / (1 - (2 - k)^2) for |2 - k| < 1.
P, K, _ = dlqr([[2]], [[1]], [[1]], [[1]])
grid = [1.0 + 2.0 * i / 20000 for i in range(1, 20000)]
best = min(grid, key=lambda k: (1 + k * k) / (1 - (2 - k) ** 2))
assert abs(best - K[0][0]) < 2e-4
assert abs((1 + K[0][0] ** 2) / (1 - (2 - K[0][0]) ** 2) - P[0][0]) < 1e-12
def test_continuous_cost_by_simulation():
A, B, Q, R = [[0, 1], [0, 0]], [[0], [1]], [[1, 0], [0, 1]], [[1]]
P, K, _ = lqr(A, B, Q, R)
def f(t, xa, u):
x = xa[:2]
uu = [-v for v in cm.matvec(K, x)]
dx = [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, uu))]
return dx + [quad(Q, x) + quad(R, uu)]
x0 = [1.0, 0.5]
_, xs, _ = cs.simulate(f, x0 + [0.0], 0.0, 40.0, 0.01)
assert abs(xs[-1][2] - quad(P, x0)) < 1e-8
def test_not_detectable_start_from_zero_fails():
# Q = 0: P = 0 is a fixed point, and A - B K = A is not stable.
with pytest.raises(ValueError):
dlqr([[2]], [[1]], [[0]], [[1]])
with pytest.raises(ValueError):
lqr([[1]], [[1]], [[0]], [[1]])
# The stabilizing solutions exist: p = 3 (discrete) and p = 2 (continuous).
P, K, _ = dlqr([[2]], [[1]], [[0]], [[1]], P0=[[1]])
assert abs(P[0][0] - 3) < 1e-12 and abs(K[0][0] - 1.5) < 1e-12
P, K, _ = lqr([[1]], [[1]], [[0]], [[1]], P0=[[1]])
assert abs(P[0][0] - 2) < 1e-9
def test_not_stabilizable_fails():
with pytest.raises(ValueError):
dlqr([[1]], [[0]], [[1]], [[1]], max_iter=500)
History
Kalman (1960) posed the linear quadratic regulator problem, solved it on a finite interval with the Riccati differential equation, and showed that under controllability and observability the solution has a limit as the interval grows. The limit gives a constant feedback that stabilizes the plant. Wonham (1968) and Kučera (1972) weakened the hypotheses to stabilizability and detectability. Kleinman (1968) gave a Newton iteration for the algebraic equation, and Laub (1979) gave the Schur method, which became the standard numerical solver. Kalman (1964) showed that LQR loops satisfy the return difference inequality, which gives the classical robustness of the design.
References
- R. E. Kalman, Contributions to the theory of optimal control, Boletín de la Sociedad Matemática Mexicana 5(2), 102-119, 1960, the regulator problem on an unbounded interval, as the limit of the finite interval problem
- Daniel Liberzon, Calculus of Variations and Optimal Control Theory, A Concise Introduction, Princeton University Press, 2012, Section 6.2, Infinite-horizon LQR problem
- Dimitri P. Bertsekas, Dynamic Programming and Optimal Control, Volume I, fourth edition, Athena Scientific, 2017, Section 3.1, Linear Systems and Quadratic Cost, on the convergence of the Riccati recursion
- Brian D. O. Anderson and John B. Moore, Optimal Control, Linear Quadratic Methods, Prentice Hall, 1990 (Dover reprint, 2007), the infinite-time regulator problem and the stability of the closed loop, in the chapters on the standard regulator problem
- Kemin Zhou, John C. Doyle and Keith Glover, Robust and Optimal Control, Prentice Hall, 1996, Chapter 13, Algebraic Riccati Equations; Chapter 14, H2 Optimal Control
- Dario A. Bini, Bruno Iannazzo and Beatrice Meini, Numerical Solution of Algebraic Riccati Equations, SIAM, 2012, the doubling algorithms and their quadratic convergence
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 G9RNJT Edit this page History Report an error Markdown