Algorithm Search⌘K

Algorithmadvanced

Representer method

Solves weak-constraint variational assimilation exactly in the span of representer functions, one per observation, from adjoint and forward runs.

Time
Θ(p K (c + n^2) + p^2 n + p^3) worst
Space
Θ(K n + p n + p^2) extra
Where
K = the number of model steps in the window; c = the cost of one model or adjoint step; n = the state dimension; p = the number of scalar observations
Properties
deterministicexact for linear model
Origin
Andrew F. Bennett, Peter C. McIntosh, 1982

The representer method solves the linear weak-constraint 4D-Var problem in observation space. For every scalar observation it computes a representer: the change of the whole trajectory over the window that one unit of influence from that observation causes, found by one run of the adjoint model backward and one forward run of the model forced by the background and model error covariances. The answer is the first guess plus a combination of the representers, and the pp coefficients solve one symmetric positive definite system (P+R)β=d(P + R)\beta = d, where PP holds the representers at the observation points and dd is the innovation. The method replaces a minimization over n(K+1)n(K + 1) unknowns by a linear system of size pp, and for a linear model the result is exact: it is the mean of the Kalman smoother with model error.

In plain words

Each measurement can only change the estimate in one fixed pattern over space and time. The pattern spreads out from the place and time of the measurement, forward along the model and also backward, and its shape comes from what is known about the errors of the start state and of the model. This pattern is the representer. The method computes the pattern of each measurement once. Then the best estimate is the first guess plus a weighted sum of these patterns, and the weights come from a small system of equations with one unknown per measurement. Few measurements and a large model make the method cheap.

The problem

Input. A linear model xk=Mkxk−1+ηkx_k = M_k x_{k-1} + \eta_k on the time levels 0,…,K0, \ldots, K with its adjoint, a background xbx^b with error covariance BB, model error covariances QkQ_k, and pp scalar observations yi=hi⊤xki+ϵiy_i = h_i^\top x_{k_i} + \epsilon_i with error covariance RR. Notation of Ide, Courtier, Ghil and Lorenc (1997).

Output. The trajectory x^0,…,x^K\hat x_0, \ldots, \hat x_K of the minimizer of the weak-constraint cost

J=12(x0−xb)⊤B−1(x0−xb)+∑k=1K12ηk⊤Qk−1ηk+12(y−Hx)⊤R−1(y−Hx),(Hx)i=hi⊤xki.J = \tfrac12 (x_0 - x^b)^\top B^{-1}(x_0 - x^b) + \sum_{k=1}^K \tfrac12 \eta_k^\top Q_k^{-1}\eta_k + \tfrac12 (y - \mathcal H x)^\top R^{-1}(y - \mathcal H x), \qquad (\mathcal H x)_i = h_i^\top x_{k_i} .

The algorithm

  1. REPRESENTER-METHOD(x^b, B, {Q_k}, {h_i, k_i, y_i}, R, M, M^T)
  2. 1x^f_0 <- x^b ; x^f_k <- M_k x^f_(k-1) ▷ first guess, no model error
  3. 2for i <- 1 to p do
  4. 3lambda <- adjoint run backward, forced by h_i at time k_i
  5. 4r_i(0) <- B lambda_0 ; r_i(k) <- M_k r_i(k-1) + Q_k lambda_k
  6. 5P_ji <- h_j^T r_i(k_j) for j = 1..p
  7. 6d_i <- y_i - h_i^T x^f_(k_i) for i = 1..p ▷ innovations
  8. 7beta <- solve (P + R) beta = d
  9. 8lambda <- adjoint run backward, forced by beta_i h_i at times k_i
  10. 9x_0 <- x^b + B lambda_0 ; x_k <- M_k x_(k-1) + Q_k lambda_k
  11. 10return x_0, ..., x_K

The representer rir_i of line L4 is the prior covariance of the trajectory with the observed quantity hi⊤xkih_i^\top x_{k_i}, so PP is the prior covariance of the observed quantities. Lines L8 and L9 form xf+∑iβirix^f + \sum_i \beta_i r_i with one more pair of sweeps, without storing the representers. The adjoint variable λ\lambda of line L8 is the same as in the Euler-Lagrange equations of JJ: the analysis increment of the initial state is Bλ0B\lambda_0 and the estimated model error is ηk=Qkλk\eta_k = Q_k\lambda_k.

Example

One step. Take x1=x0+η1x_1 = x_0 + \eta_1, xb=0x^b = 0, B=Q1=R=1B = Q_1 = R = 1 and one observation y1=3y_1 = 3 of x1x_1. The adjoint run gives λ1=λ0=1\lambda_1 = \lambda_0 = 1, and the forward run gives r(0)=1r(0) = 1 and r(1)=1+1=2r(1) = 1 + 1 = 2. So P=2P = 2, d=3d = 3 and β=3/(2+1)=1\beta = 3/(2 + 1) = 1, and the estimate is x^=βr=(1,2)\hat x = \beta r = (1, 2), the same as the result of weak-constraint 4D-Var on that page.

