Algorithm Search⌘K

Algorithmcore

Instrumental variable identification

Also called IV identification, instrument variable method for system identification.

Replaces the regressors by instruments that are correlated with them but not with the noise, so the estimate stays consistent for colored noise.

Time
O(N d^2 + d^3) worst
Space
O(N + d^2) extra
Where
N = the number of samples; d = the number of parameters
Properties
deterministicexactofflineiterative
Origin
Kwan Y. Wong, Elijah Polak, 1967

Instrumental variable identification estimates the coefficients of the difference equation A(q) y(k)=B(q) u(k)+v(k)A(q)\, y(k) = B(q)\, u(k) + v(k) when the disturbance vv is colored, the case where least-squares ARX identification is biased. The bias comes from the past outputs in the regressor φ(k)\varphi(k), which are correlated with v(k)v(k). The method keeps φ(k)\varphi(k) but multiplies the equations by an instrument vector ζ(k)\zeta(k) that is correlated with φ(k)\varphi(k) and uncorrelated with v(k)v(k), and solves ∑ζ(k)(y(k)−φ(k)Tθ)=0\sum \zeta(k) \big(y(k) - \varphi(k)^T \theta\big) = 0, a square linear system of size d=na+nbd = n_a + n_b. It is the general instrumental variables estimator of statistics applied to a dynamic system, with one difference: the instruments are not extra measured variables but are built from the input itself, as delayed inputs or as the noise-free output of a simulated model. They are valid because in open loop the input is independent of the disturbance. The cost is O(Nd2+d3)O(N d^2 + d^3), the same as least squares, and the estimate is consistent for any stationary disturbance that is independent of the input, provided the instruments are built from the input only and E ζ(k)φ(k)T\mathbb{E}\, \zeta(k) \varphi(k)^T is nonsingular.

In plain words

Least squares explains each output by the past outputs and inputs. When the noise has a memory, the past outputs carry some of the same noise as the present output, and least squares mistakes that shared noise for system behavior. The fix is to weigh the equations with signals that move with the past outputs but know nothing about the noise. The input is such a signal: you chose it, so it does not depend on the noise. Delayed copies of the input, or the output of a rough model driven by the input, serve as these helper signals. The arithmetic is the same as for least squares, one pass over the data and one small system of equations, but one factor in each product is a helper signal instead of the data.

The problem

Input. Samples y(0),…,y(N−1)y(0), \ldots, y(N-1) and u(0),…,u(N−1)u(0), \ldots, u(N-1) taken in open loop, orders na≥0n_a \ge 0, nb≥1n_b \ge 1, nk≥0n_k \ge 0, and a choice of instruments: delayed or model.

Model. A(q)=1+a1q−1+⋯+anaq−naA(q) = 1 + a_1 q^{-1} + \cdots + a_{n_a} q^{-n_a} and B(q)=b1q−nk+⋯+bnbq−nk−nb+1B(q) = b_1 q^{-n_k} + \cdots + b_{n_b} q^{-n_k-n_b+1}, with regressor φ(k)=(−y(k−1),…,−y(k−na), u(k−nk),…,u(k−nk−nb+1))T\varphi(k) = \big(-y(k-1), \ldots, -y(k-n_a),\ u(k-n_k), \ldots, u(k-n_k-n_b+1)\big)^T and θ=(a1,…,ana,b1,…,bnb)\theta = (a_1, \ldots, a_{n_a}, b_1, \ldots, b_{n_b}). The disturbance vv may be any stationary process independent of uu; it need not be white.

Instruments. The delayed instruments are ζ(k)=(u(k−nk),u(k−nk−1),…,u(k−nk−d+1))T\zeta(k) = \big(u(k-n_k), u(k-n_k-1), \ldots, u(k-n_k-d+1)\big)^T. The model instruments are ζ(k)=(−x(k−1),…,−x(k−na), u(k−nk),…,u(k−nk−nb+1))T\zeta(k) = \big(-x(k-1), \ldots, -x(k-n_a),\ u(k-n_k), \ldots, u(k-n_k-n_b+1)\big)^T, where x=(Baux/Aaux) ux = (B_{\text{aux}}/A_{\text{aux}})\, u is the output of an auxiliary model simulated from rest, by default the least squares ARX fit.

