Algorithm Search⌘K

Algorithmadvanced

N4SID

Also called numerical algorithms for subspace state space system identification.

Subspace method that estimates a state sequence from input-output data by oblique projections and an SVD, then fits A, B, C, D and the noise covariances by least squares.

Time
O(N i^2 (m + p)^2 + i^3 (m + p)^3) worst
Space
O(N i (m + p)) extra
Where
N = the number of samples; i = the number of block rows in the past and in the future; m = the number of inputs; n = the model order; p = the number of outputs
Properties
deterministicexactnot iterativeoffline
Origin
Peter Van Overschee, Bart De Moor, 1994

N4SID (numerical algorithms for subspace state space system identification) is a subspace identification method. From measured inputs and outputs it estimates a model in innovation form, xk+1=Axk+Buk+Kekx_{k+1} = A x_k + B u_k + K e_k, yk=Cxk+Duk+eky_k = C x_k + D u_k + e_k, without iterative search. Its main step is an oblique projection of the future outputs onto the past data, along the future inputs. The result is the extended observability matrix times a sequence of states, and an SVD splits the two factors. With two such state sequences, one step apart, all of AA, BB, CC and DD follow from one linear least squares problem, and its residuals give the noise covariances. MOESP is the other well known member of the family: it gets AA and CC from the observability matrix and fits BB and DD afterwards, while N4SID fits all four matrices together from estimated states.

In plain words

Cut the data into a past window and a future window. The future outputs depend on the state at the start of the future window and on the future inputs. That state depends only on the past. So remove from the future outputs the part that the future inputs explain, and keep only the part that the past explains. What is left is the state at the start of the future, seen through the output. Its size shows how many states the system has, and the SVD splits it into "how the state shows in the output" and "the states". Do the same one step later. Now you have the states at two times and the inputs and outputs between them, so one ordinary least squares fit gives the four system matrices. What the fit cannot explain is the noise.

The problem

Input. Samples 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 i>ni > n of block rows for the past and for the future, and the order nn or a threshold to choose it.

Output. (A,B,C,D)(A, B, C, D) of order nn, the covariance of the residuals (QSSTR)\begin{pmatrix} Q & S \\ S^T & R \end{pmatrix}, and the singular values used to choose nn.

Notation. UU is the 2im×j2im \times j block Hankel matrix of the inputs with 2i2i block rows and j=N−2i+1j = N - 2i + 1 columns, block (r,c)(r, c) equal to ur+cu_{r+c}. The first ii block rows are the past UpU_p, the last ii are the future UfU_f. Up+U_p^+ and Uf−U_f^- move the border one block row down. YY is the same for the outputs, and Wp=(UpYp)W_p = \begin{pmatrix} U_p \\ Y_p \end{pmatrix}. The oblique projection of the rows of aa along the row space of bb onto the row space of cc is a/bc=(a/b⊥)(c/b⊥)+ca /_b c = (a / b^\perp)(c / b^\perp)^{+} c, where a/b⊥a / b^\perp subtracts from each row of aa its orthogonal projection on the row space of bb, and +^{+} is the pseudoinverse.

The algorithm

  1. N4SID(u, y, i, n)
  2. 1U, Y ← the block Hankel matrices with 2i block rows and j = N - 2i + 1 columns
  3. 2L ← the lower triangular factor of the LQ factorization [U; Y] = L Q
  4. 3O_i ← Y_f /_(U_f) W_p
  5. 4O_(i-1) ← Y_f^- /_(U_f^-) W_p^+
  6. 5(Us, σ) ← the SVD of O_i; choose n (a gap in σ, or given), with 1 ≤ n < i
  7. 6G ← Us[:, 1:n] diag(σ_1, ..., σ_n)^(1/2); G1 ← G without its last p rows
  8. 7X_i ← G⁺ O_i; X_(i+1) ← G1⁺ O_(i-1)
  9. 8θ ← the least squares solution of [X_(i+1); Y_(i|i)] = θ [X_i; U_(i|i)]
  10. 9(A, B; C, D) ← the blocks of θ; cov ← the residuals times their transpose, over j
  11. 10return (A, B, C, D, cov, σ)