Two observations. Take the scalar model xk=12xk−1+ηkx_k = \tfrac12 x_{k-1} + \eta_k with K=2K = 2, xb=2x^b = 2, B=1B = 1, Q1=Q2=12Q_1 = Q_2 = \tfrac12, and the observations y=3y = 3 at time 1 and y=1y = 1 at time 2, each with error variance 12\tfrac12. The first guess is (2,1,12)(2, 1, \tfrac12) and the innovations are d=(2,12)d = (2, \tfrac12). The representers are

k=0k = 0 k=1k = 1 k=2k = 2
r1r_1 (observation at time 1) 1/21/2 3/43/4 3/83/8
r2r_2 (observation at time 2) 1/41/4 3/83/8 11/1611/16

so

P+R=(5/43/83/819/16),β=(70/43−4/43).P + R = \begin{pmatrix} 5/4 & 3/8 \\ 3/8 & 19/16 \end{pmatrix}, \qquad \beta = \begin{pmatrix} 70/43 \\ -4/43 \end{pmatrix}.

The estimate is x^=xf+β1r1+β2r2=(120/43,94/43,45/43)=(2.791,2.186,1.047)\hat x = x^f + \beta_1 r_1 + \beta_2 r_2 = (120/43, 94/43, 45/43) = (2.791, 2.186, 1.047). The second coefficient is negative: the first observation alone would pull x2x_2 above 1, and the second observation pulls it back. The reference code gives these values exactly in rational arithmetic.

Correctness

The proof shows by direct expansion of the sweeps that ri(k)=Cov(xk,xki)hir_i(k) = \mathrm{Cov}(x_k, x_{k_i})h_i under the prior, so P=Cov(Hx)P = \mathrm{Cov}(\mathcal H x), and that the estimate is E[x]+Cov(x,y)Cov(y)−1(y−E[y])E[x] + \mathrm{Cov}(x, y)\mathrm{Cov}(y)^{-1}(y - E[y]), the Gaussian conditional mean, which is also the minimizer of JJ (a theorem). The tests check the estimate and PP with exact rational arithmetic against a direct conditioning of the stacked trajectory, in floating point against a Kalman filter and smoother with model error to 10−910^{-9}, and they count the model and adjoint runs.

Proof: The representer expansion gives the exact minimizer of the linear weak-constraint costfull

Setting. The window has the time levels 0,…,K0, \ldots, K, and the model is linear, xk=Mkxk−1+ηkx_k = M_k x_{k-1} + \eta_k. Write Mk←j=MkMk−1⋯Mj+1M_{k \leftarrow j} = M_k M_{k-1} \cdots M_{j+1} for j≤kj \le k, with Mk←k=IM_{k \leftarrow k} = I, and C0=BC_0 = B, Cj=QjC_j = Q_j for j≥1j \ge 1. There are pp scalar observations yi=hi⊤xki+ϵiy_i = h_i^\top x_{k_i} + \epsilon_i, with ϵ∼N(0,R)\epsilon \sim N(0, R), and RR, BB and all QjQ_j are symmetric positive definite. The cost is

J(x0,η)=12(x0−xb)⊤B−1(x0−xb)+∑j=1K12ηj⊤Qj−1ηj+12(y−Hx)⊤R−1(y−Hx),J(x_0, \eta) = \tfrac12 (x_0 - x^b)^\top B^{-1}(x_0 - x^b) + \sum_{j=1}^K \tfrac12 \eta_j^\top Q_j^{-1}\eta_j + \tfrac12 (y - \mathcal H x)^\top R^{-1}(y - \mathcal H x),

where (Hx)i=hi⊤xki(\mathcal H x)_i = h_i^\top x_{k_i}. Give the control the prior x0∼N(xb,B)x_0 \sim N(x^b, B) and ηj∼N(0,Qj)\eta_j \sim N(0, Q_j), all independent. Then xk=Mk←0x0+∑j=1kMk←jηjx_k = M_{k \leftarrow 0} x_0 + \sum_{j=1}^k M_{k \leftarrow j}\eta_j, so

E[xk]=Mk←0xb=xkf,Cov(xk,xl)=∑j=0min⁡(k,l)Mk←jCjMl←j⊤.E[x_k] = M_{k \leftarrow 0} x^b = x^f_k, \qquad \mathrm{Cov}(x_k, x_l) = \sum_{j=0}^{\min(k, l)} M_{k \leftarrow j} C_j M_{l \leftarrow j}^\top .

xfx^f is the first guess of line L1.

Lemma 1 (a representer is a covariance). Lines L3 and L4 for observation ii compute ri(k)=Cov(xk,xki) hir_i(k) = \mathrm{Cov}(x_k, x_{k_i})\, h_i for every kk.

