Algorithm Search⌘K

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.

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
Properties
deterministicexactnot iterativeoffline
Origin
Jer Nan Juang, Richard S. Pappa, 1985

The eigensystem realization algorithm (ERA) fits a discrete-time state-space model xk+1=Axk+Bukx_{k+1} = A x_k + B u_k, yk=Cxk+Duky_k = C x_k + D u_k to measured samples of the impulse response, the Markov parameters h0=Dh_0 = D and hk=CAk−1Bh_k = C A^{k-1} B. It puts the samples in a block Hankel matrix, takes its singular value decomposition, keeps the nn largest singular values, and computes AA, BB and CC 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 AA 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 h0,h1,…,h2Nh_0, h_1, \ldots, h_{2N} of size p×mp \times m (the response at pp outputs to a unit pulse at each of mm inputs, sampled with period hh), the number NN of block rows, and the order nn or a rule to choose it.

Output. (A,B,C,D)(A, B, C, D) of order nn whose Markov parameters CAk−1BC A^{k-1} B are close to the data, and the singular values of the Hankel matrix.

The block Hankel matrix HH has block (i,j)(i, j) equal to hi+j−1h_{i+j-1} for i,j=1,…,Ni, j = 1, \ldots, N, so it is Np×NmNp \times Nm. The shifted matrix HsH_s has block (i,j)(i, j) equal to hi+jh_{i+j}. There is no separate page for the Hankel matrix; the Ho-Kalman page shows its layout.

The algorithm

  1. ERA(h, N, n)
  2. 1H ← the block Hankel matrix of h_1, ..., h_(2N-1)
  3. 2Hs ← the shifted block Hankel matrix of h_2, ..., h_(2N)
  4. 3(U, Σ, V) ← the singular value decomposition of H
  5. 4if n is not given then n ← the number of σ_k above tol · σ_1
  6. 5Un, Vn ← the first n columns of U and V; Σn ← diag(σ_1, ..., σ_n)
  7. 6A ← Σn^(-1/2) Unᵀ Hs Vn Σn^(-1/2)
  8. 7B ← the first m columns of Σn^(1/2) Vnᵀ
  9. 8C ← the first p rows of Un Σn^(1/2)
  10. 9D ← h_0
  11. 10return (A, B, C, D, Σ)

L3 is the only expensive step. The implementation uses a one-sided Jacobi method, which orthogonalizes the columns of HH by plane rotations. L4 is the order choice: on exact data the singular values after the nn-th are zero, and on noisy data the user looks for a gap. L6 is the least squares solution of UnΣn1/2A Σn1/2VnT=HsU_n \Sigma_n^{1/2} A \, \Sigma_n^{1/2} V_n^T = H_s: the shifted Hankel matrix is the same product of factors with one extra AA 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, (ω,ζ)=(2 rad/s,0.05)(\omega, \zeta) = (2\ \text{rad/s}, 0.05) and (5 rad/s,0.02)(5\ \text{rad/s}, 0.02), one input and two outputs, sampled with h=0.1h = 0.1 s. The true model is the real modal form with blocks (Re⁡zIm⁡z−Im⁡zRe⁡z)\begin{pmatrix} \operatorname{Re} z & \operatorname{Im} z \\ -\operatorname{Im} z & \operatorname{Re} z \end{pmatrix} for z=eshz = e^{s h}, s=−ζω+iω1−ζ2s = -\zeta \omega + i \omega \sqrt{1 - \zeta^2}, with B=(1,0,1,0)TB = (1, 0, 1, 0)^T, C=(100.500101)C = \begin{pmatrix} 1 & 0 & 0.5 & 0 \\ 0 & 1 & 0 & 1 \end{pmatrix} and D=0D = 0. With N=10N = 10, HH is 20×1020 \times 10 and uses h1,…,h19h_1, \ldots, h_{19}.

Exact data. The singular values are

7.452986,4.507395,3.448610,1.240241,0,…,0.7.452986, \quad 4.507395, \quad 3.448610, \quad 1.240241, \quad 0, \ldots, 0.

So L4 picks n=4n = 4. The eigenvalues of AA are 0.86890±0.47457i0.86890 \pm 0.47457 i and 0.97036±0.19645i0.97036 \pm 0.19645 i. Mapped back by s=ln⁡(z)/hs = \ln(z) / h, they give ω=5\omega = 5, ζ=0.02\zeta = 0.02 and ω=2\omega = 2, ζ=0.05\zeta = 0.05, correct to about 10−1410^{-14}. The result reproduces hkh_k also for kk beyond the data, and its 10-step observability and controllability gramians are both diag⁡(7.452986,4.507395,3.448610,1.240241)\operatorname{diag}(7.452986, 4.507395, 3.448610, 1.240241).

