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.
- Solves
- System identification
- 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
- Model
- Real RAM
- Properties
- deterministicexactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Kwan Y. Wong, Elijah Polak, 1967
Instrumental variable identification estimates the coefficients of the difference equation when the disturbance is colored, the case where least-squares ARX identification is biased. The bias comes from the past outputs in the regressor , which are correlated with . The method keeps but multiplies the equations by an instrument vector that is correlated with and uncorrelated with , and solves , a square linear system of size . 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 , 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 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 and taken in open loop, orders , , , and a choice of instruments: delayed or model.
Model. and , with regressor and . The disturbance may be any stationary process independent of ; it need not be white.
Instruments. The delayed instruments are . The model instruments are , where is the output of an auxiliary model simulated from rest, by default the least squares ARX fit.
Output. The solution of the IV equations
or a report that their matrix is singular.
The algorithm
IV-ARX(y, u, na, nb, nk, ⟨instruments⟩)- 1
d ← 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 - 2
R ← the d × d zero matrix; f ← the zero vector of length d - 3
for k ← k0 to N - 1 do - 4
φ ← (-y(k-1), ..., -y(k-na), u(k-nk), ..., u(k-nk-nb+1)); ζ ← the instrument vector at time k - 5
R ← R + ζ φᵀ - 6
f ← f + ζ · y(k) - 7
if R is singular then fail: the instruments are not correlated enough with φ - 8
θ ← the solution of R θ = f - 9
return θ
Line L1 chooses the first time at which both and stay inside the record; the delayed instruments reach back to , further than the regressor. For model instruments, L1 also runs least squares once and simulates the auxiliary model, using only , so contains no noise. Lines L3 to L6 add up the IV equations in one pass. Unlike the least squares matrix, is not symmetric and not positive semidefinite, so L8 needs a general solver such as Gaussian elimination with pivoting. With the loop is exactly the loop of least squares.
Example
Take and delayed instruments, so , and . The data are those of the least squares example,
| residual | |||||
|---|---|---|---|---|---|
| 2 | |||||
| 3 | |||||
| 4 | |||||
| 5 |
The loop of L3 to L6 gives
For example . The determinant is , so L7 passes, and L8 gives
The residuals are orthogonal to both instrument columns, and , but not to the column of ; least squares on one more equation of the same data gave .
Correctness
Claim. If is nonsingular, IV-ARX returns the unique solution of the IV equations. If moreover the data satisfy for , then ; in particular exactly for noise-free data, and whenever tends to a nonsingular matrix and .
Key invariant. After the pass of the loop for time , and .
With the invariant at , the IV equations read , and L8 solves them. Substituting into gives , 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 , , the orders , , , and . We work in exact real arithmetic, as in the real RAM. Let be the regressor and the instrument vector of line L4, and write
with and .
Lemma 1 (the vectors are defined). For every index used by and lies in .
Proof. The regressor uses for and for ; these are at least and . The delayed instruments use for , at least . The model instruments use the same indices as the regressor, into the simulated signal , which has the same length as . In each case L1 chooses as the largest of the shifts that occur, so every index is at least . Every index is at most .
Lemma 2 (loop invariant). After the pass of the loop of L3 for time , the variables hold and .
Proof. By induction on . Line L2 sets and . If and before the pass for , then L5 and L6 give and .
After the loop, and ; write them and .
Lemma 3 (the IV equations). A vector solves if and only if .
Proof. The left side equals .
Lemma 4 (the error formula). Suppose is nonsingular and, for some and some sequence , for every . Then the solution of is .
Proof. . Multiply by .
Theorem. If is nonsingular, IV-ARX returns the unique solution of the IV equations; if is singular, it stops at L7. Under the hypothesis of Lemma 4:
- if for all , then ;
- for a sequence of data sets with , if with nonsingular and , then .
Proof. By Lemma 1 every vector in the loop is well defined, and by Lemma 2 the loop leaves and . If is singular, L7 stops. Otherwise L8 computes the unique solution of , which by Lemma 3 is the unique solution of the IV equations, and L9 returns it.
(1) follows from Lemma 4 with .
(2) Write by Lemma 4. Matrix inversion is continuous on the open set of nonsingular matrices, so is nonsingular for all large and . The product of a convergent sequence of matrices and a sequence of vectors that tends to 0 tends to 0. Hence .
The hypotheses of (2) are where the instruments matter. In open loop with stationary, ergodic and independent of , and with built from only, the law of large numbers gives and with probability 1, so (2) holds whenever is nonsingular. With the first limit is , which is not 0 for colored , and this is the bias of least squares.
Complexity
Line L4 costs and lines L5 and L6 cost multiplications, so the loop costs . Line L8 costs by Gaussian elimination, which also detects the singular case of L7. For model instruments, L1 adds one least squares fit, , and one simulation, . The total is in the real RAM. The extra space is for and , plus for the simulated output 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 exactly.
- Consistent for colored noise (theorem). If the data come from in open loop with stationary and independent of , the instruments are built from only, and is nonsingular, then with probability 1 (Söderström and Stoica 1989; Ljung 1999, Chapter 8). No model of is needed.
- The nonsingularity condition (computation). For the delayed instruments with , and white unit-variance , the entries of are , or , where is the impulse response of , and the matrix is nonsingular exactly when . For and , and .
- Bias removed (measurement). For that system with ARMAX noise , a white input and , least squares gave , delayed IV gave and model IV gave , against the true .
- Variance depends on the instruments (measurement). Over 20 runs with , the estimate of had mean and standard deviation for least squares, and for delayed IV, and and 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 in a weighted least squares sense, which can lower the variance.
- Prefiltered and refined IV. Filter , and the instruments by a filter before L3. With 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 after every sample in as in the RLS algorithm, with in place of one of the two factors.
- Closed loop. In closed-loop identification, build the instruments from the external reference signal , which is independent of the noise, instead of from .
- Two-stage least squares. Regressing on the instruments and then 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 , or any vector with measured , in L4 brings back the correlation with and the bias of least squares. In L4 the instrument must be built from only, or from the simulated .
- A one-step predictor instead of a simulation. Computing in L1 from measured past outputs, , puts the noise into the instruments. L1 must simulate from rest, using its own past values.
- The start index of least squares. Starting the loop of L3 at with delayed instruments makes read before time 0; in Python a negative index silently reads the end of the record. For delayed instruments, L1 must use .
- Feedback in the data. In closed loop depends on past noise, so instruments from are correlated with and the estimate is biased. Build in L4 from the reference signal instead.
- A nearly singular . If the input is not persistently exciting of order or more, or if a computation like is close to 0, 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.
# 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
- 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)
- 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)
- 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
- 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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag YQN1Q7 Edit this page History Report an error Markdown