Output. The solution θ^\hat\theta of the IV equations

∑k=k0N−1ζ(k)(y(k)−φ(k)Tθ)=0,\sum_{k=k_0}^{N-1} \zeta(k) \big(y(k) - \varphi(k)^T \theta\big) = 0,

or a report that their matrix is singular.

The algorithm

  1. IV-ARX(y, u, na, nb, nk, ⟨instruments⟩)
  2. 1d ← na + nb; k0 ← max(na, nk + d - 1) for delayed instruments, max(na, nk + nb - 1) for model instruments; for model instruments: θaux ← ARX-LS(y, u, na, nb, nk) and x ← (Baux / Aaux) u from rest
  3. 2R ← the d × d zero matrix; f ← the zero vector of length d
  4. 3for k ← k0 to N - 1 do
  5. 4φ ← (-y(k-1), ..., -y(k-na), u(k-nk), ..., u(k-nk-nb+1)); ζ ← the instrument vector at time k
  6. 5R ← R + ζ φᵀ
  7. 6f ← f + ζ · y(k)
  8. 7if R is singular then fail: the instruments are not correlated enough with φ
  9. 8θ ← the solution of R θ = f
  10. 9return θ

Line L1 chooses the first time k0k_0 at which both φ(k)\varphi(k) and ζ(k)\zeta(k) stay inside the record; the delayed instruments reach back to u(k−nk−d+1)u(k - n_k - d + 1), further than the regressor. For model instruments, L1 also runs least squares once and simulates the auxiliary model, using only uu, so xx contains no noise. Lines L3 to L6 add up the IV equations in one pass. Unlike the least squares matrix, RR is not symmetric and not positive semidefinite, so L8 needs a general solver such as Gaussian elimination with pivoting. With ζ=φ\zeta = \varphi the loop is exactly the loop of least squares.

Example

Take na=nb=nk=1n_a = n_b = n_k = 1 and delayed instruments, so φ(k)=(−y(k−1),u(k−1))\varphi(k) = (-y(k-1), u(k-1)), ζ(k)=(u(k−1),u(k−2))\zeta(k) = (u(k-1), u(k-2)) and k0=2k_0 = 2. The data are those of the least squares example,

u=(1,1,−1,1,−1,−1),y=(0,1,1.4,−0.2,0.9,−0.6).u = (1, 1, -1, 1, -1, -1), \qquad y = (0, 1, 1.4, -0.2, 0.9, -0.6).
kk ζ(k)\zeta(k) φ(k)\varphi(k) y(k)y(k) φ(k)Tθ^\varphi(k)^T \hat\theta residual
2 (1,1)(1, 1) (−1,1)(-1, 1) 1.41.4 1.41.4 00
3 (−1,1)(-1, 1) (−1.4,−1)(-1.4, -1) −0.2-0.2 −0.3091-0.3091 0.10910.1091
4 (1,−1)(1, -1) (0.2,1)(0.2, 1) 0.90.9 0.85450.8545 0.04550.0455
5 (−1,1)(-1, 1) (−0.9,−1)(-0.9, -1) −0.6-0.6 −0.5364-0.5364 −0.0636-0.0636

The loop of L3 to L6 gives

R=(1.54−3.5−2),f=(3.1−0.3).R = \begin{pmatrix} 1.5 & 4 \\ -3.5 & -2 \end{pmatrix}, \qquad f = \begin{pmatrix} 3.1 \\ -0.3 \end{pmatrix}.

For example R21=∑u(k−2)⋅(−y(k−1))=−1−1.4−0.2−0.9=−3.5R_{21} = \sum u(k-2) \cdot (-y(k-1)) = -1 - 1.4 - 0.2 - 0.9 = -3.5. The determinant is 1.5⋅(−2)−4⋅(−3.5)=111.5 \cdot (-2) - 4 \cdot (-3.5) = 11, so L7 passes, and L8 gives

a^=−2⋅3.1−4⋅(−0.3)11=−511≈−0.4545,b^=1.5⋅(−0.3)+3.5⋅3.111=5255≈0.9455.\hat a = \frac{-2 \cdot 3.1 - 4 \cdot (-0.3)}{11} = -\frac{5}{11} \approx -0.4545, \qquad \hat b = \frac{1.5 \cdot (-0.3) + 3.5 \cdot 3.1}{11} = \frac{52}{55} \approx 0.9455.