Yi∣iY_{i|i} and Ui∣iU_{i|i} are the block row ii of YY and UU, the first block row of the future. Every data row is the matching row of LL times QQ, and QQ has orthonormal rows. So every inner product of data rows is the same inner product of rows of LL, and L3 to L9 run on rows of length 2i(m+p)2i(m + p) instead of jj. The code never forms QQ. L3 is the heart of the method: the future outputs are Yf=ΓiXf+TiUfY_f = \Gamma_i X_f + \mathcal{T}_i U_f, the state XfX_f is a linear function of the past WpW_p, and the oblique projection keeps exactly the part along WpW_p, which is ΓiXf\Gamma_i X_f. L4 does the same with the border one block row later, so it gives Γi−1Xf+\Gamma_{i-1} X_{f}^+, the next states. L6 chooses the balanced split UnΣn1/2U_n \Sigma_n^{1/2} of the SVD; any other split gives the same model in other coordinates.

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 and initial state (0.5,−1)(0.5, -1), driven by a Gaussian white input with unit variance (seed 7), with N=300N = 300 and i=4i = 4. Then j=293j = 293, [U;Y][U; Y] is 16×29316 \times 293, and OiO_i is 4×164 \times 16 when computed on the rows of LL.

Noise-free data. The singular values of OiO_i are 34.946334.9463, 13.126313.1263, and then values below 3⋅10−153 \cdot 10^{-15}. So n=2n = 2. The estimated AA has the eigenvalues 0.7±0.4i0.7 \pm 0.4 i, D=0.2D = 0.2, and the residual covariance is below 10−2010^{-20}, as the proof predicts.

Innovation noise (measurement). Add process and output noise in innovation form with K=(0.5,0.2)TK = (0.5, 0.2)^T and eke_k Gaussian with standard deviation 0.10.1, and use N=2000N = 2000 and i=5i = 5 (seed 1). The singular values are 93.713593.7135, 40.048740.0487, 0.32620.3262, and smaller. The gap is a factor of 120. The estimated poles are 0.69994±0.40146i0.69994 \pm 0.40146 i, and the output block of the residual covariance is R=0.009697R = 0.009697, against the true noise variance 0.010.01.

Correctness

Claim. On noise-free data, with (A,B)(A, B) controllable, (A,C)(A, C) observable, i>ni > n, and the excitation condition rank⁡(XpUpUf)=n+2im\operatorname{rank} \begin{pmatrix} X_p \\ U_p \\ U_f \end{pmatrix} = n + 2im, N4SID returns (T−1AT,T−1B,CT,D)(T^{-1} A T, T^{-1} B, C T, D) for a nonsingular TT, and a zero residual covariance.

Key invariant. Oi=ΓiXfO_i = \Gamma_i X_f and Oi−1=Γi−1Xf+O_{i-1} = \Gamma_{i-1} X_f^+. This follows from one identity of the oblique projection: if a=Mc+Pba = M c + P b and the row spaces of bb and cc meet only in 0, then a/bc=Mca /_b c = M c.

The SVD then gives G=ΓiTG = \Gamma_i T, so L7 returns T−1XfT^{-1} X_f and T−1Xf+T^{-1} X_f^+. The state equations hold exactly between these two sequences, and the regressor has full row rank, so L8 returns the stated θ\theta. The full proof is below, including the reason why the computation on the rows of LL is the same as on the data.

Proof: N4SID recovers the system up to similarity from noise-free datafull

We work in exact real arithmetic, as in the real RAM, and assume that the LQ factorization, the SVD and the pseudoinverses are exact. The data come from a noise-free system

xk+1=Axk+Buk,yk=Cxk+Duk,k=0,…,N−1,x_{k+1} = A x_k + B u_k, \qquad y_k = C x_k + D u_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, and (A,B)(A, B) controllable and (A,C)(A, C) observable. The number of block rows is 2i2i with i>ni > n, and j=N−2i+1j = N - 2i + 1.

