Algorithm Search⌘K

Algorithmadvanced

Incremental 4D-Var

Solves 4D-Var by outer loops that relinearize the model and inner loops that minimize a quadratic cost for the increment at lower resolution.

Time
Θ(n^3 + k (K c + m (K s + n^2 + n p))) worst
Space
Θ(K n + 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 step of the inner linear model
Properties
deterministic
Origin
Philippe Courtier, Jean Noël Thépaut, Anthony Hollingsworth, 1994

Incremental 4D-Var solves the 4D-Var problem as a sequence of quadratic problems. An outer loop runs the full nonlinear model from the current initial state and computes the departures of the observations from that trajectory. An inner loop then finds the increment δx0\delta x_0 that minimizes a quadratic cost in which the change of the trajectory is given by a linear model along the stored trajectory, the tangent linear model or a cheaper simplified version of it, usually at a lower resolution. The increment updates the initial state, and the next outer loop relinearizes. With the exact tangent linear model each outer loop is one step of the Gauss-Newton algorithm for the 4D-Var cost (Lawless, Gratton and Nichols 2005), and for a linear model one outer loop is enough. This is the form in which every operational 4D-Var system runs.

In plain words

Searching directly for the best start state with the full weather model is too expensive, because every trial needs a full model run. The incremental method splits the work. It runs the full model once and records how far each measurement is from that run. Then it works only with a simpler linear version of the model, which says how a small change of the start state moves the run. With this simple version the best small change is the answer to a single quadratic problem, which a cheap iterative method solves. The method adds the change to the start state, runs the full model again, and repeats a few times.

The problem

Input. As for 4D-Var: a background xbx^b with error covariance BB, the full model steps MkM_k, a linear inner model along a trajectory with its exact transpose, 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 initial state x0ax_0^a after the outer loops. With the exact tangent linear model it is a stationary point of the 4D-Var cost

J(x0)=12(x0−xb)⊤B−1(x0−xb)+∑k∈T12dk⊤Rk−1dk,dk=yk−HkM0→k(x0).J(x_0) = \tfrac12 (x_0 - x^b)^\top B^{-1}(x_0 - x^b) + \sum_{k \in T} \tfrac12 d_k^\top R_k^{-1} d_k, \qquad d_k = y_k - H_k M_{0 \to k}(x_0).

The inner cost of one outer loop, with LkL_k the linear inner model from time 00 to time kk, is

J~(δx0)=12(x0+δx0−xb)⊤B−1(x0+δx0−xb)+∑k∈T12(dk−HkLkδx0)⊤Rk−1(dk−HkLkδx0).\tilde J(\delta x_0) = \tfrac12 (x_0 + \delta x_0 - x^b)^\top B^{-1}(x_0 + \delta x_0 - x^b) + \sum_{k \in T} \tfrac12 (d_k - H_k L_k \delta x_0)^\top R_k^{-1}(d_k - H_k L_k \delta x_0).

The algorithm

  1. INCREMENTAL-4DVAR(x^b, B, {y_k, H_k, R_k}, M, L, L^T)
  2. 1x_0 <- x^b
  3. 2for outer <- 1 to max_outer do
  4. 3run the full model from x_0 and store x_1, ..., x_K
  5. 4d_k <- y_k - H_k x_k for k in T ▷ departures from the full model
  6. 5b <- -B^-1 (x_0 - x^b) + sum_k L_k^T H_k^T R_k^-1 d_k ▷ one adjoint run
  7. 6A v = B^-1 v + sum_k L_k^T H_k^T R_k^-1 H_k L_k v ▷ one linear run and one adjoint run
  8. 7dx_0 <- solve A dx_0 = b by conjugate gradients ▷ the inner loop
  9. 8x_0 <- x_0 + dx_0
  10. 9if |dx_0| <= tol (1 + |x_0|) then break
  11. 10return x_0

Line L6 never forms AA: a product AvAv runs the linear model forward from vv, applies Hk⊤Rk−1HkH_k^\top R_k^{-1} H_k at each observation time, and runs the adjoint backward, the template of the adjoint model page. With the exact tangent linear model, bb of line L5 is minus the gradient of JJ and AA is the Gauss-Newton matrix. In operational systems the increment lives on a coarser grid than the full model, the inner linear model has simplified physics, and the inner loop minimizes over a control variable vv with δx0=Uv\delta x_0 = Uv, which replaces B−1B^{-1} by the identity.

Example

A square model. Take x1=x02x_1 = x_0^2 (K=1K = 1), xb=1x^b = 1, B=1B = 1, and one observation y1=2y_1 = 2 with H=R=1H = R = 1. The full cost is J(x0)=12(x0−1)2+12(2−x02)2J(x_0) = \tfrac12 (x_0 - 1)^2 + \tfrac12 (2 - x_0^2)^2, and J′(x0)=2x03−3x0−1=(x0+1)(2x02−2x0−1)J'(x_0) = 2x_0^3 - 3x_0 - 1 = (x_0 + 1)(2x_0^2 - 2x_0 - 1), so the minimizer is (1+3)/2=1.3660254(1 + \sqrt 3)/2 = 1.3660254.

Outer loop 1 at x0=1x_0 = 1: x1=1x_1 = 1, d1=1d_1 = 1, and the tangent linear model is multiplication by 2x0=22x_0 = 2. The inner cost is 12δ2+12(1−2δ)2\tfrac12 \delta^2 + \tfrac12 (1 - 2\delta)^2, with minimizer δ=2/5\delta = 2/5, so x0=1.4x_0 = 1.4.

Outer loop 2 at x0=1.4x_0 = 1.4: x1=1.96x_1 = 1.96, d1=0.04d_1 = 0.04, and the tangent linear model is multiplication by 2.82.8. The inner cost 12(0.4+δ)2+12(0.04−2.8δ)2\tfrac12 (0.4 + \delta)^2 + \tfrac12 (0.04 - 2.8\delta)^2 has the minimizer δ=−0.288/8.84\delta = -0.288/8.84, so x0=1.3674208x_0 = 1.3674208.

The reference code continues:

outer loop x0x_0 J(x0)J(x_0) error
0 1.0000000 0.5000000 3.7e-1
1 1.4000000 0.0808000 3.4e-2
2 1.3674208 0.0759699 1.4e-3
3 1.3660701 0.0759619 4.5e-5
4 1.3660268 0.0759619 1.4e-6
5 1.3660254 0.0759619 4.5e-8

The error falls by a factor of about 0.032 per outer loop: Gauss-Newton converges only linearly here, because the residual 2−x1=0.1342 - x_1 = 0.134 at the minimum is not zero.

An inexact inner model. On a Lorenz-63 window of 20 forward Euler steps with Δt=0.01\Delta t = 0.01, the exact tangent linear model converges in 8 outer loops to a point where the full gradient is below 10−810^{-8}. With the tangent linear model scaled by 0.9 and its own transpose, the loop still converges, in 43 outer loops, but to a point 0.21 away, where the full gradient has a component of 1.15 and the cost is 3.77 instead of 3.64 (a measurement). This is the effect that Lawless, Gratton and Nichols (2005) analyze.

Correctness

The proof shows that AA is symmetric positive definite, so each inner problem has a unique minimizer, and that with the exact tangent linear model b=−∇J(x0)b = -\nabla J(x_0) and AA is the Gauss-Newton matrix of the 4D-Var least squares problem (a theorem). So each outer loop is a Gauss-Newton step and a descent direction for JJ. For a linear model the inner cost equals the full cost, and the first outer loop returns the 4D-Var minimizer, which is the Kalman smoother estimate. With an inexact inner model, a fixed point solves a different equation and is in general not a stationary point of JJ. The tests check the outer iterates against a Gauss-Newton step built with a finite difference Jacobian, the linear case against a Kalman filter and smoother to 10−810^{-8}, and the inner sweeps with the dot product test.

Proof: Each outer loop of incremental 4D-Var is a Gauss-Newton step, exact in one loop for a linear modelfull

Setting. The full model steps MkM_k are differentiable, the trajectory from x0x_0 is xk=M0→k(x0)x_k = M_{0 \to k}(x_0), and TT is the set of times with observations yky_k, linear operators HkH_k and symmetric positive definite RkR_k. BB is symmetric positive definite. The full cost is

J(x0)=12(x0−xb)⊤B−1(x0−xb)+∑k∈T12dk⊤Rk−1dk,dk=yk−HkM0→k(x0).J(x_0) = \tfrac12 (x_0 - x^b)^\top B^{-1}(x_0 - x^b) + \sum_{k \in T} \tfrac12 d_k^\top R_k^{-1} d_k, \qquad d_k = y_k - H_k M_{0 \to k}(x_0).

In one outer loop, lines L3 and L4 give the trajectory xkx_k and the departures dkd_k at the current x0x_0. Let LkL_k be the linear inner model from time 00 to time kk along this trajectory: the product of the linear steps of tangent from step 1 to step kk. If the inner model is the exact tangent linear model, Lk=M0→k′(x0)L_k = M'_{0 \to k}(x_0), the Jacobian of M0→kM_{0 \to k} at x0x_0.

Lemma 1 (the sweeps). The forward sweep returns Lk δx0L_k\,\delta x_0 for every kk, and the backward sweep with forcings fkf_k returns ∑kLk⊤fk\sum_k L_k^\top f_k, provided each adjoint step is the transpose of the matching tangent step.

Proof. The forward claim is the definition of LkL_k. For the backward claim, the same induction as on the 4D-Var proof page shows that after the forcing at time kk, λ=∑j≥k(steps k+1 to j)⊤fj\lambda = \sum_{j \ge k} (\text{steps } k + 1 \text{ to } j)^\top f_j; at k=0k = 0 this is ∑jLj⊤fj\sum_j L_j^\top f_j. □\square

Lemma 2 (the inner problem). Line L6 applies the matrix A=B−1+∑k∈TLk⊤Hk⊤Rk−1HkLkA = B^{-1} + \sum_{k \in T} L_k^\top H_k^\top R_k^{-1} H_k L_k, which is symmetric positive definite. Line L5 gives b=−B−1(x0−xb)+∑k∈TLk⊤Hk⊤Rk−1dkb = -B^{-1}(x_0 - x^b) + \sum_{k \in T} L_k^\top H_k^\top R_k^{-1} d_k. The solution δx0=A−1b\delta x_0 = A^{-1} b of line L7 is the unique minimizer of the inner quadratic cost

J~(δx0)=12(x0+δx0−xb)⊤B−1(x0+δx0−xb)+∑k∈T12(dk−HkLkδx0)⊤Rk−1(dk−HkLkδx0).\tilde J(\delta x_0) = \tfrac12 (x_0 + \delta x_0 - x^b)^\top B^{-1}(x_0 + \delta x_0 - x^b) + \sum_{k \in T} \tfrac12 (d_k - H_k L_k \delta x_0)^\top R_k^{-1}(d_k - H_k L_k \delta x_0).

Proof. The formulas for AA and bb follow from Lemma 1. AA is symmetric, and v⊤Av≥v⊤B−1v>0v^\top A v \ge v^\top B^{-1} v > 0 for v≠0v \ne 0. The gradient of J~\tilde J is A δx0−bA\,\delta x_0 - b and its Hessian is AA, so J~\tilde J is strictly convex with the single stationary point A−1bA^{-1} b. □\square

Theorem 3 (Gauss-Newton). With the exact tangent linear model, b=−∇J(x0)b = -\nabla J(x_0) and line L8 is one Gauss-Newton step for JJ, seen as the least squares problem with the residuals B−1/2(x0−xb)B^{-1/2}(x_0 - x^b) and Rk−1/2dkR_k^{-1/2} d_k.

Proof. By the chain rule the Jacobian of dkd_k with respect to x0x_0 is −HkM0→k′(x0)=−HkLk-H_k M'_{0 \to k}(x_0) = -H_k L_k. The gradient of JJ is then B−1(x0−xb)−∑kLk⊤Hk⊤Rk−1dk=−bB^{-1}(x_0 - x^b) - \sum_k L_k^\top H_k^\top R_k^{-1} d_k = -b, and the Gauss-Newton matrix, the product of the transposed Jacobian of the weighted residuals with itself, is AA. The Gauss-Newton step solves A δx0=−∇JA\,\delta x_0 = -\nabla J, which is line L7. □\square

So the outer iteration has the convergence properties of the Gauss-Newton algorithm (Lawless, Gratton and Nichols 2005): a step is a descent direction for JJ, since ∇J⊤δx0=−b⊤A−1b<0\nabla J^\top \delta x_0 = -b^\top A^{-1} b < 0 for b≠0b \ne 0; the convergence near a minimum with small residuals is fast, and with large residuals it is in general only linear.

Corollary 4 (linear model). If every MkM_k is linear, the first outer loop, with an exact inner solve, returns the 4D-Var minimizer, and the second outer loop gives δx0=0\delta x_0 = 0.

Proof. For a linear model Lk=M0→kL_k = M_{0 \to k} at every point, so J~(δx0)=J(x0+δx0)\tilde J(\delta x_0) = J(x_0 + \delta x_0) and Lemma 2 says that line L8 moves to the minimizer of JJ. At the minimizer b=−∇J=0b = -\nabla J = 0, so the next increment is zero. □\square

The theorem on the 4D-Var page then gives that, for a linear model and Gaussian errors, this point is the posterior mean of x0x_0, and its trajectory is the Kalman smoother mean (with Q=0Q = 0). The tests check the first outer loop against a separate Kalman filter and smoother to 10−810^{-8}.

Proposition 5 (an inexact inner model). If the inner model is not the tangent linear model, a fixed point of the outer loop satisfies B−1(x0−xb)=∑kLk⊤Hk⊤Rk−1dkB^{-1}(x_0 - x^b) = \sum_k L_k^\top H_k^\top R_k^{-1} d_k, which is in general not ∇J(x0)=0\nabla J(x_0) = 0.

Proof. A fixed point has δx0=0\delta x_0 = 0, so b=0b = 0 because AA is invertible. The equation b=0b = 0 has LkL_k in place of M0→k′(x0)M'_{0 \to k}(x_0). The two equations agree when all dk=0d_k = 0, or when ∑k(Lk−M0→k′)⊤Hk⊤Rk−1dk=0\sum_k (L_k - M'_{0 \to k})^\top H_k^\top R_k^{-1} d_k = 0 for another reason, and they differ in general. □\square

