Algorithm Search⌘K

Algorithmcore

Three-dimensional variational assimilation

Also called 3D-Var.

Finds the analysis by minimizing the distance to the background weighted by B^-1 plus the distance to the observations weighted by R^-1, at one time.

Time
Θ(n^3 + p^3 + k m (n^2 + n p + p^2)) worst
Space
Θ(n^2 + n p + p^2) extra
Where
k = the number of outer loops; m = the number of conjugate gradient steps per outer loop; n = the state dimension; p = the number of observations
Properties
deterministic
Origin
Andrew C. Lorenc, David F. Parrish, John C. Derber, 1986

Three-dimensional variational assimilation (3D-Var) computes the analysis xax^a as the minimizer of a cost function J(x)J(x) with two terms: the distance from the background xbx^b, weighted by the inverse of the background error covariance BB, and the distance from the observations yoy^o, weighted by the inverse of the observation error covariance RR. All observations of a time window are treated as valid at one time, hence "three-dimensional". For a linear observation operator the minimizer is the same analysis as global optimal interpolation and the analysis step of the Kalman filter, but 3D-Var uses all observations at once without local selection, accepts a nonlinear operator such as a radiative transfer model for satellite radiances, and needs only products with BB, HH and H⊤H^\top, never the inverse of a large matrix. If the errors are Gaussian, JJ is the negative logarithm of the posterior density, so xax^a is the maximum a posteriori estimate.

In plain words

A weather center has a forecast and a large set of new measurements. It looks for the state of the atmosphere that agrees as well as possible with both. Each disagreement is counted with a weight: a large departure from the forecast costs much where the forecast is known to be good, and a large departure from a measurement costs much where the measurement is known to be good. The total cost is a single number, and the method searches for the state with the smallest total. It does this in steps. In each step it replaces the curved link between the state and the measured quantities by a straight one, solves that easier problem, and moves to its solution. For measurements that depend on the state in a straight way, one step is enough.

The problem

Input. A background xb∈Rnx^b \in \mathbb R^n with error covariance BB, observations yo∈Rpy^o \in \mathbb R^p with error covariance RR (both symmetric positive definite), and an observation operator h:Rn→Rph : \mathbb R^n \to \mathbb R^p with Jacobian H(x)H(x). Here nn is the state dimension and pp the number of observations. This is the notation of Ide, Courtier, Ghil and Lorenc (1997). In the letters of the Kalman filter page, HH is its CC, and xbx^b and BB are its predicted values x^\hat x and PP.

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

J(x)=12(x−xb)⊤B−1(x−xb)+12(yo−h(x))⊤R−1(yo−h(x)).J(x) = \tfrac12 (x - x^b)^\top B^{-1}(x - x^b) + \tfrac12 \big(y^o - h(x)\big)^\top R^{-1}\big(y^o - h(x)\big).

The gradient is ∇J(x)=B−1(x−xb)−H(x)⊤R−1(yo−h(x))\nabla J(x) = B^{-1}(x - x^b) - H(x)^\top R^{-1}(y^o - h(x)). For a linear h(x)=Hxh(x) = Hx the minimizer is xa=xb+K(yo−Hxb)x^a = x^b + K(y^o - Hx^b) with K=BH⊤(HBH⊤+R)−1K = BH^\top(HBH^\top + R)^{-1}.

The algorithm

The reference code uses the incremental form: an outer loop of Gauss-Newton steps, each of which minimizes the cost with hh linearized at the current point, and an inner conjugate gradient solve.

  1. 3DVAR(x^b, B, y^o, h, H(.), R)
  2. 1x <- x^b
  3. 2for outer <- 1 to max_outer do
  4. 3d <- y^o - h(x) ▷ departures from the current point
  5. 4H <- H(x) ▷ Jacobian of h at x
  6. 5A <- B^-1 + H^T R^-1 H ▷ Gauss-Newton Hessian, as a function
  7. 6g <- B^-1 (x - x^b) - H^T R^-1 d ▷ gradient of J at x
  8. 7dx <- solve A dx = -g by conjugate gradients
  9. 8x <- x + dx
  10. 9if |dx| <= tol (1 + |x|) then break
  11. 10return x

