Algorithmadvanced
Eigensystem realization algorithm
Also called ERA.
Fits a state-space model to measured impulse response data by a truncated SVD of their block Hankel matrix; exact and balanced on noise-free data.
- Solves
- Realization problem
- Time
- O(N^3 m p (m + p)) worst
- Space
- O(N^2 m p) extra
- Where
- N = the number of block rows and block columns of the Hankel matrix; m = the number of inputs; n = the chosen order; p = the number of outputs
- Model
- Real RAM
- Properties
- deterministicexactnot iterativeoffline
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Jer Nan Juang, Richard S. Pappa, 1985
The eigensystem realization algorithm (ERA) fits a discrete-time state-space model , to measured samples of the impulse response, the Markov parameters and . It puts the samples in a block Hankel matrix, takes its singular value decomposition, keeps the largest singular values, and computes , and from the kept factors. The Ho-Kalman algorithm does the same with an exact rank and needs exact data. ERA replaces the exact rank by a truncated SVD, so it works on noisy measurements, and the size of the dropped singular values shows how much of the data the model leaves out. On noise-free data ERA returns a minimal realization that is balanced over the data window. The name comes from its first use: the eigenvalues and eigenvectors of give the frequencies, damping ratios and mode shapes of a vibrating structure.
In plain words
Tap a structure and record the response at a few sensors. Write the samples in a table where each row is the row above it moved one step in time. If the structure has a few modes, the table is almost a sum of a few simple patterns, and the rest is noise. The singular value decomposition sorts the patterns by size. Keep the large ones and drop the small ones. The kept patterns, taken from the table and from the same table moved one step, give a small model. Its eigenvalues are the modes of the structure.
The problem
Input. Measured matrices of size (the response at outputs to a unit pulse at each of inputs, sampled with period ), the number of block rows, and the order or a rule to choose it.
Output. of order whose Markov parameters are close to the data, and the singular values of the Hankel matrix.
The block Hankel matrix has block equal to for , so it is . The shifted matrix has block equal to . There is no separate page for the Hankel matrix; the Ho-Kalman page shows its layout.
The algorithm
ERA(h, N, n)- 1
H ← the block Hankel matrix of h_1, ..., h_(2N-1) - 2
Hs ← the shifted block Hankel matrix of h_2, ..., h_(2N) - 3
(U, Σ, V) ← the singular value decomposition of H - 4
if n is not given then n ← the number of σ_k above tol · σ_1 - 5
Un, Vn ← the first n columns of U and V; Σn ← diag(σ_1, ..., σ_n) - 6
A ← Σn^(-1/2) Unᵀ Hs Vn Σn^(-1/2) - 7
B ← the first m columns of Σn^(1/2) Vnᵀ - 8
C ← the first p rows of Un Σn^(1/2) - 9
D ← h_0 - 10
return (A, B, C, D, Σ)
L3 is the only expensive step. The implementation uses a one-sided Jacobi method, which orthogonalizes the columns of by plane rotations. L4 is the order choice: on exact data the singular values after the -th are zero, and on noisy data the user looks for a gap. L6 is the least squares solution of : the shifted Hankel matrix is the same product of factors with one extra in the middle. L7 and L8 take the first block column and the first block row of the factors, as in Ho-Kalman.
Example
Take a structure with two lightly damped modes, and , one input and two outputs, sampled with s. The true model is the real modal form with blocks for , , with , and . With , is and uses .
Exact data. The singular values are
So L4 picks . The eigenvalues of are and . Mapped back by , they give , and , , correct to about . The result reproduces also for beyond the data, and its 10-step observability and controllability gramians are both .
Noisy data (measurement). Add Gaussian noise with standard deviation to every entry of , with seed 1. The singular values become
The gap after the fourth value is a factor of 25, so is clear. The recovered modes are , and , . Over the seeds 1 to 10, the largest error of a discrete eigenvalue was between and . The damping ratio of the lighter mode is the least accurate number, which is usual for ERA.
Correctness
Claim. If the data are exact Markov parameters of a system of order at most and is the rank of , ERA returns a minimal realization of the data. Its -step observability and controllability gramians are both . With noise whose Hankel matrix has , the gap after survives.
Key invariant. and for the observability and controllability matrices of a minimal realization. The SVD factors and are and for one nonsingular .
L6 then gives , L7 gives and L8 gives . The gramians are because and have orthonormal columns. The noise statement is Weyl's inequality for singular values. The full proof is below.
Proof: ERA returns a balanced minimal realization on exact data, and the order gap survives small noisefull
We work in exact real arithmetic, as in the real RAM, and assume that the SVD of L3 is exact. The data are , matrices of size . is the block Hankel matrix with block equal to for , and has block equal to . The SVD is with . For the chosen order , and hold the first columns of and , and with . Write
Then L6 to L8 read , and , with and . Since and , we have and .
Exact data
Assume that some system of order at most has for , let be a minimal realization of order , and let and be its -step observability and controllability matrices: stacks and lines up for .
Lemma 1 (factorization and rank). , , and . So , and L4 with any threshold below chooses .
Proof. Block of is , and block of is . The minimal realization is controllable and observable (see minimal realization). Its order is , so by the Kalman rank condition has full column rank and has full row rank . The product of an injective map and a surjective map through has rank . The number of nonzero singular values is the rank.
From now on .
Lemma 2 (the SVD factors are the system factors in new coordinates). There is a nonsingular matrix with and .
Proof. Since , the truncated SVD is exact: . The column space of is the column space of , and by Lemma 1 it is also the column space of , because is onto. So for some matrix , and with . has rank , so is nonsingular. Now , and has full column rank, so .
Lemma 3 (the result is a minimal realization). , and . Hence for every , and with from L9 the result is a minimal realization.
Proof. By Lemmas 1 and 2, . The first block column of is , so . The first block row of is , so . Then . The order is , the minimal order.
Lemma 4 (balanced on the data window). Let and be the -step observability and controllability matrices of the result . Then .
Proof. , so . , so . Then and .
The two products are the -step observability and controllability gramians of the result. They are equal and diagonal, which is the definition of a balanced realization over the window of steps. If is Schur, they converge to the infinite gramians as .
Theorem (exact data). If the data have a realization of order at most and is the rank of , ERA returns a minimal realization of the data whose -step gramians are both .
Proof. Lemmas 1, 3 and 4.
Noisy data
Lemma 5 (Weyl's inequality for singular values). For matrices and of the same size, for every , where is the induced 2-norm.
Proof. By the Courant-Fischer theorem, . For each unit , . Take the subspace that attains the maximum for ; then . Exchange the roles of and for the other inequality.
Theorem (the gap survives noise). Let the measured parameters be , and let be the block Hankel matrix of the . If , where is the rank of the noise-free , then the singular values of the measured Hankel matrix satisfy . So the gap after the -th singular value shows the true order.
Proof. By Lemma 5, and .
Near data with , the dominant singular subspaces depend continuously on the data (Wedin's theorem). The factors and are fixed only up to an orthogonal change of basis, which changes by a similarity, so the eigenvalues of depend continuously on the data. So for small enough noise the eigenvalues of are close to the true poles. This is a statement about the limit of small noise; it gives no bias bound for a fixed noise level.
Complexity
In the real RAM, counting a dense SVD of an matrix with as operations, as for the other dense factorizations. Here and , so L3 costs , which is at most . L6 forms in . L7 and L8 cost . The SVD dominates. The extra space is for , and the factors.
The SVD is iterative in every real implementation. For the one-sided Jacobi method of the code, one sweep costs . The number of sweeps is a measurement, not a bound: the code stops when every pair of columns is orthogonal to a relative tolerance of , and it allows at most 80 sweeps.
Properties
- Exact on exact data (theorem). The result is a minimal realization, as with Ho-Kalman.
- Balanced over the window (theorem). The -step gramians are equal and diagonal. For a system with Schur they tend to the infinite gramians as grows, so the singular values approach the Hankel singular values and the result approaches a balanced realization.
- Built-in model reduction. Keeping fewer than the rank of drops the weakest states of the balanced form, much like balanced truncation.
- Order gap under noise (theorem). If the noise in the Hankel matrix has induced 2-norm below , the gap at the true order is visible.
- Biased under noise. For a fixed noise level the eigenvalues are biased, and the damping ratios are the most affected numbers. The bias goes to zero with the noise level (the continuity part of the proof), but the method gives no bound on it for a fixed noise level.
- Deterministic and not recursive. New data need a new SVD.
Variants and improvements
- Rectangular Hankel matrices. Use block rows and block columns with and both larger than . Using more columns than rows averages the noise. This is the form in Juang and Pappa 1985.
- ERA/DC. ERA with data correlations (Juang, Cooper and Wright, 1988) applies the SVD to products of Hankel matrices, which reduces the effect of noise.
- OKID and ERA. Observer/Kalman filter identification estimates the Markov parameters from general input-output data, not only from pulse responses, and then runs ERA.
- Modal accuracy indicators. Juang and Pappa added the modal amplitude coherence and the modal phase collinearity to separate true modes from noise modes.
- Shift with the observability factor. Compute from by least squares. This uses only and needs no . It is the form of Kung's method and of MOESP.
- Subspace identification. Avoids the estimate of the Markov parameters and works directly on input-output data.
When to use it
Use ERA for modal analysis of structures and flexible systems from impact or pulse tests, for a state-space model from a measured or simulated impulse response, and as a reduction step after an FIR or high-order ARX fit. It is a direct method with no iteration and no starting value, so it also gives starting values for the prediction error method. Do not use it with input-output data from a general input without first estimating the Markov parameters, or use a subspace method directly.
Pitfalls
- The order from a bad gap. Real data often show no clean gap. Taking too many states adds noise modes with random damping; taking too few merges close modes. Check the modes with a stabilization diagram (the poles for a range of ) or the modal accuracy indicators.
- Too few block rows. The method needs and , and in practice much more, so that every mode appears in many rows. With too small the singular values do not separate.
- Leaving in the Hankel matrix. starts at . A direct feedthrough that enters adds a spurious state.
- A mode that is lightly excited. A mode that one input barely excites, or that one output barely sees, has a small singular value and can fall below the noise. Add inputs or sensors.
- Continuous poles from discrete ones. is correct only for poles below the Nyquist frequency ; a faster mode is aliased.
- Large problems. A full SVD of a large is expensive. Use a randomized or Lanczos SVD for the leading singular values only.
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()
eigensystem_realization_algorithm.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eigensystem-realization-algorithm/. The authors are listed in prov/8Q2BQ4.jsonl.
"""The eigensystem realization algorithm (ERA) of Juang and Pappa (1985).
Input: measured Markov parameters h_0, ..., h_(2N) (the impulse response
samples of a discrete-time system, p by m matrices as lists of rows), the
number N of block rows and block columns, and the order n (or None to pick
the order from the singular values with a relative threshold tol).
With H the N p by N m block Hankel matrix with blocks h_(i+j-1), Hs the
shifted one with blocks h_(i+j), and H = U S V^T a singular value
decomposition truncated to the n largest singular values:
A = S^(-1/2) U^T Hs V S^(-1/2), B = (S^(1/2) V^T)[:, 0:m],
C = (U S^(1/2))[0:p, :], D = h_0.
On exact data of a system of order at most N, with n the rank of H, the
result is a minimal realization. On noisy data it is an approximation whose
error is governed by the singular values that are dropped.
The SVD is a one-sided Jacobi (Hestenes) method in floating point. Each sweep
costs O(a b^2) for an a by b matrix with a >= b; the sweeps stop when every
pair of columns is orthogonal to a relative tolerance of 1e-15.
"""
import cmath
import math
from ctlmat import mat_power, mul, transpose
__all__ = ["hankel", "jacobi_svd", "era", "markov_parameters", "continuous_poles"]
def hankel(h, rows, cols, shift=0):
"""Return the block Hankel matrix whose block (i, j) is h[i + j + 1 + shift]."""
p = len(h[0])
out = []
for i in range(rows):
for a in range(p):
line = []
for j in range(cols):
line.extend(float(v) for v in h[i + j + 1 + shift][a])
out.append(line)
return out
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]
vsorted = [vcols[j] for j in order]
return transpose(ucols), s, transpose(vsorted)
def era(h, N, n=None, tol=1e-8):
"""Return (A, B, C, D, s): an order n realization and the singular values of H."""
if len(h) < 2 * N + 1:
raise ValueError("era: need h_0, ..., h_(2N)")
p, m = len(h[0]), len(h[0][0])
H = hankel(h, N, N) # @line L1
Hs = hankel(h, N, N, shift=1) # @line L2
U, s, V = jacobi_svd(H) # @line L3
if n is None: # @line L4
n = sum(1 for v in s if v > tol * s[0])
if n < 1 or s[n - 1] <= 0.0:
raise ValueError("era: the order must be at most the rank of H")
Un = [row[:n] for row in U] # @line L5
Vn = [row[:n] for row in V]
root = [math.sqrt(v) for v in s[:n]]
core = mul(mul(transpose(Un), Hs), Vn)
A = [[core[i][j] / (root[i] * root[j]) for j in range(n)] for i in range(n)] # @line L6
B = [[root[i] * Vn[c][i] for c in range(m)] for i in range(n)] # @line L7
C = [[Un[a][j] * root[j] for j in range(n)] for a in range(p)] # @line L8
D = [[float(v) for v in row] for row in h[0]] # @line L9
return A, B, C, D, s # @line L10
def markov_parameters(A, B, C, D, K):
"""Return [D, C B, C A B, ..., C A^(K-1) B]."""
out = [[list(row) for row in D]]
for k in range(1, K + 1):
out.append(mul(mul(C, mat_power(A, k - 1)), B))
return out
def continuous_poles(eigs, h_period):
"""Map discrete poles lambda to s = ln(lambda) / h, with the principal branch."""
return [cmath.log(complex(z)) / h_period for z in eigs]
test_eigensystem_realization_algorithm.py 126 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/eigensystem-realization-algorithm/. The authors are listed in prov/8Q2BQ4.jsonl.
import cmath
import math
import random
from ctlmat import charpoly, mul, polyroots, transpose
from eigensystem_realization_algorithm import continuous_poles, era, hankel, jacobi_svd, markov_parameters
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 _modal_system(h):
# two lightly damped modes: (omega, zeta) = (2, 0.05) and (5, 0.02), period h
A = [[0.0] * 4 for _ in range(4)]
for b, (omega, zeta) in enumerate([(2.0, 0.05), (5.0, 0.02)]):
z = cmath.exp(complex(-zeta * omega, omega * math.sqrt(1 - zeta * zeta)) * h)
A[2 * b][2 * b], A[2 * b][2 * b + 1] = z.real, z.imag
A[2 * b + 1][2 * b], A[2 * b + 1][2 * b + 1] = -z.imag, z.real
B = [[1.0], [0.0], [1.0], [0.0]]
C = [[1.0, 0.0, 0.5, 0.0], [0.0, 1.0, 0.0, 1.0]]
D = [[0.0], [0.0]]
return A, B, C, D
def _max_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 test_svd_known_factors():
U, s, V = jacobi_svd([[3.0, 0.0], [4.0, 5.0]])
assert abs(s[0] - 3 * math.sqrt(5)) < 1e-12
assert abs(s[1] - math.sqrt(5)) < 1e-12
back = mul(mul(U, [[s[0], 0.0], [0.0, s[1]]]), transpose(V))
assert _close(back, [[3.0, 0.0], [4.0, 5.0]], 1e-12)
def test_svd_random_matrices():
rng = random.Random(3)
for _ in range(20):
r, c = rng.randint(1, 7), rng.randint(1, 7)
a = [[rng.uniform(-1, 1) for _ in range(c)] for _ in range(r)]
U, s, V = jacobi_svd(a)
k = min(r, c)
assert all(s[i] >= s[i + 1] for i in range(k - 1))
S = [[s[i] if i == j else 0.0 for j in range(k)] for i in range(k)]
assert _close(mul(mul(U, S), transpose(V)), a, 1e-12)
eye = [[1.0 if i == j else 0.0 for j in range(k)] for i in range(k)]
assert _close(mul(transpose(U), U), eye, 1e-12)
assert _close(mul(transpose(V), V), eye, 1e-12)
def test_exact_data_recovers_the_system():
h = 0.1
A0, B0, C0, D0 = _modal_system(h)
N = 10
hk = markov_parameters(A0, B0, C0, D0, 2 * N)
A, B, C, D, s = era(hk, N)
# the order is chosen by the singular values: four are nonzero
assert len(A) == 4
assert s[4] < 1e-12 * s[0]
far = markov_parameters(A, B, C, D, 3 * N)
true = markov_parameters(A0, B0, C0, D0, 3 * N)
for k in range(3 * N + 1):
assert _close(far[k], true[k], 1e-10)
assert _max_eig_error(A, A0) < 1e-10
# modal parameters from s = ln(lambda) / h
poles = continuous_poles(polyroots(charpoly(A)), h)
pairs = sorted((abs(z), -z.real / abs(z)) for z in poles if z.imag > 0)
assert abs(pairs[0][0] - 2.0) < 1e-9 and abs(pairs[0][1] - 0.05) < 1e-9
assert abs(pairs[1][0] - 5.0) < 1e-9 and abs(pairs[1][1] - 0.02) < 1e-9
def test_result_is_balanced():
A0, B0, C0, D0 = _modal_system(0.1)
N = 10
hk = markov_parameters(A0, B0, C0, D0, 2 * N)
A, B, C, D, s = era(hk, N)
n = len(A)
obs = []
ctr_blocks = []
for k in range(N):
Ak = [[1.0 if i == j else 0.0 for j in range(n)] for i in range(n)]
for _ in range(k):
Ak = mul(Ak, A)
obs.extend(mul(C, Ak))
ctr_blocks.append(mul(Ak, B))
ctr = [sum((blk[i] for blk in ctr_blocks), []) for i in range(n)]
sigma = [[s[i] if i == j else 0.0 for j in range(n)] for i in range(n)]
assert _close(mul(transpose(obs), obs), sigma, 1e-9)
assert _close(mul(ctr, transpose(ctr)), sigma, 1e-9)
def test_noisy_data_gives_close_eigenvalues():
# measurement: noise with standard deviation 0.01 on every Markov parameter
A0, B0, C0, D0 = _modal_system(0.1)
N = 10
hk = markov_parameters(A0, B0, C0, D0, 2 * N)
for seed in range(1, 6):
rng = random.Random(seed)
hn = [[[v + (rng.gauss(0.0, 0.01) if k > 0 else 0.0) for v in row] for row in hk[k]]
for k in range(len(hk))]
A, B, C, D, s = era(hn, N, n=4)
# a clear gap after the fourth singular value
assert s[3] > 10 * s[4]
assert _max_eig_error(A, A0) < 0.02
def test_order_above_rank_is_rejected():
hk = markov_parameters([[0.5]], [[1.0]], [[1.0]], [[0.0]], 6)
try:
era(hk, 3, n=2)
except ValueError:
return
assert False, "an order above the rank of H must be rejected"
def test_hankel_layout():
hk = [[[float(k)]] for k in range(7)]
assert hankel(hk, 3, 3) == [[1.0, 2.0, 3.0], [2.0, 3.0, 4.0], [3.0, 4.0, 5.0]]
assert hankel(hk, 3, 3, shift=1)[0] == [2.0, 3.0, 4.0]
History
Ho and Kalman gave the exact realization from the Hankel matrix in 1966. Zeiger and McEwen used the singular value decomposition with Ho's algorithm in 1974, and Kung presented an SVD method for identification and model reduction in 1978. Juang and Pappa, at NASA Langley, combined these ideas with modal accuracy indicators and published ERA in the Journal of Guidance, Control, and Dynamics in 1985. Their aim was the modal survey of large flexible space structures. ERA and its descendants (ERA/DC, OKID) became standard tools of experimental modal analysis.
References
- Jer-Nan Juang and Richard S. Pappa, An eigensystem realization algorithm for modal parameter identification and model reduction, Journal of Guidance, Control, and Dynamics 8(5), 620-627, 1985, the algorithm, the choice of order from the singular values, and the modal accuracy indicators
- Jer-Nan Juang, Applied System Identification, Prentice Hall, 1994, the chapter on system realization (ERA and its variants)
- B. L. Ho and Rudolf E. Kalman, Effective construction of linear state-variable models from input/output functions, Regelungstechnik 14(1-12), 545-548, 1966, the exact realization from the Hankel matrix that ERA extends to noisy data
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 8Q2BQ4 Edit this page History Report an error Markdown