Algorithm Search⌘K

Algorithmresearch

Kernel-based system identification

Also called regularized FIR identification, stable spline kernel method.

Estimates a long impulse response by regularized least squares with a kernel, such as the TC kernel, that encodes exponential decay.

Time
O(N d^2 + G d^3) worst
Space
O(N d + d^2) extra
Where
G = the number of grid points; N = the number of samples; d = the FIR length
Properties
deterministicexactnot iterativeoffline
Origin
Gianluigi Pillonetto, Giuseppe De Nicolao, 2010

Kernel-based identification estimates the impulse response g1,g2,…,gdg_1, g_2, \ldots, g_d of a linear system from input-output data. It fits a long FIR model, with dd much larger than the true order, by regularized least squares. The regularization matrix comes from a kernel that encodes what we know about asymptotically stable systems: the coefficients decay exponentially and neighbouring coefficients are correlated. The kernel has two or three hyperparameters, and the method chooses them by maximizing the marginal likelihood of the data. This differs from least squares ARX identification and from a prediction error method, which fit a model with a fixed small order and need a choice of that order. Here the model is long and the kernel controls its complexity. The estimate is also the posterior mean of a Gaussian process model of the impulse response.

In plain words

A plain least squares fit of 50 impulse response coefficients from 100 samples is very noisy: each coefficient has little data, and the tail of the estimate wanders around zero. We know more than the data say. The true coefficients get smaller as the lag grows, and they change smoothly from one lag to the next. The kernel writes this knowledge as a prior covariance: large variance for the first lags, smaller variance for later lags, and strong correlation between neighbours. Regularized least squares then pulls the estimate toward such shapes. How fast the prior decays and how large it is are not known in advance, so the method tries values on a grid and keeps the one for which the observed data are most probable.

The problem

Input. Scalar samples u0,…,uN−1u_0, \ldots, u_{N-1} and y0,…,yN−1y_0, \ldots, y_{N-1}, the FIR length d<Nd < N, a kernel family K(η)K(\eta) with a finite grid of hyperparameters η\eta, and optionally the noise variance σ2\sigma^2.

Output. An estimate g^∈Rd\hat g \in \mathbb{R}^d of the impulse response, the chosen hyperparameters η∗\eta^*, and the noise variance used.

Model. yk=∑t=1dgtuk−t+eky_k = \sum_{t=1}^{d} g_t u_{k-t} + e_k with ut=0u_t = 0 for t<0t < 0, and eke_k white Gaussian noise with variance σ2\sigma^2. In matrix form y=Φg+ey = \Phi g + e, where Φ\Phi is the N×dN \times d regressor with Φk,t=uk−t\Phi_{k,t} = u_{k-t}.

Kernels. The TC (tuned/correlated) kernel is Kij=cλmax⁡(i,j)K_{ij} = c \lambda^{\max(i,j)} with c>0c > 0 and 0<λ<10 < \lambda < 1. It is also the first order stable spline kernel. The DC (diagonal/correlated) kernel is Kij=cλ(i+j)/2ρ∣i−j∣K_{ij} = c \lambda^{(i+j)/2} \rho^{|i-j|} with ∣ρ∣<1|\rho| < 1; with ρ=λ\rho = \sqrt{\lambda} it is the TC kernel. In both, λ\lambda sets the decay rate and cc the scale.

The algorithm

  1. KERNEL-FIR(u, y, d, grid, σ²)
  2. 1Φ ← the N × d regressor, Φ[k][t] = u_(k-t)
  3. 2R ← Φ^T Φ; r ← Φ^T y; yy ← y^T y
  4. 3if σ² is not given: σ² ← the residual sum of squares of the least squares FIR fit / (N - d)
  5. 4for each η in the grid:
  6. 5K ← K(η); L ← the Cholesky factor of K; M ← σ² I + L^T R L
  7. 6cost ← (yy - (L^T r)^T M⁻¹ L^T r) / σ² + (N - d) log σ² + log det M
  8. 7if cost < the best cost so far: keep η and the cost
  9. 8ĝ ← L M⁻¹ L^T r for the kept η
  10. 9return (ĝ, η, σ²)

The estimate is the minimizer of the regularized criterion

