Problemcore
Minimum-energy control
Also called minimum-norm control.
Reach a given state at a given time with the input of least energy, solved by a formula in the controllability Gramian.
- Model
- Real RAM
- Evidence
- Full proofCode in 1 languages
The minimum-energy control problem asks for the input that moves a linear system from a given state to a given state in a given time , with the least energy . If the controllability Gramian is invertible, the answer is unique and has a closed form:
and the least energy is . The Gramian is invertible exactly when the system has controllability, so the problem is also the standard proof that a controllable system can reach every state. The discrete-time problem has the same form with the -step Gramian and is a least-norm solution of a linear system. The formula belongs to the controllability theory of linear systems that Kalman, Ho and Narendra developed in the early 1960s; textbooks such as Brockett (1970) present it as a least-norm problem in a space of functions, and Van Loan (1978) gave the block exponential method that computes the Gramian.
In plain words
You must bring the system to a target at a fixed time and you pay for the square of the input. Of all the inputs that arrive on time, take the one that is cheapest. Without the free motion, the system would need to cover the distance . The input that does this cheaply pushes hardest in the directions where the input moves the state easily, and the Gramian measures how easily each direction is reached. A target in a direction where has a small eigenvalue is expensive, and a short time makes every target expensive.
Definition
Input. Real matrices () and (), states and a time .
Output. An input , square integrable, such that the solution of , has , and
for every input with the same property; or the answer that no input reaches .
Solution. Let . If is invertible, the unique optimal input is the formula above. The proof (proofs/correctness.md) writes the reached state as for a linear map from inputs to , shows that , and finds that is orthogonal to every input that maps to 0. Any other admissible input is with , and its energy is . If is singular, the reachable values of lie in a proper subspace, the range of ; for in that range the formula holds with the pseudoinverse.
Variants
- Discrete time. For and steps, minimize with . With and , the answer is , energy . It is rational for rational data.
- Weighted energy. Minimize with : replace by in the Gramian and by in the input.
- Time-varying systems. Replace by the state transition matrix in all formulas.
- Soft target. Penalize in place of requiring it to be zero. This is a finite-horizon LQR problem with and a terminal weight , and as its solution tends to the minimum-energy input.
- Input bounds. With there is no closed form. Minimum time with bounded input gives bang-bang control, and minimum fuel gives inputs that switch between , and ; both follow from the maximum principle.
Examples
Double integrator. , , so and
Move from rest at 0 to rest at 1 in : , , . With and , the input is : full push at the start, full brake at the end, and it changes sign at . The energy is . For a general time the energy is , so half the time costs eight times the energy.
A stable scalar plant. , : . From to in the energy is , and grows toward the end, since an early push decays before .
Discrete scalar plant. from 0 to 21 in 3 steps: , , , so and the energy is 21. Early inputs are larger because the plant doubles them.
No solution. , . Both states move together, is a multiple of and is singular, and the target from cannot be reached.
Known algorithms
The closed form is computed in a fixed number of matrix operations:
MINIMUM-ENERGY-CONTROL(A, B, x_0, x_1, t_1)- 1
W ← Gramian(A, B, t_1) ▷ e^{M t_1}, M = [[-A, B B^T], [0, A^T]] (Van Loan) - 2
if W is not positive definite then return "x_1 cannot be reached from every x_0" - 3
d ← x_1 - e^{A t_1} x_0 - 4
η ← W^(-1) d - 5
u(t) ← B^T e^{A^T (t_1 - t)} η, for 0 ≤ t ≤ t_1 - 6
return u and the energy d^T η
Line L1 uses Van Loan's block method (1978): if , then , , and . Other ways to compute the Gramian are numerical quadrature of the integral, and the Lyapunov equation , which has a unique solution when for all eigenvalues of , including . Line L4 should use a Cholesky factorization, as is symmetric positive definite. The discrete-time problem is the least-norm solution of for the reachability matrix , solved exactly in rational arithmetic by .
The implementation computes both versions. Its tests compare the Gramian with the Lyapunov equation on 500 random systems, simulate the plant together with the optimal input (RK4, step ) and check that the state reaches within with the stated energy, check that piecewise constant inputs on finer grids cost more and tend to the optimum, and compare the discrete answer with the solution of the KKT system of the least-norm problem in exact arithmetic on 500 random problems.
Bounds
- Cost. In the real RAM, lines L2 to L4 cost . The exponential in line L1 by scaling and squaring costs operations to a fixed accuracy. Each evaluation of costs one more exponential. On a time grid it is cheaper to integrate the adjoint system from and set , at per step. The discrete version costs .
- Energy bounds. . The eigenvectors of for small eigenvalues are the hard directions.
- Short horizons. For the double integrator, the energy grows like for a change of position. In general, for a target that needs integrations of the input, the energy grows like as .
- Exactness. In continuous time the answer involves and is not rational in general. In discrete time it is rational for rational data and the formula is exact.
Reductions
- To least norm in a Hilbert space. The problem is the least-norm solution of the linear equation , from the space of square integrable inputs to . The answer is the projection of 0 on an affine subspace, , and . The discrete version is the same with .
- To LQR. As a limit of LQR problems with a terminal weight, see Variants. Conversely, the minimum-energy input is the open-loop input of an LQR problem with a terminal constraint.
- The reachable set. The states reachable from 0 at time with energy at most 1 form the ellipsoid . The dual statement for the observability Gramian gives the output energy of an initial state, and balanced truncation uses both ellipsoids to find the states that are hard to reach and hard to observe.
Applications
- Proof of reachability: the formula gives an explicit input for every target when is invertible, so it is the usual proof that the Gramian test or the rank test of controllability is sufficient.
- Open-loop transfers, such as moving a satellite or a flexible arm between two rest states, where the energy is a proxy for fuel or heating.
- The energy as a measure of how hard a system is to control, for example to compare actuator placements, or the nodes of a network that receive the input.
- Model reduction: the Gramian energy of a state is the input energy needed to reach it, which is how balanced truncation ranks states.
Proof: The Gramian formula gives the unique input of least energy, and Van Loan's block exponential gives the Gramianfull
Let , , and . The inputs are the square integrable functions , with the inner product and the energy . The solution of , at time is
So holds if and only if , with . The controllability Gramian is
Step 1: the adjoint and the Gramian
For let . Then for every input ,
so is the adjoint of . Also , by the substitution .
Step 2: the formula is optimal when W is invertible
Assume is invertible and put and , that is . By Step 1, , so reaches .
Let be any input with , and let . Then and . Hence
with equality only if , that is, almost everywhere. So is the unique input of least energy. Its energy is .
Step 3: when W is singular
is symmetric and positive semidefinite, since . If is singular, take with . The integrand is continuous and nonnegative, so for all , which means and for every input. So every reachable lies in the hyperplane , and a target with cannot be reached. This is why the code stops with an error when is not positive definite. ( is singular exactly when is not controllable, but this proof does not need that fact.)
Step 4: Van Loan's block exponential
Let and write ; the lower left block is 0 because is block upper triangular. From and , the blocks satisfy with , so ; with , so ; and
By variation of constants, . Multiply by :
So the code computes from one exponential of , as in line L1. It then makes the result exactly symmetric by averaging with its transpose, which changes nothing in exact arithmetic.
Theorem
Let and let be the Gramian. If is invertible, then the input steers to at time , every other input that does so has larger energy, and the least energy is . If is singular, some target cannot be reached. The lines L1 to L6 of the page compute exactly these quantities, in exact arithmetic.
Proof. Line L1 computes by Step 4. Line L2 stops when is singular, which is right by Step 3. Lines L3 and L4 compute and . Line L5 is the input and line L6 the energy , both optimal by Step 2.
The discrete-time version
For , the state after steps is with and stacked. The same argument with the Euclidean inner product on , and gives: if is invertible, the unique input of least is with , that is , and the least energy is . All quantities are rational for rational data, so the function minimum_energy_discrete computes them exactly.
Floating point
The continuous-time code is in floating point. The relative error of the Gramian is that of the exponential of , near when is not far from normal and has small norm. The solve with multiplies the error by about the condition number of , which is large when the target is hard to reach (a short horizon , or a direction that excites weakly). The code refuses when is not positive definite, with equal to times the largest entry of .
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()
minimum_energy_control.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-energy-control/. The authors are listed in prov/H8NC6E.jsonl.
"""Minimum-energy control of a linear system, in continuous and discrete time.
Continuous time: steer x' = A x + B u from x(0) = x0 to x(t1) = x1 with the
least energy, the integral of |u(t)|^2 over [0, t1]. The answer is
u(t) = B^T e^(A^T (t1 - t)) W^(-1) d, d = x1 - e^(A t1) x0,
with the controllability Gramian W = int_0^t1 e^(A s) B B^T e^(A^T s) ds,
and the least energy is d^T W^(-1) d. The Gramian comes from one matrix
exponential of size 2n (Van Loan's block method). Floating point.
Discrete time: steer x_(k+1) = A x_k + B u_k from x0 to x_N = x1 with the
least sum of |u_k|^2. The answer uses the N-step Gramian
W_N = sum_j A^j B B^T (A^T)^j. Exact with int and Fraction data.
"""
from fractions import Fraction
from typing import Callable, List, Sequence, Tuple, Union
import ctlmat as cm
Num = Union[int, float, Fraction]
Matrix = List[List[Num]]
def gramian(A: Sequence[Sequence[Num]], B: Sequence[Sequence[Num]], t1: float) -> List[List[float]]:
"""Return W(t1) = int_0^t1 e^(A s) B B^T e^(A^T s) ds.
Van Loan: the exponential of [[-A, B B^T], [0, A^T]] t1 is
[[., G], [0, F]] with F = e^(A^T t1) and G = e^(-A t1) W(t1), so
W(t1) = F^T G. Cost: one exponential of a 2n by 2n matrix, O(n^3 log(|A| t1)).
"""
n = len(A)
a = [[float(v) for v in row] for row in A]
b = [[float(v) for v in row] for row in B]
bbt = cm.mul(b, cm.transpose(b))
m = cm.block([[cm.scale(-1.0, a), bbt], [0, cm.transpose(a)]])
e = cm.expm(cm.scale(float(t1), m))
g = [row[n:] for row in e[:n]]
f = [row[n:] for row in e[n:]]
w = cm.mul(cm.transpose(f), g)
return [[(w[i][j] + w[j][i]) / 2 for j in range(n)] for i in range(n)]
def minimum_energy_control(
A: Sequence[Sequence[Num]],
B: Sequence[Sequence[Num]],
x0: Sequence[Num],
x1: Sequence[Num],
t1: float,
rel_tol: float = 1e-12,
) -> Tuple[Callable[[float], List[float]], float, List[float]]:
"""Return (u, energy, eta) for the transfer from x0 at time 0 to x1 at time t1.
u(t) is the optimal input as a list of m floats, energy is the least value
of int_0^t1 |u|^2 dt, and eta = W^(-1) d. Precondition: t1 > 0. Raises
ValueError if the Gramian is not positive definite within rel_tol times its
largest entry, that is, if (A, B) is not controllable in the precision used.
Cost: O(n^3 log(|A| t1)) once, then O(n^3 log(|A| t1)) per call of u.
"""
if not t1 > 0:
raise ValueError("t1 must be positive")
a = [[float(v) for v in row] for row in A]
b = [[float(v) for v in row] for row in B]
w = gramian(a, b, t1) # @line L1
big = max(abs(v) for row in w for v in row)
if big == 0.0 or not cm.is_pos_def(w, rel_tol * big): # @line L2
raise ValueError("the Gramian is singular: x1 cannot be reached from every x0")
phi = cm.expm(cm.scale(float(t1), a))
d = [float(v) - s for v, s in zip(x1, cm.matvec(phi, [float(v) for v in x0]))] # @line L3
eta = cm.solve(w, d) # @line L4
bt, at = cm.transpose(b), cm.transpose(a)
def u(t: float) -> List[float]:
return cm.matvec(bt, cm.matvec(cm.expm(cm.scale(t1 - t, at)), eta)) # @line L5
energy = cm.dot(d, eta) # @line L6
return u, energy, eta
def reach_matrix(A: Sequence[Sequence[Num]], B: Sequence[Sequence[Num]], N: int) -> Matrix:
"""Return [A^(N-1) B, A^(N-2) B, ..., B], so that x_N = A^N x0 + C u for u = (u_0, ..., u_(N-1))."""
blocks = []
p = [list(row) for row in B]
for _ in range(N):
blocks.append(p)
p = cm.mul(A, p)
blocks.reverse()
return [sum((blk[i] for blk in blocks), []) for i in range(len(A))]
def minimum_energy_discrete(
A: Sequence[Sequence[Num]],
B: Sequence[Sequence[Num]],
x0: Sequence[Num],
x1: Sequence[Num],
N: int,
) -> Tuple[List[List[Num]], Num]:
"""Return (us, energy): the inputs u_0, ..., u_(N-1) of least sum |u_k|^2 with x_N = x1.
us[k] = B^T (A^T)^(N-1-k) W_N^(-1) d with d = x1 - A^N x0 and
W_N = C C^T for C = reach_matrix(A, B, N); energy = d^T W_N^(-1) d.
Exact (Fraction) with int and Fraction data. Raises ValueError if W_N is
singular. Cost: O(N n^2 m + n^3).
"""
if N < 1:
raise ValueError("N must be at least 1")
c = reach_matrix(A, B, N)
w = cm.mul(c, cm.transpose(c))
d = [v - s for v, s in zip(x1, cm.matvec(cm.mat_power(A, N), list(x0)))]
eta = cm.solve(w, d)
flat = cm.matvec(cm.transpose(c), eta)
m = len(B[0])
us = [flat[k * m:(k + 1) * m] for k in range(N)]
return us, cm.dot(d, eta)
test_minimum_energy_control.py 184 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/minimum-energy-control/. The authors are listed in prov/H8NC6E.jsonl.
import math
import random
from fractions import Fraction
import pytest
import ctlmat as cm
import ctlsim
from minimum_energy_control import gramian, minimum_energy_control, minimum_energy_discrete, reach_matrix
def maxabs(a):
return max(abs(v) for row in a for v in row)
def rand_mat(rng, n, m, lo=-1.5, hi=1.5):
return [[rng.uniform(lo, hi) for _ in range(m)] for _ in range(n)]
def simulate_optimal(A, B, x0, eta, t1, dt):
"""RK4 on x' = A x + B B^T z, z' = -A^T z, e' = |B^T z|^2, so u = B^T z."""
n, m = len(A), len(B[0])
at = cm.transpose(A)
z0 = cm.matvec(cm.expm(cm.scale(t1, at)), eta)
def f(t, s, u):
x, z = s[:n], s[n:2 * n]
v = [sum(B[i][j] * z[i] for i in range(n)) for j in range(m)]
dx = [sum(A[i][k] * x[k] for k in range(n)) + sum(B[i][j] * v[j] for j in range(m)) for i in range(n)]
dz = [-sum(at[i][k] * z[k] for k in range(n)) for i in range(n)]
return dx + dz + [sum(vj * vj for vj in v)]
steps = round(t1 / dt)
assert abs(steps * dt - t1) <= 1e-12 * t1
_, xs, _ = ctlsim.simulate(f, list(x0) + z0 + [0.0], 0.0, t1, dt)
return xs[-1][:n], xs[-1][-1]
def lyapunov_gramian(A, B, t1):
"""Independent oracle: A W + W A^T + B B^T - e^(A t1) B B^T e^(A^T t1) = 0, by Kronecker form."""
n = len(A)
phi = cm.expm(cm.scale(t1, A))
bbt = cm.mul(B, cm.transpose(B))
rhs = cm.sub(cm.mul(phi, cm.mul(bbt, cm.transpose(phi))), bbt)
op = cm.add(cm.kron(cm.eye(n), A), cm.kron(A, cm.eye(n)))
return cm.unvec(cm.solve(op, cm.vec(rhs)), n, n)
def test_double_integrator():
A, B = [[0, 1], [0, 0]], [[0], [1]]
W = gramian(A, B, 1.0)
want = [[1 / 3, 1 / 2], [1 / 2, 1.0]]
assert maxabs(cm.sub(W, want)) <= 1e-14
u, energy, eta = minimum_energy_control(A, B, [0, 0], [1, 0], 1.0)
assert abs(energy - 12.0) <= 1e-12
assert abs(eta[0] - 12.0) <= 1e-11 and abs(eta[1] + 6.0) <= 1e-11
for t in [0.0, 0.25, 0.5, 0.75, 1.0]:
assert abs(u(t)[0] - (6.0 - 12.0 * t)) <= 1e-11
def test_scalar_closed_form():
for a in [-1.0, 0.5, 2.0]:
for t1 in [0.3, 1.0, 2.0]:
W = gramian([[a]], [[1.0]], t1)[0][0]
want = (math.exp(2 * a * t1) - 1) / (2 * a)
assert abs(W - want) <= 1e-13 * want
_, energy, _ = minimum_energy_control([[a]], [[1.0]], [0.0], [1.0], t1)
assert abs(energy - 1 / want) <= 1e-12 / want
W = gramian([[-1.0]], [[1.0]], 1.0)[0][0]
assert abs(W - (1 - math.exp(-2.0)) / 2) <= 1e-15
def test_gramian_against_lyapunov_oracle():
rng = random.Random(11)
count = 0
while count < 500:
n, m = rng.randint(1, 3), rng.randint(1, 2)
A, B = rand_mat(rng, n, n), rand_mat(rng, n, m)
sums = [r1 + r2 for r1 in cm.polyroots(cm.charpoly(A)) for r2 in cm.polyroots(cm.charpoly(A))]
if min(abs(s) for s in sums) < 0.05:
continue
t1 = rng.uniform(0.2, 1.5)
W = gramian(A, B, t1)
ref = lyapunov_gramian(A, B, t1)
assert maxabs(cm.sub(W, ref)) <= 1e-9 * (1 + maxabs(ref))
assert cm.is_symmetric(W, 0)
count += 1
def test_simulation_reaches_target_with_stated_energy():
rng = random.Random(5)
done = 0
while done < 60:
n, m = rng.randint(1, 3), rng.randint(1, 2)
A, B = rand_mat(rng, n, n), rand_mat(rng, n, m)
W = gramian(A, B, 1.0)
if min(cm._sym_eigvals(W)) < 1e-3:
continue
x0 = [rng.uniform(-1, 1) for _ in range(n)]
x1 = [rng.uniform(-1, 1) for _ in range(n)]
u, energy, eta = minimum_energy_control(A, B, x0, x1, 1.0)
# RK4 with dt = 0.01 over [0, 1]; the global error is O(dt^4).
xT, eT = simulate_optimal(A, B, x0, eta, 1.0, 0.01)
scale = 1 + max(abs(v) for v in eta)
assert max(abs(p - q) for p, q in zip(xT, x1)) <= 1e-6 * scale
assert abs(eT - energy) <= 1e-6 * (1 + energy)
z = u(0.5)
assert len(z) == m
done += 1
def test_zoh_inputs_cost_more():
"""Least-norm piecewise constant inputs reach x1 too, with energy at least the optimum, tending to it."""
A, B = [[0.0, 1.0], [-2.0, -0.3]], [[0.0], [1.0]]
x0, x1, t1 = [1.0, 0.0], [0.0, 0.5], 2.0
_, best, _ = minimum_energy_control(A, B, x0, x1, t1)
prev = None
for N in [5, 10, 20, 40]:
h = t1 / N
aug = cm.block([[A, B], [cm.zeros(1, 2), cm.zeros(1, 1)]])
e = cm.expm(cm.scale(h, aug))
Ad = [row[:2] for row in e[:2]]
Bd = [row[2:] for row in e[:2]]
us, en = minimum_energy_discrete(Ad, Bd, x0, x1, N)
zoh = h * en
assert zoh >= best * (1 - 1e-12)
if prev is not None:
assert zoh <= prev + 1e-12
prev = zoh
assert prev - best <= 0.01 * best
def kkt_oracle(C, d):
"""Least-norm solution of C u = d from the KKT system [[I, C^T], [C, 0]] [u; lam] = [0; d]."""
n, k = len(C), len(C[0])
K = cm.block([[cm.eye(k), cm.transpose(C)], [C, cm.zeros(n, n)]])
sol = cm.solve(K, [0] * k + list(d))
return sol[:k]
def test_discrete_exact_against_kkt():
rng = random.Random(23)
count = 0
while count < 500:
n, m, N = rng.randint(1, 3), rng.randint(1, 2), rng.randint(1, 4)
A = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(n)]
B = [[rng.randint(-2, 2) for _ in range(m)] for _ in range(n)]
C = reach_matrix(A, B, N)
if cm.det(cm.mul(C, cm.transpose(C))) == 0:
with pytest.raises(ValueError):
minimum_energy_discrete(A, B, [0] * n, [1] * n, N)
continue
x0 = [Fraction(rng.randint(-3, 3)) for _ in range(n)]
x1 = [Fraction(rng.randint(-3, 3)) for _ in range(n)]
us, energy = minimum_energy_discrete(A, B, x0, x1, N)
x = list(x0)
for uk in us:
x = [p + q for p, q in zip(cm.matvec(A, x), cm.matvec(B, uk))]
assert x == x1
flat = [v for uk in us for v in uk]
d = [p - q for p, q in zip(x1, cm.matvec(cm.mat_power(A, N), x0))]
assert flat == kkt_oracle(C, d)
assert energy == sum(v * v for v in flat)
count += 1
def test_discrete_scalar_example():
us, energy = minimum_energy_discrete([[2]], [[1]], [0], [21], 3)
assert us == [[Fraction(4)], [Fraction(2)], [Fraction(1)]]
assert energy == 21
def test_uncontrollable_and_bad_input():
with pytest.raises(ValueError):
minimum_energy_control([[1.0, 0.0], [0.0, 1.0]], [[1.0], [1.0]], [0.0, 0.0], [1.0, 0.0], 1.0)
with pytest.raises(ValueError):
minimum_energy_control([[0.0]], [[1.0]], [0.0], [1.0], 0.0)
with pytest.raises(ValueError):
minimum_energy_control([[0.0]], [[0.0]], [0.0], [1.0], 1.0)
with pytest.raises(ValueError):
minimum_energy_discrete([[1]], [[1]], [0], [1], 0)
References
- Roger W. Brockett, Finite Dimensional Linear Systems, Wiley, 1970 (SIAM Classics in Applied Mathematics 74, 2015), the treatment of controllability and of inputs of least norm
- Charles F. Van Loan, Computing integrals involving the matrix exponential, IEEE Transactions on Automatic Control 23(3), 395-404, 1978, integrals such as the Gramian computed from the exponential of one block triangular matrix
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 | H2 full proof |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag H8NC6E Edit this page History Report an error Markdown