This is the point of Lawless, Gratton and Nichols (2005): a simplified or lower resolution inner model changes the solution, not only the speed. The test with the tangent linear model scaled by 0.9 shows it.

Termination. The conjugate gradient method of line L7 stops after at most 2n2n steps, and the outer loop runs at most max_outer times, so the algorithm always returns.

Summary. Each outer loop minimizes exactly a quadratic cost built from the full model departures and the inner linear model. With the exact tangent linear model this is a Gauss-Newton step for the 4D-Var cost, and for a linear model the first step lands on the 4D-Var minimizer. With an inexact inner model the fixed point is in general not a stationary point of the full cost. ■\blacksquare

Complexity

An outer loop costs one full model run, KcKc, and the inner loop costs one linear run and one adjoint run per conjugate gradient step, Θ(Ks)\Theta(Ks) with ss the cost of one step of the inner linear model, and the dense operators of the reference code add Θ(n2+np)\Theta(n^2 + np). With kk outer loops of mm inner steps the time is Θ(n3+k(Kc+m(Ks+n2+np)))\Theta(n^3 + k(Kc + m(Ks + n^2 + np))), where n3n^3 is the Cholesky factorization of BB. The saving over plain 4D-Var comes from ss: an inner model at a coarser resolution and with simplified physics costs a small fraction of the full model. Operational systems use 2 to 4 outer loops and some tens of inner steps each (a rule of thumb, not a bound). The memory is the stored trajectory, Θ(Kn)\Theta(Kn).

