Algorithm Search⌘K

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.

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
Properties
deterministicnot exactofflineiterative
Origin
Karl Johan Åström, Torsten Bohlin, 1965

The prediction error method (PEM) estimates the parameters θ\theta of a dynamical model from measured inputs uu and outputs yy by choosing the θ\theta whose one-step-ahead predictions of the output are best. For each candidate θ\theta, the model gives a predictor y^(k∣θ)\hat y(k \mid \theta) built from the data before time kk; the method minimizes the mean of the squared prediction errors ε(k,θ)=y(k)−y^(k∣θ)\varepsilon(k, \theta) = y(k) - \hat y(k \mid \theta) 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 y(0),…,y(N−1)y(0), \ldots, y(N-1) and u(0),…,u(N−1)u(0), \ldots, u(N-1), and orders na,nc,nd,nf≥0n_a, n_c, n_d, n_f \ge 0, nb≥1n_b \ge 1, nk≥0n_k \ge 0 of the general linear model

A(q) y(k)=B(q)F(q) u(k)+C(q)D(q) e(k),A(q)\, y(k) = \frac{B(q)}{F(q)}\, u(k) + \frac{C(q)}{D(q)}\, e(k),

with A,C,D,FA, C, D, F monic polynomials in q−1q^{-1} and B(q)=q−nk(b1+⋯+bnbq−nb+1)B(q) = q^{-n_k}(b_1 + \cdots + b_{n_b} q^{-n_b+1}). ARX has nc=nd=nf=0n_c = n_d = n_f = 0, ARMAX has nd=nf=0n_d = n_f = 0, OE has na=nc=nd=0n_a = n_c = n_d = 0, and Box-Jenkins has na=0n_a = 0.

Predictor. With all signals taken as 0 before time 0,

w(k)=B(q)F(q) u(k),v(k)=A(q) y(k)−w(k),ε(k,θ)=D(q)C(q) v(k).w(k) = \frac{B(q)}{F(q)}\, u(k), \qquad v(k) = A(q)\, y(k) - w(k), \qquad \varepsilon(k, \theta) = \frac{D(q)}{C(q)}\, v(k).

Admissible set. θ=(a,b,c,d,f)∈Rd\theta = (a, b, c, d, f) \in \mathbb{R}^d with CC and FF Schur, so the filters 1/C1/C and 1/F1/F are BIBO stable.

Output. A local minimizer in the admissible set of

V(θ)=1N−n0∑k=n0N−1ε(k,θ)2,n0=max⁡(na,nk+nb−1,nc,nd,nf).V(\theta) = \frac{1}{N - n_0} \sum_{k=n_0}^{N-1} \varepsilon(k, \theta)^2, \qquad n_0 = \max(n_a, n_k + n_b - 1, n_c, n_d, n_f).

The algorithm

  1. PEM(y, u, orders, θ0)
  2. 1θ ← θ0, or the least squares ARX fit with c = d = 0 if no θ0 is given
  3. 2repeat
  4. 3compute ε(k, θ) and ψ(k, θ) = -∂ε(k, θ)/∂θ for k = n0, ..., N - 1 by filtering
  5. 4R ← Σ ψ(k) ψ(k)ᵀ; g ← Σ ψ(k) ε(k)
  6. 5δ ← the solution of R δ = g (fail if R is singular: the data are not informative)
  7. 6μ ← 1
  8. 7while C or F of θ + μ δ is not Schur, or V(θ + μ δ) ≥ V(θ), do μ ← μ/2 (stop after 40 halvings)
  9. 8θ ← θ + μ δ
  10. 9until the relative decrease of V is at most tol, or no step was accepted
  11. 10return θ and V(θ)

The gradient filters (L3). Differentiating the predictor equations gives, with ψ=−∂ε/∂θ\psi = -\partial \varepsilon / \partial \theta,

