Algorithm Search⌘K

Algorithmadvanced

MOESP

Also called multivariable output-error state space.

Subspace method that gets a state-space model from input-output data by an LQ factorization and an SVD of block Hankel matrices; consistent for white output noise.

Time
O(N i^2 (m + p)^2 + i^3 p^3 + N n^3 m + N p (n m + p m + n)^2) worst
Space
O(N i (m + p)) extra
Where
N = the number of samples; i = the number of block rows; m = the number of inputs; n = the model order; p = the number of outputs
Properties
deterministicexactnot iterativeoffline
Origin
Michel Verhaegen, Patrick Dewilde, 1992

MOESP (multivariable output-error state space) is a subspace identification method. It takes measured inputs and outputs of a linear system xk+1=Axk+Bukx_{k+1} = A x_k + B u_k, yk=Cxk+Duky_k = C x_k + D u_k and returns AA, BB, CC and DD without an iterative search. It stacks the data in block Hankel matrices, removes the part of the outputs that the future inputs explain with one LQ factorization, and finds the extended observability matrix from an SVD of what is left. The shift structure of that matrix gives AA and CC, and one linear least squares fit gives BB, DD and the initial state. MOESP and N4SID are the two best known members of the subspace family. MOESP estimates the observability matrix and then BB and DD; N4SID estimates a state sequence and then all four matrices in one regression. Basic MOESP is consistent when the noise is white and on the output only; for process noise use its variants PI-MOESP and PO-MOESP, or N4SID.

In plain words

Write the input and the output records as tables in which each column is a short window of the data, and the next column is the same window one step later. The outputs in a window depend on two things: the state at the start of the window and the inputs inside the window. Remove everything that the inputs inside the window can explain. What is left comes from the start states, so its columns all lie in a space with as many dimensions as the system has states. The SVD finds this space and shows its size. From the space you read how the state shows up in the output, one step after another, and from that the state matrix. A last fit on the data gives the input matrices.

The problem

Input. Samples u0,…,uN−1∈Rmu_0, \ldots, u_{N-1} \in \mathbb{R}^m and y0,…,yN−1∈Rpy_0, \ldots, y_{N-1} \in \mathbb{R}^p, a number ii of block rows with i>ni > n, and the order nn or a threshold to choose it.

Output. (A,B,C,D)(A, B, C, D) of order nn and an initial state x0x_0 such that the model output fits the data, and the singular values used to choose nn.

Assumptions. The data come from a system of order nn with (A,C)(A, C) observable. The input is rich enough: the matrix (XU)\begin{pmatrix} X \\ U \end{pmatrix} of the state sequence and the input Hankel matrix has full row rank n+imn + im. This holds, for example, for a white noise input that is persistently exciting of order i+ni + n and a controllable (A,B)(A, B). Noise, if any, is white, of equal variance on all outputs, and independent of the input.

Notation. UU is the im×jim \times j block Hankel matrix with block (r,c)(r, c) equal to ur+cu_{r+c}, for r=0,…,i−1r = 0, \ldots, i-1 and c=0,…,j−1c = 0, \ldots, j-1, with j=N−i+1j = N - i + 1. YY is the same for yy. Γi\Gamma_i stacks C,CA,…,CAi−1C, C A, \ldots, C A^{i-1}.

The algorithm

  1. MOESP(u, y, i, n)
  2. 1U, Y ← the block Hankel matrices of u and y, i block rows, j = N - i + 1 columns
  3. 2[L11 0; L21 L22] ← the triangular factor of the LQ factorization [U; Y] = L Q
  4. 3(Ul, σ) ← the left singular vectors and singular values of L22
  5. 4choose n (a gap in σ, or given), with 1 ≤ n < i
  6. 5G ← the first n columns of Ul (G = Γ_i T for some nonsingular T)
  7. 6C ← the first p rows of G
  8. 7A ← (G without its last p rows)⁺ · (G without its first p rows)
  9. 8(x0, B, D) ← the least squares fit of y_k = C A^k x0 + Σ_(t<k) C A^(k-1-t) B u_t + D u_k
  10. 9return (A, B, C, D, x0, σ)

The data equation Y=ΓiX+TiUY = \Gamma_i X + \mathcal{T}_i U holds, where XX is the state sequence and Ti\mathcal{T}_i is the block Toeplitz matrix of the Markov parameters. L2 computes only the triangular factor LL, with Householder reflections, and never stores QQ. Because U=L11Q1U = L_{11} Q_1 and Q1Q2T=0Q_1 Q_2^T = 0, the block L22=YQ2TL_{22} = Y Q_2^T is the part of YY that is orthogonal to the inputs in the window, and it equals ΓiXQ2T\Gamma_i X Q_2^T. So the column space of L22L_{22} is the column space of Γi\Gamma_i. L7 uses the shift structure: Γi\Gamma_i without its last block row, times AA, is Γi\Gamma_i without its first block row. L8 is linear in x0x_0, BB and DD once AA and CC are fixed; the code builds each regressor column by a short simulation.

Example

Take the second order system