Properties

  • Gauss-Newton. With the exact tangent linear model the outer loop is the Gauss-Newton method for the 4D-Var cost (a theorem). It converges fast when the residuals at the minimum are small and the model is close to linear over the window, and only linearly otherwise.
  • Exact for linear models. One outer loop with an exact inner solve gives the 4D-Var minimizer (a theorem).
  • Inner problems are convex. Each inner cost is a strictly convex quadratic, so the conjugate gradient method is the natural solver, and it can be stopped early.
  • The inner model changes the answer. With a simplified or lower resolution inner model the fixed point moves (a theorem for the fixed point equation; the size of the shift is a measurement).
  • No global convergence guarantee. Full Gauss-Newton steps can increase JJ far from the minimum. Operational systems rely on a good background and a short window instead of a line search.

Variants and improvements

  • Multi-incremental 4D-Var. Use a coarse inner grid in the first outer loop and finer grids in later ones.
  • Truncated inner loops. Stop the conjugate gradient method after a fixed number of steps. This is a truncated Gauss-Newton method, and its convergence depends on the inner accuracy (Gratton, Lawless and Nichols 2007).
  • Lanczos inner solvers. A Lanczos form of the conjugate gradient method also gives eigenvalue estimates of the inner Hessian, used to precondition later outer loops and to estimate the analysis error variances.
  • Dual form. Solve the inner problem in observation space, with pp unknowns instead of nn, as in the physical space analysis system and the representer method.
  • Weak constraint and ensembles. The same outer and inner structure carries over to weak-constraint 4D-Var and to 4DEnVar, where an ensemble replaces the linear model.