Line L5 never forms AA: conjugate gradients only need the product AvAv, which is one solve with BB, one product with HH, one solve with RR and one product with H⊤H^\top. Line L6 is the gradient of JJ (Lemma 1 of the proof). The code applies B−1B^{-1} and R−1R^{-1} through Cholesky factors. Operational codes do not apply B−1B^{-1} at all. They minimize over a control variable vv with x−xb=Uvx - x^b = Uv and B=UU⊤B = UU^\top, which turns the background term into 12v⊤v\tfrac12 v^\top v and makes the inner problem much better conditioned.

Example

One scalar observation. With n=p=1n = p = 1, xb=0x^b = 0, B=1B = 1, yo=1y^o = 1, R=1R = 1 and h(x)=xh(x) = x, line L6 gives g=−1g = -1, line L5 gives A=2A = 2, so xa=1/2x^a = 1/2, and the analysis error variance A−1A^{-1} is 1/21/2.

Wind speed. The state is a wind x=(u,v)x = (u, v) with the background xb=(3,4)x^b = (3, 4), so the background speed is 5. One instrument measures the speed only, h(x)=u2+v2h(x) = \sqrt{u^2 + v^2}, with yo=6y^o = 6 and R=1R = 1. This hh is nonlinear.

With B=IB = I the minimum lies on the ray through xbx^b, at the speed (5+6)/2=5.5(5 + 6)/2 = 5.5, so xa=(3.3,4.4)x^a = (3.3, 4.4). Along that ray hh is linear, and the first outer loop lands on xax^a exactly.

With B=diag(1,4)B = \mathrm{diag}(1, 4) the background vv is less certain than uu, so the analysis changes vv more. The outer iterates, from the reference code, are:

outer loop uu vv speed J(x)J(x) distance to xax^a
0 3.000000 4.000000 5.000000 0.500000000 8.4e-1
1 3.153061 4.816327 5.756631 0.124626817 2.1e-2
2 3.134954 4.824572 5.753645 0.124441540 1.3e-3
3 3.134090 4.825439 5.753901 0.124441010 8.0e-5
4 3.134038 4.825493 5.753918 0.124441008 4.9e-6
5 3.134035 4.825496 5.753920 0.124441008 3.0e-7

The distance shrinks by a factor of about 0.06 per outer loop (a measurement). This is linear, not quadratic, convergence: the final speed 5.754 does not match the observation 6, and hh is curved, so the Gauss-Newton Hessian of line L5 misses a term of the true Hessian. A grid search over the square [2,4]×[3,5][2, 4] \times [3, 5] in the tests confirms that the limit is the global minimum.

Correctness

The proof shows that AA is symmetric positive definite, so line L7 has a unique solution, and that line L8 moves to the exact minimizer of the cost with hh linearized at xx. For a linear hh this is the cost itself, so the first outer loop returns xb+K(yo−Hxb)x^b + K(y^o - Hx^b), the Kalman and optimal interpolation analysis, and A−1A^{-1} is the analysis error covariance (a theorem). For a nonlinear hh each increment is a descent direction, and the loop stops with a zero increment only at a stationary point of JJ. It need not be the global minimum, and convergence from a poor background is not guaranteed.

Proof: 3D-Var gives the Kalman analysis for a linear operator, and its outer loop stops only at stationary pointsfull

Setting. BB (n×nn \times n) and RR (p×pp \times p) are symmetric positive definite, xb∈Rnx^b \in \mathbb R^n, yo∈Rpy^o \in \mathbb R^p, and h:Rn→Rph : \mathbb R^n \to \mathbb R^p is differentiable with the Jacobian H(x)H(x). The cost is

J(x)=12(x−xb)⊤B−1(x−xb)+12(yo−h(x))⊤R−1(yo−h(x)).J(x) = \tfrac12 (x - x^b)^\top B^{-1}(x - x^b) + \tfrac12 (y^o - h(x))^\top R^{-1}(y^o - h(x)).

In one outer loop at the point xx, line L3 gives d=yo−h(x)d = y^o - h(x), line L4 gives H=H(x)H = H(x), line L5 defines A=B−1+H⊤R−1HA = B^{-1} + H^\top R^{-1} H, and line L6 gives g=B−1(x−xb)−H⊤R−1dg = B^{-1}(x - x^b) - H^\top R^{-1} d.

