Algorithm Search⌘K

Algorithmadvanced

Weak-constraint 4D-Var

Allows model error terms at each time in the window, penalized by their covariance, so the analysis need not follow the model exactly.

Time
Θ(K n^3 + k (K c + m (K s + K n^2 + n p))) worst
Space
Θ(K n^2) extra
Where
K = the number of model steps in the window; c = the cost of one full model step; k = the number of outer loops; m = the number of conjugate gradient steps per outer loop; n = the state dimension; p = the total number of observations; s = the cost of one tangent linear or adjoint step
Properties
deterministic
Origin
Yannick Trémolet, 2006

Weak-constraint 4D-Var removes the assumption of 4D-Var that the model is perfect. It adds a model error term ηk\eta_k to every step of the window, xk=Mk(xk−1)+ηkx_k = M_k(x_{k-1}) + \eta_k, and minimizes a cost over the initial state and all the model errors together, with a penalty 12ηk⊤Qk−1ηk\tfrac12 \eta_k^\top Q_k^{-1} \eta_k for each step. The analysis can then leave the model trajectory where the observations ask for it, by an amount that the model error covariance QkQ_k controls. For a linear model and Gaussian errors the minimizer is the mean of the Rauch-Tung-Striebel smoother with process noise QkQ_k, so weak-constraint 4D-Var is the variational form of the full Kalman smoother. As all QkQ_k tend to zero it becomes strong-constraint 4D-Var.

In plain words

Ordinary 4D-Var trusts the weather model completely: the answer must be an exact run of the model, and only the start state can change. But every model has errors. Weak-constraint 4D-Var lets the answer move away from the model at each time step by a small push. Each push costs something, and pushes that the model is known to need are cheap, while others are expensive. The method finds the start state and all the pushes that together give the best balance between the background, the model and the measurements. The price is a much larger search, because there is now one unknown state for every time step instead of one in total.

The problem

Input. A background xbx^b with error covariance BB, model steps MkM_k with their tangent linear and adjoint models, model error covariances QkQ_k for k=1,…,Kk = 1, \ldots, K, and observations yky_k with operators HkH_k and error covariances RkR_k at the times k∈Tk \in T of the window 0,…,K0, \ldots, K. Notation of Ide, Courtier, Ghil and Lorenc (1997).

Output. The control z=(x0,η1,…,ηK)z = (x_0, \eta_1, \ldots, \eta_K) that minimizes

J(z)=12(x0−xb)⊤B−1(x0−xb)+∑k=1K12ηk⊤Qk−1ηk+∑k∈T12dk⊤Rk−1dk,dk=yk−Hkxk,J(z) = \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 + \sum_{k \in T} \tfrac12 d_k^\top R_k^{-1} d_k, \qquad d_k = y_k - H_k x_k,

with xk=Mk(xk−1)+ηkx_k = M_k(x_{k-1}) + \eta_k, and the trajectory x0,…,xKx_0, \ldots, x_K of that control. This is the model error forcing form. Trémolet (2006) also describes the state form, with the states x0,…,xKx_0, \ldots, x_K as the control, and a form in which a constant bias is the control.

The algorithm

  1. WEAK-4DVAR(x^b, B, {Q_k}, {y_k, H_k, R_k}, M, M', M'^T)
  2. 1x_0 <- x^b ; eta_k <- 0 for k = 1..K
  3. 2for outer <- 1 to max_outer do
  4. 3x_k <- M_k(x_(k-1)) + eta_k for k = 1..K
  5. 4d_k <- y_k - H_k x_k for k in T
  6. 5mu_k <- sensitivity to x_k from one adjoint run forced by -H_k^T R_k^-1 d_k
  7. g <- (B^-1 (x_0 - x^b) + mu_0, Q_1^-1 eta_1 + mu_1, ..., Q_K^-1 eta_K + mu_K)
  8. 6A v = D v + G^T H^T R^-1 H G v ▷ one tangent linear run and one adjoint run
  9. 7dz <- solve A dz = -g by conjugate gradients
  10. 8(x_0, eta) <- (x_0, eta) + dz
  11. 9if |dz| <= tol (1 + |z|) then break
  12. 10return x_0, ..., x_K