∥y−Φg∥2+σ2gTK−1g,g^=(R+σ2K−1)−1r=KΦTZ−1y,\lVert y - \Phi g \rVert^2 + \sigma^2 g^T K^{-1} g, \qquad \hat g = (R + \sigma^2 K^{-1})^{-1} r = K \Phi^T Z^{-1} y,

with Z=ΦKΦT+σ2INZ = \Phi K \Phi^T + \sigma^2 I_N. If gg has the prior N(0,K)\mathcal{N}(0, K), then yy has the distribution N(0,Z)\mathcal{N}(0, Z), and the cost of L6 is yTZ−1y+log⁡det⁡Zy^T Z^{-1} y + \log \det Z, which is minus two times the log marginal likelihood, up to a constant. Choosing η\eta this way is empirical Bayes. The code never forms the N×NN \times N matrix ZZ. With K=LLTK = L L^T, the push-through identity, the Woodbury identity and Sylvester's determinant identity give the d×dd \times d forms of L5, L6 and L8. They also avoid K−1K^{-1}, which is badly conditioned when λd\lambda^d is small. L3 is the unbiased estimate of the noise variance from the plain least squares fit.

Example

Take the impulse response

gk=0.5⋅0.9k−1cos⁡(0.6(k−1))+0.3⋅0.6k−1,k=1,…,50,g_k = 0.5 \cdot 0.9^{k-1} \cos(0.6 (k-1)) + 0.3 \cdot 0.6^{k-1}, \qquad k = 1, \ldots, 50,

a lightly damped mode plus a fast real pole, so d=50d = 50. The input is Gaussian white noise with unit variance, the noise has σ=0.3\sigma = 0.3, and the random seed is 1. Measure the quality by the fit 100(1−∥g^−g∥/∥g∥)100 (1 - \lVert \hat g - g \rVert / \lVert g \rVert) in percent.

The TC grid is c∈{0.1,0.3,1,3}c \in \{0.1, 0.3, 1, 3\} and λ∈{0.6,0.7,0.8,0.85,0.9,0.95}\lambda \in \{0.6, 0.7, 0.8, 0.85, 0.9, 0.95\}, 24 points. The DC grid uses the same cc, λ∈{0.7,0.8,0.9}\lambda \in \{0.7, 0.8, 0.9\} and ρ∈{−0.5,0,0.5,0.9}\rho \in \{-0.5, 0, 0.5, 0.9\}, 48 points.

With N=100N = 100 samples, L3 gives σ^2=0.0887\hat\sigma^2 = 0.0887 (the true value is 0.090.09). The TC search keeps (c,λ)=(0.3,0.85)(c, \lambda) = (0.3, 0.85) and the DC search keeps (c,λ,ρ)=(1,0.8,0.9)(c, \lambda, \rho) = (1, 0.8, 0.9). The fits are:

estimate fit, N=100N = 100 fit, N=200N = 200
least squares FIR 59.0 83.3
TC kernel 89.3 89.5
DC kernel 88.5 89.5

With 100 samples and 50 unknowns, plain least squares is poor, and the kernel estimate is much better. With 200 samples the gap is smaller but still clear. Over the seeds 1 to 5 at N=100N = 100, the TC fit was between 84.6 and 89.5 and the least squares fit between 58.8 and 76.9 (measurement).

Correctness

Claim. KERNEL-FIR returns the first grid point that maximizes the Gaussian marginal likelihood of yy, and the posterior mean of gg under the kernel at that point, which is also the unique minimizer of the regularized criterion.

Key invariant. For every grid point, with K=LLTK = L L^T and M=σ2I+LTRLM = \sigma^2 I + L^T R L, the d×dd \times d quantities equal the N×NN \times N ones: LM−1LTr=KΦTZ−1yL M^{-1} L^T r = K \Phi^T Z^{-1} y, (yTy−rTLM−1LTr)/σ2=yTZ−1y(y^T y - r^T L M^{-1} L^T r)/\sigma^2 = y^T Z^{-1} y and (N−d)log⁡σ2+log⁡det⁡M=log⁡det⁡Z(N - d) \log \sigma^2 + \log \det M = \log \det Z.

The TC and DC kernels are positive definite, so LL exists and MM is positive definite. The scan keeps a point only when its cost is strictly smaller. The full proof is below.

