Algorithm Search⌘K

Algorithmcore

Least-squares identification of ARX models

Also called equation error method, linear regression identification.

Estimates ARX parameters by linear least squares on the regression of each output on past outputs and inputs.

Time
O(N d^2 + d^3) worst
Space
O(d^2) extra
Where
N = the number of samples; d = the number of parameters
Properties
deterministicexactofflineiterative
Origin
Rudolf E. Kalman, 1958

Least-squares identification of ARX models fits the coefficients of the difference equation y(k)+a1y(k−1)+⋯+anay(k−na)=b1u(k−nk)+⋯+bnbu(k−nk−nb+1)+e(k)y(k) + a_1 y(k-1) + \cdots + a_{n_a} y(k-n_a) = b_1 u(k-n_k) + \cdots + b_{n_b} u(k-n_k-n_b+1) + e(k) to measured input and output data. The ARX model says that each output is a linear function of a few past outputs and inputs plus a white error, so the coefficients that best predict the data one step ahead solve an ordinary least squares problem. The algorithm builds the d×dd \times d normal matrix of the regressors, with d=na+nbd = n_a + n_b, in one pass over the NN samples, and solves one linear system: O(Nd2+d3)O(N d^2 + d^3) operations. It returns the exact global minimizer of the sum of squared equation errors whenever the data make that minimizer unique. When the true noise is not white, the minimizer is a biased estimate of the system.

In plain words

Guess that the next output of the system is a weighted sum of the last few outputs and the last few inputs. For every time step you can then write one equation that says "this output equals that weighted sum, plus a small error". There are many more equations than unknown weights, so they cannot all hold exactly. Least squares picks the weights that make the sum of the squared errors as small as possible. The work is to add up a small table of products of past values, once for each time step, and then to solve one small system of equations.

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≥0n_a \ge 0, nb≥1n_b \ge 1, nk≥0n_k \ge 0.

Regressor. For k≥k0=max⁡(na,nk+nb−1)k \ge k_0 = \max(n_a, n_k + n_b - 1) every past value below is inside the data:

φ(k)=(−y(k−1),…,−y(k−na), u(k−nk),…,u(k−nk−nb+1))T.\varphi(k) = \big(-y(k-1), \ldots, -y(k-n_a),\ u(k-n_k), \ldots, u(k-n_k-n_b+1)\big)^T.

Output. The θ=(a1,…,ana,b1,…,bnb)\theta = (a_1, \ldots, a_{n_a}, b_1, \ldots, b_{n_b}) that minimizes

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

or a report that the minimizer is not unique.

The algorithm

  1. ARX-LS(y, u, na, nb, nk)
  2. 1k0 ← max(na, nk + nb - 1); d ← na + nb
  3. 2R ← the d × d zero matrix; f ← the zero vector of length d
  4. 3for k ← k0 to N - 1 do
  5. 4φ ← (-y(k-1), ..., -y(k-na), u(k-nk), ..., u(k-nk-nb+1))
  6. 5R ← R + φ φᵀ
  7. 6f ← f + φ · y(k)
  8. 7if R is singular then fail: the data are not informative for this model
  9. 8θ ← the solution of R θ = f
  10. 9return θ

Line L1 skips the first samples, whose regressors would reach before the start of the record. Lines L3 to L6 add up the normal equations one sample at a time, so the data are read once and the regressors are never stored. RR is symmetric, so only its upper triangle needs to be formed. Line L7 is the case where the minimizer is not unique: then some nonzero direction mm has φ(k)Tm=0\varphi(k)^T m = 0 for every sample, and θ+t m\theta + t\, m fits equally well for every tt. Line L8 solves the normal equations Rθ=fR \theta = f, the condition for a zero gradient of VV.

Example