A=(0.70.4−0.40.7),B=(10.5),C=(10),D=0.2,A = \begin{pmatrix} 0.7 & 0.4 \\ -0.4 & 0.7 \end{pmatrix}, \quad B = \begin{pmatrix} 1 \\ 0.5 \end{pmatrix}, \quad C = \begin{pmatrix} 1 & 0 \end{pmatrix}, \quad D = 0.2,

with poles 0.7±0.4i0.7 \pm 0.4 i, the initial state x0=(0.5,−1)x_0 = (0.5, -1), and a Gaussian white input with unit variance (seed 7), N=300N = 300 samples and i=4i = 4 block rows. Then j=297j = 297, and [U;Y][U; Y] is 8×2978 \times 297.

Noise-free data. The singular values of the 4×44 \times 4 block L22L_{22} are

34.5398,13.0589,1.0⋅10−14,4.7⋅10−15.34.5398, \quad 13.0589, \quad 1.0 \cdot 10^{-14}, \quad 4.7 \cdot 10^{-15}.

So n=2n = 2. The estimated AA is (0.63360.7223−0.22760.7664)\begin{pmatrix} 0.6336 & 0.7223 \\ -0.2276 & 0.7664 \end{pmatrix}, not the true matrix, but similar to it: its eigenvalues are 0.7±0.4i0.7 \pm 0.4 i to 15 digits. The fit gives D=0.2D = 0.2, and the model output with the fitted x0x_0 matches the data to 3⋅10−153 \cdot 10^{-15}.

White output noise (measurement). With N=2000N = 2000, i=6i = 6, zero initial state, and Gaussian output noise with standard deviation 0.10.1 (seed 1), the singular values are

95.276,41.754,4.420,4.381,4.376,4.229.95.276, \quad 41.754, \quad 4.420, \quad 4.381, \quad 4.376, \quad 4.229.

The four small values are almost equal, about 0.1j=4.470.1 \sqrt{j} = 4.47: this is the σ2I\sigma^2 I term of the proof. The estimated poles are 0.6995±0.4008i0.6995 \pm 0.4008 i and D=0.2010D = 0.2010. With the seeds 2 and 3 the poles are 0.6999±0.4005i0.6999 \pm 0.4005 i and 0.6993±0.4008i0.6993 \pm 0.4008 i.

Correctness

Claim. On noise-free data, with (A,C)(A, C) observable, i>ni > n, the excitation condition rank⁡(XU)=n+im\operatorname{rank} \begin{pmatrix} X \\ U \end{pmatrix} = n + im and a full rank regressor in L8, MOESP returns (T−1AT,T−1B,CT,D)(T^{-1} A T, T^{-1} B, C T, D) for a nonsingular TT. With white output noise of equal variance on all outputs, the estimated column space tends to the column space of Γi\Gamma_i as N→∞N \to \infty.

Key invariant. L22=ΓiXQ2TL_{22} = \Gamma_i X Q_2^T, and XQ2TX Q_2^T has full row rank nn. With noise, 1jL22L22T→ΓiMΓiT+σ2I\frac{1}{j} L_{22} L_{22}^T \to \Gamma_i M \Gamma_i^T + \sigma^2 I with MM positive definite.

So the first nn left singular vectors span the column space of Γi\Gamma_i, and G=ΓiTG = \Gamma_i T. Shift invariance gives A^=T−1AT\hat A = T^{-1} A T and C^=CT\hat C = C T, and the true (T−1x0,T−1B,D)(T^{-1} x_0, T^{-1} B, D) is a zero-residual point of the least squares problem of L8. The full proof is below.

Proof: MOESP recovers the system up to similarity from noise-free data, and the column space of the observability matrix under white output noisefull

We work in exact real arithmetic, as in the real RAM, and assume that the LQ factorization and the SVD are exact. The data come from

xk+1=Axk+Buk,yk=Cxk+Duk+vk,k=0,…,N−1,x_{k+1} = A x_k + B u_k, \qquad y_k = C x_k + D u_k + v_k, \qquad k = 0, \ldots, N-1,

with xk∈Rnx_k \in \mathbb{R}^n, uk∈Rmu_k \in \mathbb{R}^m, yk∈Rpy_k \in \mathbb{R}^p. In the first part vk=0v_k = 0. The integer i>ni > n is the number of block rows and j=N−i+1j = N - i + 1 is the number of columns.

Notation. UU and YY are the im×jim \times j and ip×jip \times j block Hankel matrices with block (r,c)(r, c) equal to ur+cu_{r+c} and yr+cy_{r+c} for r=0,…,i−1r = 0, \ldots, i-1 and c=0,…,j−1c = 0, \ldots, j-1. X=(x0,x1,…,xj−1)X = (x_0, x_1, \ldots, x_{j-1}) is the n×jn \times j state sequence. Γi\Gamma_i is the extended observability matrix that stacks C,CA,…,CAi−1C, CA, \ldots, CA^{i-1}, and Ti\mathcal{T}_i is the ip×imip \times im lower block triangular Toeplitz matrix with DD on the block diagonal and CAr−c−1BC A^{r-c-1} B in block (r,c)(r, c) for r>cr > c. VV is the block Hankel matrix of the vkv_k.

