Algorithmadvanced
N4SID
Also called numerical algorithms for subspace state space system identification.
Subspace method that estimates a state sequence from input-output data by oblique projections and an SVD, then fits A, B, C, D and the noise covariances by least squares.
- Solves
- System identification
- Time
- O(N i^2 (m + p)^2 + i^3 (m + p)^3) worst
- Space
- O(N i (m + p)) extra
- Where
- N = the number of samples; i = the number of block rows in the past and in the future; 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
- Peter Van Overschee, Bart De Moor, 1994
N4SID (numerical algorithms for subspace state space system identification) is a subspace identification method. From measured inputs and outputs it estimates a model in innovation form, , , without iterative search. Its main step is an oblique projection of the future outputs onto the past data, along the future inputs. The result is the extended observability matrix times a sequence of states, and an SVD splits the two factors. With two such state sequences, one step apart, all of , , and follow from one linear least squares problem, and its residuals give the noise covariances. MOESP is the other well known member of the family: it gets and from the observability matrix and fits and afterwards, while N4SID fits all four matrices together from estimated states.
In plain words
Cut the data into a past window and a future window. The future outputs depend on the state at the start of the future window and on the future inputs. That state depends only on the past. So remove from the future outputs the part that the future inputs explain, and keep only the part that the past explains. What is left is the state at the start of the future, seen through the output. Its size shows how many states the system has, and the SVD splits it into "how the state shows in the output" and "the states". Do the same one step later. Now you have the states at two times and the inputs and outputs between them, so one ordinary least squares fit gives the four system matrices. What the fit cannot explain is the noise.
The problem
Input. Samples and , a number of block rows for the past and for the future, and the order or a threshold to choose it.
Output. of order , the covariance of the residuals , and the singular values used to choose .
Notation. is the block Hankel matrix of the inputs with block rows and columns, block equal to . The first block rows are the past , the last are the future . and move the border one block row down. is the same for the outputs, and . The oblique projection of the rows of along the row space of onto the row space of is , where subtracts from each row of its orthogonal projection on the row space of , and is the pseudoinverse.
The algorithm
N4SID(u, y, i, n)- 1
U, Y ← the block Hankel matrices with 2i block rows and j = N - 2i + 1 columns - 2
L ← the lower triangular factor of the LQ factorization [U; Y] = L Q - 3
O_i ← Y_f /_(U_f) W_p - 4
O_(i-1) ← Y_f^- /_(U_f^-) W_p^+ - 5
(Us, σ) ← the SVD of O_i; choose n (a gap in σ, or given), with 1 ≤ n < i - 6
G ← Us[:, 1:n] diag(σ_1, ..., σ_n)^(1/2); G1 ← G without its last p rows - 7
X_i ← G⁺ O_i; X_(i+1) ← G1⁺ O_(i-1) - 8
θ ← the least squares solution of [X_(i+1); Y_(i|i)] = θ [X_i; U_(i|i)] - 9
(A, B; C, D) ← the blocks of θ; cov ← the residuals times their transpose, over j - 10
return (A, B, C, D, cov, σ)
and are the block row of and , the first block row of the future. Every data row is the matching row of times , and has orthonormal rows. So every inner product of data rows is the same inner product of rows of , and L3 to L9 run on rows of length instead of . The code never forms . L3 is the heart of the method: the future outputs are , the state is a linear function of the past , and the oblique projection keeps exactly the part along , which is . L4 does the same with the border one block row later, so it gives , the next states. L6 chooses the balanced split of the SVD; any other split gives the same model in other coordinates.
Example
Take the second order system
with poles and initial state , driven by a Gaussian white input with unit variance (seed 7), with and . Then , is , and is when computed on the rows of .
Noise-free data. The singular values of are , , and then values below . So . The estimated has the eigenvalues , , and the residual covariance is below , as the proof predicts.
Innovation noise (measurement). Add process and output noise in innovation form with and Gaussian with standard deviation , and use and (seed 1). The singular values are , , , and smaller. The gap is a factor of 120. The estimated poles are , and the output block of the residual covariance is , against the true noise variance .
Correctness
Claim. On noise-free data, with controllable, observable, , and the excitation condition , N4SID returns for a nonsingular , and a zero residual covariance.
Key invariant. and . This follows from one identity of the oblique projection: if and the row spaces of and meet only in 0, then .
The SVD then gives , so L7 returns and . The state equations hold exactly between these two sequences, and the regressor has full row rank, so L8 returns the stated . The full proof is below, including the reason why the computation on the rows of is the same as on the data.
Proof: N4SID recovers the system up to similarity from noise-free datafull
We work in exact real arithmetic, as in the real RAM, and assume that the LQ factorization, the SVD and the pseudoinverses are exact. The data come from a noise-free system
with , , , and controllable and observable. The number of block rows is with , and .
Notation. is the block Hankel matrix with block equal to . is its first block rows (the past) and its last block rows (the future). is the first block rows and the last block rows. , , , , are the same for , and , . , and . stacks , , and is the lower block triangular Toeplitz matrix of and the Markov parameters.
For matrices , , with columns, removes from each row of its orthogonal projection on the row space of , and the oblique projection is
Excitation condition.
Lemma 1 (data equations). , and . The same holds with past and future block rows: and .
Proof. Iterate the state equation: , and apply and add for the outputs. Read column by column.
Lemma 2 (the states lie in the past). The row space of is the row space of , and the rows of lie in it. The row space of is the row space of , and the rows of lie in it.
Proof. has full column rank because and is observable. By Lemma 1, , so the rows of lie in the row space of , and conversely the rows of are combinations of the rows of and . Then lies in it too. The same argument with block rows gives the second statement.
Lemma 3 (the oblique projection). Let , and assume that the row spaces of and meet only in 0. Then .
Proof. Since and the operation is linear, . Let and let , the orthogonal projection onto the column space of . Then , and it is enough to show . Let be in the range of , so . Then lies in the row space of ; it also lies in the row space of , so . Hence , and since is symmetric, .
Lemma 4 (O_i and O_(i-1)). Under (E), the oblique projection of L3 is , and the one of L4 is .
Proof. By Lemma 2, for some matrix , so by Lemma 1, . By Lemma 2 and (E), the row space of , which is that of , meets the row space of only in 0. Lemma 3 with , and gives . For use , and : the rows of and of are rows of the matrix in (E), so the intersection is again 0.
Lemma 5 (rank). has full row rank , and the matrix has full row rank , where is the block row of (the first block row of ).
Proof. Suppose . By Lemma 1, . These are combinations of rows of the matrix in (E), so , and . has rank because is controllable and , so . With forced, the first statement is the special case.
Lemma 6 (the factors). L5 and L6 give for a nonsingular , with . Then , and L7 gives and .
Proof. By Lemmas 4 and 5, is a product of a full column rank and a full row rank matrix, so it has rank , and its column space is that of . The first left singular vectors span this space, so with nonsingular, and . Deleting the last block row gives . Both and have full column rank, since , so is a left inverse, and the same for . Hence and .
Lemma 7 (the regression). The least squares problem of L8 has the unique solution
and the residual of L9 is zero.
Proof. Column of is , column of is , and column of is . The system equations give, column by column,
Substitute and and multiply the first block row by : the stated solves exactly. By Lemma 5 the right factor has full row rank, so the solution of the least squares problem is unique, and it is this zero-residual solution.
Lemma 8 (working on the rows of L). Computing every step on the rows of the LQ factor instead of the rows of the data gives the same results.
Proof. with , so each data row is the matching row of times . For rows and , , so all inner products are the same. The projections of L3 and L4 are combinations of rows formed with these inner products, so the projection of the data rows is the projection of the rows times . If , then , so and have the same left singular vectors and singular values. , so the state rows are the rows times . In L8, , so , and the residual covariance is .
Theorem. Under (E), with controllable, observable, and the order chosen as the rank of , N4SID returns for a nonsingular , and a zero residual covariance.
Proof. By Lemma 8 the algorithm computes the same quantities as on the data rows. Lemmas 4 to 7 give the result.
Remark (noise). With innovation noise, and , Van Overschee and De Moor (1994) show that as , tends to , where is a sequence of Kalman filter states. The residuals of L8 then estimate the noise covariances. That proof needs probability limits and is not repeated here; the test file checks the consistency of the poles and of the output noise variance by a measurement.
Complexity
In the real RAM, counting dense factorizations in the usual way. Let . L1 builds numbers. L2 is a Householder LQ factorization of the matrix, . L3 and L4 work on rows of length : each projection forms Gram matrices and pseudoinverses of at most matrices, . L5 is an SVD of an matrix, . L7 to L9 cost . The total is , and for long records the LQ factorization dominates. The extra space is for the Hankel matrices; everything after L2 is of size .
Properties
- Exact for noise-free data (theorem). Under the assumptions of the claim, the model has the true transfer function.
- Kalman filter states (theorem). With innovation noise, as , tends to , where is the state sequence of a bank of non-steady-state Kalman filters started from the past data (Van Overschee and De Moor 1994). This is why N4SID handles process noise, unlike basic MOESP.
- A bias of this version (theorem, cited). The two state sequences of L7 come from Kalman filters with different initial conditions. Van Overschee and De Moor (1996, Chapter 4) show that this simple version is asymptotically biased unless the data are noise-free or the input is white noise, and give modified algorithms without this bias. The test of the code uses a white input.
- Noise model. The residuals of L8 estimate , and , from which a steady-state Kalman gain follows by a Riccati equation.
- No local minima. There is no nonconvex search.
- Not efficient. The variance is larger than that of a prediction error method, which is often started from the N4SID estimate.
Variants and improvements
- Weightings. Multiply by weights before the SVD. Van Overschee and De Moor (1995) showed that N4SID, MOESP and CVA (Larimore 1990) differ only in these weights. The weights change the basis of the state and the finite-sample results, but not the limit.
- The unbiased and robust combined algorithms. The 1996 book gives versions that remove the bias of the simple version for general inputs; the robust one is the version used most in practice.
- Closed-loop subspace methods. The future inputs depend on past noise in closed loop, and the oblique projection is then biased. Predictor-based methods (SSARX, PBSID) avoid this.
- MOESP. Uses an orthogonal projection and the observability matrix instead of the state sequence.
- Deterministic and stochastic special cases. Without inputs, the same projections give a stochastic realization of a time series; without noise, the method is an exact realization from input-output data.
When to use it
Use N4SID to get a multivariable model with a noise model from open-loop data, with no starting value, and as the starting point of a prediction error fit. It gives the order from the singular values and handles many inputs and outputs. Do not use it as the final model when the best accuracy matters, or directly on closed-loop data.
Pitfalls
- Too few block rows. The method needs . With noise, must also be large enough for the Kalman filter states to be good, often several times the expected order.
- Too few samples. The LQ factorization needs , and the code rejects smaller . Accuracy needs much more.
- An input that is not rich enough. The excitation condition needs the input to be persistently exciting of order about . A step or a few sines do not satisfy it.
- Comparing matrices. The result is in other coordinates. Compare poles, Markov parameters or frequency responses.
- The order from a weak gap. With colored noise and many block rows, the singular values decrease slowly. Check several orders by validation on fresh data.
- Pseudoinverse thresholds. In floating point, the projections need thresholds in the pseudoinverses. A threshold that is too small makes the projection amplify noise; the code uses times the largest singular value.
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()
n4sid.py 180 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/n4sid/. The authors are listed in prov/0NXMFM.jsonl.
"""N4SID (Van Overschee and De Moor, 1994), the version that uses two state sequences.
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 in innovation form x_(k+1) = A x_k + B u_k + K e_k,
y_k = C x_k + D u_k + e_k, 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 2i block rows and j = N - 2i + 1
columns; one LQ factorization of [U; Y] = L Q; the oblique projections
O_i = Y_f /_(U_f) W_p and O_(i-1) = Y_f^- /_(U_f^-) W_p^+; an SVD of O_i that
gives Gamma_i and the order; the state sequences X_i = Gamma_i^+ O_i and
X_(i+1) = Gamma_(i-1)^+ O_(i-1); and one linear least squares problem for
A, B, C and D. The residuals give the noise covariances.
Every row of the data matrix is the matching row of L times Q, and Q has
orthonormal rows. So every projection and every least squares problem is
computed on the rows of L (vectors of length 2 i (m + p)), not on rows of
length j.
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, sub, transpose
__all__ = ["block_hankel", "householder_lq", "jacobi_svd", "pinv", "oblique_projection", "n4sid", "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-10):
"""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 oblique_projection(a, b, c):
"""Return a /_b c = (a / b_perp) (c / b_perp)^+ c, for matrices with the same row length.
x / b_perp = x - x b^T (b b^T)^+ b removes the part of each row of x that
lies in the row space of b.
"""
def perp(x):
return sub(x, mul(mul(mul(x, transpose(b)), pinv(mul(b, transpose(b)))), b))
return mul(mul(perp(a), pinv(perp(c))), c)
def simulate(A, B, C, D, u, x0, K=None, e=None):
"""Return y_0, ..., y_(N-1) of x_(k+1) = A x_k + B u_k + K e_k, y_k = C x_k + D u_k + e_k."""
x = list(x0)
n, out = len(x), []
for k, uk in enumerate(u):
ek = e[k] if e is not None else [0.0] * len(C)
out.append([sum(C[a][t] * x[t] for t in range(n)) + sum(D[a][c] * uk[c] for c in range(len(uk))) + ek[a]
for a in range(len(C))])
x = [sum(A[r][t] * x[t] for t in range(n)) + sum(B[r][c] * uk[c] for c in range(len(uk)))
+ (sum(K[r][a] * ek[a] for a in range(len(ek))) if K is not None else 0.0)
for r in range(n)]
return out
def n4sid(u, y, i, n=None, tol=1e-8):
"""Return (A, B, C, D, cov, s): the model, the residual covariance [[Q, S], [S^T, R]], and the singular values of O_i."""
m, p, N = len(u[0]), len(y[0]), len(u)
j = N - 2 * i + 1
if j < 2 * i * (m + p):
raise ValueError("n4sid: too few samples for i block rows")
U = block_hankel(u, 2 * i, j) # @line L1
Y = block_hankel(y, 2 * i, j)
L = householder_lq(U + Y) # @line L2
Lu, Ly = L[:2 * i * m], L[2 * i * m:]
Up, Uf = Lu[:i * m], Lu[i * m:]
Yp, Yf = Ly[:i * p], Ly[i * p:]
Oi = oblique_projection(Yf, Uf, Up + Yp) # @line L3
Up1, Uf1 = Lu[:(i + 1) * m], Lu[(i + 1) * m:]
Yp1, Yf1 = Ly[:(i + 1) * p], Ly[(i + 1) * p:]
Oi1 = oblique_projection(Yf1, Uf1, Up1 + Yp1) # @line L4
Us, s, _ = jacobi_svd(Oi) # @line L5
if n is None:
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("n4sid: need 1 <= n < i and n at most the rank of O_i")
G = [[Us[r][k] * math.sqrt(s[k]) for k in range(n)] for r in range(i * p)] # @line L6
G1 = G[:-p]
Xi = mul(pinv(G), Oi) # @line L7
Xi1 = mul(pinv(G1), Oi1)
lhs = Xi1 + Ly[i * p:(i + 1) * p]
rhs = Xi + Lu[i * m:(i + 1) * m]
theta = mul(lhs, pinv(rhs)) # @line L8
A = [row[:n] for row in theta[:n]]
B = [row[n:] for row in theta[:n]]
C = [row[:n] for row in theta[n:]]
D = [row[n:] for row in theta[n:]]
res = sub(lhs, mul(theta, rhs)) # @line L9
cov = [[v / j for v in row] for row in mul(res, transpose(res))]
return A, B, C, D, cov, s # @line L10
test_n4sid.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/n4sid/. The authors are listed in prov/0NXMFM.jsonl.
import random
from ctlmat import add, charpoly, mul, polyroots, transpose
from n4sid import householder_lq, n4sid, oblique_projection, 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 _rand(rng, r, c):
return [[rng.uniform(-1, 1) for _ in range(c)] for _ in range(r)]
def test_oblique_projection_splits_a_sum():
# if a = M c + P b and the row spaces of b and c meet only in 0, then a /_b c = M c
rng = random.Random(2)
for _ in range(10):
b, c = _rand(rng, 2, 9), _rand(rng, 3, 9)
M, P = _rand(rng, 4, 3), _rand(rng, 4, 2)
a = add(mul(M, c), mul(P, b))
assert _close(oblique_projection(a, b, c), mul(M, c), 1e-10)
def test_lq_factor():
rng = random.Random(1)
a = _rand(rng, 5, 11)
L = householder_lq(a)
assert all(L[r][c] == 0.0 for r in range(5) for c in range(r + 1, 5))
assert _close(mul(L, transpose(L)), mul(a, transpose(a)), 1e-12)
def test_exact_siso():
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, cov, s = n4sid(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
for g, g0 in zip(_markov(A, B, C, 12), _markov(A0, B0, C0, 12)):
assert _close(g, g0, 1e-10)
assert all(abs(v) < 1e-20 for row in cov for v in row)
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, [1.0, 0.0, -1.0])
A, B, C, D, cov, s = n4sid(u, y, 4)
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_innovation_noise():
# measurement: innovation form with K = [0.5, 0.2]^T, e white with variance 0.01,
# white input, N = 2000, i = 5
A0 = [[0.7, 0.4], [-0.4, 0.7]]
B0 = [[1.0], [0.5]]
C0 = [[1.0, 0.0]]
D0 = [[0.2]]
K0 = [[0.5], [0.2]]
for seed in (1, 2, 3):
rng = random.Random(seed)
u = [[rng.gauss(0.0, 1.0)] for _ in range(2000)]
e = [[rng.gauss(0.0, 0.1)] for _ in range(2000)]
y = simulate(A0, B0, C0, D0, u, [0.0, 0.0], K0, e)
A, B, C, D, cov, s = n4sid(u, y, 5, n=2)
assert s[1] > 50 * s[2]
assert _eig_error(A, A0) < 0.01
assert abs(D[0][0] - 0.2) < 0.02
assert abs(cov[2][2] - 0.01) < 0.002
def test_too_few_samples_rejected():
u = [[1.0]] * 20
try:
n4sid(u, u, 5)
except ValueError:
return
assert False, "n4sid must reject too few samples"
History
Akaike's work on canonical correlations in the 1970s and Larimore's canonical variate analysis of 1990 used projections of the future on the past for time series and for systems with inputs. Van Overschee and De Moor gave the oblique projection, the Kalman filter interpretation of the states, and the N4SID algorithms in Automatica in 1994. In 1995 they proved a unifying theorem that places N4SID, MOESP and CVA in one framework, and their 1996 book became the standard reference on subspace identification.
References
- Peter Van Overschee and Bart De Moor, N4SID: Subspace algorithms for the identification of combined deterministic-stochastic systems, Automatica 30(1), 75-93, 1994, the oblique projection, the Kalman filter interpretation of the state sequences, and the algorithms that use them
- Peter Van Overschee and Bart De Moor, Subspace Identification for Linear Systems: Theory, Implementation, Applications, Kluwer Academic Publishers, 1996 (ISBN 978-1-4613-8061-0), Chapter 4 (Combined Deterministic-Stochastic Identification), pp. 95-134
- Peter Van Overschee and Bart De Moor, A unifying theorem for three subspace system identification algorithms, Automatica 31(12), 1853-1864, 1995, N4SID, MOESP and CVA as weighted versions of one algorithm
- Wallace E. Larimore, Canonical variate analysis in identification, filtering, and adaptive control, Proceedings of the 29th IEEE Conference on Decision and Control, 596-604, 1990, the canonical variate analysis (CVA) weighting
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 0NXMFM Edit this page History Report an error Markdown