Algorithm Search⌘K

Algorithmresearch

Hybrid ensemble-variational assimilation

Also called EnVar, hybrid 3D-Var.

Blends a static background covariance with a localized ensemble covariance inside a variational cost; used at several operational centers.

Time
Θ(n^3 + p^3 + m (N n^2 + p n + p^2)) worst
Space
Θ(N n + n^2 + p^2) extra
Where
N = the ensemble size; m = the number of conjugate gradient steps, at most p + 1; n = the state dimension; p = the number of observations
Properties
deterministic
Origin
Thomas M. Hamill, Chris Snyder, Andrew C. Lorenc, 2000

Hybrid ensemble-variational assimilation is 3D-Var with a background error covariance that mixes two parts: a static covariance BcB_c, modelled once from long statistics, and the sample covariance of an ensemble of forecasts, with covariance localization by a matrix LL:

B=βc2Bc+βe2 L∘(X′X′⊤).B = \beta_c^2 B_c + \beta_e^2\, L \circ (X'X'^\top).

The static part is full rank but the same every day. The ensemble part follows the weather of the day but has rank at most N−1N - 1 and sampling noise, which the localization damps. The matrix BB is never formed. Instead the analysis increment is written with the alpha control variable of Lorenc (2003), δx=βcUcvc+βe∑ixi′∘(ULαi)\delta x = \beta_c U_c v_c + \beta_e \sum_i x'_i \circ (U_L\alpha_i), and the cost is minimized over (vc,α1,…,αN)(v_c, \alpha_1, \ldots, \alpha_N). Wang, Snyder and Hamill (2007) showed that this gives the same analysis as 3D-Var with the mixed BB. Hybrid systems of this kind are used at several operational centers (Bannister 2017).

In plain words

To combine a forecast with measurements, the system must know how the forecast errors are spread out and linked in space. One source of this knowledge is long statistics, which are reliable but the same every day. Another is a small set of forecasts that start from slightly different states: where they disagree, today's forecast is uncertain. This source changes with the weather, but a small set gives noisy and incomplete links, so links between far apart points are cut off. The hybrid method uses a weighted mix of both sources. It does this without building the large table of links, by searching over a few extra unknowns for each forecast in the set.

The problem

Input. A background xbx^b, an ensemble of forecasts x1,…,xNx_1, \ldots, x_N, a static covariance BcB_c, a localization matrix LL (for example from the Gaspari-Cohn function), weights βc2\beta_c^2 and βe2\beta_e^2, and observations y=Hx+ϵy = Hx + \epsilon with ϵ∼N(0,R)\epsilon \sim N(0, R). Here HH is linear. Notation of Ide, Courtier, Ghil and Lorenc (1997).

Output. The analysis xa=xb+δxx^a = x^b + \delta x, where δx=Uw\delta x = Uw and ww minimizes

J(w)=12∣w∣2+12(d−HUw)⊤R−1(d−HUw),d=y−Hxb,Uw=βcUcvc+βe∑i=1Nxi′∘(ULαi),J(w) = \tfrac12 |w|^2 + \tfrac12 (d - HUw)^\top R^{-1}(d - HUw), \qquad d = y - Hx^b, \qquad Uw = \beta_c U_cv_c + \beta_e \sum_{i=1}^N x'_i \circ (U_L\alpha_i),

with xi′=(xi−xˉ)/N−1x'_i = (x_i - \bar x)/\sqrt{N - 1}, UcUc⊤=BcU_cU_c^\top = B_c, ULUL⊤=LU_LU_L^\top = L, and ∘\circ the entrywise product.

The algorithm

  1. HYBRID-ENVAR(x^b, {x_i}, B_c, L, beta_c^2, beta_e^2, y, H, R)
  2. 1x'_i <- (x_i - mean) / sqrt(N - 1) for i = 1..N
  3. 2U_c <- square root of B_c ; U_L <- square root of L
  4. 3d <- y - H x^b
  5. 4U w = beta_c U_c v_c + beta_e sum_i x'_i o (U_L alpha_i) ▷ w = (v_c, alpha_1..alpha_N)
  6. 5b <- U^T H^T R^-1 d
  7. 6A w = w + U^T H^T R^-1 H U w
  8. 7w <- solve A w = b by conjugate gradients
  9. 8x^a <- x^b + U w
  10. 9return x^a