Noisy data (measurement). Add Gaussian noise with standard deviation 0.010.01 to every entry of h1,…,h20h_1, \ldots, h_{20}, with seed 1. The singular values become

7.4412,4.4975,3.4678,1.2309,0.0496,0.0422,…7.4412, \quad 4.4975, \quad 3.4678, \quad 1.2309, \quad 0.0496, \quad 0.0422, \ldots

The gap after the fourth value is a factor of 25, so n=4n = 4 is clear. The recovered modes are ω=4.9905\omega = 4.9905, ζ=0.02486\zeta = 0.02486 and ω=1.9896\omega = 1.9896, ζ=0.04882\zeta = 0.04882. Over the seeds 1 to 10, the largest error of a discrete eigenvalue was between 0.00160.0016 and 0.00850.0085. 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 NN and nn is the rank of HH, ERA returns a minimal realization of the data. Its NN-step observability and controllability gramians are both Σn\Sigma_n. With noise whose Hankel matrix EE has ∥E∥2<σn/2\lVert E \rVert_2 < \sigma_n / 2, the gap after σn\sigma_n survives.

Key invariant. H=OCH = \mathcal{O} \mathcal{C} and Hs=OA0CH_s = \mathcal{O} A_0 \mathcal{C} for the observability and controllability matrices of a minimal realization. The SVD factors P=UnΣn1/2P = U_n \Sigma_n^{1/2} and Q=Σn1/2VnTQ = \Sigma_n^{1/2} V_n^T are OT\mathcal{O} T and T−1CT^{-1} \mathcal{C} for one nonsingular TT.

L6 then gives T−1A0TT^{-1} A_0 T, L7 gives T−1B0T^{-1} B_0 and L8 gives C0TC_0 T. The gramians are PTP=QQT=ΣnP^T P = Q Q^T = \Sigma_n because UnU_n and VnV_n 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 h0,…,h2Nh_0, \ldots, h_{2N}, matrices of size p×mp \times m. HH is the Np×NmNp \times Nm block Hankel matrix with block (i,j)(i, j) equal to hi+j−1h_{i+j-1} for i,j=1,…,Ni, j = 1, \ldots, N, and HsH_s has block (i,j)(i, j) equal to hi+jh_{i+j}. The SVD is H=UΣVTH = U \Sigma V^T with σ1≥σ2≥⋯≥0\sigma_1 \ge \sigma_2 \ge \cdots \ge 0. For the chosen order nn, UnU_n and VnV_n hold the first nn columns of UU and VV, and Σn=diag⁡(σ1,…,σn)\Sigma_n = \operatorname{diag}(\sigma_1, \ldots, \sigma_n) with σn>0\sigma_n > 0. Write

P=UnΣn1/2∈RNp×n,Q=Σn1/2VnT∈Rn×Nm.P = U_n \Sigma_n^{1/2} \in \mathbb{R}^{Np \times n}, \qquad Q = \Sigma_n^{1/2} V_n^T \in \mathbb{R}^{n \times Nm}.

Then L6 to L8 read A=P+HsQ+A = P^{+} H_s Q^{+}, B=Q[:,1:m]B = Q[:, 1{:}m] and C=P[1:p,:]C = P[1{:}p, :], with P+=Σn−1/2UnTP^{+} = \Sigma_n^{-1/2} U_n^T and Q+=VnΣn−1/2Q^{+} = V_n \Sigma_n^{-1/2}. Since UnTUn=IU_n^T U_n = I and VnTVn=IV_n^T V_n = I, we have P+P=IP^{+} P = I and QQ+=IQ Q^{+} = I.

Exact data

Assume that some system of order at most NN has hk=CAk−1Bh_k = C A^{k-1} B for k≥1k \ge 1, let (A0,B0,C0)(A_0, B_0, C_0) be a minimal realization of order n0n_0, and let O\mathcal{O} and C\mathcal{C} be its NN-step observability and controllability matrices: O\mathcal{O} stacks C0A0iC_0 A_0^{i} and C\mathcal{C} lines up A0jB0A_0^{j} B_0 for i,j=0,…,N−1i, j = 0, \ldots, N-1.

Lemma 1 (factorization and rank). H=OCH = \mathcal{O} \mathcal{C}, Hs=OA0CH_s = \mathcal{O} A_0 \mathcal{C}, and rank⁡H=n0\operatorname{rank} H = n_0. So σn0>0=σn0+1\sigma_{n_0} > 0 = \sigma_{n_0 + 1}, and L4 with any threshold below σn0/σ1\sigma_{n_0} / \sigma_1 chooses n=n0n = n_0.