Lemma 1 (gradient). ∇J(x)=g\nabla J(x) = g, the vector of line L6.

Proof. The first term of JJ has the gradient B−1(x−xb)B^{-1}(x - x^b) because B−1B^{-1} is symmetric. For the second term, the chain rule gives −H(x)⊤R−1(yo−h(x))-H(x)^\top R^{-1}(y^o - h(x)). □\square

Lemma 2 (the inner problem). AA is symmetric positive definite, and δx=−A−1g\delta x = -A^{-1} g (line L7) is the unique minimizer of the quadratic

Jx(δx)=12(x+δx−xb)⊤B−1(x+δx−xb)+12(d−Hδx)⊤R−1(d−Hδx),J_x(\delta x) = \tfrac12 (x + \delta x - x^b)^\top B^{-1}(x + \delta x - x^b) + \tfrac12 (d - H\delta x)^\top R^{-1}(d - H\delta x),

which is JJ with hh replaced by its linearization h(x)+Hδxh(x) + H\delta x.

Proof. v⊤Av=v⊤B−1v+(Hv)⊤R−1(Hv)≥v⊤B−1v>0v^\top A v = v^\top B^{-1} v + (Hv)^\top R^{-1}(Hv) \ge v^\top B^{-1} v > 0 for v≠0v \ne 0. The gradient of JxJ_x with respect to δx\delta x is B−1(x+δx−xb)−H⊤R−1(d−Hδx)=g+AδxB^{-1}(x + \delta x - x^b) - H^\top R^{-1}(d - H\delta x) = g + A\delta x, and its Hessian is AA. So JxJ_x is strictly convex and its only stationary point is δx=−A−1g\delta x = -A^{-1}g. □\square

The conjugate gradient method of line L7 solves A δx=−gA\,\delta x = -g. In exact arithmetic it finds the solution in at most nn steps for a symmetric positive definite AA (Hestenes and Stiefel 1952). In floating point the code stops when the residual is small or after 2n2n steps.

Termination. Line L7 does at most 2n2n conjugate gradient steps, and the loop of line L2 runs at most max_outer times. Line L9 can stop it earlier. So the algorithm always returns at line L10.

Theorem 3 (linear operator). Let h(x)=Hxh(x) = Hx with a fixed matrix HH. Then JJ has the unique minimizer

xa=xb+K(yo−Hxb),K=BH⊤(HBH⊤+R)−1=(B−1+H⊤R−1H)−1H⊤R−1,x^a = x^b + K(y^o - Hx^b), \qquad K = B H^\top (H B H^\top + R)^{-1} = (B^{-1} + H^\top R^{-1} H)^{-1} H^\top R^{-1},

and the first outer loop, started at x=xbx = x^b (line L1) with an exact inner solve, returns xax^a. The second outer loop gives δx=0\delta x = 0, so line L9 stops.

Proof. For a linear hh the linearization is exact, so Jx(δx)=J(x+δx)J_x(\delta x) = J(x + \delta x) and JJ is strictly convex by Lemma 2. At x=xbx = x^b, g=−H⊤R−1dg = -H^\top R^{-1} d with d=yo−Hxbd = y^o - Hx^b, so line L8 gives xb+A−1H⊤R−1dx^b + A^{-1} H^\top R^{-1} d, the minimizer of JJ by Lemma 2. The identity (B−1+H⊤R−1H)BH⊤=H⊤R−1(HBH⊤+R)(B^{-1} + H^\top R^{-1} H) B H^\top = H^\top R^{-1}(H B H^\top + R) shows that the two forms of KK are equal. At the minimizer g=∇J=0g = \nabla J = 0, so the next inner solve gives δx=0\delta x = 0. □\square

So for a linear HH, 3D-Var, global optimal interpolation and the analysis step of the Kalman filter give the same xax^a. The covariance A−1=(B−1+H⊤R−1H)−1A^{-1} = (B^{-1} + H^\top R^{-1} H)^{-1} is the analysis error covariance (I−KH)B(I - KH)B (see the proof on the optimal interpolation page). If the errors are Gaussian, JJ is the negative logarithm of the posterior density of xx up to a constant, so xax^a is the maximum a posteriori estimate, which for a linear HH is also the posterior mean.

