Algorithmadvanced
Adaptive pole placement
Also called indirect adaptive pole placement.
A self-tuning controller that solves a polynomial pole placement equation for the current plant estimate at each step.
- Time
- O(N n^3) worst
- Space
- O(n^2) extra
- Where
- N = the number of samples; n = the order of the plant model
- Model
- Real RAM
- Properties
- deterministicnot exactonlineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Peter E. Wellstead, D. Prager, P. Zanker, Karl Johan Åström, Björn Wittenmark, 1979
Adaptive pole placement is an indirect self-tuning regulator: at every sample it updates a plant model , by recursive least squares, solves the polynomial pole placement equation for the controller polynomials and , and applies the controller . The equation is a linear system with a Sylvester matrix, which has a unique solution exactly when and are coprime. Unlike the minimum variance self-tuner it does not cancel the plant zeros, so it works for plants with zeros outside the unit circle. Its weak point is the estimate itself: when and are close to a common factor, the design is ill conditioned, and the scheme needs a fix such as parameter projection.
In plain words
The controller has two parts that run at every sample. The first part keeps a model of the plant and corrects it from the newest measurement. The second part asks: if this model were the true plant, which controller would give the closed loop the response that I want? It answers by solving a small set of linear equations. Then it applies that controller for one sample, and the cycle repeats. The wanted response is fixed by the designer as a set of pole positions. Trouble comes when the model, by chance, looks like a plant that no controller can fix, because a pole and a zero of the model almost cancel. The design then gives huge gains, so a practical version keeps the model away from such points.
The problem
The plant is , with the forward shift operator , monic and , so the delay is one sample. The coefficients are unknown, and are coprime, and the sign and a lower bound of are known. The designer chooses the closed loop polynomial of degree and an observer polynomial of degree , both with all zeros inside the unit circle. The aim is a controller
that gives the closed loop the characteristic polynomial and the static gain 1. With monic of degree and of degree , this is the Diophantine equation
and with , so that : the observer polynomial cancels, and the zeros of stay in the response. This is a two-degree-of-freedom design.
The algorithm
ADAPTIVE-POLE-PLACEMENT(A_c, A_o, θ₀, p₀, b_min, N)- 1
θ̂ ← θ₀; P ← p₀ I; R, S, T ← the design for θ₀ - 2
for t ← 0 to N - 1 do - 3
measure y_t; φ ← (-y_{t-1}, …, -y_{t-n}, u_{t-1}, …, u_{t-n}) - 4
update θ̂ and P by one RLS step with (φ, y_t) - 5
if b̂₀ < b_min then b̂₀ ← b_min ▷ projection - 6
 ← (1, â₁, …, â_n); B̂ ← (b̂₀, …, b̂_{n-1}) - 7