Lemma 1 (data equation). Y=ΓiX+TiU+VY = \Gamma_i X + \mathcal{T}_i U + V.

Proof. Iterating the state equation gives xk+r=Arxk+∑t=0r−1Ar−1−tBuk+tx_{k+r} = A^r x_k + \sum_{t=0}^{r-1} A^{r-1-t} B u_{k+t}, so yk+r=CArxk+∑t=0r−1CAr−1−tBuk+t+Duk+r+vk+ry_{k+r} = C A^r x_k + \sum_{t=0}^{r-1} C A^{r-1-t} B u_{k+t} + D u_{k+r} + v_{k+r}. Block row rr and column kk of the right side is exactly this. □\square

Lemma 2 (the LQ blocks). Let (UY)=(L110L21L22)(Q1Q2)\begin{pmatrix} U \\ Y \end{pmatrix} = \begin{pmatrix} L_{11} & 0 \\ L_{21} & L_{22} \end{pmatrix} \begin{pmatrix} Q_1 \\ Q_2 \end{pmatrix} with LL lower triangular and (Q1Q2)\begin{pmatrix} Q_1 \\ Q_2 \end{pmatrix} with orthonormal rows. If UU has full row rank imim, then L11L_{11} is nonsingular, UQ2T=0U Q_2^T = 0 and L22=YQ2TL_{22} = Y Q_2^T.

Proof. U=L11Q1U = L_{11} Q_1 has rank imim, so the im×imim \times im matrix L11L_{11} is nonsingular. The rows of QQ are orthonormal, so Q1Q2T=0Q_1 Q_2^T = 0 and Q2Q2T=IQ_2 Q_2^T = I. Hence UQ2T=L11Q1Q2T=0U Q_2^T = L_{11} Q_1 Q_2^T = 0 and YQ2T=L21Q1Q2T+L22Q2Q2T=L22Y Q_2^T = L_{21} Q_1 Q_2^T + L_{22} Q_2 Q_2^T = L_{22}. □\square

Noise-free data

Assume vk=0v_k = 0, that (A,C)(A, C) is observable, and the excitation condition

rank⁡(XU)=n+im.(E)\operatorname{rank} \begin{pmatrix} X \\ U \end{pmatrix} = n + im. \tag{E}

(E) implies that UU has full row rank, so Lemma 2 applies.

Lemma 3 (the column space). L22=ΓiXQ2TL_{22} = \Gamma_i X Q_2^T, XQ2TX Q_2^T has full row rank nn, and the column space of L22L_{22} is the column space of Γi\Gamma_i.

Proof. By Lemmas 1 and 2, L22=YQ2T=ΓiXQ2T+TiUQ2T=ΓiXQ2TL_{22} = Y Q_2^T = \Gamma_i X Q_2^T + \mathcal{T}_i U Q_2^T = \Gamma_i X Q_2^T.

Suppose aTXQ2T=0a^T X Q_2^T = 0 for some a∈Rna \in \mathbb{R}^n. Since i>ni > n and (A,C)(A, C) is observable, Γi\Gamma_i has full column rank, so X=Γi+(Y−TiU)X = \Gamma_i^{+} (Y - \mathcal{T}_i U) lies in the row space of (UY)\begin{pmatrix} U \\ Y \end{pmatrix}, which is contained in the row space of (Q1Q2)\begin{pmatrix} Q_1 \\ Q_2 \end{pmatrix}. Write aTX=bTQ1+cTQ2a^T X = b^T Q_1 + c^T Q_2. Multiplying by Q2TQ_2^T gives c=0c = 0, so aTX=bTQ1=bTL11−1Ua^T X = b^T Q_1 = b^T L_{11}^{-1} U. By (E), the rows of XX and UU are linearly independent together, so a=0a = 0. Hence XQ2TX Q_2^T has full row rank nn.

The product of the full column rank matrix Γi\Gamma_i and the full row rank matrix XQ2TX Q_2^T has the column space of Γi\Gamma_i. □\square

Lemma 4 (the observability factor). L3 to L5 give G=UnG = U_n with σn>0=σn+1\sigma_n > 0 = \sigma_{n+1}, and there is a nonsingular TT with G=ΓiTG = \Gamma_i T.

Proof. By Lemma 3, L22L_{22} has rank nn, so exactly nn singular values are nonzero and the first nn left singular vectors span the column space of L22L_{22}, which is the column space of Γi\Gamma_i. So Un=ΓiTU_n = \Gamma_i T for an n×nn \times n matrix TT, and TT is nonsingular because UnU_n has rank nn. □\square

Lemma 5 (A and C). L6 gives C^=CT\hat C = C T and L7 gives A^=T−1AT\hat A = T^{-1} A T.

Proof. The first block row of ΓiT\Gamma_i T is CTC T. Let G‾\underline{G} be GG without its last block row and G‾\overline{G} be GG without its first block row. Then G‾=Γi−1T\underline{G} = \Gamma_{i-1} T and G‾=Γi−1AT\overline{G} = \Gamma_{i-1} A T. Since i−1≥ni - 1 \ge n and (A,C)(A, C) is observable, Γi−1T\Gamma_{i-1} T has full column rank, so its pseudoinverse is a left inverse, and G‾+G‾=(Γi−1T)+(Γi−1T)T−1AT=T−1AT\underline{G}^{+} \overline{G} = (\Gamma_{i-1} T)^{+} (\Gamma_{i-1} T) T^{-1} A T = T^{-1} A T. □\square