Line L5 is the same backward sweep as in 4D-Var, but the gradient now has a part for every step: the sensitivity μk\mu_k to the state at time kk is also the sensitivity to the model error ηk\eta_k, because ηk\eta_k adds to xkx_k directly. In line L6, GG maps an increment (δx0,δη1,…,δηK)(\delta x_0, \delta\eta_1, \ldots, \delta\eta_K) to the trajectory increments δxk=Mk′δxk−1+δηk\delta x_k = M_k' \delta x_{k-1} + \delta\eta_k, and DD is the block diagonal matrix of B−1B^{-1} and the Qk−1Q_k^{-1}. Each outer loop is a Gauss-Newton step, as in incremental 4D-Var, with a control K+1K + 1 times larger.

Example

One step. Take x1=x0+η1x_1 = x_0 + \eta_1 (K=1K = 1), xb=0x^b = 0, B=Q1=1B = Q_1 = 1, and one observation y1=3y_1 = 3 with H=R=1H = R = 1. The cost is

J(x0,η1)=12x02+12η12+12(3−x0−η1)2.J(x_0, \eta_1) = \tfrac12 x_0^2 + \tfrac12 \eta_1^2 + \tfrac12 (3 - x_0 - \eta_1)^2 .

Both partial derivatives are zero when x0=η1=3−x0−η1x_0 = \eta_1 = 3 - x_0 - \eta_1, so x0=η1=1x_0 = \eta_1 = 1 and x1=2x_1 = 2. The misfit of 2 between background and observation is shared equally between the initial state and the model error, because B=Q1B = Q_1. As a check, the prior variance of x1x_1 is B+Q1=2B + Q_1 = 2, so the Kalman filter gives x1=2⋅3/(2+1)=2x_1 = 2 \cdot 3 / (2 + 1) = 2. With strong constraint (η1=0\eta_1 = 0) the cost is 12x02+12(3−x0)2\tfrac12 x_0^2 + \tfrac12 (3 - x_0)^2, with the minimizer x0=x1=1.5x_0 = x_1 = 1.5: the analysis at time 1 is pulled less towards the observation, because the prior variance of x1x_1 is only B=1B = 1.

A model with a missing forcing. In a twin test with the Lorenz-63 model, 40 forward Euler steps with Δt=0.01\Delta t = 0.01, the truth has a forcing of 0.050.05 per step on the third component that the model does not have. All three components are observed every 4 steps with error standard deviation 0.2, and B=IB = I. Over six seeds the mean error of the analysis at the end of the window is 0.20 for weak-constraint 4D-Var with Qk=0.01IQ_k = 0.01 I and 0.73 for strong constraint, with 6 to 8 and 8 to 9 outer loops (a measurement). The strong-constraint analysis must fit the drift of the truth with the initial state alone, and the error grows towards the end of the window.

Correctness

The proof shows that the backward sweep gives the exact gradient over x0x_0 and every ηk\eta_k, that the inner matrix AA is symmetric positive definite, and that each outer loop is a Gauss-Newton step (a theorem). For a linear model one outer loop gives the minimizer, and the prior times the likelihood of the control is proportional to e−Je^{-J}, so the trajectory of the minimizer is E[xk∣y]E[x_k \mid y] at every time, the Rauch-Tung-Striebel smoother mean with model error QkQ_k (a theorem). The tests check this to 10−810^{-8} against a separate Kalman filter and smoother on random problems, the gradient against finite differences on Lorenz-63, the approach to strong constraint as Q→0Q \to 0, and the stationarity of the nonlinear result.

Proof: Weak-constraint 4D-Var has the exact adjoint gradient, and for a linear model its minimizer is the Kalman smoother with model errorfull

Setting. The window has the time levels 0,…,K0, \ldots, K. The model steps MkM_k are differentiable with Jacobians Mk′(x)M_k'(x), and the trajectory of the control z=(x0,η1,…,ηK)z = (x_0, \eta_1, \ldots, \eta_K) is xk=Mk(xk−1)+ηkx_k = M_k(x_{k-1}) + \eta_k. BB, all QkQ_k and all RkR_k are symmetric positive definite, and TT is the set of times with observations yk=Hkxk+ϵky_k = H_k x_k + \epsilon_k. The cost is

J(z)=12(x0−xb)⊤B−1(x0−xb)+∑k=1K12ηk⊤Qk−1ηk+∑k∈T12dk⊤Rk−1dk,dk=yk−Hkxk.J(z) = \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 + \sum_{k \in T} \tfrac12 d_k^\top R_k^{-1} d_k, \qquad d_k = y_k - H_k x_k .