Proof. The backward sweep of line L3 starts from zero, adds hih_i at time kik_i and applies Mj⊤M_j^\top from time jj to time j−1j - 1. So λj=Mki←j⊤hi\lambda_j = M_{k_i \leftarrow j}^\top h_i for j≤kij \le k_i and λj=0\lambda_j = 0 for j>kij > k_i. The forward sweep of line L4 starts from r(0)=Bλ0r(0) = B\lambda_0 and sets r(k)=Mkr(k−1)+Qkλkr(k) = M_k r(k-1) + Q_k\lambda_k, so r(k)=∑j=0kMk←jCjλjr(k) = \sum_{j=0}^{k} M_{k \leftarrow j} C_j \lambda_j. Only the terms with j≤kij \le k_i are not zero, which gives ∑j=0min⁡(k,ki)Mk←jCjMki←j⊤hi=Cov(xk,xki)hi\sum_{j=0}^{\min(k, k_i)} M_{k \leftarrow j} C_j M_{k_i \leftarrow j}^\top h_i = \mathrm{Cov}(x_k, x_{k_i}) h_i. □\square

Corollary 2. Line L5 gives Pji=hj⊤ri(kj)=Cov(hj⊤xkj,hi⊤xki)P_{ji} = h_j^\top r_i(k_j) = \mathrm{Cov}(h_j^\top x_{k_j}, h_i^\top x_{k_i}), so P=Cov(Hx)P = \mathrm{Cov}(\mathcal H x). It is symmetric positive semidefinite, and P+RP + R is positive definite, so line L7 has a unique solution.

Lemma 3 (the combined sweep). Lines L8 and L9 compute x^k=xkf+∑iβiri(k)\hat x_k = x^f_k + \sum_i \beta_i r_i(k).

Proof. The backward sweep is linear in the forcing, so the forcing ∑iβihi\sum_i \beta_i h_i at the times kik_i gives λ=∑iβiλ(i)\lambda = \sum_i \beta_i \lambda^{(i)}. The forward sweep from xbx^b is the forward sweep from 00 plus the model run from xbx^b, which is xfx^f, and the forward sweep from 00 is linear in λ\lambda, which gives ∑iβiri\sum_i \beta_i r_i. □\square

Theorem 4. The trajectory x^\hat x returned by line L10 is the trajectory of the unique minimizer of JJ, and x^k=E[xk∣y]\hat x_k = E[x_k \mid y] for every kk.

Proof. The map from the control z=(x0,η1,…,ηK)z = (x_0, \eta_1, \ldots, \eta_K) to the trajectory is linear and invertible, and the prior density of zz times the likelihood of yy is proportional to e−J(z)e^{-J(z)}. JJ is a strictly convex quadratic, so the posterior of zz is Gaussian, its mean is the unique minimizer of JJ, and the trajectory of the minimizer is E[x∣y]E[x \mid y]. For jointly Gaussian xx and y=Hx+ϵy = \mathcal H x + \epsilon, with ϵ\epsilon independent of xx,

E[xk∣y]=E[xk]+Cov(xk,y) Cov(y)−1(y−E[y]).E[x_k \mid y] = E[x_k] + \mathrm{Cov}(x_k, y)\,\mathrm{Cov}(y)^{-1}(y - E[y]) .

Here E[y]=HxfE[y] = \mathcal H x^f, so y−E[y]=dy - E[y] = d of line L6; Cov(y)=P+R\mathrm{Cov}(y) = P + R by Corollary 2; and column ii of Cov(xk,y)\mathrm{Cov}(x_k, y) is Cov(xk,xki)hi=ri(k)\mathrm{Cov}(x_k, x_{k_i}) h_i = r_i(k) by Lemma 1. So E[xk∣y]=xkf+∑iri(k)βiE[x_k \mid y] = x^f_k + \sum_i r_i(k) \beta_i with (P+R)β=d(P + R)\beta = d, which is x^k\hat x_k by Lemma 3. □\square

Remark (the Euler-Lagrange form). At the minimizer, β=R−1(y−Hx^)\beta = R^{-1}(y - \mathcal H\hat x), x^0=xb+Bλ0\hat x_0 = x^b + B\lambda_0 and η^k=Qkλk\hat\eta_k = Q_k\lambda_k, where λ\lambda is the adjoint of the weighted residuals. This is the form in which Bennett (2002) derives the method, and it follows from Theorem 4: y−Hx^=d−Pβ=Rβy - \mathcal H\hat x = d - P\beta = R\beta.

Termination. The algorithm runs p+1p + 1 backward sweeps and p+1p + 1 forward sweeps of KK steps, plus the first guess, and one dense solve of size pp. It always stops.

Summary. Each representer is the prior covariance of the trajectory with one observed quantity, the representer matrix is the prior covariance of the observations, and the representer expansion with the coefficients from (P+R)β=d(P + R)\beta = d is the Gaussian conditional mean, which is the minimizer of the weak-constraint cost. The tests check this with exact rational arithmetic against a direct conditioning of the stacked trajectory, and in floating point against a Kalman filter and smoother with model error. ■\blacksquare

Complexity