Lemma 6 (x_0, B and D). With A^\hat A and C^\hat C fixed, the output is linear in (x0,B,D)(x_0, B, D):

yk=C^A^kx^0+∑t=0k−1C^A^k−1−tB^ut+D^uk.y_k = \hat C \hat A^k \hat x_0 + \sum_{t=0}^{k-1} \hat C \hat A^{k-1-t} \hat B u_t + \hat D u_k.

The values x^0=T−1x0\hat x_0 = T^{-1} x_0, B^=T−1B\hat B = T^{-1} B, D^=D\hat D = D give zero residual. If the regressor matrix of L8 has full column rank, the least squares solution is unique and equals these values.

Proof. With A^=T−1AT\hat A = T^{-1} A T and C^=CT\hat C = C T, the right side with these values is CAkx0+∑tCAk−1−tBut+Duk=ykC A^k x_0 + \sum_t C A^{k-1-t} B u_t + D u_k = y_k. A zero-residual point is a minimizer of the sum of squares, and with full column rank the minimizer is unique. □\square

Theorem (noise-free case). If (A,C)(A, C) is observable, i>ni > n, (E) holds, the regressor of L8 has full column rank, and the order is chosen as the number of nonzero singular values of L22L_{22}, MOESP returns (T−1AT,T−1B,CT,D)(T^{-1} A T, T^{-1} B, C T, D) and T−1x0T^{-1} x_0 for a nonsingular TT. So the model has the transfer function and the output of the true system.

Proof. Lemmas 4, 5 and 6. ■\blacksquare

White output noise

Now let vkv_k be a zero-mean noise, independent of the input, with 1jVVT→σ2I\frac{1}{j} V V^T \to \sigma^2 I and 1jVZT→0\frac{1}{j} V Z^T \to 0 for Z=UZ = U and Z=XZ = X, as j→∞j \to \infty, with probability 1. Here the state does not depend on the noise, because the noise enters only the output. Assume also that 1jUUT\frac{1}{j} U U^T, 1jXUT\frac{1}{j} X U^T and 1jXXT\frac{1}{j} X X^T converge, with the limit of 1j(XU)(XU)T\frac{1}{j} \begin{pmatrix} X \\ U \end{pmatrix} \begin{pmatrix} X \\ U \end{pmatrix}^T positive definite. This is the limit form of (E).

Lemma 7 (the noise only adds a multiple of the identity). 1jL22L22T→ΓiMΓiT+σ2I\frac{1}{j} L_{22} L_{22}^T \to \Gamma_i M \Gamma_i^T + \sigma^2 I, where MM is positive definite.

Proof. L22L22T=YQ2TQ2YTL_{22} L_{22}^T = Y Q_2^T Q_2 Y^T. The rows of YY lie in the row space of QQ, and Q1TQ1Q_1^T Q_1 is the orthogonal projection onto the row space of UU, so Q2TQ2Q_2^T Q_2 acts on the rows of YY as the projection Π=I−UT(UUT)−1U\Pi = I - U^T (U U^T)^{-1} U onto the orthogonal complement of the row space of UU. Hence L22L22T=YΠYTL_{22} L_{22}^T = Y \Pi Y^T, and with ΠUT=0\Pi U^T = 0 and Lemma 1, YΠYT=(ΓiX+V)Π(ΓiX+V)TY \Pi Y^T = (\Gamma_i X + V) \Pi (\Gamma_i X + V)^T. Divide by jj and pass to the limit. 1jXΠXT\frac{1}{j} X \Pi X^T tends to the Schur complement M=Rxx−RxuRuu−1RuxM = R_{xx} - R_{xu} R_{uu}^{-1} R_{ux} of the limit covariance, which is positive definite because the whole limit matrix is. The cross terms 1jXΠVT\frac{1}{j} X \Pi V^T tend to 0, and 1jVΠVT\frac{1}{j} V \Pi V^T tends to σ2I\sigma^2 I, because the correction 1jVUT(1jUUT)−11jUVT\frac{1}{j} V U^T (\frac{1}{j} U U^T)^{-1} \frac{1}{j} U V^T tends to 0. □\square

Theorem (consistency of the column space). Under these assumptions, the span of the first nn left singular vectors of L22L_{22} tends to the column space of Γi\Gamma_i, and the estimates of the poles tend to the true poles.