When to use it

Use the incremental form whenever 4D-Var runs with a large model: it is the practical way to do 4D-Var, and the same structure suits 3D-Var with a nonlinear observation operator. Choose the resolution and physics of the inner model as a trade-off between cost and the shift of the solution that an inexact inner model causes. If the model is strongly nonlinear over the window, add outer loops or shorten the window.

Pitfalls

  • Departures from the linear model (line L4). The departures must come from the full nonlinear model at the current x0x_0. Computing them with the linear model removes the nonlinearity that the outer loop is there to capture.
  • An adjoint that is not the transpose of the inner model (lines L5 and L6). Then AA is not symmetric, and the conjugate gradient method fails or converges to a wrong point. Check the transpose with the dot product test for the inner model actually used.
  • Inner and outer resolutions. The increment must be interpolated from the coarse grid to the full grid, and the full departures must be passed to the coarse grid in a consistent way, or the outer loop does not converge.
  • Too few outer loops for a nonlinear problem. One outer loop gives the right answer only for a linear model. For nonlinear observation operators, such as for clouds and precipitation, the result after one loop can be far from the minimum.
  • Stopping the inner loop too early (line L7). The increment is then not the inner minimizer, and the outer loop is not a full Gauss-Newton step.

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.

incremental_4d_var.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/incremental-4d-var/. The authors are listed in prov/FTZTDM.jsonl.