Take na=nb=nk=1n_a = n_b = n_k = 1, so the model is y(k)+a y(k−1)=b u(k−1)+e(k)y(k) + a\, y(k-1) = b\, u(k-1) + e(k) and φ(k)=(−y(k−1),u(k−1))\varphi(k) = (-y(k-1), u(k-1)). The data are

u=(1,1,−1,1,−1,−1),y=(0,1,1.4,−0.2,0.9,−0.6).u = (1, 1, -1, 1, -1, -1), \qquad y = (0, 1, 1.4, -0.2, 0.9, -0.6).

Line L1 gives k0=1k_0 = 1, so there are five equations, k=1,…,5k = 1, \ldots, 5.

kk φ(k)\varphi(k) y(k)y(k) φ(k)Tθ^\varphi(k)^T \hat\theta residual
1 (0,1)(0, 1) 11 0.96550.9655 0.03450.0345
2 (−1,1)(-1, 1) 1.41.4 1.45071.4507 −0.0507-0.0507
3 (−1.4,−1)(-1.4, -1) −0.2-0.2 −0.2864-0.2864 0.08640.0864
4 (0.2,1)(0.2, 1) 0.90.9 0.86850.8685 0.03150.0315
5 (−0.9,−1)(-0.9, -1) −0.6-0.6 −0.5289-0.5289 −0.0711-0.0711

The loop of L3 to L6 gives

R=(3.811.51.55),f=(−0.44.1).R = \begin{pmatrix} 3.81 & 1.5 \\ 1.5 & 5 \end{pmatrix}, \qquad f = \begin{pmatrix} -0.4 \\ 4.1 \end{pmatrix}.

For example R11=0+1+1.96+0.04+0.81=3.81R_{11} = 0 + 1 + 1.96 + 0.04 + 0.81 = 3.81 and f2=1+1.4+0.2+0.9+0.6=4.1f_2 = 1 + 1.4 + 0.2 + 0.9 + 0.6 = 4.1. The determinant is 3.81⋅5−1.52=16.83.81 \cdot 5 - 1.5^2 = 16.8, so L7 passes, and L8 gives

a^=5⋅(−0.4)−1.5⋅4.116.8=−163336≈−0.4851,b^=3.81⋅4.1−1.5⋅(−0.4)16.8=54075600≈0.9655.\hat a = \frac{5 \cdot (-0.4) - 1.5 \cdot 4.1}{16.8} = -\frac{163}{336} \approx -0.4851, \qquad \hat b = \frac{3.81 \cdot 4.1 - 1.5 \cdot (-0.4)}{16.8} = \frac{5407}{5600} \approx 0.9655.

The residual column of the table sums in squares to V(θ^)=2899/168000≈0.017256V(\hat\theta) = 2899/168000 \approx 0.017256, and it is orthogonal to both columns of φ\varphi, as the normal equations require.

Correctness

Claim. If R=∑k≥k0φ(k)φ(k)TR = \sum_{k \ge k_0} \varphi(k) \varphi(k)^T is nonsingular, ARX-LS returns the unique minimizer of VV. If RR is singular, VV has infinitely many minimizers and ARX-LS reports this at L7.

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

With the invariant at k=N−1k = N - 1, V(θ)=θTRθ−2fTθ+∑y(k)2V(\theta) = \theta^T R \theta - 2 f^T \theta + \sum y(k)^2. This is a convex quadratic whose gradient vanishes exactly on the solutions of Rθ=fR \theta = f, and RR is positive semidefinite, so it is positive definite when it is nonsingular. The full proof is below.

Proof: ARX-LS returns the unique minimizer of the sum of squared equation errorsfull

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

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

with Rk0−1=0R_{k_0 - 1} = 0 and fk0−1=0f_{k_0 - 1} = 0, and V(θ)=∑k=k0N−1(y(k)−φ(k)Tθ)2V(\theta) = \sum_{k=k_0}^{N-1} \big(y(k) - \varphi(k)^T \theta\big)^2.