The transpose U⊤U^\top in lines L5 and L6 maps a vector gg of the state space to (βcUc⊤g,βeUL⊤(x1′∘g),…,βeUL⊤(xN′∘g))(\beta_c U_c^\top g, \beta_e U_L^\top(x'_1 \circ g), \ldots, \beta_e U_L^\top(x'_N \circ g)). The cost has no B−1B^{-1}: the control variable transform makes the background term 12∣w∣2\tfrac12|w|^2. In large systems UcU_c is a sequence of operators (balance, vertical and horizontal transforms), and ULU_L is a spectral or recursive filter, not a dense Cholesky factor.

Example

One variable. Take xb=0x^b = 0, Bc=1B_c = 1, the ensemble {−1,1}\{-1, 1\}, L=1L = 1, βc2=βe2=12\beta_c^2 = \beta_e^2 = \tfrac12, and one observation y=1y = 1 with H=R=1H = R = 1. The perturbations are x1,2′=∓1/1=∓1x'_{1,2} = \mp 1/\sqrt{1} = \mp 1, so the ensemble variance is 2 and the hybrid variance is B=12⋅1+12⋅2=1.5B = \tfrac12 \cdot 1 + \tfrac12 \cdot 2 = 1.5. The analysis is xa=1.5/(1.5+1)=0.6x^a = 1.5/(1.5 + 1) = 0.6, between the static analysis 0.50.5 and the ensemble analysis 2/32/3. The reference code gives 0.60.6 to rounding error.

Flow-dependent errors. On a line of 16 points, each case has its own background error variance, a bump of height 4 at a random place over a floor of 0.05, with a Gaspari-Cohn correlation of half-width 3. The static covariance has the right correlation but the mean variance everywhere. Every second point is observed with error variance 0.25. The table gives the mean squared analysis error over 40 cases (a measurement), with localization of half-width 4:

covariance N=5N = 5 N=10N = 10
static only 0.207 0.207
localized ensemble only 0.173 0.139
hybrid, βc2=βe2=0.5\beta_c^2 = \beta_e^2 = 0.5 0.176 0.168
hybrid, βc2=0.25\beta_c^2 = 0.25, βe2=0.75\beta_e^2 = 0.75 0.166 0.151
the true covariance 0.112 0.112

With 5 members the hybrid with weight 0.75 on the ensemble beats both of its parts. With 10 members the localized ensemble alone is better: the best weights depend on the ensemble size and on how good the static covariance is, and they must be tuned.

Correctness

The proof shows that UU⊤=βc2Bc+βe2L∘(X′X′⊤)UU^\top = \beta_c^2B_c + \beta_e^2 L \circ (X'X'^\top), and with a push-through identity that the minimizer of JJ gives xa=xb+BH⊤(HBH⊤+R)−1dx^a = x^b + BH^\top(HBH^\top + R)^{-1}d with this BB, the 3D-Var analysis with the hybrid covariance (a theorem; Wang, Snyder and Hamill 2007). The Hessian is the identity plus a matrix of rank at most pp, so the conjugate gradient method converges in at most p+1p + 1 steps in exact arithmetic. The tests check the analysis to 10−810^{-8} against a direct solve with the dense hybrid covariance on random problems, and the limits βe=0\beta_e = 0 (3D-Var with BcB_c) and βc=0\beta_c = 0 without localization (the increment lies in the span of the perturbations).

Proof: The alpha control variable minimizes the 3D-Var cost with the hybrid covariancefull