The residuals are orthogonal to both instrument columns, 0−0.1091+0.0455+0.0636=00 - 0.1091 + 0.0455 + 0.0636 = 0 and 0+0.1091−0.0455−0.0636=00 + 0.1091 - 0.0455 - 0.0636 = 0, but not to the column −y(k−1)-y(k-1) of φ\varphi; least squares on one more equation of the same data gave (−0.4851,0.9655)(-0.4851, 0.9655).

Correctness

Claim. If R=∑k≥k0ζ(k)φ(k)TR = \sum_{k \ge k_0} \zeta(k) \varphi(k)^T is nonsingular, IV-ARX returns the unique solution of the IV equations. If moreover the data satisfy y(k)=φ(k)Tθ0+v(k)y(k) = \varphi(k)^T \theta_0 + v(k) for k≥k0k \ge k_0, then θ^−θ0=R−1∑ζ(k) v(k)\hat\theta - \theta_0 = R^{-1} \sum \zeta(k)\, v(k); in particular θ^=θ0\hat\theta = \theta_0 exactly for noise-free data, and θ^→θ0\hat\theta \to \theta_0 whenever 1NR\frac1N R tends to a nonsingular matrix and 1N∑ζ(k)v(k)→0\frac1N \sum \zeta(k) v(k) \to 0.

Key invariant. After the pass of the loop for time kk, R=∑j=k0kζ(j)φ(j)TR = \sum_{j=k_0}^{k} \zeta(j) \varphi(j)^T and f=∑j=k0kζ(j) y(j)f = \sum_{j=k_0}^{k} \zeta(j)\, y(j).

With the invariant at k=N−1k = N - 1, the IV equations read Rθ=fR \theta = f, and L8 solves them. Substituting y=φTθ0+vy = \varphi^T \theta_0 + v into ff gives f=Rθ0+∑ζvf = R \theta_0 + \sum \zeta v, which yields the error formula. The full proof is below.

Proof: IV-ARX solves the IV equations, and its error is R^-1 times the instrument-noise sumfull

Fix the data y(0),…,y(N−1)y(0), \ldots, y(N-1), u(0),…,u(N−1)u(0), \ldots, u(N-1), the orders na≥0n_a \ge 0, nb≥1n_b \ge 1, nk≥0n_k \ge 0, and d=na+nbd = n_a + n_b. We work in exact real arithmetic, as in the real RAM. Let φ(k)\varphi(k) be the regressor and ζ(k)\zeta(k) the instrument vector of line L4, and write

Rk=∑j=k0kζ(j)φ(j)T,fk=∑j=k0kζ(j) y(j),R_k = \sum_{j=k_0}^{k} \zeta(j) \varphi(j)^T, \qquad f_k = \sum_{j=k_0}^{k} \zeta(j)\, y(j),

with Rk0−1=0R_{k_0-1} = 0 and fk0−1=0f_{k_0-1} = 0.

Lemma 1 (the vectors are defined). For k≥k0k \ge k_0 every index used by φ(k)\varphi(k) and ζ(k)\zeta(k) lies in {0,…,N−1}\{0, \ldots, N-1\}.

Proof. The regressor uses k−ik - i for 1≤i≤na1 \le i \le n_a and k−nk−jk - n_k - j for 0≤j≤nb−10 \le j \le n_b - 1; these are at least k−nak - n_a and k−nk−nb+1k - n_k - n_b + 1. The delayed instruments use k−nk−jk - n_k - j for 0≤j≤d−10 \le j \le d - 1, at least k−nk−d+1k - n_k - d + 1. The model instruments use the same indices as the regressor, into the simulated signal xx, which has the same length as uu. In each case L1 chooses k0k_0 as the largest of the shifts that occur, so every index is at least k−k0≥0k - k_0 \ge 0. Every index is at most k≤N−1k \le N - 1. □\square

Lemma 2 (loop invariant). After the pass of the loop of L3 for time kk, the variables hold R=RkR = R_k and f=fkf = f_k.