Each representer costs one adjoint run and one forward run, Θ(K(c+n2))\Theta(K(c + n^2)) with dense QkQ_k, and filling column ii of PP costs Θ(pn)\Theta(pn). With the dense solve of size pp and the final pair of sweeps the time is Θ(pK(c+n2)+p2n+p3)\Theta(pK(c + n^2) + p^2 n + p^3). The memory is one trajectory, the observation vectors and PP, Θ(Kn+pn+p2)\Theta(Kn + pn + p^2). So the cost grows with the number of observations, not with the number n(K+1)n(K + 1) of unknowns of the primal problem: the method suits a large model with few observations, and is too expensive for the millions of observations of weather prediction unless the system is solved by iterations (see the variants).

Properties

  • Exact for linear models. The result is the minimizer of the weak-constraint cost and the Kalman smoother mean with model error (a theorem).
  • Dual form. The unknowns are the pp coefficients in observation space. Strong-constraint 4D-Var has the same dual with Q=0Q = 0, and the optimal interpolation formula is the case K=0K = 0.
  • A covariance in each column. The representers are prior covariances of the trajectory with the observed quantities, so they show which parts of the window and of the state each observation can correct.
  • Statistics for free. P+RP + R is the covariance of the innovations, so d⊤(P+R)−1dd^\top(P + R)^{-1}d has a χ2\chi^2 distribution with pp degrees of freedom when the error statistics are right, a test of BB, QQ and RR (a theorem for Gaussian errors).
  • Linear only. For a nonlinear model the method applies to the linearized problem inside outer loops, as in incremental 4D-Var.

Variants and improvements

  • Iterative (indirect) solution. Do not form PP. Solve (P+R)β=d(P + R)\beta = d by the conjugate gradient method, where each product PvP v costs one adjoint run forced by vv and one forward run. The cost is then one pair of runs per iteration instead of one per observation (Bennett 2002).
  • Outer loops for nonlinear models. Linearize the model around the current estimate, solve the linear problem with representers, and repeat.
  • Strong constraint. With Qk=0Q_k = 0 the same algorithm gives the strong-constraint 4D-Var solution in its dual form, which is the physical space form used in some weather systems.
  • Representer analysis of an observing network. The eigenvectors of R−1/2PR−1/2R^{-1/2} P R^{-1/2} show which combinations of the observations the prior can resolve, a tool for the design of observing systems.

When to use it

Use the representer method for a linear or linearized model when the number of observations is much smaller than the number of unknowns n(K+1)n(K + 1) of the weak-constraint problem, as in ocean tide and circulation problems with sparse data, and when the representers themselves are of interest. With many observations, use the iterative form, or solve the primal problem with weak-constraint 4D-Var.

Pitfalls

  • An adjoint that is not the transpose (lines L3 and L8). Then PP is not symmetric and is not a covariance, and the estimate is wrong. Check the adjoint with the dot product test.
  • The forward run without model error (line L4). Dropping QkλkQ_k \lambda_k gives the strong-constraint representers, not the weak-constraint ones.
  • Forming PP when pp is large (line L5). The cost of pp pairs of runs and the p3p^3 solve both grow fast; use the iterative form.
  • An ill-conditioned P+RP + R (line L7). With small observation errors and nearly redundant observations the system is close to singular, and the solve loses accuracy.
  • Two separate first guesses. The innovation of line L6 must come from the same first guess that line L9 starts from, the model run from xbx^b without model error.

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.

representer_method.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/representer-method/. The authors are listed in prov/6YYQY7.jsonl.

"""The representer method for weak-constraint variational assimilation.

Notation of Ide, Courtier, Ghil and Lorenc (1997). The window has the time
levels 0..K, the model is linear with model error, x_k = M_k x_(k-1) + eta_k,
and the cost is

    J = 1/2 (x_0 - x^b)^T B^-1 (x_0 - x^b) + sum_k 1/2 eta_k^T Q_k^-1 eta_k
      + 1/2 (y - H x)^T R^-1 (y - H x),

where y stacks all the scalar observations y_i = h_i^T x_(k_i) + e_i and R
is their error covariance. The minimizer is the first guess (the model run
from x^b with no model error) plus a combination sum_i beta_i r_i of the
representers r_i, one per observation. The representer r_i is found by one
adjoint run forced by h_i at time k_i and one forward run forced by B and
Q_k times the adjoint variable. The coefficients solve (P + R) beta = d,
with P_ji = h_j^T r_i(k_j) and d the innovation of the first guess.

The model is given by two functions:
    step(k, x)        M_k x, for x = x_(k-1)
    adjoint(k, lam)   M_k^T lam
B, Q[k] (k = 1..K, Q[0] is not used), the observation operators and the data
may hold Fraction entries; then every result is exact.
"""

import scimat


def observation_list(obs):
    """Return [(k_i, h_i, y_i)] for obs = {k: (H_k, y_k, R_k)} and the block diagonal R."""
    items = []
    blocks = []
    for k in sorted(obs):
        H, y, R = obs[k]
        for row, value in zip(H, y):
            items.append((k, row, value))
        blocks.append(R)
    p = len(items)
    Rall = scimat.zeros(p)
    i = 0
    for R in blocks:
        for a in range(len(R)):
            for b in range(len(R)):
                Rall[i + a][i + b] = R[a][b]
        i += len(R)
    return items, Rall