Notation. UU is the 2im×j2im \times j block Hankel matrix with block (r,c)(r, c) equal to ur+cu_{r+c}. UpU_p is its first ii block rows (the past) and UfU_f its last ii block rows (the future). Up+U_p^+ is the first i+1i+1 block rows and Uf−U_f^- the last i−1i-1 block rows. YY, YpY_p, YfY_f, Yp+Y_p^+, Yf−Y_f^- are the same for yy, and Wp=(UpYp)W_p = \begin{pmatrix} U_p \\ Y_p \end{pmatrix}, Wp+=(Up+Yp+)W_p^+ = \begin{pmatrix} U_p^+ \\ Y_p^+ \end{pmatrix}. Xp=(x0,…,xj−1)X_p = (x_0, \ldots, x_{j-1}), Xf=(xi,…,xi+j−1)X_f = (x_i, \ldots, x_{i+j-1}) and Xf+=(xi+1,…,xi+j)X_f^+ = (x_{i+1}, \ldots, x_{i+j}). Γk\Gamma_k stacks C,CA,…,CAk−1C, CA, \ldots, CA^{k-1}, Δk=(Ak−1B,…,AB,B)\Delta_k = (A^{k-1} B, \ldots, A B, B), and Tk\mathcal{T}_k is the lower block triangular Toeplitz matrix of DD and the Markov parameters.

For matrices aa, bb, cc with jj columns, a/b⊥=a−abT(bbT)+ba / b^\perp = a - a b^T (b b^T)^{+} b removes from each row of aa its orthogonal projection on the row space of bb, and the oblique projection is

a/bc=(a/b⊥)(c/b⊥)+c.a /_b c = (a / b^\perp)(c / b^\perp)^{+} c.

Excitation condition.

rank⁡(XpUpUf)=n+2im.(E)\operatorname{rank} \begin{pmatrix} X_p \\ U_p \\ U_f \end{pmatrix} = n + 2im. \tag{E}

Lemma 1 (data equations). Yp=ΓiXp+TiUpY_p = \Gamma_i X_p + \mathcal{T}_i U_p, Yf=ΓiXf+TiUfY_f = \Gamma_i X_f + \mathcal{T}_i U_f and Xf=AiXp+ΔiUpX_f = A^i X_p + \Delta_i U_p. The same holds with i+1i+1 past and i−1i-1 future block rows: Yf−=Γi−1Xf++Ti−1Uf−Y_f^- = \Gamma_{i-1} X_f^+ + \mathcal{T}_{i-1} U_f^- and Xf+=Ai+1Xp+Δi+1Up+X_f^+ = A^{i+1} X_p + \Delta_{i+1} U_p^+.

Proof. Iterate the state equation: 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}, and apply CC and add Duk+rD u_{k+r} for the outputs. Read column by column. □\square

Lemma 2 (the states lie in the past). The row space of WpW_p is the row space of (XpUp)\begin{pmatrix} X_p \\ U_p \end{pmatrix}, and the rows of XfX_f lie in it. The row space of Wp+W_p^+ is the row space of (XpUp+)\begin{pmatrix} X_p \\ U_p^+ \end{pmatrix}, and the rows of Xf+X_f^+ lie in it.

Proof. Γi\Gamma_i has full column rank because i≥ni \ge n and (A,C)(A, C) is observable. By Lemma 1, Xp=Γi+(Yp−TiUp)X_p = \Gamma_i^{+} (Y_p - \mathcal{T}_i U_p), so the rows of XpX_p lie in the row space of WpW_p, and conversely the rows of YpY_p are combinations of the rows of XpX_p and UpU_p. Then Xf=AiXp+ΔiUpX_f = A^i X_p + \Delta_i U_p lies in it too. The same argument with i+1i + 1 block rows gives the second statement. □\square

Lemma 3 (the oblique projection). Let a=Mc+Pba = M c + P b, and assume that the row spaces of bb and cc meet only in 0. Then a/bc=Mca /_b c = M c.

Proof. Since b/b⊥=0b / b^\perp = 0 and the operation is linear, a/b⊥=M(c/b⊥)a / b^\perp = M (c / b^\perp). Let c′=c/b⊥c' = c / b^\perp and let Π=c′c′+\Pi = c' c'^{+}, the orthogonal projection onto the column space of c′c'. Then a/bc=MΠca /_b c = M \Pi c, and it is enough to show (I−Π)c=0(I - \Pi) c = 0. Let ww be in the range of I−ΠI - \Pi, so wTc′=0w^T c' = 0. Then wTc=wTc bT(bbT)+bw^T c = w^T c\, b^T (b b^T)^{+} b lies in the row space of bb; it also lies in the row space of cc, so wTc=0w^T c = 0. Hence cT(I−Π)=0c^T (I - \Pi) = 0, and since I−ΠI - \Pi is symmetric, (I−Π)c=0(I - \Pi) c = 0. □\square