Proof. By induction on kk. Line L2 sets R=0=Rk0−1R = 0 = R_{k_0-1} and f=0=fk0−1f = 0 = f_{k_0-1}. If R=Rk−1R = R_{k-1} and f=fk−1f = f_{k-1} before the pass for kk, then L5 and L6 give Rk−1+ζ(k)φ(k)T=RkR_{k-1} + \zeta(k) \varphi(k)^T = R_k and fk−1+ζ(k) y(k)=fkf_{k-1} + \zeta(k)\, y(k) = f_k. □\square

After the loop, R=RN−1R = R_{N-1} and f=fN−1f = f_{N-1}; write them RR and ff.

Lemma 3 (the IV equations). A vector θ\theta solves ∑k=k0N−1ζ(k)(y(k)−φ(k)Tθ)=0\sum_{k=k_0}^{N-1} \zeta(k) \big(y(k) - \varphi(k)^T \theta\big) = 0 if and only if Rθ=fR \theta = f.

Proof. The left side equals ∑ζ(k)y(k)−(∑ζ(k)φ(k)T)θ=f−Rθ\sum \zeta(k) y(k) - \big(\sum \zeta(k) \varphi(k)^T\big) \theta = f - R \theta. □\square

Lemma 4 (the error formula). Suppose RR is nonsingular and, for some θ0\theta_0 and some sequence vv, y(k)=φ(k)Tθ0+v(k)y(k) = \varphi(k)^T \theta_0 + v(k) for every k≥k0k \ge k_0. Then the solution of Rθ=fR\theta = f is θ^=θ0+R−1∑k=k0N−1ζ(k) v(k)\hat\theta = \theta_0 + R^{-1} \sum_{k=k_0}^{N-1} \zeta(k)\, v(k).

Proof. f=∑ζ(k)(φ(k)Tθ0+v(k))=Rθ0+∑ζ(k)v(k)f = \sum \zeta(k) \big(\varphi(k)^T \theta_0 + v(k)\big) = R \theta_0 + \sum \zeta(k) v(k). Multiply by R−1R^{-1}. □\square

Theorem. If RR is nonsingular, IV-ARX returns the unique solution θ^\hat\theta of the IV equations; if RR is singular, it stops at L7. Under the hypothesis of Lemma 4:

  1. if v(k)=0v(k) = 0 for all k≥k0k \ge k_0, then θ^=θ0\hat\theta = \theta_0;
  2. for a sequence of data sets with N→∞N \to \infty, if 1NR→Rˉ\frac{1}{N} R \to \bar R with Rˉ\bar R nonsingular and 1N∑ζ(k)v(k)→0\frac{1}{N} \sum \zeta(k) v(k) \to 0, then θ^→θ0\hat\theta \to \theta_0.

Proof. By Lemma 1 every vector in the loop is well defined, and by Lemma 2 the loop leaves RR and ff. If RR is singular, L7 stops. Otherwise L8 computes the unique solution of Rθ=fR \theta = f, which by Lemma 3 is the unique solution of the IV equations, and L9 returns it.

(1) follows from Lemma 4 with ∑ζv=0\sum \zeta v = 0.

(2) Write θ^−θ0=(1NR)−1(1N∑ζv)\hat\theta - \theta_0 = \big(\frac1N R\big)^{-1} \big(\frac1N \sum \zeta v\big) by Lemma 4. Matrix inversion is continuous on the open set of nonsingular matrices, so 1NR\frac1N R is nonsingular for all large NN and (1NR)−1→Rˉ−1\big(\frac1N R\big)^{-1} \to \bar R^{-1}. The product of a convergent sequence of matrices and a sequence of vectors that tends to 0 tends to 0. Hence θ^→θ0\hat\theta \to \theta_0. ■\blacksquare

The hypotheses of (2) are where the instruments matter. In open loop with vv stationary, ergodic and independent of uu, and with ζ\zeta built from uu only, the law of large numbers gives 1N∑ζv→E ζv=0\frac1N \sum \zeta v \to \mathbb{E}\, \zeta v = 0 and 1NR→E ζφT\frac1N R \to \mathbb{E}\, \zeta \varphi^T with probability 1, so (2) holds whenever E ζφT\mathbb{E}\, \zeta \varphi^T is nonsingular. With ζ=φ\zeta = \varphi the first limit is E φv\mathbb{E}\, \varphi v, which is not 0 for colored vv, and this is the bias of least squares.

Complexity