"""Incremental 4D-Var: outer loops with the full model, inner loops with a linear model.

Notation of Ide, Courtier, Ghil and Lorenc (1997). The window has the time
levels 0..K, the full model step is x_k = M_k(x_(k-1)), and obs maps a time
level k to (H_k, y_k, R_k) with a linear H_k. The full cost is

    J(x_0) = 1/2 (x_0 - x^b)^T B^-1 (x_0 - x^b) + sum_k 1/2 d_k^T R_k^-1 d_k,
    d_k = y_k - H_k M_(0->k)(x_0).

Each outer loop runs the full model from the current x_0, computes the
departures, and minimizes the quadratic cost for an increment dx_0 in which
the trajectory change is given by a linear model along the stored
trajectory. With the exact tangent linear model this is one Gauss-Newton
step for J. The inner minimization is the conjugate gradient method; each
product with the inner Hessian costs one linear model run and one adjoint run.

A linear model along the trajectory is given by two functions:
    tangent(k, x, dx)       the linear model of step k at x = x_(k-1), applied to dx
    adjoint(k, x, lam)      its transpose applied to lam
The inner model may differ from the exact tangent linear model, for example
a simplified or lower resolution one; it must then come with its own exact
transpose.
"""

import scimat


def trajectory(x0, step, K):
    """Return [x_0, x_1, ..., x_K] for the model step from x0."""
    xs = [list(x0)]
    for k in range(1, K + 1):
        xs.append(step(k, xs[-1]))
    return xs