Lemma 4 (O_i and O_(i-1)). Under (E), the oblique projection of L3 is Oi=ΓiXfO_i = \Gamma_i X_f, and the one of L4 is Oi−1=Γi−1Xf+O_{i-1} = \Gamma_{i-1} X_f^+.

Proof. By Lemma 2, Xf=KWpX_f = K W_p for some matrix KK, so by Lemma 1, Yf=ΓiKWp+TiUfY_f = \Gamma_i K W_p + \mathcal{T}_i U_f. By Lemma 2 and (E), the row space of WpW_p, which is that of (XpUp)\begin{pmatrix} X_p \\ U_p \end{pmatrix}, meets the row space of UfU_f only in 0. Lemma 3 with a=Yfa = Y_f, b=Ufb = U_f and c=Wpc = W_p gives Oi=ΓiKWp=ΓiXfO_i = \Gamma_i K W_p = \Gamma_i X_f. For Oi−1O_{i-1} use Yf−Y_f^-, Uf−U_f^- and Wp+W_p^+: the rows of (XpUp+)\begin{pmatrix} X_p \\ U_p^+ \end{pmatrix} and of Uf−U_f^- are rows of the matrix in (E), so the intersection is again 0. □\square

Lemma 5 (rank). XfX_f has full row rank nn, and the matrix (XfUi∣i)\begin{pmatrix} X_f \\ U_{i|i} \end{pmatrix} has full row rank n+mn + m, where Ui∣iU_{i|i} is the block row ii of UU (the first block row of UfU_f).

Proof. Suppose aTXf+bTUi∣i=0a^T X_f + b^T U_{i|i} = 0. By Lemma 1, aTAiXp+aTΔiUp+bTUi∣i=0a^T A^i X_p + a^T \Delta_i U_p + b^T U_{i|i} = 0. These are combinations of rows of the matrix in (E), so aTAi=0a^T A^i = 0, aTΔi=0a^T \Delta_i = 0 and b=0b = 0. Δi\Delta_i has rank nn because (A,B)(A, B) is controllable and i≥ni \ge n, so a=0a = 0. With b=0b = 0 forced, the first statement is the special case. □\square

Lemma 6 (the factors). L5 and L6 give G=UnΣn1/2=ΓiTG = U_n \Sigma_n^{1/2} = \Gamma_i T for a nonsingular TT, with σn>0=σn+1\sigma_n > 0 = \sigma_{n+1}. Then G1=Γi−1TG_1 = \Gamma_{i-1} T, and L7 gives X^i=T−1Xf\hat X_i = T^{-1} X_f and X^i+1=T−1Xf+\hat X_{i+1} = T^{-1} X_f^+.

Proof. By Lemmas 4 and 5, Oi=ΓiXfO_i = \Gamma_i X_f is a product of a full column rank and a full row rank matrix, so it has rank nn, and its column space is that of Γi\Gamma_i. The first nn left singular vectors span this space, so Un=ΓiSU_n = \Gamma_i S with SS nonsingular, and T=SΣn1/2T = S \Sigma_n^{1/2}. Deleting the last block row gives G1=Γi−1TG_1 = \Gamma_{i-1} T. Both ΓiT\Gamma_i T and Γi−1T\Gamma_{i-1} T have full column rank, since i−1≥ni - 1 \ge n, so (ΓiT)+=T−1Γi+(\Gamma_i T)^{+} = T^{-1} \Gamma_i^{+} is a left inverse, and the same for i−1i - 1. Hence X^i=T−1Γi+ΓiXf=T−1Xf\hat X_i = T^{-1} \Gamma_i^{+} \Gamma_i X_f = T^{-1} X_f and X^i+1=T−1Γi−1+Γi−1Xf+=T−1Xf+\hat X_{i+1} = T^{-1} \Gamma_{i-1}^{+} \Gamma_{i-1} X_f^+ = T^{-1} X_f^+. □\square

Lemma 7 (the regression). The least squares problem of L8 has the unique solution