Line L4 costs O(d)O(d) and lines L5 and L6 cost d2+dd^2 + d multiplications, so the loop costs O(Nd2)O(N d^2). Line L8 costs O(d3)O(d^3) by Gaussian elimination, which also detects the singular case of L7. For model instruments, L1 adds one least squares fit, O(Nd2+d3)O(N d^2 + d^3), and one simulation, O(Nd)O(N d). The total is O(Nd2+d3)O(N d^2 + d^3) in the real RAM. The extra space is O(d2)O(d^2) for RR and ff, plus O(N)O(N) for the simulated output xx with model instruments.

Properties

  • Exact. In exact arithmetic the result is the exact solution of the IV equations; with rational data it is rational, and noise-free ARX data of the right orders give θ0\theta_0 exactly.
  • Consistent for colored noise (theorem). If the data come from A0y=B0u+vA_0 y = B_0 u + v in open loop with vv stationary and independent of uu, the instruments are built from uu only, and E ζ(k)φ(k)T\mathbb{E}\, \zeta(k) \varphi(k)^T is nonsingular, then θ^→θ0\hat\theta \to \theta_0 with probability 1 (Söderström and Stoica 1989; Ljung 1999, Chapter 8). No model of vv is needed.
  • The nonsingularity condition (computation). For the delayed instruments with na=nb=2n_a = n_b = 2, nk=1n_k = 1 and white unit-variance uu, the entries of E ζφT\mathbb{E}\, \zeta \varphi^T are 00, 11 or −gi-g_i, where gig_i is the impulse response of B0/A0B_0/A_0, and the matrix is nonsingular exactly when g22−g1g3≠0g_2^2 - g_1 g_3 \ne 0. For A0=1−1.5q−1+0.7q−2A_0 = 1 - 1.5 q^{-1} + 0.7 q^{-2} and B0=q−1+0.5q−2B_0 = q^{-1} + 0.5 q^{-2}, g=(1,2,2.3,…)g = (1, 2, 2.3, \ldots) and g22−g1g3=1.7g_2^2 - g_1 g_3 = 1.7.
  • Bias removed (measurement). For that system with ARMAX noise C=1−q−1+0.2q−2C = 1 - q^{-1} + 0.2 q^{-2}, a white ±1\pm 1 input and N=50000N = 50000, least squares gave (−1.2286,0.4547,0.9965,0.7650)(-1.2286, 0.4547, 0.9965, 0.7650), delayed IV gave (−1.5250,0.7356,0.9956,0.4698)(-1.5250, 0.7356, 0.9956, 0.4698) and model IV gave (−1.5067,0.7071,0.9954,0.4877)(-1.5067, 0.7071, 0.9954, 0.4877), against the true (−1.5,0.7,1,0.5)(-1.5, 0.7, 1, 0.5).
  • Variance depends on the instruments (measurement). Over 20 runs with N=2000N = 2000, the estimate of a1a_1 had mean −1.2248-1.2248 and standard deviation 0.01360.0136 for least squares, −1.5162-1.5162 and 0.0380.038 for delayed IV, and −1.5023-1.5023 and 0.01420.0142 for model IV. Here the model instruments, which are closer to the noise-free regressor, gave the smaller variance.
  • Not efficient (theorem). The basic IV estimate is in general less accurate than the prediction error method with a correct noise model; the best accuracy over all instruments and prefilters needs the true noise model (Söderström and Stoica 1989).

Variants and improvements

  • Extended IV. Use more instruments than parameters and solve the overdetermined system ∑ζφTθ=∑ζy\sum \zeta \varphi^T \theta = \sum \zeta y in a weighted least squares sense, which can lower the variance.
  • Prefiltered and refined IV. Filter yy, uu and the instruments by a filter L(q)L(q) before L3. With LL close to the inverse of the noise model, and the instruments from the current model, iterating gives the refined IV method of Young, which approaches the optimal accuracy.
  • Multistep IV. Least squares, then model IV, then a noise model fitted to the residuals, then IV again with prefiltering, a fixed sequence of linear solves.
  • Recursive IV. Update θ^\hat\theta after every sample in O(d2)O(d^2) as in the RLS algorithm, with ζ\zeta in place of one of the two φ\varphi factors.
  • Closed loop. In closed-loop identification, build the instruments from the external reference signal rr, which is independent of the noise, instead of from uu.
  • Two-stage least squares. Regressing φ\varphi on the instruments and then yy on the fitted regressor is two-stage least squares. It gives the same estimate when there are as many instruments as parameters, and an extended IV estimate with one particular weighting when there are more.

