Algorithmadvanced
Kautsky-Nichols-Van Dooren pole placement
Also called KNV algorithm, robust eigenstructure assignment.
Places the eigenvalues of A - BK and uses the freedom of a multi-input gain to make the eigenvector matrix well conditioned, so the poles are less sensitive.
- Solves
- Pole placement problem
- Time
- O(n^4 (s + 1)) worst
- Space
- O(n^2 m) extra
- Where
- m = the number of inputs; n = the number of states; s = the number of sweeps
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jaroslav Kautsky, Nancy K. Nichols, Paul Van Dooren, 1985
Kautsky-Nichols-Van Dooren (KNV) pole placement computes a state feedback gain for , , such that has given eigenvalues and a matrix of unit eigenvectors that is as well conditioned as the method can find. With inputs the pole placement problem has many solutions, because each eigenvector can be chosen in an -dimensional subspace. KNV uses this freedom to make the placed eigenvalues insensitive to errors in , and . It differs from Ackermann's formula, which has no freedom to use because it handles one input, and from the pole placement theorem, which only says that a solution exists. This page describes method 0 of the 1985 paper, the simplest of its methods.
In plain words
A machine with several control knobs can be made to settle in the same way by many different settings of the knob weights. Some settings are fragile: a tiny error in the model or in the weights moves the settling behaviour a lot. Others are robust. The method looks at the modes of the closed loop, the directions in which the state settles. Fragile settings have modes that point in almost the same direction. The method changes one mode direction at a time and turns it as far as it can from the others, within the directions the knobs allow. When no mode can be turned further, it computes the knob weights for these directions. The settling rates stay exactly as the designer asked.
The problem
Input: , of rank with controllable, and numbers , closed under complex conjugation. Output: a real and an invertible with unit columns such that , , and with a small 2-norm condition number .
The measure comes from the Bauer-Fike theorem: if changes by , every eigenvalue of the changed matrix lies within of some . The eigenvalue condition numbers of the single are also bounded by . A small also tends to give a smaller , because and .
The algorithm
KNV0(A, B, λ_1..λ_n)- 1
B = [U_0, U_1] [Z; 0] ▷ QR of B; Z is m by m, invertible - 2
for each j: S_j ← orthonormal basis of null(U_1^T (A - λ_j I)) ▷ n by m - 3
for each j: x_j ← unit vector in range S_j (from a fixed random start) - 4
repeat sweeps until κ_2(X) stops falling: - 5
for each j: y_j ← unit vector orthogonal to all x_i with i ≠ j - 6
x_j ← S_j S_j^H y_j, normalized - 7
M ← X Λ X^(-1) - 8
return K = Z^(-1) U_0^T (A - M)
Line L1 splits the state space into the range of , spanned by , and its orthogonal complement, spanned by . Line L2 finds, for each wanted eigenvalue, all vectors that can be eigenvectors for it: is one exactly when lies in the range of , that is, when . Lines L5 and L6 replace one eigenvector by the unit vector of that is closest to the normal of the other columns. For a complex pair, the code updates the member with positive imaginary part and sets its partner to the complex conjugate, so that is real. Lines L7 and L8 solve for .
Example
Take
and the poles . The code returns
with and . The eigenvalues of agree with the wanted ones to about .
A rank-one design uses one direction of the inputs: set , with from Ackermann's formula for the single-input pair . For the same poles:
| design | ||
|---|---|---|
| KNV method 0 | 9.11 | 9.96 |
| rank one, | 224 | 43.1 |
| rank one, | 595 | 67.4 |
| rank one, | 860 | 81.6 |
All four gains place the same eigenvalues. The KNV gain is the smallest, and its eigenvalues are about 25 to 95 times less sensitive by the Bauer-Fike bound.
Correctness
The full proof is in proofs/correctness.md. It has three parts.
- The gain. For an invertible with unit columns, there is a with if and only if every column lies in range , and then is the matrix of line L8. Multiply on the left by : the top block gives , and the bottom block is the condition .
- The subspaces. If is controllable, each has dimension exactly . This follows from the Popov-Belevitch-Hautus test: .
- The sweep. If every other column is fixed, , and line L6 maximizes over unit vectors of range by the Cauchy-Schwarz inequality. So for real eigenvalues no step decreases . By Hadamard's inequality , with equality only for orthonormal columns, so the sweep pushes towards orthogonality.
If the poles are closed under conjugation and the conjugate columns are conjugate, is real, so is real.
Proof: Every eigenvector matrix built from the subspaces S_j gives a real gain with the wanted poles, and method 0 does not decrease the determinantfull
Let and with rank . Line L1 gives an orthogonal matrix and an invertible with ; the columns of span the range of , and has columns. For a number , let . Line L2 computes an orthonormal basis of . Write and .
Lemma 1: which eigenvector matrices are possible
Let be invertible. There is a with if and only if for every . In that case is unique and equals .
Proof. Let . The equation is the same as , because is invertible. Since is orthogonal, this equation holds if and only if it holds after multiplication on the left by . With and , it splits into
The first equation has the unique solution . The second equation holds if and only if , because is invertible. Its column is , that is, .
Lemma 2: the dimension of the subspaces
for every . So if is controllable, every has dimension .
Proof. Multiplication on the left by the invertible matrix does not change the rank, and gives
Because is invertible, column operations with the last columns remove the block without changing the rank. The result is block diagonal up to the order of the blocks, with rank . By the Popov-Belevitch-Hautus test, is controllable if and only if the left side is for every . Then , an matrix, has rank , and its null space has dimension .
Lemma 3: the update does not decrease the determinant
Fix all columns of except column . Let be the matrix of the other columns, assume they are independent, and let be a unit vector with for all (line L5). Among the unit vectors , the vector , where is the orthogonal projector onto , maximizes , if .
Proof. Write any as , with in the span of the other columns, since and these columns together span and is orthogonal to them. The determinant is linear in column and vanishes when column is a combination of the other columns, so , where is with column replaced by . The factor does not depend on . For a unit vector , , so , and by the Cauchy-Schwarz inequality , with equality at .
The old column is one of the admissible vectors, so the update of line L6 never decreases when only one column changes. This is the case for every real . For a complex pair the code changes two columns, and its conjugate, and this argument does not apply. Hadamard's inequality gives , with equality if and only if the columns are orthonormal, so for real poles the values of form a bounded nondecreasing sequence and converge. This proves nothing about the limit of itself; the code only uses it as a heuristic and keeps the matrix with the smallest that it has seen.
Lemma 4: the gain is real
Assume that the poles are closed under conjugation, that are real, and that for every complex pair the code sets . Then and are real.
Proof. Let be the permutation matrix that swaps the columns of each complex pair and fixes the others. Then and , with . So
Then is a product of real matrices. Also whenever , because and are real; so the conjugate columns satisfy the condition of Lemma 1.
Theorem
If is controllable, the poles are distinct and closed under conjugation, and the final is invertible, then the gain of line L8 is real and . So the eigenvalues of are exactly , with the columns of as eigenvectors.
Proof. Every column that the code ever stores is a vector of the form , from line L3 or line L6, or the conjugate of one; so for all . Lemma 1 gives for the gain of line L8, and Lemma 4 shows that it is real. An matrix with independent eigenvectors for the eigenvalues has exactly these eigenvalues.
The code raises an error if the final exceeds , so it never returns a gain from a numerically singular . If is not controllable and an uncontrollable eigenvalue of is not among the , no invertible with exists: by Lemma 1 it would give a gain that moves an uncontrollable eigenvalue, which the pole placement theorem excludes. Every the code builds is then singular, and the test reports it, up to rounding error. In floating point all equalities above hold up to rounding error; the tests check the residual and the characteristic polynomial of .
Complexity
In the floating-point model: line L1 costs . Line L2 costs for each , in total, and stores bases of size , which is the extra space. In this implementation each step of line L5 orthogonalizes columns, , so a sweep costs ; with updates of a QR factorization of a sweep costs . Lines L7 and L8 cost . The code stops when a sweep does not lower , or after a fixed number of sweeps; no general bound on the number of sweeps is known.
Rounding errors in lines L7 and L8 act like a small change of the closed-loop matrix. By the Bauer-Fike theorem the placed eigenvalues then move by at most . So a small is both the robustness of the design and the accuracy of the computation.
Properties
- Exact placement, approximate optimum. The eigenvalues are placed exactly in exact arithmetic for any choice of the in range . Only the conditioning is optimized, and only locally.
- Monotone sweeps for real poles. Each step does not decrease , so the values converge. Nothing guarantees that converges to a global maximum, or that is minimal.
- Single input. With , each is one line, is fixed by the poles, and the method returns the unique single-input gain, the same as Ackermann's formula in exact arithmetic.
- Full input. With , , and for real poles one sweep gives an orthonormal with : each new column is orthogonal to all columns at the time of its update, and the later updates keep this.
- Repeated poles. A pole can be repeated at most times with a diagonalizable closed loop, since its eigenvectors must be independent vectors of one -dimensional . The full method allows this; the code on this page needs distinct poles.
Variants and improvements
- Other KNV methods. The 1985 paper gives further methods with other update rules and other measures of conditioning.
- Tits and Yang (1996). Maximize directly, update two columns at a time, also for complex pairs, and prove that the iteration converges from any start. SciPy's
place_polesuses this method by default and KNV method 0 as an option. MATLAB'splaceuses a KNV method. - Eigenstructure assignment. Choose the eigenvectors for other goals, such as decoupling of modes or the shape of the response, instead of conditioning.
- Observer design. Apply the method to and set to get a well conditioned Luenberger observer.
- Optimal control instead. The infinite-horizon LQR chooses by a cost and gives guaranteed margins for state feedback. Pole placement with KNV gives the exact poles, LQR gives the margins.
When to use it
Use KNV, or the Tits-Yang method, whenever a multi-input system needs a pole placement gain computed in floating point. It is the default in the main control libraries. It is also the right choice when the rank-one approach gives a large gain or poles that move under small model errors. Do not expect it to make an ill posed design good: if the wanted poles are far from the open-loop ones, or if is close to an uncontrollable pair, every gain is large, and KNV only finds a less bad one.
Pitfalls
- Robust poles are not a robust loop. A small means that the eigenvalues move little under small changes of . It gives no gain margin or phase margin at the plant input, and it says nothing about unmodelled dynamics; see model uncertainty.
- Repeated poles. Do not ask for a pole more than times; the closed loop then has a Jordan block, and its eigenvalue is very sensitive. Spread close poles a little instead.
- Local optimum. The result depends on the starting . Try a few starts, or use the Tits-Yang method, when the conditioning matters.
- Rank of . Remove dependent columns of first; the method needs invertible. A redundant input adds nothing to the freedom of .
- Complex pairs. Give both members of a pair. The code checks this and rejects an unpaired complex pole.
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()
robust_pole_placement.py 251 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/robust-pole-placement/. The authors are listed in prov/PCC8GC.jsonl.
"""Robust pole placement by the Kautsky-Nichols-Van Dooren method 0.
Given x' = A x + B u with m inputs (rank B = m) and n wanted closed-loop
eigenvalues, find K with u = -K x so that A - B K has these eigenvalues and
a well conditioned matrix X of eigenvectors.
Steps:
- QR of B: B = U0 Z with [U0, U1] orthogonal and Z invertible.
- For each eigenvalue lambda_j, S_j is an orthonormal basis of the null
space of U1^T (A - lambda_j I). Every eigenvector of A - B K for lambda_j
lies in range S_j, and every vector of range S_j is such an eigenvector
for a suitable K.
- Method 0: sweep over j. Replace x_j by the normalized projection onto
range S_j of a unit vector y_j orthogonal to all other columns of X. For
real eigenvalues each such step does not decrease |det X| when the
columns have unit length.
- K = Z^(-1) U0^T (A - X Lambda X^(-1)).
This implementation needs distinct eigenvalues, closed under complex
conjugation. For a complex pair it updates the member with positive
imaginary part and sets the other column to its conjugate, so K is real.
It is a plain version of method 0 for teaching; it is not the full KNV
algorithm with repeated eigenvalues and the real treatment of complex
pairs. Computation is in floating point (complex where needed).
"""
import random
from ctlmat import inv, mul, norm2, solve, transpose
__all__ = ["input_qr", "eigvec_subspace", "knv0", "eigvec_condition", "eigenvectors"]
def _cdot(x, y):
"""Return x^H y."""
return sum(complex(a).conjugate() * b for a, b in zip(x, y))
def _cnorm(x):
return sum(abs(v) ** 2 for v in x) ** 0.5
def _orthonormal_extend(vectors, n, total):
"""Gram-Schmidt the given vectors, then add unit vectors up to `total`.
Returns (Q, R): Q is the orthonormal basis of the span of `vectors`
(vectors with a tiny residual are dropped), R are the added vectors
(orthonormal and orthogonal to Q). Two passes of orthogonalization keep
the result orthonormal to rounding error.
"""
basis = []
def residual(v):
r = [complex(a) for a in v]
for _ in range(2):
for q in basis:
c = _cdot(q, r)
r = [a - c * b for a, b in zip(r, q)]
return r
scale = max([_cnorm(v) for v in vectors] + [1.0])
for v in vectors:
r = residual(v)
nr = _cnorm(r)
if nr > 1e-10 * scale:
basis.append([a / nr for a in r])
q_count = len(basis)
while len(basis) < total:
best, best_norm = None, -1.0
for i in range(n):
e = [0.0] * n
e[i] = 1.0
r = residual(e)
nr = _cnorm(r)
if nr > best_norm:
best, best_norm = r, nr
basis.append([a / best_norm for a in best])
return basis[:q_count], basis[q_count:]
def _real_if_close(vectors):
out = []
for v in vectors:
if all(abs(complex(a).imag) <= 1e-14 for a in v):
out.append([complex(a).real for a in v])
else:
out.append(v)
return out
def input_qr(B):
"""Return (U0, U1, Z) with B = U0 Z, [U0, U1] orthogonal, Z m by m.
U0 and U1 are lists of columns (each a flat list). Raises ValueError if
B does not have full column rank.
"""
n = len(B)
m = len(B[0])
cols = [[float(B[i][j]) for i in range(n)] for j in range(m)]
q, rest = _orthonormal_extend(cols, n, n)
if len(q) != m:
raise ValueError("B must have full column rank")
U0 = _real_if_close(q)
U1 = _real_if_close(rest)
Z = [[sum(U0[i][k] * cols[j][k] for k in range(n)) for j in range(m)] for i in range(m)]
return U0, U1, Z
def eigvec_subspace(A, U1, lam):
"""Return an orthonormal basis (list of columns) of null(U1^T (A - lam I))."""
n = len(A)
rows = []
for u in U1:
row = [sum(u[k] * (A[k][j] - (lam if k == j else 0)) for k in range(n)) for j in range(n)]
rows.append(row)
conj_rows = [[complex(v).conjugate() for v in r] for r in rows]
q, null = _orthonormal_extend(conj_rows, n, n)
return null
def _orth_to_others(X, j, n):
others = [X[i] for i in range(len(X)) if i != j]
_, rest = _orthonormal_extend(others, n, len(others) + 1)
return rest[0]
def _project(S, y):
coeffs = [_cdot(s, y) for s in S]
x = [sum(c * s[i] for c, s in zip(coeffs, S)) for i in range(len(y))]
return x
def eigvec_condition(X):
"""Return the 2-norm condition number of the matrix with columns X."""
M = transpose(X)
return norm2(M) * norm2(inv(M))
def _pairs(poles):
"""Return the indices of the poles to update and the partner index of each."""
n = len(poles)
used = [False] * n
leaders = []
partner = [None] * n
for i, p in enumerate(poles):
if used[i]:
continue
p = complex(p)
if abs(p.imag) <= 1e-14 * (1 + abs(p)):
used[i] = True
leaders.append(i)
continue
best = None
for j in range(n):
if not used[j] and j != i and abs(complex(poles[j]) - p.conjugate()) <= 1e-12 * (1 + abs(p)):
best = j
break
if best is None:
raise ValueError("complex poles must come in conjugate pairs")
used[i] = used[best] = True
lead, other = (i, best) if p.imag > 0 else (best, i)
leaders.append(lead)
partner[lead] = other
return leaders, partner
def knv0(A, B, poles, sweeps=50, seed=0):
"""Return (K, X, cond): the gain, the eigenvector columns and cond_2(X).
A is n by n, B is n by m with rank m, and poles is a list of n distinct
numbers closed under conjugation. Raises ValueError if the poles are
not distinct, if a complex pole has no partner, or if no independent
eigenvectors are found (then (A, B) is not controllable at some pole).
"""
n = len(A)
if len(poles) != n:
raise ValueError("give exactly n poles")
for i in range(n):
for j in range(i + 1, n):
if abs(complex(poles[i]) - complex(poles[j])) <= 1e-12 * (1 + abs(complex(poles[i]))):
raise ValueError("this implementation needs distinct poles")
leaders, partner = _pairs(poles)
lam = [complex(p) if abs(complex(p).imag) > 0 else float(complex(p).real) for p in poles]
U0, U1, Z = input_qr(B) # @line L1
S = [eigvec_subspace(A, U1, l) for l in lam] # @line L2
rng = random.Random(seed)
X = [None] * n
for j in leaders: # @line L3
y = [rng.uniform(-1, 1) for _ in range(n)]
x = _project(S[j], y)
nx = _cnorm(x)
X[j] = [v / nx for v in x]
if partner[j] is not None:
X[partner[j]] = [complex(v).conjugate() for v in X[j]]
best, best_X = eigvec_condition(X), [list(c) for c in X]
for _ in range(sweeps): # @line L4
for j in leaders:
y = _orth_to_others(X, j, n) # @line L5
x = _project(S[j], y) # @line L6
nx = _cnorm(x)
if nx < 1e-12:
continue
X[j] = [v / nx for v in x]
if partner[j] is not None:
X[partner[j]] = [complex(v).conjugate() for v in X[j]]
c = eigvec_condition(X)
if c >= best * (1 - 1e-9):
if c < best:
best, best_X = c, [list(col) for col in X]
break
best, best_X = c, [list(col) for col in X]
X, cond = best_X, best
if cond > 1e12:
raise ValueError("no independent eigenvectors found; (A, B) may be uncontrollable")
Xm = transpose(X)
XL = [[Xm[i][j] * lam[j] for j in range(n)] for i in range(n)]
# M = X Lambda X^(-1), computed as the solution of X^T M^T = (X Lambda)^T.
M = transpose(solve(transpose(Xm), transpose(XL))) # @line L7
D = [[A[i][j] - M[i][j] for j in range(n)] for i in range(n)]
# U0, a list of columns, read as a list of rows is the matrix U0^T.
Kc = solve(Z, mul(U0, D)) # @line L8
big = max(1.0, max(abs(v) for row in Kc for v in row))
if any(abs(complex(v).imag) > 1e-8 * big for row in Kc for v in row):
raise ValueError("the gain is not real; check the conjugate pairs")
K = [[complex(v).real for v in row] for row in Kc]
return K, X, cond
def eigenvectors(Acl, poles, iters=3):
"""Return unit eigenvectors (columns) of Acl for the given simple poles.
Uses inverse iteration with a small shift. For use on a closed loop from
any method, so that conditions can be compared.
"""
n = len(Acl)
rng = random.Random(1)
cols = []
for lam in poles:
lam = complex(lam)
shift = lam + 1e-9 * (1 + abs(lam))
M = [[complex(Acl[i][j]) - (shift if i == j else 0) for j in range(n)] for i in range(n)]
x = [complex(rng.uniform(-1, 1)) for _ in range(n)]
for _ in range(iters):
x = solve(M, x)
nx = _cnorm(x)
x = [v / nx for v in x]
cols.append(x)
return cols
test_robust_pole_placement.py 142 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/robust-pole-placement/. The authors are listed in prov/PCC8GC.jsonl.
import random
import pytest
import ctlmat as cm
from robust_pole_placement import eigenvectors, eigvec_condition, eigvec_subspace, input_qr, knv0
A4 = [[0.0, 1.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], [-1.0, 2.0, 0.0, -1.0]]
B4 = [[0.0, 0.0], [1.0, 0.0], [0.0, 0.0], [0.0, 1.0]]
POLES4 = [-1.0, -2.0, -3.0, -4.0]
def closed_loop(A, B, K):
return cm.sub(A, cm.mul(B, K))
def residual(Acl, X, poles):
"""Return max over j of |Acl x_j - lambda_j x_j|."""
worst = 0.0
for x, lam in zip(X, poles):
ax = cm.matvec(Acl, x)
worst = max(worst, max(abs(a - lam * v) for a, v in zip(ax, x)))
return worst
def ackermann_single(A, b, p):
"""Ackermann's formula, written out here as the reference gain."""
n = len(A)
cols = [list(b)]
for _ in range(n - 1):
cols.append(cm.matvec(A, cols[-1]))
W = cm.transpose(cols)
q = cm.solve(cm.transpose(W), [0.0] * (n - 1) + [1.0])
K = [0.0] * n
At = cm.transpose(A)
for c in p:
K = [x + c * y for x, y in zip(cm.matvec(At, K), q)]
return K
def poly_from_roots(roots):
p = [1.0]
for r in roots:
p = cm.polymul(p, [1.0, -r])
return [complex(c).real for c in p]
def check_placement(A, B, poles, K, X, tol=1e-8):
Acl = closed_loop(A, B, K)
assert residual(Acl, X, poles) < tol * (1 + max(abs(v) for r in Acl for v in r))
got = cm.charpoly(Acl)
want = poly_from_roots(poles)
for g, w in zip(got, want):
assert abs(g - w) < 1e-7 * (1 + abs(w))
def test_stated_example_beats_rank_one_ackermann():
K, X, cond = knv0(A4, B4, POLES4)
check_placement(A4, B4, POLES4, K, X)
roots = cm.polyroots(cm.charpoly(closed_loop(A4, B4, K)))
for r, w in zip(roots, sorted(POLES4)):
assert abs(r - w) < 1e-8
# Rank-one design: u = -v k x with b = B v and k from Ackermann.
for v in ([1.0, 1.0], [1.0, 0.0], [0.0, 1.0]):
b = cm.matvec(B4, v)
k = ackermann_single(A4, b, poly_from_roots(POLES4))
Kr = [[vi * kj for kj in k] for vi in v]
Acl = closed_loop(A4, B4, Kr)
Xr = eigenvectors(Acl, POLES4)
assert residual(Acl, Xr, POLES4) < 1e-6
assert cond <= eigvec_condition(Xr)
assert cm.norm2(K) <= cm.norm2(Kr)
assert cond < 10.0
def test_identity_input_gives_orthonormal_eigenvectors():
rng = random.Random(5)
n = 4
A = [[rng.uniform(-2, 2) for _ in range(n)] for _ in range(n)]
B = cm.eye(n)
poles = [-1.0, -2.0, -3.0, -5.0]
K, X, cond = knv0(A, [[float(v) for v in r] for r in B], poles)
check_placement(A, B, poles, K, X)
assert cond < 1 + 1e-6
def test_random_systems_real_and_complex():
rng = random.Random(7)
for trial in range(8):
n = rng.randint(3, 6)
m = rng.randint(2, min(3, n))
A = [[rng.uniform(-2, 2) for _ in range(n)] for _ in range(n)]
B = [[rng.uniform(-1, 1) for _ in range(m)] for _ in range(n)]
poles = [-(1.0 + i) for i in range(n)]
if trial % 2 == 1:
poles[0] = complex(-1.0, 1.5)
poles[1] = complex(-1.0, -1.5)
K, X, cond = knv0(A, B, poles, seed=trial)
assert all(isinstance(v, float) for row in K for v in row)
check_placement(A, B, poles, K, X, tol=1e-7)
def test_sweeps_do_not_increase_condition():
rng = random.Random(11)
A = [[rng.uniform(-2, 2) for _ in range(5)] for _ in range(5)]
B = [[rng.uniform(-1, 1) for _ in range(2)] for _ in range(5)]
poles = [-1.0, -2.0, -3.0, -4.0, -5.0]
_, _, c0 = knv0(A, B, poles, sweeps=0)
_, _, c1 = knv0(A, B, poles, sweeps=1)
_, _, c9 = knv0(A, B, poles, sweeps=20)
assert c9 <= c1 <= c0
def test_subspace_dimension_and_property():
U0, U1, Z = input_qr(B4)
assert len(U0) == 2 and len(U1) == 2
Bq = cm.mul(cm.transpose(U0), Z)
assert max(abs(x - y) for r, s in zip(Bq, B4) for x, y in zip(r, s)) < 1e-14
for lam in (-1.0, complex(-2.0, 1.0)):
S = eigvec_subspace(A4, U1, lam)
assert len(S) == 2
for s in S:
v = [sum(A4[i][j] * s[j] for j in range(4)) - lam * s[i] for i in range(4)]
for u in U1:
assert abs(sum(a * b for a, b in zip(u, v))) < 1e-12
def test_rejections():
with pytest.raises(ValueError):
knv0(A4, B4, [-1.0, -1.0, -2.0, -3.0])
with pytest.raises(ValueError):
knv0(A4, B4, [complex(-1.0, 1.0), -2.0, -3.0, -4.0])
with pytest.raises(ValueError):
knv0(A4, [[1.0, 2.0], [0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], POLES4)
# Uncontrollable: the last state is decoupled from both inputs.
A = [[0.0, 1.0, 0.0], [0.0, 0.0, 0.0], [0.0, 0.0, 2.0]]
B = [[1.0, 0.0], [0.0, 1.0], [0.0, 0.0]]
with pytest.raises(ValueError):
knv0(A, B, [-1.0, -2.0, -3.0])
History
Kautsky, Nichols and Van Dooren (1985) showed that the choice of the eigenvectors decides the sensitivity of the placed poles, gave the parametrization of the possible eigenvectors by the subspaces , and proposed iterative methods, method 0 among them, that make well conditioned. Their paper also showed the numerical problems of methods that go through canonical forms. Tits and Yang (1996) reformulated the problem as the maximization of , extended the updates to complex pairs, and gave globally convergent algorithms. Mehrmann and Xu (1996, 1997) analysed the conditioning of the single-input and multi-input problems.
References
- 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 parametrization of the eigenvectors by the subspaces S_j, the formula for K, and method 0 with its column updates
- André L. Tits and Yaguang Yang, Globally convergent algorithms for robust pole assignment by state feedback, IEEE Transactions on Automatic Control 41(10), 1432-1452, 1996, the maximization of the absolute value of det X, its relation to method 0, and the treatment of complex conjugate pairs
- Volker Mehrmann and Hongguo Xu, An analysis of the pole placement problem II. The multi-input case, Electronic Transactions on Numerical Analysis 5, 77-97, 1997, the conditioning of the multi-input pole placement problem
- Chi-Tsong Chen, Linear System Theory and Design, third edition, Oxford University Press, 1999, 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 PCC8GC Edit this page History Report an error Markdown