θ=(T−1ATT−1BCTD),\theta = \begin{pmatrix} T^{-1} A T & T^{-1} B \\ C T & D \end{pmatrix},

and the residual of L9 is zero.

Proof. Column cc of XfX_f is xi+cx_{i+c}, column cc of Xf+X_f^+ is xi+c+1x_{i+c+1}, and column cc of Yi∣iY_{i|i} is yi+cy_{i+c}. The system equations give, column by column,

(Xf+Yi∣i)=(ABCD)(XfUi∣i).\begin{pmatrix} X_f^+ \\ Y_{i|i} \end{pmatrix} = \begin{pmatrix} A & B \\ C & D \end{pmatrix} \begin{pmatrix} X_f \\ U_{i|i} \end{pmatrix}.

Substitute Xf=TX^iX_f = T \hat X_i and Xf+=TX^i+1X_f^+ = T \hat X_{i+1} and multiply the first block row by T−1T^{-1}: the stated θ\theta solves (X^i+1Yi∣i)=θ(X^iUi∣i)\begin{pmatrix} \hat X_{i+1} \\ Y_{i|i} \end{pmatrix} = \theta \begin{pmatrix} \hat X_i \\ U_{i|i} \end{pmatrix} exactly. By Lemma 5 the right factor has full row rank, so the solution of the least squares problem is unique, and it is this zero-residual solution. □\square

Lemma 8 (working on the rows of L). Computing every step on the rows of the LQ factor LL instead of the rows of the data gives the same results.

Proof. (UY)=LQ\begin{pmatrix} U \\ Y \end{pmatrix} = L Q with QQT=IQ Q^T = I, so each data row is the matching row of LL times QQ. For rows a=aLQa = a_L Q and b=bLQb = b_L Q, abT=aLbLTa b^T = a_L b_L^T, so all inner products are the same. The projections of L3 and L4 are combinations of rows formed with these inner products, so the projection of the data rows is the projection of the LL rows times QQ. If O=OLQO = O_L Q, then OOT=OLOLTO O^T = O_L O_L^T, so OO and OLO_L have the same left singular vectors and singular values. G+O=(G+OL)QG^{+} O = (G^{+} O_L) Q, so the state rows are the LL rows times QQ. In L8, (RLQ)+=QTRL+(R_L Q)^{+} = Q^T R_L^{+}, so (SLQ)(RLQ)+=SLRL+(S_L Q)(R_L Q)^{+} = S_L R_L^{+}, and the residual covariance is 1j(ELQ)(ELQ)T=1jELELT\frac{1}{j} (E_L Q)(E_L Q)^T = \frac{1}{j} E_L E_L^T. □\square

Theorem. Under (E), with (A,B)(A, B) controllable, (A,C)(A, C) observable, i>ni > n and the order chosen as the rank of OiO_i, N4SID returns (T−1AT,T−1B,CT,D)(T^{-1} A T, T^{-1} B, C T, D) for a nonsingular TT, and a zero residual covariance.

Proof. By Lemma 8 the algorithm computes the same quantities as on the data rows. Lemmas 4 to 7 give the result. ■\blacksquare

Remark (noise). With innovation noise, xk+1=Axk+Buk+Kekx_{k+1} = A x_k + B u_k + K e_k and yk=Cxk+Duk+eky_k = C x_k + D u_k + e_k, Van Overschee and De Moor (1994) show that as j→∞j \to \infty, OiO_i tends to ΓiX~i\Gamma_i \tilde X_i, where X~i\tilde X_i is a sequence of Kalman filter states. The residuals of L8 then estimate the noise covariances. That proof needs probability limits and is not repeated here; the test file checks the consistency of the poles and of the output noise variance by a measurement.

Complexity

In the real RAM, counting dense factorizations in the usual way. Let d=2i(m+p)d = 2i(m + p). L1 builds O(Nd)O(N d) numbers. L2 is a Householder LQ factorization of the d×jd \times j matrix, O(d2j)=O(Ni2(m+p)2)O(d^2 j) = O(N i^2 (m + p)^2). L3 and L4 work on rows of length dd: each projection forms Gram matrices and pseudoinverses of at most d×dd \times d matrices, O(d3)O(d^3). L5 is an SVD of an ip×dip \times d matrix, O(i2p2d)O(i^2 p^2 d). L7 to L9 cost O(d(n+m+p)2+n3)O(d (n + m + p)^2 + n^3). The total is O(Ni2(m+p)2+i3(m+p)3)O(N i^2 (m + p)^2 + i^3 (m + p)^3), and for long records the LQ factorization dominates. The extra space is O(Ni(m+p))O(N i (m + p)) for the Hankel matrices; everything after L2 is of size O(d2)O(d^2).