Theorem 4 (nonlinear operator). For any differentiable hh:

  1. If g≠0g \ne 0, the increment of line L7 is a descent direction: g⊤δx<0g^\top \delta x < 0.
  2. The increment is zero exactly when ∇J(x)=0\nabla J(x) = 0. So if line L9 stops with δx=0\delta x = 0, the returned xx is a stationary point of JJ.

Proof. (1) g⊤δx=−g⊤A−1g<0g^\top \delta x = -g^\top A^{-1} g < 0 because A−1A^{-1} is positive definite. (2) AA is invertible, so δx=−A−1g=0\delta x = -A^{-1} g = 0 exactly when g=0g = 0, and g=∇J(x)g = \nabla J(x) by Lemma 1. □\square

A stationary point of a nonconvex JJ need not be the global minimum, and the full Gauss-Newton step can increase JJ far from a minimum. A line search on JJ along δx\delta x makes each step decrease JJ; the plain method of the pseudocode uses the full step, which is the usual choice in operational incremental 3D-Var with few outer loops. Near a stationary point with zero residual yo−h(x)y^o - h(x) the convergence is quadratic, and with a nonzero residual it is in general only linear, as the measured example on the page shows.

Summary. The algorithm always stops. Each outer loop exactly minimizes the cost with hh linearized at the current point. For a linear hh the first outer loop returns the unique minimizer of JJ, which equals the Kalman and optimal interpolation analysis xb+K(yo−Hxb)x^b + K(y^o - Hx^b). For a nonlinear hh every increment is a descent direction, and the loop stops with a zero increment only at a stationary point of JJ. ■\blacksquare

Complexity

The reference code factors BB and RR once by Cholesky in Θ(n3+p3)\Theta(n^3 + p^3) time. Each conjugate gradient step costs one product AvAv, which is Θ(n2+np+p2)\Theta(n^2 + np + p^2) with dense matrices, so kk outer loops of mm inner steps cost Θ(km(n2+np+p2))\Theta(k m (n^2 + np + p^2)) more. Operational systems, with nn of the order of 10810^8 or more, never store BB. They apply UU with B=UU⊤B = UU^\top as a sequence of transforms (spectral or wavelet transforms, vertical modes, balance operators), each in about Θ(nlog⁡n)\Theta(n \log n) time. The tangent linear HH and its adjoint H⊤H^\top cost a small multiple of one evaluation of hh. A few outer loops with some tens of inner steps each are usual (a rule of thumb, not a bound). With the control variable transform the inner Hessian is I+U⊤H⊤R−1HUI + U^\top H^\top R^{-1} H U, whose eigenvalues are at least 1, which bounds the number of inner steps for a given accuracy in terms of the largest eigenvalue only.

Properties

  • Same analysis as OI for a linear HH. The minimizer is xb+Kdx^b + K d (a theorem). The two differ in what they compute: OI solves small systems in observation space for each grid value, and 3D-Var minimizes once over the whole state.
  • Global use of observations. Every observation can influence every grid value through BB, so the analysis has no jumps from data selection.
  • Nonlinear and indirect observations. Only hh, its tangent linear HH and its adjoint H⊤H^\top are needed, so radiances, refractivities and other indirect data can be used directly.
  • Fixed BB. The background covariance is the same every day, so the analysis increments do not follow the flow of the day. 4D-Var and hybrid ensemble methods address this.
  • Regularized least squares. The cost is a Tikhonov regularization of the observation fit with the background as the prior and B−1B^{-1} as the penalty matrix.

Variants and improvements

  • Control variable transform. Minimize over vv with x−xb=Uvx - x^b = Uv and B=UU⊤B = UU^\top (see control variable transform). This is how all operational 3D-Var systems are written.
  • Physical space analysis system (PSAS). Solve (HBH⊤+R)z=d(HBH^\top + R)z = d in observation space and set xa=xb+BH⊤zx^a = x^b + BH^\top z. For a linear HH this is the same analysis, and it is cheaper when pp is much smaller than nn (Kalnay 2003, Section 5.5).
  • First guess at the appropriate time (FGAT). Compute the departures of line L3 with the background at the time of each observation, while the increment stays valid at one time.
  • 4D-Var. Add the model as a link between the times of the window, so that the cost compares the model trajectory with the observations at their own times (see 4D-Var and incremental 4D-Var).
  • Hybrid 3D-Var. Replace BB by a weighted sum of the static BB and a localized ensemble covariance.