Proof. Block (i,j)(i, j) of OC\mathcal{O} \mathcal{C} is C0A0i−1A0j−1B0=hi+j−1C_0 A_0^{i-1} A_0^{j-1} B_0 = h_{i+j-1}, and block (i,j)(i, j) of OA0C\mathcal{O} A_0 \mathcal{C} is hi+jh_{i+j}. The minimal realization is controllable and observable (see minimal realization). Its order is n0≤Nn_0 \le N, so by the Kalman rank condition O\mathcal{O} has full column rank n0n_0 and C\mathcal{C} has full row rank n0n_0. The product of an injective map and a surjective map through Rn0\mathbb{R}^{n_0} has rank n0n_0. The number of nonzero singular values is the rank. □\square

From now on n=n0n = n_0.

Lemma 2 (the SVD factors are the system factors in new coordinates). There is a nonsingular n×nn \times n matrix TT with P=OTP = \mathcal{O} T and Q=T−1CQ = T^{-1} \mathcal{C}.

Proof. Since σn+1=0\sigma_{n+1} = 0, the truncated SVD is exact: H=UnΣnVnT=PQH = U_n \Sigma_n V_n^T = P Q. The column space of HH is the column space of UnU_n, and by Lemma 1 it is also the column space of O\mathcal{O}, because C\mathcal{C} is onto. So Un=OGU_n = \mathcal{O} G for some n×nn \times n matrix GG, and P=OTP = \mathcal{O} T with T=GΣn1/2T = G \Sigma_n^{1/2}. PP has rank nn, so TT is nonsingular. Now OTQ=PQ=H=OC\mathcal{O} T Q = P Q = H = \mathcal{O} \mathcal{C}, and O\mathcal{O} has full column rank, so TQ=CT Q = \mathcal{C}. □\square

Lemma 3 (the result is a minimal realization). A=T−1A0TA = T^{-1} A_0 T, B=T−1B0B = T^{-1} B_0 and C=C0TC = C_0 T. Hence CAk−1B=hkC A^{k-1} B = h_k for every k≥1k \ge 1, and with D=h0D = h_0 from L9 the result is a minimal realization.

Proof. By Lemmas 1 and 2, A=P+OA0CQ+=P+P T−1A0T QQ+=T−1A0TA = P^{+} \mathcal{O} A_0 \mathcal{C} Q^{+} = P^{+} P \, T^{-1} A_0 T \, Q Q^{+} = T^{-1} A_0 T. The first block column of C\mathcal{C} is B0B_0, so B=Q[:,1:m]=T−1B0B = Q[:, 1{:}m] = T^{-1} B_0. The first block row of O\mathcal{O} is C0C_0, so C=P[1:p,:]=C0TC = P[1{:}p, :] = C_0 T. Then CAk−1B=C0A0k−1B0=hkC A^{k-1} B = C_0 A_0^{k-1} B_0 = h_k. The order is n0n_0, the minimal order. □\square

Lemma 4 (balanced on the data window). Let Or\mathcal{O}_r and Cr\mathcal{C}_r be the NN-step observability and controllability matrices of the result (A,B,C)(A, B, C). Then OrTOr=CrCrT=Σn\mathcal{O}_r^T \mathcal{O}_r = \mathcal{C}_r \mathcal{C}_r^T = \Sigma_n.

Proof. CAi=C0A0iTC A^{i} = C_0 A_0^{i} T, so Or=OT=P\mathcal{O}_r = \mathcal{O} T = P. AjB=T−1A0jB0A^{j} B = T^{-1} A_0^{j} B_0, so Cr=T−1C=Q\mathcal{C}_r = T^{-1} \mathcal{C} = Q. Then PTP=Σn1/2UnTUnΣn1/2=ΣnP^T P = \Sigma_n^{1/2} U_n^T U_n \Sigma_n^{1/2} = \Sigma_n and QQT=Σn1/2VnTVnΣn1/2=ΣnQ Q^T = \Sigma_n^{1/2} V_n^T V_n \Sigma_n^{1/2} = \Sigma_n. □\square

The two products are the NN-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 NN steps. If A0A_0 is Schur, they converge to the infinite gramians as N→∞N \to \infty.

Theorem (exact data). If the data have a realization of order at most NN and nn is the rank of HH, ERA returns a minimal realization of the data whose NN-step gramians are both Σn\Sigma_n.

Proof. Lemmas 1, 3 and 4. ■\blacksquare

