Algorithmcore
Prediction error method
Also called PEM, prediction error identification.
Estimates model parameters by minimizing the sum of squared one-step prediction errors; for Gaussian white noise, with start-up effects ignored, this is maximum likelihood.
- Solves
- System identification
- Time
- O(I (N d^2 + d^3)) worst
- Space
- O(N d + d^2) extra
- Where
- I = the number of iterations; N = the number of samples; d = the number of parameters
- Model
- Real RAM
- Properties
- deterministicnot exactofflineiterative
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Karl Johan Åström, Torsten Bohlin, 1965
The prediction error method (PEM) estimates the parameters of a dynamical model from measured inputs and outputs by choosing the whose one-step-ahead predictions of the output are best. For each candidate , the model gives a predictor built from the data before time ; the method minimizes the mean of the squared prediction errors over the record. The idea covers every linear black-box structure, including the ARX, ARMAX, output error and Box-Jenkins models, and it also applies to state-space and nonlinear models. When the noise is Gaussian and white with a fixed variance and the start-up effects are ignored, the estimate is the maximum likelihood estimate. Except in the ARX case, the criterion is not convex, so it is minimized by a local search, most often a damped Gauss-Newton iteration from a least squares start.
In plain words
Take a model with some unknown numbers in it. For any choice of the numbers, the model can make a guess of the next output from everything measured so far. Compare each guess with what really came out, square the misses and average them. Good numbers give small misses. The method searches for the numbers that make the average miss smallest. It starts from a quick least squares answer and improves it step by step: at each step it works out which way to move each number, moves, and checks that the misses really got smaller before it keeps the move.
The problem
Input. Samples and , and orders , , of the general linear model
with monic polynomials in and . ARX has , ARMAX has , OE has , and Box-Jenkins has .
Predictor. With all signals taken as 0 before time 0,
Admissible set. with and Schur, so the filters and are BIBO stable.
Output. A local minimizer in the admissible set of
The algorithm
PEM(y, u, orders, θ0)- 1
θ ← θ0, or the least squares ARX fit with c = d = 0 if no θ0 is given - 2
repeat - 3
compute ε(k, θ) and ψ(k, θ) = -∂ε(k, θ)/∂θ for k = n0, ..., N - 1 by filtering - 4
R ← Σ ψ(k) ψ(k)ᵀ; g ← Σ ψ(k) ε(k) - 5
δ ← the solution of R δ = g (fail if R is singular: the data are not informative) - 6
μ ← 1 - 7
while C or F of θ + μ δ is not Schur, or V(θ + μ δ) ≥ V(θ), do μ ← μ/2 (stop after 40 halvings) - 8
θ ← θ + μ δ - 9
until the relative decrease of V is at most tol, or no step was accepted - 10
return θ and V(θ)
The gradient filters (L3). Differentiating the predictor equations gives, with ,
So one pass of six filters gives all components. For ARMAX this reduces to , the pseudo-regressor of past outputs, inputs and prediction errors filtered through .
The step (L4, L5). The gradient of is , and is the Gauss-Newton approximation of its Hessian, which drops the second derivatives of . So is the Gauss-Newton direction. is positive semidefinite, and it is nonsingular when the data are informative and the parametrization is identifiable at .
The line search (L6, L7). The full step can leave the admissible set or raise far from the minimum. L7 halves the step until both and stay Schur and strictly decreases. The Schur test uses the roots of and , or the Schur-Cohn test.
Example
Data: the ARMAX system , , , with a white input, white Gaussian of unit variance and samples (seed 1). The model has and , so . L1 starts from the least squares ARX fit with .
| step | |||||||
|---|---|---|---|---|---|---|---|
| 0 | -1.2639 | 0.4873 | 1.0498 | 0.7262 | 0 | 0 | 1.80043 |
| 1 | -1.4436 | 0.6338 | 1.0413 | 0.5290 | -0.4280 | -0.1328 | 1.34242 |
| 2 | -1.5081 | 0.7001 | 1.0325 | 0.4461 | -0.7097 | -0.0954 | 1.13271 |
| 3 | -1.5070 | 0.7089 | 1.0368 | 0.4711 | -0.9414 | 0.1496 | 1.04266 |
| 4 | -1.5130 | 0.7130 | 1.0328 | 0.4597 | -0.9792 | 0.1876 | 1.04079 |
| final | -1.5129 | 0.7130 | 1.0326 | 0.4604 | -0.9801 | 0.1883 | 1.04079 |
The start is the biased ARX estimate. After four steps the estimate is within a few hundredths of the true , and the search stops after eight accepted steps. The final is below at the true parameters, , which equals the mean of over the samples: the minimizer fits the particular noise sequence slightly better than the truth does.
Correctness
Claim. PEM returns an admissible with ; every accepted step keeps and Schur and strictly lowers . If the search stops because no step lowers , then either , so is a stationary point of , or no step with lowers . When is affine in , as for ARX, the first step lands exactly on the least squares solution.
Key invariant. At the start of each pass of L2, is admissible and is at most every earlier value of . The vector of L3 is the exact negative gradient of for the recursions from rest, so is a descent direction whenever : .
Since the admissible set is open and is differentiable on it, a small enough gives a strict decrease, which is what L7 searches for. The full proof is below.
Proof: PEM is a descent method on the prediction error criterion, exact in one step for ARXfull
We work in exact real arithmetic, as in the real RAM. Fix the data, the orders and , and write . The admissible set is the set of for which and are Schur.
Signals as power series. Identify a signal that is 0 before time 0 with the formal power series in a variable that stands for . A polynomial acting on from rest is multiplication by . For a monic , the recursion from rest, that is with for , is multiplication by the power series , which exists because . Formal power series form a commutative ring, so all these filters commute and obey the usual rules of algebra. This is exact for finite data: the first coefficients of a product depend only on the first coefficients of the factors.
Lemma 1 (the gradient filters). For every and every , the vector computed by L3 equals .
Proof. In the ring of power series, , and . The power series and have coefficients that are polynomials in and , so each is a polynomial in , and the product and quotient rules hold coefficientwise. Differentiate.
- , so , the signal delayed by .
- , so and .
- , so .
- .
- , so and .
Negating gives , , , and , which are the filtered and delayed signals that L3 forms.
Let and , the quantities of L4.
Lemma 2 (the gradient of the criterion). is differentiable on and .
Proof. is a polynomial in by the proof of Lemma 1, and .
Lemma 3 (descent). Let , let be nonsingular and let . If , there is such that and for all .
Proof. is a sum of matrices , so it is positive semidefinite, and being nonsingular it is positive definite; so is . By Lemma 2, . Since is differentiable, , which is below for all small . The roots of a polynomial depend continuously on its coefficients, so the set where and are Schur is open, and for all small . Take as the smaller of the two bounds.
Lemma 4 (one step for affine errors). Suppose for fixed vectors , as in the ARX case (), and let be nonsingular. Then from any , is the least squares solution .
Proof. Here for every , so and . Hence and .
Theorem. Suppose the start is admissible and every matrix met at L5 is nonsingular. Then:
- at the start of each pass of L2, , and the values of at the start of the passes strictly decrease;
- the returned is admissible and ;
- if the search ends because L7 accepts no step, then , so is a stationary point of , or no gives an admissible point with a lower ;
- in the ARX case, if , the first pass accepts and moves to , the unique minimizer of .
Proof. (1) By induction on the passes. Initially . A pass changes only at L8, and only to a point that the test of L7 has found admissible with . So the new is admissible and its is strictly smaller. (2) follows from (1) because the returned is the last value of the induction, and the loop ends after a finite number of passes. (3) If L7 rejects all 40 values of , then by the test in L7 none of them gives an admissible point with lower . If , Lemma 3 guarantees such points for all small , so this can happen only when all the tested are larger than ; otherwise and by Lemma 2. (4) In the ARX case , since there is no or . By Lemma 4 the step with reaches , the unique minimizer of the convex quadratic when is nonsingular, so when , and L7 accepts at once.
Complexity
L3 runs a fixed number of linear filters of order over the data, . L4 costs , and L5 costs by Gaussian elimination. Each trial of L7 costs for and for the roots of and , and there are at most 40 trials. One iteration is therefore in the real RAM, and iterations cost . The extra space is for the filtered signals and . The number of iterations has no general bound. Near a minimum with small residuals Gauss-Newton converges fast; in the example eight steps were enough.
Properties
- Local, not global. For ARMAX, OE and Box-Jenkins structures is not convex, and the search finds a local minimum near the start. For ARX it is convex and one step suffices.
- Consistent (theorem). If the model set contains the true system, the data are informative, and the global minimizer is found, then with probability 1 (Ljung 1999, Chapter 8). In open loop, structures with an independent noise model, such as OE and Box-Jenkins, give a consistent even when the noise model is wrong.
- Asymptotically efficient (theorem). Under the same conditions is asymptotically normal with covariance , and for Gaussian this equals the Cramér-Rao bound (Ljung 1999, Chapter 9). The matrix of L4 at the end gives the estimate of the covariance of .
- Maximum likelihood (theorem). If is Gaussian and white with a fixed variance, and the start-up effect of the zero initial conditions is ignored, then the log-likelihood is a decreasing function of , so the minimizer of is the maximum likelihood estimate. With the variance unknown, maximizing over it gives the same . Without these conditions, PEM is still defined, but it is not the likelihood.
- Approximation (theorem). When the true system is not in the model set, the estimate converges to the minimizer of the limit criterion, which in the frequency domain is a fit of weighted by the input spectrum and the inverse noise model (Ljung 1999, Chapter 8).
Variants and improvements
- Levenberg-Marquardt. Solve in L5 instead of halving the step; this handles a nearly singular .
- Quasi-Newton. BFGS and other quasi-Newton methods use the exact gradient of L3 and build up curvature, which helps when the residuals are large.
- Recursive prediction error method. Update and at each sample with the current , as the RLS algorithm does for ARX, for online use.
- Multivariable and state-space models. For several outputs, minimize ; for innovations state-space models, the predictor is the steady-state Kalman filter.
- Initial conditions. Estimate the initial state together with , or use large enough to let the transient die out, instead of the zero start.
- Frequency-domain PEM. Weight the squared errors of the discrete Fourier transforms, which allows prefiltering and band selection.
- Better starts. Instrumental variable estimates or high-order ARX fits followed by model reduction lower the risk of a bad local minimum.
When to use it
Use it when an accurate low-order model with a noise model is wanted, after a quick least squares fit has given a start value. It is the method of choice for ARMAX, OE and Box-Jenkins structures in open loop, and the direct method in closed-loop identification when the noise model can be made correct. If only a quick answer is needed or the noise is close to white equation error, least squares may be enough; if the criterion has bad local minima, start from an instrumental variable estimate.
Pitfalls
- Unstable predictor filters. Taking without testing and in L7 can give a with a root outside the unit circle; then grows without bound and the next is useless. L7 must halve until and are Schur.
- Steps that raise the criterion. Accepting the full Gauss-Newton step in L8 without the test of L7 can diverge when the start is far from the minimum. Keep the strict decrease test.
- The pseudo-linear shortcut. Using the unfiltered pseudo-regressor in place of in L3 gives the extended least squares method, which converges only under a positive real condition on . L3 must filter through , and through for the and components.
- A poor start. A zero start in L1 for an OE model can lead to a local minimum far from the truth. L1 should start from a least squares or instrumental variable estimate, with taken from the autoregressive part when .
- Transients in the sum. Summing from in L4 when the system was not at rest adds start-up errors that do not shrink with . Sum from , and estimate the initial state if the transient is long.
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()
prediction_error_method.py 225 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/prediction-error-method/. The authors are listed in prov/R82NR4.jsonl.
"""Prediction error method for the general linear black-box model.
The model is
A(q) y(t) = (B(q) / F(q)) u(t) + (C(q) / D(q)) e(t)
with A = 1 + a_1 q^-1 + ... + a_na q^-na, and the same form for C, D and F.
B(q) = b_1 q^-nk + ... + b_nb q^-(nk+nb-1). ARX, ARMAX, OE and Box-Jenkins
are the special cases with some orders set to 0.
The one step ahead prediction error is
eps(t) = (D / C) (A y(t) - (B / F) u(t)),
computed from rest (all signals 0 before t = 0). pem minimizes
V = (1/M) sum of eps(t)^2 over t = n0, ..., N-1, n0 = max(na, nk + nb - 1,
nc, nd, nf), by damped Gauss-Newton steps. C and F are kept Schur (all zeros
strictly inside the unit circle), so the filters stay bounded.
Precondition: nb >= 1, nk >= 0, the other orders >= 0, len(y) == len(u) and
the data are informative for the model. The start value must have C and F
Schur. The result is a local minimum of V; V need not be convex.
Cost per iteration: O(N d) to filter the data and O(N d^2 + d^3) for the
Gauss-Newton step, d = na + nb + nc + nd + nf, in the real RAM.
"""
from typing import Optional, Sequence
from ctlmat import polymul, polyroots, solve
def _filter(num: Sequence, den: Sequence, x: Sequence) -> list:
"""Return (num(q^-1) / den(q^-1)) x from rest; den[0] must be 1."""
out = []
for t in range(len(x)):
s = 0.0
for i, c in enumerate(num):
if t - i < 0:
break
s += c * x[t - i]
for i in range(1, len(den)):
if t - i < 0:
break
s -= den[i] * out[t - i]
out.append(s)
return out
def _lag(x: Sequence, k: int, t: int) -> float:
return x[t - k] if t - k >= 0 else 0.0
def is_schur(poly: Sequence) -> bool:
"""True if every zero of 1 + p_1 z^-1 + ... + p_n z^-n has modulus < 1."""
if len(poly) <= 1:
return True
return all(abs(r) < 1.0 for r in polyroots(list(poly)))
def _split(theta: Sequence, na: int, nb: int, nc: int, nd: int, nf: int):
i = 0
parts = []
for n in (na, nb, nc, nd, nf):
parts.append(list(theta[i:i + n]))
i += n
return parts
def prediction_errors(theta: Sequence, y: Sequence, u: Sequence, na: int, nb: int,
nc: int = 0, nd: int = 0, nf: int = 0, nk: int = 1):
"""Return (eps, w, v) for the parameter vector theta = (a, b, c, d, f).
w = (B / F) u is the noise-free model output, v = A y - w and
eps = (D / C) v is the prediction error.
"""
a, b, c, d, f = _split(theta, na, nb, nc, nd, nf)
apol, cpol, dpol, fpol = [1.0] + a, [1.0] + c, [1.0] + d, [1.0] + f
bpol = [0.0] * nk + b
w = _filter(bpol, fpol, u)
ay = _filter(apol, [1.0], y)
v = [p - q for p, q in zip(ay, w)]
eps = _filter(dpol, cpol, v)
return eps, w, v
def _gradients(theta, y, u, eps, w, v, na, nb, nc, nd, nf, nk):
"""Return the filtered signals that give psi(t) = -d eps(t) / d theta."""
_, _, c, d, f = _split(theta, na, nb, nc, nd, nf)
cpol, dpol, fpol = [1.0] + c, [1.0] + d, [1.0] + f
cf = polymul(cpol, fpol)
yf = _filter(dpol, cpol, y)
uf = _filter(dpol, cf, u)
wf = _filter(dpol, cf, w)
ef = _filter([1.0], cpol, eps)
vf = _filter([1.0], cpol, v)
return yf, uf, wf, ef, vf
def _psi(t, sig, na, nb, nc, nd, nf, nk):
yf, uf, wf, ef, vf = sig
return ([-_lag(yf, k, t) for k in range(1, na + 1)]
+ [_lag(uf, nk + k, t) for k in range(nb)]
+ [_lag(ef, k, t) for k in range(1, nc + 1)]
+ [-_lag(vf, k, t) for k in range(1, nd + 1)]
+ [-_lag(wf, k, t) for k in range(1, nf + 1)])
def first_sample(na: int, nb: int, nc: int, nd: int, nf: int, nk: int) -> int:
"""Return n0, the first sample used in the cost."""
return max(na, nk + nb - 1, nc, nd, nf)
def pem_loss(theta: Sequence, y: Sequence, u: Sequence, na: int, nb: int,
nc: int = 0, nd: int = 0, nf: int = 0, nk: int = 1) -> float:
"""Return V(theta) = mean of eps(t)^2 over t >= n0."""
eps, _, _ = prediction_errors(theta, y, u, na, nb, nc, nd, nf, nk)
n0 = first_sample(na, nb, nc, nd, nf, nk)
return sum(e * e for e in eps[n0:]) / (len(eps) - n0)
def _arx_start(y, u, na, nb, nc, nd, nf, nk):
"""Start value from a least squares ARX fit; c = d = 0."""
n_ar = na if na > 0 else nf
n0 = max(n_ar, nk + nb - 1)
p = n_ar + nb
r = [[0.0] * p for _ in range(p)]
g = [0.0] * p
for t in range(n0, len(y)):
phi = [-y[t - i] for i in range(1, n_ar + 1)] + [u[t - nk - j] for j in range(nb)]
for i in range(p):
for j in range(p):
r[i][j] += phi[i] * phi[j]
g[i] += phi[i] * y[t]
est = solve(r, g)
ar, bb = est[:n_ar], est[n_ar:]
a = ar if na > 0 else []
f = ar if na == 0 else [0.0] * nf
if nf > 0 and not is_schur([1.0] + f):
f = [0.0] * nf
return a + bb + [0.0] * nc + [0.0] * nd + f
def pem(y: Sequence, u: Sequence, na: int, nb: int, nc: int = 0, nd: int = 0,
nf: int = 0, nk: int = 1, theta0: Optional[Sequence] = None,
maxiter: int = 100, tol: float = 1e-12) -> dict:
"""Minimize the prediction error cost by damped Gauss-Newton.
Returns a dict with the polynomials "a", "b", "c", "d", "f" (without the
leading 1), the vector "theta", the cost "loss" and the number of
accepted steps "iterations". Raises ValueError if the Gauss-Newton matrix
is singular (the data are not informative) or theta0 is not admissible.
"""
if nb < 1 or min(na, nc, nd, nf, nk) < 0:
raise ValueError("need nb >= 1 and all other orders >= 0")
if len(y) != len(u):
raise ValueError("y and u must have the same length")
dim = na + nb + nc + nd + nf
n0 = first_sample(na, nb, nc, nd, nf, nk)
if len(y) - n0 <= dim:
raise ValueError("too few samples for the model orders")
if theta0 is None:
theta = _arx_start(y, u, na, nb, nc, nd, nf, nk) # @line L1
else:
theta = [float(v) for v in theta0]
if len(theta) != dim:
raise ValueError("theta0 has the wrong length")
def admissible(th):
_, _, c, _, f = _split(th, na, nb, nc, nd, nf)
return is_schur([1.0] + c) and is_schur([1.0] + f)
if not admissible(theta):
raise ValueError("start value must have C and F Schur")
loss = pem_loss(theta, y, u, na, nb, nc, nd, nf, nk)
steps = 0
for _ in range(maxiter): # @line L2
eps, w, v = prediction_errors(theta, y, u, na, nb, nc, nd, nf, nk) # @line L3
sig = _gradients(theta, y, u, eps, w, v, na, nb, nc, nd, nf, nk)
r = [[0.0] * dim for _ in range(dim)]
g = [0.0] * dim
for t in range(n0, len(y)):
psi = _psi(t, sig, na, nb, nc, nd, nf, nk)
for i in range(dim):
pi = psi[i]
row = r[i]
for j in range(dim):
row[j] += pi * psi[j] # @line L4
g[i] += pi * eps[t]
try:
delta = solve(r, g) # @line L5
except ValueError:
raise ValueError("Gauss-Newton matrix is singular: the data are not informative") from None
mu = 1.0 # @line L6
accepted = False
for _ in range(40):
cand = [th + mu * dl for th, dl in zip(theta, delta)]
if admissible(cand):
new_loss = pem_loss(cand, y, u, na, nb, nc, nd, nf, nk)
if new_loss < loss:
accepted = True
break
mu /= 2.0 # @line L7
if not accepted:
break
theta = cand # @line L8
old, loss = loss, new_loss
steps += 1
if old - loss <= tol * old: # @line L9
break
a, b, c, d, f = _split(theta, na, nb, nc, nd, nf)
return {"a": a, "b": b, "c": c, "d": d, "f": f, "theta": theta,
"loss": loss, "iterations": steps} # @line L10
def simulate_general(a: Sequence, b: Sequence, c: Sequence, d: Sequence, f: Sequence,
nk: int, u: Sequence, e: Sequence) -> list:
"""Return y with A y = (B / F) u + (C / D) e, from rest."""
w = _filter([0.0] * nk + list(b), [1.0] + list(f), u)
n = _filter([1.0] + list(c), [1.0] + list(d), e)
s = [p + q for p, q in zip(w, n)]
return _filter([1.0], [1.0] + list(a), s)
test_prediction_error_method.py 152 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/prediction-error-method/. The authors are listed in prov/R82NR4.jsonl.
import random
from prediction_error_method import (_gradients, _psi, first_sample, is_schur, pem, pem_loss,
prediction_errors, simulate_general)
A_TRUE = [-1.5, 0.7]
B_TRUE = [1.0, 0.5]
C_TRUE = [-1.0, 0.2]
def _data(n, seed, c=(), f=None):
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)]
if f is None:
y = simulate_general(A_TRUE, B_TRUE, list(c), [], [], 1, u, e)
else:
y = simulate_general([], B_TRUE, [], [], f, 1, u, e)
return y, u, e
def test_worked_example_armax():
y, u, e = _data(2000, 1, c=C_TRUE)
r = pem(y, u, 2, 2, nc=2)
want = [-1.5129, 0.7130, 1.0326, 0.4604, -0.9801, 0.1883]
assert all(abs(p - q) < 2e-4 for p, q in zip(r["theta"], want))
assert abs(r["loss"] - 1.04079) < 1e-4
true_loss = pem_loss(A_TRUE + B_TRUE + C_TRUE, y, u, 2, 2, 2)
assert r["loss"] <= true_loss
assert is_schur([1.0] + r["c"])
def _det(m):
if len(m) == 1:
return m[0][0]
return sum((-1) ** j * m[0][j] * _det([row[:j] + row[j + 1:] for row in m[1:]]) for j in range(len(m)))
def _ls_oracle(y, u, na, nb, nk):
# Normal equations solved by Cramer's rule.
d = na + nb
r = [[0.0] * d for _ in range(d)]
g = [0.0] * d
for t in range(max(na, nk + nb - 1), len(y)):
phi = [-y[t - i] for i in range(1, na + 1)] + [u[t - nk - j] for j in range(nb)]
for i in range(d):
g[i] += phi[i] * y[t]
for j in range(d):
r[i][j] += phi[i] * phi[j]
dr = _det(r)
out = []
for k in range(d):
m = [row[:k] + [g[i]] + row[k + 1:] for i, row in enumerate(r)]
out.append(_det(m) / dr)
return out, dr
def test_random_arx_case_is_least_squares():
# For ARX the prediction error is linear in theta, so one Gauss-Newton
# step from any start gives the least squares solution.
rng = random.Random(7)
done = 0
while done < 500:
na = rng.randint(0, 1)
nb = rng.randint(1, 2)
nk = rng.randint(0, 1)
n = rng.randint(15, 30)
u = [rng.uniform(-1, 1) for _ in range(n)]
y = [rng.uniform(-1, 1) for _ in range(n)]
want, dr = _ls_oracle(y, u, na, nb, nk)
if abs(dr) < 1e-3:
continue
theta0 = [rng.uniform(-2, 2) for _ in range(na + nb)]
r = pem(y, u, na, nb, nk=nk, theta0=theta0)
assert r["iterations"] >= 1
assert all(abs(p - q) < 1e-8 for p, q in zip(r["theta"], want))
done += 1
def test_output_error_noise_free_is_exact():
rng = random.Random(3)
u = [rng.choice((-1.0, 1.0)) for _ in range(300)]
y = simulate_general([], B_TRUE, [], [], A_TRUE, 1, u, [0.0] * 300)
r = pem(y, u, 0, 2, nf=2)
assert all(abs(p - q) < 1e-6 for p, q in zip(r["b"] + r["f"], B_TRUE + A_TRUE))
assert r["loss"] < 1e-12
def test_output_error_consistent_with_colored_noise():
# OE data with an output error that is not white still gives G.
rng = random.Random(9)
n = 3000
u = [rng.choice((-1.0, 1.0)) for _ in range(n)]
e = [rng.gauss(0.0, 1.0) for _ in range(n)]
w = simulate_general([], B_TRUE, [], [], A_TRUE, 1, u, [0.0] * n)
col = [e[t] + 0.9 * (e[t - 1] if t else 0.0) for t in range(n)]
y = [p + q for p, q in zip(w, col)]
r = pem(y, u, 0, 2, nf=2)
assert all(abs(p - q) < 0.08 for p, q in zip(r["b"] + r["f"], B_TRUE + A_TRUE))
def test_gradient_matches_finite_differences():
rng = random.Random(5)
n = 60
u = [rng.uniform(-1, 1) for _ in range(n)]
y = [rng.uniform(-1, 1) for _ in range(n)]
na, nb, nc, nd, nf, nk = 1, 2, 1, 1, 1, 1
theta = [0.3, 0.8, -0.4, 0.5, -0.2, 0.6]
eps, w, v = prediction_errors(theta, y, u, na, nb, nc, nd, nf, nk)
sig = _gradients(theta, y, u, eps, w, v, na, nb, nc, nd, nf, nk)
h = 1e-6
for i in range(len(theta)):
tp = list(theta)
tm = list(theta)
tp[i] += h
tm[i] -= h
ep, _, _ = prediction_errors(tp, y, u, na, nb, nc, nd, nf, nk)
em, _, _ = prediction_errors(tm, y, u, na, nb, nc, nd, nf, nk)
for t in range(first_sample(na, nb, nc, nd, nf, nk), n):
fd = -(ep[t] - em[t]) / (2 * h)
assert abs(_psi(t, sig, na, nb, nc, nd, nf, nk)[i] - fd) < 1e-6
def test_cost_does_not_increase():
y, u, _ = _data(800, 2, c=C_TRUE)
losses = [pem(y, u, 2, 2, nc=2, maxiter=k)["loss"] for k in range(6)]
assert all(b <= a for a, b in zip(losses, losses[1:]))
def test_bad_arguments():
y, u, _ = _data(50, 4)
for kwargs in ({"na": 1, "nb": 0}, {"na": -1, "nb": 1}):
try:
pem(y, u, **kwargs)
except ValueError:
continue
raise AssertionError("expected ValueError")
try:
pem(y, u, 1, 1, nc=1, theta0=[0.0, 1.0, 2.0])
except ValueError:
pass
else:
raise AssertionError("expected ValueError for a C that is not Schur")
try:
pem([1.0] * 50, [1.0] * 50, 0, 2)
except ValueError:
pass
else:
raise AssertionError("expected ValueError for a constant input")
History
Åström and Bohlin fitted ARMAX models to normal operating records by maximum likelihood in 1965, with a numerical search on the sum of squared residuals of the predictor. In the 1970s Ljung showed that the same criterion makes sense for any model structure that defines a predictor, gave convergence results that do not assume the true system is in the model set (1978), and made the prediction error framework the basis of his textbook of 1987 and its second edition of 1999.
References
- Lennart Ljung, System Identification: Theory for the User, second edition, Prentice Hall, 1999, Chapter 7 (prediction error methods and their relation to maximum likelihood), Chapter 8 (convergence and consistency), Chapter 9 (asymptotic distribution) and Chapter 10 (computing the estimate: Gauss-Newton search and the gradient filters)
- Torsten Söderström and Petre Stoica, System Identification, Prentice Hall, 1989, the chapter on prediction error methods
- Lennart Ljung, Convergence analysis of parametric identification methods, IEEE Transactions on Automatic Control 23(5), 770-783, 1978, the convergence of prediction error estimates for general model structures
- Karl Johan Åström and Torsten Bohlin, Numerical identification of linear dynamic systems from normal operating records, IFAC Symposium on Self-Adaptive Systems, Teddington, 1965; in P. H. Hammond (editor), Theory of Self-Adaptive Control Systems, Plenum Press, 1966, pp. 96-111, the maximum likelihood fit of ARMAX models by a numerical search
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 R82NR4 Edit this page History Report an error Markdown