def cost(x0, xb, B, obs, step, K):
    """Return the full cost J(x0)."""
    xs = trajectory(x0, step, K)
    e = scimat.sub(x0, xb)
    J = 0.5 * scimat.dot(e, scimat.solve(B, e))
    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 tangent_sweep(xs, dx0, tangent, K):
    """Return [dx_0, ..., dx_K] for the linear model along the trajectory xs."""
    out = [list(dx0)]
    for k in range(1, K + 1):
        out.append(tangent(k, xs[k - 1], out[-1]))
    return out


def adjoint_sweep(xs, forcing, adjoint, K, n):
    """Return sum_k (linear model from 0 to k)^T forcing[k] by one backward run."""
    lam = [0.0] * n
    for k in range(K, -1, -1):
        if k in forcing:
            lam = scimat.add(lam, forcing[k])
        if k > 0:
            lam = adjoint(k, xs[k - 1], lam)
    return lam


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 incremental_4dvar(xb, B, obs, step, tangent, adjoint, K, max_outer=30, tol=1e-12):
    """Return (x_0^a, outer iterates) for incremental 4D-Var.

    The outer loop stops when |dx_0| <= tol (1 + |x_0|) or after max_outer loops.
    """
    n = len(xb)
    LB = scimat.cholesky(B)
    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
    iterates = [list(x0)]
    for _ in range(max_outer):  # @line L2
        xs = trajectory(x0, 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: scimat.matvec(Ht, scimat.cholesky_solve(LR, d[k])) for k, (H, Ht, y, LR) in ob.items()}
        b = scimat.sub(adjoint_sweep(xs, forcing, adjoint, K, n), scimat.cholesky_solve(LB, scimat.sub(x0, xb)))  # @line L5

        def apply_a(v):  # @line L6
            vs = tangent_sweep(xs, v, tangent, K)
            f = {k: scimat.matvec(Ht, scimat.cholesky_solve(LR, scimat.matvec(H, vs[k]))) for k, (H, Ht, y, LR) in ob.items()}
            return scimat.add(scimat.cholesky_solve(LB, v), adjoint_sweep(xs, f, adjoint, K, n))

        dx = conjugate_gradient(apply_a, b)  # @line L7
        x0 = scimat.add(x0, dx)  # @line L8
        iterates.append(list(x0))
        if scimat.norm2(dx) <= tol * (1.0 + scimat.norm2(x0)):  # @line L9
            break
    return x0, iterates  # @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
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_incremental_4d_var.py 211 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/incremental-4d-var/. The authors are listed in prov/FTZTDM.jsonl.

import math
import random

import scimat
from incremental_4d_var import (
    adjoint_sweep,
    conjugate_gradient,
    cost,
    incremental_4dvar,
    linear_model,
    lorenz63,
    tangent_sweep,
    trajectory,
)


def random_spd(rng, n):
    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] += 0.5
    return S


def kalman_and_rts(xb, B, M, obs, K):
    """Oracle: Kalman filter and Rauch-Tung-Striebel smoother means with Q = 0."""
    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.matmul(scimat.matmul(M, Pa[-1]), Mt)
        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 fd_gradient(x0, xb, B, obs, step, K, eps=1e-6):
    g = []
    for j in range(len(x0)):
        xp, xm = list(x0), list(x0)
        xp[j] += eps
        xm[j] -= eps
        g.append((cost(xp, xb, B, obs, step, K) - cost(xm, xb, B, obs, step, K)) / (2 * eps))
    return g


def gauss_newton_step_by_finite_differences(x0, xb, B, obs, step, K, eps=1e-6):
    """Reference: one Gauss-Newton step for the stacked residuals, Jacobian by finite differences."""

    def residuals(x):
        xs = trajectory(x, step, K)
        out = [scimat.sub(x, xb)]
        for k in sorted(obs):
            H, y, R = obs[k]
            out.append(scimat.sub(y, scimat.matvec(H, xs[k])))
        return out

    n = len(x0)
    base = residuals(x0)
    cols = []
    for j in range(n):
        xp, xm = list(x0), list(x0)
        xp[j] += eps
        xm[j] -= eps
        rp, rm = residuals(xp), residuals(xm)
        cols.append([[(a - b) / (2 * eps) for a, b in zip(u, v)] for u, v in zip(rp, rm)])
    weights = [B] + [obs[k][2] for k in sorted(obs)]
    A = [[0.0] * n for _ in range(n)]
    g = [0.0] * n
    for blk, W in enumerate(weights):
        Wr = scimat.solve(W, base[blk])
        WJ = [scimat.solve(W, cols[j][blk]) for j in range(n)]
        for i in range(n):
            g[i] += scimat.dot(cols[i][blk], Wr)
            for j in range(n):
                A[i][j] += scimat.dot(cols[i][blk], WJ[j])
    return scimat.add(x0, scimat.solve(A, [-v for v in g]))