Proof: The kernel-based FIR estimate is the posterior mean at the grid point of largest marginal likelihoodfull

We work in exact real arithmetic, as in the real RAM. The data are u0,…,uN−1u_0, \ldots, u_{N-1} and y0,…,yN−1y_0, \ldots, y_{N-1}, the FIR length is d<Nd < N, and Φ\Phi is the N×dN \times d regressor of L1 with Φk,t=uk−t\Phi_{k,t} = u_{k-t} (00 for k<tk < t). Write R=ΦTΦR = \Phi^T \Phi and r=ΦTyr = \Phi^T y (L2).

The Bayesian model. g∼N(0,K)g \sim \mathcal{N}(0, K) with KK positive definite, and y=Φg+ey = \Phi g + e with e∼N(0,σ2IN)e \sim \mathcal{N}(0, \sigma^2 I_N) independent of gg and σ2>0\sigma^2 > 0. Then y∼N(0,Z)y \sim \mathcal{N}(0, Z) with Z=ΦKΦT+σ2INZ = \Phi K \Phi^T + \sigma^2 I_N.

Lemma 1 (the TC kernel is positive definite). For c>0c > 0 and 0<λ<10 < \lambda < 1, the matrix Kij=cλmax⁡(i,j)K_{ij} = c \lambda^{\max(i, j)}, i,j=1,…,di, j = 1, \ldots, d, is positive definite.

Proof. Let 1t∈Rd\mathbf{1}_t \in \mathbb{R}^d have entries 1 at the indices i≤ti \le t and 0 elsewhere. For i,j≤di, j \le d,

λmax⁡(i,j)=∑t=max⁡(i,j)d−1(λt−λt+1)+λd,\lambda^{\max(i, j)} = \sum_{t = \max(i, j)}^{d-1} (\lambda^t - \lambda^{t+1}) + \lambda^d,

so K=c∑t=1d−1(λt−λt+1)1t1tT+cλd1d1dTK = c \sum_{t=1}^{d-1} (\lambda^t - \lambda^{t+1}) \mathbf{1}_t \mathbf{1}_t^T + c \lambda^d \mathbf{1}_d \mathbf{1}_d^T. All weights are positive. If vTKv=0v^T K v = 0, then 1tTv=0\mathbf{1}_t^T v = 0 for t=1,…,dt = 1, \ldots, d, so v1=0v_1 = 0, then v2=0v_2 = 0, and so on: v=0v = 0. □\square

The DC kernel cλ(i+j)/2ρ∣i−j∣c \lambda^{(i+j)/2} \rho^{|i-j|} with ∣ρ∣<1|\rho| < 1 is cc times diag⁡(λi/2)\operatorname{diag}(\lambda^{i/2}) times the correlation matrix of a first order autoregressive process times the same diagonal, so it is also positive definite. With ρ=λ\rho = \sqrt{\lambda} it equals the TC kernel, since λ(i+j)/2λ∣i−j∣/2=λmax⁡(i,j)\lambda^{(i+j)/2} \lambda^{|i-j|/2} = \lambda^{\max(i,j)}.

Lemma 2 (posterior mean and regularized least squares). The posterior mean of gg given yy is

g^=KΦTZ−1y=(R+σ2K−1)−1r,\hat g = K \Phi^T Z^{-1} y = (R + \sigma^2 K^{-1})^{-1} r,

and it is the unique minimizer of ∥y−Φg∥2+σ2gTK−1g\lVert y - \Phi g \rVert^2 + \sigma^2 g^T K^{-1} g.

Proof. (g,y)(g, y) is jointly Gaussian with Cov⁡(g,y)=KΦT\operatorname{Cov}(g, y) = K \Phi^T and Cov⁡(y)=Z\operatorname{Cov}(y) = Z, so E[g∣y]=KΦTZ−1y\mathbb{E}[g \mid y] = K \Phi^T Z^{-1} y. The push-through identity ΦT(ΦKΦT+σ2I)=(ΦTΦK+σ2I)ΦT\Phi^T (\Phi K \Phi^T + \sigma^2 I) = (\Phi^T \Phi K + \sigma^2 I) \Phi^T gives KΦTZ−1=K(RK+σ2I)−1ΦT=(R+σ2K−1)−1ΦTK \Phi^T Z^{-1} = K (R K + \sigma^2 I)^{-1} \Phi^T = (R + \sigma^2 K^{-1})^{-1} \Phi^T. The criterion is a quadratic with Hessian 2(R+σ2K−1)2(R + \sigma^2 K^{-1}), which is positive definite, and its gradient vanishes at (R+σ2K−1)g=r(R + \sigma^2 K^{-1}) g = r. □\square