Proof. The left singular vectors of L22L_{22} are the eigenvectors of 1jL22L22T\frac{1}{j} L_{22} L_{22}^T. For the limit matrix ΓiMΓiT+σ2I\Gamma_i M \Gamma_i^T + \sigma^2 I, every vector in the column space of Γi\Gamma_i is mapped into that space, and every vector orthogonal to it is an eigenvector with eigenvalue σ2\sigma^2. On the column space of Γi\Gamma_i the eigenvalues are σ2\sigma^2 plus the positive eigenvalues of ΓiMΓiT\Gamma_i M \Gamma_i^T there. So the nn dominant eigenvectors span the column space of Γi\Gamma_i, with a gap above σ2\sigma^2. Invariant subspaces of a symmetric matrix with such a gap depend continuously on the matrix (the Davis-Kahan theorem), so the estimate converges. Lemma 5 is continuous in GG at a point where G‾\underline{G} has full column rank, and the eigenvalues of A^\hat A do not depend on the choice of TT. ■\blacksquare

The identity in Lemma 7 needs 1jVVT→σ2I\frac{1}{j} V V^T \to \sigma^2 I: the noise must be white in time and have the same variance in every output. Colored output noise or process noise adds a matrix that is not a multiple of the identity, and then the column space is biased. The PI-MOESP and PO-MOESP variants use past inputs or past outputs as instruments to remove this bias.

Complexity

In the real RAM, counting dense factorizations in the usual way. L2 factors a d×jd \times j matrix with d=i(m+p)d = i(m + p) by Householder reflections in O(d2j)=O(Ni2(m+p)2)O(d^2 j) = O(N i^2 (m + p)^2). L3 is an SVD of the ip×ipip \times ip block L22L_{22} in O(i3p3)O(i^3 p^3). L7 is a pseudoinverse of an (i−1)p×n(i-1)p \times n matrix, O(ipn2)O(i p n^2). L8 builds n+nmn + nm regressor columns by simulations of NN steps, in O(Nn3m)O(N n^3 m) for the code's simple loops, and solves a least squares problem with NpNp rows and q=n+nm+pmq = n + nm + pm unknowns in O(Npq2)O(N p q^2). The extra space is O(Ni(m+p))O(N i (m + p)) for the Hankel matrices; the LQ factor is only d×dd \times d.

For long records, L2 dominates. The SVD and the pseudoinverse are iterative inside, so the counts above are the usual dense counts, as for the other factorizations in this area.

Properties

  • Exact for noise-free data (theorem). Under the assumptions above the model has the true transfer function, in other state coordinates.
  • Consistent for white output noise (theorem). The column space of Γi\Gamma_i, and so AA and CC, are consistent when the noise is white, has equal variance on all outputs, and is independent of the input (Verhaegen and Dewilde 1992, Part 2).
  • Biased for process noise. With noise in the state equation, or colored output noise, basic MOESP is biased. PI-MOESP and PO-MOESP remove the bias with instruments.
  • No local minima. There is no nonconvex search, so no starting value is needed.
  • Not optimal. The estimate is not the maximum likelihood estimate, and its variance is larger than that of a prediction error method.
  • The order is a choice. The singular values give a visual aid, not a test. A gap that is clear on noise-free data can be hard to see on real data.

Variants and improvements

  • PI-MOESP. Uses the past inputs as instruments. It is consistent for output noise that is colored but independent of the input (Verhaegen 1993, Part 3).
  • PO-MOESP. Uses the past inputs and the past outputs as instruments. It is consistent for innovation form models with process noise (Verhaegen, Automatica, 1994).
  • N4SID. Uses an oblique projection to get a state sequence and then fits all matrices in one least squares problem. Van Overschee and De Moor (1995) showed that MOESP, N4SID and CVA are the same algorithm with different weightings of the SVD.
  • ERA. The same shift idea applied to a Hankel matrix of Markov parameters, not of raw data.
  • Closed loop. Basic MOESP is biased in closed loop, because the input depends on past noise. Predictor-based subspace methods address this.
  • Recursive MOESP. Updates the LQ factor and the subspace as data arrive, for tracking slowly changing systems.

When to use it

Use MOESP to get a multivariable state-space model from open-loop data in one step, when there is no good starting value for a prediction error method, or as the starting value for one. It handles many inputs and outputs at the same cost as one, and it gives the order from the singular values. With strong process noise, prefer PO-MOESP or N4SID. With feedback in the data, use a closed-loop method.

Pitfalls

  • Too few block rows. The method needs i>ni > n, and in practice ii two or three times the expected order. With ii too small, L7 has no unique solution.
  • Too few samples. The LQ factorization needs j≥i(m+p)j \ge i(m + p), and the estimate is poor long before that limit. The code rejects j<i(m+p)j < i(m + p).
  • An input that is not rich enough. A step or a sum of a few sines does not satisfy the excitation condition for large ii. Then L22L_{22} contains input effects and the rank is wrong.
  • Unequal noise on the outputs. The proof needs the same noise variance on every output. Scale the outputs to equal noise levels before L1.
  • Offsets. A constant offset in the data acts as an extra input. Remove the means first.
  • Comparing matrices. The estimate is in other coordinates. Compare eigenvalues, Markov parameters or frequency responses, never the entries of AA.

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()
moesp.py 175 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moesp/. The authors are listed in prov/7ZZDNB.jsonl.