def test_scalar_check_value():
    step, tl, adj = linear_model([[1.0]])
    xa, its = incremental_4dvar([0.0], [[1.0]], {0: ([[1.0]], [1.0], [[1.0]])}, step, tl, adj, 0)
    assert abs(xa[0] - 0.5) < 1e-14 and abs(its[1][0] - 0.5) < 1e-14


def test_page_example_square_model():
    # x_1 = x_0^2, x^b = 1, B = 1, y_1 = 2, R = 1. The minimizer is (1 + sqrt 3) / 2.
    step = lambda k, x: [x[0] * x[0]]
    tl = lambda k, x, dx: [2 * x[0] * dx[0]]
    adj = lambda k, x, lam: [2 * x[0] * lam[0]]
    xa, its = incremental_4dvar([1.0], [[1.0]], {1: ([[1.0]], [2.0], [[1.0]])}, step, tl, adj, 1)
    assert abs(its[1][0] - 1.4) < 1e-14
    assert abs(its[2][0] - 1.367420814479638) < 1e-12
    star = (1 + math.sqrt(3)) / 2
    assert abs(xa[0] - star) < 1e-12
    errs = [abs(x[0] - star) for x in its[1:6]]
    for k in range(len(errs) - 1):
        assert 0.02 < errs[k + 1] / errs[k] < 0.05  # linear convergence


def test_linear_model_one_outer_loop_is_exact():
    rng = random.Random(51)
    for _ in range(40):
        n = rng.randint(1, 4)
        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)
        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]])
        step, tl, adj = linear_model(M)
        x0, its = incremental_4dvar(xb, B, obs, step, tl, adj, K)
        xa, xs = kalman_and_rts(xb, B, M, obs, K)
        assert close(its[1], xs[0], 1e-8)
        assert close(trajectory(its[1], step, K)[K], xa[K], 1e-8)
        assert len(its) <= 4


def test_outer_loop_is_gauss_newton_lorenz63():
    rng = random.Random(52)
    step, tl, adj = lorenz63()
    K = 30
    B = [[1.0, 0.2, 0.0], [0.2, 2.0, 0.1], [0.0, 0.1, 1.5]]
    truth = trajectory([-5.8, -5.0, 24.0], step, K)
    H = [[1.0, 0.0, 0.0], [0.0, 0.0, 1.0]]
    R = [[0.5, 0.0], [0.0, 0.5]]
    obs = {k: (H, [v + rng.gauss(0, 0.7) for v in scimat.matvec(H, truth[k])], R) for k in (0, 10, 20, 30)}
    xb = [v + rng.gauss(0, 1.0) for v in truth[0]]
    x0, its = incremental_4dvar(xb, B, obs, step, tl, adj, K)
    ref = gauss_newton_step_by_finite_differences(xb, xb, B, obs, step, K)
    assert close(its[1], ref, 1e-6)
    ref2 = gauss_newton_step_by_finite_differences(its[1], xb, B, obs, step, K)
    assert close(its[2], ref2, 1e-6)
    # the limit is a stationary point of the full cost
    g = fd_gradient(x0, xb, B, obs, step, K)
    assert max(abs(v) for v in g) < 1e-6
    costs = [cost(x, xb, B, obs, step, K) for x in its]
    assert costs[-1] < costs[0]


