Algorithm Search⌘K

Algorithmcore

Four-dimensional variational assimilation

Also called 4D-Var, strong-constraint 4D-Var.

Finds the initial state whose model trajectory best fits the background and the observations over a time window, with gradients from the adjoint model.

Time
Θ(n^3 + I (K c + n^2 + n p)) worst
Space
Θ(K n + n^2) extra
Where
I = the number of minimizer iterations; K = the number of model steps in the window; c = the cost of one model step; n = the state dimension; p = the total number of observations
Properties
deterministic
Origin
François Xavier Le Dimet, Olivier Talagrand, Philippe Courtier, 1986

Four-dimensional variational assimilation (4D-Var) finds the initial state x0x_0 of an assimilation window whose model trajectory xk=M0→k(x0)x_k = M_{0 \to k}(x_0) best fits a background xbx^b at the start and all the observations yky_k made at their own times kk during the window. The fit is measured by a cost function with the same two terms as in 3D-Var, the departure from the background weighted by B−1B^{-1} and the departures from the observations weighted by Rk−1R_k^{-1}, but the observation term is a sum over the window and the model links the times. The model is a strong constraint: the analysis is an exact model trajectory. The gradient of the cost with respect to all nn components of x0x_0 comes from one forward run of the model and one backward run of its adjoint, and a quasi-Newton or conjugate gradient method minimizes the cost. For a linear model and Gaussian errors the result is the Rauch-Tung-Striebel smoother estimate, and at the end of the window it is the Kalman filter estimate, without ever forming a covariance matrix of the size of the state.

In plain words

A weather center has a forecast for the start of a six or twelve hour period and many measurements taken at different moments during that period. It wants the start state from which the model, run forward, passes as close as possible to all the measurements at their own times, while it stays near the old forecast at the start. Each start state gets a score: how far it is from the old forecast, plus how far its model run is from each measurement. The method runs the model forward to compute the score, then runs a special backward model that tells, for every start value, which way to change it to lower the score. It takes a step in that direction and repeats until the score stops falling.

The problem

Input. A background xb∈Rnx^b \in \mathbb R^n for time 00 with error covariance BB; model steps xk=Mk(xk−1)x_k = M_k(x_{k-1}) for k=1,…,Kk = 1, \ldots, K, with their adjoint steps Mk′(x)⊤M_k'(x)^\top; and for each time kk of a set T⊆{0,…,K}T \subseteq \{0, \ldots, K\}, observations yky_k with an operator HkH_k and an error covariance RkR_k. The total number of observations is pp. The notation is that of Ide, Courtier, Ghil and Lorenc (1997). In the letters of the Kalman filter page, MM is its AA, HkH_k is its CC, and xbx^b and BB are its predicted mean and covariance at time 00.

Output. A minimizer, or for a nonlinear model a stationary point, of

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

The reference code uses linear operators HkH_k. A nonlinear hkh_k replaces HkxkH_k x_k by hk(xk)h_k(x_k) and Hk⊤H_k^\top by the adjoint of its Jacobian. The analysis trajectory is xka=M0→k(x0a)x_k^a = M_{0 \to k}(x_0^a), and its last state is the start of the next forecast.