"""Ordinary MOESP (Verhaegen and Dewilde, 1992).

Input: an input sequence u_0, ..., u_(N-1) (vectors of length m) and an
output sequence y_0, ..., y_(N-1) (vectors of length p) of a discrete-time
system x_(k+1) = A x_k + B u_k, y_k = C x_k + D u_k (+ white output noise),
the number i of block rows (i > n), and the order n (or None to pick it from
the singular values with the relative threshold tol).

Steps: block Hankel matrices U and Y with i block rows and j = N - i + 1
columns; the LQ factorization [U; Y] = L Q; the SVD of the block L22; the
extended observability matrix Gamma = U_n (left singular vectors); C from the
first block row of Gamma; A from its shift structure; then x_0, B and D by
linear least squares on the data.

The LQ factorization uses Householder reflections. The SVD is a one-sided
Jacobi (Hestenes) method. Both are in floating point.
"""

import math

from ctlmat import mul, transpose

__all__ = ["block_hankel", "householder_lq", "jacobi_svd", "pinv", "moesp", "estimate_x0_b_d", "simulate"]


def block_hankel(w, i, j):
    """Return the i q by j matrix whose block (r, c) is the vector w[r + c] as a column."""
    q = len(w[0])
    return [[float(w[r + c][a]) for c in range(j)] for r in range(i) for a in range(q)]


def householder_lq(a):
    """Return the d by d lower triangular L with a = L Q, Q with orthonormal rows.

    a is d by N with d <= N. Each step applies a Householder reflection from
    the right that sets the entries to the right of the diagonal in one row
    to zero. Cost: O(d^2 N).
    """
    d, ncol = len(a), len(a[0])
    if d > ncol:
        raise ValueError("householder_lq: need at least as many columns as rows")
    w = [[float(v) for v in row] for row in a]
    for k in range(d):
        v = w[k][k:]
        normx = math.sqrt(sum(t * t for t in v))
        if normx == 0.0:
            continue
        alpha = -math.copysign(normx, v[0])
        v[0] -= alpha
        vv = sum(t * t for t in v)
        for r in range(k, d):
            row = w[r]
            f = 2.0 * sum(row[k + t] * v[t] for t in range(len(v))) / vv
            if f != 0.0:
                for t in range(len(v)):
                    row[k + t] -= f * v[t]
    return [[w[r][c] if c <= r else 0.0 for c in range(d)] for r in range(d)]


def jacobi_svd(a, tol=1e-15, max_sweeps=80):
    """Return (U, s, V) with a = U diag(s) V^T and s sorted in decreasing order.

    a is r by c. U is r by k and V is c by k, with k = min(r, c), as lists of
    rows. A column of U that belongs to a zero singular value is zero. A
    column whose squared norm is below 1e-30 times the squared Frobenius norm
    of a counts as zero and is not rotated.
    """
    r, c = len(a), len(a[0])
    if r < c:
        v, s, u = jacobi_svd(transpose(a), tol, max_sweeps)
        return u, s, v
    cols = [[float(a[i][j]) for i in range(r)] for j in range(c)]
    vcols = [[1.0 if i == j else 0.0 for i in range(c)] for j in range(c)]
    tiny = 1e-30 * sum(t * t for col in cols for t in col)
    for _ in range(max_sweeps):
        rotated = False
        for p in range(c - 1):
            for q in range(p + 1, c):
                x, y = cols[p], cols[q]
                alpha = sum(t * t for t in x)
                beta = sum(t * t for t in y)
                gamma = sum(s * t for s, t in zip(x, y))
                if min(alpha, beta) <= tiny or abs(gamma) <= tol * math.sqrt(alpha * beta):
                    continue
                rotated = True
                zeta = (beta - alpha) / (2.0 * gamma)
                t = math.copysign(1.0, zeta) / (abs(zeta) + math.sqrt(1.0 + zeta * zeta))
                cs = 1.0 / math.sqrt(1.0 + t * t)
                sn = cs * t
                cols[p] = [cs * xi - sn * yi for xi, yi in zip(x, y)]
                cols[q] = [sn * xi + cs * yi for xi, yi in zip(x, y)]
                vx, vy = vcols[p], vcols[q]
                vcols[p] = [cs * xi - sn * yi for xi, yi in zip(vx, vy)]
                vcols[q] = [sn * xi + cs * yi for xi, yi in zip(vx, vy)]
        if not rotated:
            break
    sv = [math.sqrt(sum(t * t for t in col)) for col in cols]
    order = sorted(range(c), key=lambda j: -sv[j])
    s = [sv[j] for j in order]
    ucols = [[t / sv[j] for t in cols[j]] if sv[j] > 0.0 else [0.0] * r for j in order]
    return transpose(ucols), s, transpose([vcols[j] for j in order])


def pinv(a, rtol=1e-12):
    """Return the Moore-Penrose pseudoinverse; singular values below rtol s_max count as zero."""
    U, s, V = jacobi_svd(a)
    keep = [k for k in range(len(s)) if s[k] > rtol * s[0]] if s and s[0] > 0.0 else []
    return [[sum(V[r][k] * U[c][k] / s[k] for k in keep) for c in range(len(U))] for r in range(len(V))]


