Algorithmadvanced
Unknown input observer
Also called UIO.
An observer whose error does not depend on some unmeasured inputs, under a rank condition on how those inputs enter.
- 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 known inputs; n = the number of states; p = the number of outputs
- Model
- Real RAM
- Properties
- deterministicexactonlinerecursive
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Mohamed Darouach, Michel Zasadzinski, Shi Jie Xu, 1994
An unknown input observer estimates the state of
where is measured and is not. Its error goes to 0 for every signal , with no model of at all. A Luenberger observer for the same system has the error equation , so drives the error and the estimate is biased. The unknown input observer makes the error equation by a projection that removes the direction before the correction. This is possible when , that is, when every unknown input shows up in the output at once, and the error can be made stable when the invariant zeros of are stable. The design on this page is the full-order observer of Darouach, Zasadzinski and Xu. A disturbance observer solves a different task: it estimates itself, usually in a limited frequency band, so that a controller can cancel it. The state observer page compares the observers of this area.
In plain words
A machine is pushed by forces that nobody measures, such as wind or load changes. An ordinary observer copies the machine's model, but its copy does not feel these forces, so its guess drifts away from the truth. An unknown input observer is built so that these forces cannot affect its error at all. It does this by using the sensors twice: once to correct the guess, and once to see in which way the unknown forces have just moved the machine, so that it can ignore that direction. This works only when the sensors see each unknown force at once, and when the machine has no hidden dynamics that the forces can excite without any trace in the output.
The problem
Input: , , , with , and a monic real polynomial of degree . Output: matrices such that the observer
has for every input and every unknown input , with .
Darouach, Zasadzinski and Xu showed that an observer of this form with a stable exists if and only if
- , and
- for all with .
The second condition says that has no invariant zeros in the closed right half plane. Condition 1 needs : there must be at least as many outputs as unknown inputs. All eigenvalues of can be chosen freely if and only if has no invariant zeros at all. This implementation covers that case and raises an error otherwise. In discrete time the observer is with the same matrices, and the zeros must lie inside the unit circle.
The algorithm
UIO(A, B, C, E, alpha)- 1
if rank(C E) < rank(E): fail ▷ some d is not seen in y at once - 2
H ← E ((C E)^T (C E))^(-1) (C E)^T ▷ then H C E = E - 3
T ← I - H C; A1 ← T A; G ← T B ▷ T E = 0 - 4
K1 ← PLACE(A1^T, C^T, alpha)^T ▷ fails if (A, E, C) has invariant zeros - 5
F ← A1 - K1 C; K ← K1 + F H - 6
return F, G, K, H UPDATE(z, u, y)- 7
z' ← F z + G u + K y ▷ derivative, or next value in discrete time - 8
x_hat ← z + H y
Line L2 uses the left inverse of , which exists by line L1, so and the matrix of line L3 annihilates . The observer state estimates , and the term adds back the part of that removes. Line L4 is the observer pole placement of the Luenberger observer applied to the pair : Heymann's lemma in the form of Hautus, then Ackermann's formula. Line L5 chooses so that the terms in cancel in the error equation.
Example
Take , two outputs and one unknown input that acts on the first state:
Here has rank 1, so line L1 passes, and lines L2 and L3 give
The system has no invariant zeros: a vector with is , and needs in the second row. So is observable. For the implementation returns
A simulation with , the unknown input plus a unit step at , the initial state and the estimates started at 0 gives the largest error over the three states below. The Luenberger observer has the same poles, from .
| 1 | 2 | 3 | 4 | 6 | |
|---|---|---|---|---|---|
| unknown input observer | 0.048 | 0.0050 | 0.00057 | 7.1e-5 | 1.2e-6 |
| Luenberger observer | 0.070 | 0.68 | 0.69 | 0.55 | 0.64 |
The error of the unknown input observer follows exactly, whatever does. The Luenberger observer keeps an error of the size of .
A system with a zero. Change to . Now satisfies and , so is an invariant zero. Then and , so 1 is an eigenvalue of for every , and no stable unknown input observer exists. The input with gives and : a growing state that leaves no trace in the output.
Correctness
Let . Then
Line L3 gives and , so and drop out. With , . Line L5 gives , so . Line L4 gives . The eigenvalues of that no moves are the invariant zeros of , which is why the second existence condition appears. The full proof is in proofs/correctness.md. The tests check , and the exact error for random discrete-time systems driven by random unknown inputs, and the fixed eigenvalue at an invariant zero.
Proof: The unknown input observer has the error e' = F e for every unknown input, and its fixed eigenvalues are the invariant zerosfull
Let , , and with . The system is , .
Lemma 1: the projection
If , then is invertible, the matrix of line L2 satisfies , and satisfies . If , no matrix with exists.
Proof. has full column rank, so is a positive definite matrix and satisfies . Then and . Conversely, gives .
So line L1 rejects exactly the systems for which no observer of this form can cancel : any observer whose error is independent of needs , as the note after Lemma 2 shows.
Lemma 2: the error equation
Let be as in lines L3 and L5, with any . Then satisfies for all inputs and . In discrete time, .
Proof. . Differentiate and use the observer equation:
By Lemma 1, , and , so the terms in and vanish. Substitute :
Now , using . So . In discrete time the same computation with and gives .
The term is the only place where can enter. If , then a in a direction with changes directly, so the error depends on .
Lemma 3: the fixed eigenvalues are the invariant zeros
Let and . For , there is with and if and only if there are and with
that is, if and only if is an invariant zero of .
Proof. Suppose and . Then , so with . With this is the zero equation. Conversely, suppose and with . Apply : . Since , , so .
By the Popov-Belevitch-Hautus test, is observable if and only if no such exists. For every , an unobservable eigenvalue of is an eigenvalue of , since . So the invariant zeros of are eigenvalues of for every gain, and the other eigenvalues can be placed freely.
Lemma 4: the placement
If has no invariant zeros, line L4 returns with . Otherwise line L4 raises an error.
Proof. By Lemma 3 and the test cited there, is observable exactly when there are no invariant zeros, and by duality this holds exactly when is controllable. PLACE is correct for controllable pairs and raises an error for the others, as proved on the Luenberger observer page. Transposition does not change the characteristic polynomial.
Theorem
If and has no invariant zeros, the algorithm returns with , and the estimate has the error for all inputs and (in discrete time ). If the rank condition fails or an invariant zero exists, the algorithm raises an error.
Proof. Lemmas 1, 2 and 4.
Remarks
- The general existence result. If invariant zeros exist but all lie in the open left half plane, Lemma 3 shows that a stable still exists: put in the form of the Kalman decomposition and place only the observable eigenvalues. A zero with is an eigenvalue of every , so no stable observer of this form exists. Together with Lemma 1 this gives the two conditions of Darouach, Zasadzinski and Xu.
- Deadbeat. With in discrete time, by the Cayley-Hamilton theorem, and the estimate is exact after steps for every unknown input sequence. The tests check this in rational arithmetic.
Complexity
Lines L1 to L3 cost , because has only columns. Line L4 is pole placement of size with columns, with the simple rank tests of the implementation. Each update costs .
Properties
- Exact decoupling. The error does not depend on at all, for any signal: steps, ramps, or noise without a model.
- Full order. The observer has states, although the part of the estimate comes from directly.
- Direct feedthrough. The term passes measurement noise into without filtering.
- Estimating . If has full column rank, can be recovered from and by once the error has decayed. This needs a derivative of .
- Relation to zeros. Strong detectability in the sense of Hautus is the condition that the state can be estimated with an error that goes to 0 for every unknown input. With , the existence condition 2 says that the system from to is minimum phase.
Variants and improvements
- Reduced-order unknown input observers. As for the reduced-order observer, the part of the state that gives directly need not be estimated, and observers of lower order exist under similar conditions.
- Fault detection. Decoupling the error from disturbances while keeping its sensitivity to faults gives residuals that react only to faults. Model-based fault diagnosis uses unknown input observers widely for this purpose.
- When rank rank. Derivatives of , or a sliding-mode term, can restore the decoupling; see sliding mode observer.
- Discrete time. The same matrices work for , with .
When to use it
Use an unknown input observer when a disturbance or an unknown input acts through a known direction , when the outputs see it directly, and when no model of the disturbance is available or wanted. Examples are unknown loads in mechanical systems and unknown inflows in process models. If the disturbance has a known model, such as a constant or a sinusoid, an augmented Luenberger observer or a disturbance observer is often simpler and filters noise better.
Pitfalls
- Rank condition. If an unknown input does not affect at once ( rank deficient), no observer of this form exists. Adding a sensor in the direction of is the usual remedy.
- Non-minimum-phase zeros. An invariant zero of in the right half plane is a fixed unstable eigenvalue of . No gain fixes it.
- Noise. The projection and the term can amplify measurement noise, because the observer trusts fully in the direction of .
- Model error. The decoupling is exact only for the exact and . An error in lets leak into .
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()
unknown_input_observer.py 157 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unknown-input-observer/. The authors are listed in prov/A7P4SP.jsonl.
"""Full-order unknown input observer (Darouach, Zasadzinski and Xu, 1994).
System: x' = A x + B u + E d, y = C x, with u known and d unknown. E is n by
q with full column rank q. The observer
z' = F z + G u + K y, x_hat = z + H y,
has the error e = x - x_hat with e' = F e for every d, if
H = E (C E)^+, T = I - H C, G = T B, F = T A - K1 C, K = K1 + F H.
This needs rank(C E) = rank(E) (so that H C E = E and T E = 0). K1 places
the eigenvalues of F as for a Luenberger observer of the pair (C, T A). The
eigenvalues of T A that no K1 can move are the invariant zeros of (A, E, C);
all must be stable for the error to converge (strong detectability). This
module places all eigenvalues, so it needs (C, T A) observable, that is,
no invariant zeros at all.
The same formulas hold in discrete time. Exact (Fraction) for int and
Fraction data.
"""
from fractions import Fraction
from ctlmat import add, eye, inv, matvec, mul, solve, sub, transpose
__all__ = ["place", "uio_matrices", "unknown_input_observer", "observer_rhs", "observer_step", "estimate"]
def _rank(vectors, tol):
rows = [list(v) for v in vectors]
if not rows or not rows[0]:
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."""
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))
k1 = _ackermann(add(A, mul(B, F)), 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 uio_matrices(A, B, C, E, tol=1e-10):
"""Return (H, T, A1, G) with H C E = E, T = I - H C, A1 = T A, G = T B.
Raises ValueError if E does not have full column rank or if
rank(C E) < rank(E).
"""
n, q = len(A), len(E[0])
if _rank(transpose(E), tol) != q:
raise ValueError("E must have full column rank")
CE = mul(C, E)
if _rank(transpose(CE), tol) != q: # @line L1
raise ValueError("rank(C E) < rank(E): no unknown input observer exists")
CEt = transpose(CE)
H = mul(E, mul(inv(mul(CEt, CE)), CEt)) # @line L2
T = sub(eye(n), mul(H, C)) # @line L3
A1 = mul(T, A)
G = mul(T, B) if B is not None else None
return H, T, A1, G
def unknown_input_observer(A, B, C, E, alpha, tol=1e-10):
"""Return (F, G, K, H) with det(s I - F) = alpha(s).
Raises ValueError if the rank condition fails or if (C, T A) is not
observable (then (A, E, C) has invariant zeros, which stay eigenvalues
of F for every gain).
"""
H, T, A1, G = uio_matrices(A, B, C, E, tol)
try:
K1 = transpose(place(transpose(A1), transpose(C), alpha, tol)) # @line L4
except ValueError:
raise ValueError("(C, T A) is not observable: (A, E, C) has invariant zeros") from None
F = sub(A1, mul(K1, C)) # @line L5
K = add(K1, mul(F, H))
return F, G, K, H # @line L6
def observer_rhs(F, G, K):
"""Return f(t, z, (u, y)) = F z + G u + K y."""
def f(t, z, uy):
u, y = uy
out = [a + b for a, b in zip(matvec(F, z), matvec(K, y))] # @line L7
if G is not None and u is not None:
out = [a + b for a, b in zip(out, matvec(G, u))]
return out
return f
def observer_step(F, G, K, z, u, y):
"""Return the discrete-time update F z + G u + K y."""
return observer_rhs(F, G, K)(0, z, (u, y))
def estimate(H, z, y):
"""Return x_hat = z + H y."""
return [a + b for a, b in zip(z, matvec(H, y))] # @line L8
test_unknown_input_observer.py 141 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/unknown-input-observer/. The authors are listed in prov/A7P4SP.jsonl.
import math
import random
from fractions import Fraction
import pytest
import ctlmat as cm
from ctlsim import simulate
from unknown_input_observer import (
estimate,
observer_rhs,
observer_step,
place,
uio_matrices,
unknown_input_observer,
)
A_EX = [[0, 1, 0], [0, 0, 1], [-1, -3, -3]]
B_EX = [[0], [0], [1]]
E_EX = [[1], [0], [0]]
C_EX = [[1, 0, 0], [0, 1, 0]]
ALPHA = [1, 9, 26, 24] # (s + 2)(s + 3)(s + 4)
def as_float(M):
return [[float(v) for v in r] for r in M]
def test_example_matrices():
H, T, A1, G = uio_matrices(A_EX, B_EX, C_EX, E_EX)
assert H == [[1, 0], [0, 0], [0, 0]]
assert T == [[0, 0, 0], [0, 1, 0], [0, 0, 1]]
assert A1 == [[0, 0, 0], [0, 0, 1], [-1, -3, -3]]
F, G, K, H = unknown_input_observer(A_EX, B_EX, C_EX, E_EX, ALPHA)
assert cm.charpoly(F) == ALPHA
assert cm.mul(T, E_EX) == [[0], [0], [0]]
def rand_case(rng, n, p, q):
while True:
A = [[rng.randint(-3, 3) for _ in range(n)] for _ in range(n)]
B = [[rng.randint(-2, 2)] for _ in range(n)]
C = [[rng.randint(-2, 2) for _ in range(n)] for _ in range(p)]
E = [[rng.randint(-2, 2) for _ in range(q)] for _ in range(n)]
try:
return A, B, C, E, unknown_input_observer(A, B, C, E, [1] + [0] * n)
except ValueError:
continue
def test_identities_random_exact():
rng = random.Random(7)
for n, p, q in [(3, 2, 1), (4, 2, 1), (4, 3, 2), (5, 3, 1), (5, 4, 2)]:
for _ in range(3):
A, B, C, E, _ = rand_case(rng, n, p, q)
alpha = [1]
for r in [rng.randint(-5, -1) for _ in range(n)]:
alpha = cm.polymul(alpha, [1, -r])
F, G, K, H = unknown_input_observer(A, B, C, E, alpha)
T = cm.sub(cm.eye(n), cm.mul(H, C))
assert cm.mul(cm.mul(H, C), E) == [[Fraction(v) for v in r] for r in E]
assert cm.mul(T, E) == cm.zeros(n, q)
assert cm.add(cm.mul(F, T), cm.mul(K, C)) == cm.mul(T, A) # F T + K C = T A
assert G == cm.mul(T, B)
assert cm.charpoly(F) == alpha
def test_discrete_error_ignores_unknown_input_exact():
rng = random.Random(8)
for n, p, q in [(3, 2, 1), (4, 3, 2)]:
A, B, C, E, (F, G, K, H) = rand_case(rng, n, p, q)
x = [Fraction(rng.randint(-4, 4)) for _ in range(n)]
z = [0] * n
T = cm.sub(cm.eye(n), cm.mul(H, C))
e0 = [a - b for a, b in zip(cm.matvec(T, x), z)]
for k in range(n + 3):
u = [Fraction(rng.randint(-9, 9), 2)]
d = [Fraction(rng.randint(-50, 50), rng.randint(1, 7)) for _ in range(q)]
y = cm.matvec(C, x)
err = [a - b for a, b in zip(x, estimate(H, z, y))]
assert err == cm.matvec(cm.mat_power(F, k), e0)
z = observer_step(F, G, K, z, u, y)
x = [a + b + c for a, b, c in zip(cm.matvec(A, x), cm.matvec(B, u), cm.matvec(E, d))]
# deadbeat: alpha = z^n, so the estimate is exact from step n on
assert cm.mat_power(F, n) == cm.zeros(n)
def test_continuous_against_luenberger():
F, G, K, H = unknown_input_observer(A_EX, B_EX, C_EX, E_EX, ALPHA)
L = cm.transpose(place(cm.transpose(A_EX), cm.transpose(C_EX), ALPHA))
A, B, C, Lf = as_float(A_EX), as_float(B_EX), as_float(C_EX), as_float(L)
obs = observer_rhs(as_float(F), as_float(G), as_float(K))
n = 3
def d(t):
return (1.0 if t >= 1.0 else 0.0) + 0.5 * math.sin(5 * t)
def f(t, s, u):
x, z, xl = s[:n], s[n:2 * n], s[2 * n:]
y = cm.matvec(C, x)
dx = [a + b + e * d(t) for a, b, e in zip(cm.matvec(A, x), cm.matvec(B, u), [1.0, 0.0, 0.0])]
r = [a - b for a, b in zip(y, cm.matvec(C, xl))]
dxl = [a + b + c for a, b, c in zip(cm.matvec(A, xl), cm.matvec(B, u), cm.matvec(Lf, r))]
return dx + obs(t, z, (u, y)) + dxl
x0 = [0.5, 0.3, -0.2]
ts, ss, _ = simulate(f, x0 + [0.0] * 6, 0.0, 6.0, 0.001, control=lambda t, s: [math.sin(t)])
T = cm.sub(cm.eye(n), cm.mul(as_float(H), C))
e0 = cm.matvec(T, x0)
for k in (1000, 3000, 6000):
x, z, xl = ss[k][:n], ss[k][n:2 * n], ss[k][2 * n:]
err = [a - b for a, b in zip(x, estimate(as_float(H), z, cm.matvec(C, x)))]
want = cm.matvec(cm.expm(cm.scale(ts[k], as_float(F))), e0)
assert max(abs(a - b) for a, b in zip(err, want)) < 1e-8
if ts[k] >= 3:
assert max(abs(a - b) for a, b in zip(x, xl)) > 0.1 # the Luenberger observer is biased
assert cm.norm2(err) < 1e-5
def test_invariant_zero_is_a_fixed_eigenvalue():
# (A, E, C) has the invariant zero s = 1: (I - A) e3 = E (-1) and C e3 = 0.
A = [[0, 1, 1], [0, 0, 0], [1, -1, 1]]
B = [[0], [0], [1]]
H, T, A1, G = uio_matrices(A, B, C_EX, E_EX)
rng = random.Random(9)
for _ in range(20):
K1 = [[rng.randint(-9, 9) for _ in range(2)] for _ in range(3)]
F = cm.sub(A1, cm.mul(K1, C_EX))
assert cm.det(cm.sub(cm.eye(3), F)) == 0
with pytest.raises(ValueError):
unknown_input_observer(A, B, C_EX, E_EX, ALPHA)
def test_rank_condition():
with pytest.raises(ValueError): # C E = 0
uio_matrices(A_EX, B_EX, [[0, 1, 0], [0, 0, 1]], E_EX)
with pytest.raises(ValueError): # E rank deficient
uio_matrices(A_EX, B_EX, C_EX, [[1, 2], [0, 0], [0, 0]])
History
Observers for systems with unknown inputs were studied in the 1970s. Kudva, Viswanadham and Ramakrishna (1980) gave existence conditions with . Hautus (1983) introduced strong detectability and related it to observers whose error converges for every unknown input. Darouach, Zasadzinski and Xu (1994) gave the full-order observer with and showed that their two conditions are necessary and sufficient for it to exist.
References
- Mohamed Darouach, Michel Zasadzinski and Shi Jie Xu, Full-order observers for linear systems with unknown inputs, IEEE Transactions on Automatic Control 39(3), 606-609, 1994, the observer z' = F z + G u + K y, x_hat = z + H y, its design equations and its existence conditions
- M. L. J. Hautus, Strong detectability and observers, Linear Algebra and its Applications 50, 353-368, 1983, strong detectability and its relation to observers for systems with unknown inputs
- P. Kudva, N. Viswanadham and A. Ramakrishna, Observers for linear systems with unknown inputs, IEEE Transactions on Automatic Control 25(1), 113-115, 1980, the existence conditions, with rank(CE) = rank(E)
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 A7P4SP Edit this page History Report an error Markdown