Lemma 3 (small forms). Let K=LLTK = L L^T be the Cholesky factorization and M=σ2Id+LTRLM = \sigma^2 I_d + L^T R L. Then

g^=LM−1LTr,yTZ−1y=yTy−rTLM−1LTrσ2,log⁡det⁡Z=(N−d)log⁡σ2+log⁡det⁡M.\hat g = L M^{-1} L^T r, \qquad y^T Z^{-1} y = \frac{y^T y - r^T L M^{-1} L^T r}{\sigma^2}, \qquad \log \det Z = (N - d) \log \sigma^2 + \log \det M.

Proof. Put X=ΦLX = \Phi L, so Z=XXT+σ2INZ = X X^T + \sigma^2 I_N and M=XTX+σ2IdM = X^T X + \sigma^2 I_d. The push-through identity gives XTZ−1=M−1XTX^T Z^{-1} = M^{-1} X^T, so g^=KΦTZ−1y=LXTZ−1y=LM−1XTy=LM−1LTr\hat g = K \Phi^T Z^{-1} y = L X^T Z^{-1} y = L M^{-1} X^T y = L M^{-1} L^T r. The Woodbury identity gives Z−1=σ−2(IN−XM−1XT)Z^{-1} = \sigma^{-2} (I_N - X M^{-1} X^T), which gives the second formula. Sylvester's determinant identity det⁡(IN+XXT/σ2)=det⁡(Id+XTX/σ2)\det(I_N + X X^T / \sigma^2) = \det(I_d + X^T X / \sigma^2) gives det⁡Z=σ2Ndet⁡(Id+XTX/σ2)=σ2Nσ−2ddet⁡M\det Z = \sigma^{2N} \det(I_d + X^T X / \sigma^2) = \sigma^{2N} \sigma^{-2d} \det M. □\square

Lemma 4 (the cost is the marginal likelihood). The cost of L6 is yTZ−1y+log⁡det⁡Z=−2log⁡p(y∣η)−Nlog⁡(2π)y^T Z^{-1} y + \log \det Z = -2 \log p(y \mid \eta) - N \log(2 \pi), where p(y∣η)p(y \mid \eta) is the Gaussian density of yy under the kernel with hyperparameters η\eta.

Proof. p(y∣η)=(2π)−N/2(det⁡Z)−1/2exp⁡(−12yTZ−1y)p(y \mid \eta) = (2 \pi)^{-N/2} (\det Z)^{-1/2} \exp(-\tfrac12 y^T Z^{-1} y). Take −2log⁡-2 \log. By Lemma 3, the code computes exactly these two terms from RR, rr and yTyy^T y. □\square

Lemma 5 (the noise variance of L3). If RR is nonsingular and the data follow the FIR model with dd taps, then σ^2=∥y−ΦgLS∥2/(N−d)\hat\sigma^2 = \lVert y - \Phi g_{LS} \rVert^2 / (N - d) with gLS=R−1rg_{LS} = R^{-1} r has expectation σ2\sigma^2, given uu.

Proof. The residual is (I−P)e(I - P) e with P=ΦR−1ΦTP = \Phi R^{-1} \Phi^T, an orthogonal projection of rank dd. So E∥(I−P)e∥2=σ2tr⁡(I−P)=σ2(N−d)\mathbb{E} \lVert (I - P) e \rVert^2 = \sigma^2 \operatorname{tr}(I - P) = \sigma^2 (N - d). The code computes ∥y−ΦgLS∥2=yTy−2gLSTr+gLSTRgLS\lVert y - \Phi g_{LS} \rVert^2 = y^T y - 2 g_{LS}^T r + g_{LS}^T R g_{LS}. □\square