Lemma 1 (the regressor is defined). For k≥k0k \ge k_0 every index used by L4 lies in {0,…,N−1}\{0, \ldots, N-1\}.

Proof. The output terms use k−ik - i for 1≤i≤na1 \le i \le n_a, and k−i≥k0−na≥0k - i \ge k_0 - n_a \ge 0. The input terms use k−nk−jk - n_k - j for 0≤j≤nb−10 \le j \le n_b - 1, and k−nk−j≥k0−nk−nb+1≥0k - n_k - j \ge k_0 - n_k - n_b + 1 \ge 0. All indices are at most k−1≤N−1k - 1 \le N - 1 or k−nk≤N−1k - n_k \le N - 1. □\square

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

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

So after the loop R=RN−1R = R_{N-1} and f=fN−1f = f_{N-1}; write them RR and ff from now on.

Lemma 3 (the criterion as a quadratic). For every θ∈Rd\theta \in \mathbb{R}^d,

V(θ)=θTRθ−2fTθ+c,c=∑k=k0N−1y(k)2,V(\theta) = \theta^T R \theta - 2 f^T \theta + c, \qquad c = \sum_{k=k_0}^{N-1} y(k)^2,

and RR is symmetric and positive semidefinite.

Proof. Expand each square: (y(k)−φ(k)Tθ)2=y(k)2−2y(k) φ(k)Tθ+θTφ(k)φ(k)Tθ(y(k) - \varphi(k)^T \theta)^2 = y(k)^2 - 2 y(k)\, \varphi(k)^T \theta + \theta^T \varphi(k) \varphi(k)^T \theta, and sum over kk. Each φ(k)φ(k)T\varphi(k)\varphi(k)^T is symmetric, and vTRv=∑k(φ(k)Tv)2≥0v^T R v = \sum_k (\varphi(k)^T v)^2 \ge 0 for every vv. □\square

Lemma 4 (the minimizers). A vector θ\theta minimizes VV if and only if Rθ=fR \theta = f. If RR is nonsingular, there is exactly one minimizer, R−1fR^{-1} f. If RR is singular, VV has infinitely many minimizers.

Proof. For any θ\theta and δ\delta, Lemma 3 gives

V(θ+δ)−V(θ)=2(Rθ−f)Tδ+δTRδ.V(\theta + \delta) - V(\theta) = 2 (R \theta - f)^T \delta + \delta^T R \delta.

If Rθ=fR \theta = f, the right side is δTRδ≥0\delta^T R \delta \ge 0, so θ\theta is a minimizer. If Rθ≠fR \theta \ne f, take δ=−t(Rθ−f)\delta = -t (R \theta - f) with t>0t > 0; the right side is −2t∥Rθ−f∥2+t2δ1-2t \lVert R\theta - f \rVert^2 + t^2 \delta_1 with δ1=(Rθ−f)TR(Rθ−f)\delta_1 = (R\theta - f)^T R (R\theta - f), which is negative for small tt, so θ\theta is not a minimizer.

Now f=∑kφ(k)y(k)f = \sum_k \varphi(k) y(k) lies in the column space of RR: if Rv=0R v = 0, then vTRv=∑k(φ(k)Tv)2=0v^T R v = \sum_k (\varphi(k)^T v)^2 = 0, so φ(k)Tv=0\varphi(k)^T v = 0 for every kk and fTv=0f^T v = 0. Since RR is symmetric, its column space is the orthogonal complement of its null space, and ff is orthogonal to that null space. Hence Rθ=fR \theta = f always has a solution θ∗\theta^*. If RR is nonsingular the solution is unique. If RR is singular, pick v≠0v \ne 0 with Rv=0R v = 0; then θ∗+tv\theta^* + t v solves Rθ=fR\theta = f for every real tt, and these are infinitely many minimizers. □\square

Theorem. If RR is nonsingular, ARX-LS returns the unique minimizer of VV. If RR is singular, it stops at L7, and in that case the minimizer of VV is not unique.