Lemma 1 (gradient). Let fk=−Hk⊤Rk−1dkf_k = -H_k^\top R_k^{-1} d_k for k∈Tk \in T and fk=0f_k = 0 otherwise, and let μK=fK\mu_K = f_K, μk=fk+Mk+1′(xk)⊤μk+1\mu_k = f_k + M_{k+1}'(x_k)^\top \mu_{k+1} (the values the backward sweep of line L5 stores after the forcing at each time). Then

∇x0J=B−1(x0−xb)+μ0,∇ηkJ=Qk−1ηk+μk(k=1,…,K).\nabla_{x_0} J = B^{-1}(x_0 - x^b) + \mu_0, \qquad \nabla_{\eta_k} J = Q_k^{-1}\eta_k + \mu_k \quad (k = 1, \ldots, K).

Proof. μk\mu_k is the gradient of the observation term with respect to xkx_k, with all later states seen as functions of xkx_k and the later ηj\eta_j: the term at time kk gives fkf_k, and the terms after kk act on xkx_k only through xk+1=Mk+1(xk)+ηk+1x_{k+1} = M_{k+1}(x_k) + \eta_{k+1}, which gives Mk+1′(xk)⊤μk+1M_{k+1}'(x_k)^\top \mu_{k+1} by the chain rule. A change of ηk\eta_k changes xkx_k by the same amount and nothing before time kk, so the observation term has the gradient μk\mu_k with respect to ηk\eta_k. The same holds for x0x_0 with μ0\mu_0. The background and model error terms add B−1(x0−xb)B^{-1}(x_0 - x^b) and Qk−1ηkQ_k^{-1}\eta_k. □\square

Lemma 2 (the inner problem). Let GG be the linear map from an increment δz=(δx0,δη1,…,δηK)\delta z = (\delta x_0, \delta\eta_1, \ldots, \delta\eta_K) to the trajectory increments, δxk=Mk′(xk−1)δxk−1+δηk\delta x_k = M_k'(x_{k-1})\delta x_{k-1} + \delta\eta_k, and let D=diag(B−1,Q1−1,…,QK−1)D = \mathrm{diag}(B^{-1}, Q_1^{-1}, \ldots, Q_K^{-1}). Line L6 applies

A=D+G⊤(⨁k∈THk⊤Rk−1Hk)G,A = D + G^\top \Big(\textstyle\bigoplus_{k \in T} H_k^\top R_k^{-1} H_k\Big) G ,

which is symmetric positive definite, and line L7 gives the unique minimizer of JJ with the model linearized along the current trajectory.

Proof. The forward loop inside apply_a computes G δzG\,\delta z, the forcing applies Hk⊤Rk−1HkH_k^\top R_k^{-1} H_k, and the backward sweep with Lemma 1 applied to these forcings computes G⊤G^\top of the result, so apply_a is AA. v⊤Av≥v⊤Dv>0v^\top A v \ge v^\top D v > 0 for v≠0v \ne 0. With the linearized model the cost is a quadratic in δz\delta z with Hessian AA and gradient gg at δz=0\delta z = 0, where g=∇J(z)g = \nabla J(z) by Lemma 1, so its minimizer is −A−1g-A^{-1} g. □\square

So each outer loop is a Gauss-Newton step for JJ over the control zz, and g⊤δz=−g⊤A−1g<0g^\top \delta z = -g^\top A^{-1} g < 0 when g≠0g \ne 0.

Theorem 3 (linear model). Let Mk(x)=MxM_k(x) = Mx. Then the first outer loop, with an exact inner solve, returns the unique minimizer of JJ. If x0∼N(xb,B)x_0 \sim N(x^b, B), ηk∼N(0,Qk)\eta_k \sim N(0, Q_k) and ϵk∼N(0,Rk)\epsilon_k \sim N(0, R_k) are independent, the trajectory of the minimizer is xka=E[xk∣y]x_k^a = E[x_k \mid y] for every kk, the mean of the Rauch-Tung-Striebel smoother with model error covariance QkQ_k, and xKax_K^a is the Kalman filter mean at time KK.

