Algorithmcore
Ackermann's formula
Also called Ackermann pole placement formula.
Gives the single-input pole placement gain as K = [0 ... 0 1] W^(-1) p(A), from the controllability matrix W and the desired polynomial p.
- Solves
- Pole placement problem
- Time
- O(n^3) worst
- Space
- O(n^2) extra
- Where
- n = the number of states
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jürgen Ackermann, 1972
Ackermann's formula computes the state feedback gain that gives a single-input system the closed-loop characteristic polynomial , with :
The formula needs no change of coordinates, and it is the same in discrete time. It is one method for the pole placement problem. The pole placement theorem says when a solution exists, and the formula is the constructive part of its single-input proof. With one input, is unique, so all exact methods give the same ; they differ only in rounding error. With more than one input, is not unique, and robust pole placement uses the extra freedom to make the closed loop well conditioned. The formula is exact in exact arithmetic, but it is numerically unstable for larger .
In plain words
A machine has one control knob. Its state is a list of numbers, and the knob is set to a weighted sum of these numbers. The choice of weights decides how the machine settles: fast or slow, with or without oscillation. The designer writes down the wanted settling behaviour as a polynomial. Ackermann's formula turns that polynomial into the weights in one step. It uses only the model of the machine and a table of how the knob moves the state over successive steps. If some part of the state cannot be moved by the knob, the table is singular and no set of weights exists. The formula is short and easy to check by hand. On a computer it loses accuracy fast when the state has many numbers.
The problem
Input: , and a monic polynomial with real coefficients. Output: the row vector with . A solution exists for every if and only if is controllable, that is, is invertible (the Kalman rank condition). The solution is then unique. If the wanted poles are , then , and the complex poles must come in conjugate pairs for to be real.
The same formula serves the discrete system and the observer gain: for with one output, apply it to and set ; see Luenberger observer.
The algorithm
ACKERMANN(A, b, p) ▷ p = [1, p_1, ..., p_n]- 1
W ← [b, A b, ..., A^(n-1) b] ▷ n matrix-vector products - 2
solve W^T q = e_n; if W is singular, fail ▷ q^T = last row of W^(-1) - 3
K ← 0 (a row vector); for each coefficient c of p, highest power first: - 4
K ← K A + c q^T ▷ Horner's rule on row vectors - 5
return K ▷ K = q^T p(A)
Line L1 builds the controllability matrix one column at a time. Line L2 gets the last row of by one linear solve; a singular means that is not controllable. Lines L3 and L4 compute by Horner's rule, so the code multiplies row vectors by and never forms .
Example
Double integrator. Take , and the poles , so . Line L1 gives , and line L2 gives . Then
Check: has the characteristic polynomial .
A companion matrix. For , and the poles , the formula gives . Here is already in controllable canonical form, and is the difference of the coefficient vectors: and , so .
Deadbeat in discrete time. The zero-order hold model of the double integrator with period is , . With , line L2 gives , and . Then , so every initial state reaches 0 in two samples. See deadbeat control.
Loss of accuracy. Take , the vector of ones, and the poles , all well separated. The code was run in double precision, and the characteristic polynomial of the computed was then evaluated exactly. The largest relative error of its coefficients, and the 2-norm condition number of , were:
| relative coefficient error | ||
|---|---|---|
| 4 | ||
| 6 | ||
| 8 | ||
| 10 | ||
| 12 |
The error grows roughly like times the unit roundoff. At the placed polynomial is wrong in the second digit.
Correctness
The full proof is in proofs/correctness.md. In short: write . Expanding gives . Summing with the coefficients of gives , where is an matrix whose last row is . If is the characteristic polynomial of , the Cayley-Hamilton theorem gives , so , and the last row of is . This proves uniqueness. Existence follows from the controllable canonical form, where the gain that gives is obvious; by uniqueness it equals the formula.
Proof: Ackermann's formula gives the only single-input gain with the wanted characteristic polynomialfull
Let , , and with . Write , for a row vector , and for the last unit vector. The claim is: if is invertible, then is the only row vector with , and lines L1 to L5 compute it.
Lemma 1: expansion of the powers
For every row vector and every ,
Proof. For the sum is empty and both sides are . If the identity holds for , then
Shift the index in the sum. The last term is the term of the new sum, so .
Lemma 2: the polynomial of the closed loop
, where is the matrix with rows
and the last row is .
Proof. By Lemma 1, . Exchange the two sums: runs from 0 to , and for fixed , runs from to . This gives , because is column of and is row of . For only occurs, with and , so .
Lemma 3: uniqueness
If is invertible and , then .
Proof. By the Cayley-Hamilton theorem, a matrix satisfies its characteristic polynomial, so . Lemma 2 gives , so . The last row of is (Lemma 2), and the last row of is .
Lemma 4: existence
If is invertible, some row vector gives .
Proof. Let , so , that is, for and . Let be the matrix with rows .
is invertible. The entry of is . It is 0 if and 1 if . So has ones on the antidiagonal and zeros above it, its determinant is , and is invertible.
The new coordinates. Entry of is , which is 1 for and 0 otherwise, so . Row of is , which is row of for . Let . By the Cayley-Hamilton theorem, . So , where has rows and the last row .
The gain. Let . Then has rows and the last row . Call this companion matrix . Expand along the first column. The entry in position has the minor with . The entry in position has a minor that is lower triangular with on the diagonal, so its cofactor is . So by induction on , with the base case . Finally set . Then , and similar matrices have the same characteristic polynomial.
Theorem
If is invertible, the output of lines L1 to L5 is the only row vector with .
Proof. By Lemma 4 a solution exists, and by Lemma 3 every solution equals , so this vector is the unique solution. It remains to see that the lines compute it.
Line L1 builds column by column, since column is times column . Line L2 solves , so and . In lines L3 and L4, the loop invariant is: after the coefficients have been used, . This holds after the first step, where . If it holds after step , the update gives . After step , , which line L5 returns. The code forms as the vector , which is the same numbers.
When is singular
If is singular, is not controllable by the Kalman rank condition. By the pole placement theorem, the eigenvalues of the uncontrollable part are then eigenvalues of for every , so some polynomials cannot be reached. The solve in line L2 meets a zero pivot, and the code raises an error for every , also for the polynomials that could be reached. With exact data this test is exact. With floating point data, a nearly singular usually gives a nonzero pivot, and the code returns a very large gain; the page discusses this.
Complexity
Line L1 costs matrix-vector products, in total. Line L2 is one solve, . Lines L3 and L4 cost vector-matrix products, . The time is and the extra space is for . Forming by matrix products, as the textbook formula reads, costs and is not needed.
In the floating-point model the cost is the same, but the accuracy is poor. The controllability matrix of a well behaved system is often very ill conditioned, because its columns turn towards the dominant eigenvector of as grows. The solve in line L2 then has a relative error of about times the unit roundoff, and the table above shows this growth. Mehrmann and Xu (1996) show that the single-input problem itself is often ill conditioned, so no method can be accurate for every input. Methods that use orthogonal transformations do not form and do better than the formula in practice.
Properties
- Exact in rational arithmetic. With integer or rational data, every step is a rational operation, and the result is exact. This makes the formula a good reference for tests.
- Linear in . The gain is affine in the coefficients of : . If is the open-loop polynomial, , by the Cayley-Hamilton theorem.
- Same in continuous and discrete time. The formula is pure algebra on , and . Only the choice of depends on the time domain: Hurwitz roots in continuous time, roots inside the unit circle in discrete time.
- Invariance. If and , then , and the gain in the new coordinates is , as it should be.
Variants and improvements
- Bass-Gura formula. Transform to controllable canonical form by a matrix built from and the open-loop coefficients. In the new coordinates the gain is the difference of the wanted and the open-loop coefficient vectors, as in the companion example above; multiply by to return. It has the same unique result and the same numerical weakness.
- Observer form. For one output, , with the observability matrix.
- Multi-input systems. Choose a vector so that is controllable for some (Heymann's lemma), and apply the formula to that pair. The result is one of many valid gains, often a poor one. Robust pole placement chooses among them.
- Orthogonal methods. Reduce by an orthogonal similarity to Hessenberg form with a multiple of , then compute by a recursion on the Hessenberg matrix. No controllability matrix is formed. MATLAB's
ackeris the formula of this page. MATLAB'splaceuses the Kautsky-Nichols-Van Dooren method, and SciPy'splace_polesuses the Tits-Yang refinement of it by default.
When to use it
Use the formula for hand computation, for teaching, for exact computation with rational data, and for systems of small order, say with well spread poles. It is also the standard proof of the single-input case of the pole placement theorem. For larger , for poles close together, or for any use in floating point where accuracy matters, use an orthogonal method. Even then, check the closed-loop eigenvalues of after the design.
Pitfalls
- Instability for larger . As in the table above, the formula can give a gain that places the poles in the wrong place, with no warning. Compute the eigenvalues of and compare.
- Near loss of controllability. If is close to an uncontrollable pair, is close to singular. The gain is then very large, and the closed loop is very sensitive, with any method. This is a property of the plant, not of the formula.
- Sign convention. The formula is for and the closed loop . With the sign of changes.
- Conjugate pairs. If one pole of a complex pair is missing, has complex coefficients and is complex. The code rejects such pole lists.
- Poles are not the whole design. The formula places poles only. The zeros, the input size and the robustness margins follow from the choice of poles and are not under separate control; see state feedback.
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
# Part of https://algorithm.tamnd.com/ackermann-formula/. The authors are listed in prov/DZTY4S.jsonl.
"""Ackermann's formula for single-input pole placement.
For x' = A x + b u (or x_(k+1) = A x_k + b u_k) with one input and the
control u = -K x, the closed-loop matrix is A - b K. If (A, b) is
controllable, the only row vector K with det(s I - (A - b K)) = p(s) for a
given monic p of degree n is
K = [0 ... 0 1] W^(-1) p(A), W = [b, A b, ..., A^(n-1) b].
The code computes q^T = e_n^T W^(-1) by one linear solve W^T q = e_n, so W
is never inverted, and then K = q^T p(A) by Horner's rule on row vectors,
K <- K A + p_i q^T, so p(A) is never formed. The cost is O(n^3).
With int and Fraction data the result is exact. With
float data the formula is numerically unstable for larger n, because W is
then badly conditioned (see the page).
"""
from fractions import Fraction
from ctlmat import matvec, mul, polymul, solve, transpose, zeros
__all__ = ["controllability_matrix", "poly_of_matrix", "poly_from_roots", "ackermann", "ackermann_poles"]
def controllability_matrix(A, b):
"""Return W = [b, A b, ..., A^(n-1) b] for a flat vector b."""
n = len(A)
if len(b) != n or any(len(row) != n for row in A):
raise ValueError("A must be n by n and b must have n entries")
cols = [list(b)]
for _ in range(n - 1):
cols.append(matvec(A, cols[-1]))
return transpose(cols)
def poly_of_matrix(p, A):
"""Return p(A) = p_0 A^n + p_1 A^(n-1) + ... + p_n I by Horner's rule."""
n = len(A)
P = zeros(n)
for c in p:
P = mul(A, P)
for i in range(n):
P[i][i] += c
return P
def poly_from_roots(roots):
"""Return the monic polynomial with the given roots, highest power first.
Exact roots (int, Fraction) give exact coefficients. If the roots are
closed under complex conjugation, the tiny imaginary parts of the
coefficients are removed and the coefficients are real floats.
"""
p = [1]
for r in roots:
p = polymul(p, [1, -r])
if any(isinstance(c, complex) for c in p):
big = max(abs(c) for c in p)
if all(abs(complex(c).imag) <= 1e-12 * big for c in p):
p = [complex(c).real for c in p]
return p
def ackermann(A, b, p):
"""Return the row vector K (a flat list) with charpoly(A - b K) = p.
p is monic of degree n, highest power first. Raises ValueError if p has
the wrong form or if (A, b) is not controllable (W is singular).
"""
n = len(A)
if len(p) != n + 1 or p[0] != 1:
raise ValueError("p must be monic of degree n")
W = controllability_matrix(A, b) # @line L1
e_n = [0] * (n - 1) + [1]
try:
q = solve(transpose(W), e_n) # @line L2
except ValueError:
raise ValueError("(A, b) is not controllable") from None
At = transpose(A)
K = [0] * n
for c in p: # @line L3
K = [x + c * y for x, y in zip(matvec(At, K), q)] # @line L4
return K # @line L5
def ackermann_poles(A, b, poles):
"""Return K that places the eigenvalues of A - b K at the given poles.
Complex poles must come in conjugate pairs, so that K is real.
"""
if len(poles) != len(A):
raise ValueError("give exactly n poles")
p = poly_from_roots(poles)
if any(isinstance(c, complex) for c in p):
raise ValueError("complex poles must come in conjugate pairs")
return ackermann(A, b, p)
if __name__ == "__main__":
h = Fraction(1, 10)
print(ackermann([[0, 1], [0, 0]], [0, 1], [1, 2, 2]))
print(ackermann([[1, h], [0, 1]], [h * h / 2, h], [1, 0, 0]))
ctlmat.py 630 lines
# 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()
test_ackermann_formula.py 165 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ackermann-formula/. The authors are listed in prov/DZTY4S.jsonl.
import random
from fractions import Fraction
import pytest
import ctlmat as cm
from ackermann_formula import (
ackermann,
ackermann_poles,
controllability_matrix,
poly_from_roots,
poly_of_matrix,
)
def closed_loop(A, b, K):
return [[A[i][j] - b[i] * K[j] for j in range(len(A))] for i in range(len(A))]
def rand_pair(rng, n, lo=-3, hi=3):
while True:
A = [[rng.randint(lo, hi) for _ in range(n)] for _ in range(n)]
b = [rng.randint(lo, hi) for _ in range(n)]
if cm.det(controllability_matrix(A, b)) != 0:
return A, b
def brute_force_gain(A, b, p):
"""Solve the affine map from K to the closed-loop coefficients directly.
The coefficients of charpoly(A - b K) are affine in K, because
A - b K is a rank-one change of A. Evaluate the map at K = 0 and at the
n unit vectors, then solve the n by n linear system.
"""
n = len(A)
c0 = cm.charpoly(A)[1:]
cols = []
for j in range(n):
e = [0] * n
e[j] = 1
cj = cm.charpoly(closed_loop(A, b, e))[1:]
cols.append([x - y for x, y in zip(cj, c0)])
M = cm.transpose(cols)
rhs = [Fraction(x) - y for x, y in zip(p[1:], c0)]
return cm.solve(M, rhs)
def test_double_integrator():
A = [[0, 1], [0, 0]]
b = [0, 1]
K = ackermann(A, b, [1, 2, 2])
assert K == [2, 2]
assert cm.charpoly(closed_loop(A, b, K)) == [1, 2, 2]
def test_companion_example():
A = [[0, 1], [-2, -3]]
b = [0, 1]
K = ackermann_poles(A, b, [-4, -5])
assert K == [18, 6]
def test_zoh_double_integrator_deadbeat():
for h in (Fraction(1, 10), Fraction(1, 2), Fraction(3)):
A = [[1, h], [0, 1]]
b = [h * h / 2, h]
K = ackermann(A, b, [1, 0, 0])
assert K == [1 / h ** 2, Fraction(3, 2) / h]
Acl = closed_loop(A, b, K)
assert cm.mat_power(Acl, 2) == cm.zeros(2)
def test_random_exact():
rng = random.Random(1)
for n in range(1, 7):
for _ in range(6):
A, b = rand_pair(rng, n)
p = [1] + [Fraction(rng.randint(-20, 20), rng.randint(1, 4)) for _ in range(n)]
K = ackermann(A, b, p)
assert cm.charpoly(closed_loop(A, b, K)) == p
assert K == brute_force_gain(A, b, p)
def test_poly_of_matrix_matches_powers():
rng = random.Random(2)
A = [[rng.randint(-4, 4) for _ in range(4)] for _ in range(4)]
p = [1, 3, -2, 5, 7]
want = cm.zeros(4)
for i, c in enumerate(p):
want = cm.add(want, cm.scale(c, cm.mat_power(A, len(p) - 1 - i)))
assert poly_of_matrix(p, A) == want
def test_matches_textbook_form():
# K = e_n^T W^(-1) p(A), with the inverse and p(A) formed explicitly.
rng = random.Random(4)
for n in range(1, 6):
A, b = rand_pair(rng, n)
p = [1] + [rng.randint(-9, 9) for _ in range(n)]
Winv = cm.inv(controllability_matrix(A, b))
want = cm.mul([Winv[-1]], poly_of_matrix(p, A))[0]
assert ackermann(A, b, p) == want
def test_cayley_hamilton_gives_zero_gain():
rng = random.Random(3)
A, b = rand_pair(rng, 4)
assert ackermann(A, b, cm.charpoly(A)) == [0, 0, 0, 0]
def test_complex_poles_float():
A = [[0.0, 1.0, 0.0], [0.0, 0.0, 1.0], [1.0, -2.0, 0.5]]
b = [0.0, 0.0, 1.0]
poles = [-2.0, complex(-1.0, 2.0), complex(-1.0, -2.0)]
K = ackermann_poles(A, b, poles)
assert all(isinstance(k, float) for k in K)
roots = cm.polyroots(cm.charpoly(closed_loop(A, b, K)))
for r, w in zip(roots, sorted(poles, key=lambda v: (complex(v).real, complex(v).imag))):
assert abs(r - w) < 1e-9
def test_unpaired_complex_pole_rejected():
with pytest.raises(ValueError):
ackermann_poles([[0, 1], [0, 0]], [0, 1], [complex(-1, 1), -2])
def test_uncontrollable_rejected():
A = [[1, 0], [0, 2]]
b = [1, 0]
with pytest.raises(ValueError):
ackermann(A, b, [1, 3, 2])
def test_wrong_polynomial_rejected():
with pytest.raises(ValueError):
ackermann([[0, 1], [0, 0]], [0, 1], [2, 2, 2])
with pytest.raises(ValueError):
ackermann([[0, 1], [0, 0]], [0, 1], [1, 2])
def test_poly_from_roots_exact():
assert poly_from_roots([-1, -2]) == [1, 3, 2]
assert poly_from_roots([Fraction(1, 2)]) == [1, Fraction(-1, 2)]
p = poly_from_roots([complex(-1, 1), complex(-1, -1)])
assert p == [1.0, 2.0, 2.0]
def test_float_error_grows_with_n():
# A = diag(-1, ..., -n), b = ones, poles at -(n + 1), ..., -2n. The
# coefficient error of the placed polynomial, relative to its size,
# grows quickly with n. This shows the instability; the bound is loose.
def rel_error(n):
A = [[float(-(i + 1)) if i == j else 0.0 for j in range(n)] for i in range(n)]
b = [1.0] * n
p = poly_from_roots([float(-(n + 1 + i)) for i in range(n)])
K = ackermann(A, b, p)
Acl = [[Fraction(v) for v in row] for row in closed_loop(A, b, K)]
got = cm.charpoly(Acl)
return max(abs(float(g) - c) / abs(c) for g, c in zip(got, p))
assert rel_error(4) < 1e-10
assert rel_error(12) > 100 * rel_error(4)
History
Ackermann (1972) published the formula in the German journal Regelungstechnik as a direct design rule for single-input systems in state space. Before it, the usual route was a change of coordinates to a canonical form and a comparison of coefficients, as in the Bass-Gura formula. The formula became a standard textbook result and appears in Chen (1999) and in Åström and Wittenmark (1997). Its numerical weakness was well known by the 1980s; Kautsky, Nichols and Van Dooren (1985) cite the poor conditioning of canonical form methods as the reason for their algorithm, and Mehrmann and Xu (1996) analysed the conditioning of the single-input problem.
References
- Jürgen Ackermann, Der Entwurf linearer Regelungssysteme im Zustandsraum, Regelungstechnik 20(7), 297-300, 1972, the formula for the feedback vector of a single-input system from the controllability matrix and the desired characteristic polynomial
- Chi-Tsong Chen, Linear System Theory and Design, third edition, Oxford University Press, 1999, Section 8.2, State Feedback
- Karl J. Åström and Björn Wittenmark, Computer-Controlled Systems, Theory and Design, third edition, Prentice Hall, 1997 (Dover reprint, 2011), Section 4.3, Regulation by State Feedback
- Volker Mehrmann and Hongguo Xu, An analysis of the pole placement problem I. The single-input case, Electronic Transactions on Numerical Analysis 4, 89-105, 1996, the conditioning of the single-input pole placement problem and of the closed-loop eigenvalues
- Jaroslav Kautsky, Nancy K. Nichols and Paul Van Dooren, Robust pole assignment in linear state feedback, International Journal of Control 41(5), 1129-1155, 1985, the introduction, on the numerical problems of methods that use canonical forms
Where this leads
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag DZTY4S Edit this page History Report an error Markdown