Algorithmcore
Ensemble Kalman filter
Also called EnKF.
Propagates an ensemble of states through the model and uses its sample covariance in the Kalman update, with perturbed observations for each member.
- Time
- Θ(N p (n + p) + p^3) worst
- Space
- Θ(n p + p^2 + N (n + p)) extra
- Where
- N = the ensemble size; n = the size of the state; p = the number of observations
- Model
- Real RAM
- Properties
- derivative freerandomizedperturbed observations
- Evidence
- Proof sketchCode in 1 languages
- Origin
- Geir Evensen, Gerrit Burgers, Peter Jan van Leeuwen, Peter L. Houtekamer, Herschel L. Mitchell, 1994
The ensemble Kalman filter (EnKF) is a Monte Carlo form of the Kalman filter for large and nonlinear models. It keeps an ensemble of model states. In the forecast step every member is run through the model, so the ensemble carries the error statistics forward with no tangent linear model and no covariance matrix. In the analysis step the sample covariance of the ensemble takes the place of the forecast covariance in the Kalman gain, and each member moves towards its own randomly perturbed copy of the observations. The perturbations are needed: without them the analysis spread is too small. With localization a few tens of members can be enough for a model with many more variables, as the measurement below shows for a small model.
In plain words
Instead of carrying one best guess and a large table of its error variances, carry a few dozen possible states and run each through the model. Their spread shows how uncertain the forecast is, and their joint variations show which variables go up and down together. When observations arrive, each member is pulled towards the data by the amount that the Kalman rule gives for that spread. Each member sees a slightly different, randomly disturbed copy of the data. This keeps the cloud of members as wide as the uncertainty after the update really is.
The problem
Input. A forecast ensemble , observations , an observation operator (it may be nonlinear), a symmetric positive definite observation error covariance , a source of random numbers, and optional localization weights. The notation is that of Ide, Courtier, Ghil and Lorenc (1997). In the letters of the Kalman filter page, is its , the model is its , the forecast and are its predicted and , and the analysis and are its filtered and .
Output. An analysis ensemble. For a linear and no localization, its mean is the Kalman mean plus times the mean of the perturbations, and its expected sample covariance is , where is the sample covariance of the forecast and .
The algorithm
The forecast step runs each member through the model, , usually followed by covariance inflation. The analysis step is below. and hold the unscaled perturbations of the state and of the predicted observations.
EnKF-ANALYSIS(x_1..x_N, y^o, H, R)- 1
y_i <- H(x_i) for each member i - 2
xbar, ybar <- means; X, Y <- perturbations - 3
PH^T <- X Y^T / (N - 1); HPH^T <- Y Y^T / (N - 1) ▷ times the weights, if localized - 4
draw ε_i ~ N(0, R) for each member i - 5
S <- HPH^T + R - 6
d_i <- y^o + ε_i - y_i - 7
x^a_i <- x_i + PH^T S^-1 d_i for each member i - 8
return x^a_1..x^a_N
Line L3 is where the ensemble replaces the covariance. For a linear the two products are exactly and , and the full matrix is never formed. Line L4 draws a new perturbation for each member and each analysis. Line L7 solves one system with right sides.
Example
Take two members , a scalar state observed directly with and , and the perturbations . The sample variance is , so . Line L7 gives and . The mean is the Kalman mean, because the perturbations have mean zero. The variance is , while the Kalman value is : with only two members the perturbations add sampling error. Over many draws of the expected variance is (Theorem 3 of the proof).
For the check value of the page group: with two members (sample mean , variance ), and , the mean and the variance over 20000 draws of the perturbations were and within .
A measurement. On the Lorenz-96 model with , , RK4 with step , every other variable observed every time units with , , multiplicative inflation of the forecast covariance and a Gaspari-Cohn weight with half-width grid units on the gain, the mean analysis RMSE over cycles 501 to 1500 was (one seed, about 3 ms for each analysis in pure Python):
| RMSE | ||
|---|---|---|
| 4 | 1.02 | 0.398 |
| 4 | 1.05 | 0.384 |
| 4 | 1.1 | 0.409 |
| 6 | 1.05 | 0.352 |
| 8 | 1.02 | 1.486 |
| 8 | 1.05 | 0.347 |
| 8 | 1.1 | 0.355 |
| 10 | 1.1 | 0.345 |
| none | 1.2 | 4.65 |
| none | 1.5 | 4.85 |
The free ensemble mean has an RMSE of about . On the same runs the serial EnSRF had with and , and without localization it reached with , where the EnKF fails. The noise of the perturbed observations costs accuracy, most of all with weak localization.
Correctness
The proof shows for a linear that line L3 gives the Kalman gain of the sample prior (Lemma 1), that the analysis mean is the Kalman mean plus (Lemma 2), and that for independent draws the expected analysis covariance is (Theorem 3, from Burgers, van Leeuwen and Evensen 1998). Without the perturbations the covariance is too small by (Corollary 4). For a linear model, Mandel, Cobb and Beezley (2011) prove that the EnKF converges to the Kalman filter as . For a finite ensemble, a nonlinear model or localization, the filter is an approximation whose quality is measured, not proved. The update is linear in the data, so for non-Gaussian errors it is not the Bayesian update. A particle filter aims at the Bayesian posterior, at a much higher cost.
Proof: The perturbed observation EnKF gives the Kalman mean and, in expectation, the Kalman covariance of the sample priorfull
Setting. There are forecast members with mean , unscaled perturbations (, column is ) and sample covariance . The observations are with a linear operator and a symmetric positive definite error covariance . There is no localization until the remarks. The Kalman values for the sample prior are
The perturbations of line L4 have the mean , the centred values (columns of ) and the sample covariance .
Lemma 1 (the gain). For a linear , line L3 computes and , so the matrix used in line L7 is the Kalman gain of the sample prior.
Proof. Line L1 gives , so and . Then and . Lines L5 and L7 use with .
Lemma 2 (members, mean and perturbations). The analysis members are . Their mean is and their perturbations are
Proof. Lines L6 and L7 give the first formula. Average it over to get . Subtract the mean from each member to get column of : .
Theorem 3 (Burgers, van Leeuwen and Evensen 1998). Let the forecast ensemble be fixed and let be independent draws of . Then the expected analysis mean is and the expected sample covariance of the analysis is .
Proof. depends only on the forecast ensemble, so it is fixed. gives the mean by Lemma 2. By Lemma 2 the sample covariance is
The centred sample covariance of independent draws is unbiased, so . Each entry of has mean zero and is fixed, so the last term has mean zero. Hence the expectation is . Expand it and use :
Corollary 4 (without perturbations the spread is too small). If for every member, the analysis covariance is , which is smaller than by the positive semidefinite matrix . This is why the observations must be perturbed (Burgers et al. 1998).
Corollary 5 (exact perturbations). If , and , then the analysis has exactly the mean and the covariance . This follows from the formula in the proof of Theorem 3 without the expectation.
With , , , and , and , and the members are and . The mean is , which is the Kalman mean because , but the variance is instead of , because and . With three members and , , the conditions of Corollary 5 hold and the result is exact.
Large ensembles. For a linear model and Gaussian data, Mandel, Cobb and Beezley (2011) prove that the EnKF members converge in to the Kalman filter as . This is cited, not proved here.
Remark (localization). If picks state values at the positions , and the weights are in and in for a weight matrix on the grid, then line L3 computes and , where is the entrywise product. So the gain is the Kalman gain of the localized covariance . For other operators the localized gain is a heuristic.
A nonlinear . Line L3 then uses the sample covariances of the state and the predicted observations. Lemma 1 no longer holds, and the update is the usual heuristic of the ensemble filters.
Termination. Line L1 makes calls of . is positive semidefinite and is positive definite, so is positive definite and line L7 can solve with it. With localization stays positive definite if the weight matrix of the observations is positive semidefinite, by the Schur product theorem. The loop of line L7 runs times, and the algorithm returns at line L8.
Complexity
Line L3 costs , lines L5 to L7 cost , and line L1 costs calls of . So one analysis costs . The extra space is for the two covariance blocks and for the ensembles. The forecast costs model runs, which usually dominates. With localization, the observations can be processed in local batches, which removes the term.
Properties
- Randomized. The analysis depends on the draws of the perturbations. Two runs with different seeds give different members.
- Derivative free. It needs no tangent linear or adjoint model, unlike the extended Kalman filter.
- Exact in expectation. For a linear the expected analysis mean and covariance are the Kalman values for the sample prior.
- Low rank. Without localization the analysis stays in , because the gain has its columns in the span of the forecast perturbations.
- Consistent as . For linear Gaussian models the filter converges to the Kalman filter.
- Parallel forecast. The members are run through the model independently.
Variants and improvements
- Square root filters. The EnSRF, the EAKF and the ETKF replace the perturbed observations by a deterministic transform, which removes the sampling noise.
- Localization. Multiply and entry by entry by a Gaspari-Cohn weight of the distance, as Houtekamer and Mitchell (2001) did. For an that picks grid values this is the Kalman gain of the localized covariance . See covariance localization.
- Inflation. Multiply the forecast perturbations by or add noise, see covariance inflation.
- Centred perturbations. Subtract the mean of the before line L6, so the mean is the Kalman mean exactly.
- Smoothing. The ensemble Kalman smoother applies the same update to past states.
- Inverse problems. Ensemble Kalman inversion applies the update in an artificial time to estimate parameters.
When to use it
Use the EnKF when the model is large and nonlinear, when no adjoint model is available, and when a flow dependent estimate of the forecast error is needed. It is simple to code around an existing model. If the extra noise of the perturbed observations matters, as with small ensembles or weak localization, use a square root filter. For strongly non-Gaussian errors with a small state, a particle filter may be better. For a small linear model, use the Kalman filter itself.
Pitfalls
- No perturbed observations (line L4). Using the same for every member gives the covariance , which is too small. The filter then trusts its forecast too much and can stop using the data.
- Perturbations with the wrong covariance (line L4). The perturbations must be drawn from with the same that is in . With a correlated , use a Cholesky factor to draw them.
- Small ensembles without localization (line L3). With much smaller than , the sample covariance has spurious long range correlations. Distant observations then change the state where they should not. In the measurement, no inflation factor made the filter work without localization.
- Spread collapse. The sample error makes the ensemble too confident over many cycles. Use inflation.
- Forming . For large the matrix does not fit in memory. Line L3 forms only the and blocks.
- A singular (line L7). If the localization weights of the observations are not positive semidefinite, can lose positive definiteness. Weights from a valid correlation function avoid this, such as the Gaspari-Cohn function of the distance in the plane. The Gaspari-Cohn function of the distance along a ring is not one when its support is more than half the ring: on the 40-point ring of Lorenz-96 its matrix has a negative eigenvalue for .
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/ensemble-kalman-filter/. The authors are listed in prov/JS3602.jsonl.
"""Ensemble Kalman filter (EnKF) with perturbed observations.
Notation of Ide, Courtier, Ghil and Lorenc (1997). The forecast ensemble has
N members in R^n, the observations y^o in R^p have the error covariance R,
and h is the observation operator (it may be nonlinear).
enkf_analysis forms the gain from the sample covariances of the state and of
the predicted observations and moves each member towards its own perturbed
copy of the observations (Burgers, van Leeuwen and Evensen 1998; Houtekamer
and Mitchell 1998). The optional weights loc_xy (n by p) and loc_yy (p by p)
multiply the two sample covariances entry by entry, which localizes the gain.
enkf_forecast runs every member through the model.
Cost of one analysis: O(N p (n + p) + p^3) and N calls of h.
"""
import random
import scimat
def enkf_forecast(ens, model):
"""Return the forecast ensemble [model(x) for each member x]."""
return [list(model(x)) for x in ens]
def observation_perturbations(R, N, rng):
"""Return N draws of N(0, R), one list of length p for each member."""
low = scimat.cholesky(R)
p = len(R)
out = []
for _ in range(N):
z = [rng.gauss(0.0, 1.0) for _ in range(p)]
out.append([sum(low[a][b] * z[b] for b in range(a + 1)) for a in range(p)])
return out
def enkf_analysis(ens, yo, h, R, rng=None, eps=None, loc_xy=None, loc_yy=None):
"""Return the analysis ensemble of the perturbed observation EnKF.
eps, if given, is the list of the N observation perturbations; otherwise
they are drawn from N(0, R) with rng (a random.Random).
"""
N, n, p = len(ens), len(ens[0]), len(yo)
y = [list(h(x)) for x in ens] # @line L1
xbar = [sum(x[j] for x in ens) / N for j in range(n)] # @line L2
ybar = [sum(v[k] for v in y) / N for k in range(p)]
X = [[x[j] - xbar[j] for j in range(n)] for x in ens]
Y = [[v[k] - ybar[k] for k in range(p)] for v in y]
PHt = [[sum(X[i][j] * Y[i][k] for i in range(N)) / (N - 1) for k in range(p)] for j in range(n)] # @line L3
HPHt = [[sum(Y[i][a] * Y[i][b] for i in range(N)) / (N - 1) for b in range(p)] for a in range(p)]
if loc_xy is not None:
PHt = [[PHt[j][k] * loc_xy[j][k] for k in range(p)] for j in range(n)]
if loc_yy is not None:
HPHt = [[HPHt[a][b] * loc_yy[a][b] for b in range(p)] for a in range(p)]
if eps is None: # @line L4
eps = observation_perturbations(R, N, rng if rng is not None else random.Random(0))
S = scimat.add(HPHt, R) # @line L5
D = [[yo[k] + eps[i][k] - y[i][k] for i in range(N)] for k in range(p)] # @line L6
Z = scimat.solve(S, D) # p by N
out = []
for i in range(N): # @line L7
out.append([ens[i][j] + sum(PHt[j][k] * Z[k][i] for k in range(p)) for j in range(n)])
return out # @line L8
def ensemble_moments(ens):
"""Return (mean, P): the ensemble mean and the sample covariance with divisor N - 1."""
N, n = len(ens), len(ens[0])
mean = [sum(x[j] for x in ens) / N for j in range(n)]
P = [[sum((x[a] - mean[a]) * (x[b] - mean[b]) for x in ens) / (N - 1) for b in range(n)] for a in range(n)]
return mean, P
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_ensemble_kalman_filter.py 177 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/ensemble-kalman-filter/. The authors are listed in prov/JS3602.jsonl.
import math
import random
import scimat
from ensemble_kalman_filter import enkf_analysis, enkf_forecast, ensemble_moments, observation_perturbations
def kalman(ens, yo, H, R):
n = len(ens[0])
xbar, P = ensemble_moments(ens)
PHt = scimat.matmul(P, scimat.transpose(H))
S = scimat.add(scimat.matmul(H, PHt), R)
K = scimat.transpose(scimat.solve(S, scimat.transpose(PHt)))
xa = scimat.add(xbar, scimat.matvec(K, scimat.sub(yo, scimat.matvec(H, xbar))))
Pa = scimat.matmul(scimat.sub(scimat.eye(n), scimat.matmul(K, H)), P)
return K, xa, Pa
def test_page_example():
out = enkf_analysis([[-1.0], [1.0]], [1.0], lambda x: x, [[1.0]], eps=[[-0.5], [0.5]])
assert abs(out[0][0] - 0.0) < 1e-12
assert abs(out[1][0] - 4 / 3) < 1e-12
mean, P = ensemble_moments(out)
assert abs(mean[0] - 2 / 3) < 1e-12
assert abs(P[0][0] - 8 / 9) < 1e-12
def test_exact_when_perturbations_match_R_and_are_orthogonal():
# eps has sample variance R and no sample covariance with the prior, so the
# analysis has exactly the Kalman mean and variance.
R = 0.7
c = math.sqrt(R / 3)
ens = [[-1.0], [0.0], [1.0]]
out = enkf_analysis(ens, [2.0], lambda x: x, [[R]], eps=[[c], [-2 * c], [c]])
_, xa, Pa = kalman(ens, [2.0], [[1.0]], [[R]])
mean, P = ensemble_moments(out)
assert abs(mean[0] - xa[0]) < 1e-12
assert abs(P[0][0] - Pa[0][0]) < 1e-12
def test_scalar_check_value_in_expectation():
s = 1 / math.sqrt(2.0)
rng = random.Random(7)
trials, m_sum, v_sum = 20000, 0.0, 0.0
for _ in range(trials):
out = enkf_analysis([[-s], [s]], [1.0], lambda x: x, [[1.0]], rng=rng)
mean, P = ensemble_moments(out)
m_sum += mean[0]
v_sum += P[0][0]
assert abs(m_sum / trials - 0.5) < 0.01
assert abs(v_sum / trials - 0.5) < 0.01
def test_mean_is_kalman_mean_plus_gain_times_mean_perturbation():
rng = random.Random(8)
for _ in range(40):
n, p, N = rng.randint(1, 4), rng.randint(1, 4), rng.randint(2, 8)
ens = [[rng.gauss(0, 1) for _ in range(n)] for _ in range(N)]
H = [[rng.uniform(-1, 1) for _ in range(n)] for _ in range(p)]
L = [[rng.uniform(-1, 1) for _ in range(p)] for _ in range(p)]
R = scimat.add(scimat.matmul(L, scimat.transpose(L)), scimat.scale(0.3, scimat.eye(p)))
yo = [rng.gauss(0, 2) for _ in range(p)]
eps = observation_perturbations(R, N, rng)
out = enkf_analysis(ens, yo, lambda x: scimat.matvec(H, x), R, eps=eps)
K, xa, _ = kalman(ens, yo, H, R)
ebar = [sum(e[k] for e in eps) / N for k in range(p)]
want = scimat.add(xa, scimat.matvec(K, ebar))
mean, _ = ensemble_moments(out)
for a in range(n):
assert abs(mean[a] - want[a]) < 1e-9 * (1 + abs(want[a]))
def test_covariance_is_kalman_in_expectation():
rng = random.Random(9)
ens = [[0.0, 1.0], [1.0, 3.0], [2.0, 2.0], [0.5, -1.0]]
H = [[1.0, 0.0]]
R = [[0.5]]
_, _, Pa = kalman(ens, [1.0], H, R)
trials = 6000
acc = [[0.0, 0.0], [0.0, 0.0]]
for _ in range(trials):
out = enkf_analysis(ens, [1.0], lambda x: [x[0]], R, rng=rng)
_, P = ensemble_moments(out)
for a in range(2):
for b in range(2):
acc[a][b] += P[a][b] / trials
for a in range(2):
for b in range(2):
assert abs(acc[a][b] - Pa[a][b]) < 0.04
def test_observation_perturbations_have_covariance_R():
rng = random.Random(10)
R = [[2.0, 0.6], [0.6, 1.0]]
eps = observation_perturbations(R, 40000, rng)
_, C = ensemble_moments(eps)
for a in range(2):
for b in range(2):
assert abs(C[a][b] - R[a][b]) < 0.05
def test_localization_weights_one_change_nothing_and_zero_freezes():
rng = random.Random(11)
ens = [[rng.gauss(0, 1) for _ in range(3)] for _ in range(6)]
h = lambda x: [x[0], x[1]]
R = [[0.5, 0.0], [0.0, 0.8]]
eps = observation_perturbations(R, 6, rng)
a = enkf_analysis(ens, [1.0, -1.0], h, R, eps=eps)
ones_xy = [[1.0, 1.0] for _ in range(3)]
ones_yy = [[1.0, 1.0], [1.0, 1.0]]
b = enkf_analysis(ens, [1.0, -1.0], h, R, eps=eps, loc_xy=ones_xy, loc_yy=ones_yy)
assert all(abs(u - v) < 1e-12 for x, z in zip(a, b) for u, v in zip(x, z))
zero_last = [[1.0, 1.0], [1.0, 1.0], [0.0, 0.0]]
c = enkf_analysis(ens, [1.0, -1.0], h, R, eps=eps, loc_xy=zero_last, loc_yy=ones_yy)
for x, z in zip(ens, c):
assert z[2] == x[2]
def l96(x, F=8.0):
n = len(x)
return [(x[(j + 1) % n] - x[j - 2]) * x[j - 1] - x[j] + F for j in range(n)]
def rk4(x, dt):
k1 = l96(x)
k2 = l96([a + 0.5 * dt * b for a, b in zip(x, k1)])
k3 = l96([a + 0.5 * dt * b for a, b in zip(x, k2)])
k4 = l96([a + dt * b for a, b in zip(x, k3)])
return [a + dt * (b + 2 * c + 2 * d + e) / 6 for a, b, c, d, e in zip(x, k1, k2, k3, k4)]
def gaspari_cohn(r, c):
z = abs(r) / c
if z <= 1:
return -z**5 / 4 + z**4 / 2 + 5 * z**3 / 8 - 5 * z**2 / 3 + 1
if z < 2:
return z**5 / 12 - z**4 / 2 + 5 * z**3 / 8 + 5 * z**2 / 3 - 5 * z + 4 - 2 / (3 * z)
return 0.0
def test_lorenz96_twin_tracks_the_truth():
n, N, dt, rho, c = 40, 10, 0.05, 1.1, 4.0
rng, prng = random.Random(1), random.Random(101)
x = [8.0] * n
x[0] += 0.01
for _ in range(1000):
x = rk4(x, dt)
ens, z = [], list(x)
for _ in range(N):
for _ in range(50):
z = rk4(z, dt)
ens.append(list(z))
free = [list(e) for e in ens]
obs = list(range(0, n, 2))
p = len(obs)
dist = lambda a, b: min(abs(a - b), n - abs(a - b))
lxy = [[gaspari_cohn(dist(j, q), c) for q in obs] for j in range(n)]
lyy = [[gaspari_cohn(dist(q, q2), c) for q2 in obs] for q in obs]
R = [[1.0 if a == b else 0.0 for b in range(p)] for a in range(p)]
model = lambda s: rk4(s, dt)
errs, ferrs = [], []
for _ in range(150):
x = rk4(x, dt)
ens = enkf_forecast(ens, model)
free = enkf_forecast(free, model)
m = [sum(e[j] for e in ens) / N for j in range(n)]
ens = [[m[j] + math.sqrt(rho) * (e[j] - m[j]) for j in range(n)] for e in ens]
yo = [x[k] + rng.gauss(0, 1) for k in obs]
ens = enkf_analysis(ens, yo, lambda s: [s[k] for k in obs], R, rng=prng, loc_xy=lxy, loc_yy=lyy)
for e_list, out in ((ens, errs), (free, ferrs)):
m = [sum(e[j] for e in e_list) / N for j in range(n)]
out.append(math.sqrt(sum((m[j] - x[j]) ** 2 for j in range(n)) / n))
assert sum(errs[50:]) / 100 < 0.7
assert sum(ferrs[50:]) / 100 > 2.0
History
Evensen proposed the ensemble Kalman filter in 1994 for a quasi-geostrophic ocean model, as a way to forecast the error statistics by Monte Carlo instead of with the extended Kalman filter. In 1998 Burgers, van Leeuwen and Evensen showed that the observations must be perturbed to give the right analysis spread, and in the same year Houtekamer and Mitchell used an EnKF with perturbed observations for atmospheric data assimilation. In 2001 Houtekamer and Mitchell localized the gain with a compactly supported correlation. The square root filters of 2001 to 2003 removed the perturbed observations. In 2011 Mandel, Cobb and Beezley proved that the filter converges to the Kalman filter for linear models as the ensemble grows.
References
- G. Evensen, Sequential data assimilation with a nonlinear quasi-geostrophic model using Monte Carlo methods to forecast error statistics, Journal of Geophysical Research: Oceans 99(C5) (1994) 10143-10162, the ensemble forecast of the error statistics and the ensemble form of the Kalman update
- G. Burgers, P. J. van Leeuwen and G. Evensen, Analysis scheme in the ensemble Kalman filter, Monthly Weather Review 126(6) (1998) 1719-1724, the need to perturb the observations, and the expected analysis covariance (I - KH)P
- P. L. Houtekamer and H. L. Mitchell, Data assimilation using an ensemble Kalman filter technique, Monthly Weather Review 126(3) (1998) 796-811, an EnKF with perturbed observations for atmospheric data assimilation
- P. L. Houtekamer and H. L. Mitchell, A sequential ensemble Kalman filter for atmospheric data assimilation, Monthly Weather Review 129(1) (2001) 123-137, the localized gain with a compactly supported correlation function
- J. Mandel, L. Cobb and J. D. Beezley, On the convergence of the ensemble Kalman filter, Applications of Mathematics 56(6) (2011) 533-541, convergence of the EnKF to the Kalman filter as N goes to infinity, for linear models
- J. S. Whitaker and T. M. Hamill, Ensemble data assimilation without perturbed observations, Monthly Weather Review 130(7) (2002) 1913-1924, the sampling error that the perturbed observations add
- 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.
| 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 JS3602 Edit this page History Report an error Markdown