Proof. By Lemma 1 every regressor is well defined, and by Lemma 2 the matrix and vector after the loop are RR and ff. If RR is singular, L7 reports it, and Lemma 4 shows that VV has infinitely many minimizers. Otherwise L8 computes the unique solution of Rθ=fR \theta = f, which by Lemma 4 is the unique minimizer of VV, and L9 returns it. ■\blacksquare

Complexity

Line L4 costs O(d)O(d) to gather the regressor. Line L5 costs d2d^2 multiplications, or d(d+1)/2d(d+1)/2 using symmetry, and line L6 costs dd. Over the N−k0N - k_0 samples this is O(Nd2)O(N d^2). Line L8 solves a d×dd \times d system by Gaussian elimination in O(d3)O(d^3), and the same elimination detects the singular case of L7. The total is O(Nd2+d3)O(N d^2 + d^3) in the real RAM, with O(d2)O(d^2) extra space for RR and ff. Reading the data costs Ω(N)\Omega(N), and for N≫dN \gg d the pass over the samples dominates.

Properties

  • Exact. In exact arithmetic the result is the exact minimizer of VV; with rational data it is rational.
  • Global. VV is a convex quadratic, so there are no local minima to get stuck in.
  • Consistent for ARX data (theorem). If the data come from an ARX system of the same orders with white noise, an open-loop input that is persistently exciting of order na+nbn_a + n_b, and coprime AA and BB, then θ^→θ0\hat\theta \to \theta_0 with probability 1 as N→∞N \to \infty (Ljung 1999, Chapter 8).
  • Biased for colored noise (theorem and measurement). If the equation error is not white, φ(k)\varphi(k) contains past outputs that are correlated with it, and the limit is not θ0\theta_0. For the 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} with ARMAX noise C=1−q−1+0.2q−2C = 1 - q^{-1} + 0.2 q^{-2}, a white ±1\pm 1 input and N=50000N = 50000, the estimate was (−1.2286,0.4547,0.9965,0.7650)(-1.2286, 0.4547, 0.9965, 0.7650) against the true (−1.5,0.7,1,0.5)(-1.5, 0.7, 1, 0.5).
  • Asymptotic covariance (theorem). For ARX data, N(θ^−θ0)\sqrt{N}(\hat\theta - \theta_0) tends to a normal law with covariance σ2(E φφT)−1\sigma^2 \big(\mathbb{E}\, \varphi \varphi^T\big)^{-1}, which is estimated by σ^2NR−1\hat\sigma^2 N R^{-1} with σ^2=V(θ^)/(N−k0−d)\hat\sigma^2 = V(\hat\theta)/(N - k_0 - d).
  • Not online. The batch form needs all data before L8; the RLS algorithm gives the same answer after every sample.

Variants and improvements

  • QR on the data matrix. Stack the regressors as rows of an (N−k0)×d(N - k_0) \times d matrix Φ\Phi and solve min⁡∥Y−Φθ∥\min \lVert Y - \Phi \theta \rVert by a QR decomposition. This costs O(Nd2)O(N d^2) as well, but avoids squaring the condition number in L5.
  • Recursive least squares. Update θ^\hat\theta at each sample in O(d2)O(d^2) by the Sherman-Morrison formula; with a forgetting factor it tracks slowly changing systems.
  • Weighted and prefiltered least squares. Weight the equations, or filter yy and uu by the same filter L(q)L(q) before L3, to shape the frequency range where the model fits best.
  • Regularized least squares. Add λI\lambda I or a kernel matrix to RR in L8, as in kernel-based identification, to fit long FIR or high-order ARX models with less variance.
  • Instrumental variables. Replace one φ\varphi in L5 and L6 by an instrument vector uncorrelated with the noise, which removes the bias under colored noise.
  • Order scan. With the columns of the data matrix ordered as −y(k−1),u(k−1),−y(k−2),u(k−2),…-y(k-1), u(k-1), -y(k-2), u(k-2), \ldots, the leading columns are the regressors of the lower orders, and one QR decomposition gives the losses of all of them.