When to use it

Use it when least squares is biased because the disturbance is colored, and a full noise model is not needed or not wanted. It costs one or two linear solves, needs no starting value and has no local minima, so it is also a good starting value for the prediction error method on ARMAX or Box-Jenkins structures. Do not use input-based instruments when the data come from a closed loop, and prefer a prediction error method when the most accurate estimate is needed.

Pitfalls

  • Past outputs as instruments. Taking ζ(k)=φ(k)\zeta(k) = \varphi(k), or any vector with measured y(k−i)y(k-i), in L4 brings back the correlation with v(k)v(k) and the bias of least squares. In L4 the instrument must be built from uu only, or from the simulated xx.
  • A one-step predictor instead of a simulation. Computing x(k)x(k) in L1 from measured past outputs, x(k)=−∑aiy(k−i)+⋯x(k) = -\sum a_i y(k-i) + \cdots, puts the noise into the instruments. L1 must simulate x=(Baux/Aaux) ux = (B_{\text{aux}}/A_{\text{aux}})\, u from rest, using its own past values.
  • The start index of least squares. Starting the loop of L3 at max⁡(na,nk+nb−1)\max(n_a, n_k + n_b - 1) with delayed instruments makes ζ\zeta read uu before time 0; in Python a negative index silently reads the end of the record. For delayed instruments, L1 must use k0=max⁡(na,nk+d−1)k_0 = \max(n_a, n_k + d - 1).
  • Feedback in the data. In closed loop uu depends on past noise, so instruments from uu are correlated with vv and the estimate is biased. Build ζ\zeta in L4 from the reference signal instead.
  • A nearly singular RR. If the input is not persistently exciting of order dd or more, or if a computation like g22−g1g3g_2^2 - g_1 g_3 is close to 0, RR in L7 is close to singular and the estimate has a large variance. Choose a rich input, or model instruments, before L3.

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()
instrumental_variable_identification.py 111 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/instrumental-variable-identification/. The authors are listed in prov/YQN1Q7.jsonl.

"""Instrumental variable identification of the parameters of an ARX structure.

The model is A(q) y(t) = B(q) u(t) + v(t) with
A = 1 + a_1 q^-1 + ... + a_na q^-na and B = b_1 q^-nk + ... +
b_nb q^-(nk+nb-1). The noise v(t) may be colored. With the regressor
phi(t) = (-y(t-1), ..., -y(t-na), u(t-nk), ..., u(t-nk-nb+1)) and an
instrument vector zeta(t) of the same length d = na + nb, the estimate is

    theta = (sum of zeta(t) phi(t)^T)^-1 (sum of zeta(t) y(t)).

Two instrument choices are given:
- "delayed": zeta(t) = (u(t-nk), u(t-nk-1), ..., u(t-nk-d+1)).
- "model": zeta(t) = (-x(t-1), ..., -x(t-na), u(t-nk), ..., u(t-nk-nb+1))
  with x = (B_aux / A_aux) u, the noise-free output of an auxiliary model
  (by default the least squares ARX fit). This is the two-step IV.

Precondition: na >= 0, nb >= 1, nk >= 0, len(y) == len(u) and the matrix
sum of zeta phi^T is nonsingular. With int or Fraction data and the
"delayed" instruments the result is exact (Fraction).

Cost: O(N d^2) to form the sums and O(d^3) to solve, in the real RAM.
"""

from typing import Callable, Optional, Sequence

from ctlmat import solve


def regressor(y: Sequence, u: Sequence, na: int, nb: int, nk: int, t: int) -> list:
    """Return phi(t) = (-y(t-1), ..., -y(t-na), u(t-nk), ..., u(t-nk-nb+1))."""
    return [-y[t - i] for i in range(1, na + 1)] + [u[t - nk - j] for j in range(nb)]