Properties

  • Exact for noise-free data (theorem). Under the assumptions of the claim, the model has the true transfer function.
  • Kalman filter states (theorem). With innovation noise, as j→∞j \to \infty, OiO_i tends to ΓiX~i\Gamma_i \tilde X_i, where X~i\tilde X_i is the state sequence of a bank of non-steady-state Kalman filters started from the past data (Van Overschee and De Moor 1994). This is why N4SID handles process noise, unlike basic MOESP.
  • A bias of this version (theorem, cited). The two state sequences of L7 come from Kalman filters with different initial conditions. Van Overschee and De Moor (1996, Chapter 4) show that this simple version is asymptotically biased unless the data are noise-free or the input is white noise, and give modified algorithms without this bias. The test of the code uses a white input.
  • Noise model. The residuals of L8 estimate QQ, SS and RR, from which a steady-state Kalman gain follows by a Riccati equation.
  • No local minima. There is no nonconvex search.
  • Not efficient. The variance is larger than that of a prediction error method, which is often started from the N4SID estimate.

Variants and improvements

  • Weightings. Multiply OiO_i by weights before the SVD. Van Overschee and De Moor (1995) showed that N4SID, MOESP and CVA (Larimore 1990) differ only in these weights. The weights change the basis of the state and the finite-sample results, but not the limit.
  • The unbiased and robust combined algorithms. The 1996 book gives versions that remove the bias of the simple version for general inputs; the robust one is the version used most in practice.
  • Closed-loop subspace methods. The future inputs depend on past noise in closed loop, and the oblique projection is then biased. Predictor-based methods (SSARX, PBSID) avoid this.
  • MOESP. Uses an orthogonal projection and the observability matrix instead of the state sequence.
  • Deterministic and stochastic special cases. Without inputs, the same projections give a stochastic realization of a time series; without noise, the method is an exact realization from input-output data.

When to use it

Use N4SID to get a multivariable model with a noise model from open-loop data, with no starting value, and as the starting point of a prediction error fit. It gives the order from the singular values and handles many inputs and outputs. Do not use it as the final model when the best accuracy matters, or directly on closed-loop data.

Pitfalls

  • Too few block rows. The method needs i>ni > n. With noise, ii must also be large enough for the Kalman filter states to be good, often several times the expected order.
  • Too few samples. The LQ factorization needs j≥2i(m+p)j \ge 2i(m + p), and the code rejects smaller jj. Accuracy needs much more.
  • An input that is not rich enough. The excitation condition needs the input to be persistently exciting of order about 2i2i. A step or a few sines do not satisfy it.
  • Comparing matrices. The result is in other coordinates. Compare poles, Markov parameters or frequency responses.
  • The order from a weak gap. With colored noise and many block rows, the singular values decrease slowly. Check several orders by validation on fresh data.
  • Pseudoinverse thresholds. In floating point, the projections need thresholds in the pseudoinverses. A threshold that is too small makes the projection amplify noise; the code uses 10−1010^{-10} times the largest singular value.

Implementations

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

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

