Algorithmcore
Reduced-order observer
Also called minimal-order observer, Luenberger reduced-order observer.
Estimates only the part of the state that the outputs do not measure, with an observer of order n minus the number of outputs.
- Solves
- State estimation
- Time
- O(n^3 + p (n - p)^4 + N n (n + m)) worst
- Space
- O(n^2) 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, Bhaskar Gopinath, 1964
A reduced-order observer estimates the state of , when has full row rank. The outputs already give independent combinations of the state without error, so the observer has only states. It is also called a minimal-order observer. The Luenberger observer of full order estimates all states and filters the measured ones too. The reduced-order observer trusts the measurement and passes it directly to the estimate. Both are deterministic: for noisy outputs, the Kalman filter is the usual choice. The state observer page defines observers in general.
In plain words
A machine has some quantities that sensors read directly and others that no sensor reads. A full observer estimates all of them, even the ones that are measured. A reduced-order observer does not. It takes the measured quantities as they are and builds a small model only for the missing ones. It watches how the measured quantities change, because that change depends on the missing quantities, and it corrects its guess from that. A trick in the design avoids taking the rate of change of a noisy signal. The result is a smaller observer that needs less computation. The price is that sensor noise goes straight into the estimate, with no smoothing.
The problem
Input: , , with , and a monic real polynomial of degree . Output: matrices and such that the system
gives for every initial state and every input, with . A solution exists for every if and only if is observable. In discrete time the observer is with the same matrices, and must be Schur.
The algorithm
REDUCED-ORDER-OBSERVER(A, B, C, alpha)- 1
V ← unit rows that complete the rows of C to a basis; T ← [C; V] - 2
[A11 A12; A21 A22] ← T A T^(-1); [B1; B2] ← T B ▷ split after p rows and columns - 3
L ← PLACE(A22^T, A12^T, alpha)^T ▷ fails if (C, A) is not observable - 4
F ← A22 - L A12; G ← F L + A21 - L A11; H ← B2 - L B1 - 5
return F, G, H, L, T^(-1) UPDATE(z, u, y)- 6
z' ← F z + G y + H u ▷ derivative, or next value in discrete time - 7
x_hat ← T^(-1) [y; z + L y]
Line L1 picks new coordinates : the first are the outputs, and holds other coordinates. Line L2 writes the system in these coordinates:
The second equation is a system with state and known inputs and . The first equation says that is a measured output of it. An observer for with this output would need . The variable removes the derivative: the term cancels, and line L4 collects what is left. Line L3 is pole placement for the dual pair, as in the Luenberger observer. The implementation uses the same PLACE routine: Heymann's lemma in the form of Hautus, then Ackermann's formula.
Example
Double integrator. A cart has position and velocity , with , . The position is measured. Here , , , , , , . For the observer pole , , and gives . Line L4 gives
The observer is one equation:
To check it, let . Then , so obeys , and . The position estimate is itself, with no error. A full-order observer for the same cart has two states.
Deadbeat in discrete time. With , is nilpotent and the estimate is exact after samples. For the sampled cart, one sample is enough, against two for the full-order deadbeat observer.
Correctness
Let be the lower part of and . Then
Substitute : . So obeys the same equation as , and obeys . The estimate error is . Line L3 makes , which is possible for every because is observable when is. The full proof is in proofs/correctness.md. The tests check that the estimate error equals exactly in rational arithmetic, that a simulated continuous observer follows , and that the deadbeat version is exact after steps.
Proof: The reduced-order observer has the error T^(-1) [0; e] with e' = F e, and F gets the chosen characteristic polynomialfull
Let , and with , and let be a monic real polynomial of degree .
Lemma 1: the coordinates
Line L1 returns invertible, and in the coordinates the system is
with the blocks of line L2.
Proof. The loop adds the unit row when it is independent of the rows already chosen. The unit rows span , so after the loop the chosen rows span ; there are of them and they are independent, so is invertible. Let . Then , and the first entries of are . Splitting and after rows and columns gives the two equations.
Lemma 2: the error equation
Let be any matrix, and let be as in line L4. Let solve , and let . Then satisfies , and .
Proof. Let . By Lemma 1,
Substitute :
Subtracting the equation of gives . Finally and , so .
In discrete time the same algebra with and in place of and gives . The derivative never appears in the observer, because the term in was replaced by its value from the model.
Lemma 3: observability is inherited
If is observable, then is observable.
Proof. Observability does not change under a change of coordinates, so is observable. Suppose is not observable. By the Popov-Belevitch-Hautus test there are and with and . Then satisfies
so by the same test is not observable, a contradiction.
The converse also holds: if has an eigenvector with , then , and gives and . So the two pairs are observable together, and the algorithm raises an error exactly when is not observable.
Lemma 4: the eigenvalues of F
Line L3 returns with whenever is observable.
Proof. , and is controllable by duality. PLACE returns with ; this is proved on the Luenberger observer page (Heymann's lemma in the form of Hautus, then Ackermann's formula). With , transposition does not change the determinant.
Theorem
If and is observable, the algorithm returns with , and for every input and every initial value the estimate error is (in discrete time ). If the roots of are in the open left half plane (inside the unit circle), the error goes to 0. Otherwise the algorithm raises an error.
Proof. Lemmas 1 to 4. The checks for and come before line L1.
Remark
With , the Cayley-Hamilton theorem gives , so the estimate is exact from step on, for every input sequence. The tests check this in rational arithmetic.
Complexity
Lines L1 and L2 cost : rank tests to complete the basis, one inverse and two products. Line L3 is pole placement of size with columns, which costs with the simple rank tests of the implementation. Line L4 costs . Each update costs for line L6 and for line L7.
Properties
- Order . The observer has fewer states than the full-order observer, and its error has eigenvalues, all of which are free to choose.
- Direct feedthrough. The measured part of is itself. This is exact for exact data, but the noise of goes into without filtering, through and .
- No derivative. The observer uses and , not .
- Separation. Feedback gives the closed-loop eigenvalues of together with those of ; see separation principle.
- Exact arithmetic. With rational data, the implementation is exact.
Variants and improvements
- Other choices of . Any that makes invertible works, and the error eigenvalues do not depend on the choice. A with orthonormal rows that are orthogonal to the rows of is the numerically safer choice.
- Functional observers. If only is needed, for feedback, an observer of even lower order can estimate directly. Luenberger's 1971 tutorial discusses such observers.
- Unknown inputs. If some inputs are not measured, see unknown input observer.
- Noisy outputs. If the measured outputs are noisy, a full-order Kalman filter smooths them, while the reduced-order observer does not.
When to use it
Use a reduced-order observer when some outputs are accurate, the computing budget is small, and the model is good: for example, with an encoder that measures position precisely, to estimate the velocity of a motor. Use the full-order Luenberger observer or a Kalman filter when the outputs are noisy.
Pitfalls
- Noise in the estimate. Large amplifies the noise of in directly. Check the gain from to at high frequency.
- Rank of . If does not have full row rank, remove dependent outputs first.
- Unobservable modes. If is not observable, is not observable either, and some eigenvalues of are fixed.
- Model errors. The cancellation that removes uses the model; a wrong or gives a bias.
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()
reduced_order_observer.py 161 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reduced-order-observer/. The authors are listed in prov/3BXD4W.jsonl.
"""Reduced-order (minimal-order) observer for x' = A x + B u, y = C x.
C is p by n with full row rank p < n. The outputs give p combinations of
the state exactly, so only n - p numbers are estimated. In the coordinates
T x = [y; w], with T = [C; V],
y' = A11 y + A12 w + B1 u,
w' = A21 y + A22 w + B2 u.
The observer state z estimates w - L y:
z' = F z + G y + H u, w_hat = z + L y, x_hat = T^(-1) [y; w_hat],
F = A22 - L A12, G = F L + A21 - L A11, H = B2 - L B1.
Its error w - w_hat obeys e' = F e, and L places the eigenvalues of F.
(A12, A22) is observable if (C, A) is, so this is always possible then.
The same formulas hold in discrete time (z_(k+1) = F z_k + G y_k + H u_k).
Exact (Fraction) for int and Fraction data.
"""
from fractions import Fraction
from ctlmat import add, inv, matvec, mul, solve, sub, transpose
__all__ = ["place", "reduced_order_observer", "observer_rhs", "observer_step", "estimate"]
def _rank(vectors, tol):
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 = 1 if exact else max([abs(x) for r in rows for x in r] + [1.0])
rank = 0
for c in range(len(rows[0])):
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])
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 with det(s I - (A - B K)) = p(s); Heymann's lemma, then Ackermann.
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 = next((j for j in range(m) if _rank([cols[j]], tol) == 1), None)
if lead is None:
raise ValueError("the pair is not controllable (B = 0)")
xs, us = [cols[lead]], []
while len(xs) < n:
ax = matvec(A, xs[-1])
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):
break
else:
raise ValueError("the pair is not controllable")
u = [0] * m
if j is not None:
u[j] = 1
us.append(u)
xs.append(cand)
us.append([0] * m)
F = transpose(solve(xs, us))
AF = add(A, mul(B, F))
k1 = _ackermann(AF, cols[lead], p)
return [[-F[j][k] + (k1[k] if j == lead else 0) for k in range(n)] for j in range(m)]
def reduced_order_observer(A, B, C, alpha, tol=1e-10):
"""Return (F, G, H, L, Tinv) of the reduced-order observer.
alpha is the monic characteristic polynomial wanted for F, of degree
n - p. Raises ValueError if C does not have full row rank p < n or if
(C, A) is not observable.
"""
n, p = len(A), len(C)
if _rank(C, tol) != p:
raise ValueError("C must have full row rank")
if p >= n:
raise ValueError("p < n is needed; for p = n, x = C^(-1) y")
V = []
for i in range(n): # @line L1
e = [1 if j == i else 0 for j in range(n)]
if _rank(C + V + [e], tol) > p + len(V):
V.append(e)
T = [list(r) for r in C] + V
Tinv = inv(T)
Ab = mul(mul(T, A), Tinv) # @line L2
Bb = mul(T, B) if B is not None else None
A11 = [r[:p] for r in Ab[:p]]
A12 = [r[p:] for r in Ab[:p]]
A21 = [r[:p] for r in Ab[p:]]
A22 = [r[p:] for r in Ab[p:]]
try:
L = transpose(place(transpose(A22), transpose(A12), alpha, tol)) # @line L3
except ValueError:
raise ValueError("(C, A) is not observable") from None
F = sub(A22, mul(L, A12)) # @line L4
G = add(mul(F, L), sub(A21, mul(L, A11)))
H = None
if Bb is not None:
H = sub(Bb[p:], mul(L, Bb[:p]))
return F, G, H, L, Tinv # @line L5
def observer_rhs(F, G, H):
"""Return f(t, z, (u, y)) = F z + G y + H u."""
def f(t, z, uy):
u, y = uy
out = [a + b for a, b in zip(matvec(F, z), matvec(G, y))] # @line L6
if H is not None and u is not None:
out = [a + b for a, b in zip(out, matvec(H, u))]
return out
return f
def observer_step(F, G, H, z, u, y):
"""Return the discrete-time update F z + G y + H u."""
return observer_rhs(F, G, H)(0, z, (u, y))
def estimate(L, Tinv, z, y):
"""Return x_hat = T^(-1) [y; z + L y]."""
w = [a + b for a, b in zip(z, matvec(L, y))]
return matvec(Tinv, list(y) + w) # @line L7
test_reduced_order_observer.py 155 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/reduced-order-observer/. The authors are listed in prov/3BXD4W.jsonl.
import math
import random
from fractions import Fraction
import pytest
import ctlmat as cm
from ctlsim import simulate, simulate_discrete
from reduced_order_observer import estimate, observer_rhs, observer_step, place, reduced_order_observer
def poly_from_roots(roots):
p = [1]
for r in roots:
p = cm.polymul(p, [1, -r])
return p
def rank(rows):
R = [[Fraction(v) for v in r] for r in rows]
rk = 0
for c in range(len(R[0]) if R else 0):
piv = next((i for i in range(rk, len(R)) if R[i][c] != 0), None)
if piv is None:
continue
R[rk], R[piv] = R[piv], R[rk]
for i in range(len(R)):
if i != rk and R[i][c] != 0:
f = R[i][c] / R[rk][c]
R[i] = [a - f * b for a, b in zip(R[i], R[rk])]
rk += 1
return rk
def observable(A, C):
rows, M = [], [list(r) for r in C]
for _ in range(len(A)):
rows += M
M = cm.mul(M, A)
return rank(rows) == len(A)
def rand_system(rng, n, p, m=1):
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)]
B = [[rng.randint(-2, 2) for _ in range(m)] for _ in range(n)]
if rank(C) == p and observable(A, C):
return A, B, C
def test_double_integrator():
A = [[0, 1], [0, 0]]
B = [[0], [1]]
C = [[1, 0]]
F, G, H, L, Tinv = reduced_order_observer(A, B, C, [1, 3])
assert (F, G, H, L) == ([[-3]], [[-9]], [[1]], [[3]])
assert Tinv == cm.eye(2)
def test_eigenvalues_of_F_exact():
rng = random.Random(4)
for n, p in [(3, 1), (3, 2), (4, 1), (4, 2), (5, 2), (5, 3)]:
for _ in range(3):
A, B, C = rand_system(rng, n, p)
alpha = poly_from_roots([rng.randint(-5, -1) for _ in range(n - p)])
F, G, H, L, Tinv = reduced_order_observer(A, B, C, alpha)
assert len(F) == n - p
assert cm.charpoly(F) == alpha
def test_discrete_error_is_F_power_exact():
rng = random.Random(5)
for n, p in [(3, 1), (4, 2), (5, 2)]:
A, B, C = rand_system(rng, n, p)
alpha = poly_from_roots([Fraction(rng.randint(-3, 3), 4) for _ in range(n - p)])
F, G, H, L, Tinv = reduced_order_observer(A, B, C, alpha)
T = cm.inv(Tinv)
us = [[Fraction(rng.randint(-5, 5), 3)] for _ in range(8)]
x = [Fraction(rng.randint(-4, 4)) for _ in range(n)]
z = [0] * (n - p)
w0 = cm.matvec(T, x)[p:]
e0 = [a - b for a, b in zip(w0, cm.matvec(L, cm.matvec(C, x)))] # z_true(0) - z(0)
for k in range(8):
y = cm.matvec(C, x)
xh = estimate(L, Tinv, z, y)
err = [a - b for a, b in zip(x, xh)]
want = cm.matvec(Tinv, [0] * p + cm.matvec(cm.mat_power(F, k), e0))
assert err == want
assert cm.matvec(C, xh) == y # the measured part is exact
z = observer_step(F, G, H, z, us[k], y)
x = [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, us[k]))]
def test_deadbeat_reduced_observer():
rng = random.Random(6)
for n, p in [(3, 1), (4, 2), (5, 3)]:
A, B, C = rand_system(rng, n, p)
F, G, H, L, Tinv = reduced_order_observer(A, B, C, [1] + [0] * (n - p))
us = [[rng.randint(-5, 5)] for _ in range(n)]
def step(k, s, u):
x, z = s[:n], s[n:]
xn = [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]
return xn + observer_step(F, G, H, z, u, cm.matvec(C, x))
x0 = [rng.randint(-4, 4) for _ in range(n)]
ss, _ = simulate_discrete(step, x0 + [0] * (n - p), n, control=lambda k, s: us[k])
for k in range(n - p, n + 1):
x, z = ss[k][:n], ss[k][n:]
assert estimate(L, Tinv, z, cm.matvec(C, x)) == x
def test_continuous_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, 1.0, 0.0]]
F, G, H, L, Tinv = reduced_order_observer(A, B, C, poly_from_roots([-2.0, -3.0]))
T = cm.inv(Tinv)
n, p = 3, 1
obs = observer_rhs(F, G, H)
def f(t, s, u):
x, z = s[:n], s[n:]
dx = [a + b for a, b in zip(cm.matvec(A, x), cm.matvec(B, u))]
return dx + obs(t, z, (u, cm.matvec(C, x)))
x0 = [1.0, -0.5, 0.25]
ts, ss, _ = simulate(f, x0 + [0.0, 0.0], 0.0, 4.0, 0.001, control=lambda t, s: [math.cos(2 * t)])
e0 = [a - b for a, b in zip(cm.matvec(T, x0)[p:], cm.matvec(L, cm.matvec(C, x0)))]
for k in (1000, 2000, 4000):
x, z = ss[k][:n], ss[k][n:]
xh = estimate(L, Tinv, z, cm.matvec(C, x))
err = [a - b for a, b in zip(x, xh)]
want = cm.matvec(Tinv, [0.0] + cm.matvec(cm.expm(cm.scale(ts[k], F)), e0))
assert max(abs(a - b) for a, b in zip(err, want)) < 1e-9
def test_place_multi_input():
A = [[0, 1, 0], [0, 0, 1], [1, 0, 0]]
B = [[1, 0], [0, 0], [0, 1]]
K = place(A, B, [1, 6, 11, 6])
assert cm.charpoly(cm.sub(A, cm.mul(B, K))) == [1, 6, 11, 6]
def test_rejections():
with pytest.raises(ValueError): # C rank deficient
reduced_order_observer([[0, 1], [0, 0]], [[0], [1]], [[1, 0], [2, 0]], [1])
with pytest.raises(ValueError): # p = n
reduced_order_observer([[0, 1], [0, 0]], [[0], [1]], [[1, 0], [0, 1]], [1])
with pytest.raises(ValueError): # unobservable
reduced_order_observer([[1, 0], [0, 2]], [[1], [1]], [[1, 0]], [1, 3])
History
Luenberger's papers of 1964 and 1966 showed that the measured outputs reduce the order of the observer that is needed to reconstruct the state. Gopinath (1971) gave the construction in the coordinates with the gain on the unmeasured part, which is the form on this page. Luenberger's tutorial of 1971 gave an account of both the full-order and the reduced-order observer.
References
- David G. Luenberger, Observing the state of a linear system, IEEE Transactions on Military Electronics 8(2), 74-80, 1964, the observers of reduced dynamic order, n minus the number of outputs
- David G. Luenberger, Observers for multivariable systems, IEEE Transactions on Automatic Control 11(2), 190-197, 1966, the observers of reduced order for systems with several outputs
- Bhaskar Gopinath, On the control of linear multiple input-output systems, Bell System Technical Journal 50(3), 1063-1081, 1971, the construction of the reduced-order observer from a partition of the state into measured and unmeasured parts
- David G. Luenberger, An introduction to observers, IEEE Transactions on Automatic Control 16(6), 596-602, 1971, the reduced-order observer and its error equation
- Chi-Tsong Chen, Linear System Theory and Design, third edition, Oxford University Press, 1999, Section 8.4.1, Reduced-Dimensional State Estimator
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 3BXD4W Edit this page History Report an error Markdown