def iv_solve(y: Sequence, phi: Callable[[int], list], zeta: Callable[[int], list],
             t0: int) -> list:
    """Return theta from sum of zeta phi^T theta = sum of zeta y over t0 <= t < N."""
    d = len(phi(t0))
    r = [[0] * d for _ in range(d)]  # @line L2
    f = [0] * d
    for t in range(t0, len(y)):  # @line L3
        p = phi(t)  # @line L4
        z = zeta(t)
        if len(z) != d:
            raise ValueError("zeta and phi must have the same length")
        for i in range(d):
            zi = z[i]
            if zi == 0:
                continue
            row = r[i]
            for j in range(d):
                row[j] += zi * p[j]  # @line L5
            f[i] += zi * y[t]  # @line L6
    try:
        return solve(r, f)  # @line L8
    except ValueError:
        raise ValueError("sum of zeta phi^T is singular: the instruments are not correlated enough with phi") from None  # @line L7


def _simulate_arx(a: Sequence, b: Sequence, nk: int, u: Sequence) -> list:
    """Return x with A x = B u from rest."""
    x = []
    for t in range(len(u)):
        s = 0
        for j, bj in enumerate(b):
            if t - nk - j >= 0:
                s += bj * u[t - nk - j]
        for i, ai in enumerate(a, start=1):
            if t - i >= 0:
                s -= ai * x[t - i]
        x.append(s)
    return x


def iv_arx(y: Sequence, u: Sequence, na: int, nb: int, nk: int = 1,
           instruments: str = "delayed", aux: Optional[Sequence] = None) -> list:
    """IV estimate (a_1, ..., a_na, b_1, ..., b_nb).

    instruments is "delayed" or "model". For "model", aux is the auxiliary
    parameter vector (a, b); if it is None the least squares ARX estimate is
    used. Raises ValueError for bad orders, short data or a singular matrix.
    """
    if na < 0 or nb < 1 or nk < 0:
        raise ValueError("need na >= 0, nb >= 1 and nk >= 0")
    if len(y) != len(u):
        raise ValueError("y and u must have the same length")
    d = na + nb

    def phi(t):
        return regressor(y, u, na, nb, nk, t)

    if instruments == "delayed":
        t0 = max(na, nk + d - 1)  # @line L1

        def zeta(t):
            return [u[t - nk - j] for j in range(d)]
    elif instruments == "model":
        t0 = max(na, nk + nb - 1)
        if aux is None:
            aux = iv_solve(y, phi, phi, t0)
        x = _simulate_arx(list(aux[:na]), list(aux[na:]), nk, u)

        def zeta(t):
            return regressor(x, u, na, nb, nk, t)
    else:
        raise ValueError("instruments must be 'delayed' or 'model'")
    if len(y) - t0 < d:
        raise ValueError("too few samples for the model orders")
    return iv_solve(y, phi, zeta, t0)  # @line L9
test_instrumental_variable_identification.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/instrumental-variable-identification/. The authors are listed in prov/YQN1Q7.jsonl.

import random
from fractions import Fraction

from instrumental_variable_identification import iv_arx, iv_solve, regressor

A_TRUE = [-1.5, 0.7]
B_TRUE = [1.0, 0.5]
C_TRUE = [-1.0, 0.2]


def _armax(a, b, c, u, e):
    y = []
    for t in range(len(u)):
        s = e[t]
        for i, ci in enumerate(c, start=1):
            if t - i >= 0:
                s += ci * e[t - i]
        for j, bj in enumerate(b):
            if t - 1 - j >= 0:
                s += bj * u[t - 1 - j]
        for i, ai in enumerate(a, start=1):
            if t - i >= 0:
                s -= ai * y[t - i]
        y.append(s)
    return y


def _data(n, seed):
    rng = random.Random(seed)
    u = [rng.choice((-1.0, 1.0)) for _ in range(n)]
    e = [rng.gauss(0.0, 1.0) for _ in range(n)]
    return _armax(A_TRUE, B_TRUE, C_TRUE, u, e), u


def test_worked_example():
    y, u = _data(2000, 1)
    want_delayed = [-1.5471, 0.7584, 1.0261, 0.4135]
    want_model = [-1.5210, 0.7207, 1.0311, 0.4428]
    got = iv_arx(y, u, 2, 2, 1)
    assert all(abs(p - q) < 1e-4 for p, q in zip(got, want_delayed))
    got = iv_arx(y, u, 2, 2, 1, "model")
    assert all(abs(p - q) < 1e-4 for p, q in zip(got, want_model))