Theorem. KERNEL-FIR returns σ^2\hat\sigma^2 (or the given σ2\sigma^2), the first grid point η∗\eta^* that minimizes −2log⁡p(y∣η)-2 \log p(y \mid \eta) over the grid, and the posterior mean of gg under the kernel K(η∗)K(\eta^*), which is also the regularized least squares estimate of Lemma 2.

Proof. L4 to L7 scan the grid and keep a point only when its cost is strictly smaller, so the kept point is the first minimizer of the cost, which by Lemma 4 is the first maximizer of the marginal likelihood. L8 computes LM−1LTrL M^{-1} L^T r for this kernel, which by Lemmas 2 and 3 is the posterior mean. ■\blacksquare

Remark. The theorem is about the optimization over the grid only. The marginal likelihood is not convex in the hyperparameters, and a continuous search can stop at a local minimum. Whether the empirical Bayes choice gives a small error ∥g^−g0∥\lVert \hat g - g_0 \rVert is a statistical question; the page reports measurements and cites the theory.

Complexity

In the real RAM. L1 is O(Nd)O(N d) and L2 is O(Nd2)O(N d^2). Each grid point costs a Cholesky factorization, two products of d×dd \times d matrices, a linear solve and a second Cholesky factorization for log⁡det⁡M\log \det M, all O(d3)O(d^3). With GG grid points the total is O(Nd2+Gd3)O(N d^2 + G d^3). The extra space is O(Nd)O(N d) for Φ\Phi and O(d2)O(d^2) for the matrices; a streaming version forms RR and rr without storing Φ\Phi and needs O(d2)O(d^2).

A continuous search over η\eta with a quasi-Newton method costs O(d3)O(d^3) per evaluation of the cost, the same as one grid point.

Properties

  • Posterior mean (theorem). Under the Gaussian prior g∼N(0,K)g \sim \mathcal{N}(0, K) and Gaussian noise, g^\hat g is the posterior mean, and the cost is minus two times the log marginal likelihood up to a constant.
  • Bias and variance (theorem). For a fixed kernel, g^\hat g is biased toward zero, but its variance is smaller than that of least squares. The regularization trades bias for variance; see bias-variance tradeoff.
  • No order selection. The FIR length dd only needs to be long enough for the response to decay. The kernel, not dd, sets the effective number of parameters.
  • Decaying estimates. With the TC or DC kernel the prior variance of gkg_k decays as λk\lambda^k, so the estimate decays as well. This is a property of the prior, not a guarantee about every data set.
  • Better accuracy on short records (measurement). In the example, the TC estimate had a fit near 89 percent where least squares had 59 percent. Chen, Ohlsson and Ljung (2012) report similar gains in Monte Carlo studies, also against prediction error methods with the order chosen by a criterion.
  • Nonconvex hyperparameter search. The marginal likelihood is not convex in η\eta. A grid is safe for two or three hyperparameters, but a local search can stop at a local optimum.

Variants and improvements

  • Stable spline kernels. Pillonetto and De Nicolao (2010) use the second order stable spline kernel, which makes the estimate smoother. The TC kernel is the first order case.
  • Other kernels. Sums and products of kernels, kernels for resonant systems, and kernels learned from data. The survey of Pillonetto et al. (2014) describes many.
  • Multiple inputs and outputs. One impulse response per input-output pair, each with its own kernel, or a shared kernel.
  • Continuous search. Optimize the marginal likelihood over η\eta with gradients. A QR factorization of the stacked regressor gives a more accurate cost than the normal equations.
  • Other tuning criteria. Cross-validation or Stein's unbiased risk estimate in place of the marginal likelihood.
  • From FIR to state space. Fit a low order state-space model to g^\hat g, for example by the Ho-Kalman algorithm or by model reduction, when a compact model is needed.

When to use it

Use kernel-based identification for a linear, asymptotically stable system when the data record is short, the noise is large, or the order is unknown. It gives a good impulse response and frequency response without a choice of order and without local minima in the model parameters. Use it as a reference model or as a starting point for a low order fit. For a system with a very slow mode, dd must be large, and the cost grows as d3d^3. For an unstable system, the kernels above are wrong.

