Algorithmcore
Luenberger observer
Also called full-order observer, Luenberger state observer.
Estimates the state by a copy of the model corrected by L times the output error, with error dynamics A - LC placed by the choice of L.
- Solves
- State estimation
- Time
- O(p n^4 + N n (n + m + p)) worst
- Space
- O(n (n + p)) extra
- Where
- N = the number of updates; m = the number of inputs; n = the number of states; p = the number of outputs
- Model
- Real RAM
- Properties
- deterministicexactonlinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- David G. Luenberger, 1964
A Luenberger observer estimates the state of a linear system , from the input and the measured output . It runs a copy of the model and corrects it with a gain times the output error:
The error obeys , whatever the input is. The design task is to choose so that is Hurwitz with chosen eigenvalues. This is the pole placement problem for the dual pair , and it has a solution for all eigenvalues if and only if is observable. This page gives the full-order observer, which estimates all states. The state observer page defines observers in general. The reduced-order observer estimates only the states that the output does not give directly. The unknown input observer and the disturbance observer handle inputs that are not measured. The high-gain observer and the sliding mode observer are for nonlinear systems. The Kalman-Bucy filter has the same structure, but it gets from noise statistics, while the observer on this page uses no noise model.
In plain words
Some quantities of a machine can be measured, and some cannot. The observer is a computer model of the machine that gets the same commands as the machine. The model would drift away from the real machine if its starting point were wrong. So the observer compares the measured output of the machine with the output that the model predicts. It pushes the model toward the machine in proportion to the difference. The designer chooses how hard to push. With a good choice, the error of the model dies out at a chosen speed, whatever commands the machine gets. This is possible only when the measurements together show every part of the state over time. Pushing very hard makes the error die out fast, but it also passes more sensor noise into the estimate.
The problem
Input: , and a monic real polynomial , usually for chosen observer poles in conjugate pairs. Output: with , and the observer that uses it. A solution exists for every if and only if is observable. If is only detectable, a stable still exists, but the unobservable eigenvalues cannot be moved.
In discrete time the model is , , the observer is , and must be Schur. The design of is the same.
The algorithm
LUENBERGER-GAIN(A, C, alpha)- 1
K_d ← PLACE(A^T, C^T, alpha) ▷ fails if (C, A) is not observable - 2
return L ← K_d^T ▷ A - L C = (A^T - C^T K_d)^T LUENBERGER-UPDATE(xhat, u, y)- 3
r ← y - C xhat ▷ output error, p numbers - 4
return A xhat + B u + L r ▷ the derivative, or the next estimate in discrete time
Line L1 solves a state feedback problem. The matrices and are transposes of each other, so they have the same characteristic polynomial, and is observable if and only if is controllable. With one output, PLACE is Ackermann's formula. With several outputs, the implementation uses the construction of Hautus for Heymann's lemma: it starts with one column of and builds vectors , with equal to or a unit vector, so that each new vector is independent of the earlier ones. The feedback with makes controllable, and Ackermann's formula then places the poles of this single-input pair. The pole placement theorem page proves that this construction always succeeds for a controllable pair. Lines L3 and L4 run at each time step, with an ODE solver in continuous time or as a plain recursion in discrete time.
Example
Double integrator. A cart with position and velocity has , , and only the position is measured, . For the observer poles and , . With ,
so . The observer is , . If the observer starts at the true position but with a velocity error of 1, the error is
whatever the input is:
| 0 | 0.5 | 1 | 2 | 3 | |
|---|---|---|---|---|---|
| position error | 0 | 0.145 | 0.086 | 0.016 | 0.002 |
| velocity error | 1 | 0.657 | 0.306 | 0.050 | 0.007 |
Deadbeat observer. For the zero-order hold model of the same cart with period , . The polynomial gives , and . The estimate is then exact after two samples, for every initial error and every input sequence. This is the dual of deadbeat control.
Two outputs. For and with the poles , the implementation starts from the first output, which alone already makes the pair observable, and returns . This is one valid gain among many. Robust pole placement uses the freedom to get a better conditioned .
Correctness
The error equation follows by subtraction: . The input cancels, so the error is for every input, and it goes to 0 if and only if is Hurwitz. The gain of line L2 gives , because a matrix and its transpose have the same determinant. The correctness of PLACE is the pole placement theorem, proved constructively by the same steps. The full proof is in proofs/correctness.md. The tests check the exact characteristic polynomial for random systems with up to 3 outputs, the error of a simulated observer against for an unstable plant, and the exact convergence of a deadbeat observer in steps.
Proof: The Luenberger observer error obeys e' = (A - LC) e, and the computed L gives A - LC the chosen characteristic polynomialfull
Let , , , and let be a monic real polynomial of degree .
Lemma 1: the error equation
Let solve , , and let solve with the same input . Then satisfies , so . In discrete time, and .
Proof. Subtract the two equations: , because the terms cancel. The solution of a linear system with constant matrix is given by the matrix exponential. The discrete case is the same subtraction.
So for every if and only if is Hurwitz (Schur in discrete time), and the input plays no role.
Lemma 2: duality
, and is observable if and only if is controllable.
Proof. , and a matrix and its transpose have the same determinant, so the same characteristic polynomial. The observability matrix of has the rows ; its transpose has the columns , which is the controllability matrix of . Both have the same rank.
So lines L1 and L2 are correct if PLACE is correct: if gives , then gives .
Lemma 3: the construction of Hautus
Let be controllable with , and let be a nonzero column of . Set . For , if , set ; otherwise choose a column and set . Put . Then the choice is always possible, are independent, and the matrix with for and makes controllable.
Proof. Suppose that for some neither choice works: and every column of is in . For , , and , so is -invariant. It contains , so it contains for all , so it contains the controllable subspace, which is . This contradicts . When a choice works, : either and , or and . So the vectors are independent, is invertible, and with is the unique matrix with the stated values. Then for , so , and the controllability matrix of is , which is invertible.
The implementation tries first and then the columns in order, which is one valid choice. It tests membership in by a rank computation, exactly for rational data. Note that exists, because would make the pair uncontrollable for .
Lemma 4: PLACE is correct
Let be controllable, and let , be as in Lemma 3. Let be the Ackermann gain for the single-input pair and . Then satisfies .
Proof. . By Lemma 3, is controllable, and the Ackermann formula page proves that gives this matrix the characteristic polynomial .
If PLACE cannot find a nonzero column or a new vector, Lemma 3 shows that the pair is not controllable, so by Lemma 2 is not observable, and the error raised is correct. If the pair is controllable, Lemma 3 shows that no failure occurs.
Theorem
If is observable, the algorithm returns with , and the observer of lines L3 and L4 has the error for every input. If all roots of have negative real parts (modulus less than 1 in discrete time), the error goes to 0 for every initial estimate. If is not observable, the algorithm raises an error.
Proof. Lemmas 1, 2 and 4.
Remarks
- Deadbeat observer. With , the Cayley-Hamilton theorem gives , so in discrete time for every and every input sequence. The tests check this exactly in rational arithmetic.
- Detectable but not observable. By the Kalman decomposition, the unobservable eigenvalues are eigenvalues of for every . The algorithm raises an error in this case, although a stable may exist if those eigenvalues are stable.
Complexity
PLACE builds vectors. For each new vector it tests at most candidates, and each test is a rank computation on at most vectors of length , which costs . This gives for the gain. A rank test that updates one elimination instead of starting again brings this down to , and the solve for and Ackermann's formula cost . Each update of lines L3 and L4 costs . An RK4 step calls it four times.
Properties
- The error is independent of the input. Feedback therefore does not change the error dynamics, which is the basis of the separation principle.
- No noise model. The observer assumes exact measurements and an exact model. With noise, a fast observer passes more noise into ; the Kalman filter chooses to balance this.
- Exact arithmetic. With rational data the implementation is exact, so the characteristic polynomial matches exactly.
- Non-uniqueness. With one output, is unique for a given . With several outputs, a family of gains gives the same eigenvalues but different eigenvectors.
- Peaking. A fast observer can have a large transient error before the error decays, because is far from normal for large . The high-gain observer page studies this effect.
Variants and improvements
- Reduced-order observer. When outputs are measured exactly, only states need estimating. See reduced-order observer.
- Kalman filter. The gain that minimizes the error covariance for white process and measurement noise. See Kalman filter and Kalman-Bucy filter.
- Observers for unknown inputs. If part of the input is not measured, an unknown input observer decouples the error from it, and a disturbance observer estimates it.
- Current observer. In discrete time, the estimate of can use itself, not only . This removes one sample of delay from the estimate.
- Nonlinear systems. Copy the nonlinear model and add ; the high-gain observer and the sliding mode observer give conditions under which this works.
When to use it
Use the full-order observer when the model is known well, the noise is small or not characterized, and a simple, fixed linear estimator is wanted, for example for state feedback in an embedded controller. Choose the observer poles a few times faster than the controller poles, but not so fast that sensor noise dominates. If the outputs are exact and the computing budget is tight, use the reduced-order observer. If noise statistics are known, use the Kalman filter.
Pitfalls
- Unobservable modes. If is not observable, PLACE fails. If the unobservable modes are stable, design for the observable part only; if one is unstable, no observer converges.
- Too fast poles. Large amplifies sensor noise and causes peaking. Check the error transient and the noise gain, not only the eigenvalues.
- Model mismatch. The error equation holds only for the exact model. A wrong or gives a bias that the input drives.
- Different inputs. The observer must get the same input as the plant. If the actuator saturates, feed the saturated value to the observer; see anti-windup.
- Numerical conditioning. Ackermann's formula is unstable for larger . For more than a few states use a numerically stable method on .
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()
ctlsim.py 120 lines
# SPDX-License-Identifier: MIT
# Shared helper of the control pages of https://algorithm.tamnd.com/. The authors are listed in prov/.
"""Fixed step simulation for the control pages.
Conventions:
- A continuous-time system is a function f(t, x, u) that returns x' as a
flat list. x is a flat list. u is whatever the control returns (a flat
list, a scalar, or None when there is no control).
- A discrete-time system is a function F(k, x, u) that returns x_(k+1).
- The integrator is the classical 4th order Runge-Kutta method with a fixed
step dt. The input is held constant over each step.
- Time t_k = t0 + k dt is computed by multiplication, not by summation.
- The number of steps round((t1 - t0) / dt) and the hold ratio
round(hold / dt) must match the real ratios within 1e-9 (relative), or
ValueError is raised.
This file holds no controller or observer of a control page.
"""
__all__ = ["rk4_step", "simulate", "simulate_discrete", "lti"]
def _axpy(a, x, y):
return [yi + a * xi for xi, yi in zip(x, y)]
def rk4_step(f, t, x, u, dt):
"""Return x(t + dt) after one RK4 step of x' = f(t, x, u), u held constant."""
k1 = f(t, x, u)
k2 = f(t + dt / 2, _axpy(dt / 2, k1, x), u)
k3 = f(t + dt / 2, _axpy(dt / 2, k2, x), u)
k4 = f(t + dt, _axpy(dt, k3, x), u)
return [xi + dt / 6 * (a + 2 * b + 2 * c + d) for xi, a, b, c, d in zip(x, k1, k2, k3, k4)]
def _ratio(num, den, what):
r = round(num / den)
if abs(r * den - num) > 1e-9 * max(abs(num), abs(den)):
raise ValueError(what + " is not an integer multiple of dt")
return r
def simulate(f, x0, t0, t1, dt, control=None, hold=None):
"""Simulate x' = f(t, x, u) from x(t0) = x0 to t1 with RK4 and step dt.
control(t, x) gives the input. It is called at each sampling instant
t0 + j hold, and its value is held (zero-order hold) until the next
instant. hold must be an integer multiple of dt; hold = None means
hold = dt. With control = None the input is None.
Returns (ts, xs, us): ts has N + 1 times, xs the N + 1 states, and us the
N inputs, where us[k] acts on [ts[k], ts[k + 1]].
"""
if dt <= 0:
raise ValueError("dt must be positive")
n_steps = _ratio(t1 - t0, dt, "t1 - t0")
if n_steps < 0:
raise ValueError("t1 is before t0")
r = 1 if hold is None else _ratio(hold, dt, "hold")
if r < 1:
raise ValueError("hold must be at least dt")
x = list(x0)
ts = [t0]
xs = [list(x)]
us = []
u = None
for k in range(n_steps):
t = t0 + k * dt
if control is not None and k % r == 0:
u = control(t, list(x))
x = rk4_step(f, t, x, u, dt)
ts.append(t0 + (k + 1) * dt)
xs.append(x)
us.append(u)
return ts, xs, us
def simulate_discrete(F, x0, N, control=None):
"""Run x_(k+1) = F(k, x_k, u_k) for k = 0, ..., N - 1.
u_k = control(k, x_k), or None if control is None. Returns (xs, us) with
N + 1 states and N inputs. Exact if F and control are exact.
"""
x = list(x0)
xs = [list(x)]
us = []
for k in range(N):
u = control(k, list(x)) if control is not None else None
x = list(F(k, x, u))
xs.append(x)
us.append(u)
return xs, us
def lti(A, B=None):
"""Return f(t, x, u) = A x + B u for the system x' = A x + B u.
u may be a flat list, a scalar (one input) or None (zero input). B may
be None for a system with no input.
"""
def f(t, x, u):
dx = [sum(a * xi for a, xi in zip(row, x)) for row in A]
if B is None or u is None:
return dx
uu = u if isinstance(u, (list, tuple)) else [u]
return [d + sum(b * ui for b, ui in zip(row, uu)) for d, row in zip(dx, B)]
return f
def _self_test():
import math
f = lti([[-1.0]])
_, xs, _ = simulate(f, [1.0], 0.0, 1.0, 0.01)
assert abs(xs[-1][0] - math.exp(-1.0)) < 1e-9
return True
if __name__ == "__main__":
_self_test()
luenberger_observer.py 146 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/luenberger-observer/. The authors are listed in prov/7T6PY4.jsonl.
"""Full-order Luenberger observer for x' = A x + B u, y = C x.
The observer is
xhat' = A xhat + B u + L (y - C xhat),
so the error e = x - xhat obeys e' = (A - L C) e, whatever u is. The gain L
places the eigenvalues of A - L C. It is the transpose of a state feedback
gain for the dual pair (A^T, C^T): A - L C = (A^T - C^T L^T)^T.
place() handles any number of inputs (here: outputs of the observed
system). It uses Heymann's lemma in the constructive form of Hautus (1977):
a feedback F and one input column b = B e_l make (A + B F, b) controllable,
and then Ackermann's formula places the poles of the single-input pair. The
result is one valid gain, not a well conditioned one; for that, see the
robust pole placement page.
The same formulas hold in discrete time, with
xhat_(k+1) = A xhat_k + B u_k + L (y_k - C xhat_k).
Exact (Fraction) for int and Fraction data.
"""
from fractions import Fraction
from ctlmat import matvec, solve, transpose
__all__ = ["place", "observer_gain", "observer_rhs", "observer_step"]
def _rank(vectors, tol):
"""Rank of a list of flat vectors (exact for int and Fraction data)."""
rows = [list(v) for v in vectors]
if not rows:
return 0
exact = all(isinstance(x, (int, Fraction)) for r in rows for x in r)
if exact:
rows = [[Fraction(x) for x in r] for r in rows]
big = max([abs(x) for r in rows for x in r] + [1.0]) if not exact else 1
rank = 0
ncol = len(rows[0])
for c in range(ncol):
p = max(range(rank, len(rows)), key=lambda i: abs(rows[i][c]), default=None)
if p is None:
break
if (rows[p][c] == 0) if exact else (abs(rows[p][c]) <= tol * big):
continue
rows[rank], rows[p] = rows[p], rows[rank]
for i in range(rank + 1, len(rows)):
f = rows[i][c] / rows[rank][c]
rows[i] = [a - f * b for a, b in zip(rows[i], rows[rank])]
rank += 1
return rank
def _ackermann(A, b, p):
n = len(A)
cols = [list(b)]
for _ in range(n - 1):
cols.append(matvec(A, cols[-1]))
try:
q = solve(cols, [0] * (n - 1) + [1]) # rows of W^T are the columns of W
except ValueError:
raise ValueError("the pair is not controllable") from None
At = transpose(A)
K = [0] * n
for c in p:
K = [x + c * y for x, y in zip(matvec(At, K), q)]
return K
def place(A, B, p, tol=1e-10):
"""Return K (m by n) with det(s I - (A - B K)) = p(s), p monic of degree n.
Raises ValueError if (A, B) is not controllable.
"""
n = len(A)
m = len(B[0])
if len(p) != n + 1 or p[0] != 1:
raise ValueError("p must be monic of degree n")
cols = [[B[i][j] for i in range(n)] for j in range(m)]
lead = None
for j in range(m):
if _rank([cols[j]], tol) == 1:
lead = j
break
if lead is None:
raise ValueError("the pair is not controllable (B = 0)")
# Hautus' construction: x_1 = b, x_(k+1) = A x_k + B u_k not in span(x_1..x_k).
xs = [cols[lead]]
us = []
while len(xs) < n:
ax = matvec(A, xs[-1])
chosen = None
for j in [None] + list(range(m)):
cand = ax if j is None else [a + c for a, c in zip(ax, cols[j])]
if _rank(xs + [cand], tol) > len(xs):
chosen = (j, cand)
break
if chosen is None:
raise ValueError("the pair is not controllable")
j, cand = chosen
u = [0] * m
if j is not None:
u[j] = 1
us.append(u)
xs.append(cand)
us.append([0] * m)
# F x_k = u_k for all k, so F = U X^(-1): solve X^T F^T = U^T.
Ft = solve(xs, us) # xs as rows is X^T, us as rows is U^T
F = transpose(Ft)
AF = [[A[i][k] + sum(B[i][j] * F[j][k] for j in range(m)) for k in range(n)] for i in range(n)]
k1 = _ackermann(AF, cols[lead], p)
# A - B K = A + B F - b k1 with K = -F + e_lead k1.
return [[-F[j][k] + (k1[k] if j == lead else 0) for k in range(n)] for j in range(m)]
def observer_gain(A, C, p, tol=1e-10):
"""Return L (n by p) with det(s I - (A - L C)) = p(s).
Raises ValueError if (C, A) is not observable.
"""
try:
Kd = place(transpose(A), transpose(C), p, tol) # @line L1
except ValueError:
raise ValueError("(C, A) is not observable") from None
return transpose(Kd) # @line L2
def observer_rhs(A, B, C, L):
"""Return f(t, xhat, (u, y)) = A xhat + B u + L (y - C xhat)."""
def f(t, xhat, uy):
u, y = uy
r = [yi - ci for yi, ci in zip(y, matvec(C, xhat))] # @line L3
out = matvec(A, xhat) # @line L4
if B is not None and u is not None:
out = [o + v for o, v in zip(out, matvec(B, u))]
return [o + v for o, v in zip(out, matvec(L, r))]
return f
def observer_step(A, B, C, L, xhat, u, y):
"""Return the discrete-time update A xhat + B u + L (y - C xhat)."""
return observer_rhs(A, B, C, L)(0, xhat, (u, y))
test_luenberger_observer.py 169 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/luenberger-observer/. The authors are listed in prov/7T6PY4.jsonl.
import math
import random
from fractions import Fraction
import pytest
import ctlmat as cm
from ctlsim import simulate, simulate_discrete
from luenberger_observer import observer_gain, observer_rhs, observer_step, place
def poly_from_roots(roots):
p = [1]
for r in roots:
p = cm.polymul(p, [1, -r])
return p
def obs_matrix_rank(A, C):
rows = []
M = [list(r) for r in C]
for _ in range(len(A)):
rows += M
M = cm.mul(M, A)
# rank of the stacked rows by exact elimination
R = [[Fraction(v) for v in r] for r in rows]
rank = 0
for c in range(len(A)):
piv = next((i for i in range(rank, len(R)) if R[i][c] != 0), None)
if piv is None:
continue
R[rank], R[piv] = R[piv], R[rank]
for i in range(len(R)):
if i != rank and R[i][c] != 0:
f = R[i][c] / R[rank][c]
R[i] = [a - f * b for a, b in zip(R[i], R[rank])]
rank += 1
return rank
def rand_observable(rng, n, p):
while True:
A = [[rng.randint(-3, 3) for _ in range(n)] for _ in range(n)]
C = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(p)]
if obs_matrix_rank(A, C) == n:
return A, C
def a_minus_lc(A, L, C):
return cm.sub(A, cm.mul(L, C))
def test_double_integrator():
A = [[0, 1], [0, 0]]
C = [[1, 0]]
L = observer_gain(A, C, [1, 5, 6])
assert L == [[5], [6]]
assert cm.charpoly(a_minus_lc(A, L, C)) == [1, 5, 6]
def test_random_exact_multi_output():
rng = random.Random(1)
for n, p in [(2, 1), (3, 1), (3, 2), (4, 2), (5, 3), (5, 1)]:
for _ in range(4):
A, C = rand_observable(rng, n, p)
roots = [rng.randint(-6, -1) for _ in range(n)]
poly = poly_from_roots(roots)
L = observer_gain(A, C, poly)
assert len(L) == n and len(L[0]) == p
assert cm.charpoly(a_minus_lc(A, L, C)) == poly
def test_place_multi_input_exact():
rng = random.Random(2)
for n, m in [(3, 2), (4, 3), (4, 2)]:
for _ in range(4):
At, Bt = rand_observable(rng, n, m)
A, B = cm.transpose(At), cm.transpose(Bt)
poly = poly_from_roots([rng.randint(-5, 0) for _ in range(n)])
K = place(A, B, poly)
assert cm.charpoly(cm.sub(A, cm.mul(B, K))) == poly
def test_error_follows_matrix_exponential():
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]]
C = [[1.0, 0.0, 0.0]]
L = observer_gain(A, C, poly_from_roots([-2.0, -3.0, -4.0]))
obs = observer_rhs(A, B, C, L)
n = 3
def f(t, z, u):
x, xh = z[:n], z[n:]
dx = [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]
return dx + obs(t, xh, (u, cm.matvec(C, x)))
x0 = [1.0, -0.5, 0.25]
ts, zs, _ = simulate(f, x0 + [0.0, 0.0, 0.0], 0.0, 6.0, 0.001, control=lambda t, z: [math.sin(3 * t)])
Acl = a_minus_lc(A, L, C)
for k in (500, 1500, 3000, 6000):
e = [a - b for a, b in zip(zs[k][:n], zs[k][n:])]
want = cm.matvec(cm.expm(cm.scale(ts[k], Acl)), x0)
assert max(abs(a - b) for a, b in zip(e, want)) < 1e-9
# the plant is unstable, but the estimation error goes to 0
e = [a - b for a, b in zip(zs[-1][:n], zs[-1][n:])]
assert cm.norm2(e) < 1e-3 * cm.norm2(x0)
assert cm.norm2(zs[-1][:n]) > 4 * cm.norm2(x0)
def test_discrete_deadbeat_observer_exact():
rng = random.Random(3)
for n, p in [(3, 1), (4, 2), (5, 2)]:
A, C = rand_observable(rng, n, p)
B = [[rng.randint(-2, 2)] for _ in range(n)]
L = observer_gain(A, C, [1] + [0] * n)
us = [[Fraction(rng.randint(-5, 5), rng.randint(1, 4))] for _ in range(n + 3)]
def F(k, z, u):
x, xh = z[:n], z[n:]
xn = [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]
return xn + observer_step(A, B, C, L, xh, u, cm.matvec(C, x))
x0 = [Fraction(rng.randint(-4, 4)) for _ in range(n)]
zs, _ = simulate_discrete(F, x0 + [0] * n, n + 3, control=lambda k, z: us[k])
for k in range(n, n + 4):
assert zs[k][:n] == zs[k][n:]
def test_error_does_not_depend_on_input():
A = [[1, 1], [0, 1]]
B = [[0], [1]]
C = [[1, 0]]
L = observer_gain(A, C, poly_from_roots([Fraction(1, 2), Fraction(-1, 3)]))
errs = []
for scale_u in (0, 1, -7):
x, xh = [3, -1], [0, 0]
run = []
for k in range(6):
u = [scale_u * (k * k - 2)]
y = cm.matvec(C, x)
xh = observer_step(A, B, C, L, xh, u, y)
x = [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]
run.append([a - b for a, b in zip(x, xh)])
errs.append(run)
assert errs[0] == errs[1] == errs[2]
def test_complex_poles_float():
A = [[0.0, 1.0, 0.0, 0.0], [-2.0, -0.1, 1.0, 0.0], [0.0, 0.0, 0.0, 1.0], [1.0, 0.0, -3.0, -0.2]]
C = [[1.0, 0.0, 0.0, 0.0], [0.0, 0.0, 1.0, 0.0]]
want = [complex(-1, 2), complex(-1, -2), -3.0, -4.0]
L = observer_gain(A, C, [c.real for c in poly_from_roots(want)])
got = cm.polyroots(cm.charpoly(a_minus_lc(A, L, C)))
for w in want:
assert min(abs(g - w) for g in got) < 1e-8
def test_rejects_unobservable_and_bad_polynomial():
A = [[1, 0], [0, 2]]
C = [[1, 0]]
with pytest.raises(ValueError):
observer_gain(A, C, [1, 3, 2])
with pytest.raises(ValueError):
observer_gain([[0, 1], [0, 0]], [[1, 0]], [1, 3])
with pytest.raises(ValueError):
place([[0, 1], [0, 0]], [[0], [0]], [1, 3, 2])
History
Luenberger introduced the observer in 1964, in a paper that showed how a linear system driven by the inputs and outputs of a plant can reconstruct its state, with an error that decays at a rate the designer chooses. His 1966 paper treated systems with several outputs, and his 1971 tutorial gave a short account of the identity observer and the reduced-order observer. The duality with state feedback, which turns the observer design into pole placement for , follows Kalman's duality between controllability and observability. The Kalman-Bucy filter of 1961 has the same structure and gets its gain from noise statistics.
References
- David G. Luenberger, Observing the state of a linear system, IEEE Transactions on Military Electronics 8(2), 74-80, 1964, the definition of an observer and the result that its error decays with eigenvalues that can be chosen
- David G. Luenberger, Observers for multivariable systems, IEEE Transactions on Automatic Control 11(2), 190-197, 1966, the design of observers for systems with several outputs
- David G. Luenberger, An introduction to observers, IEEE Transactions on Automatic Control 16(6), 596-602, 1971, the tutorial account of the identity observer and its error equation
- M. L. J. Hautus, A simple proof of Heymann's lemma, IEEE Transactions on Automatic Control 22(5), 885-886, 1977, the construction of a feedback that makes a multi-input pair controllable from one input, used here for several outputs
- Chi-Tsong Chen, Linear System Theory and Design, third edition, Oxford University Press, 1999, Section 8.4, State Estimator, and Section 8.7, State Estimators, Multivariable Case
- Karl J. Åström and Richard M. Murray, Feedback Systems, An Introduction for Scientists and Engineers, second edition, Princeton University Press, 2021, Chapter 8, Output Feedback, the section State Estimation
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 7T6PY4 Edit this page History Report an error Markdown