Techniquecore
Indirect method for optimal control
Also called optimize then discretize.
Solves an optimal control problem by applying the maximum principle first and then solving the boundary value problem for state and costate, usually by shooting with Newton's method.
The indirect method solves an optimal control problem in two stages. First it applies the maximum principle: the input that minimizes the Hamiltonian is written as a function of the state and the costate, and this gives a system of differential equations with conditions at the start and conditions at the end. Then it solves this two-point boundary value problem numerically. The most common solver is shooting: guess the initial costate, integrate forward, measure the error in the end conditions, and correct the guess with Newton's method. The name means that the method finds the optimum indirectly, through the necessary conditions, and not by comparing costs. It is also called "optimize then discretize", in contrast to direct methods, which discretize the problem first.
In plain words
The maximum principle gives a rule that tells the best input at each moment, if you know the current state and a second quantity, the costate, which measures how much a small change in the state is worth. The state is known at the start. The costate is not known at the start, but there is a condition that it must meet at the end. So you guess its start value, run the system forward with the rule, and look at the end. If the end condition fails, you change the guess and run again, and Newton's method tells you how to change it. When the end condition holds, the run gives an input that satisfies the necessary conditions for an optimum. The answer is very accurate, but a good first guess is necessary, and long runs of unstable systems make the method fail.
When it applies
- The problem is smooth, and the minimum condition gives the input as an explicit and smooth function . The usual case is a Hamiltonian that is strictly convex in , for example a cost with a term , .
- The problem is normal (). Abnormal extremals exist (see the maximum principle), and the method does not find them unless they are set up separately.
- The structure of the solution is known: which arcs are bang, which are singular, and where state constraints are active. With the structure known, the switching and junction times become extra unknowns.
- A good first guess for the costate is available, for example from a direct method, from a simpler problem, or from a continuation in a parameter.
- High accuracy is needed. A converged solution satisfies the necessary conditions to the accuracy of the integrator, and it gives the costate, which is the sensitivity of the optimal cost to the state.
- The method is a poor choice when the structure of the solution is unknown, when the horizon is long and the dynamics are unstable (single shooting loses all accuracy, see Pitfalls), and when only a rough answer is needed quickly. Direct methods, as in trajectory optimization and nonlinear MPC, are more robust in those cases.
The template
The boundary value problem. Take the problem: minimize subject to , . With and , the maximum principle gives the canonical equations
with and end conditions from the transversality conditions. Some cases:
| end condition | residual |
|---|---|
| free end, fixed | |
| fixed end | |
| free final time, added to one of the above | , with as an extra unknown |
Single shooting. The unknowns are , with added if the final time is free. Each defines an initial value problem, and the residual is a function of . Shooting solves :
INDIRECT-SHOOTING(canon, x0, R, s, T, N, tol) ▷ s is the guess for λ(0), with T last if T is free- 1
repeat - 2
(x(T), λ(T)) ← RK4 with N steps on z' = canon(t, z) from z(0) = (x0, s) - 3
r ← R(x(T), λ(T), T) - 4
if ‖r‖ ≤ tol then return s - 5
J ← forward-difference Jacobian of r with respect to s - 6
solve J d = r and set s ← s - d
Line L2 uses the classical Runge-Kutta method with a fixed step. Line L5 costs one more integration for each unknown. After convergence, one more integration gives the state, the costate and the input , and a quadrature state gives the cost.
Why it works. If , and are , the end point is a function of , so is . The maximum principle says that a normal optimal solution gives a root of . Near a root where the Jacobian is nonsingular, Newton's method converges quadratically. A forward difference with step puts an error of order in , which makes the convergence linear with a rate of order : fast, but not quadratic. A root is only an extremal: it satisfies the necessary conditions, and second-order conditions or a comparison of costs must confirm that it is a minimum.
Checks. For a problem without explicit time dependence, is constant along an extremal, so its variation along the computed trajectory measures the integration error. A small perturbation of the input must change the cost only by , and for a minimum it must not lower it.
Classic examples
A scalar problem solved by hand. Minimize with , , the example of the optimal control problem page. Here , , and the residual is . With , and . This is linear, so one Newton step from any guess gives , , and the cost . For a general horizon and start , and . The tests check this for random and .
Linear quadratic problems and the Riccati equation. For with the cost and a free end, , and the canonical equations are linear:
So is affine and Newton converges in one step. The solution is , where solves the Riccati differential equation , , of the LQR problem. For the double integrator (, ) with , and , , and for shooting gives . The tests compare shooting with a separate RK4 integration of the Riccati equation, and they agree to . As , tends to , the solution of the continuous algebraic Riccati equation.
A nonlinear problem. Minimize with , and a free end. Then , , and
From the guess with steps, Newton needs 8 steps and gives , so . Along the solution stays at 0.174668 to within , , and the cost is about 2.21587. The tests add a random smooth perturbation to the input: the cost rises for , and , and its derivative at is below .
A free final time. Minimize with , , and free, the example of the transversality conditions page. Here is constant, and . The unknowns are and the residual is . From the guess Newton needs 4 steps to reach : and .
A bang-bang problem with a known structure. Steer the double integrator from to the origin in minimum time with (see time-optimal control). With , is constant, and . Here is not smooth, so it is better to fix the structure (one switch, from to ) and use the switch time and as unknowns, with the conditions . They give and . The costate follows from and : .
Variations
- Multiple shooting (Bulirsch 1971). Split into intervals, take the state and the costate at each node as unknowns, and add continuity conditions at the nodes. The system is larger but sparse, and each integration covers only , so the growth that ruins single shooting (see Pitfalls) falls from about to . Stoer and Bulirsch (Section 7.3) describe it, and it is the standard indirect solver for hard trajectory problems.
- Exact Jacobians. Integrate the variational equations next to , or use automatic differentiation, in place of the forward differences of line L5. This removes the error of order and costs about the same.
- Damped Newton. Take with chosen so that decreases. This widens the region of convergence, but it does not make it global.
- Continuation. Solve an easy problem first, for example with a large weight on , a short horizon, or a smoothed version of a bang-bang problem, and then change the parameter in small steps. Each solution is the guess for the next one. This is homotopy continuation applied to . Trélat (2012) describes its use for aerospace problems.
- Collocation of the boundary value problem. Solve the canonical equations with a collocation method for boundary value problems in place of shooting. Collocation does not integrate across the whole interval, so it does not suffer from the growth problem.
- Gradient methods in function space. Integrate the state forward with the current input, the costate backward from its end condition, and change the input in the direction (Kirk, Chapter 6). This is gradient descent on the cost. It needs no guess of the costate and converges from far away, but slowly. It is often used to get a guess for shooting.
- Direct and indirect methods together. A direct method gives a rough solution and estimates of the costate from the multipliers of the discretized problem. Shooting then refines this to high accuracy (von Stryk and Bulirsch 1992).
Pitfalls
- Growth of the sensitivity. The canonical equations are a Hamiltonian system, so the eigenvalues of their linearization come in pairs , and some solutions grow like . For with the cost , the canonical matrix has , and . This is 0.81 at , 172 at , at and at . The problem is linear, and the code needs 2 Newton steps at and (the second only removes the error of the forward differences). At it needs 5, because the forward-difference Jacobian loses digits. It still gives , which agrees with the infinite-horizon value to . At a change of in its last bit changes by about , so the residual cannot be made small and single shooting fails. The tests check both cases. Use multiple shooting or collocation for long horizons.
- The first guess. The costate has no direct physical meaning, so it is hard to guess, and the region in which Newton converges can be small. In the free-time example, the guess sends Newton toward the other root of , which needs , and the integration fails when becomes negative.
- An unknown structure. If the true solution has a bang arc, a singular arc or an active state constraint that the formulation does not include, there is no root, or there is a root of the wrong problem. A switch inside a fixed integration step also lowers the order of RK4. Find the structure with a direct method first, and then use switch times as unknowns.
- Abnormal and singular cases. The template assumes and a smooth . On a singular arc the minimum condition does not give , and the arc needs its own conditions.
- Necessary is not sufficient. A root of can be a maximum, a saddle or a local minimum that is not global. Compare the cost with other candidates, test perturbations, or check second-order conditions.
- The scaling of the costate. The costate can be many orders of magnitude larger or smaller than the state. Scale the variables so that the Newton system is well conditioned and the stopping test means the same in every component.
Code
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()
indirect_method_optimal_control.py 100 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/indirect-method-optimal-control/. The authors are listed in prov/NBHETY.jsonl.
"""Indirect method for optimal control by single shooting.
The maximum principle turns an optimal control problem into a two-point
boundary value problem for the state x and the costate lam:
x' = H_lam, lam' = -H_x, x(0) = x0, R(x(T), lam(T), T) = 0,
where the input u(x, lam) is already eliminated by the minimum condition.
Single shooting guesses the unknown initial costate s = lam(0) (and the final
time T if it is free), integrates the canonical equations forward with RK4,
and corrects the guess by Newton's method on the residual R.
Conventions:
- canon(t, z) returns z' for z = x + lam, one flat list with x first.
- residual(zT, T) returns a flat list with one entry for each unknown.
- With free_time = True the unknowns are s = lam(0) + [T], so T is last.
- The Newton Jacobian comes from forward differences with the step
h * max(1, |s_j|).
"""
import ctlmat as cm
import ctlsim as cs
__all__ = ["integrate", "shooting_residual", "fd_jacobian", "single_shooting"]
def integrate(canon, z0, T, N):
"""Return the N + 1 points z(k T / N), k = 0..N, of z' = canon(t, z) by RK4."""
if N < 1:
raise ValueError("integrate: N must be at least 1")
if not T > 0:
raise ValueError("integrate: T must be positive")
_, zs, _ = cs.simulate(lambda t, z, u: canon(t, z), [float(v) for v in z0], 0.0, T, T / N)
return zs
def _split(s, n, T, free_time):
"""Split the unknowns into the initial costate and the final time."""
want = n + 1 if free_time else n
if len(s) != want:
raise ValueError("expected %d unknowns, got %d" % (want, len(s)))
if free_time:
return [float(v) for v in s[:n]], float(s[n])
if T is None:
raise ValueError("T is required when the final time is fixed")
return [float(v) for v in s], float(T)
def shooting_residual(canon, x0, residual, s, T=None, N=200, free_time=False):
"""Return R(z(T), T) for the trajectory that starts at (x0, lam(0))."""
lam0, TT = _split(s, len(x0), T, free_time)
zT = integrate(canon, list(x0) + lam0, TT, N)[-1]
return [float(v) for v in residual(zT, TT)]
def fd_jacobian(phi, s, r=None, h=1e-7):
"""Return the forward difference Jacobian of phi at s (r = phi(s) if given)."""
r = phi(s) if r is None else r
cols = []
for j in range(len(s)):
step = h * max(1.0, abs(s[j]))
sj = list(s)
sj[j] += step
rj = phi(sj)
cols.append([(a - b) / step for a, b in zip(rj, r)])
return cm.transpose(cols)
def single_shooting(canon, x0, residual, s0, T=None, N=200, free_time=False,
tol=1e-10, maxit=50, h=1e-7):
"""Solve the boundary value problem by single shooting and Newton's method.
Returns (s, k): the unknowns s (lam(0), then T if free_time) with
||R|| <= tol, and the number k of Newton steps taken. Raises RuntimeError
if maxit Newton steps do not reach the tolerance.
"""
n = len(x0)
s = [float(v) for v in s0]
_split(s, n, T, free_time)
def phi(v):
return shooting_residual(canon, x0, residual, v, T, N, free_time)
for k in range(maxit + 1): # @line L1
lam0, TT = _split(s, n, T, free_time)
zT = integrate(canon, list(x0) + lam0, TT, N)[-1] # @line L2
r = [float(v) for v in residual(zT, TT)] # @line L3
if len(r) != len(s):
raise ValueError("the residual must have one entry for each unknown")
if cm.norm2(r) <= tol: # @line L4
return s, k
if k == maxit:
break
J = fd_jacobian(phi, s, r, h) # @line L5
d = cm.solve(J, r)
s = [a - b for a, b in zip(s, d)] # @line L6
raise RuntimeError("single_shooting: no convergence in %d Newton steps" % maxit)
test_indirect_method_optimal_control.py 174 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/indirect-method-optimal-control/. The authors are listed in prov/NBHETY.jsonl.
import math
import random
import pytest
import ctlmat as cm
import ctlsim as cs
from indirect_method_optimal_control import (
fd_jacobian,
integrate,
shooting_residual,
single_shooting,
)
def test_helper_self_tests():
assert cm._self_test()
assert cs._self_test()
# Scalar LQ problem: x' = u, cost int_0^T u^2 dt + x(T)^2.
# H = u^2 + lam u, u = -lam/2, lam' = 0, lam(T) = 2 x(T), so lam = 2 x0 / (1 + T).
def scalar_canon(t, z):
return [-z[1] / 2, 0.0]
def scalar_residual(zT, T):
return [zT[1] - 2 * zT[0]]
def test_scalar_lq_example():
s, k = single_shooting(scalar_canon, [1.0], scalar_residual, [0.0], T=1.0)
assert abs(s[0] - 1.0) < 1e-9
assert k <= 3
def test_scalar_lq_random():
rng = random.Random(11)
for _ in range(10):
x0 = rng.uniform(-3, 3)
T = rng.uniform(0.2, 4)
s, _ = single_shooting(scalar_canon, [x0], scalar_residual, [rng.uniform(-5, 5)], T=T, N=50)
assert abs(s[0] - 2 * x0 / (1 + T)) < 1e-9
# Double integrator LQ: x1' = x2, x2' = u, cost int_0^T (x^T x + u^2) dt, free end.
# u = -lam2/2, lam' = -2 x - A^T lam, lam(T) = 0; the Riccati solution gives lam(0) = 2 P(0) x0.
A2 = [[0, 1], [0, 0]]
def di_canon(t, z):
return [z[1], -z[3] / 2, -2 * z[0], -2 * z[1] - z[2]]
def riccati_p0(T, steps=600):
"""P(0) from -P' = A^T P + P A + Q - P B B^T P, P(T) = 0, in reversed time."""
def rhs(t, p, u):
P = cm.unvec(p, 2)
PB = [[P[0][1]], [P[1][1]]]
D = cm.add(cm.add(cm.mul(cm.transpose(A2), P), cm.mul(P, A2)),
cm.sub(cm.eye(2), cm.mul(PB, cm.transpose(PB))))
return cm.vec(D)
_, ps, _ = cs.simulate(rhs, [0.0] * 4, 0.0, T, T / steps)
return cm.unvec(ps[-1], 2)
def test_double_integrator_matches_riccati():
rng = random.Random(5)
T = 3.0
P0 = riccati_p0(T)
for _ in range(3):
x0 = [rng.uniform(-2, 2), rng.uniform(-2, 2)]
s, _ = single_shooting(di_canon, x0, lambda zT, TT: [zT[2], zT[3]], [0.0, 0.0], T=T, N=300)
want = [2 * v for v in cm.matvec(P0, x0)]
assert max(abs(a - b) for a, b in zip(s, want)) < 1e-8
# Nonlinear: x' = sin x + u, cost int_0^2 (x^2 + u^2) dt, x(0) = 1, free end.
# H = x^2 + u^2 + lam (sin x + u), u = -lam/2, lam' = -2 x - lam cos x, lam(2) = 0.
def nl_canon(t, z):
x, lam = z
return [math.sin(x) - lam / 2, -2 * x - lam * math.cos(x)]
def nl_solution():
return single_shooting(nl_canon, [1.0], lambda zT, T: [zT[1]], [0.0], T=2.0, N=400)
def test_nonlinear_converges_and_h_is_constant():
s, k = nl_solution()
assert abs(s[0] - 4.15956) < 1e-4
zs = integrate(nl_canon, [1.0] + s, 2.0, 400)
assert abs(zs[-1][1]) <= 1e-10
hs = [x * x - lam * lam / 4 + lam * math.sin(x) for x, lam in zs]
assert max(hs) - min(hs) < 1e-8
def test_nonlinear_cost_is_stationary_and_does_not_drop():
s, _ = nl_solution()
rng = random.Random(7)
co = [rng.uniform(-1, 1) for _ in range(4)]
def phi(t):
return co[0] + sum(co[j] * math.sin(j * math.pi * t / 2) for j in range(1, 4))
def cost(e):
# Integrate the optimal pair (x*, lam*) next to the perturbed state x
# and its cost, so the optimal input -lam*/2 is known at every RK4 stage.
def f(t, w, u):
xs, ls, x, _ = w
uu = -ls / 2 + e * phi(t)
return [math.sin(xs) - ls / 2, -2 * xs - ls * math.cos(xs), math.sin(x) + uu, x * x + uu * uu]
_, ws, _ = cs.simulate(f, [1.0, s[0], 1.0, 0.0], 0.0, 2.0, 2.0 / 400)
return ws[-1][3]
j0 = cost(0.0)
for e in (0.3, 0.1, -0.1, 0.03):
assert cost(e) > j0
e = 1e-3
assert abs((cost(e) - cost(-e)) / (2 * e)) < 1e-4
# Free final time: x' = u, cost int_0^T (1 + u^2) dt, x(0) = 1, x(T) = 0.
# Unknowns (lam(0), T), residual (x(T), H(T)) with H = 1 - lam^2 / 4. Answer (2, 1).
def test_free_final_time():
s, _ = single_shooting(scalar_canon, [1.0], lambda zT, T: [zT[0], 1 - zT[1] ** 2 / 4],
[1.5, 0.7], free_time=True, N=50)
assert abs(s[0] - 2) < 1e-9
assert abs(s[1] - 1) < 1e-9
def test_free_final_time_wrong_sign_guess():
# Newton heads for lam = -2, which needs T = -1, so the time goes negative.
with pytest.raises(ValueError):
single_shooting(scalar_canon, [1.0], lambda zT, T: [zT[0], 1 - zT[1] ** 2 / 4],
[-1.0, 0.7], free_time=True, N=50)
# x' = x + u, cost int (x^2 + u^2): the canonical matrix M has M^2 = 2 I, so the
# shooting derivative d lam(T) / d lam(0) is cosh(sqrt2 T) - sinh(sqrt2 T) / sqrt2.
def unstable_canon(t, z):
return [z[0] - z[1] / 2, -2 * z[0] - z[1]]
def test_shooting_sensitivity_grows_exponentially():
m = math.sqrt(2)
for T in (1.0, 5.0, 10.0):
def phi(v):
return shooting_residual(unstable_canon, [1.0], lambda zT, TT: [zT[1]], v, T=T, N=int(200 * T))
J = fd_jacobian(phi, [0.0])
want = math.cosh(m * T) - math.sinh(m * T) / m
assert abs(J[0][0] - want) < 1e-5 * want
assert want > 2e5
def test_long_horizon_approaches_riccati_and_long_one_fails():
s, _ = single_shooting(unstable_canon, [1.0], lambda zT, TT: [zT[1]], [0.0], T=10.0, N=1000)
assert abs(s[0] - 2 * (1 + math.sqrt(2))) < 1e-5
with pytest.raises(RuntimeError):
single_shooting(unstable_canon, [1.0], lambda zT, TT: [zT[1]], [0.0], T=20.0, N=1000, maxit=4)
def test_maxit_and_bad_input():
with pytest.raises(RuntimeError):
single_shooting(nl_canon, [1.0], lambda zT, T: [zT[1]], [0.0], T=2.0, maxit=0)
with pytest.raises(ValueError):
single_shooting(scalar_canon, [1.0], scalar_residual, [0.0, 1.0], T=1.0)
with pytest.raises(ValueError):
single_shooting(scalar_canon, [1.0], scalar_residual, [0.0])
with pytest.raises(ValueError):
integrate(scalar_canon, [1.0, 0.0], -1.0, 10)
Exercises
- For with the cost , show that and that Newton converges in one step from any guess.
- For the LQ problem, show that the canonical equations are linear, so that is affine in , and that satisfies them if solves the Riccati differential equation with .
- For with the cost and a free end, show that , , and . Show that this tends to as . (For and it is 3.37900.)
- In the free-time example, find both roots of and show that only gives .
- For the time-optimal double integrator from , check that , and satisfy , and .
- Explain why multiple shooting with equal intervals reduces the growth factor of the previous Pitfall from about to , and estimate the needed for if each interval may have a growth of at most . (Answer: gives .)
References
- Josef Stoer and Roland Bulirsch, Introduction to Numerical Analysis, third edition, Springer, 2002, Section 7.3 (boundary value problems, simple shooting and multiple shooting)
- Oskar von Stryk and Roland Bulirsch, Direct and indirect methods for trajectory optimization, Annals of Operations Research 37, 357-373, 1992
- John T. Betts, Survey of numerical methods for trajectory optimization, Journal of Guidance, Control, and Dynamics 21(2), 193-207, 1998
- Donald E. Kirk, Optimal Control Theory, An Introduction, Prentice-Hall, 1970 (Dover reprint, 2004), Chapter 6 (numerical determination of optimal trajectories)
- Roland Bulirsch, Die Mehrzielmethode zur numerischen Lösung von nichtlinearen Randwertproblemen und Aufgaben der optimalen Steuerung, report of the Carl-Cranz-Gesellschaft, 1971
- Emmanuel Trélat, Optimal control and applications to aerospace, some results and challenges, Journal of Optimization Theory and Applications 154(3), 713-758, 2012
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 | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag NBHETY Edit this page History Report an error Markdown