Pitfalls

  • dd too short. If gdg_d is not small, the truncated tail acts as extra noise and biases the result. Check that the estimate has decayed at lag dd.
  • K−1K^{-1} in the code. Forming R+σ2K−1R + \sigma^2 K^{-1} directly fails when λd\lambda^d is near the machine epsilon. Use the Cholesky factor of KK as in L5.
  • Initial conditions. The code sets ut=0u_t = 0 for t<0t < 0. If the system was not at rest before the record, drop the first dd outputs from the fit.
  • A grid that is too coarse. If the best point is on the edge of the grid, extend the grid.
  • Unknown noise variance. L3 needs N>dN > d and a nonsingular RR. With NN close to dd the estimate of σ2\sigma^2 is poor; estimate it from a low order model or include it in the marginal likelihood.
  • Colored noise. The model assumes white noise. Colored noise gives a wrong marginal likelihood and a wrong choice of η\eta.

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()
kernel_based_identification.py 114 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernel-based-identification/. The authors are listed in prov/BXFFBH.jsonl.

"""Kernel-based (regularized) FIR identification with the TC and DC kernels.

Input: an input sequence u_0, ..., u_(N-1) and an output sequence
y_0, ..., y_(N-1) (scalars) of a system y_k = sum_(t=1..d) g_t u_(k-t) + e_k
with u_t = 0 for t < 0, the FIR length d, a grid of kernel hyperparameters,
and the noise variance sigma2 (or None to estimate it from the residuals of
the least squares FIR fit).

Model: the impulse response g is a Gaussian vector with zero mean and
covariance K (the kernel matrix), and e is white Gaussian noise with variance
sigma2. Then y is Gaussian with covariance Z = Phi K Phi^T + sigma2 I, and

    g_hat = (Phi^T Phi + sigma2 K^-1)^-1 Phi^T y = K Phi^T Z^-1 y

is the posterior mean (the regularized least squares estimate). The
hyperparameters minimize the negative log marginal likelihood
y^T Z^-1 y + log det Z (empirical Bayes) over the grid.

With K = L L^T (Cholesky) and M = sigma2 I + L^T Phi^T Phi L, every step
uses d by d matrices only:

    g_hat = L M^-1 L^T Phi^T y,
    y^T Z^-1 y = (y^T y - y^T Phi L M^-1 L^T Phi^T y) / sigma2,
    log det Z = (N - d) log sigma2 + log det M.
"""

import math

from ctlmat import mul, solve, transpose

__all__ = ["regressor", "tc_kernel", "dc_kernel", "cholesky", "fit", "neg_log_marginal_likelihood", "kernel_fir"]


def regressor(u, d):
    """Return the N by d matrix Phi with Phi[k][t - 1] = u_(k-t) (zero for k - t < 0)."""
    return [[float(u[k - t]) if k - t >= 0 else 0.0 for t in range(1, d + 1)] for k in range(len(u))]


def tc_kernel(d, c, lam):
    """Tuned/correlated kernel: K[i][j] = c lam^max(i, j), for i, j = 1, ..., d."""
    return [[c * lam ** max(i, j) for j in range(1, d + 1)] for i in range(1, d + 1)]


def dc_kernel(d, c, lam, rho):
    """Diagonal/correlated kernel: K[i][j] = c lam^((i + j) / 2) rho^|i - j|."""
    return [[c * lam ** ((i + j) / 2.0) * rho ** abs(i - j) for j in range(1, d + 1)] for i in range(1, d + 1)]


def cholesky(a):
    """Return the lower triangular L with a = L L^T; raise ValueError if a is not positive definite."""
    n = len(a)
    L = [[0.0] * n for _ in range(n)]
    for j in range(n):
        s = a[j][j] - sum(L[j][k] ** 2 for k in range(j))
        if not s > 0.0:
            raise ValueError("cholesky: the matrix is not positive definite")
        L[j][j] = math.sqrt(s)
        for i in range(j + 1, n):
            L[i][j] = (a[i][j] - sum(L[i][k] * L[j][k] for k in range(j))) / L[j][j]
    return L


def _parts(R, r, K, sigma2):
    d = len(K)
    L = cholesky(K)
    M = mul(mul(transpose(L), R), L)
    for i in range(d):
        M[i][i] += sigma2
    Ltr = [sum(L[t][i] * r[t] for t in range(d)) for i in range(d)]
    w = solve(M, Ltr)
    return L, M, Ltr, w