ψai=−DC y(k−i),ψbj=DCF u(k−nk−j+1),ψci=1C ε(k−i),ψdi=−1C v(k−i),ψfi=−DCF w(k−i).\psi_{a_i} = -\frac{D}{C}\, y(k-i), \quad \psi_{b_j} = \frac{D}{CF}\, u(k - n_k - j + 1), \quad \psi_{c_i} = \frac{1}{C}\, \varepsilon(k-i), \quad \psi_{d_i} = -\frac{1}{C}\, v(k-i), \quad \psi_{f_i} = -\frac{D}{CF}\, w(k-i).

So one pass of six filters gives all dd components. For ARMAX this reduces to ψ=φ(k,θ)/C\psi = \varphi(k, \theta)/C, the pseudo-regressor of past outputs, inputs and prediction errors filtered through 1/C1/C.

The step (L4, L5). The gradient of VV is −2N−n0g-\frac{2}{N - n_0} g, and 2N−n0R\frac{2}{N - n_0} R is the Gauss-Newton approximation of its Hessian, which drops the second derivatives of ε\varepsilon. So δ=R−1g\delta = R^{-1} g is the Gauss-Newton direction. RR is positive semidefinite, and it is nonsingular when the data are informative and the parametrization is identifiable at θ\theta.

The line search (L6, L7). The full step can leave the admissible set or raise VV far from the minimum. L7 halves the step until both CC and FF stay Schur and VV strictly decreases. The Schur test uses the roots of CC and FF, or the Schur-Cohn test.

Example

Data: the ARMAX system A=1−1.5q−1+0.7q−2A = 1 - 1.5 q^{-1} + 0.7 q^{-2}, B=q−1+0.5q−2B = q^{-1} + 0.5 q^{-2}, C=1−q−1+0.2q−2C = 1 - q^{-1} + 0.2 q^{-2}, with a white ±1\pm 1 input, white Gaussian ee of unit variance and N=2000N = 2000 samples (seed 1). The model has na=nb=nc=2n_a = n_b = n_c = 2 and nk=1n_k = 1, so d=6d = 6. L1 starts from the least squares ARX fit with c=0c = 0.

step a1a_1 a2a_2 b1b_1 b2b_2 c1c_1 c2c_2 VV
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 (−1.5,0.7,1,0.5,−1,0.2)(-1.5, 0.7, 1, 0.5, -1, 0.2), and the search stops after eight accepted steps. The final V=1.04079V = 1.04079 is below VV at the true parameters, 1.046751.04675, which equals the mean of e(k)2e(k)^2 over the samples: the minimizer fits the particular noise sequence slightly better than the truth does.

Correctness

Claim. PEM returns an admissible θ\theta with V(θ)≤V(θ0)V(\theta) \le V(\theta_0); every accepted step keeps CC and FF Schur and strictly lowers VV. If the search stops because no step lowers VV, then either g=0g = 0, so θ\theta is a stationary point of VV, or no step μδ\mu \delta with μ≥2−39\mu \ge 2^{-39} lowers VV. When ε\varepsilon is affine in θ\theta, as for ARX, the first step lands exactly on the least squares solution.

Key invariant. At the start of each pass of L2, θ\theta is admissible and V(θ)V(\theta) is at most every earlier value of VV. The vector ψ(k)\psi(k) of L3 is the exact negative gradient of ε(k,θ)\varepsilon(k, \theta) for the recursions from rest, so δ\delta is a descent direction whenever g≠0g \ne 0: ∇VTδ=−2N−n0 gTR−1g<0\nabla V^T \delta = -\frac{2}{N - n_0}\, g^T R^{-1} g < 0.

Since the admissible set is open and VV is differentiable on it, a small enough μ\mu 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 n0=max⁡(na,nk+nb−1,nc,nd,nf)n_0 = \max(n_a, n_k + n_b - 1, n_c, n_d, n_f), and write M=N−n0M = N - n_0. The admissible set Θ\Theta is the set of θ=(a,b,c,d,f)\theta = (a, b, c, d, f) for which CC and FF are Schur.