def backward(forcing, adjoint, K, n):
    """Return [lam_0, ..., lam_K] with lam_k = M_(k+1)^T lam_(k+1) + forcing at time k."""
    lam = [None] * (K + 1)
    v = [0] * n
    for k in range(K, -1, -1):
        if k in forcing:
            v = scimat.add(v, forcing[k])
        lam[k] = v
        if k > 0:
            v = adjoint(k, v)
    return lam


def forward(start, lam, B, Q, step, K):
    """Return [x_0, ..., x_K] with x_0 = start + B lam_0 and x_k = M_k x_(k-1) + Q_k lam_k."""
    xs = [scimat.add(start, scimat.matvec(B, lam[0]))]
    for k in range(1, K + 1):
        xs.append(scimat.add(step(k, xs[-1]), scimat.matvec(Q[k], lam[k])))
    return xs


def representer_method(xb, B, Q, obs, step, adjoint, K):
    """Return (estimate [x_0, ..., x_K], beta, representer matrix P)."""
    n = len(xb)
    items, R = observation_list(obs)
    p = len(items)
    zero = [0] * n
    first = [list(xb)]  # @line L1
    for k in range(1, K + 1):
        first.append(step(k, first[-1]))
    P = scimat.zeros(p)
    for i, (ki, hi, _) in enumerate(items):  # @line L2
        lam = backward({ki: list(hi)}, adjoint, K, n)  # @line L3
        r = forward(zero, lam, B, Q, step, K)  # @line L4
        for j, (kj, hj, _) in enumerate(items):  # @line L5
            P[j][i] = scimat.dot(hj, r[kj])
    d = [yi - scimat.dot(hi, first[ki]) for ki, hi, yi in items]  # @line L6
    beta = scimat.solve(scimat.add(P, R), d)  # @line L7
    forcing = {}
    for (ki, hi, _), bi in zip(items, beta):  # @line L8
        forcing[ki] = scimat.add(forcing.get(ki, zero), scimat.scale(bi, hi))
    lam = backward(forcing, adjoint, K, n)
    estimate = forward(list(xb), lam, B, Q, step, K)  # @line L9
    return estimate, beta, P  # @line L10


def linear_model(M):
    """Return (step, adjoint) for the linear model x_k = M x_(k-1)."""
    Mt = scimat.transpose(M)
    return (lambda k, x: scimat.matvec(M, x), lambda k, lam: scimat.matvec(Mt, lam))
scimat.py 227 lines
# SPDX-License-Identifier: MIT
# Shared helper of the scientific-computing pages of https://algorithm.tamnd.com/. The authors are listed in prov/.

"""Small dense linear algebra and error norms for the scientific-computing pages.

A matrix is a list of rows and a vector is a list. Entries may be int,
float or fractions.Fraction. The routines that do not take a square root
(solve, inv, det and the arithmetic) keep Fraction entries exact.
cholesky, cholesky_solve and norm2 take square roots and return floats.

API (fixed; other pages copy this file byte for byte):
    zeros(m, n=None)        m by n zero matrix (n = m if not given)
    eye(n)                  n by n identity
    add(A, B), sub(A, B)    entrywise sum and difference (vectors or matrices)
    scale(c, A)             c times A (vector or matrix)
    matmul(A, B)            matrix product
    matvec(A, x)            matrix times vector
    transpose(A)            transpose
    dot(x, y)               inner product of two vectors
    norm2(x)                Euclidean norm of a vector, as a float
    outer(x, y)             outer product x y^T
    solve(A, b)             Gaussian elimination with partial pivoting;
                            b is a vector or a matrix of right sides
    inv(A)                  inverse of A
    det(A)                  determinant of A
    cholesky(A)             lower triangular L with A = L L^T (floats)
    cholesky_solve(L, b)    solve L L^T x = b for a vector b
    err_l1(e, dx=1)         sum |e_j| dx
    err_l2(e, dx=1)         sqrt(sum e_j^2 dx), as a float
    err_linf(e, dx=1)       max |e_j| (dx is not used)
    observed_order(errors)  [log2(E_i / E_(i+1)) for successive errors]
"""

import math


def zeros(m, n=None):
    """Return an m by n matrix of zeros (n = m if n is None)."""
    if n is None:
        n = m
    return [[0] * n for _ in range(m)]


def eye(n):
    """Return the n by n identity matrix."""
    out = zeros(n, n)
    for i in range(n):
        out[i][i] = 1
    return out


def _is_matrix(a):
    return len(a) > 0 and isinstance(a[0], list)