When to use it

Use 3D-Var when the observations are many and of many kinds, some with a nonlinear operator, when a smooth global analysis is wanted, and when a good static model of BB exists. It is the standard choice for regional and limited area systems with short cycles and for systems where a tangent linear and adjoint of the forecast model are not available. If the errors of the day matter, use an ensemble or a four-dimensional method.

Pitfalls

  • Inverse of BB in the code (line L6). Applying B−1B^{-1} directly fails when BB is huge or nearly singular, and the inner problem is badly conditioned. Use the control variable transform, which needs UU only.
  • Wrong adjoint (line L5 and line L6). If the code for H⊤H^\top is not the exact transpose of the code for HH, the conjugate gradient method fails to converge or converges to a wrong point. Check it with the dot product test ⟨Hv,w⟩=⟨v,H⊤w⟩\langle Hv, w \rangle = \langle v, H^\top w\rangle to rounding error.
  • Departures from the wrong point (line L3). In the incremental form, dd must be computed with the full nonlinear hh at the current xx, not at xbx^b. Computing it once at xbx^b freezes the outer loop at the first step.
  • Too few inner steps (line L7). Stopping conjugate gradients early gives an increment that is not the minimizer of the inner problem. Then one outer loop is no longer exact for a linear HH, and the analysis depends on the stopping rule.
  • Trusting one outer loop for a nonlinear hh. The first increment can be far from the minimum, and the full step can even increase JJ. Check the cost after line L8, and add outer loops or a line search.

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)]
three_dimensional_variational_assimilation.py 96 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/three-dimensional-variational-assimilation/. The authors are listed in prov/BZ95E9.jsonl.

"""Three-dimensional variational assimilation (3D-Var).

Notation of Ide, Courtier, Ghil and Lorenc (1997): background x^b in R^n
with error covariance B, observations y^o in R^p with error covariance R,
and an observation operator h from R^n to R^p, possibly nonlinear, with
Jacobian H(x). The analysis minimizes

    J(x) = 1/2 (x - x^b)^T B^-1 (x - x^b) + 1/2 (y^o - h(x))^T R^-1 (y^o - h(x)).

The minimizer here is incremental Gauss-Newton: each outer loop linearizes h
at the current x and solves the quadratic problem for the increment with the
conjugate gradient method. B^-1 and R^-1 are applied with Cholesky factors
and never formed. For a linear h one outer loop gives the exact minimizer,
which equals the optimal interpolation and Kalman analysis.
"""