def neg_log_marginal_likelihood(R, r, yy, N, K, sigma2):
    """Return y^T Z^-1 y + log det Z from R = Phi^T Phi, r = Phi^T y and yy = y^T y."""
    d = len(K)
    L, M, Ltr, w = _parts(R, r, K, sigma2)
    logdet_m = 2.0 * sum(math.log(v[i]) for i, v in enumerate(cholesky(M)))
    quad = (yy - sum(a * b for a, b in zip(Ltr, w))) / sigma2
    return quad + (N - d) * math.log(sigma2) + logdet_m


def fit(R, r, K, sigma2):
    """Return g_hat = L M^-1 L^T r, the regularized least squares estimate."""
    L, M, Ltr, w = _parts(R, r, K, sigma2)
    d = len(K)
    return [sum(L[i][t] * w[t] for t in range(d)) for i in range(d)]


def kernel_fir(u, y, d, grid, kernel=tc_kernel, sigma2=None):
    """Return (g_hat, best, sigma2): the estimate, the chosen hyperparameters and the noise variance.

    grid is a list of tuples; kernel(d, *eta) is called for each tuple eta.
    """
    N = len(y)
    Phi = regressor(u, d)  # @line L1
    R = mul(transpose(Phi), Phi)  # @line L2
    r = [sum(Phi[k][t] * y[k] for k in range(N)) for t in range(d)]
    yy = sum(v * v for v in y)
    if sigma2 is None:  # @line L3
        g_ls = solve(R, r)
        sigma2 = (yy - 2.0 * sum(a * b for a, b in zip(g_ls, r))
                  + sum(g_ls[i] * R[i][j] * g_ls[j] for i in range(d) for j in range(d))) / (N - d)
    best, best_cost = None, math.inf
    for eta in grid:  # @line L4
        K = kernel(d, *eta)  # @line L5
        cost = neg_log_marginal_likelihood(R, r, yy, N, K, sigma2)  # @line L6
        if cost < best_cost:  # @line L7
            best, best_cost = eta, cost
    g_hat = fit(R, r, kernel(d, *best), sigma2)  # @line L8
    return g_hat, best, sigma2  # @line L9
test_kernel_based_identification.py 99 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/kernel-based-identification/. The authors are listed in prov/BXFFBH.jsonl.

import math
import random

from ctlmat import det, mul, solve, transpose
from kernel_based_identification import (cholesky, dc_kernel, fit, kernel_fir, neg_log_marginal_likelihood,
                                         regressor, tc_kernel)


def _true_g(d):
    return [0.5 * 0.9 ** (k - 1) * math.cos(0.6 * (k - 1)) + 0.3 * 0.6 ** (k - 1) for k in range(1, d + 1)]


def _data(rng, g, N, sigma):
    u = [rng.gauss(0.0, 1.0) for _ in range(N)]
    y = [sum(g[t - 1] * u[k - t] for t in range(1, len(g) + 1) if k - t >= 0) + rng.gauss(0.0, sigma)
         for k in range(N)]
    return u, y


def _normal_eq(u, y, d):
    Phi = regressor(u, d)
    R = mul(transpose(Phi), Phi)
    r = [sum(Phi[k][t] * y[k] for k in range(len(y))) for t in range(d)]
    return Phi, R, r


def test_regressor_layout():
    assert regressor([1, 2, 3], 2) == [[0.0, 0.0], [1.0, 0.0], [2.0, 1.0]]


def test_dc_kernel_contains_tc_kernel():
    # rho = lam^(1/2) turns the DC kernel into the TC kernel
    lam = 0.8
    a, b = dc_kernel(6, 2.0, lam, math.sqrt(lam)), tc_kernel(6, 2.0, lam)
    assert all(abs(x - y) < 1e-14 for ra, rb in zip(a, b) for x, y in zip(ra, rb))
    L = cholesky(tc_kernel(6, 1.0, 0.7))
    back = mul(L, transpose(L))
    assert all(abs(x - y) < 1e-14 for ra, rb in zip(back, tc_kernel(6, 1.0, 0.7)) for x, y in zip(ra, rb))