Signals as power series. Identify a signal x(0),x(1),…x(0), x(1), \ldots that is 0 before time 0 with the formal power series ∑kx(k) zk\sum_k x(k)\, z^k in a variable zz that stands for q−1q^{-1}. A polynomial P(q)=p0+p1q−1+⋯P(q) = p_0 + p_1 q^{-1} + \cdots acting on xx from rest is multiplication by P(z)P(z). For a monic PP, the recursion P(q) x′=xP(q)\, x' = x from rest, that is x′(k)=x(k)−∑i≥1pix′(k−i)x'(k) = x(k) - \sum_{i \ge 1} p_i x'(k-i) with x′(k)=0x'(k) = 0 for k<0k < 0, is multiplication by the power series 1/P(z)1/P(z), which exists because P(0)=1P(0) = 1. 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 NN coefficients of a product depend only on the first NN coefficients of the factors.

Lemma 1 (the gradient filters). For every θ\theta and every kk, the vector ψ(k,θ)\psi(k, \theta) computed by L3 equals −∂ε(k,θ)/∂θ-\partial \varepsilon(k, \theta)/\partial \theta.

Proof. In the ring of power series, w=(B/F) uw = (B/F)\, u, v=Ay−wv = A y - w and ε=(D/C) v\varepsilon = (D/C)\, v. The power series 1/C1/C and 1/F1/F have coefficients that are polynomials in cc and ff, so each ε(k,θ)\varepsilon(k, \theta) is a polynomial in θ\theta, and the product and quotient rules hold coefficientwise. Differentiate.

  • ∂A/∂ai=zi\partial A/\partial a_i = z^i, so ∂ε/∂ai=(D/C) ziy\partial \varepsilon/\partial a_i = (D/C)\, z^i y, the signal (D/C) y(D/C)\, y delayed by ii.
  • ∂B/∂bj=znk+j−1\partial B/\partial b_j = z^{n_k + j - 1}, so ∂w/∂bj=znk+j−1u/F\partial w/\partial b_j = z^{n_k + j - 1} u/F and ∂ε/∂bj=−(D/(CF)) znk+j−1u\partial \varepsilon/\partial b_j = -(D/(CF))\, z^{n_k + j - 1} u.
  • ∂(1/C)/∂ci=−zi/C2\partial (1/C)/\partial c_i = -z^i/C^2, so ∂ε/∂ci=−ziDv/C2=−(1/C) ziε\partial \varepsilon/\partial c_i = -z^i D v/C^2 = -(1/C)\, z^i \varepsilon.
  • ∂ε/∂di=(1/C) ziv\partial \varepsilon/\partial d_i = (1/C)\, z^i v.
  • ∂(1/F)/∂fi=−zi/F2\partial (1/F)/\partial f_i = -z^i/F^2, so ∂w/∂fi=−ziw/F\partial w/\partial f_i = -z^i w/F and ∂ε/∂fi=(D/(CF)) ziw\partial \varepsilon/\partial f_i = (D/(CF))\, z^i w.

Negating gives ψai=−zi(D/C)y\psi_{a_i} = -z^i (D/C) y, ψbj=znk+j−1(D/(CF))u\psi_{b_j} = z^{n_k+j-1} (D/(CF)) u, ψci=ziε/C\psi_{c_i} = z^i \varepsilon / C, ψdi=−ziv/C\psi_{d_i} = -z^i v/C and ψfi=−zi(D/(CF))w\psi_{f_i} = -z^i (D/(CF)) w, which are the filtered and delayed signals that L3 forms. □\square

Let g(θ)=∑k=n0N−1ψ(k,θ) ε(k,θ)g(\theta) = \sum_{k=n_0}^{N-1} \psi(k, \theta)\, \varepsilon(k, \theta) and R(θ)=∑k=n0N−1ψ(k,θ)ψ(k,θ)TR(\theta) = \sum_{k=n_0}^{N-1} \psi(k, \theta) \psi(k, \theta)^T, the quantities of L4.

Lemma 2 (the gradient of the criterion). VV is differentiable on Rd\mathbb{R}^d and ∇V(θ)=−2M g(θ)\nabla V(\theta) = -\frac{2}{M}\, g(\theta).