def test_inner_operators_are_transposes():
    rng = random.Random(53)
    step, tl, adj = lorenz63()
    K = 40
    xs = trajectory([1.0, 2.0, 20.0], step, K)
    for _ in range(10):
        dx = [rng.uniform(-1, 1) for _ in range(3)]
        lam = [rng.uniform(-1, 1) for _ in range(3)]
        vK = tangent_sweep(xs, dx, tl, K)[K]
        w = adjoint_sweep(xs, {K: lam}, adj, K, 3)
        lhs, rhs = scimat.dot(vK, lam), scimat.dot(dx, w)
        assert abs(lhs - rhs) <= 1e-10 * (abs(lhs) + abs(rhs))


def test_non_tangent_linear_inner_model_moves_the_fixed_point():
    # A simplified inner model (the tangent linear model times 0.9, with its own transpose)
    # still converges, but to a point where the gradient of the full cost is not zero.
    rng = random.Random(54)
    step, tl, adj = lorenz63()
    K = 20
    B = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    truth = trajectory([-5.8, -5.0, 24.0], step, K)
    H = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    R = [[0.5, 0.0, 0.0], [0.0, 0.5, 0.0], [0.0, 0.0, 0.5]]
    obs = {k: (H, [v + rng.gauss(0, 0.7) for v in truth[k]], R) for k in (0, 10, 20)}
    xb = [v + rng.gauss(0, 1.0) for v in truth[0]]
    tl9 = lambda k, x, dx: [0.9 * v for v in tl(k, x, dx)]
    adj9 = lambda k, x, lam: [0.9 * v for v in adj(k, x, lam)]
    x_exact, _ = incremental_4dvar(xb, B, obs, step, tl, adj, K)
    x_simple, its = incremental_4dvar(xb, B, obs, step, tl9, adj9, K, max_outer=200)
    assert scimat.norm2(scimat.sub(its[-1], its[-2])) < 1e-10
    assert max(abs(v) for v in fd_gradient(x_exact, xb, B, obs, step, K)) < 1e-6
    assert max(abs(v) for v in fd_gradient(x_simple, xb, B, obs, step, K)) > 1e-3


def test_conjugate_gradient_against_elimination():
    rng = random.Random(55)
    for _ in range(50):
        n = rng.randint(1, 8)
        A = random_spd(rng, n)
        b = [rng.uniform(-1, 1) for _ in range(n)]
        z = conjugate_gradient(lambda v: scimat.matvec(A, v), b)
        assert close(z, scimat.solve(A, b), 1e-9)

History

Courtier, Thépaut and Hollingsworth proposed the incremental approach in 1994 as a way to make 4D-Var affordable for a global weather model: the increment is found at a lower resolution, with a simplified linear model, inside outer loops that use the full model. ECMWF started operational 4D-Var in this form in November 1997, with simplified physics in the inner loop (Rabier et al. 2000). Lawless, Gratton and Nichols showed in 2005 that incremental 4D-Var is a Gauss-Newton method and studied the effect of non-tangent linear inner models, and Gratton, Lawless and Nichols gave the convergence theory of the truncated form in 2007.

References

  1. P. Courtier, J.-N. Thépaut and A. Hollingsworth, A strategy for operational implementation of 4D-Var, using an incremental approach, Quarterly Journal of the Royal Meteorological Society 120(519) (1994) 1367-1387, the outer and inner loops, the increment at low resolution and the simplified linear model
  2. A. S. Lawless, S. Gratton and N. K. Nichols, An investigation of incremental 4D-Var using non-tangent linear models, Quarterly Journal of the Royal Meteorological Society 131(606) (2005) 459-476, incremental 4D-Var as a Gauss-Newton method, and the effect of an inexact linear model on the fixed point
  3. F. Rabier, H. Järvinen, E. Klinker, J.-F. Mahfouf and A. Simmons, The ECMWF operational implementation of four-dimensional variational assimilation. I, Experimental results with simplified physics, Quarterly Journal of the Royal Meteorological Society 126(564) (2000) 1143-1170, the operational incremental system with simplified physics in the inner loop
  4. Eugenia Kalnay, Atmospheric Modeling, Data Assimilation and Predictability, Cambridge University Press, 2003, Section 5.6 (methods with an evolving forecast error covariance, 4D-Var and the Kalman filter)
  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