def add(a, b):
    """Return a + b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x + y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x + y for x, y in zip(a, b)]


def sub(a, b):
    """Return a - b for two vectors or two matrices of the same shape."""
    if _is_matrix(a):
        return [[x - y for x, y in zip(ra, rb)] for ra, rb in zip(a, b)]
    return [x - y for x, y in zip(a, b)]


def scale(c, a):
    """Return c times a, for a vector or a matrix a."""
    if _is_matrix(a):
        return [[c * x for x in row] for row in a]
    return [c * x for x in a]


def transpose(a):
    """Return the transpose of the matrix a."""
    return [list(col) for col in zip(*a)]


def matmul(a, b):
    """Return the matrix product a b."""
    bt = transpose(b)
    return [[sum(x * y for x, y in zip(row, col)) for col in bt] for row in a]


def matvec(a, x):
    """Return the product of the matrix a and the vector x."""
    return [sum(aij * xj for aij, xj in zip(row, x)) for row in a]


def dot(x, y):
    """Return the inner product of the vectors x and y."""
    return sum(a * b for a, b in zip(x, y))


def norm2(x):
    """Return the Euclidean norm of the vector x, as a float."""
    return math.sqrt(float(dot(x, x)))


def outer(x, y):
    """Return the outer product x y^T as a matrix."""
    return [[a * b for b in y] for a in x]


def _eliminate(a, rhs):
    """Reduce a to upper triangular form with partial pivoting.

    a is a copy of the square matrix, rhs a list of right side rows (one
    row per row of a) that receives the same row operations. Return the
    number of row swaps. Raise ValueError if a pivot is zero.
    """
    n = len(a)
    swaps = 0
    for k in range(n):
        p = max(range(k, n), key=lambda i: abs(a[i][k]))
        if a[p][k] == 0:
            raise ValueError("matrix is singular")
        if p != k:
            a[k], a[p] = a[p], a[k]
            rhs[k], rhs[p] = rhs[p], rhs[k]
            swaps += 1
        for i in range(k + 1, n):
            f = a[i][k] / a[k][k]
            if f == 0:
                continue
            for j in range(k, n):
                a[i][j] -= f * a[k][j]
            for j in range(len(rhs[i])):
                rhs[i][j] -= f * rhs[k][j]
    return swaps


def solve(a, b):
    """Solve a x = b by Gaussian elimination with partial pivoting.

    b is a vector (the result is a vector) or a matrix with one column per
    right side (the result is a matrix). Fraction entries stay exact.
    Raise ValueError if a is singular.
    """
    n = len(a)
    work = [list(row) for row in a]
    vector = not _is_matrix(b)
    rhs = [[v] for v in b] if vector else [list(row) for row in b]
    _eliminate(work, rhs)
    m = len(rhs[0]) if n else 0
    x = [[0] * m for _ in range(n)]
    for i in range(n - 1, -1, -1):
        for j in range(m):
            s = rhs[i][j]
            for k in range(i + 1, n):
                s -= work[i][k] * x[k][j]
            x[i][j] = s / work[i][i]
    if vector:
        return [row[0] for row in x]
    return x


def inv(a):
    """Return the inverse of the square matrix a."""
    return solve(a, eye(len(a)))


def det(a):
    """Return the determinant of the square matrix a (0 if singular)."""
    work = [list(row) for row in a]
    rhs = [[] for _ in a]
    try:
        swaps = _eliminate(work, rhs)
    except ValueError:
        return 0
    d = -1 if swaps % 2 else 1
    for i in range(len(a)):
        d *= work[i][i]
    return d


def cholesky(a):
    """Return the lower triangular L with a = L L^T, in floats.

    Raise ValueError if a is not symmetric positive definite.
    """
    n = len(a)
    low = [[0.0] * n for _ in range(n)]
    for j in range(n):
        s = float(a[j][j]) - sum(low[j][k] ** 2 for k in range(j))
        if s <= 0.0:
            raise ValueError("matrix is not positive definite")
        low[j][j] = math.sqrt(s)
        for i in range(j + 1, n):
            t = float(a[i][j]) - sum(low[i][k] * low[j][k] for k in range(j))
            low[i][j] = t / low[j][j]
    return low


def cholesky_solve(low, b):
    """Solve L L^T x = b, with L from cholesky, for a vector b."""
    n = len(low)
    y = [0.0] * n
    for i in range(n):
        y[i] = (float(b[i]) - sum(low[i][k] * y[k] for k in range(i))) / low[i][i]
    x = [0.0] * n
    for i in range(n - 1, -1, -1):
        x[i] = (y[i] - sum(low[k][i] * x[k] for k in range(i + 1, n))) / low[i][i]
    return x


def err_l1(e, dx=1):
    """Return the discrete L1 norm sum |e_j| dx."""
    return sum(abs(v) for v in e) * dx


def err_l2(e, dx=1):
    """Return the discrete L2 norm sqrt(sum e_j^2 dx), as a float."""
    return math.sqrt(float(sum(v * v for v in e) * dx))


def err_linf(e, dx=1):
    """Return the max norm max |e_j|. dx is accepted for a uniform call and not used."""
    return max(abs(v) for v in e)


def observed_order(errors):
    """Return [log2(E_i / E_(i+1))] for a list of errors on meshes h, h/2, h/4, ..."""
    return [math.log2(float(errors[i]) / float(errors[i + 1])) for i in range(len(errors) - 1)]
test_representer_method.py 190 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/representer-method/. The authors are listed in prov/6YYQY7.jsonl.

import random
from fractions import Fraction

import scimat
from representer_method import linear_model, representer_method


def random_spd(rng, n, shift=0.5):
    L = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(n)]
    S = scimat.matmul(L, scimat.transpose(L))
    for i in range(n):
        S[i][i] += shift
    return S


def frac(rng, lo=-3, hi=3, den=4):
    return Fraction(rng.randint(lo * den, hi * den), den)


def frac_spd(rng, n):
    L = [[frac(rng, -1, 1) for _ in range(n)] for _ in range(n)]
    S = scimat.matmul(L, scimat.transpose(L))
    for i in range(n):
        S[i][i] += Fraction(1, 2)
    return S


def kalman_and_rts(xb, B, M, Q, obs, K):
    """Oracle: Kalman filter and Rauch-Tung-Striebel smoother means with model error Q[k]."""
    Mt = scimat.transpose(M)
    xf, Pf, xa, Pa = [], [], [], []
    x, P = list(xb), B
    for k in range(K + 1):
        if k > 0:
            x = scimat.matvec(M, xa[-1])
            P = scimat.add(scimat.matmul(scimat.matmul(M, Pa[-1]), Mt), Q[k])
        xf.append(x)
        Pf.append(P)
        if k in obs:
            H, y, R = obs[k]
            S = scimat.add(scimat.matmul(scimat.matmul(H, P), scimat.transpose(H)), R)
            G = scimat.transpose(scimat.solve(S, scimat.matmul(H, P)))
            x = scimat.add(x, scimat.matvec(G, scimat.sub(y, scimat.matvec(H, x))))
            P = scimat.sub(P, scimat.matmul(G, scimat.matmul(H, P)))
        xa.append(x)
        Pa.append(P)
    xs = [None] * (K + 1)
    xs[K] = xa[K]
    for k in range(K - 1, -1, -1):
        C = scimat.transpose(scimat.solve(Pf[k + 1], scimat.matmul(M, Pa[k])))
        xs[k] = scimat.add(xa[k], scimat.matvec(C, scimat.sub(xs[k + 1], xf[k + 1])))
    return xa, xs


def gaussian_conditioning(xb, B, M, Q, obs, K):
    """Brute force: condition the stacked trajectory on all observations at once.

    Return (E[x | y] as a list of states, prior covariance of the stacked observations).
    """
    n = len(xb)
    N = n * (K + 1)
    # T maps z = (x_0, eta_1, ..., eta_K) to the stacked trajectory.
    T = scimat.zeros(N)
    powers = [scimat.eye(n)]
    for _ in range(K):
        powers.append(scimat.matmul(M, powers[-1]))
    for k in range(K + 1):
        for j in range(k + 1):
            blk = powers[k - j]
            for a in range(n):
                for b in range(n):
                    T[k * n + a][j * n + b] = blk[a][b]
    C = scimat.zeros(N)
    for j in range(K + 1):
        cov = B if j == 0 else Q[j]
        for a in range(n):
            for b in range(n):
                C[j * n + a][j * n + b] = cov[a][b]
    mean_z = list(xb) + [0] * (n * K)
    mean = scimat.matvec(T, mean_z)
    cov = scimat.matmul(scimat.matmul(T, C), scimat.transpose(T))
    rows, y, blocks = [], [], []
    for k in sorted(obs):
        H, yk, R = obs[k]
        for row, v in zip(H, yk):
            full = [0] * N
            for a in range(n):
                full[k * n + a] = row[a]
            rows.append(full)
            y.append(v)
        blocks.append(R)
    p = len(rows)
    Rall = scimat.zeros(p)
    i = 0
    for R in blocks:
        for a in range(len(R)):
            for b in range(len(R)):
                Rall[i + a][i + b] = R[a][b]
        i += len(R)
    Hs = rows
    HC = scimat.matmul(Hs, cov)
    S = scimat.matmul(HC, scimat.transpose(Hs))
    gain_t = scimat.solve(scimat.add(S, Rall), HC)
    post = scimat.add(mean, scimat.matvec(scimat.transpose(gain_t), scimat.sub(y, scimat.matvec(Hs, mean))))
    return [post[k * n : (k + 1) * n] for k in range(K + 1)], S


def close(a, b, tol):
    return all(abs(u - v) <= tol * (1 + abs(v)) for u, v in zip(a, b))


def test_scalar_check_value():
    step, adj = linear_model([[1]])
    est, beta, P = representer_method([0], [[1]], [None], {0: ([[1]], [1], [[1]])}, step, adj, 0)
    assert est[0][0] == Fraction(1, 2) and P == [[1]]


def test_page_example():
    # x_1 = x_0 + eta_1, x^b = 0, B = Q = R = 1, y_1 = 3: r = (1, 2), P = 2, beta = 1, estimate (1, 2).
    step, adj = linear_model([[1]])
    est, beta, P = representer_method([0], [[1]], [None, [[1]]], {1: ([[1]], [3], [[1]])}, step, adj, 1)
    assert P == [[2]] and beta == [1] and est == [[1], [2]]


def test_exact_against_gaussian_conditioning():
    rng = random.Random(71)
    for _ in range(12):
        n = rng.randint(1, 3)
        K = rng.randint(0, 3)
        M = [[frac(rng, -1, 1) + (1 if i == j else 0) for j in range(n)] for i in range(n)]
        B = frac_spd(rng, n)
        Q = [None] + [frac_spd(rng, n) for _ in range(K)]
        xb = [frac(rng) for _ in range(n)]
        obs = {}
        for k in range(K + 1):
            if rng.random() < 0.7 or k == K:
                p = rng.randint(1, 2)
                obs[k] = ([[frac(rng, -1, 1) for _ in range(n)] for _ in range(p)], [frac(rng) for _ in range(p)], frac_spd(rng, p))
        step, adj = linear_model(M)
        est, beta, P = representer_method(xb, B, Q, obs, step, adj, K)
        ref, S = gaussian_conditioning(xb, B, M, Q, obs, K)
        assert est == ref
        assert P == S  # the representer matrix is the prior covariance of the observations


def test_equals_kalman_smoother_with_q():
    rng = random.Random(72)
    for _ in range(30):
        n = rng.randint(1, 3)
        K = rng.randint(1, 6)
        M = [[(1.0 if i == j else 0.0) + 0.3 * rng.uniform(-1, 1) for j in range(n)] for i in range(n)]
        B = random_spd(rng, n)
        Q = [None] + [random_spd(rng, n, 0.2) for _ in range(K)]
        xb = [rng.uniform(-2, 2) for _ in range(n)]
        obs = {}
        for k in range(K + 1):
            if rng.random() < 0.6 or k == K:
                p = rng.randint(1, 3)
                obs[k] = ([[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)], [rng.uniform(-2, 2) for _ in range(p)], random_spd(rng, p))
        step, adj = linear_model(M)
        est, _, _ = representer_method(xb, B, Q, obs, step, adj, K)
        xa, xs = kalman_and_rts(xb, B, M, Q, obs, K)
        for k in range(K + 1):
            assert close(est[k], xs[k], 1e-9)


def test_one_adjoint_and_one_forward_run_per_observation():
    rng = random.Random(73)
    n, K = 2, 5
    M = [[1.0, 0.1], [-0.1, 1.0]]
    step0, adj0 = linear_model(M)
    calls = {"step": 0, "adjoint": 0}

    def step(k, x):
        calls["step"] += 1
        return step0(k, x)

    def adj(k, lam):
        calls["adjoint"] += 1
        return adj0(k, lam)

    obs = {1: ([[1.0, 0.0]], [0.5], [[0.1]]), 3: ([[0.0, 1.0], [1.0, 1.0]], [0.2, -0.4], [[0.1, 0.0], [0.0, 0.2]]), 5: ([[1.0, -1.0]], [1.0], [[0.3]])}
    p = 4
    Q = [None] + [[[0.05, 0.0], [0.0, 0.05]] for _ in range(K)]
    representer_method([rng.uniform(-1, 1) for _ in range(n)], [[1.0, 0.0], [0.0, 1.0]], Q, obs, step, adj, K)
    assert calls["adjoint"] == (p + 1) * K
    assert calls["step"] == (p + 2) * K

History

Bennett and McIntosh used representers in 1982 to solve a variational inverse problem for open ocean tides, in which the tidal equations hold only as weak constraints. Bennett developed the method into a general tool for ocean inverse problems in his books of 1992 and 2002, with the iterative form that avoids the computation of all representers. Egbert, Bennett and Foreman (1994) applied it to estimate global ocean tides from TOPEX/POSEIDON altimeter data.

References

  1. Andrew F. Bennett, Inverse Modeling of the Ocean and Atmosphere, Cambridge University Press, 2002, the representer solution of the weak-constraint problem and its indirect solution by iterations
  2. Andrew F. Bennett, Inverse Methods in Physical Oceanography, Cambridge University Press, 1992, the generalized inverse of a linear model and its representer expansion
  3. A. F. Bennett and P. C. McIntosh, Open ocean modeling as an inverse problem, tidal theory, Journal of Physical Oceanography 12(10) (1982) 1004-1018, the variational tidal inverse problem
  4. G. D. Egbert, A. F. Bennett and M. G. G. Foreman, TOPEX/POSEIDON tides estimated using a global inverse model, Journal of Geophysical Research 99(C12) (1994) 24821-24852, a global tidal inverse solution with representers and altimeter data
  5. K. Ide, P. Courtier, M. Ghil and A. C. Lorenc, Unified notation for data assimilation, operational, sequential and variational, Journal of the Meteorological Society of Japan 75(1B) (1997) 181-189, the notation used here

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