Algorithmadvanced
MOESP
Also called multivariable output-error state space.
Subspace method that gets a state-space model from input-output data by an LQ factorization and an SVD of block Hankel matrices; consistent for white output noise.
- Solves
- System identification
- Time
- O(N i^2 (m + p)^2 + i^3 p^3 + N n^3 m + N p (n m + p m + n)^2) worst
- Space
- O(N i (m + p)) extra
- Where
- N = the number of samples; i = the number of block rows; m = the number of inputs; n = the model order; p = the number of outputs
- Model
- Real RAM
- Properties
- deterministicexactnot iterativeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Michel Verhaegen, Patrick Dewilde, 1992
MOESP (multivariable output-error state space) is a subspace identification method. It takes measured inputs and outputs of a linear system , and returns , , and without an iterative search. It stacks the data in block Hankel matrices, removes the part of the outputs that the future inputs explain with one LQ factorization, and finds the extended observability matrix from an SVD of what is left. The shift structure of that matrix gives and , and one linear least squares fit gives , and the initial state. MOESP and N4SID are the two best known members of the subspace family. MOESP estimates the observability matrix and then and ; N4SID estimates a state sequence and then all four matrices in one regression. Basic MOESP is consistent when the noise is white and on the output only; for process noise use its variants PI-MOESP and PO-MOESP, or N4SID.
In plain words
Write the input and the output records as tables in which each column is a short window of the data, and the next column is the same window one step later. The outputs in a window depend on two things: the state at the start of the window and the inputs inside the window. Remove everything that the inputs inside the window can explain. What is left comes from the start states, so its columns all lie in a space with as many dimensions as the system has states. The SVD finds this space and shows its size. From the space you read how the state shows up in the output, one step after another, and from that the state matrix. A last fit on the data gives the input matrices.
The problem
Input. Samples and , a number of block rows with , and the order or a threshold to choose it.
Output. of order and an initial state such that the model output fits the data, and the singular values used to choose .
Assumptions. The data come from a system of order with observable. The input is rich enough: the matrix of the state sequence and the input Hankel matrix has full row rank . This holds, for example, for a white noise input that is persistently exciting of order and a controllable . Noise, if any, is white, of equal variance on all outputs, and independent of the input.
Notation. is the block Hankel matrix with block equal to , for and , with . is the same for . stacks .
The algorithm
MOESP(u, y, i, n)- 1
U, Y ← the block Hankel matrices of u and y, i block rows, j = N - i + 1 columns - 2
[L11 0; L21 L22] ← the triangular factor of the LQ factorization [U; Y] = L Q - 3
(Ul, σ) ← the left singular vectors and singular values of L22 - 4
choose n (a gap in σ, or given), with 1 ≤ n < i - 5
G ← the first n columns of Ul (G = Γ_i T for some nonsingular T) - 6
C ← the first p rows of G - 7
A ← (G without its last p rows)⁺ · (G without its first p rows) - 8
(x0, B, D) ← the least squares fit of y_k = C A^k x0 + Σ_(t<k) C A^(k-1-t) B u_t + D u_k - 9
return (A, B, C, D, x0, σ)
The data equation holds, where is the state sequence and is the block Toeplitz matrix of the Markov parameters. L2 computes only the triangular factor , with Householder reflections, and never stores . Because and , the block is the part of that is orthogonal to the inputs in the window, and it equals . So the column space of is the column space of . L7 uses the shift structure: without its last block row, times , is without its first block row. L8 is linear in , and once and are fixed; the code builds each regressor column by a short simulation.
Example
Take the second order system
with poles , the initial state , and a Gaussian white input with unit variance (seed 7), samples and block rows. Then , and is .
Noise-free data. The singular values of the block are
So . The estimated is , not the true matrix, but similar to it: its eigenvalues are to 15 digits. The fit gives , and the model output with the fitted matches the data to .
White output noise (measurement). With , , zero initial state, and Gaussian output noise with standard deviation (seed 1), the singular values are
The four small values are almost equal, about : this is the term of the proof. The estimated poles are and . With the seeds 2 and 3 the poles are and .
Correctness
Claim. On noise-free data, with observable, , the excitation condition and a full rank regressor in L8, MOESP returns for a nonsingular . With white output noise of equal variance on all outputs, the estimated column space tends to the column space of as .
Key invariant. , and has full row rank . With noise, with positive definite.
So the first left singular vectors span the column space of , and . Shift invariance gives and , and the true is a zero-residual point of the least squares problem of L8. The full proof is below.
Proof: MOESP recovers the system up to similarity from noise-free data, and the column space of the observability matrix under white output noisefull
We work in exact real arithmetic, as in the real RAM, and assume that the LQ factorization and the SVD are exact. The data come from
with , , . In the first part . The integer is the number of block rows and is the number of columns.
Notation. and are the and block Hankel matrices with block equal to and for and . is the state sequence. is the extended observability matrix that stacks , and is the lower block triangular Toeplitz matrix with on the block diagonal and in block for . is the block Hankel matrix of the .
Lemma 1 (data equation). .
Proof. Iterating the state equation gives , so . Block row and column of the right side is exactly this.
Lemma 2 (the LQ blocks). Let with lower triangular and with orthonormal rows. If has full row rank , then is nonsingular, and .
Proof. has rank , so the matrix is nonsingular. The rows of are orthonormal, so and . Hence and .
Noise-free data
Assume , that is observable, and the excitation condition
(E) implies that has full row rank, so Lemma 2 applies.
Lemma 3 (the column space). , has full row rank , and the column space of is the column space of .
Proof. By Lemmas 1 and 2, .
Suppose for some . Since and is observable, has full column rank, so lies in the row space of , which is contained in the row space of . Write . Multiplying by gives , so . By (E), the rows of and are linearly independent together, so . Hence has full row rank .
The product of the full column rank matrix and the full row rank matrix has the column space of .
Lemma 4 (the observability factor). L3 to L5 give with , and there is a nonsingular with .
Proof. By Lemma 3, has rank , so exactly singular values are nonzero and the first left singular vectors span the column space of , which is the column space of . So for an matrix , and is nonsingular because has rank .
Lemma 5 (A and C). L6 gives and L7 gives .
Proof. The first block row of is . Let be without its last block row and be without its first block row. Then and . Since and is observable, has full column rank, so its pseudoinverse is a left inverse, and .
Lemma 6 (x_0, B and D). With and fixed, the output is linear in :
The values , , give zero residual. If the regressor matrix of L8 has full column rank, the least squares solution is unique and equals these values.
Proof. With and , the right side with these values is . A zero-residual point is a minimizer of the sum of squares, and with full column rank the minimizer is unique.
Theorem (noise-free case). If is observable, , (E) holds, the regressor of L8 has full column rank, and the order is chosen as the number of nonzero singular values of , MOESP returns and for a nonsingular . So the model has the transfer function and the output of the true system.
Proof. Lemmas 4, 5 and 6.
White output noise
Now let be a zero-mean noise, independent of the input, with and for and , as , with probability 1. Here the state does not depend on the noise, because the noise enters only the output. Assume also that , and converge, with the limit of positive definite. This is the limit form of (E).
Lemma 7 (the noise only adds a multiple of the identity). , where is positive definite.
Proof. . The rows of lie in the row space of , and is the orthogonal projection onto the row space of , so acts on the rows of as the projection onto the orthogonal complement of the row space of . Hence , and with and Lemma 1, . Divide by and pass to the limit. tends to the Schur complement of the limit covariance, which is positive definite because the whole limit matrix is. The cross terms tend to 0, and tends to , because the correction tends to 0.
Theorem (consistency of the column space). Under these assumptions, the span of the first left singular vectors of tends to the column space of , and the estimates of the poles tend to the true poles.
Proof. The left singular vectors of are the eigenvectors of . For the limit matrix , every vector in the column space of is mapped into that space, and every vector orthogonal to it is an eigenvector with eigenvalue . On the column space of the eigenvalues are plus the positive eigenvalues of there. So the dominant eigenvectors span the column space of , with a gap above . Invariant subspaces of a symmetric matrix with such a gap depend continuously on the matrix (the Davis-Kahan theorem), so the estimate converges. Lemma 5 is continuous in at a point where has full column rank, and the eigenvalues of do not depend on the choice of .
The identity in Lemma 7 needs : the noise must be white in time and have the same variance in every output. Colored output noise or process noise adds a matrix that is not a multiple of the identity, and then the column space is biased. The PI-MOESP and PO-MOESP variants use past inputs or past outputs as instruments to remove this bias.
Complexity
In the real RAM, counting dense factorizations in the usual way. L2 factors a matrix with by Householder reflections in . L3 is an SVD of the block in . L7 is a pseudoinverse of an matrix, . L8 builds regressor columns by simulations of steps, in for the code's simple loops, and solves a least squares problem with rows and unknowns in . The extra space is for the Hankel matrices; the LQ factor is only .
For long records, L2 dominates. The SVD and the pseudoinverse are iterative inside, so the counts above are the usual dense counts, as for the other factorizations in this area.
Properties
- Exact for noise-free data (theorem). Under the assumptions above the model has the true transfer function, in other state coordinates.
- Consistent for white output noise (theorem). The column space of , and so and , are consistent when the noise is white, has equal variance on all outputs, and is independent of the input (Verhaegen and Dewilde 1992, Part 2).
- Biased for process noise. With noise in the state equation, or colored output noise, basic MOESP is biased. PI-MOESP and PO-MOESP remove the bias with instruments.
- No local minima. There is no nonconvex search, so no starting value is needed.
- Not optimal. The estimate is not the maximum likelihood estimate, and its variance is larger than that of a prediction error method.
- The order is a choice. The singular values give a visual aid, not a test. A gap that is clear on noise-free data can be hard to see on real data.
Variants and improvements
- PI-MOESP. Uses the past inputs as instruments. It is consistent for output noise that is colored but independent of the input (Verhaegen 1993, Part 3).
- PO-MOESP. Uses the past inputs and the past outputs as instruments. It is consistent for innovation form models with process noise (Verhaegen, Automatica, 1994).
- N4SID. Uses an oblique projection to get a state sequence and then fits all matrices in one least squares problem. Van Overschee and De Moor (1995) showed that MOESP, N4SID and CVA are the same algorithm with different weightings of the SVD.
- ERA. The same shift idea applied to a Hankel matrix of Markov parameters, not of raw data.
- Closed loop. Basic MOESP is biased in closed loop, because the input depends on past noise. Predictor-based subspace methods address this.
- Recursive MOESP. Updates the LQ factor and the subspace as data arrive, for tracking slowly changing systems.
When to use it
Use MOESP to get a multivariable state-space model from open-loop data in one step, when there is no good starting value for a prediction error method, or as the starting value for one. It handles many inputs and outputs at the same cost as one, and it gives the order from the singular values. With strong process noise, prefer PO-MOESP or N4SID. With feedback in the data, use a closed-loop method.
Pitfalls
- Too few block rows. The method needs , and in practice two or three times the expected order. With too small, L7 has no unique solution.
- Too few samples. The LQ factorization needs , and the estimate is poor long before that limit. The code rejects .
- An input that is not rich enough. A step or a sum of a few sines does not satisfy the excitation condition for large . Then contains input effects and the rank is wrong.
- Unequal noise on the outputs. The proof needs the same noise variance on every output. Scale the outputs to equal noise levels before L1.
- Offsets. A constant offset in the data acts as an extra input. Remove the means first.
- Comparing matrices. The estimate is in other coordinates. Compare eigenvalues, Markov parameters or frequency responses, never the entries of .
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()
moesp.py 175 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moesp/. The authors are listed in prov/7ZZDNB.jsonl.
"""Ordinary MOESP (Verhaegen and Dewilde, 1992).
Input: an input sequence u_0, ..., u_(N-1) (vectors of length m) and an
output sequence y_0, ..., y_(N-1) (vectors of length p) of a discrete-time
system x_(k+1) = A x_k + B u_k, y_k = C x_k + D u_k (+ white output noise),
the number i of block rows (i > n), and the order n (or None to pick it from
the singular values with the relative threshold tol).
Steps: block Hankel matrices U and Y with i block rows and j = N - i + 1
columns; the LQ factorization [U; Y] = L Q; the SVD of the block L22; the
extended observability matrix Gamma = U_n (left singular vectors); C from the
first block row of Gamma; A from its shift structure; then x_0, B and D by
linear least squares on the data.
The LQ factorization uses Householder reflections. The SVD is a one-sided
Jacobi (Hestenes) method. Both are in floating point.
"""
import math
from ctlmat import mul, transpose
__all__ = ["block_hankel", "householder_lq", "jacobi_svd", "pinv", "moesp", "estimate_x0_b_d", "simulate"]
def block_hankel(w, i, j):
"""Return the i q by j matrix whose block (r, c) is the vector w[r + c] as a column."""
q = len(w[0])
return [[float(w[r + c][a]) for c in range(j)] for r in range(i) for a in range(q)]
def householder_lq(a):
"""Return the d by d lower triangular L with a = L Q, Q with orthonormal rows.
a is d by N with d <= N. Each step applies a Householder reflection from
the right that sets the entries to the right of the diagonal in one row
to zero. Cost: O(d^2 N).
"""
d, ncol = len(a), len(a[0])
if d > ncol:
raise ValueError("householder_lq: need at least as many columns as rows")
w = [[float(v) for v in row] for row in a]
for k in range(d):
v = w[k][k:]
normx = math.sqrt(sum(t * t for t in v))
if normx == 0.0:
continue
alpha = -math.copysign(normx, v[0])
v[0] -= alpha
vv = sum(t * t for t in v)
for r in range(k, d):
row = w[r]
f = 2.0 * sum(row[k + t] * v[t] for t in range(len(v))) / vv
if f != 0.0:
for t in range(len(v)):
row[k + t] -= f * v[t]
return [[w[r][c] if c <= r else 0.0 for c in range(d)] for r in range(d)]
def jacobi_svd(a, tol=1e-15, max_sweeps=80):
"""Return (U, s, V) with a = U diag(s) V^T and s sorted in decreasing order.
a is r by c. U is r by k and V is c by k, with k = min(r, c), as lists of
rows. A column of U that belongs to a zero singular value is zero. A
column whose squared norm is below 1e-30 times the squared Frobenius norm
of a counts as zero and is not rotated.
"""
r, c = len(a), len(a[0])
if r < c:
v, s, u = jacobi_svd(transpose(a), tol, max_sweeps)
return u, s, v
cols = [[float(a[i][j]) for i in range(r)] for j in range(c)]
vcols = [[1.0 if i == j else 0.0 for i in range(c)] for j in range(c)]
tiny = 1e-30 * sum(t * t for col in cols for t in col)
for _ in range(max_sweeps):
rotated = False
for p in range(c - 1):
for q in range(p + 1, c):
x, y = cols[p], cols[q]
alpha = sum(t * t for t in x)
beta = sum(t * t for t in y)
gamma = sum(s * t for s, t in zip(x, y))
if min(alpha, beta) <= tiny or abs(gamma) <= tol * math.sqrt(alpha * beta):
continue
rotated = True
zeta = (beta - alpha) / (2.0 * gamma)
t = math.copysign(1.0, zeta) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
cs = 1.0 / math.sqrt(1.0 + t * t)
sn = cs * t
cols[p] = [cs * xi - sn * yi for xi, yi in zip(x, y)]
cols[q] = [sn * xi + cs * yi for xi, yi in zip(x, y)]
vx, vy = vcols[p], vcols[q]
vcols[p] = [cs * xi - sn * yi for xi, yi in zip(vx, vy)]
vcols[q] = [sn * xi + cs * yi for xi, yi in zip(vx, vy)]
if not rotated:
break
sv = [math.sqrt(sum(t * t for t in col)) for col in cols]
order = sorted(range(c), key=lambda j: -sv[j])
s = [sv[j] for j in order]
ucols = [[t / sv[j] for t in cols[j]] if sv[j] > 0.0 else [0.0] * r for j in order]
return transpose(ucols), s, transpose([vcols[j] for j in order])
def pinv(a, rtol=1e-12):
"""Return the Moore-Penrose pseudoinverse; singular values below rtol s_max count as zero."""
U, s, V = jacobi_svd(a)
keep = [k for k in range(len(s)) if s[k] > rtol * s[0]] if s and s[0] > 0.0 else []
return [[sum(V[r][k] * U[c][k] / s[k] for k in keep) for c in range(len(U))] for r in range(len(V))]
def simulate(A, B, C, D, u, x0):
"""Return y_0, ..., y_(N-1) of x_(k+1) = A x_k + B u_k, y_k = C x_k + D u_k."""
x = list(x0)
out = []
for uk in u:
out.append([sum(C[a][t] * x[t] for t in range(len(x))) + sum(D[a][c] * uk[c] for c in range(len(uk)))
for a in range(len(C))])
x = [sum(A[r][t] * x[t] for t in range(len(x))) + sum(B[r][c] * uk[c] for c in range(len(uk)))
for r in range(len(x))]
return out
def estimate_x0_b_d(A, C, u, y):
"""Fit x_0, B and D by linear least squares, with A and C fixed.
y_k = C A^k x_0 + sum_(t<k) C A^(k-1-t) B u_t + D u_k is linear in the
entries of x_0, B and D. Each regressor column is the output of a small
simulation, so the cost is O(N n^3 m + N p m) to build the columns and
O(N p q^2) per SVD sweep for the q = n + n m + p m unknowns.
"""
n, p, m, N = len(A), len(C), len(u[0]), len(u)
columns = []
for r in range(n): # x_0 entries: free response C A^k e_r
e = [1.0 if t == r else 0.0 for t in range(n)]
columns.append([v for yk in simulate(A, [[0.0] * m for _ in range(n)], C, [[0.0] * m for _ in range(p)], u, e)
for v in yk])
for r in range(n): # B entries
for c in range(m):
E = [[1.0 if (t == r and s == c) else 0.0 for s in range(m)] for t in range(n)]
columns.append([v for yk in simulate(A, E, C, [[0.0] * m for _ in range(p)], u, [0.0] * n) for v in yk])
for a in range(p): # D entries
for c in range(m):
columns.append([float(u[k][c]) if b == a else 0.0 for k in range(N) for b in range(p)])
phi = transpose(columns)
theta = mul(pinv(phi), [[float(v)] for yk in y for v in yk])
theta = [row[0] for row in theta]
x0 = theta[:n]
B = [[theta[n + r * m + c] for c in range(m)] for r in range(n)]
D = [[theta[n + n * m + a * m + c] for c in range(m)] for a in range(p)]
return x0, B, D
def moesp(u, y, i, n=None, tol=1e-8):
"""Return (A, B, C, D, x0, s): an order n model and the singular values of L22."""
m, p, N = len(u[0]), len(y[0]), len(u)
j = N - i + 1
if j < i * (m + p):
raise ValueError("moesp: too few samples for i block rows")
U = block_hankel(u, i, j) # @line L1
Y = block_hankel(y, i, j)
L = householder_lq(U + Y) # @line L2
L22 = [row[i * m:] for row in L[i * m:]]
Ul, s, _ = jacobi_svd(L22) # @line L3
if n is None: # @line L4
n = sum(1 for v in s if v > tol * s[0])
if n < 1 or n >= i or s[n - 1] <= 0.0:
raise ValueError("moesp: need 1 <= n < i and n at most the rank of L22")
G = [row[:n] for row in Ul] # @line L5
C = [list(row) for row in G[:p]] # @line L6
A = mul(pinv(G[:-p]), G[p:]) # @line L7
x0, B, D = estimate_x0_b_d(A, C, u, y) # @line L8
return A, B, C, D, x0, s # @line L9
test_moesp.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moesp/. The authors are listed in prov/7ZZDNB.jsonl.
import random
from ctlmat import charpoly, mul, polyroots, transpose
from moesp import block_hankel, householder_lq, jacobi_svd, moesp, pinv, simulate
def _close(a, b, tol):
return all(abs(x - y) <= tol for ra, rb in zip(a, b) for x, y in zip(ra, rb))
def _eig_error(A, A0):
eig = polyroots(charpoly(A))
true = polyroots(charpoly(A0))
return max(min(abs(e - t) for t in true) for e in eig)
def _markov(A, B, C, K):
out = []
P = [list(row) for row in B]
for _ in range(K):
out.append(mul(C, P))
P = mul(A, P)
return out
def test_lq_factor():
rng = random.Random(1)
for _ in range(10):
d, ncol = rng.randint(1, 6), rng.randint(6, 12)
a = [[rng.uniform(-1, 1) for _ in range(ncol)] for _ in range(d)]
L = householder_lq(a)
assert all(L[r][c] == 0.0 for r in range(d) for c in range(r + 1, d))
# a = L Q with Q Q^T = I implies a a^T = L L^T
assert _close(mul(L, transpose(L)), mul(a, transpose(a)), 1e-12)
def test_block_hankel_layout():
w = [[k, 10 * k] for k in range(5)]
assert block_hankel(w, 2, 3) == [[0, 1, 2], [0, 10, 20], [1, 2, 3], [10, 20, 30]]
def test_pinv_of_rank_deficient_matrix():
a = [[1.0, 2.0], [2.0, 4.0], [0.0, 0.0]]
p = pinv(a)
assert _close(mul(mul(a, p), a), a, 1e-12)
assert _close(mul(mul(p, a), p), p, 1e-12)
def test_exact_siso_with_initial_state():
A0 = [[0.7, 0.4], [-0.4, 0.7]]
B0 = [[1.0], [0.5]]
C0 = [[1.0, 0.0]]
D0 = [[0.2]]
rng = random.Random(7)
u = [[rng.gauss(0.0, 1.0)] for _ in range(300)]
y = simulate(A0, B0, C0, D0, u, [0.5, -1.0])
A, B, C, D, x0, s = moesp(u, y, 4)
assert len(A) == 2
assert s[2] < 1e-12 * s[0]
assert _eig_error(A, A0) < 1e-10
assert abs(D[0][0] - 0.2) < 1e-10
yh = simulate(A, B, C, D, u, x0)
assert max(abs(a[0] - b[0]) for a, b in zip(y, yh)) < 1e-9
for g, g0 in zip(_markov(A, B, C, 12), _markov(A0, B0, C0, 12)):
assert _close(g, g0, 1e-10)
def test_exact_mimo():
A0 = [[0.5, 0.3, 0.0], [-0.3, 0.5, 0.2], [0.0, 0.0, -0.6]]
B0 = [[1.0, 0.0], [0.0, 1.0], [1.0, -1.0]]
C0 = [[1.0, 0.0, 1.0], [0.0, 1.0, 0.0]]
D0 = [[0.0, 0.1], [0.0, 0.0]]
rng = random.Random(11)
u = [[rng.gauss(0.0, 1.0), rng.gauss(0.0, 1.0)] for _ in range(250)]
y = simulate(A0, B0, C0, D0, u, [0.0, 0.0, 0.0])
A, B, C, D, x0, s = moesp(u, y, 5)
assert len(A) == 3
assert _eig_error(A, A0) < 1e-9
assert _close(D, D0, 1e-9)
for g, g0 in zip(_markov(A, B, C, 12), _markov(A0, B0, C0, 12)):
assert _close(g, g0, 1e-9)
def test_white_output_noise():
# measurement: white output noise with standard deviation 0.1, N = 2000
A0 = [[0.7, 0.4], [-0.4, 0.7]]
B0 = [[1.0], [0.5]]
C0 = [[1.0, 0.0]]
D0 = [[0.2]]
for seed in (1, 2, 3):
rng = random.Random(seed)
u = [[rng.gauss(0.0, 1.0)] for _ in range(2000)]
y = simulate(A0, B0, C0, D0, u, [0.0, 0.0])
yn = [[v[0] + rng.gauss(0.0, 0.1)] for v in y]
A, B, C, D, x0, s = moesp(u, yn, 6, n=2)
assert s[1] > 5 * s[2]
assert _eig_error(A, A0) < 0.01
assert abs(D[0][0] - 0.2) < 0.02
def test_svd_reconstruction():
rng = random.Random(5)
a = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(6)]
U, s, V = jacobi_svd(a)
S = [[s[i] if i == j else 0.0 for j in range(4)] for i in range(4)]
assert _close(mul(mul(U, S), transpose(V)), a, 1e-12)
def test_too_few_samples_rejected():
u = [[1.0]] * 10
try:
moesp(u, u, 6)
except ValueError:
return
assert False, "moesp must reject too few samples"
History
Subspace identification grew out of realization theory: Ho and Kalman (1966), then the SVD methods of Kung (1978) and of Juang and Pappa (1985) worked on Markov parameters. In 1992, Verhaegen and Dewilde published the MOESP class in two parts in the International Journal of Control. They worked directly on input-output data with an LQ factorization and an SVD. Verhaegen analysed ordinary MOESP and introduced PI-MOESP in Part 3 (1993), and PO-MOESP for models in innovation form in 1994. At the same time Van Overschee and De Moor developed N4SID, and in 1995 they showed that both are special cases of one weighted algorithm.
References
- Michel Verhaegen and Patrick Dewilde, Subspace model identification Part 1. The output-error state-space model identification class of algorithms, International Journal of Control 56(5), 1187-1210, 1992, the data equation, the LQ factorization of the block Hankel matrices, and the estimate of A and C from the observability matrix
- Michel Verhaegen and Patrick Dewilde, Subspace model identification Part 2. Analysis of the elementary output-error state-space model identification algorithm, International Journal of Control 56(5), 1211-1241, 1992, the analysis of the algorithm with noise on the output
- Michel Verhaegen, Subspace model identification Part 3. Analysis of the ordinary output-error state-space model identification algorithm, International Journal of Control 58(3), 555-586, 1993, the analysis of ordinary MOESP and the instrumental variable version with past inputs
- Michel Verhaegen and Vincent Verdult, Filtering and System Identification: A Least Squares Approach, Cambridge University Press, 2007, the chapter on subspace model identification (MOESP, PI-MOESP and PO-MOESP)
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 7ZZDNB Edit this page History Report an error Markdown