import scimat


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.

    Stop when |r| <= tol |b|, or after max_iter steps (default 2 len(b)).
    """
    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 cost(x, xb, B, yo, h, R):
    """Return J(x)."""
    LB, LR = scimat.cholesky(B), scimat.cholesky(R)
    e = scimat.sub(x, xb)
    r = scimat.sub(yo, h(x))
    return 0.5 * scimat.dot(e, scimat.cholesky_solve(LB, e)) + 0.5 * scimat.dot(r, scimat.cholesky_solve(LR, r))


def gradient(x, xb, B, yo, h, jac, R):
    """Return grad J(x) = B^-1 (x - x^b) - H(x)^T R^-1 (y^o - h(x))."""
    LB, LR = scimat.cholesky(B), scimat.cholesky(R)
    e = scimat.sub(x, xb)
    r = scimat.sub(yo, h(x))
    Ht = scimat.transpose(jac(x))
    return scimat.sub(scimat.cholesky_solve(LB, e), scimat.matvec(Ht, scimat.cholesky_solve(LR, r)))


def var3d(xb, B, yo, h, jac, R, max_outer=30, tol=1e-12):
    """Return (x^a, iterates): the 3D-Var analysis and the list of outer iterates.

    h(x) returns the model equivalents of the observations and jac(x) the
    p by n Jacobian of h at x. The outer loop stops when the increment is
    below tol (1 + |x|) or after max_outer loops.
    """
    LB, LR = scimat.cholesky(B), scimat.cholesky(R)
    x = [float(v) for v in xb]  # @line L1
    iterates = [list(x)]
    for _ in range(max_outer):  # @line L2
        d = scimat.sub(yo, h(x))  # @line L3
        Hl = jac(x)  # @line L4
        Ht = scimat.transpose(Hl)

        def apply_a(v):  # @line L5
            return scimat.add(scimat.cholesky_solve(LB, v), scimat.matvec(Ht, scimat.cholesky_solve(LR, scimat.matvec(Hl, v))))

        e = scimat.sub(x, xb)
        g = scimat.sub(scimat.cholesky_solve(LB, e), scimat.matvec(Ht, scimat.cholesky_solve(LR, d)))  # @line L6
        dx = conjugate_gradient(apply_a, [-v for v in g])  # @line L7
        x = scimat.add(x, dx)  # @line L8
        iterates.append(list(x))
        if scimat.norm2(dx) <= tol * (1.0 + scimat.norm2(x)):  # @line L9
            break
    return x, iterates  # @line L10


def linear_operator(H):
    """Return (h, jac) for the linear observation operator given by the matrix H."""
    return (lambda x: scimat.matvec(H, x)), (lambda x: H)
test_three_dimensional_variational_assimilation.py 134 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/three-dimensional-variational-assimilation/. The authors are listed in prov/BZ95E9.jsonl.

import math
import random

import scimat
from three_dimensional_variational_assimilation import (
    conjugate_gradient,
    cost,
    gradient,
    linear_operator,
    var3d,
)


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_analysis(xb, B, yo, H, R):
    """Oracle: x^b + B H^T (H B H^T + R)^-1 (y^o - H x^b), by Gaussian elimination."""
    A = scimat.add(scimat.matmul(scimat.matmul(H, B), scimat.transpose(H)), R)
    d = scimat.sub(yo, scimat.matvec(H, xb))
    z = scimat.solve(A, d)
    return scimat.add(xb, scimat.matvec(scimat.matmul(B, scimat.transpose(H)), z))


def speed():
    h = lambda x: [math.hypot(x[0], x[1])]
    jac = lambda x: [[x[0] / math.hypot(x[0], x[1]), x[1] / math.hypot(x[0], x[1])]]
    return h, jac


def test_scalar_check_value():
    h, jac = linear_operator([[1.0]])
    xa, _ = var3d([0.0], [[1.0]], [1.0], h, jac, [[1.0]])
    assert abs(xa[0] - 0.5) < 1e-15


def test_linear_equals_kalman_and_oi_formula():
    rng = random.Random(21)
    for _ in range(200):
        n, p = rng.randint(1, 6), rng.randint(1, 5)
        B, R = random_spd(rng, n), random_spd(rng, p)
        H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
        xb = [rng.uniform(-3, 3) for _ in range(n)]
        yo = [rng.uniform(-3, 3) for _ in range(p)]
        h, jac = linear_operator(H)
        xa, its = var3d(xb, B, yo, h, jac, R)
        xk = kalman_analysis(xb, B, yo, H, R)
        for a, b in zip(xa, xk):
            assert abs(a - b) <= 1e-10 * (1 + abs(b))
        # one outer loop is exact for a linear h
        for a, b in zip(its[1], xk):
            assert abs(a - b) <= 1e-10 * (1 + abs(b))
        assert len(its) <= 3


def test_gradient_matches_finite_differences():
    rng = random.Random(22)
    n, p = 4, 3

    def h(x):
        return [x[0] * x[1], math.sin(x[2]) + x[3], x[0] ** 2 - x[3]]

    def jac(x):
        return [[x[1], x[0], 0.0, 0.0], [0.0, 0.0, math.cos(x[2]), 1.0], [2 * x[0], 0.0, 0.0, -1.0]]

    B, R = random_spd(rng, n), random_spd(rng, p)
    xb = [rng.uniform(-1, 1) for _ in range(n)]
    yo = [rng.uniform(-1, 1) for _ in range(p)]
    for _ in range(5):
        x = [rng.uniform(-1, 1) for _ in range(n)]
        g = gradient(x, xb, B, yo, h, jac, R)
        eps = 1e-6
        for j in range(n):
            xp, xm = list(x), list(x)
            xp[j] += eps
            xm[j] -= eps
            fd = (cost(xp, xb, B, yo, h, R) - cost(xm, xb, B, yo, h, R)) / (2 * eps)
            assert abs(fd - g[j]) < 1e-6 * (1 + abs(g[j]))


def test_wind_speed_isotropic_exact():
    # B = I: the minimum lies on the ray through x^b with speed (5 + 6) / 2.
    h, jac = speed()
    xa, its = var3d([3.0, 4.0], [[1.0, 0.0], [0.0, 1.0]], [6.0], h, jac, [[1.0]])
    assert abs(xa[0] - 3.3) < 1e-12 and abs(xa[1] - 4.4) < 1e-12


def test_wind_speed_anisotropic_converges_to_stationary_point():
    h, jac = speed()
    B = [[1.0, 0.0], [0.0, 4.0]]
    xa, its = var3d([3.0, 4.0], B, [6.0], h, jac, [[1.0]])
    g = gradient(xa, [3.0, 4.0], B, [6.0], h, jac, [[1.0]])
    assert max(abs(v) for v in g) < 1e-10
    assert abs(xa[0] - 3.134034646) < 1e-8 and abs(xa[1] - 4.825496589) < 1e-8
    costs = [cost(x, [3.0, 4.0], B, [6.0], h, [[1.0]]) for x in its]
    assert all(costs[k + 1] <= costs[k] + 1e-15 for k in range(len(costs) - 1))
    # Gauss-Newton converges linearly here: the residual is not zero and h is curved.
    e = [scimat.norm2(scimat.sub(x, xa)) for x in its[1:5]]
    for k in range(len(e) - 1):
        assert 0.01 < e[k + 1] / e[k] < 0.1
    # The minimum is a global one: compare with a fine grid search.
    best = min(
        cost([3.0 + i * 0.01 - 1.0, 4.0 + j * 0.01 - 1.0], [3.0, 4.0], B, [6.0], h, [[1.0]])
        for i in range(201)
        for j in range(201)
    )
    assert cost(xa, [3.0, 4.0], B, [6.0], h, [[1.0]]) <= best + 1e-12


def test_conjugate_gradient_against_elimination():
    rng = random.Random(23)
    for _ in range(100):
        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)
        zo = scimat.solve(A, b)
        for a, c in zip(z, zo):
            assert abs(a - c) <= 1e-9 * (1 + abs(c))


def test_no_information_in_observations():
    # Huge R: the analysis stays at the background.
    h, jac = linear_operator([[1.0, 1.0]])
    xa, _ = var3d([1.0, 2.0], [[1.0, 0.3], [0.3, 2.0]], [100.0], h, jac, [[1e12]])
    assert abs(xa[0] - 1.0) < 1e-8 and abs(xa[1] - 2.0) < 1e-8

History

Sasaki proposed variational objective analysis in the late 1950s, with dynamical constraints imposed through a cost function. Lorenc showed in 1986 that the analysis of optimal interpolation is the minimizer of a cost function derived from Bayes' theorem, which opened the way to a variational method with nonlinear observation operators and without data selection. Parrish and Derber's spectral statistical interpolation, described in 1992, replaced optimal interpolation at the US National Meteorological Center, and ECMWF followed with its own 3D-Var in the mid 1990s, before moving to 4D-Var in 1997. The incremental form with outer and inner loops was proposed for 4D-Var by Courtier, Thepaut and Hollingsworth in 1994, and 3D-Var systems use the same structure.

References

  1. A. C. Lorenc, Analysis methods for numerical weather prediction, Quarterly Journal of the Royal Meteorological Society 112(474) (1986) 1177-1194, the Bayesian derivation of the variational cost and its equivalence with optimal interpolation
  2. D. F. Parrish and J. C. Derber, The National Meteorological Center's spectral statistical-interpolation analysis system, Monthly Weather Review 120(8) (1992) 1747-1763, the first operational 3D-Var, with B modeled in spectral space
  3. Eugenia Kalnay, Atmospheric Modeling, Data Assimilation and Predictability, Cambridge University Press, 2003, Section 5.5 (3D-Var, the physical space analysis scheme, and their relation to OI)
  4. K. Law, A. Stuart and K. Zygalakis, Data Assimilation, A Mathematical Introduction, Springer, 2015, Section 4.2.1 (3DVAR as a filter) and Section 4.4.2 (the 3DVAR filter for the Lorenz models)
  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