Proof. For a linear model the linearization is exact, so the first outer loop minimizes JJ itself, and JJ is strictly convex by Lemma 2. The map from zz to the trajectory is linear and invertible (ηk=xk−Mxk−1\eta_k = x_k - Mx_{k-1}), and the prior density of zz times the likelihood of yy is proportional to exp⁡(−J(z))\exp(-J(z)). So the posterior of zz is Gaussian with mean z^=arg⁡min⁡J\hat z = \arg\min J, and since each xkx_k is a linear function of zz, E[xk∣y]E[x_k \mid y] is the trajectory of z^\hat z. The Rauch-Tung-Striebel smoother computes E[xk∣y]E[x_k \mid y] for this linear Gaussian model, and the Kalman filter computes E[xK∣yj,j≤K]=E[xK∣y]E[x_K \mid y_j, j \le K] = E[x_K \mid y]. □\square

Strong-constraint limit. As every Qk→0Q_k \to 0, the penalty forces ηk→0\eta_k \to 0, and the minimizer tends to the strong-constraint 4D-Var minimizer. In the linear case this is continuity of E[xk∣y]E[x_k \mid y] in QQ; the tests check it with Q=10−9Q = 10^{-9} times a positive definite matrix.

Termination. The conjugate gradient method of line L7 stops after at most 2n(K+1)2n(K+1) steps, and the outer loop runs at most max_outer times.

Summary. The backward sweep gives the exact gradient over the initial state and all model errors. Each outer loop is a Gauss-Newton step with a strictly convex inner problem. For a linear model one outer loop gives the minimizer, whose trajectory is the Kalman smoother mean with model error QQ. The tests check this to 10−810^{-8} against a separate Kalman filter and smoother, and the gradient against finite differences. ■\blacksquare

Complexity

The control has n(K+1)n(K + 1) entries instead of nn. An outer loop costs one full model run, KcKc, and each conjugate gradient step one tangent linear and one adjoint run, KsKs, plus solves with the factors of BB and the QkQ_k, Θ(Kn2)\Theta(Kn^2) with dense covariances, and the observation terms, Θ(np)\Theta(np). With kk outer loops of mm inner steps the time is Θ(Kn3+k(Kc+m(Ks+Kn2+np)))\Theta(Kn^3 + k(Kc + m(Ks + Kn^2 + np))), where Kn3Kn^3 is the Cholesky factorization of BB and every QkQ_k. The memory is Θ(Kn2)\Theta(Kn^2) for the dense factors of the QkQ_k; with a single QQ for all steps, or with an operator for QQ, it is the Θ(Kn)\Theta(Kn) of the trajectory and the control. The inner problem is also harder to precondition than in strong constraint, so mm is larger in practice.

Properties

  • Kalman smoother with model error. For a linear model and Gaussian errors, the minimizer is the smoother mean with process noise QkQ_k (a theorem). Strong-constraint 4D-Var is the case Qk=0Q_k = 0.
  • Continuous in QQ. As Qk→0Q_k \to 0 the minimizer tends to the strong-constraint minimizer (a theorem for the linear case; the tests check it with Q=10−9Q = 10^{-9} times a positive definite matrix).
  • The window can be longer. Strong-constraint 4D-Var needs a window short enough that the model is nearly perfect over it; the model error terms relax this.
  • The answer depends on QQ. A QQ that is too large lets the analysis follow the observation noise, and a QQ that is too small gives strong constraint back. QQ is harder to estimate than BB (a heuristic that Trémolet 2007 discusses).
  • Parallel in time. In the state form the model runs over the subwindows are independent, so they can run in parallel.

Variants and improvements

  • State form. Use the states at the start of each subwindow as the control, and penalize the jumps between the model run from one and the next. This is the form that allows parallel subwindows (Trémolet 2006).
  • Bias form. Use one constant model error η\eta for the whole window, with a small control. It suits systematic model errors.
  • Representer method. Solve the linear problem exactly in observation space, with one unknown per observation, using representer functions. This is the representer method of Bennett, the dual of this algorithm.
  • Ensemble estimates of QQ. Estimate the model error covariance from differences between model versions or from ensemble statistics, as ensemble Kalman smoothers do with inflation.

When to use it

Use weak-constraint 4D-Var when the model error over the window is not small next to the background error: long windows, models with known systematic errors, and ocean and atmospheric chemistry problems with weakly known forcing. If the model is good over a short window, strong-constraint 4D-Var is cheaper and has fewer parameters to tune. If no model error covariance can be estimated, start with the bias form.

