Algorithmcore
Finite-horizon LQR
Also called Riccati recursion, backward Riccati recursion.
Computes the time-varying optimal gains of a finite-horizon LQ problem by a Riccati difference or differential equation run backward.
- Time
- O(N (n^3 + m^3)) worst
- Space
- O(N n m + n^2) extra
- Where
- N = the number of steps of the horizon; m = the number of inputs; n = the number of states
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Rudolf E. Kalman, 1960
Finite-horizon LQR computes the optimal input of the linear quadratic regulator problem on a horizon of steps, or on a time interval . The answer is a linear state feedback whose gain changes with time. In discrete time the gains come from a recursion on symmetric matrices that starts at the terminal weight and runs backward to . In continuous time the same role is played by the Riccati differential equation, which is integrated backward from . The matrix gives the optimal cost from step : it is . The page differs from infinite-horizon LQR, where the horizon is unbounded and the gain is constant, and from the discrete and continuous algebraic Riccati equations, which are the fixed points of the backward recursion.
In plain words
You must steer a system for a fixed number of steps. Each step costs something for being far from zero and something for pushing hard, and the final position has its own cost. The trick is to plan from the end. At the last step there is nothing left to decide, so the cost is known. One step earlier, you can try every push, see where it lands, and add the known cost of that landing point. The best push turns out to be a fixed multiple of the current state, and the best cost is again a simple bowl-shaped function of the state. So the same reasoning repeats, one step earlier each time, back to the start. The output is one gain per step, computed once, before the system runs. While the system runs, the controller only multiplies the measured state by the gain of the current step.
The problem
Discrete time. Input: , , weights , and , and a horizon . The plant is and the cost is
Output: gains such that, for every initial state , the inputs minimize over all input sequences, and matrices such that the minimum of the cost from step and state is .
Continuous time. The plant is on , and the cost is . Output: the function on and the gain . This page has no cross term in the cost; the Variants section gives the change for it. The plant data may also depend on or ; the recursion then uses , , , at step with no other change.
The algorithm
FINITE-HORIZON-LQR(A, B, Q, R, Q_f, N)- 1
P_N ← Q_f - 2
for k ← N - 1 down to 0 - 3
S_k ← R + B^T P_(k+1) B ▷ m by m, positive definite - 4
K_k ← S_k^(-1) B^T P_(k+1) A ▷ solve S_k K_k = B^T P_(k+1) A - 5
P_k ← Q + A^T P_(k+1) A - A^T P_(k+1) B K_k - 6
return (P_0, ..., P_N), (K_0, ..., K_(N-1))
Line L1 sets the cost of the last state. Lines L3 and L4 compute the optimal gain of step from the cost matrix of step ; line L4 solves and does not form . Line L5 is the Riccati difference equation. It can also be written , which is a sum of positive semidefinite terms and keeps the symmetry better in floating point. The implementation also replaces each float by .
In continuous time the backward step is replaced by the Riccati differential equation
with the feedback . The implementation integrates it in the backward time with the classical Runge-Kutta method of order 4 and a fixed step for steps. To apply the controller to a plant model in continuous time, it stores on a grid twice as fine as the simulation step, so every stage of the RK4 step of the plant has its own .
Example
Scalar case. Take , and . Then , and . Starting from :
| 5 | 4 | 3 | 2 | 1 | 0 | |
|---|---|---|---|---|---|---|
| 0 | 1 | 3/2 | 8/5 | 21/13 | 55/34 | |
| 0 | 1/2 | 3/5 | 8/13 | 21/34 |
The values are ratios of Fibonacci numbers, for . They increase toward the golden ratio , and the gains increase toward . These limits are the solution and the gain of the scalar DARE. The last gain is 0: with no terminal cost, the last input only costs and gains nothing.
Sampled double integrator. The zero-order hold model of with period 1 is , . Weight the position only, , with and . At , line L3 gives , and , so line L4 gives . Line L5 gives
Two more steps give , and . From the optimal cost is . The tests check exactly against the minimum of over all three inputs, computed by one linear solve on the stacked input vector.
Continuous double integrator. For , , , and , the Riccati differential equation gives these values of :
| 1 | 0.964836 | 0.389571 |
| 2 | 1.536475 | 0.833236 |
| 5 | 1.730851 | 0.998961 |
| 10 | 1.732051 | 1.000000 |
As grows, tends to , the stabilizing solution of the CARE, and the gain tends to . For the scalar plant with , the equation is , with the closed form , where and . For it gives ; the limit for large is .
Correctness
The full proof is in proofs/correctness.md. In short, it is an induction on from down to 0, using the principle of optimality: the optimal cost from step satisfies the Bellman equation with . If with , the expression in the minimum is . Because , it is a strictly convex quadratic in , and completing the square gives the unique minimizer and the value with from line L5. The form shows , which keeps the induction going. In continuous time, the identity along every trajectory, integrated from 0 to , gives . The proof file also shows that exists on all of .
The tests check the recursion in exact rational arithmetic against the stacked least squares minimum on random problems, check that the simulated cost of the feedback equals exactly and that random other inputs cost more, check the scalar closed forms, and check that a long horizon gives the DARE and CARE solutions within .
Proof: The backward Riccati recursion gives the optimal feedback and the optimal cost of the finite-horizon LQ problemfull
Let , , , , and . The plant is . For and a state , let be the infimum of
over all input sequences. The algorithm sets and, for ,
Lemma 1: completing the square
Let be , let and . Then has the unique minimizer , and with .
Proof. Expand , using and the symmetry of . So , a constant. The term is positive for because .
Lemma 2: the algebra of one step
Let , , and . Then , is symmetric, and
Proof. For , . So is positive definite and invertible. Expand the right side:
Since , we have , so the last two terms cancel and the right side equals . The right side is a sum of symmetric matrices, and each of , and is positive semidefinite. So is symmetric and .
Theorem
For every and , . The minimum is attained, and an input sequence is optimal from if and only if for along the trajectory it produces. All are symmetric and positive semidefinite.
Proof. By induction on downward. For there is no input and , and is symmetric and positive semidefinite.
Let and assume the claim for . Fix and any inputs . Split the cost as
By the induction hypothesis, for , with equality if and only if follow the feedback from step . So
This is of Lemma 1 with , and ; Lemma 2 gives . Lemma 1 gives with equality if and only if , and
So for every input sequence. Equality holds if and only if and the later inputs are optimal from , which by the induction hypothesis means that they follow the feedback. This choice exists, so and the minimum is attained. Lemma 2 with gives that is symmetric and .
This is the principle of optimality for this problem: the tail of an optimal sequence is optimal for the tail problem, and satisfies the Bellman equation .
Exact arithmetic. Each step uses only sums, products and one linear solve with the matrix , which is invertible by Lemma 2. So with rational data every and is rational, and the implementation computes them exactly in Fraction.
Continuous time
Let , , be as above and . Consider on with a measurable, square integrable input , and the cost . Let .
Lemma 3: the Riccati differential equation has a solution on all of . The equation , , has a unique solution on , and , where solves the linear equation , .
Proof. The right side is a polynomial in the entries of , so it is locally Lipschitz, and a unique solution exists on a maximal interval . If , the solution must be unbounded as . We show that it stays between and , which is bounded on , so . On , the identity of Lemma 4 below holds for every input, because its proof uses only the equation on the interval . Taking any and starting the plant at time from , it gives for every input. With the feedback , which gives a linear equation with continuous coefficients and so a solution on , the integral vanishes and is a cost, hence at least 0. With the input , , where the last equality holds because, for , , and the integral of this from to gives . Both bounds hold for every , so .
Lemma 4: the cost identity. Let . For every input and every trajectory,
Proof. Along a trajectory, using the symmetry of ,
Now , because and . So
Integrate from 0 to and use :
Rearranging gives the identity.
Theorem (continuous time). The minimum of from is . It is attained by the feedback , and every optimal input equals for almost every .
Proof. By Lemma 4, , because makes the integral nonnegative. The feedback makes the integral 0. If the integral is 0 for some input, then almost everywhere, again because .
The numerical method. The implementation integrates the equation in , where it reads , with the classical RK4 method and a fixed step . RK4 has global error on a bounded interval for a smooth right side, and Lemma 3 shows that the exact solution stays in a bounded set, so for small enough the computed is within of at the grid points. The tests compare it with the scalar closed form within . This part is a property of the integrator, not of the LQ problem.
Complexity
In the real RAM, with dense matrices and flops counted as for a dense product or factorization of size :
- Line L3 costs .
- Line L4 costs for the right side and for the solve with right sides.
- Line L5 costs .
One step costs , which is , and the whole recursion costs . Storing all gains takes space; the recursion itself needs . A controller that runs online pays per step for . In continuous time, one RK4 step costs four evaluations of the right side, each , and the number of steps is set by the accuracy wanted and by the stiffness of the equation, not by .
The stacked formulation, which treats as one vector of size , costs for a dense solve. The backward recursion uses the stage structure and is linear in .
Properties
- Feedback, not a fixed sequence. The gains do not depend on . The same gains are optimal from every initial state, and from every state reached at step .
- Symmetric and positive semidefinite. Every is symmetric and , by the induction in the proof. If , then for .
- Monotone in the horizon. With , the cost matrix of horizon does not decrease when grows, because a longer horizon adds nonnegative terms to the cost. The scalar example shows this.
- Convergence for a long horizon. If is stabilizable and is detectable, then as , where is the stabilizing solution of the DARE, for every . Bertsekas (Section 3.1) proves this under the stronger hypotheses that is controllable and is observable; the stabilizing solution theorem gives the limit. With the recursion stays at and the gain is constant.
- Certainty equivalence. If zero mean independent noise with finite covariance is added to the plant, the same gains minimize the expected cost (Bertsekas, Section 3.1). The noise only adds a constant to the cost.
- Duality with the Kalman filter. With , , process noise covariance and measurement noise covariance, line L5 becomes the covariance recursion of the Kalman filter, which runs forward in time.
Variants and improvements
- Time-varying data. For and weights , , use the data of step in lines L3 to L5. In continuous time this is the linear time-varying system case.
- Cross term. For a cost term , replace by in line L4, and line L5 becomes . The weight matrix must be positive semidefinite with .
- Tracking. To follow a known reference, add an affine term: the value function becomes , and follows a linear backward recursion next to .
- Sampled continuous cost. To minimize a continuous cost with a held input, sample the plant with the zero-order hold and compute the matching , and by one block matrix exponential (Van Loan 1978). The result has a cross term even when the continuous cost has none.
- Square root forms. For poorly conditioned data, propagate a Cholesky factor of with orthogonal transformations instead of itself, as in square root Kalman filters.
- Constraints. With bounds on or the value function is no longer quadratic, and the problem becomes a quadratic program; see linear MPC, which repeats a finite-horizon problem at every sampling instant.
When to use it
Use it when the task has a natural end: a maneuver with a fixed duration, a landing, a batch process, or the inner problem of model predictive control without constraints. It is also the right tool for time-varying plants, where no constant gain exists, for example a trajectory that was linearized along a nominal path. For regulation about an equilibrium over a long time, use infinite-horizon LQR instead. Its constant gain is simpler to implement, and it comes with the stability guarantee that a finite horizon does not give.
Pitfalls
- Wrong direction. The recursion runs backward from . Running line L5 forward from computes the gains of a different problem. In continuous time, integrating the Riccati differential equation forward from is a sign error, and the solution can blow up.
- Index shift. The gain uses , not . An off-by-one error here gives a feedback that looks reasonable and is not optimal.
- No stability from a finite horizon. The time-varying gains are optimal for the horizon, but the gains near the end are small (here when ). Repeating the first gain forever as a constant feedback is not guaranteed to give a Schur closed loop unless is chosen well, for example equal to the DARE solution. This is the stability problem of receding horizon control that the MPC stability theorem addresses.
- Loss of symmetry. In floating point, the form in line L5 can lose symmetry and even positive semidefiniteness. Symmetrize, or use the form .
- Stiff differential equation. The Riccati differential equation can be stiff when the closed loop has fast and slow modes. A fixed step explicit method then needs a small step. The tests use RK4 with steps of at most on plants with eigenvalues of size about 1.
- The name. "Riccati recursion" also names the covariance update of the Kalman filter, so say which one is meant.
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()
finite_horizon_lqr.py 104 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/finite-horizon-lqr/. The authors are listed in prov/6S5J80.jsonl.
"""Finite-horizon linear quadratic regulator.
Discrete time. The plant is x_(k+1) = A x_k + B u_k for k = 0, ..., N - 1,
and the cost is
J = sum_(k=0)^(N-1) (x_k^T Q x_k + u_k^T R u_k) + x_N^T Q_f x_N,
with Q >= 0, Q_f >= 0 and R > 0. The backward recursion
P_N = Q_f,
K_k = (R + B^T P_(k+1) B)^(-1) B^T P_(k+1) A,
P_k = Q + A^T P_(k+1) A - A^T P_(k+1) B K_k,
gives the optimal feedback u_k = -K_k x_k and the optimal cost x_0^T P_0 x_0.
With int or Fraction data every step is exact.
Continuous time. The plant is x' = A x + B u on [0, T], and the cost is the
integral of x^T Q x + u^T R u plus x(T)^T Q_f x(T). The Riccati differential
equation
-P'(t) = A^T P + P A - P B R^(-1) B^T P + Q, P(T) = Q_f,
is integrated backward from T with the classical RK4 method and a fixed
step. The optimal feedback is u(t) = -R^(-1) B^T P(t) x(t).
"""
from ctlmat import add, mul, scale, solve, sub, transpose
__all__ = ["riccati_backward", "lqr_cost", "riccati_ode", "rde_rhs"]
def _sym(p):
"""Return (P + P^T) / 2 for a float matrix; exact matrices are returned as they are."""
return [[(p[i][j] + p[j][i]) / 2 if isinstance(p[i][j], float) else p[i][j]
for j in range(len(p))] for i in range(len(p))]
def riccati_backward(A, B, Q, R, Qf, N):
"""Return (Ps, Ks): Ps[k] = P_k for k = 0, ..., N and Ks[k] = K_k for k < N."""
if N < 0:
raise ValueError("the horizon N must be at least 0")
at, bt = transpose(A), transpose(B)
Ps = [None] * (N + 1)
Ks = [None] * N
p = [list(row) for row in Qf] # @line L1
Ps[N] = p
for k in range(N - 1, -1, -1): # @line L2
pb = mul(p, B)
s = add(R, mul(bt, pb)) # @line L3
kk = solve(s, mul(transpose(pb), A)) # @line L4
p = sub(add(Q, mul(at, mul(p, A))), mul(at, mul(pb, kk))) # @line L5
Ps[k] = _sym(p)
Ks[k] = kk
p = Ps[k]
return Ps, Ks # @line L6
def lqr_cost(A, B, Q, R, Qf, xs, us):
"""Return the cost J of the trajectory xs (N + 1 states) and inputs us (N inputs)."""
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)))
total = 0
for x, u in zip(xs, us):
total += quad(Q, x) + quad(R, u)
return total + quad(Qf, xs[-1])
def rde_rhs(A, B, Q, R, P):
"""Return A^T P + P A - P B R^(-1) B^T P + Q, which is -P'(t)."""
pb = mul(P, B)
return add(add(mul(transpose(A), P), mul(P, A)),
sub(Q, mul(pb, solve(R, transpose(pb)))))
def riccati_ode(A, B, Q, R, Qf, T, steps):
"""Integrate the Riccati differential equation backward from P(T) = Qf.
Uses `steps` RK4 steps of size T / steps. Returns (ts, Ps) with
ts[j] = j T / steps and Ps[j] approximately P(ts[j]), so Ps[0] is P(0).
The cost of the optimal control from x(0) = x_0 is x_0^T P(0) x_0.
"""
if steps < 1 or T <= 0:
raise ValueError("T must be positive and steps at least 1")
h = T / steps
p = [[float(v) for v in row] for row in Qf]
Ps = [None] * (steps + 1)
Ps[steps] = p
def f(m):
return rde_rhs(A, B, Q, R, m)
for j in range(steps, 0, -1):
# In backward time tau = T - t the equation is dP/dtau = f(P).
k1 = f(p)
k2 = f(add(p, scale(h / 2, k1)))
k3 = f(add(p, scale(h / 2, k2)))
k4 = f(add(p, scale(h, k3)))
inc = add(add(k1, scale(2, k2)), add(scale(2, k3), k4))
p = _sym(add(p, scale(h / 6, inc)))
Ps[j - 1] = p
return [j * h for j in range(steps + 1)], Ps
test_finite_horizon_lqr.py 193 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/finite-horizon-lqr/. The authors are listed in prov/6S5J80.jsonl.
import math
import random
from fractions import Fraction
import pytest
import ctlmat as cm
import ctlsim as cs
from finite_horizon_lqr import lqr_cost, rde_rhs, riccati_backward, riccati_ode
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 batch_value_matrix(A, B, Q, R, Qf, N):
"""Minimum of J over all input sequences, as x0^T W x0, by stacking the inputs.
x_k = Phi_k x0 + Gamma_k U with U = (u_0, ..., u_(N-1)). J is a quadratic
form in (x0, U), and the minimum over U is x0^T (M - G^T H^(-1) G) x0.
This is the brute force reference: one linear solve of size N m, no recursion.
"""
n, m = len(A), len(B[0])
phi = cm.eye(n)
gam = cm.zeros(n, N * m)
H = cm.zeros(N * m)
for k in range(N):
for i in range(m):
H[k * m + i][k * m:(k + 1) * m] = list(R[i])
G = cm.zeros(N * m, n)
M = cm.zeros(n)
for k in range(N + 1):
w = Qf if k == N else Q
gtw = cm.mul(cm.transpose(gam), w)
H = cm.add(H, cm.mul(gtw, gam))
G = cm.add(G, cm.mul(gtw, phi))
M = cm.add(M, cm.mul(cm.transpose(phi), cm.mul(w, phi)))
if k < N:
gam = cm.mul(A, gam)
for i in range(n):
for j in range(m):
gam[i][k * m + j] += B[i][j]
phi = cm.mul(A, phi)
return cm.sub(M, cm.mul(cm.transpose(G), cm.solve(H, G))), H
def closed_loop(A, B, Ks):
def step(k, x, u):
return [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]
def control(k, x):
return [-v for v in cm.matvec(Ks[k], x)]
return step, control
def test_scalar_fibonacci():
Ps, Ks = riccati_backward([[1]], [[1]], [[1]], [[1]], [[0]], 5)
assert [p[0][0] for p in Ps] == [Fraction(55, 34), Fraction(21, 13), Fraction(8, 5),
Fraction(3, 2), 1, 0]
assert [k[0][0] for k in Ks] == [Fraction(21, 34), Fraction(8, 13), Fraction(3, 5),
Fraction(1, 2), 0]
def test_scalar_limit_is_golden_ratio():
Ps, Ks = riccati_backward([[1.0]], [[1.0]], [[1.0]], [[1.0]], [[0.0]], 40)
phi = (1 + math.sqrt(5)) / 2
assert abs(Ps[0][0][0] - phi) < 1e-12
assert abs(Ks[0][0][0] - (phi - 1)) < 1e-12
def test_double_integrator_steps_exact():
A = [[1, 1], [0, 1]]
B = [[Fraction(1, 2)], [1]]
Q = [[1, 0], [0, 0]]
Ps, Ks = riccati_backward(A, B, Q, [[1]], Q, 3)
assert Ps[2] == [[Fraction(9, 5), Fraction(4, 5)], [Fraction(4, 5), Fraction(4, 5)]]
assert Ks[2] == [[Fraction(2, 5), Fraction(2, 5)]]
assert Ps[0] == [[Fraction(1817, 949), Fraction(900, 949)], [Fraction(900, 949), Fraction(1388, 949)]]
def random_problem(rng, n, m):
A = [[Fraction(rng.randint(-4, 4), 2) for _ in range(n)] for _ in range(n)]
B = [[Fraction(rng.randint(-3, 3), 2) for _ in range(m)] for _ in range(n)]
C = [[Fraction(rng.randint(-2, 2)) for _ in range(n)] for _ in range(n)]
Q = cm.mul(cm.transpose(C), C)
D = [[Fraction(rng.randint(-2, 2)) for _ in range(m)] for _ in range(m)]
R = cm.add(cm.mul(cm.transpose(D), D), cm.eye(m))
E = [[Fraction(rng.randint(-1, 1)) for _ in range(n)] for _ in range(n)]
Qf = cm.mul(cm.transpose(E), E)
return A, B, Q, R, Qf
@pytest.mark.parametrize("seed", [1, 2, 3, 4, 5])
def test_matches_batch_minimum_exactly(seed):
rng = random.Random(seed)
n, m = rng.choice([(2, 1), (3, 1), (3, 2)])
N = rng.randint(1, 4)
A, B, Q, R, Qf = random_problem(rng, n, m)
Ps, Ks = riccati_backward(A, B, Q, R, Qf, N)
W, _ = batch_value_matrix(A, B, Q, R, Qf, N)
assert Ps[0] == W
for p in Ps:
assert cm.is_symmetric(p)
@pytest.mark.parametrize("seed", [11, 12, 13])
def test_feedback_cost_and_perturbations(seed):
rng = random.Random(seed)
n, m, N = 3, 2, 4
A, B, Q, R, Qf = random_problem(rng, n, m)
Ps, Ks = riccati_backward(A, B, Q, R, Qf, N)
step, control = closed_loop(A, B, Ks)
x0 = [Fraction(rng.randint(-3, 3)) for _ in range(n)]
xs, us = cs.simulate_discrete(step, x0, N, control)
best = lqr_cost(A, B, Q, R, Qf, xs, us)
assert best == quad(Ps[0], x0)
for _ in range(10):
vs = [[u[i] + Fraction(rng.randint(-2, 2), 3) for i in range(m)] for u in us]
if vs == us:
continue
ys, _ = cs.simulate_discrete(step, x0, N, lambda k, x: vs[k])
assert lqr_cost(A, B, Q, R, Qf, ys, vs) > best
def test_long_horizon_solves_the_dare():
A = [[1.0, 1.0], [0.0, 1.0]]
B = [[0.5], [1.0]]
Q = [[1.0, 0.0], [0.0, 1.0]]
R = [[1.0]]
Ps, Ks = riccati_backward(A, B, Q, R, [[0.0, 0.0], [0.0, 0.0]], 80)
P = Ps[0]
pb = cm.mul(P, B)
s = cm.add(R, cm.mul(cm.transpose(B), pb))
rhs = cm.sub(cm.add(Q, cm.mul(cm.transpose(A), cm.mul(P, A))),
cm.mul(cm.mul(cm.transpose(A), pb), cm.solve(s, cm.mul(cm.transpose(pb), A))))
assert cm.norm2(cm.sub(rhs, P)) < 1e-12 * cm.norm2(P)
acl = cm.sub(A, cm.mul(B, Ks[0]))
assert max(abs(z) for z in cm.polyroots(cm.charpoly(acl))) < 1
def test_zero_horizon():
Ps, Ks = riccati_backward([[2]], [[1]], [[1]], [[1]], [[3]], 0)
assert Ps == [[[3]]] and Ks == []
with pytest.raises(ValueError):
riccati_backward([[2]], [[1]], [[1]], [[1]], [[3]], -1)
def test_scalar_riccati_ode_closed_form():
T = 1.0
ts, Ps = riccati_ode([[1.0]], [[1.0]], [[1.0]], [[1.0]], [[0.0]], T, 200)
s = math.sqrt(2.0)
pp, pm = 1 + s, 1 - s
for t, P in zip(ts[::20], Ps[::20]):
w = (pp / pm) * math.exp(-2 * s * (T - t))
assert abs(P[0][0] - (pp - w * pm) / (1 - w)) < 1e-9
def test_riccati_ode_long_horizon_tends_to_care():
A = [[0.0, 1.0], [0.0, 0.0]]
B = [[0.0], [1.0]]
Q = [[1.0, 0.0], [0.0, 1.0]]
_, Ps = riccati_ode(A, B, Q, [[1.0]], [[0.0, 0.0], [0.0, 0.0]], 30.0, 3000)
r3 = math.sqrt(3.0)
want = [[r3, 1.0], [1.0, r3]]
assert max(abs(Ps[0][i][j] - want[i][j]) for i in range(2) for j in range(2)) < 1e-9
assert cm.norm2(rde_rhs(A, B, Q, [[1.0]], Ps[0])) < 1e-9
def test_continuous_simulated_cost_equals_value():
A = [[0.0, 1.0], [-1.0, 0.5]]
B = [[0.0], [1.0]]
Q = [[2.0, 0.0], [0.0, 1.0]]
R = [[0.5]]
Qf = [[1.0, 0.0], [0.0, 3.0]]
T, S = 2.0, 400
_, Ps = riccati_ode(A, B, Q, R, Qf, T, 2 * S)
half = T / (2 * S)
def f(t, xa, u):
x = xa[:2]
P = Ps[round(t / half)]
k = cm.solve(R, cm.mul(cm.transpose(B), P))
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, T, T / S)
cost = xs[-1][2] + quad(Qf, xs[-1][:2])
assert abs(cost - quad(Ps[0], x0)) < 1e-8 * quad(Ps[0], x0)
History
Kalman (1960) posed the regulator problem for linear systems with a quadratic cost and showed that the optimal control on a finite interval is a linear feedback whose gain comes from a Riccati differential equation solved backward from the terminal time. The discrete version follows from Bellman's dynamic programming, which was developed in the 1950s. Kalman's paper also studied the limit of an unbounded horizon. The textbooks of Anderson and Moore made the backward Riccati equation the standard tool of the area; their 1990 book is the one cited here.
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 a finite interval and the Riccati differential equation of the optimal cost
- Brian D. O. Anderson and John B. Moore, Optimal Control, Linear Quadratic Methods, Prentice Hall, 1990 (Dover reprint, 2007), Chapter 2, The Standard Regulator Problem I
- Daniel Liberzon, Calculus of Variations and Optimal Control Theory, A Concise Introduction, Princeton University Press, 2012, Section 6.1, Finite-horizon LQR problem, with Section 6.1.2 on the Riccati differential equation
- Dimitri P. Bertsekas, Dynamic Programming and Optimal Control, Volume I, fourth edition, Athena Scientific, 2017, Section 3.1, Linear Systems and Quadratic Cost
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 6S5J80 Edit this page History Report an error Markdown