def test_small_forms_match_the_n_by_n_formulas():
    rng = random.Random(3)
    d, N, sigma2 = 6, 25, 0.04
    u, y = _data(rng, _true_g(d), N, 0.2)
    Phi, R, r = _normal_eq(u, y, d)
    K = tc_kernel(d, 0.5, 0.8)
    Z = mul(mul(Phi, K), transpose(Phi))
    for i in range(N):
        Z[i][i] += sigma2
    zy = solve(Z, y)
    direct = [sum(v * w for v, w in zip(row, zy)) for row in mul(K, transpose(Phi))]
    assert max(abs(a - b) for a, b in zip(fit(R, r, K, sigma2), direct)) < 1e-10
    want = sum(a * b for a, b in zip(y, zy)) + math.log(det(Z))
    got = neg_log_marginal_likelihood(R, r, sum(v * v for v in y), N, K, sigma2)
    assert abs(got - want) < 1e-8 * abs(want)


def test_noise_free_recovery():
    # no noise and a tiny sigma2: the estimate is the exact FIR
    rng = random.Random(5)
    g = _true_g(8)
    u, y = _data(rng, g, 60, 0.0)
    grid = [(c, lam) for c in (0.3, 1.0) for lam in (0.7, 0.9)]
    g_hat, best, s2 = kernel_fir(u, y, 8, grid, sigma2=1e-10)
    assert max(abs(a - b) for a, b in zip(g_hat, g)) < 1e-6


def test_regularization_beats_least_squares():
    # measurement: d = 30, N = 120, noise standard deviation 0.3
    d, N = 30, 120
    g = _true_g(d)
    grid = [(c, lam) for c in (0.1, 0.3, 1.0) for lam in (0.7, 0.8, 0.9)]
    for seed in (1, 2, 3):
        rng = random.Random(seed)
        u, y = _data(rng, g, N, 0.3)
        g_hat, best, s2 = kernel_fir(u, y, d, grid)
        _, R, r = _normal_eq(u, y, d)
        g_ls = solve(R, r)
        err = math.sqrt(sum((a - b) ** 2 for a, b in zip(g_hat, g)))
        err_ls = math.sqrt(sum((a - b) ** 2 for a, b in zip(g_ls, g)))
        size = math.sqrt(sum(b * b for b in g))
        assert err < err_ls
        assert err < 0.2 * size
        assert 0.05 < s2 < 0.15


def test_dc_kernel_search():
    d, N = 20, 100
    g = _true_g(d)
    rng = random.Random(8)
    u, y = _data(rng, g, N, 0.3)
    grid = [(c, lam, rho) for c in (0.3, 1.0) for lam in (0.7, 0.9) for rho in (0.0, 0.9)]
    g_hat, best, s2 = kernel_fir(u, y, d, grid, kernel=dc_kernel)
    assert best in grid
    err = math.sqrt(sum((a - b) ** 2 for a, b in zip(g_hat, g)))
    assert err < 0.25 * math.sqrt(sum(b * b for b in g))

History

Tikhonov regularization of ill-posed least squares problems is much older than this method. The kernel approach of this page starts with Pillonetto and De Nicolao (2010), who treated the impulse response as a Gaussian process with a stable spline kernel and tuned it by the marginal likelihood. Chen, Ohlsson and Ljung (2012) introduced the TC and DC kernels and compared the method with classical prediction error methods. Pillonetto, Dinuzzo, Chen, De Nicolao and Ljung (2014) surveyed the field in Automatica.

References

  1. Gianluigi Pillonetto and Giuseppe De Nicolao, A new kernel-based approach for linear system identification, Automatica 46(1), 81-93, 2010, the stable spline kernel, the Gaussian prior on the impulse response, and the choice of hyperparameters by the marginal likelihood
  2. Tianshi Chen, Henrik Ohlsson and Lennart Ljung, On the estimation of transfer functions, regularizations and Gaussian processes, Revisited, Automatica 48(8), 1525-1535, 2012, the TC and DC kernels and the comparison of regularized FIR estimates with prediction error methods
  3. Gianluigi Pillonetto, Francesco Dinuzzo, Tianshi Chen, Giuseppe De Nicolao and Lennart Ljung, Kernel methods in system identification, machine learning and function estimation: A survey, Automatica 50(3), 657-682, 2014, the survey of kernels for asymptotically stable systems, empirical Bayes and the relation to regularized least squares

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