Algorithmcore
Deadbeat control
Also called deadbeat controller.
A discrete-time state feedback that places all closed-loop poles at the origin, so the state reaches zero in at most n steps.
- Solves
- Pole placement problem
- Time
- O(N n^2 (n + m)) worst
- Space
- O(n (n + m)) extra
- Where
- N = the number of steps to reach zero; m = the number of inputs; n = the number of states
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- John O'Reilly, 1981
Deadbeat control is a state feedback for a discrete-time system that makes nilpotent: for some . All closed-loop eigenvalues are then at , and every initial state reaches the origin exactly after steps and stays there. The algorithm on this page finds a gain with the least possible , for any number of inputs. With one input, it is Ackermann's formula with the polynomial . Deadbeat control has no continuous-time counterpart: no finite gain brings a continuous linear system to rest in finite time. The price is large inputs, especially for short sampling periods.
In plain words
A computer controls a machine at fixed clock ticks. A deadbeat controller is a rule that brings the machine exactly to rest after a fixed number of ticks, from any starting point. It is not a slow approach that gets closer and closer: after the last tick, the error is zero. The method builds the rule backwards. First it finds the states that can be stopped in one tick, then those that can be moved into that set in one tick, and so on, until every state is covered. Then it picks, for each kind of state, the push that moves it one set closer to rest. The pushes can be very large, and the motion between ticks is not controlled.
The problem
Input: and for the system . Output: and the least with .
A deadbeat gain exists if and only if every uncontrollable eigenvalue of is ; this holds in particular when is controllable. By the pole placement theorem, the eigenvalues of the uncontrollable part do not move under feedback, so they must already be 0. With one input and controllable, and is unique. With several inputs, is not unique and can be smaller than .
The least is the same for feedback and for open-loop input sequences: it is the least such that every state can be brought to 0 in steps by some inputs, that is, the least with . If is invertible, this is the controllability index, the least with .
The algorithm
DEADBEAT(A, B)- 1
V ← [] (basis of S_0 = {0}); C ← []; N ← 0; while |V| < n: N ← N + 1 - 2
S_N ← {x : A x = V a + B c for some a, c} ▷ null space of [A, -V, -B] - 3
for each vector x of S_N that is independent of V: append x to V, its c to C - 4
if no vector was appended: fail ▷ an uncontrollable eigenvalue is not 0 - 5
return K = C V^(-1), N ▷ K v_i = c_i for every basis vector
The subspace is the set of states that some input sequence brings to 0 in steps: exactly when one input moves to . Line L2 computes as the projection of a null space, and the null vector also gives the input . Line L3 extends the basis, so the basis vectors are ordered by the first that contains them. Line L5 defines by its values on this basis: for a basis vector of , lies in . So maps into , and steps map to .
Example
Double integrator, sampled. The zero-order hold model of a unit mass with period is , . The algorithm gives and
From , the inputs are and , and , . With the inputs are and the peak velocity is 10, for a move of length 1. Halving makes the inputs four times larger. This is the price of deadbeat control.
Two inputs, fewer steps. For
, so the controllability index is 2. The algorithm returns and , with , whose square is 0. Any single input of this system needs three steps.
Singular . For and , the third state is not controllable, but its eigenvalue is 0, and maps it to 0 in one step. The algorithm returns and : the open loop is already deadbeat.
Correctness
The full proof is in proofs/correctness.md. Its steps:
- The subspaces grow. , by induction on . If for some , then for all , so the loop ends after at most rounds, by success or by line L4.
- Meaning of . is exactly the set of states that some input sequence brings to 0 in steps.
- Nilpotency. For the gain of line L5, , so .
- Minimality. If for some gain , then the feedback inputs bring every state to 0 in steps, so and .
- Failure. If the loop stops with , no input sequence brings every state to 0, so no gain is deadbeat. This happens exactly when an uncontrollable eigenvalue is not 0.
Proof: The subspace recursion gives a deadbeat gain with the least number of steps, or proves that none existsfull
Let and , and write . Define and
Each is a subspace, because it is the preimage under of the subspace . Line L2 computes : a null vector of satisfies , where the columns of span , and the -parts of the null vectors span , because the projection of the null space onto the first coordinates is linear and onto .
Lemma 1: the subspaces grow, and stop growing for good
for all . If for some , then for all .
Proof. . If , then for we have , so . For the second claim, is defined from by the same rule as from , so gives , and so on.
So the dimensions increase strictly until they stop, and the loop of line L1 runs at most rounds.
Lemma 2: meaning of the subspaces
if and only if there are inputs that bring to .
Proof. By induction on . For both sides say . For : if , write with , and take ; then , which the induction hypothesis brings to 0 in more steps. Conversely, if inputs bring to 0 in steps, then is brought to 0 in steps, so and .
Lemma 3: the gain is deadbeat
Suppose the loop ends with . Then the gain of line L5 satisfies for , and .
Proof. Line L3 adds each new basis vector in the first round with , together with the of its null vector, so with . Because the vectors added before round span (Lemma 1 and the fact that line L3 adds a maximal independent set of new vectors), the vectors added up to round span . They are independent by construction, and after round they form a basis of , so is invertible and is the unique matrix with . For added in round , . Every vector of is a combination of basis vectors added in rounds up to , each of which is mapped into for its round . So . Applying this times gives .
Lemma 4: no gain needs fewer steps
If for some , then .
Proof. The feedback inputs bring every state to . By Lemma 2, every state lies in , so . Since is the first index with and the subspaces grow, .
The same argument with open-loop inputs shows that no input sequence brings every state to 0 in fewer than steps.
Lemma 5: when the loop fails
If line L4 fails, no deadbeat gain exists, and this happens if and only if has an uncontrollable eigenvalue other than 0.
Proof. Line L4 fails when round adds no vector, that is, . By Lemma 1, for all , so by Lemma 2 some state cannot be brought to 0 in any number of steps, and by the proof of Lemma 4 no gain is deadbeat.
For the second statement, use the Kalman decomposition: in suitable coordinates and with controllable, and the uncontrollable eigenvalues are the eigenvalues of . For every , is block upper triangular with the diagonal blocks and . If a deadbeat gain exists, is nilpotent, so all its eigenvalues are 0, and so are those of . Conversely, if all eigenvalues of are 0, then is nilpotent. By the pole placement theorem there is a that makes all eigenvalues of equal to 0, so this block is nilpotent too. With , a block upper triangular matrix with nilpotent diagonal blocks is nilpotent, because its -th power has the -th powers of the diagonal blocks on its diagonal and is again block upper triangular. Then a deadbeat gain exists, and the loop does not fail.
Theorem
For every and , the algorithm either returns and with and the least such number over all gains and all input sequences, or it raises an error, and it raises an error exactly when no deadbeat gain exists.
Proof. Lemmas 1, 3, 4 and 5.
Remarks
- One input. If and is controllable, a matrix is nilpotent exactly when its characteristic polynomial is , and the Ackermann formula page proves that exactly one gain gives this polynomial. So the algorithm returns the Ackermann gain for . In the coordinates of the controllable canonical form, is the companion matrix of , a single nilpotent Jordan block of size , so . The tests check that the two gains agree.
- Invertible . By Lemma 2 and induction, when is invertible, so , and is the controllability index.
- Exactness. With integer or rational data the implementation uses exact fractions, so the rank decisions are exact and holds exactly, as the tests check.
Complexity
In the real RAM, with exact arithmetic: each round of the loop computes the null space of a matrix with rows and at most columns, by elimination in operations, and tests at most vectors for independence. With the independence tests done incrementally against an echelon form of , each costs , so a round costs , and there are rounds. Line L5 is one solve with right sides, . The total is and the extra space is . The code on this page recomputes each rank from scratch, which is simpler and slower by a factor of . With rational data the entries can grow; the implementation uses exact fractions, and the bit cost is polynomial but larger.
In floating point, the rank decisions in lines L2 to L4 need a tolerance, and a system close to an uncontrollable one gives a gain that is very large or wrong. For one input, the Ackermann formula with has the same numerical weakness.
Properties
- Exact zero, not decay. After steps the state is 0, not small. In the -domain, all closed-loop poles are at , and the closed-loop response to any initial state is a polynomial in of degree below , a finite impulse response.
- Minimum time. No feedback and no open-loop input sequence reaches the origin from every state in fewer than steps.
- Size of the inputs. The gain grows as shrinks. In the double integrator, grows like . With bounded inputs, the deadbeat law works only for small enough states; a time-optimal controller with bounds needs more steps.
- Not unique with several inputs. For the algorithm returns one of many deadbeat gains. The choice of basis in line L3 decides which one. The Jordan structure of can also differ between gains with the same .
- Observers. Applied to , the algorithm gives a deadbeat observer gain : the estimation error of a Luenberger observer is then exactly 0 after steps.
Variants and improvements
- Single input. Use Ackermann's formula with : .
- Deadbeat tracking. Add a feedforward term so that the output follows a step reference after a finite number of steps; with integral action as in state feedback with integral action, the augmented system is made deadbeat.
- Bounded inputs. If the inputs must stay within bounds, the minimum time problem becomes a linear program for each initial state, or a model predictive control problem. The deadbeat gain is its unbounded limit.
- Ripple-free deadbeat. A deadbeat design on the sampled model can leave oscillations between samples, for example when it cancels a sampling zero near . Ripple-free designs constrain the controller so that the continuous output also settles; see sampled-data system.
- Robust alternatives. Placing all poles at a small positive radius instead of 0 gives a smooth decay like , much smaller inputs, and less sensitivity. The design is then ordinary pole placement.
When to use it
Use deadbeat control when the samples must settle in the least number of steps and the inputs can be large: for slow sampling relative to the plant, in digital servo loops with a strong actuator, or as the observer in a system where the state must be known exactly after samples. It is also a clean test case for discrete-time designs, because the result can be checked exactly. Avoid it when the sampling is fast relative to the plant dynamics, when the actuator saturates, or when the model is uncertain: the gain is large and the poles at 0 are very sensitive.
Pitfalls
- Large gains for short periods. The inputs grow like for the double integrator, and faster for higher order systems. Check the input sequence for the largest expected initial state.
- Sensitive poles. A nilpotent matrix with one Jordan block of size has eigenvalues that move like under a change of its entries. A small model error therefore moves the poles far from 0, and the finite settling is lost.
- Intersample ripple. The design controls only the samples. Simulate the continuous plant with the held input, as the zero-order hold page shows.
- Not continuous-time. For with , the state is , which is never 0 for . Finite time settling in continuous time needs nonlinear or time-varying control.
- Uncontrollable modes. The algorithm fails when an uncontrollable eigenvalue is not 0. A stable uncontrollable mode still decays, but not in finite time; then use ordinary pole placement for the controllable part.
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()
deadbeat_control.py 130 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deadbeat-control/. The authors are listed in prov/HZQ8MT.jsonl.
"""Deadbeat state feedback for x_(k+1) = A x_k + B u_k, with u_k = -K x_k.
The gain makes A - B K nilpotent, (A - B K)^N = 0, with the least possible N,
so every initial state reaches 0 in at most N steps. It works with any
number of inputs.
Method: the subspaces S_0 = {0} and S_j = {x : A x in S_(j-1) + range B}
are the states that some input sequence brings to 0 in j steps. They grow
until S_N = R^n. Choose a basis of R^n that runs through S_1, S_2, ...,
and for each basis vector v of S_j solve A v = s + B c with s in S_(j-1).
Setting K v = c gives (A - B K) v = s, so A - B K maps S_j into S_(j-1).
All arithmetic is exact (Fraction) for int and Fraction data. With float
data the rank decisions use a tolerance and the result is approximate.
"""
from fractions import Fraction
from ctlmat import mul, solve, transpose
__all__ = ["rref", "nullspace", "deadbeat_gain", "steps_to_zero"]
def _exact(M):
return all(isinstance(v, (int, Fraction)) for row in M for v in row)
def rref(M, tol=1e-10):
"""Return (R, pivots): the reduced row echelon form of M and its pivot columns."""
exact = _exact(M)
R = [[Fraction(v) for v in row] for row in M] if exact else [[float(v) for v in row] for row in M]
rows = len(R)
cols = len(R[0]) if R else 0
scale = 1.0 if exact else max([abs(v) for row in R for v in row] + [1.0])
pivots = []
r = 0
for c in range(cols):
if r == rows:
break
p = max(range(r, rows), key=lambda i: abs(R[i][c]))
if (R[p][c] == 0) if exact else (abs(R[p][c]) <= tol * scale):
continue
R[r], R[p] = R[p], R[r]
piv = R[r][c]
R[r] = [v / piv for v in R[r]]
for i in range(rows):
if i != r and R[i][c] != 0:
f = R[i][c]
R[i] = [a - f * b for a, b in zip(R[i], R[r])]
pivots.append(c)
r += 1
return R, pivots
def nullspace(M, tol=1e-10):
"""Return a basis (list of flat vectors) of the null space of M."""
cols = len(M[0])
R, pivots = rref(M, tol)
free = [c for c in range(cols) if c not in pivots]
basis = []
one = Fraction(1) if _exact(M) else 1.0
for f in free:
v = [0 * one] * cols
v[f] = one
for i, p in enumerate(pivots):
v[p] = -R[i][f]
basis.append(v)
return basis
def _rank(vectors, tol=1e-10):
"""Return the rank of a list of flat vectors."""
if not vectors:
return 0
return len(rref(vectors, tol)[1])
def deadbeat_gain(A, B, tol=1e-10):
"""Return (K, N): a gain with (A - B K)^N = 0 and the least such N.
A is n by n, B is n by m (lists of rows). Raises ValueError if no
feedback makes A - B K nilpotent, that is, if some state cannot be
brought to 0 in finite time (an uncontrollable eigenvalue is not 0).
"""
n = len(A)
m = len(B[0])
V = [] # basis of S_(j-1), flat vectors
C = [] # C[i] = c with A V[i] - B c in the previous subspace
N = 0
while len(V) < n: # @line L1
N += 1
# Rows of [A, -V, -B]; a null vector (x, a, c) gives A x = V a + B c.
big = [list(A[i]) + [-v[i] for v in V] + [-B[i][j] for j in range(m)] for i in range(n)]
found = False
offset = n + len(V)
for z in nullspace(big, tol): # @line L2
x = z[:n]
c = z[offset:]
if _rank(V + [x], tol) > len(V): # @line L3
V.append(x)
C.append(c)
found = True
if not found: # @line L4
raise ValueError("A - B K cannot be made nilpotent: an uncontrollable eigenvalue is not 0")
# K V = C, so K = C V^(-1); solve V^T K^T = C^T.
Vm = transpose(V)
Cm = transpose(C)
K = transpose(solve(transpose(Vm), transpose(Cm))) # @line L5
return K, N
def steps_to_zero(A, B):
"""Return the least j with range A^j inside range [B, A B, ..., A^(j-1) B].
This is the least number of steps in which every state can be brought
to 0 by some input sequence. Brute force, exact for exact data. Raises
ValueError if there is no such j at most n.
"""
n = len(A)
R = [] # the columns of [B, A B, ..., A^(j-1) B]
P = [[1 if i == j else 0 for j in range(n)] for i in range(n)] # A^j
for j in range(0, n + 1):
if _rank(R + transpose(P)) == _rank(R):
return j
R = R + transpose(mul(P, B))
P = mul(A, P)
raise ValueError("some state cannot be brought to 0 in n steps")
test_deadbeat_control.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/deadbeat-control/. The authors are listed in prov/HZQ8MT.jsonl.
import random
from fractions import Fraction
import pytest
import ctlmat as cm
from deadbeat_control import deadbeat_gain, nullspace, rref, steps_to_zero
def closed_loop(A, B, K):
return cm.sub(A, cm.mul(B, K))
def nil_index(M):
"""Return the least N with M^N = 0 (exact), or None if M is not nilpotent."""
n = len(M)
P = cm.eye(n)
for N in range(0, n + 1):
if P == cm.zeros(n):
return N
P = cm.mul(M, P)
return None
def ackermann_deadbeat(A, b):
"""Single-input deadbeat gain by Ackermann's formula with p(z) = z^n."""
n = len(A)
cols = [list(b)]
for _ in range(n - 1):
cols.append(cm.matvec(A, cols[-1]))
q = cm.solve(cm.transpose(cm.transpose(cols)), [0] * (n - 1) + [1])
return cm.mul([q], cm.mat_power(A, n))[0]
def run(A, B, K, x0, steps):
x = list(x0)
xs, us = [x], []
for _ in range(steps):
u = [-v for v in cm.matvec(K, x)]
x = [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]
xs.append(x)
us.append(u)
return xs, us
def test_zoh_double_integrator():
for h in (Fraction(1, 10), Fraction(1, 4), Fraction(2)):
A = [[1, h], [0, 1]]
B = [[h * h / 2], [h]]
K, N = deadbeat_gain(A, B)
assert N == 2
assert K == [[1 / h ** 2, Fraction(3, 2) / h]]
xs, us = run(A, B, K, [1, 0], 2)
assert xs[2] == [0, 0]
assert us == [[-1 / h ** 2], [1 / h ** 2]]
def test_single_input_matches_ackermann():
rng = random.Random(3)
done = 0
while done < 12:
n = rng.randint(1, 5)
A = [[rng.randint(-3, 3) for _ in range(n)] for _ in range(n)]
b = [rng.randint(-2, 2) for _ in range(n)]
W = cm.transpose([cm.matvec(cm.mat_power(A, k), b) for k in range(n)])
if cm.det(W) == 0:
continue
K, N = deadbeat_gain(A, [[v] for v in b])
assert N == n
assert K[0] == ackermann_deadbeat(A, b)
done += 1
def test_multi_input_minimum_time():
rng = random.Random(4)
for trial in range(25):
n = rng.randint(2, 6)
m = rng.randint(1, 3)
A = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(n)]
B = [[rng.randint(-1, 1) for _ in range(m)] for _ in range(n)]
try:
want = steps_to_zero(A, B)
except ValueError:
with pytest.raises(ValueError):
deadbeat_gain(A, B)
continue
K, N = deadbeat_gain(A, B)
assert N == want
assert nil_index(closed_loop(A, B, K)) == N
x0 = [rng.randint(-5, 5) for _ in range(n)]
xs, _ = run(A, B, K, x0, N)
assert xs[N] == [0] * n
def test_stated_three_state_example():
A = [[1, 1, 0], [0, 1, 1], [0, 0, 1]]
B = [[0, 0], [1, 0], [0, 1]]
K, N = deadbeat_gain(A, B)
assert N == 2
Acl = closed_loop(A, B, K)
assert cm.mat_power(Acl, 2) == cm.zeros(3)
assert Acl != cm.zeros(3)
def test_singular_A_uncontrollable_zero_mode_is_fine():
# The third state is not reachable but decays to 0 in one step by itself.
A = [[0, 1, 0], [0, 0, 0], [0, 0, 0]]
B = [[0], [1], [0]]
K, N = deadbeat_gain(A, B)
assert N == 2
assert nil_index(closed_loop(A, B, K)) == 2
def test_unstable_uncontrollable_mode_rejected():
A = [[1, 0], [0, 2]]
B = [[1], [0]]
with pytest.raises(ValueError):
deadbeat_gain(A, B)
with pytest.raises(ValueError):
steps_to_zero(A, B)
def test_rref_and_nullspace():
M = [[1, 2, 3], [2, 4, 6], [1, 0, 1]]
R, piv = rref(M)
assert piv == [0, 1]
for v in nullspace(M):
assert cm.matvec(M, v) == [0, 0, 0]
assert len(nullspace(M)) == 1
def test_float_data():
h = 0.1
A = [[1.0, h], [0.0, 1.0]]
B = [[h * h / 2], [h]]
K, N = deadbeat_gain(A, B)
assert N == 2
assert abs(K[0][0] - 100.0) < 1e-9 and abs(K[0][1] - 15.0) < 1e-9
History
Designs with a finite settling time for sampled systems appeared in the early transfer-function theory of sampled-data control, under the name deadbeat response. The state-space form, with the minimum number of steps given by the controllability structure of , came with the state-space theory of the 1960s. O'Reilly (1981) surveyed the discrete time-optimal control problem and its deadbeat solutions. For one input, Ackermann's formula of 1972 gives the deadbeat gain directly.
References
- John O'Reilly, The discrete linear time invariant time-optimal control problem, an overview, Automatica 17(2), 363-370, 1981, the survey of the minimum-time problem for discrete linear systems and its deadbeat solutions
- Karl J. Åström and Björn Wittenmark, Computer-Controlled Systems, Theory and Design, third edition, Prentice Hall, 1997 (Dover reprint, 2011), Chapter 4, on pole placement by state feedback in discrete time and on the deadbeat case
- Jürgen Ackermann, Der Entwurf linearer Regelungssysteme im Zustandsraum, Regelungstechnik 20(7), 297-300, 1972, the single-input gain formula, which gives the deadbeat gain for p(z) = z^n
- Chi-Tsong Chen, Linear System Theory and Design, third edition, Oxford University Press, 1999, Section 8.2, State Feedback, and Section 8.6, State Feedback, Multivariable Case
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 HZQ8MT Edit this page History Report an error Markdown