if |det Syl(Â, B̂)| > tol and |B̂(1)| > tol then solve  R + B̂ S = A_c A_o; T ← (A_c(1)/B̂(1)) A_o- 8
u_t ← from R u = T u_c - S y ▷ certainty equivalence - 9
return θ̂
Line L7 writes and and compares the coefficients of . This gives linear equations in the unknowns, with a matrix whose columns are shifted copies of the coefficients of and . Its determinant is, up to sign, the resultant of and . If the test in line L7 fails, the controller of the last sample is kept. Line L8 divides the controller equation by to get from past values.
Example
Take (poles , inside the unit circle but lightly damped) and . The designer chooses and .
The design for the true plant. With and , the coefficients of , and in give
The determinant of this system is , and the exact solution is , , . Then and . The closed loop is , and its step response starts toward 1.
The adaptive loop. The estimate starts at , , with and . The command is a square wave of amplitude 1 that switches every 25 samples, and there is no noise. These are measurements.
| sample | ||||
|---|---|---|---|---|
| 2 | -0.6685 | 0.0000 | 1.2168 | 0.7685 |
| 5 | -1.1671 | 0.2679 | 0.9284 | 0.9871 |
| 10 | -1.4846 | 0.6851 | 0.9876 | 0.5140 |
| 199 | -1.4965 | 0.6967 | 1.0008 | 0.5010 |
| true | -1.5 | 0.7 | 1 | 0.5 |
The first outputs are , an overshoot of 70 percent while the model is wrong. From sample 50 on, the output differs from the response of the true design by at most . The start would fail: and share the factor , the design does not exist, the input stays zero, and the estimator never gets data.
Correctness
The proof in proofs/correctness.md proves the design step. For coprime and the Sylvester matrix is invertible (its determinant is the resultant), so line L7 has exactly one solution with , and the closed loop with the true plant has the characteristic polynomial and the transfer function (theorem). The adaptive loop is a different matter. With the certainty equivalence design and a projection that keeps the estimates in a convex set where and stay uniformly coprime, the closed loop signals are bounded and the tracking error goes to zero (a theorem that Ioannou and Sun, Chapter 7, prove for the continuous-time form). Without such a set, no general guarantee is known for the plain scheme: the estimate can pass near a common factor, where the gains of the design become unbounded.
Proof: The pole placement design step has a unique solution for coprime estimates and places the closed loop polesfull
Notation is that of the page. is monic of degree , has degree at most , is monic of degree and is monic of degree . The unknowns are and .
Claim 1 (the linear system). holds if and only if , where , the column of for holds the coefficients of , the column for holds those of , and holds the coefficients of , all for the powers .
Proof. and . Both and are monic of degree , so their difference has degree at most , and every term of the sums has degree at most . Two polynomials of degree at most are equal if and only if their coefficients are equal, which is .
Claim 2 (unique solution for coprime polynomials). is invertible if and only if and have no common zero.
Proof. is square of size . Suppose with . Then with of degree at most and of degree at most , not both zero. If then forces , so . From , every zero of (with multiplicity) is a zero of . If and are coprime, all zeros of are zeros of , but has degree at most , a contradiction. So coprime , give an invertible . Conversely, if and with , then (degree at most ) and (degree at most ) give with , so is singular.
The determinant of equals, up to sign, the resultant of and , which for monic with zeros is . The tests check this identity on random polynomials, and line L7 uses as the test of coprimeness.
Claim 3 (the closed loop). Let , be the true plant, coprime, and let , solve the equation with , , . Then the closed loop from to is , its characteristic polynomial is , and the static gain is 1.
Proof. From and , eliminate : , so and . The closed loop poles are the zeros of ; the factor cancels in the transfer function from but not in the response to disturbances and initial states. At the gain is .
Claim 4 (the projection keeps the design defined). Line L5 makes , so never vanishes identically and exactly. Line L7 changes the controller only when and , so by Claim 2 the solve is well defined whenever it runs; otherwise the last controller is kept. These two lines make every step of the algorithm defined; they do not prove that the adaptive closed loop is bounded, which needs the stronger projection described on the page.
Example check. For , , , the solution in rational arithmetic is , , , and . The resultant is , which agrees.
Complexity
In the real-RAM model, one RLS step with parameters costs operations. Building the Sylvester matrix costs , and its determinant and the solution of the Diophantine equation by Gaussian elimination cost . So samples cost , and the memory is for and the matrix. For the small of practice (2 to 4), the cost per sample is a few hundred operations.
Properties
- Non-minimum phase plants. The design does not cancel , so zeros outside the unit circle are allowed. The zeros of appear in the closed loop response.
- Stabilizability problem. The design needs and coprime. Least squares does not ensure this, and near a common factor the gains in and are large. This is the main difficulty of all indirect adaptive schemes (Ioannou and Sun, Section 7.6).
- Static gain one. With the static gain from to is 1 for the estimate; with an estimation error it is not exactly 1. Integral action in , by the internal model principle, gives zero static error for every model error.
- Excitation. Parameter convergence needs a command that is persistently exciting of order . A square wave is rich enough; a constant command is not.
- Separation. The estimator and the design are independent modules, so other designs (linear quadratic, model predictive) can be put in line L7.
Variants and improvements
- Projection on a coprime set. Keep in a convex set where the resultant of and is bounded away from zero (parameter projection). This gives a proof of bounded signals but needs prior knowledge to build the set.
- Integral action. Choose and solve the Diophantine equation with the extra factor. This removes static errors from load disturbances and model errors.
- Robust estimation. Normalization, dead zones and forgetting make the estimator tolerant of unmodeled dynamics and noise.
- Continuous time. The same design works with polynomials in and a continuous estimator; Ioannou and Sun treat this form.
- Direct pole placement. For minimum phase plants, the design can be parameterized by the controller coefficients and estimated directly, as in the minimum variance self-tuner.
When to use it
Use adaptive pole placement for a sampled plant of low, known order with slowly varying parameters and possibly non-minimum phase zeros, when the wanted closed loop response is given as pole positions. Add integral action and a guard against near common factors. For a minimum phase plant and a noise regulation goal, the minimum variance self-tuning regulator is simpler. For a plant whose full state is measured, model reference adaptive control has a cleaner stability proof.
Pitfalls
- Common factors in the start estimate. A start such as , has no design; the example shows that the loop then never starts learning.
- Wrong order. If the model order is too high, and get a common factor at convergence, and the design is singular.
- Bursting. With little excitation, the estimate drifts toward a near common factor, the loop gets large gains and bursts, and the burst brings new data. Keep a small dither or stop the update when the excitation is low.
- Polynomial conventions. The page writes polynomials in with the highest power first. Many books use ; the coefficient lists then read in the opposite order.
- Sampling period. A small sampling period makes the poles cluster near 1 and the Sylvester matrix ill conditioned.
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/adaptive-pole-placement/. The authors are listed in prov/G5MEWV.jsonl.
"""Indirect adaptive pole placement (a self-tuning regulator with a polynomial design).
Plant, in the forward shift operator q, of order n and delay one:
A(q) y = B(q) u + e, A = q^n + a_1 q^(n-1) + ... + a_n,
B = b_0 q^(n-1) + ... + b_(n-1).
Polynomials are lists of coefficients, highest power first. The
controller is R u = T u_c - S y with R monic of degree n - 1 and S of
degree n - 1. Given a wanted closed loop polynomial A_c (degree n) and an
observer polynomial A_o (degree n - 1), R and S solve the Diophantine
equation
A R + B S = A_c A_o,
and T = t0 A_o with t0 = A_c(1) / B(1), so the closed loop is
y = t0 B / A_c u_c with static gain 1.
The adaptive loop estimates (a_1..a_n, b_0..b_(n-1)) by recursive least
squares, keeps b_0 at least b_min (projection), and solves the design for
the estimate at every sample (certainty equivalence). It keeps the last
controller when the Sylvester matrix of the estimate is close to singular.
diophantine is exact when the inputs are int or Fraction.
"""
import random
from ctlmat import det, polyadd, polymul, polyval, solve
__all__ = ["sylvester_matrix", "diophantine", "design", "app_simulate"]
def _pad(p, length):
return [0] * (length - len(p)) + list(p)
def sylvester_matrix(A, B):
"""Matrix of the map (r_1..r_(n-1), s_0..s_(n-1)) -> coefficients of A R + B S.
A is monic of degree n, B has degree at most n - 1 (padded to n
coefficients). The rows are the coefficients of q^(2n-2) down to q^0.
Its determinant is, up to sign, the resultant of A and B, so it is
nonzero exactly when A and B are coprime.
"""
n = len(A) - 1
Bp = _pad(B, n)
m = 2 * n - 1
cols = []
for i in range(1, n):
cols.append(_pad(polymul(A, [1] + [0] * (n - 1 - i)), m))
for j in range(n):
cols.append(_pad(polymul(Bp, [1] + [0] * (n - 1 - j)), m)[-m:])
return [[cols[c][r] for c in range(m)] for r in range(m)]
def diophantine(A, B, Acl):
"""Solve A R + B S = Acl for R (monic, degree n - 1) and S (degree n - 1).
Acl must be monic of degree 2n - 1. Raises ValueError if A and B have a
common factor (singular Sylvester matrix).
"""
n = len(A) - 1
m = 2 * n - 1
lead = polymul(A, [1] + [0] * (n - 1)) # A q^(n-1)
rhs = polyadd(Acl, [-c for c in lead])
rhs = _pad(rhs, m)[-m:]
x = solve(sylvester_matrix(A, B), rhs)
R = [1] + list(x[:n - 1])
S = list(x[n - 1:])
return R, S
def design(A, B, Ac, Ao):
"""Return (R, S, T) of the pole placement design for the model (A, B)."""
R, S = diophantine(A, B, polymul(Ac, Ao))
t0 = polyval(Ac, 1) / polyval(B, 1)
T = [t0 * c for c in Ao]
return R, S, T
def app_simulate(a, b, Ac, Ao, uc, N, theta0, p0=100.0, b_min=0.1, tol=1e-6, sigma=0.0, seed=0,
adapt=True):
"""Run adaptive pole placement on the plant with coefficients a, b.
a = [a_1..a_n], b = [b_0..b_(n-1)] define A and B of the module notes.
uc(t) is the command. theta0 = (a_1..a_n, b_0..b_(n-1)) is the first
estimate. With adapt=False the estimate stays at theta0. Process noise
e_t is Gaussian with standard deviation sigma from random.Random(seed).
Returns (thetas, ys, us): the estimate after each sample, the outputs
and the inputs.
"""
rng = random.Random(seed)
n = len(a)
d = 2 * n
theta = [float(v) for v in theta0] # @line L1
P = [[p0 if i == j else 0.0 for j in range(d)] for i in range(d)]
try:
R, S, T = design([1.0] + theta[:n], theta[n:], Ac, Ao)
except (ValueError, ZeroDivisionError):
R, S, T = [1.0] + [0.0] * (n - 1), [0.0] * n, [0.0] * n # u = 0 until a design exists
ys, us, ucs = [0.0] * n, [0.0] * n, [0.0] * n
thetas = []
for t in range(N): # @line L2
e = rng.gauss(0.0, sigma) if sigma > 0 else 0.0
y = (-sum(a[i] * ys[-1 - i] for i in range(n))
+ sum(b[j] * us[-1 - j] for j in range(n)) + e) # @line L3
phi = [-ys[-1 - i] for i in range(n)] + [us[-1 - j] for j in range(n)]
ys.append(y)
if adapt:
Pphi = [sum(P[i][j] * phi[j] for j in range(d)) for i in range(d)]
den = 1.0 + sum(phi[i] * Pphi[i] for i in range(d))
eps = y - sum(phi[i] * theta[i] for i in range(d))
theta = [theta[i] + Pphi[i] * eps / den for i in range(d)] # @line L4
P = [[P[i][j] - Pphi[i] * Pphi[j] / den for j in range(d)] for i in range(d)]
if theta[n] < b_min:
theta[n] = b_min # @line L5
Ah, Bh = [1.0] + theta[:n], theta[n:] # @line L6
if abs(det(sylvester_matrix(Ah, Bh))) > tol and abs(sum(Bh)) > tol:
R, S, T = design(Ah, Bh, Ac, Ao) # @line L7
ucs.append(uc(t))
# R u = T u_c - S y, divided by q^(n-1): coefficient k acts on lag k
u = (sum(T[k] * ucs[-1 - k] for k in range(n)) - sum(S[k] * ys[-1 - k] for k in range(n))
- sum(R[k] * us[-k] for k in range(1, n))) # @line L8
us.append(u)
thetas.append(list(theta))
return thetas, ys[n:], us[n:] # @line L9
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_adaptive_pole_placement.py 79 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/adaptive-pole-placement/. The authors are listed in prov/G5MEWV.jsonl.
"""Tests for adaptive pole placement."""
import random
import unittest
from fractions import Fraction as F
from adaptive_pole_placement import app_simulate, design, diophantine, sylvester_matrix
from ctlmat import det, polyadd, polymul, polyroots, polyval
A_TRUE = [-1.5, 0.7] # A = q^2 - 1.5 q + 0.7
B_TRUE = [1.0, 0.5] # B = q + 0.5
AC = [1, -1, 0.25] # (q - 0.5)^2
AO = [1, 0] # q
def square(t):
return 1.0 if (t // 25) % 2 == 0 else -1.0
class TestDiophantine(unittest.TestCase):
def test_page_example_exact(self):
A, B, Ac = [1, F(-3, 2), F(7, 10)], [1, F(1, 2)], [1, -1, F(1, 4)]
R, S, T = design(A, B, Ac, [1, 0])
self.assertEqual(R, [1, F(7, 34)])
self.assertEqual(S, [F(5, 17), F(-49, 170)])
self.assertEqual(T, [F(1, 6), 0])
self.assertEqual(polyadd(polymul(A, R), polymul(B, S)), polymul(Ac, [1, 0]))
self.assertEqual(det(sylvester_matrix(A, B)), F(17, 10))
def test_random_exact_and_resultant(self):
rng = random.Random(11)
for n in (2, 3):
for _ in range(5):
A = [1] + [F(rng.randint(-9, 9), 4) for _ in range(n)]
B = [F(rng.randint(1, 9), 4)] + [F(rng.randint(-9, 9), 4) for _ in range(n - 1)]
Acl = [1] + [F(rng.randint(-9, 9), 8) for _ in range(2 * n - 1)]
R, S = diophantine(A, B, Acl)
self.assertEqual(len(R), n)
self.assertEqual(len(S), n)
self.assertEqual(polyadd(polymul(A, R), polymul(B, S)), Acl)
# reference: |det| = |resultant| = |prod of B at the roots of A|
res = 1
for z in polyroots([float(c) for c in A]):
res *= polyval([float(c) for c in B], z)
self.assertAlmostEqual(abs(float(det(sylvester_matrix(A, B)))), abs(res), places=6)
def test_common_factor_is_rejected(self):
A = polymul([1, F(-1, 2)], [1, F(-1, 3)])
B = [1, F(-1, 2)]
self.assertEqual(det(sylvester_matrix(A, B)), 0)
with self.assertRaises(ValueError):
diophantine(A, B, [1, 0, 0, 0])
class TestAdaptiveLoop(unittest.TestCase):
def test_converges_to_known_plant_design(self):
# reference: the same design with the true plant, no adaptation
_, y_ref, _ = app_simulate(A_TRUE, B_TRUE, AC, AO, square, 200, A_TRUE + B_TRUE, adapt=False)
self.assertAlmostEqual(y_ref[1], 1 / 6, places=12)
th, ys, _ = app_simulate(A_TRUE, B_TRUE, AC, AO, square, 200, [0.0, 0.0, 1.0, 0.1])
self.assertLess(max(abs(a - b) for a, b in zip(ys[100:], y_ref[100:])), 0.02)
self.assertLess(max(abs(a - b) for a, b in zip(th[-1], A_TRUE + B_TRUE)), 0.01)
def test_with_noise(self):
th, _, _ = app_simulate(A_TRUE, B_TRUE, AC, AO, square, 1000, [0.0, 0.0, 1.0, 0.1],
sigma=0.05, seed=0)
self.assertLess(max(abs(a - b) for a, b in zip(th[-1], A_TRUE + B_TRUE)), 0.15)
def test_projection_keeps_b0_above_minimum(self):
th, ys, _ = app_simulate(A_TRUE, B_TRUE, AC, AO, square, 200, [0.0, 0.0, 0.1, 0.3], b_min=0.1)
self.assertTrue(all(v[2] >= 0.1 for v in th))
self.assertLess(max(abs(v) for v in ys), 1e3)
if __name__ == "__main__":
unittest.main()
History
The self-tuning regulator of Åström and Wittenmark (1973) used minimum variance control, which needs a minimum phase plant. Wellstead, Prager and Zanker (1979) replaced it by a pole assignment design, and Åström and Wittenmark (1980) gave a pole and zero placement version. The difficulty that the estimates can lose coprimeness, the stabilizability problem, was studied in the 1980s and 1990s; Ioannou and Sun (Chapter 7) give the projection solution and other fixes.
References
- Karl Johan Åström and Björn Wittenmark, Adaptive Control, second edition, Addison-Wesley 1995 (Dover reprint 2008), Chapter 3, Deterministic self-tuning regulators: the pole placement design with the Diophantine equation and the indirect self-tuning regulator
- Petros A. Ioannou and Jing Sun, Robust Adaptive Control, Prentice Hall 1996 (Dover reprint 2012), Chapter 7, Adaptive pole placement control: the indirect schemes and Section 7.6 (the stabilizability problem and its solution by projection)
- P. E. Wellstead, D. Prager and P. Zanker, Pole assignment self-tuning regulator, Proceedings of the IEE 126(8), 1979, pages 781 to 787
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 G5MEWV Edit this page History Report an error Markdown