"""N4SID (Van Overschee and De Moor, 1994), the version that uses two state sequences.

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

Steps: block Hankel matrices U and Y with 2i block rows and j = N - 2i + 1
columns; one LQ factorization of [U; Y] = L Q; the oblique projections
O_i = Y_f /_(U_f) W_p and O_(i-1) = Y_f^- /_(U_f^-) W_p^+; an SVD of O_i that
gives Gamma_i and the order; the state sequences X_i = Gamma_i^+ O_i and
X_(i+1) = Gamma_(i-1)^+ O_(i-1); and one linear least squares problem for
A, B, C and D. The residuals give the noise covariances.

Every row of the data matrix is the matching row of L times Q, and Q has
orthonormal rows. So every projection and every least squares problem is
computed on the rows of L (vectors of length 2 i (m + p)), not on rows of
length j.

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

import math

from ctlmat import mul, sub, transpose

__all__ = ["block_hankel", "householder_lq", "jacobi_svd", "pinv", "oblique_projection", "n4sid", "simulate"]


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


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

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


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

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


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


def oblique_projection(a, b, c):
    """Return a /_b c = (a / b_perp) (c / b_perp)^+ c, for matrices with the same row length.

    x / b_perp = x - x b^T (b b^T)^+ b removes the part of each row of x that
    lies in the row space of b.
    """
    def perp(x):
        return sub(x, mul(mul(mul(x, transpose(b)), pinv(mul(b, transpose(b)))), b))
    return mul(mul(perp(a), pinv(perp(c))), c)


def simulate(A, B, C, D, u, x0, K=None, e=None):
    """Return y_0, ..., y_(N-1) of x_(k+1) = A x_k + B u_k + K e_k, y_k = C x_k + D u_k + e_k."""
    x = list(x0)
    n, out = len(x), []
    for k, uk in enumerate(u):
        ek = e[k] if e is not None else [0.0] * len(C)
        out.append([sum(C[a][t] * x[t] for t in range(n)) + sum(D[a][c] * uk[c] for c in range(len(uk))) + ek[a]
                    for a in range(len(C))])
        x = [sum(A[r][t] * x[t] for t in range(n)) + sum(B[r][c] * uk[c] for c in range(len(uk)))
             + (sum(K[r][a] * ek[a] for a in range(len(ek))) if K is not None else 0.0)
             for r in range(n)]
    return out


def n4sid(u, y, i, n=None, tol=1e-8):
    """Return (A, B, C, D, cov, s): the model, the residual covariance [[Q, S], [S^T, R]], and the singular values of O_i."""
    m, p, N = len(u[0]), len(y[0]), len(u)
    j = N - 2 * i + 1
    if j < 2 * i * (m + p):
        raise ValueError("n4sid: too few samples for i block rows")
    U = block_hankel(u, 2 * i, j)  # @line L1
    Y = block_hankel(y, 2 * i, j)
    L = householder_lq(U + Y)  # @line L2
    Lu, Ly = L[:2 * i * m], L[2 * i * m:]
    Up, Uf = Lu[:i * m], Lu[i * m:]
    Yp, Yf = Ly[:i * p], Ly[i * p:]
    Oi = oblique_projection(Yf, Uf, Up + Yp)  # @line L3
    Up1, Uf1 = Lu[:(i + 1) * m], Lu[(i + 1) * m:]
    Yp1, Yf1 = Ly[:(i + 1) * p], Ly[(i + 1) * p:]
    Oi1 = oblique_projection(Yf1, Uf1, Up1 + Yp1)  # @line L4
    Us, s, _ = jacobi_svd(Oi)  # @line L5
    if n is None:
        n = sum(1 for v in s if v > tol * s[0])
    if n < 1 or n >= i or s[n - 1] <= 0.0:
        raise ValueError("n4sid: need 1 <= n < i and n at most the rank of O_i")
    G = [[Us[r][k] * math.sqrt(s[k]) for k in range(n)] for r in range(i * p)]  # @line L6
    G1 = G[:-p]
    Xi = mul(pinv(G), Oi)  # @line L7
    Xi1 = mul(pinv(G1), Oi1)
    lhs = Xi1 + Ly[i * p:(i + 1) * p]
    rhs = Xi + Lu[i * m:(i + 1) * m]
    theta = mul(lhs, pinv(rhs))  # @line L8
    A = [row[:n] for row in theta[:n]]
    B = [row[n:] for row in theta[:n]]
    C = [row[:n] for row in theta[n:]]
    D = [row[n:] for row in theta[n:]]
    res = sub(lhs, mul(theta, rhs))  # @line L9
    cov = [[v / j for v in row] for row in mul(res, transpose(res))]
    return A, B, C, D, cov, s  # @line L10
test_n4sid.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/n4sid/. The authors are listed in prov/0NXMFM.jsonl.

import random

from ctlmat import add, charpoly, mul, polyroots, transpose
from n4sid import householder_lq, n4sid, oblique_projection, simulate


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


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


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


def _rand(rng, r, c):
    return [[rng.uniform(-1, 1) for _ in range(c)] for _ in range(r)]


def test_oblique_projection_splits_a_sum():
    # if a = M c + P b and the row spaces of b and c meet only in 0, then a /_b c = M c
    rng = random.Random(2)
    for _ in range(10):
        b, c = _rand(rng, 2, 9), _rand(rng, 3, 9)
        M, P = _rand(rng, 4, 3), _rand(rng, 4, 2)
        a = add(mul(M, c), mul(P, b))
        assert _close(oblique_projection(a, b, c), mul(M, c), 1e-10)


def test_lq_factor():
    rng = random.Random(1)
    a = _rand(rng, 5, 11)
    L = householder_lq(a)
    assert all(L[r][c] == 0.0 for r in range(5) for c in range(r + 1, 5))
    assert _close(mul(L, transpose(L)), mul(a, transpose(a)), 1e-12)


def test_exact_siso():
    A0 = [[0.7, 0.4], [-0.4, 0.7]]
    B0 = [[1.0], [0.5]]
    C0 = [[1.0, 0.0]]
    D0 = [[0.2]]
    rng = random.Random(7)
    u = [[rng.gauss(0.0, 1.0)] for _ in range(300)]
    y = simulate(A0, B0, C0, D0, u, [0.5, -1.0])
    A, B, C, D, cov, s = n4sid(u, y, 4)
    assert len(A) == 2
    assert s[2] < 1e-12 * s[0]
    assert _eig_error(A, A0) < 1e-10
    assert abs(D[0][0] - 0.2) < 1e-10
    for g, g0 in zip(_markov(A, B, C, 12), _markov(A0, B0, C0, 12)):
        assert _close(g, g0, 1e-10)
    assert all(abs(v) < 1e-20 for row in cov for v in row)


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


def test_innovation_noise():
    # measurement: innovation form with K = [0.5, 0.2]^T, e white with variance 0.01,
    # white input, N = 2000, i = 5
    A0 = [[0.7, 0.4], [-0.4, 0.7]]
    B0 = [[1.0], [0.5]]
    C0 = [[1.0, 0.0]]
    D0 = [[0.2]]
    K0 = [[0.5], [0.2]]
    for seed in (1, 2, 3):
        rng = random.Random(seed)
        u = [[rng.gauss(0.0, 1.0)] for _ in range(2000)]
        e = [[rng.gauss(0.0, 0.1)] for _ in range(2000)]
        y = simulate(A0, B0, C0, D0, u, [0.0, 0.0], K0, e)
        A, B, C, D, cov, s = n4sid(u, y, 5, n=2)
        assert s[1] > 50 * s[2]
        assert _eig_error(A, A0) < 0.01
        assert abs(D[0][0] - 0.2) < 0.02
        assert abs(cov[2][2] - 0.01) < 0.002


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

History

Akaike's work on canonical correlations in the 1970s and Larimore's canonical variate analysis of 1990 used projections of the future on the past for time series and for systems with inputs. Van Overschee and De Moor gave the oblique projection, the Kalman filter interpretation of the states, and the N4SID algorithms in Automatica in 1994. In 1995 they proved a unifying theorem that places N4SID, MOESP and CVA in one framework, and their 1996 book became the standard reference on subspace identification.

References

  1. Peter Van Overschee and Bart De Moor, N4SID: Subspace algorithms for the identification of combined deterministic-stochastic systems, Automatica 30(1), 75-93, 1994, the oblique projection, the Kalman filter interpretation of the state sequences, and the algorithms that use them
  2. Peter Van Overschee and Bart De Moor, Subspace Identification for Linear Systems: Theory, Implementation, Applications, Kluwer Academic Publishers, 1996 (ISBN 978-1-4613-8061-0), Chapter 4 (Combined Deterministic-Stochastic Identification), pp. 95-134
  3. Peter Van Overschee and Bart De Moor, A unifying theorem for three subspace system identification algorithms, Automatica 31(12), 1853-1864, 1995, N4SID, MOESP and CVA as weighted versions of one algorithm
  4. Wallace E. Larimore, Canonical variate analysis in identification, filtering, and adaptive control, Proceedings of the 29th IEEE Conference on Decision and Control, 596-604, 1990, the canonical variate analysis (CVA) weighting

About this page

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

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