Pitfalls

  • A gradient that ignores the model error (line L5). The gradient over ηk\eta_k is Qk−1ηk+μkQ_k^{-1}\eta_k + \mu_k, with μk\mu_k the adjoint variable after the forcing at time kk. Taking it before the forcing at time kk drops the observation at that time.
  • A badly chosen QQ. The answer depends strongly on QQ; check it with innovation statistics, as in Desroziers diagnostics.
  • Poor conditioning (line L7). The inner problem has n(K+1)n(K + 1) unknowns and couples them along the window, so the conjugate gradient method needs a preconditioner, such as a control variable transform with B1/2B^{1/2} and Qk1/2Q_k^{1/2}.
  • Memory. Storing a dense QkQ_k for every step is not possible for a large model; use one QQ for all steps or an operator form.
  • An unobserved error. Model error and initial state error can have the same effect on the observations, and then only BB and QQ decide how the misfit is split, as in the example.

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.

scimat.pyI0RawGitHub
# 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)]
weak_constraint_4d_var.py 182 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weak-constraint-4d-var/. The authors are listed in prov/2GGXNP.jsonl.

"""Weak-constraint 4D-Var in the model error forcing form.

Notation of Ide, Courtier, Ghil and Lorenc (1997). The window has the time
levels 0..K. The model is not exact: x_k = M_k(x_(k-1)) + eta_k, where the
model error eta_k has the covariance Q_k. The control variable is
z = (x_0, eta_1, ..., eta_K), and the cost is

    J(z) = 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
         + sum_(k in T) 1/2 d_k^T R_k^-1 d_k,       d_k = y_k - H_k x_k.

The minimizer is Gauss-Newton: each outer loop linearizes the model along
the current trajectory and solves the quadratic problem for the increment
dz with the conjugate gradient method. Products with the Gauss-Newton
Hessian cost one tangent linear run and one adjoint run. For a linear model
one outer loop gives the exact minimizer, which is the Kalman smoother
estimate with model error covariance Q.

The model is given by three functions:
    step(k, x)              M_k(x) for x = x_(k-1), without the model error
    tangent(k, x, dx)       M_k'(x) dx
    adjoint(k, x, lam)      M_k'(x)^T lam
Q is a list with Q[k] the covariance of eta_k for k = 1..K (Q[0] is not used).
"""

import scimat


def trajectory(x0, eta, step, K):
    """Return [x_0, ..., x_K] with x_k = M_k(x_(k-1)) + eta_k."""
    xs = [list(x0)]
    for k in range(1, K + 1):
        xs.append(scimat.add(step(k, xs[-1]), eta[k]))
    return xs


def cost(x0, eta, xb, B, Q, obs, step, K):
    """Return J(x_0, eta)."""
    xs = trajectory(x0, eta, step, K)
    e = scimat.sub(x0, xb)
    J = 0.5 * scimat.dot(e, scimat.solve(B, e))
    for k in range(1, K + 1):
        J += 0.5 * scimat.dot(eta[k], scimat.solve(Q[k], eta[k]))
    for k, (H, y, R) in obs.items():
        d = scimat.sub(y, scimat.matvec(H, xs[k]))
        J += 0.5 * scimat.dot(d, scimat.solve(R, d))
    return J


def _backward(xs, forcing, adjoint, K, n):
    """Return [mu_0, ..., mu_K]: mu_k is the sensitivity to x_k after the forcing at time k."""
    mu = [None] * (K + 1)
    lam = [0.0] * n
    for k in range(K, -1, -1):
        if k in forcing:
            lam = scimat.add(lam, forcing[k])
        mu[k] = lam
        if k > 0:
            lam = adjoint(k, xs[k - 1], lam)
    return mu


def gradient(x0, eta, xb, B, Q, obs, step, adjoint, K):
    """Return (grad over x_0, [None, grad over eta_1, ..., grad over eta_K])."""
    n = len(x0)
    xs = trajectory(x0, eta, step, K)
    forcing = {}
    for k, (H, y, R) in obs.items():
        d = scimat.sub(y, scimat.matvec(H, xs[k]))
        forcing[k] = [-v for v in scimat.matvec(scimat.transpose(H), scimat.solve(R, d))]
    mu = _backward(xs, forcing, adjoint, K, n)
    g0 = scimat.add(scimat.solve(B, scimat.sub(x0, xb)), mu[0])
    geta = [None] + [scimat.add(scimat.solve(Q[k], eta[k]), mu[k]) for k in range(1, K + 1)]
    return g0, geta