Proof. V=1M∑kε(k,θ)2V = \frac{1}{M} \sum_k \varepsilon(k, \theta)^2 is a polynomial in θ\theta by the proof of Lemma 1, and ∇V=2M∑kε ∂ε/∂θ=−2M∑kε ψ\nabla V = \frac{2}{M} \sum_k \varepsilon\, \partial\varepsilon/\partial\theta = -\frac{2}{M} \sum_k \varepsilon\, \psi. □\square

Lemma 3 (descent). Let θ∈Θ\theta \in \Theta, let R=R(θ)R = R(\theta) be nonsingular and let δ=R−1g(θ)\delta = R^{-1} g(\theta). If g(θ)≠0g(\theta) \ne 0, there is μˉ>0\bar\mu > 0 such that θ+μδ∈Θ\theta + \mu\delta \in \Theta and V(θ+μδ)<V(θ)V(\theta + \mu\delta) < V(\theta) for all 0<μ≤μˉ0 < \mu \le \bar\mu.

Proof. RR is a sum of matrices ψψT\psi\psi^T, so it is positive semidefinite, and being nonsingular it is positive definite; so is R−1R^{-1}. By Lemma 2, ∇V(θ)Tδ=−2M gTR−1g<0\nabla V(\theta)^T \delta = -\frac{2}{M}\, g^T R^{-1} g < 0. Since VV is differentiable, V(θ+μδ)=V(θ)+μ∇V(θ)Tδ+o(μ)V(\theta + \mu\delta) = V(\theta) + \mu \nabla V(\theta)^T \delta + o(\mu), which is below V(θ)V(\theta) for all small μ>0\mu > 0. The roots of a polynomial depend continuously on its coefficients, so the set where CC and FF are Schur is open, and θ+μδ∈Θ\theta + \mu\delta \in \Theta for all small μ\mu. Take μˉ\bar\mu as the smaller of the two bounds. □\square

Lemma 4 (one step for affine errors). Suppose ε(k,θ)=y(k)−φ(k)Tθ\varepsilon(k, \theta) = y(k) - \varphi(k)^T \theta for fixed vectors φ(k)\varphi(k), as in the ARX case (nc=nd=nf=0n_c = n_d = n_f = 0), and let R=∑φφTR = \sum \varphi \varphi^T be nonsingular. Then from any θ\theta, θ+δ\theta + \delta is the least squares solution θ∗=R−1∑φ(k) y(k)\theta^* = R^{-1} \sum \varphi(k)\, y(k).

Proof. Here ψ(k)=φ(k)\psi(k) = \varphi(k) for every θ\theta, so R(θ)=RR(\theta) = R and g(θ)=∑φ (y−φTθ)=Rθ∗−Rθg(\theta) = \sum \varphi\, (y - \varphi^T \theta) = R \theta^* - R \theta. Hence δ=θ∗−θ\delta = \theta^* - \theta and θ+δ=θ∗\theta + \delta = \theta^*. □\square

Theorem. Suppose the start θ0\theta_0 is admissible and every matrix RR met at L5 is nonsingular. Then:

  1. at the start of each pass of L2, θ∈Θ\theta \in \Theta, and the values of VV at the start of the passes strictly decrease;
  2. the returned θ\theta is admissible and V(θ)≤V(θ0)V(\theta) \le V(\theta_0);
  3. if the search ends because L7 accepts no step, then g(θ)=0g(\theta) = 0, so θ\theta is a stationary point of VV, or no μ∈{1,12,…,2−39}\mu \in \{1, \frac12, \ldots, 2^{-39}\} gives an admissible point with a lower VV;
  4. in the ARX case, if θ0≠θ∗\theta_0 \ne \theta^*, the first pass accepts μ=1\mu = 1 and moves to θ∗\theta^*, the unique minimizer of VV.