def test_exact_without_noise():
    rng = random.Random(4)
    a = [Fraction(-3, 2), Fraction(7, 10)]
    b = [Fraction(1), Fraction(1, 2)]
    u = [rng.choice((-1, 1)) for _ in range(25)]
    y = _armax(a, b, [], u, [0] * 25)
    assert iv_arx(y, u, 2, 2, 1) == a + b
    assert iv_arx(y, u, 2, 2, 1, "model") == a + b


def test_random_phi_as_instrument_is_least_squares():
    # Oracle: with zeta = phi the estimate must satisfy the least squares
    # normal equations exactly: the residual is orthogonal to every column.
    rng = random.Random(99)
    done = 0
    while done < 500:
        na = rng.randint(0, 2)
        nb = rng.randint(1, 2)
        nk = rng.randint(0, 2)
        n = rng.randint(na + nb + 5, 12)
        u = [rng.randint(-3, 3) for _ in range(n)]
        y = [Fraction(rng.randint(-9, 9), rng.randint(1, 3)) for _ in range(n)]
        t0 = max(na, nk + nb - 1)

        def phi(t):
            return regressor(y, u, na, nb, nk, t)

        try:
            theta = iv_solve(y, phi, phi, t0)
        except ValueError:
            continue
        for i in range(na + nb):
            s = 0
            for t in range(t0, n):
                p = phi(t)
                s += p[i] * (y[t] - sum(x * th for x, th in zip(p, theta)))
            assert s == 0
        done += 1


def test_consistent_where_least_squares_is_biased():
    y, u = _data(20000, 2)
    iv = iv_arx(y, u, 2, 2, 1, "model")
    for est, true in zip(iv, A_TRUE + B_TRUE):
        assert abs(est - true) < 0.05

    def phi(t):
        return regressor(y, u, 2, 2, 1, t)

    ls = iv_solve(y, phi, phi, 2)
    assert abs(ls[0] - A_TRUE[0]) > 0.15


def test_constant_input_gives_singular_matrix():
    u = [1] * 20
    y = _armax([Fraction(-1, 2)], [1], [], u, [0] * 20)
    try:
        iv_arx(y, u, 1, 1, 1)
    except ValueError:
        pass
    else:
        raise AssertionError("expected a singular matrix")


def test_bad_arguments():
    for args, kwargs in ((([1.0] * 9, [1.0] * 9, 1, 0), {}), (([1.0] * 9, [1.0] * 8, 1, 1), {}),
                         (([1.0] * 9, [1.0] * 9, 1, 1), {"instruments": "other"}),
                         (([1.0] * 3, [1.0] * 3, 2, 2), {})):
        try:
            iv_arx(*args, **kwargs)
        except ValueError:
            continue
        raise AssertionError("expected ValueError")

History

The instrumental variable idea came from econometrics, where it was used to estimate equations whose regressors are correlated with the error. In the middle of the 1960s Young, and Wong and Polak in 1967, applied it to discrete-time dynamic systems, with instruments generated from the input by an auxiliary model. Söderström and Stoica analyzed the method in detail from about 1980 on, in a monograph of 1983 and in their 1989 textbook: they gave the conditions for consistency, the asymptotic covariance and the optimal choice of instruments and prefilters. Young's refined IV method is the iterative form that approaches that optimal accuracy.

References

  1. Torsten Söderström and Petre Stoica, System Identification, Prentice Hall, 1989, the chapter on instrumental variable methods (the basic and extended IV estimates, consistency conditions, asymptotic covariance and optimal instruments)
  2. Lennart Ljung, System Identification: Theory for the User, second edition, Prentice Hall, 1999, Chapter 7 (the instrumental variable method among the correlation approaches) and Chapter 8 (consistency)
  3. Kwan Y. Wong and Elijah Polak, Identification of linear discrete time systems using the instrumental variable method, IEEE Transactions on Automatic Control 12(6), 707-718, 1967, the instrumental variable estimate for linear discrete-time systems and its consistency
  4. Torsten Söderström and Petre Stoica, Instrumental variable methods for system identification, Circuits, Systems and Signal Processing 21(1), 1-9, 2002, tutorial overview, comparison with least squares, consistency and asymptotic distribution

Where this leads

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