Noisy data

Lemma 5 (Weyl's inequality for singular values). For matrices XX and EE of the same size, ∣σk(X+E)−σk(X)∣≤∥E∥2|\sigma_k(X + E) - \sigma_k(X)| \le \lVert E \rVert_2 for every kk, where ∥⋅∥2\lVert \cdot \rVert_2 is the induced 2-norm.

Proof. By the Courant-Fischer theorem, σk(X)=max⁡dim⁡W=kmin⁡w∈W,∥w∥=1∥Xw∥\sigma_k(X) = \max_{\dim W = k} \min_{w \in W, \lVert w \rVert = 1} \lVert X w \rVert. For each unit ww, ∥(X+E)w∥≥∥Xw∥−∥E∥2\lVert (X + E) w \rVert \ge \lVert X w \rVert - \lVert E \rVert_2. Take the subspace WW that attains the maximum for XX; then σk(X+E)≥σk(X)−∥E∥2\sigma_k(X + E) \ge \sigma_k(X) - \lVert E \rVert_2. Exchange the roles of XX and X+EX + E for the other inequality. □\square

Theorem (the gap survives noise). Let the measured parameters be hk+ekh_k + e_k, and let EE be the block Hankel matrix of the eke_k. If ∥E∥2<σn(H)/2\lVert E \rVert_2 < \sigma_n(H) / 2, where nn is the rank of the noise-free HH, then the singular values of the measured Hankel matrix satisfy σn>σn(H)/2>σn+1\sigma_n > \sigma_n(H)/2 > \sigma_{n+1}. So the gap after the nn-th singular value shows the true order.

Proof. By Lemma 5, σn(H+E)≥σn(H)−∥E∥2>σn(H)/2\sigma_n(H + E) \ge \sigma_n(H) - \lVert E \rVert_2 > \sigma_n(H)/2 and σn+1(H+E)≤σn+1(H)+∥E∥2=∥E∥2<σn(H)/2\sigma_{n+1}(H + E) \le \sigma_{n+1}(H) + \lVert E \rVert_2 = \lVert E \rVert_2 < \sigma_n(H)/2. ■\blacksquare

Near data with σn>σn+1\sigma_n > \sigma_{n+1}, the dominant singular subspaces depend continuously on the data (Wedin's theorem). The factors UnU_n and VnV_n are fixed only up to an orthogonal change of basis, which changes AA by a similarity, so the eigenvalues of AA depend continuously on the data. So for small enough noise the eigenvalues of AA 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 a×ba \times b matrix with a≥ba \ge b as O(ab2)O(a b^2) operations, as for the other dense factorizations. Here a=Nmax⁡(m,p)a = N \max(m, p) and b=Nmin⁡(m,p)b = N \min(m, p), so L3 costs O(N3mpmin⁡(m,p))O(N^3 m p \min(m, p)), which is at most O(N3mp(m+p))O(N^3 m p (m + p)). L6 forms UnTHsVnU_n^T H_s V_n in O(N2mpn)O(N^2 m p n). L7 and L8 cost O(Nn(m+p))O(N n (m + p)). The SVD dominates. The extra space is O(N2mp)O(N^2 m p) for HH, HsH_s and the factors.

The SVD is iterative in every real implementation. For the one-sided Jacobi method of the code, one sweep costs O(ab2)O(a b^2). 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 10−1510^{-15}, 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 NN-step gramians are equal and diagonal. For a system with AA Schur they tend to the infinite gramians as NN 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 HH 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 σn/2\sigma_n / 2, 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 rr block rows and cc block columns with rpr p and cmc m both larger than nn. 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 AA from P[1:(N−1)p,:] A=P[p+1:Np,:]P[1{:}(N-1)p, :] \, A = P[p{+}1{:}Np, :] by least squares. This uses only HH and needs no HsH_s. 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 nn) or the modal accuracy indicators.
  • Too few block rows. The method needs Np≥nN p \ge n and Nm≥nN m \ge n, and in practice much more, so that every mode appears in many rows. With NN too small the singular values do not separate.
  • Leaving h0h_0 in the Hankel matrix. HH starts at h1h_1. A direct feedthrough DD that enters HH 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. s=ln⁡(z)/hs = \ln(z) / h is correct only for poles below the Nyquist frequency π/h\pi / h; a faster mode is aliased.
  • Large problems. A full SVD of a large HH 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.

ctlmat.pyI0RawGitHub
# 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

  1. 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
  2. Jer-Nan Juang, Applied System Identification, Prentice Hall, 1994, the chapter on system realization (ERA and its variants)
  3. 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.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.worst
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example