Algorithmresearch
Four-dimensional ensemble-variational assimilation
Also called 4DEnVar.
Replaces the tangent linear and adjoint models of 4D-Var by ensemble trajectories over the window, so no adjoint code is needed.
- Time
- Θ(N K c + n^3 + p^3 + m (K N n^2 + p n)) worst
- Space
- Θ(N K n + n^2 + p^2) extra
- Where
- K = the number of time steps in the window; N = the ensemble size; c = the cost of one model step; m = the number of conjugate gradient steps, at most p + 1; n = the state dimension; p = the number of observations in the window
- Model
- Real RAM
- Properties
- deterministicnot needs adjoint
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Chengsi Liu, Qingnong Xiao, Bin Wang, Mark Buehner, 2008
Four-dimensional ensemble-variational assimilation (4DEnVar) fits a model state to all observations of a time window, like 4D-Var, but it needs no tangent linear and no adjoint model. An ensemble of forecasts is run forward over the window with the full model. At each time the scaled perturbations of the members about their mean describe how an error at the start of the window has grown by time . The increment at time is
with the same control at all times and a localization matrix . The control is found by minimizing a quadratic cost with the conjugate gradient method. This is the alpha control variable of hybrid ensemble-variational assimilation, applied over the window. The implied covariance between the increments at times and is , and for a linear model without localization and an ensemble with the analysis is exactly 4D-Var.
In plain words
4D-Var finds the start of a forecast that best fits all measurements in a time window. To do this it needs special extra code that runs the model backward, and this code is hard to write and to keep correct. 4DEnVar replaces this code with a set of ordinary forecasts that start from slightly different states. The way these forecasts spread apart over the window shows how a change at the start moves and grows. The method then looks for the best mix of these spreads to fit the measurements. It uses only the normal forecast model, run once for each member of the set, and the runs can all go at the same time.
The problem
Input. A background state at the start of the window, a model for , an ensemble of start states , a localization matrix , and observations with at the times , with linear . Notation of Ide, Courtier, Ghil and Lorenc (1997).
Output. The analysis at the start, at the end and at the observation times, where is the background trajectory, is as above and minimizes
with and the entrywise product.
The algorithm
FOUR-D-ENVAR(x^b, {x_i(0)}, L, {(H_k, y_k, R_k)}, M, K)- 1
x^b_k <- run the model from x^b for k = 0..K - 2
x_i(k) <- run the model from x_i(0) for i = 1..N ▷ forward only - 3
x'_i(k) <- (x_i(k) - mean_k) / sqrt(N - 1) ; U_L <- square root of L - 4
d_k <- y_k - H_k x^b_k for every k in T - 5
U_k alpha = sum_i x'_i(k) o (U_L alpha_i) - 6
b <- sum_k U_k^T H_k^T R_k^-1 d_k - 7
A alpha = alpha + sum_k U_k^T H_k^T R_k^-1 H_k U_k alpha - 8
alpha <- solve A alpha = b by conjugate gradients - 9
x^a_k <- x^b_k + U_k alpha for each k - 10
return {x^a_k}
The transpose maps a vector to . In 4D-Var the same products need the tangent linear model forward and the adjoint model backward at every iteration. Here the time dimension is carried by the stored perturbations , so an iteration costs only products with and with the observation operators. In large systems is a spectral or recursive filter, and only the perturbations at the observation times are stored.
Example
One variable. Take the model , , and the two members . Their perturbations are , so , and . One observation with gives , , , and
This is the 4D-Var analysis . The reference code gives and to rounding error.
Lorenz-63. A twin run uses the Lorenz-63 equations with forward Euler steps of , a window of steps, a background error of standard deviation 1 in each variable, members drawn about the background with the same spread, and all three variables observed at steps 10 and 25 with error variance 0.25. No localization is used. The table gives the mean error norm over 20 cases (a measurement):
| start of window | end of window | |
|---|---|---|
| background | 1.45 | 2.10 |
| 4DEnVar, | 1.11 | 0.61 |
| 4DEnVar, | 0.94 | 0.46 |
| 4DEnVar, | 0.89 | 0.47 |
The error at the end of the window falls to about a quarter of the background error. More members help up to about ; after that the error is limited by the nonlinearity of the model over the window and by the observation errors.
Correctness
The proof shows that , and with a push-through identity that the minimizer gives the conditional mean of the increments given all observations of the window, for a Gaussian prior with these covariance blocks (a theorem). For a linear model with the matrix of ones and , the perturbations are , the blocks are , and the analysis is the strong-constraint 4D-Var analysis (a theorem). The tests check the first result to against a direct solve with the stacked covariance, for a linear and a nonlinear model, the second to against the 4D-Var formula with an ensemble built to have exactly, and the count of forward model calls.
Proof: 4DEnVar conditions on all observations of the window with the localized four-dimensional ensemble covariancefull
Setting. The window has the time levels , and is the set of observation times. Lines L1 and L2 give the background trajectory and the member trajectories , , with . Let , let be the matrix with the columns , and let . is symmetric positive semidefinite (line L3). For , is a matrix, is symmetric positive definite and (line L4). The control is , and line L5 is the linear map
The cost is . Stack the times of : has the block rows , , and has the blocks . Then , and .
Lemma 1 (the implied four-dimensional covariance). For all times and ,
Proof. has the blocks , so . The entry of is , and the sum over is .
So the same control at all times gives increments whose covariance between times and is the localized sample covariance of the ensemble between those times. The block matrix with the blocks is positive semidefinite.
Theorem 2. The minimizer of is unique, and the analysis of line L9 is
This is the conditional mean of the increments at time given all observations of the window, for a Gaussian prior with the covariance blocks .
Proof. is a quadratic with Hessian , which is symmetric positive definite, so is the unique minimizer. Line L6 computes the right side , and line L7 applies . Expanding both sides gives
Multiply on the left by and on the right by : . So and by Lemma 1. For jointly Gaussian increments with the covariances and observations , , the conditional mean of is , and this is the same expression.
Theorem 3 (equivalence with 4D-Var). Let the model be linear, , with and . Let be the matrix of ones and let be positive definite (this needs ). Then is the minimizer of the strong-constraint 4D-Var cost with background covariance , and for every .
Proof. The model is linear, so , and . With the matrix of ones, . Let have the block rows , . Then , and, by Theorem 2,
The 4D-Var cost is a quadratic in , and its minimizer is the same vector by the Sherman-Morrison-Woodbury identity . Finally and , so .
For a nonlinear model, the member trajectories replace the tangent linear model: is a finite difference estimate of applied to , and the analysis is not in general a model trajectory.
Termination. has rank at most , so has at most distinct eigenvalues, and the conjugate gradient method of line L8 reaches in at most steps in exact arithmetic. The code also stops after at most steps. The model runs only forward, steps for the background and steps for each member, so line L1 and line L2 call it times and the minimization does not call it at all.
Summary. 4DEnVar gives the analysis of all observations of the window with the localized four-dimensional covariance (Theorem 2), and for a linear model without localization and an ensemble with it is strong-constraint 4D-Var (Theorem 3). The tests check Theorem 2 to against a direct solve with the stacked covariance for a linear and a nonlinear model, Theorem 3 to against the 4D-Var formula, and the count of model calls.
Complexity
The model runs cost for forward runs of steps, and they are independent, so they can run in parallel. The control has entries. With a dense , one product with costs , the Cholesky factorizations of and of the cost once, and conjugate gradient steps give the time . The stored perturbations take memory, or if only the observation times are kept. In 4D-Var each iteration needs one tangent linear and one adjoint run over the window, so 4DEnVar trades such pairs of runs for forward runs that run at the same time.
Properties
- No adjoint. The model runs only forward, steps in total, before the minimization starts.
- Four-dimensional covariance. The covariance between the increments at times and is , so an observation at time changes the state at all times of the window (a theorem).
- Exact 4D-Var in the linear case. For a linear model, the matrix of ones and , the analysis is the strong-constraint 4D-Var analysis (a theorem).
- Static localization in time. The same is applied at all times. If features move far during the window, the localization does not move with them, unlike 4D-Var with a localized , whose covariance the tangent linear model carries along.
- The analysis trajectory is not a model trajectory. For a nonlinear model, is in general not .
- Parallel. The ensemble runs are independent, and the minimization has no sequential model runs.
Variants and improvements
- Hybrid 4DEnVar. Add a static covariance part, , to the increment, as in hybrid ensemble-variational assimilation. The static part has no time evolution in 4DEnVar unless a model propagates it.
- Hybrid 4D-Var. Keep the tangent linear and adjoint models of incremental 4D-Var and use the hybrid covariance only at the start of the window.
- Outer loops. Rerun the background and the ensemble from the new analysis to treat stronger nonlinearity, at the cost of more ensemble runs.
- Ensemble Kalman smoother. The ensemble Kalman smoother uses the same four-dimensional ensemble covariances, but it updates the members by a sequential formula instead of a variational minimization.
- Weak constraint. Model error can be added as in weak-constraint 4D-Var, with an ensemble estimate of its covariance.
When to use it
Use 4DEnVar when an ensemble is already run and the model has no maintained adjoint, or when the computer is massively parallel and the sequential tangent linear and adjoint runs of 4D-Var are the bottleneck. It is the four-dimensional form of a hybrid system and needs a good ensemble with enough spread. If an adjoint exists and the window has strong nonlinearity or features that move far, 4D-Var with a hybrid covariance can give better results. If no variational system exists, an ensemble Kalman filter or the LETKF is simpler.
Pitfalls
- No localization (line L5). With much smaller than , the raw four-dimensional covariance has rank and spurious long-range links, also between times. Use covariance localization.
- Wrong perturbation scaling (line L3). The perturbations must be divided by , or the implied covariance is too large or too small.
- Perturbations about the wrong trajectory (lines L1 to L3). The perturbations are deviations from the ensemble mean at each time, not from the background trajectory. If the mean and the background drift apart, the increments are wrong.
- Too long a window. The ensemble perturbations grow nonlinearly and the linear relation between and breaks down. Shorten the window or use outer loops.
- Ensemble spread that is too small. An under-dispersive ensemble gives too small increments; use covariance inflation.
- An inexact transpose of (lines L6 and L7). Then is not symmetric and the conjugate gradient method fails. Check and 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.
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/four-dimensional-ensemble-variational/. The authors are listed in prov/5MYERD.jsonl.
"""Four-dimensional ensemble-variational assimilation (4DEnVar).
Notation of Ide, Courtier, Ghil and Lorenc (1997). The window has the time
levels 0..K. Each ensemble member is run forward over the window with the
full model, and the scaled perturbations x'_i(k) = (x_i(k) - mean_k) /
sqrt(N - 1) at each time replace the tangent linear model of 4D-Var. The
increment at time k is
dx_k = sum_i x'_i(k) o (U_L alpha_i), U_L U_L^T = L,
with the same control alpha = (alpha_1, ..., alpha_N) at all times, and the
cost over alpha is
J = 1/2 |alpha|^2 + sum_(k in T) 1/2 (d_k - H_k dx_k)^T R_k^-1 (d_k - H_k dx_k),
where d_k = y_k - H_k x^b_k is the departure from the background
trajectory. No tangent linear or adjoint model is needed: the model runs
only forward, once for the background and once for each member. The
implied covariance between the increments at times k and l is
L o (X'_k X'_l^T).
The model is a function step(k, x) = M_k(x) for x = x_(k-1). obs maps a
time k to (H_k, y_k, R_k), with a linear observation operator H_k.
"""
import math
import scimat
def run(x0, step, K):
"""Return the trajectory [x_0, ..., x_K] of the model from x0."""
xs = [list(x0)]
for k in range(1, K + 1):
xs.append(step(k, xs[-1]))
return xs
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 four_d_envar(xb, members, L, obs, step, K):
"""Return {k: x^a_k} of 4DEnVar with localization matrix L, for k = 0, K and every observation time."""
n = len(xb)
N = len(members)
background = run(xb, step, K) # @line L1
trajs = [run(m, step, K) for m in members] # @line L2
s = 1.0 / math.sqrt(N - 1)
xp = {}
for k in sorted(set(obs) | {0, K}):
mean = [sum(t[k][j] for t in trajs) / N for j in range(n)]
xp[k] = [[s * (t[k][j] - mean[j]) for j in range(n)] for t in trajs]
UL = _square_root(L) # @line L3
ULt = scimat.transpose(UL)
ob = {k: (H, scimat.transpose(H), y, scimat.cholesky(R)) for k, (H, y, R) in obs.items()}
d = {k: scimat.sub(y, scimat.matvec(H, background[k])) for k, (H, Ht, y, LR) in ob.items()} # @line L4
def U(k, a, loc=None): # @line L5
if loc is None:
loc = [scimat.matvec(UL, a[n * i : n * (i + 1)]) for i in range(N)]
dx = [0.0] * n
for i in range(N):
dx = [v + p * q for v, p, q in zip(dx, xp[k][i], loc[i])]
return dx
def Ut(k, g):
out = []
for i in range(N):
out.extend(scimat.matvec(ULt, [p * q for p, q in zip(xp[k][i], g)]))
return out
b = [0.0] * (N * n) # @line L6
for k, (H, Ht, y, LR) in ob.items():
b = scimat.add(b, Ut(k, scimat.matvec(Ht, scimat.cholesky_solve(LR, d[k]))))
def apply_a(a): # @line L7
loc = [scimat.matvec(UL, a[n * i : n * (i + 1)]) for i in range(N)]
out = list(a)
for k, (H, Ht, y, LR) in ob.items():
g = scimat.matvec(Ht, scimat.cholesky_solve(LR, scimat.matvec(H, U(k, a, loc))))
out = scimat.add(out, Ut(k, g))
return out
a = conjugate_gradient(apply_a, b) # @line L8
loc = [scimat.matvec(UL, a[n * i : n * (i + 1)]) for i in range(N)]
analysis = {}
for k in xp: # @line L9
analysis[k] = scimat.add(background[k], U(k, a, loc))
return analysis # @line L10
def linear_model(M):
"""Return step for the linear model x_k = M x_(k-1)."""
return lambda k, x: scimat.matvec(M, x)
def lorenz63(dt=0.01, sigma=10.0, rho=28.0, beta=8.0 / 3.0):
"""Return step for forward Euler steps of the Lorenz-63 model."""
def step(k, x):
f = [sigma * (x[1] - x[0]), x[0] * (rho - x[2]) - x[1], x[0] * x[1] - beta * x[2]]
return [xi + dt * fi for xi, fi in zip(x, f)]
return step
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_ensemble_variational.py 214 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/four-dimensional-ensemble-variational/. The authors are listed in prov/5MYERD.jsonl.
import math
import random
import scimat
from four_dimensional_ensemble_variational import four_d_envar, linear_model, lorenz63, run
def random_matrix(rng, m, n):
return [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(m)]
def random_spd(rng, n, shift=0.5):
A = random_matrix(rng, n, n)
S = scimat.matmul(A, scimat.transpose(A))
for i in range(n):
S[i][i] += shift
return S
def gaussian_localization(n, c):
return [[math.exp(-((i - j) ** 2) / (2.0 * c * c)) for j in range(n)] for i in range(n)]
def close(a, b, tol):
return all(abs(u - v) <= tol * (1 + abs(v)) for u, v in zip(a, b))
def exact_ensemble(xb, B):
"""Return N = n + 1 members whose scaled perturbations X' satisfy X' X'^T = B exactly."""
n = len(xb)
N = n + 1
basis = [[1.0] * N] + [[1.0 if j == i else 0.0 for j in range(N)] for i in range(n)]
rows = []
for v in basis:
w = list(v)
for q in rows:
c = scimat.dot(w, q)
w = [a - c * b for a, b in zip(w, q)]
rows.append(scimat.scale(1.0 / scimat.norm2(w), w))
W = rows[1:] # n orthonormal rows, each orthogonal to the ones vector
UB = scimat.cholesky(B)
cols = scimat.matmul(UB, W)
return [[xb[j] + math.sqrt(N - 1) * cols[j][i] for j in range(n)] for i in range(N)]
def strong_4dvar_reference(xb, B, M, obs):
"""x^a_0 = x^b + B G^T (G B G^T + R)^-1 (y - G x^b), with G the stacked H_k M^k."""
n = len(xb)
G, y, blocks = [], [], []
for k in sorted(obs):
H, yk, R = obs[k]
Mk = scimat.eye(n)
for _ in range(k):
Mk = scimat.matmul(M, Mk)
G.extend(scimat.matmul(H, Mk))
y.extend(yk)
blocks.append(R)
m = len(y)
Rbig = scimat.zeros(m, m)
off = 0
for R in blocks:
for i in range(len(R)):
for j in range(len(R)):
Rbig[off + i][off + j] = R[i][j]
off += len(R)
GB = scimat.matmul(G, B)
S = scimat.add(scimat.matmul(GB, scimat.transpose(G)), Rbig)
w = scimat.solve(S, scimat.sub(y, scimat.matvec(G, xb)))
return scimat.add(xb, scimat.matvec(scimat.transpose(GB), w))
def localized_reference(xb, members, L, obs, step, K):
"""Brute force: condition on all observations at once with C_kl = L o (X'_k X'_l^T)."""
n, N = len(xb), len(members)
background = run(xb, step, K)
trajs = [run(m, step, K) for m in members]
times = sorted(set(obs) | {0, K})
s = 1.0 / math.sqrt(N - 1)
X = {}
for k in times:
mean = [sum(t[k][j] for t in trajs) / N for j in range(n)]
X[k] = [[s * (t[k][j] - mean[j]) for t in trajs] for j in range(n)]
def C(k, l):
P = scimat.matmul(X[k], scimat.transpose(X[l]))
return [[L[i][j] * P[i][j] for j in range(n)] for i in range(n)]
otimes = sorted(obs)
sizes = [len(obs[k][1]) for k in otimes]
m = sum(sizes)
S = scimat.zeros(m, m)
d = []
oi = 0
for a, k in enumerate(otimes):
Hk, yk, Rk = obs[k]
d.extend(scimat.sub(yk, scimat.matvec(Hk, background[k])))
oj = 0
for b, l in enumerate(otimes):
Hl = obs[l][0]
blk = scimat.matmul(scimat.matmul(Hk, C(k, l)), scimat.transpose(Hl))
for i in range(sizes[a]):
for j in range(sizes[b]):
S[oi + i][oj + j] = blk[i][j] + (Rk[i][j] if a == b else 0.0)
oj += sizes[b]
oi += sizes[a]
w = scimat.solve(S, d)
out = {}
for k in times:
x = list(background[k])
off = 0
for l, size in zip(otimes, sizes):
Hl = obs[l][0]
g = scimat.matvec(scimat.transpose(Hl), w[off : off + size])
x = scimat.add(x, scimat.matvec(C(k, l), g))
off += size
out[k] = x
return out
def test_scalar_check_value():
# x_1 = 2 x_0, B = 1 from the members -1/sqrt(2) and 1/sqrt(2), y_1 = 2 with R = 1: x^a_0 = 0.8.
r = 1.0 / math.sqrt(2.0)
obs = {1: ([[1.0]], [2.0], [[1.0]])}
xa = four_d_envar([0.0], [[-r], [r]], [[1.0]], obs, linear_model([[2.0]]), 1)
assert abs(xa[0][0] - 0.8) < 1e-12
assert abs(xa[1][0] - 1.6) < 1e-12
def test_equals_strong_4dvar_for_exact_ensemble():
# Linear model, no localization and X' X'^T = B: 4DEnVar is 4D-Var with the same B.
rng = random.Random(11)
n, K = 4, 3
M = scimat.add(scimat.eye(n), scimat.scale(0.3, random_matrix(rng, n, n)))
B = random_spd(rng, n)
xb = [rng.gauss(0, 1) for _ in range(n)]
obs = {}
for k in (1, 3):
H = random_matrix(rng, 2, n)
obs[k] = (H, [rng.gauss(0, 1) for _ in range(2)], random_spd(rng, 2, 0.3))
members = exact_ensemble(xb, B)
ones = [[1.0] * n for _ in range(n)]
xa = four_d_envar(xb, members, ones, obs, linear_model(M), K)
ref0 = strong_4dvar_reference(xb, B, M, obs)
assert close(xa[0], ref0, 1e-8)
refK = ref0
for _ in range(K):
refK = scimat.matvec(M, refK)
assert close(xa[K], refK, 1e-8)
def test_localized_against_stacked_conditioning():
rng = random.Random(5)
n, N, K = 5, 3, 2
M = scimat.add(scimat.eye(n), scimat.scale(0.2, random_matrix(rng, n, n)))
xb = [rng.gauss(0, 1) for _ in range(n)]
members = [[x + rng.gauss(0, 1) for x in xb] for _ in range(N)]
L = gaussian_localization(n, 1.0)
obs = {}
for k in (1, 2):
H = random_matrix(rng, 2, n)
obs[k] = (H, [rng.gauss(0, 1) for _ in range(2)], random_spd(rng, 2, 0.3))
for step in (linear_model(M), lorenz_like(n)):
xa = four_d_envar(xb, members, L, obs, step, K)
ref = localized_reference(xb, members, L, obs, step, K)
for k in ref:
assert close(xa[k], ref[k], 1e-8)
def lorenz_like(n):
"""A small nonlinear map, to show that the formula holds for any member trajectories."""
return lambda k, x: [x[j] + 0.1 * (x[(j + 1) % n] - x[j - 2]) * x[j - 1] - 0.05 * x[j] for j in range(n)]
def test_model_runs_forward_only():
calls = [0]
base = linear_model([[0.9, 0.1], [0.0, 1.1]])
def step(k, x):
calls[0] += 1
return base(k, x)
rng = random.Random(3)
N, K = 4, 6
xb = [0.0, 0.0]
members = [[rng.gauss(0, 1), rng.gauss(0, 1)] for _ in range(N)]
obs = {k: ([[1.0, 0.0]], [1.0], [[0.5]]) for k in (2, 4, 6)}
four_d_envar(xb, members, [[1.0, 0.5], [0.5, 1.0]], obs, step, K)
assert calls[0] == (N + 1) * K
def test_lorenz63_twin_reduces_error():
step = lorenz63(0.01)
K = 25
obs_times = (10, 25)
H = scimat.eye(3)
R = scimat.scale(0.25, scimat.eye(3))
ones = [[1.0] * 3 for _ in range(3)]
err_b = err_a = 0.0
seeds = range(20)
for seed in seeds:
rng = random.Random(100 + seed)
spin = run([1.0, 1.0, 20.0], step, 200 + 37 * seed)[-1]
truth = run(spin, step, K)
xb = [v + rng.gauss(0, 1) for v in spin]
members = [[v + rng.gauss(0, 1) for v in xb] for _ in range(10)]
obs = {k: (H, [v + rng.gauss(0, 0.5) for v in truth[k]], R) for k in obs_times}
xa = four_d_envar(xb, members, ones, obs, step, K)
back = run(xb, step, K)
err_b += scimat.norm2(scimat.sub(back[K], truth[K])) / len(seeds)
err_a += scimat.norm2(scimat.sub(xa[K], truth[K])) / len(seeds)
assert err_a < 0.6 * err_b
History
Lorenc (2003) introduced the alpha control variable, which brings a localized ensemble covariance into a variational system. Liu, Xiao and Wang (2008) formulated an ensemble-based four-dimensional variational scheme in which the increment is a combination of ensemble trajectories, so no tangent linear and adjoint models are needed. Buehner and coworkers (2010) compared an ensemble four-dimensional variational scheme with 4D-Var and the ensemble Kalman filter at Environment Canada. Several operational centers later adopted 4D ensemble-variational systems (Bannister 2017).
References
- C. Liu, Q. Xiao and B. Wang, An ensemble-based four-dimensional variational data assimilation scheme. Part I, technical formulation and preliminary test, Monthly Weather Review 136(9) (2008) 3363-3373, the analysis increment as a combination of ensemble trajectories, without tangent linear and adjoint models
- M. Buehner, P. L. Houtekamer, C. Charette, H. L. Mitchell and B. He, Intercomparison of variational data assimilation and the ensemble Kalman filter for global deterministic NWP. Part I, description and single-observation experiments, Monthly Weather Review 138(5) (2010) 1550-1566, the ensemble 4D variational scheme with localized four-dimensional ensemble covariances
- M. Buehner, P. L. Houtekamer, C. Charette, H. L. Mitchell and B. He, Intercomparison of variational data assimilation and the ensemble Kalman filter for global deterministic NWP. Part II, one-month experiments with real observations, Monthly Weather Review 138(5) (2010) 1567-1586, the comparison with 4D-Var and the EnKF over one month of real observations
- 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
- 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 4D ensemble-variational systems of the operational centers
- K. Ide, P. Courtier, M. Ghil and A. C. Lorenc, Unified notation for data assimilation, operational, sequential and variational, Journal of the Meteorological Society of Japan 75(1B) (1997) 181-189, the notation used here
About this page
The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H1 sketch |
|
| Lean | L0 no Lean part |
|
| Code (python) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W2 basic |
|
Tag 5MYERD Edit this page History Report an error Markdown