When to use it

Use it as the first fit on new data, as a starting value for the prediction error method or for instrumental variables, inside recursive and adaptive schemes, and whenever the signal-to-noise ratio is high. High-order ARX models fitted this way also approximate a general linear system well. Do not trust its pole estimates when the disturbance is strongly colored and the model order is low; use instrumental variables or a prediction error method with a noise model.

Pitfalls

  • Zero padding before the record. Starting the loop at k=0k = 0 in L1 with the missing past set to 0 adds equations that the data do not support, and biases the fit when the system was not at rest. L1 must start at k0=max⁡(na,nk+nb−1)k_0 = \max(n_a, n_k + n_b - 1).
  • The sign of the output terms. Writing +y(k−i)+y(k-i) in L4 makes the regression estimate −ai-a_i instead of aia_i. L4 must use −y(k−i)-y(k-i), because A(q)=1+a1q−1+⋯A(q) = 1 + a_1 q^{-1} + \cdots has the coefficients on the left side.
  • Ignoring a singular RR. A constant input makes u(k−1)u(k-1) and u(k−2)u(k-2) equal, so with nb=2n_b = 2 the matrix of L5 is singular; a solver without the check of L7 returns an arbitrary point or overflows. Keep L7, and choose an input that is persistently exciting of order at least nbn_b.
  • Ill-conditioning of the normal equations. In floating point, forming RR in L5 squares the condition number of the data. For fast sampling or high orders, replace L5 to L8 by a QR decomposition of the stacked regressors.
  • Unremoved means. A constant offset in uu or yy that is not in the model is fitted by distorting θ\theta. Subtract the sample means before L3, or add a constant 1 to the regressor in L4.

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()
least_squares_arx_identification.py 106 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/least-squares-arx-identification/. The authors are listed in prov/HXP9D6.jsonl.