def simulate(A, B, C, D, u, x0):
    """Return y_0, ..., y_(N-1) of x_(k+1) = A x_k + B u_k, y_k = C x_k + D u_k."""
    x = list(x0)
    out = []
    for uk in u:
        out.append([sum(C[a][t] * x[t] for t in range(len(x))) + sum(D[a][c] * uk[c] for c in range(len(uk)))
                    for a in range(len(C))])
        x = [sum(A[r][t] * x[t] for t in range(len(x))) + sum(B[r][c] * uk[c] for c in range(len(uk)))
             for r in range(len(x))]
    return out


def estimate_x0_b_d(A, C, u, y):
    """Fit x_0, B and D by linear least squares, with A and C fixed.

    y_k = C A^k x_0 + sum_(t<k) C A^(k-1-t) B u_t + D u_k is linear in the
    entries of x_0, B and D. Each regressor column is the output of a small
    simulation, so the cost is O(N n^3 m + N p m) to build the columns and
    O(N p q^2) per SVD sweep for the q = n + n m + p m unknowns.
    """
    n, p, m, N = len(A), len(C), len(u[0]), len(u)
    columns = []
    for r in range(n):  # x_0 entries: free response C A^k e_r
        e = [1.0 if t == r else 0.0 for t in range(n)]
        columns.append([v for yk in simulate(A, [[0.0] * m for _ in range(n)], C, [[0.0] * m for _ in range(p)], u, e)
                        for v in yk])
    for r in range(n):  # B entries
        for c in range(m):
            E = [[1.0 if (t == r and s == c) else 0.0 for s in range(m)] for t in range(n)]
            columns.append([v for yk in simulate(A, E, C, [[0.0] * m for _ in range(p)], u, [0.0] * n) for v in yk])
    for a in range(p):  # D entries
        for c in range(m):
            columns.append([float(u[k][c]) if b == a else 0.0 for k in range(N) for b in range(p)])
    phi = transpose(columns)
    theta = mul(pinv(phi), [[float(v)] for yk in y for v in yk])
    theta = [row[0] for row in theta]
    x0 = theta[:n]
    B = [[theta[n + r * m + c] for c in range(m)] for r in range(n)]
    D = [[theta[n + n * m + a * m + c] for c in range(m)] for a in range(p)]
    return x0, B, D


def moesp(u, y, i, n=None, tol=1e-8):
    """Return (A, B, C, D, x0, s): an order n model and the singular values of L22."""
    m, p, N = len(u[0]), len(y[0]), len(u)
    j = N - i + 1
    if j < i * (m + p):
        raise ValueError("moesp: too few samples for i block rows")
    U = block_hankel(u, i, j)  # @line L1
    Y = block_hankel(y, i, j)
    L = householder_lq(U + Y)  # @line L2
    L22 = [row[i * m:] for row in L[i * m:]]
    Ul, s, _ = jacobi_svd(L22)  # @line L3
    if n is None:  # @line L4
        n = sum(1 for v in s if v > tol * s[0])
    if n < 1 or n >= i or s[n - 1] <= 0.0:
        raise ValueError("moesp: need 1 <= n < i and n at most the rank of L22")
    G = [row[:n] for row in Ul]  # @line L5
    C = [list(row) for row in G[:p]]  # @line L6
    A = mul(pinv(G[:-p]), G[p:])  # @line L7
    x0, B, D = estimate_x0_b_d(A, C, u, y)  # @line L8
    return A, B, C, D, x0, s  # @line L9
test_moesp.py 118 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/moesp/. The authors are listed in prov/7ZZDNB.jsonl.

import random

from ctlmat import charpoly, mul, polyroots, transpose
from moesp import block_hankel, householder_lq, jacobi_svd, moesp, pinv, simulate


def _close(a, b, tol):
    return all(abs(x - y) <= tol for ra, rb in zip(a, b) for x, y in zip(ra, rb))


def _eig_error(A, A0):
    eig = polyroots(charpoly(A))
    true = polyroots(charpoly(A0))
    return max(min(abs(e - t) for t in true) for e in eig)


def _markov(A, B, C, K):
    out = []
    P = [list(row) for row in B]
    for _ in range(K):
        out.append(mul(C, P))
        P = mul(A, P)
    return out


def test_lq_factor():
    rng = random.Random(1)
    for _ in range(10):
        d, ncol = rng.randint(1, 6), rng.randint(6, 12)
        a = [[rng.uniform(-1, 1) for _ in range(ncol)] for _ in range(d)]
        L = householder_lq(a)
        assert all(L[r][c] == 0.0 for r in range(d) for c in range(r + 1, d))
        # a = L Q with Q Q^T = I implies a a^T = L L^T
        assert _close(mul(L, transpose(L)), mul(a, transpose(a)), 1e-12)


def test_block_hankel_layout():
    w = [[k, 10 * k] for k in range(5)]
    assert block_hankel(w, 2, 3) == [[0, 1, 2], [0, 10, 20], [1, 2, 3], [10, 20, 30]]


def test_pinv_of_rank_deficient_matrix():
    a = [[1.0, 2.0], [2.0, 4.0], [0.0, 0.0]]
    p = pinv(a)
    assert _close(mul(mul(a, p), a), a, 1e-12)
    assert _close(mul(mul(p, a), p), p, 1e-12)