The algorithm

  1. 4DVAR(x^b, B, {y_k, H_k, R_k}, M, M'^T)
  2. 1x_0 <- x^b
  3. 2for iter <- 1 to max_iter do
  4. 3run the model from x_0 and store x_1, ..., x_K
  5. 4J <- 1/2 |x_0 - x^b|^2_(B^-1) + sum_k 1/2 |d_k|^2_(R_k^-1), d_k = y_k - H_k x_k
  6. 5lambda <- 0
  7. 6for k <- K down to 0 do
  8. 7if k in T then lambda <- lambda - H_k^T R_k^-1 d_k ▷ observation forcing
  9. 8if k > 0 then lambda <- M_k'(x_(k-1))^T lambda ▷ one adjoint step
  10. 9g <- B^-1 (x_0 - x^b) + lambda ▷ = grad J(x_0)
  11. 10if |g| <= tol then break
  12. 11x_0 <- x_0 + alpha p, p from BFGS, alpha from a line search on J
  13. 12return x_0

Lines L3 to L9 are one evaluation of the cost and its gradient. The backward loop is the template of the adjoint model page, with the sign of the observation forcing written for departures dk=yk−Hkxkd_k = y_k - H_k x_k. Line L11 is a quasi-Newton step. The reference code uses BFGS, started with BB as the inverse Hessian, which is the inverse Hessian of the background term, and an Armijo backtracking line search; each trial point of the line search costs one more evaluation of lines L3 to L9. Operational systems use limited memory quasi-Newton or conjugate gradient methods inside the incremental form (see incremental 4D-Var), and they minimize over a control variable vv with x0−xb=Uvx_0 - x^b = Uv instead of applying B−1B^{-1}.

Example

A scalar window. Take x1=2x0x_1 = 2x_0 (K=1K = 1), xb=0x^b = 0, B=1B = 1, and one observation y1=2y_1 = 2 with H1=R1=1H_1 = R_1 = 1. Then

J(x0)=12x02+12(2−2x0)2,J′(x0)=5x0−4.J(x_0) = \tfrac12 x_0^2 + \tfrac12 (2 - 2x_0)^2, \qquad J'(x_0) = 5x_0 - 4 .

At x0=0x_0 = 0 the code gives x1=0x_1 = 0, d1=2d_1 = 2, J=2J = 2. Line L7 at k=1k = 1 gives λ=−2\lambda = -2, line L8 gives λ=2⋅(−2)=−4\lambda = 2 \cdot (-2) = -4, and line L9 gives g=0+(−4)=J′(0)g = 0 + (-4) = J'(0). The minimizer is x0a=0.8x_0^a = 0.8, so x1a=1.6x_1^a = 1.6.

Check with the Kalman filter: the forecast at time 1 has mean 00 and variance 2⋅1⋅2=42 \cdot 1 \cdot 2 = 4, the gain is 4/(4+1)=0.84/(4 + 1) = 0.8, and the filter mean is 0.8⋅2=1.6=x1a0.8 \cdot 2 = 1.6 = x_1^a. The smoother gain is 1⋅2/4=0.51 \cdot 2 / 4 = 0.5, and the smoothed mean at time 0 is 0.5⋅1.6=0.8=x0a0.5 \cdot 1.6 = 0.8 = x_0^a.

Lorenz-63 twin experiments. With forward Euler steps of Δt=0.01\Delta t = 0.01 on the Lorenz-63 system, a window of K=40K = 40 steps, all three variables observed every 8 steps with error standard deviation 0.50.5, B=IB = I, and a background error drawn from N(0,I)N(0, I), the reference code converges in 9 to 11 BFGS iterations. Over 8 seeds the mean error of x0x_0 falls from 1.55 for the background to 0.41 for the analysis, and the mean error at the end of the window from 1.60 to 0.31 (a measurement).

Correctness

The proof shows by induction over the backward loop that line L9 returns the exact gradient of JJ, so every BFGS direction is a descent direction. For a linear model, linear HkH_k and Gaussian errors, J(x0)J(x_0) is, up to a constant, the negative logarithm of the posterior density of x0x_0 given all the observations of the window, so the minimizer is the posterior mean (a theorem). Run forward, it is the smoother mean at every time of the window, and at the last time the Kalman filter mean with the same BB at the start. The tests check this to 10−810^{-8} against a separate Kalman filter and smoother, check the gradient against finite differences, and check the adjoint with the dot product test to 10−1010^{-10}. For a nonlinear model, 4D-Var finds a stationary point, which need not be the global minimum.

Proof: The adjoint sweep gives the gradient of the 4D-Var cost, and for a linear model the minimizer is the Kalman smoother estimatefull

Setting. The window has the time levels 0,1,…,K0, 1, \ldots, K. The model steps are differentiable maps Mk:Rn→RnM_k : \mathbb R^n \to \mathbb R^n with Jacobians Mk′(x)M_k'(x), and the trajectory from x0x_0 is xk=Mk(xk−1)x_k = M_k(x_{k-1}). The set T⊆{0,…,K}T \subseteq \{0, \ldots, K\} holds the times with observations yk∈Rpky_k \in \mathbb R^{p_k}, linear operators HkH_k and symmetric positive definite error covariances RkR_k. BB is symmetric positive definite. The cost is

J(x0)=12(x0−xb)⊤B−1(x0−xb)+∑k∈T12dk⊤Rk−1dk,dk=yk−Hkxk.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 x_k .

Write M0→k=Mk∘⋯∘M1M_{0 \to k} = M_k \circ \cdots \circ M_1, so xk=M0→k(x0)x_k = M_{0 \to k}(x_0), and write M0→k′=Mk′(xk−1)⋯M1′(x0)M'_{0 \to k} = M_k'(x_{k-1}) \cdots M_1'(x_0) for its Jacobian at x0x_0 (chain rule).

Lemma 1 (gradient). The vector gg of line L9 is ∇J(x0)\nabla J(x_0).

Proof. By the chain rule,

∇J(x0)=B−1(x0−xb)−∑k∈T(M0→k′)⊤Hk⊤Rk−1dk.\nabla J(x_0) = B^{-1}(x_0 - x^b) - \sum_{k \in T} (M'_{0 \to k})^\top H_k^\top R_k^{-1} d_k .

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. Let λ(k)\lambda^{(k)} be the value of λ\lambda after line L7 at time kk. We claim

λ(k)=−∑j≥kMk+1′(xk)⊤⋯Mj′(xj−1)⊤fj,\lambda^{(k)} = -\sum_{j \ge k} M_{k+1}'(x_k)^\top \cdots M_j'(x_{j-1})^\top f_j ,

where the empty product for j=kj = k is the identity. For k=Kk = K, line L5 sets λ=0\lambda = 0 and line L7 gives λ(K)=−fK\lambda^{(K)} = -f_K. If the claim holds for kk, line L8 multiplies by Mk′(xk−1)⊤M_k'(x_{k-1})^\top and line L7 at time k−1k - 1 subtracts fk−1f_{k-1}, which gives the claim for k−1k - 1. At k=0k = 0 the claim reads λ(0)=−∑j(M0→j′)⊤fj\lambda^{(0)} = -\sum_j (M'_{0 \to j})^\top f_j, because (M0→j′)⊤=M1′(x0)⊤⋯Mj′(xj−1)⊤(M'_{0 \to j})^\top = M_1'(x_0)^\top \cdots M_j'(x_{j-1})^\top. Line L9 adds B−1(x0−xb)B^{-1}(x_0 - x^b). □\square

So every iterate of line L11 uses the exact gradient. BFGS with the Armijo line search starts from BB as the inverse Hessian, keeps the inverse Hessian symmetric positive definite (the update is skipped when s⊤y≤0s^\top y \le 0), and so every search direction is a descent direction: g⊤p=−g⊤Hinv g<0g^\top p = -g^\top H_{\text{inv}}\, g < 0 for g≠0g \ne 0. For a strictly convex quadratic JJ the iterates converge to the unique minimizer. For a nonconvex JJ the method stops, by line L10, only near a stationary point.

Theorem 2 (linear model). Let Mk(x)=MxM_k(x) = M x for a fixed invertible matrix MM. Then JJ is strictly convex and has the unique minimizer

x0a=(B−1+∑k∈T(Mk)⊤Hk⊤Rk−1HkMk)−1(B−1xb+∑k∈T(Mk)⊤Hk⊤Rk−1yk).x_0^a = \Big(B^{-1} + \sum_{k \in T} (M^k)^\top H_k^\top R_k^{-1} H_k M^k\Big)^{-1}\Big(B^{-1} x^b + \sum_{k \in T} (M^k)^\top H_k^\top R_k^{-1} y_k\Big).

Let x0∼N(xb,B)x_0 \sim N(x^b, B), xk=Mxk−1x_k = M x_{k-1} (no model noise) and yk=Hkxk+ϵky_k = H_k x_k + \epsilon_k with independent ϵk∼N(0,Rk)\epsilon_k \sim N(0, R_k). Then x0a=E[x0∣y]x_0^a = E[x_0 \mid y], and Mkx0a=E[xk∣y]M^k x_0^a = E[x_k \mid y] for every kk. In particular MKx0aM^K x_0^a is the Kalman filter mean at time KK, and Mkx0aM^k x_0^a is the Rauch-Tung-Striebel smoother mean at time kk when that smoother runs with Q=0Q = 0.

Proof. With xk=Mkx0x_k = M^k x_0 the cost is a quadratic in x0x_0 with the Hessian A=B−1+∑k∈T(Mk)⊤Hk⊤Rk−1HkMkA = B^{-1} + \sum_{k \in T} (M^k)^\top H_k^\top R_k^{-1} H_k M^k, and v⊤Av≥v⊤B−1v>0v^\top A v \ge v^\top B^{-1} v > 0 for v≠0v \ne 0. Setting the gradient to zero gives the formula.

By Bayes' theorem the posterior density of x0x_0 is proportional to

exp⁡(−12(x0−xb)⊤B−1(x0−xb))∏k∈Texp⁡(−12(yk−HkMkx0)⊤Rk−1(yk−HkMkx0))=exp⁡(−J(x0)),\exp\big(-\tfrac12 (x_0 - x^b)^\top B^{-1}(x_0 - x^b)\big) \prod_{k \in T} \exp\big(-\tfrac12 (y_k - H_k M^k x_0)^\top R_k^{-1}(y_k - H_k M^k x_0)\big) = \exp(-J(x_0)),

so the posterior is Gaussian with mean x0ax_0^a and covariance A−1A^{-1}. Each xk=Mkx0x_k = M^k x_0 is a linear function of x0x_0, so E[xk∣y]=MkE[x0∣y]=Mkx0aE[x_k \mid y] = M^k E[x_0 \mid y] = M^k x_0^a.

The Kalman filter mean at time KK is E[xK∣yj,j≤K]E[x_K \mid y_j, j \le K], which is E[xK∣y]E[x_K \mid y] because the window ends at KK. The Rauch-Tung-Striebel smoother gives E[xk∣y]E[x_k \mid y] for the same linear Gaussian model. Both facts are the standard optimality of these recursions for linear Gaussian models (see the pages on the Kalman filter and the Rauch-Tung-Striebel smoother). With Q=0Q = 0 the smoother needs the predicted covariances MPM⊤M P M^\top to be invertible, which holds because MM is invertible. □\square

The tests check Theorem 2 to 10−810^{-8} against a Kalman filter and smoother written separately with Gaussian elimination, and Lemma 1 against central finite differences for Lorenz-63.

Summary. Lines L3 to L9 compute JJ and its exact gradient with one forward run and one backward adjoint run. The minimizer uses descent directions only. For a linear model the cost is strictly convex, and its minimizer is the posterior mean of the initial state; run forward, it is the smoother mean at every time of the window and the Kalman filter mean at the end. ■\blacksquare

Complexity

One evaluation of JJ and ∇J\nabla J costs one forward run, KK model steps, plus one adjoint run, whose steps cost a small multiple of a model step each (the cheap gradient principle of reverse mode differentiation). The observation terms cost Θ(np)\Theta(np) with dense HkH_k. The reference code factors BB and the RkR_k once and keeps a dense n×nn \times n BFGS matrix, so II iterations cost Θ(n3+I(Kc+n2+np))\Theta(n^3 + I(Kc + n^2 + np)), with a few extra cost evaluations when the line search backtracks. The memory is the stored trajectory, Θ(Kn)\Theta(Kn), which checkpointing can reduce. For a weather model with nn near 10810^8 or more, the dense matrix is replaced by limited memory updates in Θ(n)\Theta(n) memory, and the work is dominated by the forward and adjoint runs: the cost of 4D-Var is roughly the number of iterations times two or three model runs over the window (a rule of thumb).

Properties

  • Flow-dependent increments. The effective covariance of the analysis at time kk is propagated by the model through the window, so a single observation spreads along the flow of the day even with a static BB.
  • Same result as the smoother for linear models. With a linear model, linear HkH_k and no model error, 4D-Var and the Kalman smoother give the same estimates (a theorem), but 4D-Var never forms or stores an n×nn \times n covariance matrix.
  • Strong constraint. The analysis is an exact model trajectory. Model error is ignored, which limits the useful length of the window. Weak-constraint 4D-Var adds model error terms.
  • Observations at their own times. Each observation is compared with the model at the time it was taken, which suits satellite and aircraft data spread through the window.
  • No analysis covariance. The method returns the estimate only. The analysis error covariance is the inverse Hessian, which is not computed; the next window starts from the static BB again.

Variants and improvements

  • Incremental 4D-Var. Minimize a sequence of quadratic costs for an increment with the tangent linear model, at a lower resolution, inside outer loops with the full model. This is the form of all operational systems (Courtier, Thépaut and Hollingsworth 1994; see incremental 4D-Var).
  • Weak-constraint 4D-Var. Add model error terms with covariance QQ to the cost (see weak-constraint 4D-Var). Its dual, observation space form is the representer method.
  • 4DEnVar. Replace the tangent linear and adjoint models by an ensemble of trajectories over the window (see four-dimensional ensemble-variational assimilation).
  • Hybrid 4D-Var. Replace BB by a weighted sum of the static covariance and a localized ensemble covariance (see hybrid ensemble-variational assimilation).
  • Long windows and quasi-static minimization. For a chaotic model, lengthen the window step by step and start each minimization from the previous solution, which avoids some of the local minima of a long window.

When to use it

Use 4D-Var when the observations are spread in time, when the model is good enough to be a strong constraint over the window, and when a tangent linear and adjoint model can be written and maintained. It gives a dynamically consistent analysis and uses the model to spread information from the observations, which an analysis at one time cannot do. If an adjoint is not available, use an ensemble method or 4DEnVar. If the model error over the window is comparable to the observation error, use the weak-constraint form.

Pitfalls

  • A wrong adjoint (line L8). A gradient that is wrong but close makes the minimizer stall or stop at a wrong point. Run the dot product test for each step and for the whole window, and compare the gradient with finite differences.
  • The order of forcing and adjoint step (lines L7 and L8). The observation at time kk must enter λ\lambda before the adjoint step to time k−1k - 1. The other order attaches each observation to the wrong time.
  • Departures at the wrong state (line L4). The departures must use the trajectory of the current x0x_0, not of the background.
  • A long window in a chaotic model. The cost becomes very rough as the window grows, with many local minima, and the tangent linear approximation behind the incremental form breaks down. Windows of 6 to 12 hours are usual for global weather models.
  • Ignoring model error. With a strong constraint, systematic model errors are pushed into x0x_0, and the analysis can fit the observations by an unrealistic initial state.
  • Badly conditioned minimization (line L11). Without a good preconditioner, such as BB in the BFGS start or the control variable transform, the number of iterations grows with the condition number of the Hessian.

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.

four_dimensional_variational_assimilation.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/four-dimensional-variational-assimilation/. The authors are listed in prov/XB7N6C.jsonl.

"""Strong-constraint four-dimensional variational assimilation (4D-Var).

Notation of Ide, Courtier, Ghil and Lorenc (1997). The window has the time
levels 0, 1, ..., K. The model step k maps x_(k-1) to x_k = M_k(x_(k-1)),
and the model is a perfect constraint, so the initial state x_0 fixes the
whole trajectory. Observations y_k with a linear operator H_k and an error
covariance R_k can be given at any subset of the time levels. The 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 x_k.

The gradient comes from one forward run and one backward run of the
adjoint model. The minimizer is BFGS with a backtracking line search,
started with B as the inverse Hessian, which is the inverse Hessian of the
background term.

A model is given by two functions:
    step(k, x)              returns x_k = M_k(x) for x = x_(k-1)
    adjoint(k, x, lam)      returns M_k'(x)^T lam, the adjoint of step k at x
"""

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_and_gradient(x0, xb, LB, obs, step, adjoint, K):
    """Return (J(x0), grad J(x0)).

    LB is the Cholesky factor of B, and obs maps a time level k to
    (H_k, y_k, LR_k) with LR_k the Cholesky factor of R_k.
    """
    xs = trajectory(x0, step, K)  # @line L3
    e = scimat.sub(x0, xb)
    J = 0.5 * scimat.dot(e, scimat.cholesky_solve(LB, e))
    forcing = {}
    for k, (H, y, LR) in obs.items():
        d = scimat.sub(y, scimat.matvec(H, xs[k]))
        rd = scimat.cholesky_solve(LR, d)
        J += 0.5 * scimat.dot(d, rd)  # @line L4
        forcing[k] = scimat.matvec(scimat.transpose(H), rd)
    lam = [0.0] * len(x0)  # @line L5
    for k in range(K, -1, -1):  # @line L6
        if k in forcing:
            lam = scimat.sub(lam, forcing[k])  # @line L7
        if k > 0:
            lam = adjoint(k, xs[k - 1], lam)  # @line L8
    g = scimat.add(scimat.cholesky_solve(LB, e), lam)  # @line L9
    return J, g


def _bfgs_update(Hinv, s, y):
    """Return the BFGS update of the inverse Hessian Hinv for the step s and the gradient change y."""
    sy = scimat.dot(s, y)
    if sy <= 0.0:
        return Hinv
    rho = 1.0 / sy
    hy = scimat.matvec(Hinv, y)
    c = rho * rho * scimat.dot(y, hy) + rho
    n = len(s)
    return [[Hinv[i][j] - rho * (s[i] * hy[j] + hy[i] * s[j]) + c * s[i] * s[j] for j in range(n)] for i in range(n)]


def var4d(xb, B, obs, step, adjoint, K, max_iter=500, tol=1e-12):
    """Return (x_0^a, number of iterations) for strong-constraint 4D-Var.

    obs maps a time level k in 0..K to (H_k, y_k, R_k). The iteration stops
    when |grad J| <= tol (1 + |grad J(x^b)|) or after max_iter iterations.
    """
    LB = scimat.cholesky(B)
    ob = {k: (H, y, scimat.cholesky(R)) for k, (H, y, R) in obs.items()}
    x = [float(v) for v in xb]  # @line L1
    J, g = cost_and_gradient(x, xb, LB, ob, step, adjoint, K)
    g0 = scimat.norm2(g)
    Hinv = [[float(v) for v in row] for row in B]
    it = 0
    for it in range(max_iter):  # @line L2
        if scimat.norm2(g) <= tol * (1.0 + g0):  # @line L10
            break
        p = [-v for v in scimat.matvec(Hinv, g)]  # @line L11
        gp = scimat.dot(g, p)
        if gp >= 0.0:
            Hinv = [[float(v) for v in row] for row in B]
            p = [-v for v in scimat.matvec(Hinv, g)]
            gp = scimat.dot(g, p)
        a = 1.0
        while True:
            xn = [xi + a * pi for xi, pi in zip(x, p)]
            Jn, gn = cost_and_gradient(xn, xb, LB, ob, step, adjoint, K)
            # Armijo test, with a rounding allowance for the last steps
            if Jn <= J + 1e-4 * a * gp + 1e-14 * abs(J) or a < 1e-12:
                break
            a *= 0.5
        Hinv = _bfgs_update(Hinv, scimat.sub(xn, x), scimat.sub(gn, g))
        x, J, g = xn, Jn, gn
    return x, it  # @line L12


def linear_model(M):
    """Return (step, adjoint) for the linear model x_k = M x_(k-1) with a fixed matrix M."""
    Mt = scimat.transpose(M)
    return (lambda k, x: scimat.matvec(M, x)), (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.

    tangent(k, x, dx) is M_k'(x) dx and adjoint(k, x, lam) is M_k'(x)^T lam.
    """

    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_four_dimensional_variational_assimilation.py 162 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/four-dimensional-variational-assimilation/. The authors are listed in prov/XB7N6C.jsonl.

import random

import scimat
from four_dimensional_variational_assimilation import (
    cost_and_gradient,
    linear_model,
    lorenz63,
    trajectory,
    var4d,
)


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 means and Rauch-Tung-Striebel smoother means, with Q = 0.

    Gains by Gaussian elimination. Return (filter means, smoother means).
    """
    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 test_scalar_check_value():
    step, adj = linear_model([[1.0]])
    xa, _ = var4d([0.0], [[1.0]], {0: ([[1.0]], [1.0], [[1.0]])}, step, adj, 0)
    assert abs(xa[0] - 0.5) < 1e-12


def test_page_example():
    # x_1 = 2 x_0, x^b = 0, B = 1, y_1 = 2, R = 1: x_0^a = 0.8 and x_1 = 1.6.
    step, adj = linear_model([[2.0]])
    obs = {1: ([[1.0]], [2.0], [[1.0]])}
    J, g = cost_and_gradient([0.0], [0.0], [[1.0]], {1: ([[1.0]], [2.0], [[1.0]])}, step, adj, 1)
    assert abs(J - 2.0) < 1e-15 and abs(g[0] + 4.0) < 1e-15
    xa, _ = var4d([0.0], [[1.0]], obs, step, adj, 1)
    assert abs(xa[0] - 0.8) < 1e-12
    assert abs(trajectory(xa, step, 1)[1][0] - 1.6) < 1e-12


def test_linear_model_equals_kalman_smoother():
    rng = random.Random(41)
    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, adj = linear_model(M)
        x0, _ = var4d(xb, B, obs, step, adj, K)
        xa, xs = kalman_and_rts(xb, B, M, obs, K)
        traj = trajectory(x0, step, K)
        assert close(x0, xs[0], 1e-8)
        assert close(traj[K], xa[K], 1e-8)
        for k in range(K + 1):
            assert close(traj[k], xs[k], 1e-8)


def test_gradient_matches_finite_differences_lorenz63():
    rng = random.Random(42)
    step, _, adj = lorenz63()
    K = 30
    LB = scimat.cholesky([[1.0, 0.2, 0.0], [0.2, 2.0, 0.1], [0.0, 0.1, 1.5]])
    xb = [1.0, 2.0, 20.0]
    obs = {}
    for k in (0, 10, 20, 30):
        H = [[1.0, 0.0, 0.0], [0.0, 0.5, 0.5]]
        obs[k] = (H, [rng.uniform(-5, 5), rng.uniform(-5, 5)], scimat.cholesky([[0.5, 0.0], [0.0, 1.0]]))
    for _ in range(4):
        x0 = [xi + rng.uniform(-1, 1) for xi in xb]
        J, g = cost_and_gradient(x0, xb, LB, 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_and_gradient(xp, xb, LB, obs, step, adj, K)[0] - cost_and_gradient(xm, xb, LB, obs, step, adj, K)[0]) / (2 * eps)
            assert abs(fd - g[j]) <= 1e-6 * (1 + abs(g[j]))


def test_dot_product_test_of_the_adjoint():
    rng = random.Random(43)
    step, tl, adj = lorenz63()
    x = [1.0, 2.0, 20.0]
    xs = trajectory(x, step, 40)
    for _ in range(10):
        dx = [rng.uniform(-1, 1) for _ in range(3)]
        lam = [rng.uniform(-1, 1) for _ in range(3)]
        # the whole window: M' = M_40' ... M_1'
        v = dx
        for k in range(1, 41):
            v = tl(k, xs[k - 1], v)
        w = lam
        for k in range(40, 0, -1):
            w = adj(k, xs[k - 1], w)
        lhs, rhs = scimat.dot(v, lam), scimat.dot(dx, w)
        assert abs(lhs - rhs) <= 1e-10 * (abs(lhs) + abs(rhs))


def test_lorenz63_twin_reduces_the_error():
    # A measurement over 8 twin experiments: the mean error of x_0 falls by more than half.
    step, _, adj = lorenz63()
    truth0 = trajectory([1.0, 1.0, 1.0], step, 500)[-1]
    K = 40
    truth = trajectory(truth0, step, K)
    H = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    R = [[0.25, 0.0, 0.0], [0.0, 0.25, 0.0], [0.0, 0.0, 0.25]]
    B = [[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]
    eb = ea = 0.0
    for seed in range(44, 52):
        rng = random.Random(seed)
        obs = {k: (H, [v + rng.gauss(0, 0.5) for v in truth[k]], R) for k in range(0, K + 1, 8)}
        xb = [v + rng.gauss(0, 1.0) for v in truth0]
        x0, _ = var4d(xb, B, obs, step, adj, K)
        ob = {k: (h, y, scimat.cholesky(r)) for k, (h, y, r) in obs.items()}
        _, g = cost_and_gradient(x0, xb, scimat.cholesky(B), ob, step, adj, K)
        assert scimat.norm2(g) < 1e-8
        eb += scimat.norm2(scimat.sub(xb, truth0))
        ea += scimat.norm2(scimat.sub(x0, truth0))
    assert ea < 0.5 * eb

History

Variational methods with a dynamical constraint go back to Sasaki in the late 1950s and 1970. Le Dimet and Talagrand in 1986 posed assimilation over a time window as an optimal control problem and computed the gradient with the adjoint equations, and Talagrand and Courtier in 1987 applied the adjoint of a discrete vorticity model, with numerical results in the companion paper of Courtier and Talagrand. Lewis and Derber had used an adjoint method for the same kind of problem in 1985. The cost of the full method for a weather model was too high until Courtier, Thépaut and Hollingsworth proposed the incremental form in 1994. ECMWF began operational 4D-Var on 25 November 1997 (Rabier et al. 2000), and Météo-France, the UK Met Office, the Japan Meteorological Agency and Environment Canada followed in the next decade.

References

  1. F.-X. Le Dimet and O. Talagrand, Variational algorithms for analysis and assimilation of meteorological observations, theoretical aspects, Tellus A 38(2) (1986) 97-110, the variational problem over a time window and the adjoint equations for its gradient
  2. O. Talagrand and P. Courtier, Variational assimilation of meteorological observations with the adjoint vorticity equation. I, Theory, Quarterly Journal of the Royal Meteorological Society 113(478) (1987) 1311-1328, the adjoint of the discrete model and the gradient of the cost
  3. P. Courtier and O. Talagrand, Variational assimilation of meteorological observations with the adjoint vorticity equation. II, Numerical results, Quarterly Journal of the Royal Meteorological Society 113(478) (1987) 1329-1347, numerical experiments with a barotropic vorticity model
  4. 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 ECMWF 4D-Var and its comparison with 3D-Var
  5. 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 incremental form with outer and inner loops
  6. 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)
  7. 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