def conjugate_gradient(apply_a, b, tol=1e-14, max_iter=None):
    """Solve A z = b for symmetric positive definite A given as a function."""
    n = len(b)
    if max_iter is None:
        max_iter = 2 * n
    z = [0.0] * n
    r = [float(v) for v in b]
    q = list(r)
    rr = scimat.dot(r, r)
    stop = (tol * scimat.norm2(b)) ** 2
    for _ in range(max_iter):
        if rr <= stop:
            break
        aq = apply_a(q)
        alpha = rr / scimat.dot(q, aq)
        z = [zi + alpha * qi for zi, qi in zip(z, q)]
        r = [ri - alpha * ai for ri, ai in zip(r, aq)]
        rr_new = scimat.dot(r, r)
        q = [ri + (rr_new / rr) * qi for ri, qi in zip(r, q)]
        rr = rr_new
    return z


def _split(v, n, K):
    return v[:n], [None] + [v[n * k : n * (k + 1)] for k in range(1, K + 1)]


def _join(v0, w, K):
    out = list(v0)
    for k in range(1, K + 1):
        out.extend(w[k])
    return out


def weak_4dvar(xb, B, Q, obs, step, tangent, adjoint, K, max_outer=30, tol=1e-12):
    """Return (trajectory, x_0, eta, number of outer loops) for weak-constraint 4D-Var."""
    n = len(xb)
    LB = scimat.cholesky(B)
    LQ = [None] + [scimat.cholesky(Q[k]) for k in range(1, K + 1)]
    ob = {k: (H, scimat.transpose(H), y, scimat.cholesky(R)) for k, (H, y, R) in obs.items()}
    x0 = [float(v) for v in xb]  # @line L1
    eta = [None] + [[0.0] * n for _ in range(K)]
    outer = 0
    for outer in range(1, max_outer + 1):  # @line L2
        xs = trajectory(x0, eta, step, K)  # @line L3
        d = {k: scimat.sub(y, scimat.matvec(H, xs[k])) for k, (H, Ht, y, LR) in ob.items()}  # @line L4
        forcing = {k: [-v for v in scimat.matvec(Ht, scimat.cholesky_solve(LR, d[k]))] for k, (H, Ht, y, LR) in ob.items()}
        mu = _backward(xs, forcing, adjoint, K, n)  # @line L5
        g = _join(
            scimat.add(scimat.cholesky_solve(LB, scimat.sub(x0, xb)), mu[0]),
            [None] + [scimat.add(scimat.cholesky_solve(LQ[k], eta[k]), mu[k]) for k in range(1, K + 1)],
            K,
        )

        def apply_a(v):  # @line L6
            v0, w = _split(v, n, K)
            dx = [v0]
            for k in range(1, K + 1):
                dx.append(scimat.add(tangent(k, xs[k - 1], dx[-1]), w[k]))
            f = {k: scimat.matvec(Ht, scimat.cholesky_solve(LR, scimat.matvec(H, dx[k]))) for k, (H, Ht, y, LR) in ob.items()}
            m = _backward(xs, f, adjoint, K, n)
            out0 = scimat.add(scimat.cholesky_solve(LB, v0), m[0])
            outw = [None] + [scimat.add(scimat.cholesky_solve(LQ[k], w[k]), m[k]) for k in range(1, K + 1)]
            return _join(out0, outw, K)

        dz = conjugate_gradient(apply_a, [-v for v in g])  # @line L7
        d0, dw = _split(dz, n, K)
        x0 = scimat.add(x0, d0)  # @line L8
        eta = [None] + [scimat.add(eta[k], dw[k]) for k in range(1, K + 1)]
        size = scimat.norm2(x0) + sum(scimat.norm2(eta[k]) for k in range(1, K + 1))
        if scimat.norm2(dz) <= tol * (1.0 + size):  # @line L9
            break
    return trajectory(x0, eta, step, K), x0, eta, outer  # @line L10