Proof. (1) By induction on the passes. Initially θ=θ0∈Θ\theta = \theta_0 \in \Theta. A pass changes θ\theta only at L8, and only to a point θ+μδ\theta + \mu\delta that the test of L7 has found admissible with V(θ+μδ)<V(θ)V(\theta + \mu\delta) < V(\theta). So the new θ\theta is admissible and its VV is strictly smaller. (2) follows from (1) because the returned θ\theta 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 μ\mu, then by the test in L7 none of them gives an admissible point with lower VV. If g(θ)≠0g(\theta) \ne 0, Lemma 3 guarantees such points for all small μ\mu, so this can happen only when all the tested μ\mu are larger than μˉ\bar\mu; otherwise g(θ)=0g(\theta) = 0 and ∇V(θ)=0\nabla V(\theta) = 0 by Lemma 2. (4) In the ARX case Θ=Rd\Theta = \mathbb{R}^d, since there is no CC or FF. By Lemma 4 the step with μ=1\mu = 1 reaches θ∗\theta^*, the unique minimizer of the convex quadratic VV when RR is nonsingular, so V(θ∗)<V(θ0)V(\theta^*) < V(\theta_0) when θ0≠θ∗\theta_0 \ne \theta^*, and L7 accepts μ=1\mu = 1 at once. ■\blacksquare

Complexity

L3 runs a fixed number of linear filters of order O(d)O(d) over the data, O(Nd)O(N d). L4 costs O(Nd2)O(N d^2), and L5 costs O(d3)O(d^3) by Gaussian elimination. Each trial of L7 costs O(Nd)O(N d) for VV and O(d3)O(d^3) for the roots of CC and FF, and there are at most 40 trials. One iteration is therefore O(Nd2+d3)O(N d^2 + d^3) in the real RAM, and II iterations cost O(I(Nd2+d3))O(I (N d^2 + d^3)). The extra space is O(Nd+d2)O(N d + d^2) for the filtered signals and RR. 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 VV 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 θ^N→θ0\hat\theta_N \to \theta_0 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 GG even when the noise model is wrong.
  • Asymptotically efficient (theorem). Under the same conditions N(θ^N−θ0)\sqrt{N}(\hat\theta_N - \theta_0) is asymptotically normal with covariance σ2(E ψψT)−1\sigma^2 (\mathbb{E}\, \psi \psi^T)^{-1}, and for Gaussian ee this equals the Cramér-Rao bound (Ljung 1999, Chapter 9). The matrix RR of L4 at the end gives the estimate σ^2R−1\hat\sigma^2 R^{-1} of the covariance of θ^\hat\theta.
  • Maximum likelihood (theorem). If ee 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 VV, so the minimizer of VV is the maximum likelihood estimate. With the variance unknown, maximizing over it gives the same θ\theta. 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 GG weighted by the input spectrum and the inverse noise model (Ljung 1999, Chapter 8).

Variants and improvements

  • Levenberg-Marquardt. Solve (R+λI) δ=g(R + \lambda I)\, \delta = g in L5 instead of halving the step; this handles a nearly singular RR.
  • 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 θ\theta and R−1R^{-1} at each sample with the current ψ\psi, as the RLS algorithm does for ARX, for online use.
  • Multivariable and state-space models. For several outputs, minimize det⁡∑εεT\det \sum \varepsilon \varepsilon^T; for innovations state-space models, the predictor is the steady-state Kalman filter.
  • Initial conditions. Estimate the initial state together with θ\theta, or use n0n_0 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 θ←θ+δ\theta \leftarrow \theta + \delta without testing CC and FF in L7 can give a CC with a root outside the unit circle; then ε\varepsilon grows without bound and the next RR is useless. L7 must halve μ\mu until CC and FF are Schur.
  • Steps that raise the criterion. Accepting the full Gauss-Newton step in L8 without the test V(θ+μδ)<V(θ)V(\theta + \mu\delta) < V(\theta) 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 φ(k,θ)\varphi(k, \theta) in place of ψ\psi in L3 gives the extended least squares method, which converges only under a positive real condition on 1/C1/C. L3 must filter through 1/C1/C, and through 1/F1/F for the bb and ff 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 FF taken from the autoregressive part when na=0n_a = 0.
  • Transients in the sum. Summing from k=0k = 0 in L4 when the system was not at rest adds start-up errors that do not shrink with θ\theta. Sum from n0n_0, 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.

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()
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

  1. 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)
  2. Torsten Söderström and Petre Stoica, System Identification, Prentice Hall, 1989, the chapter on prediction error methods
  3. 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
  4. 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.

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