Setting. Bc=UcUc⊤B_c = U_cU_c^\top and L=ULUL⊤L = U_LU_L^\top are symmetric positive semidefinite n×nn \times n matrices, x1′,…,xN′x'_1, \ldots, x'_N are the scaled ensemble perturbations of line L1, Di=diag(xi′)D_i = \mathrm{diag}(x'_i), βc2,βe2≥0\beta_c^2, \beta_e^2 \ge 0, HH is a p×np \times n matrix, RR is symmetric positive definite and d=y−Hxbd = y - Hx^b. The control is w=(vc,α1,…,αN)∈Rn(N+1)w = (v_c, \alpha_1, \ldots, \alpha_N) \in \mathbb R^{n(N+1)}, and line L4 is the linear map

Uw=βcUcvc+βe∑i=1NDiULαi.Uw = \beta_c U_c v_c + \beta_e \sum_{i=1}^N D_i U_L \alpha_i .

The cost is J(w)=12∣w∣2+12(d−HUw)⊤R−1(d−HUw)J(w) = \tfrac12 |w|^2 + \tfrac12 (d - HUw)^\top R^{-1}(d - HUw).

Lemma 1 (the implied covariance).

UU⊤=βc2Bc+βe2 L∘(∑i=1Nxi′xi′⊤)=:Bh.UU^\top = \beta_c^2 B_c + \beta_e^2\, L \circ \Big(\sum_{i=1}^N x'_i x'^\top_i\Big) =: B_h .

Proof. The blocks of UU are βcUc\beta_c U_c and βeDiUL\beta_e D_iU_L, so UU⊤=βc2UcUc⊤+βe2∑iDiULUL⊤Di=βc2Bc+βe2∑iDiLDiUU^\top = \beta_c^2 U_cU_c^\top + \beta_e^2 \sum_i D_i U_LU_L^\top D_i = \beta_c^2 B_c + \beta_e^2 \sum_i D_i L D_i. The entry (j,k)(j, k) of DiLDiD_iLD_i is xij′Ljkxik′x'_{ij} L_{jk} x'_{ik}, so ∑iDiLDi=L∘∑ixi′xi′⊤\sum_i D_iLD_i = L \circ \sum_i x'_ix'^\top_i. □\square

In particular BhB_h is positive semidefinite, which is the Schur product theorem for LL and the sample covariance X′X′⊤X'X'^\top.

Theorem 2. The minimizer w∗w^\ast of JJ is unique, and

xb+Uw∗=xb+BhH⊤(HBhH⊤+R)−1d,x^b + Uw^\ast = x^b + B_hH^\top (HB_hH^\top + R)^{-1} d ,

which is the minimizer of the 3D-Var cost with background covariance BhB_h when BhB_h is positive definite, and the best linear unbiased estimate with that covariance in every case.

Proof. JJ is a quadratic with Hessian A=I+U⊤H⊤R−1HUA = I + U^\top H^\top R^{-1} HU, which is symmetric positive definite, so w∗=A−1U⊤H⊤R−1dw^\ast = A^{-1} U^\top H^\top R^{-1} d is the unique minimizer. The identity

(I+U⊤H⊤R−1HU) U⊤H⊤=U⊤H⊤R−1(R+HUU⊤H⊤)(I + U^\top H^\top R^{-1}HU)\, U^\top H^\top = U^\top H^\top R^{-1}(R + HUU^\top H^\top)

holds by expanding both sides. Multiply it by A−1A^{-1} on the left and by (R+HUU⊤H⊤)−1(R + HUU^\top H^\top)^{-1} on the right: U⊤H⊤(HBhH⊤+R)−1=A−1U⊤H⊤R−1U^\top H^\top (HB_hH^\top + R)^{-1} = A^{-1}U^\top H^\top R^{-1}, using Lemma 1. So w∗=U⊤H⊤(HBhH⊤+R)−1dw^\ast = U^\top H^\top (HB_hH^\top + R)^{-1} d and Uw∗=BhH⊤(HBhH⊤+R)−1dUw^\ast = B_hH^\top (HB_hH^\top + R)^{-1} d. If BhB_h is positive definite, this is the 3D-Var minimizer xb+BhH⊤(HBhH⊤+R)−1dx^b + B_hH^\top (HB_hH^\top + R)^{-1}d (the Kalman gain form of the 3D-Var normal equations). □\square

Termination. A−I=U⊤H⊤R−1HUA - I = U^\top H^\top R^{-1}HU has rank at most pp, so AA has at most p+1p + 1 distinct eigenvalues, and the conjugate gradient method of line L7 reaches w∗w^\ast in at most p+1p + 1 steps in exact arithmetic. The code also stops after at most 2n(N+1)2n(N + 1) steps.

Limits. With βe=0\beta_e = 0 the result is 3D-Var with βc2Bc\beta_c^2B_c. With βc=0\beta_c = 0 and LL the matrix of ones it is the analysis with the raw sample covariance, whose increment BhH⊤(⋅)B_hH^\top(\cdot) lies in the span of the perturbations.

Summary. The alpha control variable gives the same analysis as 3D-Var with the hybrid covariance βc2Bc+βe2L∘X′X′⊤\beta_c^2B_c + \beta_e^2 L \circ X'X'^\top (Wang, Snyder and Hamill 2007), and it never forms that matrix. The tests check the analysis to 10−810^{-8} against a direct solve with the hybrid covariance on random problems, and the two limits. ■\blacksquare

Complexity

The control has n(N+1)n(N + 1) entries. With dense square roots one product with UU or U⊤U^\top costs Θ(Nn2)\Theta(Nn^2), the observation term Θ(pn+p2)\Theta(pn + p^2), and the Cholesky factorizations of BcB_c, LL and RR cost Θ(n3+p3)\Theta(n^3 + p^3) once. With m≤p+1m \le p + 1 conjugate gradient steps the time is Θ(n3+p3+m(Nn2+pn+p2))\Theta(n^3 + p^3 + m(Nn^2 + pn + p^2)), and the memory is Θ(Nn+n2+p2)\Theta(Nn + n^2 + p^2). In operational systems the square roots are fast operators, so a product costs about NN times one application of the localization operator, and the ensemble itself, NN forecasts, is the main extra cost over 3D-Var.

Properties

  • Equivalent to 3D-Var with the hybrid BB. The alpha control variable and the explicit covariance give the same analysis (a theorem).
  • Positive semidefinite by construction. L∘(X′X′⊤)L \circ (X'X'^\top) is positive semidefinite by the Schur product theorem, so the hybrid BB is a valid covariance for any weights βc2,βe2≥0\beta_c^2, \beta_e^2 \ge 0.
  • Full rank. With βc>0\beta_c > 0 and BcB_c positive definite, the hybrid BB has full rank, unlike the raw ensemble covariance, whose increments lie in the span of the N−1N - 1 independent perturbations.
  • Flow dependence. The ensemble part gives variances and correlations of the day, which a static BcB_c cannot.
  • The weights need tuning. The best βc2\beta_c^2 and βe2\beta_e^2 depend on the ensemble size and quality (a measurement, as in the example).

Variants and improvements

  • 4DEnVar. Use ensemble trajectories over a time window instead of a single time, which gives a 4D analysis without tangent linear and adjoint models.
  • Hybrid 4D-Var. Use the hybrid BB at the start of the window of incremental 4D-Var, with the tangent linear and adjoint models for the propagation.
  • Ensemble of data assimilations. Make the ensemble by running the variational system itself many times with perturbed observations, instead of with a separate ensemble Kalman filter.
  • Scale-dependent localization. Localize different spatial scales of the perturbations with different length scales.
  • Pure EnVar. βc=0\beta_c = 0: the variational analysis with only the localized ensemble covariance.

When to use it

Use a hybrid when a variational system already exists and an ensemble is available: it adds flow-dependent covariances at the price of the ensemble and NN extra control fields. It helps most when the ensemble is small and the static covariance is reasonable. With a large and well-tuned ensemble, the weight on the ensemble part can grow. If no static covariance model exists, an ensemble Kalman filter or the LETKF is simpler.

Pitfalls

  • No localization (line L4). Without LL, the ensemble part has rank N−1N - 1 and spurious long-range correlations, and observations change the state far away.
  • Wrong perturbation scaling (line L1). The perturbations must be divided by N−1\sqrt{N - 1}, or the ensemble part is N−1N - 1 times too large or too small.
  • Weights that do not sum to the right total. If the static and the ensemble covariances are both good estimates of BB, then βc2+βe2=1\beta_c^2 + \beta_e^2 = 1 keeps the variance right; other choices inflate or deflate it.
  • Ensemble spread that is too small. An under-dispersive ensemble makes the ensemble part too small; use covariance inflation on the ensemble.
  • An adjoint of UU that is not exact (lines L5 and L6). Then the Hessian is not symmetric and the conjugate gradient method fails. Check UU and U⊤U^\top with the dot product test.

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.

hybrid_ensemble_variational.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hybrid-ensemble-variational/. The authors are listed in prov/GBD29Q.jsonl.

"""Hybrid ensemble-variational analysis (hybrid 3D-Var) with the alpha control variable.

Notation of Ide, Courtier, Ghil and Lorenc (1997). The analysis increment is

    dx = beta_c U_c v_c + beta_e sum_i x'_i o (U_L alpha_i),

where U_c U_c^T = B_c is the static (climatological) covariance, the x'_i =
(x_i - mean) / sqrt(N - 1) are the scaled ensemble perturbations, o is the
entrywise product, and U_L U_L^T = L is the localization matrix. The cost
over the control w = (v_c, alpha_1, ..., alpha_N) is

    J(w) = 1/2 |w|^2 + 1/2 (d - H dx)^T R^-1 (d - H dx),   d = y - H x^b,

and it is the 3D-Var cost with the hybrid background covariance

    B = beta_c^2 B_c + beta_e^2 L o (X' X'^T)

(Lorenc 2003; Wang, Snyder and Hamill 2007). The observation operator H is
linear here, and the minimizer is the conjugate gradient method.
"""

import math

import scimat


def gaspari_cohn(r, c):
    """Return the Gaspari-Cohn fifth order correlation at distance r for the half-width c (zero beyond 2c)."""
    z = abs(r) / c
    if z <= 1.0:
        return -0.25 * z**5 + 0.5 * z**4 + 0.625 * z**3 - (5.0 / 3.0) * z**2 + 1.0
    if z <= 2.0:
        return z**5 / 12.0 - 0.5 * z**4 + 0.625 * z**3 + (5.0 / 3.0) * z**2 - 5.0 * z + 4.0 - 2.0 / (3.0 * z)
    return 0.0


def localization_matrix(positions, c):
    """Return the matrix L_jk = gaspari_cohn(positions[j] - positions[k], c)."""
    return [[gaspari_cohn(a - b, c) for b in positions] for a in positions]


def perturbations(ensemble):
    """Return (mean, [x'_i]) with x'_i = (x_i - mean) / sqrt(N - 1)."""
    N = len(ensemble)
    n = len(ensemble[0])
    mean = [sum(x[j] for x in ensemble) / N for j in range(n)]
    s = 1.0 / math.sqrt(N - 1)
    return mean, [[s * (x[j] - mean[j]) for j in range(n)] for x in ensemble]


def _square_root(A):
    """Return a lower triangular U with U U^T = A, with a tiny shift if A is only semidefinite."""
    try:
        return scimat.cholesky(A)
    except ValueError:
        n = len(A)
        eps = 1e-12 * max(1.0, max(abs(A[i][i]) for i in range(n)))
        return scimat.cholesky([[A[i][j] + (eps if i == j else 0.0) for j in range(n)] for i in range(n)])


def conjugate_gradient(apply_a, b, tol=1e-13, max_iter=None):
    """Solve A w = b for symmetric positive definite A given as a function."""
    n = len(b)
    if max_iter is None:
        max_iter = 2 * n
    w = [0.0] * n
    r = list(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)
        w = [wi + alpha * qi for wi, qi in zip(w, 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 w


def hybrid_envar(xb, ensemble, Bc, L, beta_c2, beta_e2, y, H, R):
    """Return the hybrid analysis x^a, with the weights beta_c^2 and beta_e^2 of the two covariances."""
    n = len(xb)
    N = len(ensemble)
    _, xp = perturbations(ensemble)  # @line L1
    Uc = _square_root(Bc)  # @line L2
    UL = _square_root(L)
    bc, be = math.sqrt(beta_c2), math.sqrt(beta_e2)
    LR = scimat.cholesky(R)
    Ht = scimat.transpose(H)
    Uct, ULt = scimat.transpose(Uc), scimat.transpose(UL)
    d = scimat.sub(y, scimat.matvec(H, xb))  # @line L3

    def U(w):  # @line L4
        dx = scimat.scale(bc, scimat.matvec(Uc, w[:n]))
        for i in range(N):
            loc = scimat.matvec(UL, w[n * (i + 1) : n * (i + 2)])
            dx = [a + be * p * q for a, p, q in zip(dx, xp[i], loc)]
        return dx

    def Ut(g):
        out = scimat.scale(bc, scimat.matvec(Uct, g))
        for i in range(N):
            out.extend(scimat.scale(be, scimat.matvec(ULt, [p * q for p, q in zip(xp[i], g)])))
        return out

    b = Ut(scimat.matvec(Ht, scimat.cholesky_solve(LR, d)))  # @line L5

    def apply_a(w):  # @line L6
        g = scimat.matvec(Ht, scimat.cholesky_solve(LR, scimat.matvec(H, U(w))))
        return [wi + gi for wi, gi in zip(w, Ut(g))]

    w = conjugate_gradient(apply_a, b)  # @line L7
    xa = scimat.add(xb, U(w))  # @line L8
    return xa  # @line L9


def hybrid_covariance(ensemble, Bc, L, beta_c2, beta_e2):
    """Return the hybrid covariance beta_c^2 B_c + beta_e^2 L o (X' X'^T) as a dense matrix."""
    _, xp = perturbations(ensemble)
    n = len(Bc)
    return [[beta_c2 * Bc[j][k] + beta_e2 * L[j][k] * sum(x[j] * x[k] for x in xp) for k in range(n)] for j in range(n)]
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_hybrid_ensemble_variational.py 120 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/hybrid-ensemble-variational/. The authors are listed in prov/GBD29Q.jsonl.

import math
import random

import scimat
from hybrid_ensemble_variational import gaspari_cohn, hybrid_covariance, hybrid_envar, localization_matrix


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


def three_d_var(xb, B, y, H, R):
    """Reference: the 3D-Var minimizer x^b + B H^T (H B H^T + R)^-1 (y - H x^b), by elimination."""
    HB = scimat.matmul(H, B)
    S = scimat.add(scimat.matmul(HB, scimat.transpose(H)), R)
    w = scimat.solve(S, scimat.sub(y, scimat.matvec(H, xb)))
    return scimat.add(xb, scimat.matvec(scimat.transpose(HB), w))


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


def draw(rng, LB):
    return scimat.matvec(LB, [rng.gauss(0, 1) for _ in range(len(LB))])


def test_scalar_check_value():
    # B_c = 1, members -1 and 1 (variance 2), weights 1/2 each: B = 1.5 and x^a = 1.5 / 2.5.
    xa = hybrid_envar([0.0], [[-1.0], [1.0]], [[1.0]], [[1.0]], 0.5, 0.5, [1.0], [[1.0]], [[1.0]])
    assert abs(xa[0] - 0.6) < 1e-14


def test_gaspari_cohn_values():
    assert gaspari_cohn(0.0, 2.0) == 1.0
    assert abs(gaspari_cohn(2.0, 2.0) - 5.0 / 24.0) < 1e-15  # z = 1 from both pieces
    assert abs(gaspari_cohn(2.0 + 1e-9, 2.0) - 5.0 / 24.0) < 1e-8
    assert abs(gaspari_cohn(4.0, 2.0)) < 1e-14 and gaspari_cohn(5.0, 2.0) == 0.0


def test_equals_3dvar_with_hybrid_covariance():
    rng = random.Random(91)
    for _ in range(25):
        n = rng.randint(1, 6)
        N = rng.randint(2, 5)
        p = rng.randint(1, n + 1)
        Bc = random_spd(rng, n)
        ens = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
        L = localization_matrix([float(j) for j in range(n)], rng.uniform(0.5, 3.0))
        bc2 = rng.uniform(0.0, 1.0)
        be2 = rng.uniform(0.0, 1.0)
        H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
        R = random_spd(rng, p)
        xb = [rng.uniform(-1, 1) for _ in range(n)]
        y = [rng.uniform(-2, 2) for _ in range(p)]
        xa = hybrid_envar(xb, ens, Bc, L, bc2, be2, y, H, R)
        ref = three_d_var(xb, hybrid_covariance(ens, Bc, L, bc2, be2), y, H, R)
        assert close(xa, ref, 1e-8)


def test_limits_static_and_pure_ensemble():
    rng = random.Random(92)
    n, N = 5, 3
    Bc = random_spd(rng, n)
    ens = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
    ones = [[1.0] * n for _ in range(n)]
    H = [[1.0 if j == 2 * i else 0.0 for j in range(n)] for i in range(3)]
    R = [[0.5 if i == j else 0.0 for j in range(3)] for i in range(3)]
    xb = [0.0] * n
    y = [1.0, -1.0, 0.5]
    assert close(hybrid_envar(xb, ens, Bc, ones, 1.0, 0.0, y, H, R), three_d_var(xb, Bc, y, H, R), 1e-10)
    xp = hybrid_covariance(ens, Bc, ones, 0.0, 1.0)  # the sample covariance X' X'^T
    xa = hybrid_envar(xb, ens, Bc, ones, 0.0, 1.0, y, H, R)
    assert close(xa, three_d_var(xb, xp, y, H, R), 1e-9)
    # Without localization the increment lies in the span of the N perturbations.
    mean = [sum(x[j] for x in ens) / N for j in range(n)]
    P = [[x[j] - mean[j] for j in range(n)] for x in ens[:2]]
    G = [[scimat.dot(a, b) for b in P] for a in P]
    c = scimat.solve(G, [scimat.dot(a, xa) for a in P])
    resid = scimat.sub(xa, [c[0] * P[0][j] + c[1] * P[1][j] for j in range(n)])
    assert scimat.norm2(resid) < 1e-9


def test_hybrid_beats_static_and_localized_ensemble_in_a_twin():
    # Each case has its own error variance profile (a bump at a random place), which the
    # ensemble of 5 members sees and the static B_c, with the mean variance, does not.
    n, N = 16, 5
    pos = [float(j) for j in range(n)]
    C = localization_matrix(pos, 3.0)
    Lloc = localization_matrix(pos, 4.0)
    ones = [[1.0] * n for _ in range(n)]
    H = [[1.0 if j == 2 * i else 0.0 for j in range(n)] for i in range(8)]
    R = [[0.25 if i == j else 0.0 for j in range(8)] for i in range(8)]
    err = {"static": 0.0, "ensemble": 0.0, "hybrid": 0.0}
    for seed in range(93, 133):
        rng = random.Random(seed)
        xb = [0.0] * n
        c0 = rng.uniform(0, n - 1)
        s = [0.05 + 4.0 * math.exp(-(((j - c0) / 2.0) ** 2)) for j in range(n)]
        Btrue = [[math.sqrt(s[a] * s[b]) * C[a][b] for b in range(n)] for a in range(n)]
        LB = scimat.cholesky(Btrue)
        Bc = scimat.scale(sum(s) / n, C)
        truth = draw(rng, LB)
        y = [v + rng.gauss(0, 0.5) for v in scimat.matvec(H, truth)]
        ens = [draw(rng, LB) for _ in range(N)]
        cases = {
            "static": hybrid_envar(xb, ens, Bc, ones, 1.0, 0.0, y, H, R),
            "ensemble": hybrid_envar(xb, ens, Bc, Lloc, 0.0, 1.0, y, H, R),
            "hybrid": hybrid_envar(xb, ens, Bc, Lloc, 0.25, 0.75, y, H, R),
        }
        for key, xa in cases.items():
            err[key] += sum((a - t) ** 2 for a, t in zip(xa, truth)) / n
    assert err["hybrid"] < err["ensemble"] < err["static"]

History

Hamill and Snyder (2000) proposed a hybrid of an ensemble Kalman filter and 3D-Var, with a weighted sum of the static and the ensemble covariance. Lorenc (2003) introduced the alpha control variable, which brings the localized ensemble covariance into a variational system without forming it, and Wang, Snyder and Hamill (2007) proved that the two formulations are equivalent. Hybrid ensemble-variational systems became operational at several weather centers in the following years (Bannister 2017).

References

  1. T. M. Hamill and C. Snyder, A hybrid ensemble Kalman filter-3D variational analysis scheme, Monthly Weather Review 128 (2000) 2905-2919, the weighted sum of the static and the ensemble covariance in 3D-Var
  2. A. C. Lorenc, The potential of the ensemble Kalman filter for NWP, a comparison with 4D-Var, Quarterly Journal of the Royal Meteorological Society 129 (2003) 3183-3203, the alpha control variable with localization in a variational system
  3. X. Wang, C. Snyder and T. M. Hamill, On the theoretical equivalence of differently proposed ensemble-3DVAR hybrid analysis schemes, Monthly Weather Review 135(1) (2007) 222-227, the proof that the covariance form and the alpha control variable form give the same analysis
  4. R. N. Bannister, A review of operational methods of variational and ensemble-variational data assimilation, Quarterly Journal of the Royal Meteorological Society 143(703) (2017) 607-633, the hybrid and ensemble-variational systems of the operational centers
  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