def linear_model(M):
    """Return (step, tangent, 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, x, dx: scimat.matvec(M, dx),
        lambda k, x, lam: scimat.matvec(Mt, lam),
    )


def lorenz63(dt=0.01, sigma=10.0, rho=28.0, beta=8.0 / 3.0):
    """Return (step, tangent, adjoint) for forward Euler steps of the Lorenz-63 model."""

    def f(x):
        return [sigma * (x[1] - x[0]), x[0] * (rho - x[2]) - x[1], x[0] * x[1] - beta * x[2]]

    def jac(x):
        return [[-sigma, sigma, 0.0], [rho - x[2], -1.0, -x[0]], [x[1], x[0], -beta]]

    def step(k, x):
        return [xi + dt * fi for xi, fi in zip(x, f(x))]

    def tangent(k, x, dx):
        return [di + dt * v for di, v in zip(dx, scimat.matvec(jac(x), dx))]

    def adjoint(k, x, lam):
        return [li + dt * v for li, v in zip(lam, scimat.matvec(scimat.transpose(jac(x)), lam))]

    return step, tangent, adjoint
test_weak_constraint_4d_var.py 164 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/weak-constraint-4d-var/. The authors are listed in prov/2GGXNP.jsonl.

import random

import scimat
from weak_constraint_4d_var import (
    cost,
    gradient,
    linear_model,
    lorenz63,
    trajectory,
    weak_4dvar,
)


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 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 close(a, b, tol):
    return all(abs(u - v) <= tol * (1 + abs(v)) for u, v in zip(a, b))


def random_problem(rng, n, K, qscale=1.0):
    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] + [scimat.scale(qscale, 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:
            p = rng.randint(1, 3)
            H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
            obs[k] = (H, [rng.uniform(-2, 2) for _ in range(p)], random_spd(rng, p))
    if not obs:
        obs[K] = ([[1.0] + [0.0] * (n - 1)], [1.0], [[1.0]])
    return M, B, Q, xb, obs


def test_scalar_check_value():
    step, tl, adj = linear_model([[1.0]])
    xs, x0, eta, _ = weak_4dvar([0.0], [[1.0]], [None], {0: ([[1.0]], [1.0], [[1.0]])}, step, tl, adj, 0)
    assert abs(x0[0] - 0.5) < 1e-14


def test_page_example():
    # x_1 = x_0 + eta_1, x^b = 0, B = Q = R = 1, y_1 = 3: x_0 = eta_1 = 1 and x_1 = 2.
    step, tl, adj = linear_model([[1.0]])
    xs, x0, eta, _ = weak_4dvar([0.0], [[1.0]], [None, [[1.0]]], {1: ([[1.0]], [3.0], [[1.0]])}, step, tl, adj, 1)
    assert abs(x0[0] - 1.0) < 1e-13 and abs(eta[1][0] - 1.0) < 1e-13 and abs(xs[1][0] - 2.0) < 1e-13


def test_linear_model_equals_kalman_smoother_with_q():
    rng = random.Random(61)
    for _ in range(40):
        n = rng.randint(1, 3)
        K = rng.randint(1, 5)
        M, B, Q, xb, obs = random_problem(rng, n, K)
        step, tl, adj = linear_model(M)
        xs, x0, eta, outer = weak_4dvar(xb, B, Q, obs, step, tl, adj, K)
        xa, xsm = kalman_and_rts(xb, B, M, Q, obs, K)
        for k in range(K + 1):
            assert close(xs[k], xsm[k], 1e-8)
        assert close(xs[K], xa[K], 1e-8)
        assert outer <= 3


def test_small_q_approaches_strong_constraint():
    rng = random.Random(62)
    n, K = 2, 4
    M, B, Q, xb, obs = random_problem(rng, n, K, qscale=1e-9)
    step, tl, adj = linear_model(M)
    xs, x0, eta, _ = weak_4dvar(xb, B, Q, obs, step, tl, adj, K)
    zero = [None] + [[[0.0] * n for _ in range(n)] for _ in range(K)]
    _, strong = kalman_and_rts(xb, B, M, zero, obs, K)
    for k in range(K + 1):
        assert close(xs[k], strong[k], 1e-6)


def test_gradient_matches_finite_differences_lorenz63():
    rng = random.Random(63)
    step, _, adj = lorenz63()
    K = 15
    B = [[1.0, 0.2, 0.0], [0.2, 2.0, 0.1], [0.0, 0.1, 1.5]]
    Q = [None] + [[[0.1, 0.0, 0.0], [0.0, 0.2, 0.0], [0.0, 0.0, 0.1]] for _ in range(K)]
    xb = [1.0, 2.0, 20.0]
    H = [[1.0, 0.0, 0.0], [0.0, 0.5, 0.5]]
    obs = {k: (H, [rng.uniform(-5, 5), rng.uniform(-5, 5)], [[0.5, 0.0], [0.0, 1.0]]) for k in (0, 5, 10, 15)}
    x0 = [v + rng.uniform(-1, 1) for v in xb]
    eta = [None] + [[rng.uniform(-0.3, 0.3) for _ in range(3)] for _ in range(K)]
    g0, geta = gradient(x0, eta, xb, B, Q, obs, step, adj, K)
    eps = 1e-6
    for j in range(3):
        xp, xm = list(x0), list(x0)
        xp[j] += eps
        xm[j] -= eps
        fd = (cost(xp, eta, xb, B, Q, obs, step, K) - cost(xm, eta, xb, B, Q, obs, step, K)) / (2 * eps)
        assert abs(fd - g0[j]) <= 1e-6 * (1 + abs(fd))
    for k in (1, 7, 15):
        for j in range(3):
            ep = [None] + [list(e) for e in eta[1:]]
            em = [None] + [list(e) for e in eta[1:]]
            ep[k][j] += eps
            em[k][j] -= eps
            fd = (cost(x0, ep, xb, B, Q, obs, step, K) - cost(x0, em, xb, B, Q, obs, step, K)) / (2 * eps)
            assert abs(fd - geta[k][j]) <= 1e-6 * (1 + abs(fd))


def test_nonlinear_limit_is_stationary_and_weak_beats_strong_with_model_error():
    # Twin: the truth has a constant forcing that the model lacks (model error).
    step, tl, adj = lorenz63()
    K = 40
    forcing = [0.0, 0.0, 0.05]
    truth0 = trajectory([1.0, 1.0, 1.0], [None] + [[0.0] * 3] * 500, step, 500)[-1]
    truth = trajectory(truth0, [None] + [forcing] * K, step, K)
    H = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    R = [[0.04, 0.0, 0.0], [0.0, 0.04, 0.0], [0.0, 0.0, 0.04]]
    B = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    err_weak = err_strong = 0.0
    for seed in range(64, 70):
        rng = random.Random(seed)
        obs = {k: (H, [v + rng.gauss(0, 0.2) for v in truth[k]], R) for k in range(0, K + 1, 4)}
        xb = [v + rng.gauss(0, 1.0) for v in truth0]
        Qw = [None] + [[[0.01, 0.0, 0.0], [0.0, 0.01, 0.0], [0.0, 0.0, 0.01]] for _ in range(K)]
        Qs = [None] + [[[1e-8, 0.0, 0.0], [0.0, 1e-8, 0.0], [0.0, 0.0, 1e-8]] for _ in range(K)]
        xw, x0, eta, _ = weak_4dvar(xb, B, Qw, obs, step, tl, adj, K)
        g0, geta = gradient(x0, eta, xb, B, Qw, obs, step, adj, K)
        assert scimat.norm2(g0) + sum(scimat.norm2(g) for g in geta[1:]) < 1e-7
        xstr, _, _, _ = weak_4dvar(xb, B, Qs, obs, step, tl, adj, K)
        err_weak += scimat.norm2(scimat.sub(xw[K], truth[K]))
        err_strong += scimat.norm2(scimat.sub(xstr[K], truth[K]))
    assert err_weak < 0.5 * err_strong

History

Sasaki (1970) distinguished strong and weak constraints in variational analysis, depending on whether the dynamics must hold exactly or only approximately. Bennett developed the weak-constraint problem for ocean models in the 1980s and 1990s and solved it with representers (Bennett 1992 and 2002). Trémolet (2006) compared the forcing, state and bias formulations for the ECMWF 4D-Var system and studied the estimation of model error in 2007.

References

  1. Y. Sasaki, Some basic formalisms in numerical variational analysis, Monthly Weather Review 98(12) (1970) 875-883, the formalisms with strong and with weak constraint
  2. Y. Trémolet, Accounting for an imperfect model in 4D-Var, Quarterly Journal of the Royal Meteorological Society 132(621) (2006) 2483-2504, the model error forcing, state and bias formulations of weak-constraint 4D-Var
  3. Y. Trémolet, Model-error estimation in 4D-Var, Quarterly Journal of the Royal Meteorological Society 133 (2007) 1267-1280, the estimation of model error in the ECMWF system and the specification of Q
  4. Andrew F. Bennett, Inverse Modeling of the Ocean and Atmosphere, Cambridge University Press, 2002, the weak-constraint least squares problem and its solution by representers
  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

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