"""Least squares identification of an ARX model.

The ARX model with orders na, nb and input delay nk is

    y(t) + a_1 y(t-1) + ... + a_na y(t-na)
        = b_1 u(t-nk) + ... + b_nb u(t-nk-nb+1) + e(t).

With the regressor phi(t) = (-y(t-1), ..., -y(t-na), u(t-nk), ...,
u(t-nk-nb+1)) and theta = (a_1, ..., a_na, b_1, ..., b_nb) this is the
linear regression y(t) = phi(t)^T theta + e(t). arx_ls returns the theta
that minimizes the sum of e(t)^2 over the samples t = t0, ..., N-1 whose
regressor is fully inside the data, t0 = max(na, nk + nb - 1).

Precondition: na >= 0, nb >= 1, nk >= 0 and the d by d matrix R = sum of
phi phi^T, d = na + nb, is nonsingular (the data are informative for the
model). With int or Fraction data the result is exact (Fraction).

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

from typing import Sequence

from ctlmat import solve


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


def first_sample(na: int, nb: int, nk: int) -> int:
    """Return t0 = max(na, nk + nb - 1), the first t with a full regressor."""
    return max(na, nk + nb - 1)


def arx_ls(y: Sequence, u: Sequence, na: int, nb: int, nk: int = 1) -> list:
    """Least squares estimate (a_1, ..., a_na, b_1, ..., b_nb) of an ARX model.

    Raises ValueError if the orders are invalid, the data are too short, or
    R is singular (the input is not persistently exciting enough, or the
    data are otherwise not informative).
    """
    if na < 0 or nb < 1 or nk < 0:
        raise ValueError("need na >= 0, nb >= 1 and nk >= 0")
    if len(y) != len(u):
        raise ValueError("y and u must have the same length")
    d = na + nb
    t0 = first_sample(na, nb, nk)  # @line L1
    if len(y) - t0 < d:
        raise ValueError("too few samples for the model orders")
    r = [[0] * d for _ in range(d)]  # @line L2
    f = [0] * d
    for t in range(t0, len(y)):  # @line L3
        phi = arx_regressor(y, u, na, nb, nk, t)  # @line L4
        for i in range(d):
            pi = phi[i]
            if pi == 0:
                continue
            row = r[i]
            for j in range(d):
                row[j] += pi * phi[j]  # @line L5
            f[i] += pi * y[t]  # @line L6
    try:
        theta = solve(r, f)  # @line L8
    except ValueError:
        raise ValueError("R is singular: the data are not informative for this model") from None  # @line L7
    return theta  # @line L9


def arx_loss(theta: Sequence, y: Sequence, u: Sequence, na: int, nb: int, nk: int = 1):
    """Return the sum of squared equation errors y(t) - phi(t)^T theta over t >= t0."""
    s = 0
    for t in range(first_sample(na, nb, nk), len(y)):
        phi = arx_regressor(y, u, na, nb, nk, t)
        e = y[t] - sum(p * th for p, th in zip(phi, theta))
        s += e * e
    return s


def arx_simulate(a: Sequence, b: Sequence, nk: int, u: Sequence, e: Sequence = None, c: Sequence = ()) -> list:
    """Simulate A(q) y = B(q) u + C(q) e from rest (all signals 0 before t = 0).

    a = (a_1, ..., a_na), b = (b_1, ..., b_nb) with b_1 on u(t-nk), and
    c = (c_1, ..., c_nc) for the moving average of the noise (C = 1 when c
    is empty, which is the ARX case). e defaults to zero noise.
    """
    n = len(u)
    if e is None:
        e = [0] * n
    y = []
    for t in range(n):
        v = e[t]
        for i, ci in enumerate(c, start=1):
            if t - i >= 0:
                v += ci * e[t - i]
        for j, bj in enumerate(b):
            if t - nk - j >= 0:
                v += bj * u[t - nk - j]
        for i, ai in enumerate(a, start=1):
            if t - i >= 0:
                v -= ai * y[t - i]
        y.append(v)
    return y
test_least_squares_arx_identification.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/least-squares-arx-identification/. The authors are listed in prov/HXP9D6.jsonl.

import random
from fractions import Fraction

from least_squares_arx_identification import arx_loss, arx_ls, arx_regressor, arx_simulate, first_sample


def test_worked_example():
    u = [1, 1, -1, 1, -1, -1]
    y = [Fraction(0), Fraction(1), Fraction(7, 5), Fraction(-1, 5), Fraction(9, 10), Fraction(-3, 5)]
    theta = arx_ls(y, u, 1, 1, 1)
    assert theta == [Fraction(-163, 336), Fraction(5407, 5600)]
    assert arx_loss(theta, y, u, 1, 1, 1) == Fraction(2899, 168000)


def test_exact_recovery_without_noise():
    rng = random.Random(11)
    a = [Fraction(-3, 2), Fraction(7, 10)]
    b = [Fraction(1), Fraction(1, 2)]
    u = [rng.choice((-1, 1)) for _ in range(30)]
    y = arx_simulate(a, b, 1, u)
    assert arx_ls(y, u, 2, 2, 1) == a + b


def _normal_residual(theta, y, u, na, nb, nk):
    d = na + nb
    g = [Fraction(0)] * d
    for t in range(first_sample(na, nb, nk), len(y)):
        phi = arx_regressor(y, u, na, nb, nk, t)
        e = y[t] - sum(p * th for p, th in zip(phi, theta))
        for i in range(d):
            g[i] += phi[i] * e
    return g


def test_random_normal_equations_and_minimum():
    # Oracle: the least squares minimizer is the unique theta whose residual is
    # orthogonal to every regressor column; also no perturbation lowers the loss.
    rng = random.Random(2024)
    done = 0
    while done < 500:
        na = rng.randint(0, 2)
        nb = rng.randint(1, 2)
        nk = rng.randint(0, 2)
        n = rng.randint(na + nb + 4, 12)
        u = [rng.randint(-3, 3) for _ in range(n)]
        y = [Fraction(rng.randint(-9, 9), rng.randint(1, 4)) for _ in range(n)]
        try:
            theta = arx_ls(y, u, na, nb, nk)
        except ValueError:
            continue
        assert all(v == 0 for v in _normal_residual(theta, y, u, na, nb, nk))
        v0 = arx_loss(theta, y, u, na, nb, nk)
        for _ in range(2):
            pert = [th + Fraction(rng.randint(-3, 3), 7) for th in theta]
            assert arx_loss(pert, y, u, na, nb, nk) >= v0
        done += 1


def test_consistent_with_white_noise():
    rng = random.Random(1)
    n = 4000
    u = [rng.choice((-1.0, 1.0)) for _ in range(n)]
    e = [rng.gauss(0.0, 1.0) for _ in range(n)]
    y = arx_simulate([-1.5, 0.7], [1.0, 0.5], 1, u, e)
    theta = arx_ls(y, u, 2, 2, 1)
    for est, true in zip(theta, [-1.5, 0.7, 1.0, 0.5]):
        assert abs(est - true) < 0.06


def test_biased_with_colored_noise():
    rng = random.Random(1)
    n = 4000
    u = [rng.choice((-1.0, 1.0)) for _ in range(n)]
    e = [rng.gauss(0.0, 1.0) for _ in range(n)]
    y = arx_simulate([-1.5, 0.7], [1.0, 0.5], 1, u, e, c=[-1.0, 0.2])
    theta = arx_ls(y, u, 2, 2, 1)
    assert abs(theta[0] - (-1.5)) > 0.15
    assert abs(theta[1] - 0.7) > 0.15


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


def test_fir_and_direct_term():
    rng = random.Random(5)
    u = [rng.randint(-2, 2) for _ in range(15)]
    y = [3 * u[t] - (2 * u[t - 1] if t >= 1 else 0) for t in range(15)]
    assert arx_ls(y, u, 0, 2, 0) == [3, -2]


def test_bad_arguments():
    for args in (([1, 2, 3], [1, 2, 3], -1, 1, 1), ([1, 2, 3], [1, 2, 3], 1, 0, 1),
                 ([1, 2, 3], [1, 2], 1, 1, 1), ([1, 2], [1, 2], 2, 2, 1)):
        try:
            arx_ls(*args)
        except ValueError:
            continue
        raise AssertionError("expected ValueError for %r" % (args,))

History

Least squares itself goes back to Legendre and Gauss at the start of the nineteenth century. Kalman's 1958 design of a self-optimizing controller estimated the coefficients of a difference equation model of the plant by least squares and recomputed the controller from them. Åström and Eykhoff's survey of 1971 presented least squares for difference equation models as the basic method of system identification and discussed its bias when the residuals are correlated, the problem that led to instrumental variables and to maximum likelihood fits of ARMAX models.

References

  1. Lennart Ljung, System Identification: Theory for the User, second edition, Prentice Hall, 1999, Chapter 7 (linear regressions and the least squares method), Chapter 8 (consistency) and Chapter 10 (computing the estimate, including solution by QR factorization)
  2. Torsten Söderström and Petre Stoica, System Identification, Prentice Hall, 1989, the chapter on linear regression and Chapter 5 (persistent excitation and the nonsingularity of the normal matrix)
  3. Karl Johan Åström and Pieter Eykhoff, System identification: a survey, Automatica 7(2), 123-162, 1971, the least squares method for difference equation models, its bias under correlated residuals, and its history
  4. Rudolf E. Kalman, Design of a self-optimizing control system, Transactions of the ASME 80, 468-478, 1958, the estimation of the coefficients of a difference equation model of the plant

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