def test_exact_siso_with_initial_state():
    A0 = [[0.7, 0.4], [-0.4, 0.7]]
    B0 = [[1.0], [0.5]]
    C0 = [[1.0, 0.0]]
    D0 = [[0.2]]
    rng = random.Random(7)
    u = [[rng.gauss(0.0, 1.0)] for _ in range(300)]
    y = simulate(A0, B0, C0, D0, u, [0.5, -1.0])
    A, B, C, D, x0, s = moesp(u, y, 4)
    assert len(A) == 2
    assert s[2] < 1e-12 * s[0]
    assert _eig_error(A, A0) < 1e-10
    assert abs(D[0][0] - 0.2) < 1e-10
    yh = simulate(A, B, C, D, u, x0)
    assert max(abs(a[0] - b[0]) for a, b in zip(y, yh)) < 1e-9
    for g, g0 in zip(_markov(A, B, C, 12), _markov(A0, B0, C0, 12)):
        assert _close(g, g0, 1e-10)


def test_exact_mimo():
    A0 = [[0.5, 0.3, 0.0], [-0.3, 0.5, 0.2], [0.0, 0.0, -0.6]]
    B0 = [[1.0, 0.0], [0.0, 1.0], [1.0, -1.0]]
    C0 = [[1.0, 0.0, 1.0], [0.0, 1.0, 0.0]]
    D0 = [[0.0, 0.1], [0.0, 0.0]]
    rng = random.Random(11)
    u = [[rng.gauss(0.0, 1.0), rng.gauss(0.0, 1.0)] for _ in range(250)]
    y = simulate(A0, B0, C0, D0, u, [0.0, 0.0, 0.0])
    A, B, C, D, x0, s = moesp(u, y, 5)
    assert len(A) == 3
    assert _eig_error(A, A0) < 1e-9
    assert _close(D, D0, 1e-9)
    for g, g0 in zip(_markov(A, B, C, 12), _markov(A0, B0, C0, 12)):
        assert _close(g, g0, 1e-9)


def test_white_output_noise():
    # measurement: white output noise with standard deviation 0.1, N = 2000
    A0 = [[0.7, 0.4], [-0.4, 0.7]]
    B0 = [[1.0], [0.5]]
    C0 = [[1.0, 0.0]]
    D0 = [[0.2]]
    for seed in (1, 2, 3):
        rng = random.Random(seed)
        u = [[rng.gauss(0.0, 1.0)] for _ in range(2000)]
        y = simulate(A0, B0, C0, D0, u, [0.0, 0.0])
        yn = [[v[0] + rng.gauss(0.0, 0.1)] for v in y]
        A, B, C, D, x0, s = moesp(u, yn, 6, n=2)
        assert s[1] > 5 * s[2]
        assert _eig_error(A, A0) < 0.01
        assert abs(D[0][0] - 0.2) < 0.02


def test_svd_reconstruction():
    rng = random.Random(5)
    a = [[rng.uniform(-1, 1) for _ in range(4)] for _ in range(6)]
    U, s, V = jacobi_svd(a)
    S = [[s[i] if i == j else 0.0 for j in range(4)] for i in range(4)]
    assert _close(mul(mul(U, S), transpose(V)), a, 1e-12)


def test_too_few_samples_rejected():
    u = [[1.0]] * 10
    try:
        moesp(u, u, 6)
    except ValueError:
        return
    assert False, "moesp must reject too few samples"

History

Subspace identification grew out of realization theory: Ho and Kalman (1966), then the SVD methods of Kung (1978) and of Juang and Pappa (1985) worked on Markov parameters. In 1992, Verhaegen and Dewilde published the MOESP class in two parts in the International Journal of Control. They worked directly on input-output data with an LQ factorization and an SVD. Verhaegen analysed ordinary MOESP and introduced PI-MOESP in Part 3 (1993), and PO-MOESP for models in innovation form in 1994. At the same time Van Overschee and De Moor developed N4SID, and in 1995 they showed that both are special cases of one weighted algorithm.

References

  1. Michel Verhaegen and Patrick Dewilde, Subspace model identification Part 1. The output-error state-space model identification class of algorithms, International Journal of Control 56(5), 1187-1210, 1992, the data equation, the LQ factorization of the block Hankel matrices, and the estimate of A and C from the observability matrix
  2. Michel Verhaegen and Patrick Dewilde, Subspace model identification Part 2. Analysis of the elementary output-error state-space model identification algorithm, International Journal of Control 56(5), 1211-1241, 1992, the analysis of the algorithm with noise on the output
  3. Michel Verhaegen, Subspace model identification Part 3. Analysis of the ordinary output-error state-space model identification algorithm, International Journal of Control 58(3), 555-586, 1993, the analysis of ordinary MOESP and the instrumental variable version with past inputs
  4. Michel Verhaegen and Vincent Verdult, Filtering and System Identification: A Least Squares Approach, Cambridge University Press, 2007, the chapter on subspace model identification (MOESP, PI-MOESP and PO-MOESP)

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

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